thongnt commited on
Commit
33362fc
·
verified ·
1 Parent(s): 607b876

Upload model

Browse files
Files changed (4) hide show
  1. README.md +199 -0
  2. config.json +197 -0
  3. milco.py +218 -0
  4. pytorch_model.bin +3 -0
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "MILCOModel"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "milco.MILCOConfig",
7
+ "AutoModel": "milco.MILCOModel"
8
+ },
9
+ "dtype": "float32",
10
+ "en_hidden_size": 768,
11
+ "en_sub_config": {
12
+ "_name_or_path": "naver/splade-v3",
13
+ "add_cross_attention": false,
14
+ "architectures": [
15
+ "BertForMaskedLM"
16
+ ],
17
+ "attention_probs_dropout_prob": 0.1,
18
+ "bad_words_ids": null,
19
+ "begin_suppress_tokens": null,
20
+ "bos_token_id": null,
21
+ "chunk_size_feed_forward": 0,
22
+ "classifier_dropout": null,
23
+ "cross_attention_hidden_size": null,
24
+ "decoder_start_token_id": null,
25
+ "diversity_penalty": 0.0,
26
+ "do_sample": false,
27
+ "dtype": "float32",
28
+ "early_stopping": false,
29
+ "encoder_no_repeat_ngram_size": 0,
30
+ "eos_token_id": null,
31
+ "exponential_decay_length_penalty": null,
32
+ "finetuning_task": null,
33
+ "forced_bos_token_id": null,
34
+ "forced_eos_token_id": null,
35
+ "gradient_checkpointing": false,
36
+ "hidden_act": "gelu",
37
+ "hidden_dropout_prob": 0.1,
38
+ "hidden_size": 768,
39
+ "id2label": {
40
+ "0": "LABEL_0",
41
+ "1": "LABEL_1"
42
+ },
43
+ "initializer_range": 0.02,
44
+ "intermediate_size": 3072,
45
+ "is_decoder": false,
46
+ "is_encoder_decoder": false,
47
+ "label2id": {
48
+ "LABEL_0": 0,
49
+ "LABEL_1": 1
50
+ },
51
+ "layer_norm_eps": 1e-12,
52
+ "length_penalty": 1.0,
53
+ "max_length": 20,
54
+ "max_position_embeddings": 512,
55
+ "min_length": 0,
56
+ "model_type": "bert",
57
+ "no_repeat_ngram_size": 0,
58
+ "num_attention_heads": 12,
59
+ "num_beam_groups": 1,
60
+ "num_beams": 1,
61
+ "num_hidden_layers": 12,
62
+ "num_return_sequences": 1,
63
+ "output_attentions": false,
64
+ "output_hidden_states": false,
65
+ "output_scores": false,
66
+ "pad_token_id": 0,
67
+ "position_embedding_type": "absolute",
68
+ "prefix": null,
69
+ "problem_type": null,
70
+ "pruned_heads": {},
71
+ "remove_invalid_values": false,
72
+ "repetition_penalty": 1.0,
73
+ "return_dict": true,
74
+ "return_dict_in_generate": false,
75
+ "sep_token_id": null,
76
+ "suppress_tokens": null,
77
+ "task_specific_params": null,
78
+ "temperature": 1.0,
79
+ "tf_legacy_loss": false,
80
+ "tie_encoder_decoder": false,
81
+ "tie_word_embeddings": true,
82
+ "tokenizer_class": null,
83
+ "top_k": 50,
84
+ "top_p": 1.0,
85
+ "torchscript": false,
86
+ "transformers_version": "4.57.3",
87
+ "type_vocab_size": 2,
88
+ "typical_p": 1.0,
89
+ "use_bfloat16": false,
90
+ "use_cache": true,
91
+ "vocab_size": 30522
92
+ },
93
+ "en_vocab_size": 30522,
94
+ "freeze_embeddings": false,
95
+ "lambda_commitment": 0.0,
96
+ "lambda_d": 1e-05,
97
+ "lambda_q": 0.001,
98
+ "lambda_sparsity": 0.0,
99
+ "lsr_encoder_checkpoint": "naver/splade-v3",
100
+ "m_hidden_size": 1024,
101
+ "m_sub_config": {
102
+ "_name_or_path": "BAAI/bge-m3-unsupervised",
103
+ "add_cross_attention": false,
104
+ "architectures": [
105
+ "XLMRobertaModel"
106
+ ],
107
+ "attention_probs_dropout_prob": 0.1,
108
+ "bad_words_ids": null,
109
+ "begin_suppress_tokens": null,
110
+ "bos_token_id": 0,
111
+ "chunk_size_feed_forward": 0,
112
+ "classifier_dropout": null,
113
+ "cross_attention_hidden_size": null,
114
+ "decoder_start_token_id": null,
115
+ "diversity_penalty": 0.0,
116
+ "do_sample": false,
117
+ "dtype": "float32",
118
+ "early_stopping": false,
119
+ "encoder_no_repeat_ngram_size": 0,
120
+ "eos_token_id": 2,
121
+ "exponential_decay_length_penalty": null,
122
+ "finetuning_task": null,
123
+ "forced_bos_token_id": null,
124
+ "forced_eos_token_id": null,
125
+ "hidden_act": "gelu",
126
+ "hidden_dropout_prob": 0.1,
127
+ "hidden_size": 1024,
128
+ "id2label": {
129
+ "0": "LABEL_0",
130
+ "1": "LABEL_1"
131
+ },
132
+ "initializer_range": 0.02,
133
+ "intermediate_size": 4096,
134
+ "is_decoder": false,
135
+ "is_encoder_decoder": false,
136
+ "label2id": {
137
+ "LABEL_0": 0,
138
+ "LABEL_1": 1
139
+ },
140
+ "layer_norm_eps": 1e-05,
141
+ "length_penalty": 1.0,
142
+ "max_length": 20,
143
+ "max_position_embeddings": 8194,
144
+ "min_length": 0,
145
+ "model_type": "xlm-roberta",
146
+ "no_repeat_ngram_size": 0,
147
+ "num_attention_heads": 16,
148
+ "num_beam_groups": 1,
149
+ "num_beams": 1,
150
+ "num_hidden_layers": 24,
151
+ "num_return_sequences": 1,
152
+ "output_attentions": false,
153
+ "output_hidden_states": false,
154
+ "output_past": true,
155
+ "output_scores": false,
156
+ "pad_token_id": 1,
157
+ "position_embedding_type": "absolute",
158
+ "prefix": null,
159
+ "problem_type": null,
160
+ "pruned_heads": {},
161
+ "remove_invalid_values": false,
162
+ "repetition_penalty": 1.0,
163
+ "return_dict": true,
164
+ "return_dict_in_generate": false,
165
+ "sep_token_id": null,
166
+ "suppress_tokens": null,
167
+ "task_specific_params": null,
168
+ "temperature": 1.0,
169
+ "tf_legacy_loss": false,
170
+ "tie_encoder_decoder": false,
171
+ "tie_word_embeddings": true,
172
+ "tokenizer_class": null,
173
+ "top_k": 50,
174
+ "top_p": 1.0,
175
+ "torchscript": false,
176
+ "transformers_version": "4.57.3",
177
+ "type_vocab_size": 1,
178
+ "typical_p": 1.0,
179
+ "use_bfloat16": false,
180
+ "use_cache": true,
181
+ "vocab_size": 250002
182
+ },
183
+ "m_vocab_size": 250002,
184
+ "model_type": "milco",
185
+ "model_variant": "bert",
186
+ "multilingual_encoder_checkpoint": "BAAI/bge-m3-unsupervised",
187
+ "only_distillation": true,
188
+ "pooling": "2d",
189
+ "projector_pretraining": false,
190
+ "prompt_length": 0,
191
+ "separate_mlp": true,
192
+ "softmax_temperature": 1.0,
193
+ "sparse_reg": "l1",
194
+ "transformers_version": "4.57.3",
195
+ "use_2d_mlp": true,
196
+ "use_cross_device_negatives": false
197
+ }
milco.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from transformers import (
4
+ AutoConfig,
5
+ AutoModel,
6
+ AutoModelForMaskedLM,
7
+ AutoTokenizer,
8
+ PretrainedConfig,
9
+ PreTrainedModel,
10
+ )
11
+ from transformers.activations import GELUActivation
12
+ from transformers.utils import logging
13
+
14
+ logger = logging.get_logger(__name__)
15
+
16
+
17
+ class MILCOConfig(PretrainedConfig):
18
+ model_type = "milco"
19
+
20
+ def __init__(self, **kwargs):
21
+ super().__init__(**kwargs)
22
+ self.lsr_encoder_checkpoint = kwargs.get("lsr_encoder_checkpoint", "bert-base-uncased")
23
+ self.multilingual_encoder_checkpoint = kwargs.get("multilingual_encoder_checkpoint", "bert-base-uncased")
24
+ self.model_variant = kwargs.get("model_variant", "bert")
25
+ # Sub-model dimensions — cached in config.json after first save.
26
+ self.en_vocab_size = kwargs.get("en_vocab_size", None)
27
+ self.en_hidden_size = kwargs.get("en_hidden_size", None)
28
+ self.m_vocab_size = kwargs.get("m_vocab_size", None)
29
+ self.m_hidden_size = kwargs.get("m_hidden_size", None)
30
+ # Sub-model config dicts — stored so __init__ can rebuild architecture offline.
31
+ self.en_sub_config = kwargs.get("en_sub_config", None)
32
+ self.m_sub_config = kwargs.get("m_sub_config", None)
33
+
34
+ def _resolve_sub_configs(self):
35
+ """Fetch sub-model configs from HF hub if not already cached."""
36
+ if self.en_sub_config is None:
37
+ en_config = AutoConfig.from_pretrained(self.lsr_encoder_checkpoint, trust_remote_code=True)
38
+ self.en_vocab_size = en_config.vocab_size
39
+ self.en_hidden_size = en_config.hidden_size
40
+ self.en_sub_config = en_config.to_dict()
41
+ if self.m_sub_config is None:
42
+ m_config = AutoConfig.from_pretrained(self.multilingual_encoder_checkpoint, trust_remote_code=True)
43
+ self.m_vocab_size = m_config.vocab_size
44
+ self.m_hidden_size = m_config.hidden_size
45
+ self.m_sub_config = m_config.to_dict()
46
+
47
+
48
+ class MILCOModel(PreTrainedModel):
49
+ config_class = MILCOConfig
50
+ base_model_prefix = "milco"
51
+
52
+ def __init__(self, config: MILCOConfig):
53
+ super().__init__(config)
54
+ config._resolve_sub_configs()
55
+ # Build architecture from cached configs — no pretrained weight downloads.
56
+ m_sub_config = AutoConfig.for_model(**config.m_sub_config)
57
+ self.m_model = AutoModel.from_config(m_sub_config)
58
+ en_sub_config = AutoConfig.for_model(**config.en_sub_config)
59
+ en_lsr = AutoModelForMaskedLM.from_config(en_sub_config)
60
+ if hasattr(en_lsr, "cls"):
61
+ self.mlm_head = en_lsr.cls
62
+ else:
63
+ self.mlm_head = en_lsr.lm_head
64
+ self.projector = nn.Linear(config.m_hidden_size, config.en_hidden_size)
65
+ self.activation = GELUActivation()
66
+ self.echo = nn.Linear(config.m_hidden_size, 1)
67
+ self.scale = nn.Parameter(torch.tensor([1.0]))
68
+ self.post_init()
69
+
70
+ @property
71
+ def en_tokenizer(self):
72
+ if not hasattr(self, "_en_tokenizer"):
73
+ self._en_tokenizer = AutoTokenizer.from_pretrained(
74
+ self.config.lsr_encoder_checkpoint, trust_remote_code=True,
75
+ )
76
+ return self._en_tokenizer
77
+
78
+ @property
79
+ def m_tokenizer(self):
80
+ if not hasattr(self, "_m_tokenizer"):
81
+ self._m_tokenizer = AutoTokenizer.from_pretrained(
82
+ self.config.multilingual_encoder_checkpoint, trust_remote_code=True,
83
+ )
84
+ return self._m_tokenizer
85
+
86
+ def get_vocab(self):
87
+ en_term2id = self.en_tokenizer.vocab
88
+ en_id2term = {idx: f"e_{term}" for term, idx in en_term2id.items()}
89
+ m_term2id = self.m_tokenizer.vocab
90
+ m_id2term = {idx + self.config.en_vocab_size: f"m_{term}" for term, idx in m_term2id.items()}
91
+ return en_id2term | m_id2term
92
+
93
+ def encode_query(self, *args, **kwargs):
94
+ return self.encode_text(*args, **kwargs)
95
+
96
+ def encode_document(self, *args, **kwargs):
97
+ return self.encode_text(*args, **kwargs)
98
+
99
+ def encode_text(self, texts, batch_size: int = 32, max_length: int = None, source_view=False, return_dict=False, **kwargs):
100
+ if isinstance(texts, str):
101
+ texts = [texts]
102
+ if max_length is None:
103
+ max_length = self.m_tokenizer.model_max_length
104
+ device = "cuda" if torch.cuda.is_available() else "cpu"
105
+ self.to(device)
106
+ reps = []
107
+ for idx in range(0, len(texts), batch_size):
108
+ batch_texts = texts[idx:idx + batch_size]
109
+ inputs = self.m_tokenizer(
110
+ batch_texts, padding=True, truncation=True,
111
+ pad_to_multiple_of=32, max_length=max_length, return_tensors="pt",
112
+ )
113
+ inputs = {k: v.to(device) for k, v in inputs.items()}
114
+ with torch.no_grad(), torch.autocast(device_type=device, dtype=torch.bfloat16):
115
+ output = self._encode(
116
+ input_ids=inputs["input_ids"],
117
+ attention_mask=inputs["attention_mask"],
118
+ source_view=source_view,
119
+ )
120
+ if isinstance(output, tuple):
121
+ sparse_rep = self._build_dual_view_sparse(output)
122
+ else:
123
+ sparse_rep = output.to_sparse()
124
+ reps.append(sparse_rep.cpu())
125
+ combined = sparse_row_cat_2d(reps)
126
+ assert len(texts) == combined.size(0)
127
+ if return_dict:
128
+ return self._sparse_to_dicts(combined)
129
+ return combined
130
+
131
+ def _sparse_to_dicts(self, sparse_tensor):
132
+ """Convert a sparse [N, vocab] tensor to a list of {token: weight} dicts."""
133
+ id2term = self.get_vocab()
134
+ sparse_tensor = sparse_tensor.coalesce()
135
+ indices = sparse_tensor.indices()
136
+ values = sparse_tensor.values()
137
+ rows, cols = indices[0], indices[1]
138
+ result = [[] for _ in range(sparse_tensor.size(0))]
139
+ for i in range(len(values)):
140
+ row = rows[i].item()
141
+ col = cols[i].item()
142
+ weight = values[i].item()
143
+ token = id2term.get(col, f"unk_{col}")
144
+ result[row].append((token, weight))
145
+ return [
146
+ dict(sorted(pairs, key=lambda x: x[1], reverse=True))
147
+ for pairs in result
148
+ ]
149
+
150
+ def _build_dual_view_sparse(self, output):
151
+ pivot_view, (source_ids, source_weights) = output
152
+ batch_size = source_ids.size(0)
153
+ vocab_size = self.config.en_vocab_size + self.config.m_vocab_size
154
+
155
+ pivot_rows, pivot_cols = pivot_view.nonzero(as_tuple=True)
156
+ pivot_vals = pivot_view[pivot_rows, pivot_cols].contiguous()
157
+
158
+ source_rows = torch.arange(batch_size, device=source_ids.device).repeat_interleave(source_ids.size(1))
159
+ source_cols = source_ids.view(-1)
160
+ source_vals = source_weights.view(-1)
161
+ nonzero_mask = source_vals > 0
162
+ source_rows = source_rows[nonzero_mask]
163
+ source_cols = source_cols[nonzero_mask] + self.config.en_vocab_size
164
+ source_vals = source_vals[nonzero_mask]
165
+
166
+ rows = torch.cat([pivot_rows, source_rows])
167
+ cols = torch.cat([pivot_cols, source_cols])
168
+ indices = torch.stack([rows, cols], dim=0)
169
+ values = torch.cat([pivot_vals, source_vals])
170
+ return torch.sparse_coo_tensor(indices, values, (batch_size, vocab_size))
171
+
172
+ def _encode(self, input_ids, attention_mask, source_view=False):
173
+ hidden_states_m = self.m_model(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state
174
+ hidden_states_e = self.activation(self.projector(hidden_states_m))
175
+ logits = self.mlm_head(hidden_states_e) * attention_mask.unsqueeze(-1)
176
+ pivot_view = torch.log1p(torch.relu(logits.max(dim=1).values))
177
+ if source_view:
178
+ token_scores = torch.relu(self.echo(hidden_states_m).squeeze(-1))
179
+ source_weights = token_scores * attention_mask
180
+ return pivot_view, (input_ids, source_weights)
181
+ return pivot_view
182
+
183
+ def forward(self, *args, **kwargs):
184
+ return self._encode(*args, **kwargs)
185
+
186
+ def save_pretrained(self, save_directory: str, **kwargs):
187
+ kwargs["safe_serialization"] = False
188
+ super().save_pretrained(save_directory, **kwargs)
189
+
190
+
191
+ def sparse_row_cat_2d(tensors):
192
+ """Concatenate a list of 2-D COO sparse tensors along rows (dim=0)."""
193
+ assert len(tensors) > 0, "empty list"
194
+ if len(tensors) == 1:
195
+ return tensors[0]
196
+ tensors = [t.coalesce() for t in tensors]
197
+ assert all(t.layout == torch.sparse_coo for t in tensors), "COO only"
198
+
199
+ ncols = tensors[0].size(1)
200
+ assert all(t.dim() == 2 and t.size(1) == ncols for t in tensors), "size(1) mismatch"
201
+
202
+ total_rows = sum(t.size(0) for t in tensors)
203
+ device = tensors[0].device
204
+
205
+ ind_parts, val_parts = [], []
206
+ row_offset = 0
207
+ for t in tensors:
208
+ idx = t._indices()
209
+ if row_offset:
210
+ idx = idx.clone()
211
+ idx[0] += row_offset
212
+ ind_parts.append(idx)
213
+ val_parts.append(t._values())
214
+ row_offset += t.size(0)
215
+
216
+ indices = torch.cat(ind_parts, dim=1)
217
+ values = torch.cat(val_parts, dim=0)
218
+ return torch.sparse_coo_tensor(indices, values, (total_rows, ncols), device=device).coalesce()
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ff8fdc2da6b7462a3a97fd60a978044c8291809b3e6f8a3ab1b5c566d49e9ec0
3
+ size 2370559915