├── LICENSE ├── README.md ├── compute_mexa.py └── embed_extractor.py /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MEXA 2 | __MEXA__ stands for **M**ultilingual **E**valuation via **Cross**-Lingual **A**lignment, [Paper, arXiv 2024](http://arxiv.org/abs/2410.05873) 3 | 4 | We introduce MEXA, a method for assessing the multilingual capabilities of English-centric large language models (LLMs). MEXA builds on the observation that English-centric LLMs semantically use English as a kind of pivot language in their intermediate layers. MEXA computes the alignment between non-English languages and English using parallel sentences, estimating the transfer of language understanding capabilities from English to other languages through this alignment. This metric can be useful in estimating task performance, provided we know the English performance in the task and the alignment score between languages derived from a parallel dataset. 5 | 6 | ## Compute 7 | 8 | Follow steps 1 to 3, prepare your data, and run 2 commands! 9 | 10 | ### 1) Preparing a Parallel Dataset 11 | 12 | Save the parallel data in the following format: 13 | 14 | Each language should have one text file named after the language (e.g., `eng_Latn.txt`), containing $n$ sentences. The line number corresponds to the sentence ID, meaning line $i$ in each file is parallel across languages. 15 | 16 | - We use [FLORES-200](https://github.com/facebookresearch/flores/blob/main/flores200/README.md), available for download [here](https://tinyurl.com/flores200dataset). For our experiments, we use the first 100 sentences from the devtest folder. 17 | - We also use the Bible dataset, which contains 103 sentences across 1,401 languages in the same format, accessible [here](https://huggingface.co/datasets/cis-lmu/sPBC). 18 | 19 | ### 2) Computing Embeddings with embed_extractor.py 20 | 21 | The `embed_extractor.py` script allows you to extract embeddings from a specified model for a given dataset. 22 | It generates embeddings based on two methods: a __weighted average__ based on token positions and the __last token__. 23 | Below are the instructions for using the script along with descriptions for each argument. 24 | 25 | To run the script, use the following command: 26 | 27 | ```bash 28 | python embed_extractor.py --model_name --data_path --gpus --num_sents --save_path --cache_dir --file_ext --token 29 | ``` 30 | 31 |
Click to Expand Arguments Description 32 | 33 | - `--model_name` (str, required): 34 | The name of the model to use for embedding extraction. It can be any compatible model from Hugging Face. 35 | **Examples**: 36 | - `"google/gemma-2-9b"` 37 | - `"google/gemma-7b"` 38 | - `"meta-llama/Meta-Llama-3.1-70B"` 39 | - `"meta-llama/Llama-3.1-8B"` 40 | - `"meta-llama/Meta-Llama-3-8B"` 41 | - `"meta-llama/Llama-2-7b-hf"` 42 | - `"yahma/llama-7b-hf"` 43 | - `"mistralai/Mistral-7B-v0.3"` 44 | - `"allenai/OLMo-1.7-7B-hf"` 45 | 46 | 47 | - `--data_path` (str, required): 48 | The path to the directory containing the parallel data files. 49 | 50 | - `--gpus` (str, default='0'): 51 | The GPU IDs to use for processing. You can specify a single GPU (e.g., `"0"`) or multiple GPUs separated by commas (e.g., `"0,1"`). 52 | 53 | - `--num_sents` (int, default=100): 54 | The maximum number of sentences to process from each input file. The default value is 100, but you can adjust it as needed. 55 | 56 | - `--save_path` (str, required): 57 | The path where the extracted embeddings will be saved. Ensure that the directory exists or the script has permission to create it. 58 | 59 | - `--token` (str, optional, default=None): 60 | Your Hugging Face token for authentication (if required). This is optional and can be omitted if the model does not require authentication. 61 | 62 | - `--cache_dir` (str, optional, default='./cache'): 63 | The directory where the model will be cached after downloading. This prevents re-downloading the model for future runs. 64 | 65 | - `--file_ext` (str, optional, default='.txt'): 66 | The file extension of the input files containing the parallel data. The default is `.txt`, but you can specify a different extension as needed (e.g., `.devtest`). 67 | 68 |
69 | 70 | __Example Command:__ 71 | 72 | To extract embeddings using the `allenai/OLMo-1.7-7B-hf` model from the `./flores200_dataset/devtest` directory and save the results in `./embd_olmo`, processing the first 100 sentences of each file, use the following command: 73 | 74 | ```bash 75 | python embed_extractor.py --model_name allenai/OLMo-1.7-7B-hf --data_path ./flores200_dataset/devtest --gpus '0' --num_sents 100 --save_path ./embd_olmo/ --cache_dir ./cache/ --file_ext .devtest 76 | ``` 77 | 78 | 79 | ### 3) Computing MEXA Score with compute_mexa.py 80 | 81 | 82 | The `compute_mexa.py` script computes mexa score between embeddings from a pivot language and multiple target languages. It uses cosine similarity to evaluate the embeddings and outputs the alignment scores as JSON files. 83 | 84 | To execute the script, use the following command: 85 | 86 | ```bash 87 | python compute_mexa.py --embedding_path --save_path --num_sents --embedding_type --pivot --file_ext 88 | ``` 89 | 90 |
Click to Expand Arguments Description 91 | 92 | - `--embedding_path` (str, required): 93 | The path to the directory containing the embedding files. Ensure this directory exists and contains the required `.pkl` files. 94 | 95 | - `--save_path` (str, required): 96 | The path where the computed alignment results will be saved as JSON files. The directory should exist or the script should have permission to create it. 97 | 98 | - `--num_sents` (int, optional, default=100): 99 | The maximum number of sentences to process from each input file. The default value is 100, but you can adjust it as needed. 100 | 101 | - `--embedding_type` (str, optional, default='embd_weighted'): 102 | The type of embedding to use. Choose between: 103 | - `'embd_weighted'`: For weighted average embeddings based on token positions. 104 | - `'embd_lasttoken'`: For embeddings based on the last token. 105 | 106 | - `--pivot` (str, optional, default='eng_Latn'): 107 | The language code of the pivot language. This is the language against which other languages will be compared. 108 | 109 | - `--file_ext` (str, optional, default='.pkl'): 110 | The file extension for the embedding files. The default is `.pkl`, but you can specify a different extension if needed. 111 | 112 |
113 | 114 | __Example Command:__ 115 | 116 | To compute alignments using the pivot language `eng_Latn`, processing the first 100 sentences from each embedding file located in `./embd_olmo/` and saving the results in `./mexa_olmo/`, use the following command: 117 | 118 | ```bash 119 | python compute_mexa.py --embedding_path ./embd_olmo/ --save_path ./mexa_olmo/ --num_sents 100 --embedding_type embd_weighted --pivot eng_Latn --file_ext .pkl 120 | ``` 121 | 122 | ## Language Coverage — Computed Scores 123 | 124 | We host the estimated Mexa scores, which are calculated using mean and max pooling methods over layers and adjusted based on the models' performance in different tasks in English. These scores are available for popular state-of-the-art models based on FLORES and the Bible at https://huggingface.co/spaces/cis-lmu/Mexa. 125 | 126 | ## Citation 127 | 128 | If you find our method, code and scores useful for your research, please cite: 129 | 130 | ```bash 131 | @article{kargaran2024mexa, 132 | title = {{MEXA}: Multilingual Evaluation of {E}nglish-Centric {LLMs} via Cross-Lingual Alignment}, 133 | author = {Kargaran, Amir Hossein and Modarressi, Ali and Nikeghbal, Nafiseh and Diesner, Jana and Yvon, François and Schütze, Hinrich}, 134 | journal = {arXiv preprint arXiv:2410.05873}, 135 | year = {2024}, 136 | url = {https://arxiv.org/abs/2410.05873} 137 | } 138 | ``` 139 | -------------------------------------------------------------------------------- /compute_mexa.py: -------------------------------------------------------------------------------- 1 | import os 2 | import json 3 | import pickle 4 | import numpy as np 5 | from tqdm import tqdm 6 | from scipy.spatial.distance import cosine 7 | import argparse 8 | 9 | def cosine_similarity(array1, array2): 10 | array1 = array1.astype(np.float64) 11 | array2 = array2.astype(np.float64) 12 | cosine_dist = cosine(array1, array2) 13 | cosine_similarity = 1 - cosine_dist 14 | return cosine_similarity 15 | 16 | def mexa(matrix): 17 | n = len(matrix) # size of the square matrix 18 | count = 0 19 | 20 | for i in range(n): 21 | # Get the diagonal element 22 | diag_element = matrix[i][i] 23 | 24 | # Get the row and column 25 | row = matrix[i] 26 | column = matrix[:,i] 27 | 28 | # Check if the diagonal element is strictly greater than all other elements in its row (excluding itself) 29 | if diag_element > max(np.delete(row, i)): 30 | # Check if the diagonal element is strictly greater than all other elements in its column (excluding itself) 31 | if diag_element > max(np.delete(column, i)): 32 | count += 1 33 | 34 | # Normalized count 35 | count_norm = count / n 36 | return count_norm 37 | 38 | def compute_distance(lang, embedding_type='embd_weighted', num_sents=100): 39 | with open(os.path.join(embedding_path, f"{lang}.pkl"), "rb") as pickle_file: 40 | lang_embd = pickle.load(pickle_file) 41 | 42 | similarities_dict = {} 43 | for layer in lang_embd.keys(): 44 | pivot_embd_layer = pivot_embd[layer][:num_sents] 45 | lang_embd_layer = lang_embd[layer][:num_sents] 46 | 47 | # Initialize the similarities_dict matrix for each layer 48 | num_actual_sentences = min(len(pivot_embd_layer), len(lang_embd_layer)) 49 | similarities_dict[layer] = np.zeros((num_actual_sentences, num_actual_sentences)) 50 | 51 | # Compute similarities 52 | for p_id, pivot_single in enumerate(pivot_embd_layer): 53 | for l_id, lang_single in enumerate(lang_embd_layer): 54 | similarities_dict[layer][p_id, l_id] = cosine_similarity(pivot_single[embedding_type], lang_single[embedding_type]) 55 | 56 | alignments = {} 57 | for layer in lang_embd.keys(): 58 | alignments[layer] = mexa(similarities_dict[layer]) 59 | 60 | return alignments 61 | 62 | if __name__ == "__main__": 63 | parser = argparse.ArgumentParser(description='Process embeddings and compute alignments.') 64 | 65 | parser.add_argument('--pivot', type=str, default='eng_Latn', help='Pivot language code (default: eng_Latn)') 66 | parser.add_argument('--file_ext', type=str, default='.pkl', help='File extension for embedding files (default: .pkl)') 67 | parser.add_argument('--embedding_path', type=str, required=True, help='Path to the directory containing embedding files.') 68 | parser.add_argument('--save_path', type=str, required=True, help='Path to save the results.') 69 | parser.add_argument('--num_sents', type=int, default=100, help='Maximum number of sentences to process (default: 100)') 70 | parser.add_argument('--embedding_type', type=str, choices=['embd_weighted', 'embd_lasttoken'], default='embd_weighted', help='Type of embedding to use (default: embd_weighted)') 71 | 72 | args = parser.parse_args() 73 | 74 | # Set the global variables based on input arguments 75 | pivot = args.pivot 76 | file_ext = args.file_ext 77 | embedding_path = args.embedding_path 78 | save_path = args.save_path 79 | num_sents = args.num_sents 80 | embedding_type = args.embedding_type 81 | 82 | # Load the pivot embeddings 83 | with open(os.path.join(embedding_path, f"{pivot}{file_ext}"), "rb") as pickle_file: 84 | pivot_embd = pickle.load(pickle_file) 85 | 86 | languages = [filename[:-len(file_ext)] for filename in os.listdir(embedding_path) if filename.endswith(file_ext)] 87 | 88 | for lang in tqdm(languages): 89 | alignment_lang = compute_distance(lang, embedding_type=embedding_type, num_sents=num_sents) 90 | save_filepath = os.path.join(save_path, f"{lang}.json") 91 | os.makedirs(os.path.dirname(save_filepath), exist_ok=True) 92 | 93 | with open(save_filepath, "w") as json_file: 94 | json.dump(alignment_lang, json_file) 95 | -------------------------------------------------------------------------------- /embed_extractor.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import os 3 | import torch 4 | import json 5 | import pickle 6 | from transformers import AutoTokenizer, AutoModelForCausalLM 7 | from tqdm import tqdm 8 | 9 | # Function to handle weighted embeddings 10 | def weighted_embeddings(layer, attention_mask, device='cuda'): 11 | # Compute weights for non-padding tokens 12 | weights_for_non_padding = attention_mask * torch.arange(start=1, end=layer.shape[1] + 1, device=device).unsqueeze(0) 13 | sum_embeddings = torch.sum(layer * weights_for_non_padding.unsqueeze(-1), dim=1) 14 | num_of_non_padding_tokens = torch.sum(weights_for_non_padding, dim=-1).unsqueeze(-1) 15 | sentence_embeddings = sum_embeddings / num_of_non_padding_tokens 16 | sentence_embeddings = sentence_embeddings.squeeze().to(torch.float32).cpu().numpy() 17 | return sentence_embeddings 18 | 19 | 20 | def lasttoken_embeddings(layer, attention_mask, device='cuda'): 21 | # Compute the index of the last non-padding token 22 | idx_of_last_token = attention_mask.bool().sum().item() - 1 # scalar index 23 | # Extract the embedding from the layer 24 | embedding = layer[0, idx_of_last_token, :] # shape: [hidden_dim] 25 | sentence_embedding = embedding.to(torch.float32).cpu().numpy() 26 | return sentence_embedding 27 | 28 | 29 | # Function to extract embeddings 30 | def get_embedding_layers(text, model, tokenizer, device='cuda'): 31 | tokens = tokenizer(text, return_tensors='pt', padding=True).to(device) 32 | attention_mask = tokens.attention_mask.to(device) 33 | 34 | sentence_embeddings_weighted = [] 35 | sentence_embeddings_last_token = [] 36 | 37 | with torch.no_grad(): 38 | hidden_state_layers = model(**tokens, output_hidden_states=True)["hidden_states"] 39 | 40 | for layer in hidden_state_layers: 41 | embd_weighted = weighted_embeddings(layer, attention_mask, device) 42 | embd_last_token = lasttoken_embeddings(layer, attention_mask, device) 43 | 44 | sentence_embeddings_weighted.append(embd_weighted) 45 | sentence_embeddings_last_token.append(embd_last_token) 46 | 47 | return sentence_embeddings_weighted, sentence_embeddings_last_token 48 | 49 | # Main function 50 | def main(): 51 | parser = argparse.ArgumentParser(description="Extract embeddings from a model") 52 | 53 | # Add arguments for the parser 54 | parser.add_argument('--model_name', type=str, required=True, help='The model name from Hugging Face.') 55 | parser.add_argument('--data_path', type=str, required=True, help='Path to the parallel data directory.') 56 | parser.add_argument('--gpus', type=str, default='0', help='GPUs to use, e.g. "0".') 57 | parser.add_argument('--num_sents', type=int, default=100, help='Maximum number of sentences to process.') 58 | parser.add_argument('--save_path', type=str, required=True, help='Path to save the embeddings.') 59 | parser.add_argument('--token', type=str, default=None, help='Hugging Face token (optional).') 60 | parser.add_argument('--cache_dir', type=str, default='./cache', help='Directory for caching the model (optional).') 61 | parser.add_argument('--file_ext', type=str, default='.txt', help='File extension for input files (optional, default: .txt).') 62 | 63 | # Parse the arguments 64 | args = parser.parse_args() 65 | 66 | # Set GPU environment 67 | os.environ['CUDA_VISIBLE_DEVICES'] = args.gpus 68 | 69 | # Define model name and token 70 | model_name = args.model_name 71 | token = args.token # Optional token 72 | 73 | # Load the model and tokenizer 74 | model = AutoModelForCausalLM.from_pretrained(model_name, device_map='auto', cache_dir=args.cache_dir, use_auth_token=token) 75 | tokenizer = AutoTokenizer.from_pretrained(model_name, use_auth_token=token) 76 | tokenizer.pad_token = tokenizer.eos_token 77 | 78 | # Directory and number of sentences 79 | directory = args.data_path 80 | number_of_sents = args.num_sents 81 | 82 | # Initialize a dictionary to store embeddings 83 | result_dict = {} 84 | 85 | # Process the files in the directory 86 | for filename in os.listdir(directory): 87 | if filename.endswith(args.file_ext): 88 | language = filename.split('.')[0] 89 | filepath = os.path.join(directory, filename) 90 | 91 | sentences = [] 92 | with open(filepath, 'r', encoding='utf-8') as file: 93 | lines = file.readlines() 94 | for idx, line in enumerate(lines): 95 | if idx < number_of_sents: 96 | sentence = line.strip() 97 | sentences.append({'id': idx + 1, 'text': sentence}) 98 | 99 | result_dict[language] = sentences 100 | 101 | # Prepare to save embeddings 102 | embeddings_dict = {} 103 | 104 | # Extract embeddings 105 | for language, texts in tqdm(result_dict.items()): 106 | embeddings_dict = {} 107 | 108 | for text in texts: 109 | embds_weighted, embds_last_token = get_embedding_layers(text['text'], model, tokenizer) 110 | 111 | for layer in range(len(embds_weighted)): 112 | if layer not in embeddings_dict: 113 | embeddings_dict[layer] = [] 114 | 115 | embeddings_dict[layer].append({ 116 | 'id': text['id'], 117 | 'embd_weighted': embds_weighted[layer], 118 | 'embd_lasttoken': embds_last_token[layer] 119 | }) 120 | 121 | # Save the embeddings as pickle 122 | save_filepath = os.path.join(args.save_path, f"{language}.pkl") 123 | os.makedirs(os.path.dirname(save_filepath), exist_ok=True) 124 | with open(save_filepath, "wb") as pickle_file: 125 | pickle.dump(embeddings_dict, pickle_file) 126 | 127 | if __name__ == "__main__": 128 | main() 129 | --------------------------------------------------------------------------------