mohammadmahdinouri commited on
Commit
aeec937
·
verified ·
1 Parent(s): b5b06cb

Upload ModernALBERTForMaskedLM

Browse files
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,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "adapter_reduction": 16,
3
+ "architectures": [
4
+ "ModernALBERTForMaskedLM"
5
+ ],
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_modernalbert.ModernALBERTConfig",
9
+ "AutoModelForMaskedLM": "modeling_modernalbert.ModernALBERTForMaskedLM"
10
+ },
11
+ "classifier_dropout": null,
12
+ "dtype": "float32",
13
+ "embedding_size": 128,
14
+ "expert_intermediate_size": 2624,
15
+ "group_depth": 2,
16
+ "hidden_act": "gelu",
17
+ "hidden_dropout_prob": 0.1,
18
+ "hidden_size": 768,
19
+ "initializer_range": 0.02,
20
+ "intermediate_size": 1152,
21
+ "layer_norm_eps": 1e-06,
22
+ "load_balancing_loss_coef": 0.1,
23
+ "lora_alpha": 32,
24
+ "lora_rank": 16,
25
+ "max_position_embeddings": 8192,
26
+ "model_type": "ModernALBERT",
27
+ "num_attention_heads": 12,
28
+ "num_expert_modules": 2,
29
+ "num_experts": 4,
30
+ "num_hidden_layers": 14,
31
+ "pad_token_id": 0,
32
+ "router_jitter_noise": 0.01,
33
+ "routing_strategy": "standard",
34
+ "top_k": 1,
35
+ "transformers_version": "4.56.0",
36
+ "use_adapter": true,
37
+ "use_cache": true,
38
+ "use_moa": true,
39
+ "vocab_size": 50368
40
+ }
configuration_modernalbert.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import load_dataset
2
+ from transformers import (
3
+ AutoTokenizer,
4
+ AutoModelForMaskedLM,
5
+ DataCollatorForLanguageModeling,
6
+ Trainer,
7
+ TrainingArguments,
8
+ )
9
+
10
+ from itertools import chain
11
+ import torch
12
+
13
+ import transformers as ts
14
+ from optimi import StableAdamW
15
+ import os
16
+
17
+ from transformers.modeling_outputs import *
18
+ import torch.nn as nn
19
+ import torch
20
+ from dataclasses import dataclass
21
+ from typing import Optional, Tuple
22
+ import transformers as ts
23
+ import gc
24
+
25
+ from transformers import PretrainedConfig
26
+ import torch.nn.functional as F
27
+
28
+ from typing import Optional, Union
29
+
30
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
31
+ from transformers.activations import ACT2FN
32
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
33
+
34
+ import math
35
+
36
+ class ModernALBERTConfig(PretrainedConfig):
37
+ """
38
+ Configuration class for the ModernALBERT model with a LoRA-based MoE.
39
+ """
40
+ model_type = "ModernALBERT"
41
+
42
+ def __init__(
43
+ self,
44
+ # Block Adapter settings
45
+ use_adapter: bool = True,
46
+ adapter_reduction: int = 16,
47
+
48
+ # LoRA Mixture of Experts (MoE) settings
49
+ use_moa: bool = True,
50
+ num_experts: int = 8,
51
+ expert_intermediate_size = 2048,
52
+ top_k: int = 2,
53
+ lora_rank: int = 16,
54
+ lora_alpha: int = 32,
55
+ router_jitter_noise: float = 0.01,
56
+ load_balancing_loss_coef: float = 0.01,
57
+ num_expert_modules = 3,
58
+
59
+ # Layer sharing
60
+ group_depth: int = 4,
61
+
62
+ # Model dims
63
+ vocab_size: int = 50368,
64
+ hidden_size: int = 1024,
65
+ embedding_size: int = 128,
66
+ num_hidden_layers: int = 16,
67
+ num_attention_heads: int = 16,
68
+ intermediate_size: int = 2624, # Typically 4 * hidden_size
69
+
70
+ # Activation and dropout
71
+ hidden_act: str = "gelu",
72
+ hidden_dropout_prob: float = 0.1,
73
+ attention_probs_dropout_prob: float = 0.1,
74
+
75
+ # Position embeddings
76
+ max_position_embeddings: int = 8192,
77
+
78
+ # Other standard params
79
+ pad_token_id: int = 0,
80
+ initializer_range: float = 0.02,
81
+ layer_norm_eps: float = 1e-6,
82
+ use_cache: bool = True,
83
+
84
+ # Sequence classification
85
+ num_labels: int = 2,
86
+ classifier_dropout: float = None,
87
+ routing_strategy: str = "standard",
88
+ **kwargs,
89
+ ):
90
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
91
+
92
+ self.use_adapter = use_adapter
93
+ self.adapter_reduction = adapter_reduction
94
+ self.use_moa = use_moa
95
+ self.num_experts = num_experts
96
+ self.top_k = top_k
97
+ self.lora_rank = lora_rank
98
+ self.router_jitter_noise = router_jitter_noise
99
+ self.load_balancing_loss_coef = load_balancing_loss_coef
100
+ self.group_depth = group_depth
101
+ self.vocab_size = vocab_size
102
+ self.hidden_size = hidden_size
103
+ self.embedding_size = embedding_size
104
+ self.num_hidden_layers = num_hidden_layers
105
+ self.num_attention_heads = num_attention_heads
106
+ self.intermediate_size = intermediate_size
107
+ self.expert_intermediate_size = expert_intermediate_size
108
+ self.hidden_act = hidden_act
109
+ self.hidden_dropout_prob = hidden_dropout_prob
110
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
111
+ self.max_position_embeddings = max_position_embeddings
112
+ self.initializer_range = initializer_range
113
+ self.layer_norm_eps = layer_norm_eps
114
+ self.use_cache = use_cache
115
+ self.num_labels = num_labels
116
+ self.classifier_dropout = classifier_dropout
117
+ self.lora_alpha = lora_alpha
118
+ self.num_expert_modules = num_expert_modules
119
+ self.routing_strategy = routing_strategy
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:07e724fef0ad384d28b2cfd16fd7697a8340c5901be48a42a07335e3d38a8a2f
3
+ size 205288808
modeling_modernalbert.py ADDED
@@ -0,0 +1,1728 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import load_dataset
2
+ from transformers import (
3
+ AutoTokenizer,
4
+ AutoModelForMaskedLM,
5
+ DataCollatorForLanguageModeling,
6
+ Trainer,
7
+ TrainingArguments,
8
+ )
9
+
10
+ from itertools import chain
11
+ import torch
12
+
13
+ import transformers as ts
14
+ from optimi import StableAdamW
15
+ import os
16
+
17
+ from transformers.modeling_outputs import *
18
+ import torch.nn as nn
19
+ import torch
20
+ from dataclasses import dataclass
21
+ from typing import Optional, Tuple
22
+ import transformers as ts
23
+ import gc
24
+
25
+ from transformers import PretrainedConfig
26
+ import torch.nn.functional as F
27
+
28
+ from typing import Optional, Union
29
+
30
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
31
+ from transformers.activations import ACT2FN
32
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
33
+
34
+ import math
35
+
36
+ # Optional FlashAttention import
37
+ try:
38
+ from flash_attn.bert_padding import unpad_input, pad_input
39
+ from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func
40
+ from flash_attn.layers.rotary import RotaryEmbedding
41
+ from flash_attn.ops.triton.rotary import apply_rotary
42
+ FLASH_ATTN_AVAILABLE = True
43
+ print("✅ FlashAttention is available.")
44
+ except ImportError:
45
+ FLASH_ATTN_AVAILABLE = False
46
+ print("❌ FlashAttention is not available. Using PyTorch SDPA fallback.")
47
+
48
+ from .configuration_modernalbert import ModernALBERTConfig
49
+
50
+ # --- Shared FFN (Unchanged) ---
51
+ class SharedLoraFFN(nn.Module):
52
+ """
53
+ A shared Feed-Forward Network modified by LoRA weights.
54
+ The forward pass accepts pre-merged LoRA weights.
55
+ """
56
+ def __init__(self, config):
57
+ super().__init__()
58
+ dim = config.hidden_size
59
+ intermediate_dim = config.expert_intermediate_size
60
+
61
+ self.linear1 = nn.Linear(dim, intermediate_dim)
62
+ self.act = nn.GELU()
63
+ self.linear2 = nn.Linear(intermediate_dim, dim)
64
+ self.lora_scaling = config.lora_alpha / config.lora_rank
65
+
66
+ def forward(self, x, lora_A1, lora_B1, lora_A2, lora_B2):
67
+ # Apply the merged LoRA weights
68
+ # Formula: (x @ A.T @ B.T) * scale
69
+ expanded = self.linear1(x) + (x @ lora_A1.T @ lora_B1.T) * self.lora_scaling
70
+ activated = self.act(expanded)
71
+ contracted = self.linear2(activated) + (activated @ lora_A2.T @ lora_B2.T) * self.lora_scaling
72
+ return contracted
73
+
74
+ # --- 1. The Router (Fixed for Flash Attention / Unpadded Inputs) ---
75
+ class SwitchRouterTopK(nn.Module):
76
+ """
77
+ Calculates the EMA weights for expert merging.
78
+ Optimized for unpadded (Flash Attention) inputs where shape is (total_nnz, dim).
79
+ """
80
+ def __init__(self, config):
81
+ super().__init__()
82
+ self.config = config
83
+
84
+ self.num_experts = config.num_experts
85
+ # Use a slightly lower decay during training if starting from scratch (e.g., 0.9)
86
+ self.ema_decay = getattr(config, "router_ema_decay", 0.99)
87
+
88
+ self.layer = nn.Linear(config.hidden_size, config.num_experts, bias=False)
89
+ self.k = config.top_k
90
+ self.jitter_noise = config.router_jitter_noise
91
+
92
+ # Buffer for inference (frozen stats)
93
+ self.register_buffer("ema_weights", torch.ones(config.num_experts) / config.num_experts)
94
+
95
+ def forward(self, hidden_states):
96
+ # hidden_states shape: (total_nnz, hidden_size)
97
+ if self.config.routing_strategy == "ema":
98
+ # 1. Compute Router Probabilities
99
+ logits = self.layer(hidden_states) # Shape: (total_nnz, num_experts)
100
+ probs = F.softmax(logits, dim=-1)
101
+
102
+ if self.training:
103
+ # 2. Compute batch-level routing vector r_b
104
+ # Since inputs are unpadded (Batch * Seq flattened to dim 0),
105
+ # we simply average across all tokens to get the global batch stats.
106
+ r_b = probs.mean(dim=0) # Shape: (num_experts,)
107
+
108
+ # 3. Calculate the weight to USE for this step (Allow Gradients!)
109
+ # We mix history (detached) with current (with grad) to stabilize training.
110
+ weights_for_forward = self.ema_decay * self.ema_weights.detach() + (1 - self.ema_decay) * r_b
111
+
112
+ # 4. Update the buffer in the background (No Gradients needed for storage)
113
+ new_ema_value = weights_for_forward.detach()
114
+ self.ema_weights.copy_(new_ema_value)
115
+
116
+ # Normalize to ensure sum is 1
117
+ self.ema_weights.div_(self.ema_weights.sum() + 1e-9)
118
+
119
+ return weights_for_forward
120
+
121
+ # During inference, return the frozen stable weights
122
+ return self.ema_weights
123
+ else:
124
+ num_tokens = hidden_states.shape[0]
125
+
126
+ # if self.training and self.jitter_noise > 0:
127
+ # noise = torch.randn_like(hidden_states) * self.jitter_noise
128
+ # hidden_states = hidden_states + noise
129
+
130
+ logits = self.layer(hidden_states)
131
+ probs = F.softmax(logits, dim=-1, dtype=torch.float32)
132
+ topk_probs, topk_indices = torch.topk(probs, k=self.k, dim=-1)
133
+ topk_probs_normalized = topk_probs / torch.sum(topk_probs, dim=-1, keepdim=True)
134
+
135
+ # Load Balancing for K = 1
136
+
137
+ # flat_topk_indices = topk_indices.flatten()
138
+ # one_hot_assignments = F.one_hot(flat_topk_indices, num_classes=self.num_experts).float()
139
+ # tokens_per_expert_fraction = one_hot_assignments.sum(0) / num_tokens
140
+ # print(tokens_per_expert_fraction)
141
+ # router_prob_per_expert = torch.mean(probs, dim=0)
142
+
143
+ # Load Balancing for K > 1
144
+ one_hot = F.one_hot(topk_indices, num_classes=self.num_experts).float()
145
+ tokens_per_expert = torch.sum(one_hot * topk_probs.unsqueeze(-1), dim=(0, 1)) / num_tokens
146
+ router_prob_per_expert = torch.mean(probs, dim=0)
147
+
148
+ aux_loss = self.num_experts * torch.mean(tokens_per_expert * router_prob_per_expert)
149
+
150
+ # --- DEBUG: print expert utilization for this batch ---
151
+ # print("Expert utilization (fraction of tokens per expert):", tokens_per_expert.detach().cpu().numpy())
152
+ # print(aux_loss)
153
+
154
+ return topk_indices, topk_probs_normalized, aux_loss
155
+
156
+ # --- 2. The MoE Layer (Minor cleanup for debug prints) ---
157
+ class LoraMoELayerTopK(nn.Module):
158
+ """
159
+ Implements the MoL layer with expert merging.
160
+ Allows for efficient dense computation by collapsing experts
161
+ into a single adapter based on router weights.
162
+ """
163
+ def __init__(self, config):
164
+ super().__init__()
165
+ self.config = config
166
+
167
+ dim = config.hidden_size
168
+ expert_intermediate_dim = config.expert_intermediate_size
169
+ num_experts = config.num_experts
170
+ lora_rank = config.lora_rank
171
+
172
+ self.k = config.top_k
173
+ self.num_experts = num_experts
174
+
175
+ self.norm = nn.LayerNorm(dim, eps=config.layer_norm_eps)
176
+
177
+ self.router = SwitchRouterTopK(config)
178
+ self.shared_ffn = SharedLoraFFN(config)
179
+
180
+ # The pool of Expert LoRA weights {\Delta_1, ..., \Delta_E}
181
+ self.lora_A1 = nn.Parameter(torch.randn(num_experts, lora_rank, dim))
182
+ self.lora_B1 = nn.Parameter(torch.zeros(num_experts, expert_intermediate_dim, lora_rank))
183
+ self.lora_A2 = nn.Parameter(torch.randn(num_experts, lora_rank, expert_intermediate_dim))
184
+ self.lora_B2 = nn.Parameter(torch.zeros(num_experts, dim, lora_rank))
185
+
186
+ # Initialization (Kaiming Uniform)
187
+ for i in range(num_experts):
188
+ nn.init.kaiming_uniform_(self.lora_A1[i], a=math.sqrt(5))
189
+ nn.init.kaiming_uniform_(self.lora_A2[i], a=math.sqrt(5))
190
+
191
+ def forward(self, hidden_states: torch.Tensor):
192
+ if self.config.routing_strategy == "ema":
193
+ residual = hidden_states
194
+ hidden_states_norm = self.norm(hidden_states)
195
+
196
+ # 1. Get the global merging weights (w_t)
197
+ # Returns shape: (num_experts,)
198
+ merge_weights = self.router(hidden_states_norm)
199
+
200
+ # 2. Weighted Merge of all LoRA parameters
201
+ # Formula: \Delta_{merged} = \sum_{j=1}^E w_j * \Delta_j
202
+ # We reshape weights to [Experts, 1, 1] for broadcasting against [Experts, Rank, Dim]
203
+ w = merge_weights.view(-1, 1, 1)
204
+
205
+ merged_A1 = torch.sum(w * self.lora_A1, dim=0)
206
+ merged_B1 = torch.sum(w * self.lora_B1, dim=0)
207
+ merged_A2 = torch.sum(w * self.lora_A2, dim=0)
208
+ merged_B2 = torch.sum(w * self.lora_B2, dim=0)
209
+
210
+ # 3. Dense Forward Pass
211
+ # Pass the merged adapter to the FFN.
212
+ output = self.shared_ffn(
213
+ hidden_states_norm,
214
+ merged_A1, merged_B1,
215
+ merged_A2, merged_B2
216
+ )
217
+
218
+ # We return 0.0 for aux_loss because we are not doing load balancing in this mode
219
+ return residual + output, torch.tensor(0.0, device=hidden_states.device)
220
+ elif self.config.routing_strategy == "uniform":
221
+ residual = hidden_states
222
+ hidden_states_norm = self.norm(hidden_states)
223
+
224
+ # 1. Get the global merging weights (w_t)
225
+ # Returns shape: (num_experts,)
226
+ merge_weights = torch.ones(self.config.num_experts, dtype=hidden_states_norm.dtype, device=hidden_states_norm.device) / (self.config.num_experts)
227
+
228
+ # 2. Weighted Merge of all LoRA parameters
229
+ # Formula: \Delta_{merged} = \sum_{j=1}^E w_j * \Delta_j
230
+ # We reshape weights to [Experts, 1, 1] for broadcasting against [Experts, Rank, Dim]
231
+ w = merge_weights.view(-1, 1, 1)
232
+
233
+ merged_A1 = torch.sum(w * self.lora_A1, dim=0)
234
+ merged_B1 = torch.sum(w * self.lora_B1, dim=0)
235
+ merged_A2 = torch.sum(w * self.lora_A2, dim=0)
236
+ merged_B2 = torch.sum(w * self.lora_B2, dim=0)
237
+
238
+ # 3. Dense Forward Pass
239
+ # Pass the merged adapter to the FFN.
240
+ output = self.shared_ffn(
241
+ hidden_states_norm,
242
+ merged_A1, merged_B1,
243
+ merged_A2, merged_B2
244
+ )
245
+
246
+ # We return 0.0 for aux_loss because we are not doing load balancing in this mode
247
+ return residual + output, torch.tensor(0.0, device=hidden_states.device)
248
+ else:
249
+ residual = hidden_states
250
+ hidden_states_norm = self.norm(hidden_states)
251
+ num_tokens, dim = hidden_states_norm.shape
252
+
253
+ topk_indices, topk_probs, aux_loss = self.router(hidden_states_norm)
254
+
255
+ # Efficient permutation-based dispatch
256
+ flat_token_indices = torch.arange(num_tokens, device=hidden_states.device).repeat_interleave(self.k)
257
+ flat_expert_indices = topk_indices.flatten()
258
+
259
+ perm_indices = torch.argsort(flat_expert_indices)
260
+ sorted_token_indices = flat_token_indices[perm_indices]
261
+ sorted_expert_indices = flat_expert_indices[perm_indices]
262
+
263
+ permuted_tokens = hidden_states_norm[sorted_token_indices]
264
+ permuted_probs = topk_probs.flatten()[perm_indices]
265
+
266
+ tokens_per_expert = F.one_hot(sorted_expert_indices, self.num_experts).sum(dim=0)
267
+ split_tokens = torch.split(permuted_tokens, tokens_per_expert.tolist(), dim=0)
268
+ split_probs = torch.split(permuted_probs, tokens_per_expert.tolist(), dim=0)
269
+
270
+ # Batched processing loop over experts
271
+ expert_outputs = []
272
+ for i in range(self.num_experts):
273
+ if tokens_per_expert[i] > 0:
274
+ output = self.shared_ffn(
275
+ split_tokens[i],
276
+ self.lora_A1[i], self.lora_B1[i],
277
+ self.lora_A2[i], self.lora_B2[i]
278
+ )
279
+ expert_outputs.append(output * split_probs[i].unsqueeze(1))
280
+ else:
281
+ expert_outputs.append(torch.empty(0, dim, device=hidden_states.device))
282
+
283
+ # Un-permute and combine results
284
+ concatenated_outputs = torch.cat(expert_outputs, dim=0)
285
+ inverse_perm_indices = torch.argsort(perm_indices)
286
+ unpermuted_outputs = concatenated_outputs[inverse_perm_indices]
287
+
288
+ final_output = unpermuted_outputs.view(num_tokens, self.k, dim).sum(dim=1)
289
+
290
+ # Final residual connection
291
+ output = residual + final_output
292
+ return output, aux_loss
293
+
294
+
295
+ class ModernAlbertMLP(nn.Module):
296
+ def __init__(self, config: ModernALBERTConfig):
297
+ super().__init__()
298
+ self.config = config
299
+ self.Wi = nn.Linear(config.hidden_size, int(config.intermediate_size) * 2, bias=False)
300
+ # self.act = ACT2FN[config.hidden_activation]
301
+ self.act = ACT2FN["gelu"]
302
+ self.drop = nn.Dropout(config.hidden_dropout_prob)
303
+ self.Wo = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
304
+
305
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
306
+ input, gate = self.Wi(hidden_states).chunk(2, dim=-1)
307
+ return self.Wo(self.drop(self.act(input) * gate))
308
+
309
+ #Flash Attention Rotatory Embedding
310
+ class ApplyRotaryEmbUnpad(torch.autograd.Function):
311
+ @staticmethod
312
+ def forward(
313
+ ctx,
314
+ qkv,
315
+ cos,
316
+ sin,
317
+ cu_seqlens: Optional[torch.Tensor] = None,
318
+ max_seqlen: Optional[int] = None,
319
+ ):
320
+ # (total_nnz, 3, nheads, headdim)
321
+ qkv = qkv.contiguous()
322
+ total_nnz, _three, _nheads, headdim = qkv.shape
323
+ # We need qkv to be contiguous so that when we reshape to combine (3, nheads) dimensions,
324
+ # we get the same tensor
325
+ # qk = rearrange(qkv[:, :2], "b_s t h d -> b_s (t h) d")
326
+ qk = qkv[:, :2].view(total_nnz, -1, headdim)
327
+ apply_rotary(
328
+ qk,
329
+ cos,
330
+ sin,
331
+ seqlen_offsets=0,
332
+ cu_seqlens=cu_seqlens,
333
+ max_seqlen=max_seqlen,
334
+ interleaved=False,
335
+ inplace=True,
336
+ )
337
+
338
+ ctx.save_for_backward(cos, sin, cu_seqlens)
339
+ ctx.max_seqlen = max_seqlen
340
+ return qkv
341
+
342
+ @staticmethod
343
+ def backward(ctx, do):
344
+ cos, sin, cu_seqlens = ctx.saved_tensors
345
+ do = do.contiguous()
346
+ total_nnz, _three, _nheads, headdim = do.shape
347
+ # We need dqkv to be contiguous so that when we reshape to combine (3, nheads) dimensions,
348
+ # we get the same tensor
349
+ dqk = do[:, :2].view(total_nnz, -1, headdim)
350
+ apply_rotary(
351
+ dqk,
352
+ cos,
353
+ sin,
354
+ seqlen_offsets=0,
355
+ cu_seqlens=cu_seqlens,
356
+ max_seqlen=ctx.max_seqlen,
357
+ interleaved=False,
358
+ inplace=True,
359
+ conjugate=True,
360
+ )
361
+
362
+ return do, None, None, None, None, None, None
363
+
364
+
365
+ def apply_rotary_unpadded(
366
+ qkv,
367
+ cos,
368
+ sin,
369
+ cu_seqlens: Optional[torch.Tensor] = None,
370
+ max_seqlen: Optional[int] = None,
371
+ ):
372
+ """
373
+ Arguments:
374
+ qkv: (total_nnz, 3, nheads, headdim) - input tensor for packed QKV.
375
+ cos, sin: (seqlen_rotary, rotary_dim / 2)
376
+ interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead
377
+ of 1st half and 2nd half (GPT-NeoX style).
378
+ inplace: if True, apply rotary embedding in-place.
379
+ seqlen_offsets: (batch_size,) or int. Each sequence in x is shifted by this amount.
380
+ Most commonly used in inference when we have KV cache.
381
+ cu_seqlens: (batch + 1,) or None
382
+ max_seqlen: int
383
+ Return:
384
+ out: (total_nnz, dim)
385
+ rotary_dim must be <= headdim
386
+ Apply rotary embedding to the first rotary_dim of x.
387
+ """
388
+ return ApplyRotaryEmbUnpad.apply(qkv, cos, sin, cu_seqlens, max_seqlen)
389
+
390
+
391
+ class ModernAlbertUnpaddedRotaryEmbedding(RotaryEmbedding):
392
+ """
393
+ The rotary position embeddings applied directly to unpadded sequences.
394
+ """
395
+
396
+ def __init__(
397
+ self,
398
+ dim: int,
399
+ base: float = 10000.0,
400
+ max_seqlen: Optional[int] = None,
401
+ device: Optional[torch.device] = None,
402
+ dtype: Optional[torch.dtype] = None,
403
+ ):
404
+ """
405
+ max_seqlen: if max_seqlen, device, and dtype are provided, we precompute the cos_sin_cache
406
+ up to max_seqlen. If the max_seqlen, device, or dtype during training/inference differ,
407
+ the cos_sin_cache will be recomputed during the forward pass.
408
+ """
409
+ super().__init__(dim=dim, base=base, device=device, interleaved=False)
410
+ self.max_seqlen = max_seqlen
411
+
412
+ if max_seqlen is not None and device is not None and dtype is not None:
413
+ self._update_cos_sin_cache(max_seqlen, device=device, dtype=dtype)
414
+
415
+ def forward(
416
+ self,
417
+ qkv: torch.Tensor,
418
+ cu_seqlens: torch.Tensor,
419
+ max_seqlen: Optional[int] = None,
420
+ ) -> Union[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]:
421
+ """
422
+ Apply rotary embedding *inplace* to qkv.
423
+ qkv: (total_nnz, 3, nheads, headdim)
424
+ cu_seqlens: (batch + 1,) cumulative sequence lengths
425
+ max_seqlen: int max seq length in the batch
426
+ """
427
+ if max_seqlen is not None:
428
+ self._update_cos_sin_cache(max_seqlen, device=qkv.device, dtype=qkv.dtype)
429
+
430
+ qkv = apply_rotary_unpadded(
431
+ qkv,
432
+ self._cos_cached,
433
+ self._sin_cached,
434
+ cu_seqlens=cu_seqlens,
435
+ max_seqlen=max_seqlen,
436
+ )
437
+
438
+ return qkv
439
+
440
+ def extra_repr(self) -> str:
441
+ return f"dim={self.dim}, base={self.base}, scale_base={self.scale_base}"
442
+
443
+ class ModernAlbertRotaryEmbedding(nn.Module):
444
+ def __init__(self, config: ModernALBERTConfig, device=None):
445
+ super().__init__()
446
+ # BC: "rope_type" was originally "type"
447
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
448
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
449
+ else:
450
+ self.rope_type = "default"
451
+ self.max_seq_len_cached = config.max_position_embeddings
452
+ self.original_max_seq_len = config.max_position_embeddings
453
+
454
+ self.config = config
455
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
456
+
457
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
458
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
459
+ self.original_inv_freq = self.inv_freq
460
+
461
+ @torch.no_grad()
462
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
463
+ def forward(self, x, position_ids):
464
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
465
+ position_ids_expanded = position_ids[:, None, :].float()
466
+
467
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
468
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
469
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
470
+ emb = torch.cat((freqs, freqs), dim=-1)
471
+ cos = emb.cos() * self.attention_scaling
472
+ sin = emb.sin() * self.attention_scaling
473
+
474
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
475
+
476
+ # GeGLU unchanged
477
+ class GeGLU(nn.Module):
478
+ def __init__(self, dim_in, dim_out):
479
+ super().__init__()
480
+ self.w1 = nn.Linear(dim_in, dim_out)
481
+ self.w2 = nn.Linear(dim_in, dim_out)
482
+ def forward(self, x):
483
+ return F.gelu(self.w1(x)) * self.w2(x)
484
+
485
+
486
+ #Flash Attention
487
+ def _unpad_modernbert_input(
488
+ inputs: torch.Tensor,
489
+ attention_mask: torch.Tensor,
490
+ position_ids: Optional[torch.Tensor] = None,
491
+ labels: Optional[torch.Tensor] = None,
492
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, int, Optional[torch.Tensor], Optional[torch.Tensor]]:
493
+ """
494
+ Remove padding from input sequences.
495
+
496
+ Args:
497
+ inputs: (batch, seqlen, ...) or (batch, seqlen)
498
+ attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid.
499
+ position_ids: (batch, seqlen), int, position ids
500
+ labels: (batch, seqlen), int, labels
501
+
502
+ Returns:
503
+ unpadded_inputs: (total_nnz, ...), where total_nnz = number of tokens selected in attention_mask.
504
+ indices: (total_nnz)
505
+ cu_seqlens: (batch + 1), the cumulative sequence lengths
506
+ max_seqlen_in_batch: int
507
+ unpadded_position_ids: (total_nnz) or None
508
+ unpadded_labels: (total_nnz) or None
509
+ """
510
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
511
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
512
+ max_seqlen_in_batch = int(seqlens_in_batch.max().item())
513
+ cu_seqlens = torch.nn.functional.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
514
+
515
+ if inputs.dim() == 2:
516
+ unpadded_inputs = inputs.flatten()[indices]
517
+ else:
518
+ batch, seqlen, *rest = inputs.shape
519
+ shape = batch * seqlen
520
+ unpadded_inputs = inputs.view(shape, *rest)[indices]
521
+
522
+ unpadded_position_ids = position_ids.flatten()[indices] if position_ids is not None else None
523
+ unpadded_labels = labels.flatten()[indices] if labels is not None else None
524
+
525
+ return unpadded_inputs, indices, cu_seqlens, max_seqlen_in_batch, unpadded_position_ids, unpadded_labels
526
+
527
+
528
+ def _pad_modernbert_output(
529
+ inputs: torch.Tensor,
530
+ indices: torch.Tensor,
531
+ batch: int,
532
+ seqlen: int,
533
+ ) -> torch.Tensor:
534
+ """
535
+ Add padding to sequences.
536
+
537
+ Args:
538
+ inputs: (total_nnz, ...) or (total_nnz,), where total_nnz = number of tokens selected in attention_mask.
539
+ indices: (total_nnz)
540
+ batch: int, batch size
541
+ seqlen: int, max sequence length
542
+
543
+ Returns:
544
+ padded_inputs: (batch, seqlen, ...) or (batch, seqlen)
545
+ """
546
+ if inputs.dim() == 1:
547
+ output = torch.zeros(batch * seqlen, dtype=inputs.dtype, device=inputs.device)
548
+ output[indices] = inputs
549
+ padded_inputs = output.view(batch, seqlen)
550
+ else:
551
+ _, *rest = inputs.shape
552
+ output = torch.zeros(batch * seqlen, *rest, dtype=inputs.dtype, device=inputs.device)
553
+ output[indices] = inputs
554
+ padded_inputs = output.view(batch, seqlen, *rest)
555
+
556
+ return padded_inputs
557
+
558
+
559
+ def flash_attention_forward(
560
+ module: "SharedGroup",
561
+ qkv: torch.Tensor,
562
+ rotary_emb: ModernAlbertUnpaddedRotaryEmbedding,
563
+ cu_seqlens: torch.Tensor,
564
+ max_seqlen: int,
565
+ local_attention: tuple[int, int],
566
+ bs: int,
567
+ dim: int,
568
+ target_dtype: torch.dtype = torch.bfloat16,
569
+ **_kwargs,
570
+ ) -> tuple[torch.Tensor]:
571
+ # (total_seqlen, 3, nheads, headdim)
572
+ qkv = rotary_emb(qkv, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen)
573
+
574
+ convert_dtype = qkv.dtype not in (torch.float16, torch.bfloat16)
575
+ if convert_dtype:
576
+ # FA2 implementation only supports fp16 and bf16. If FA2 is supported,
577
+ # bfloat16 must be supported as of FA2 2.5.7. (Turing GPUs not supported)
578
+ orig_dtype = qkv.dtype
579
+ qkv = qkv.to(target_dtype)
580
+
581
+ attn = flash_attn_varlen_qkvpacked_func(
582
+ qkv,
583
+ cu_seqlens=cu_seqlens,
584
+ max_seqlen=max_seqlen,
585
+ dropout_p=module.att_dropout.p if module.training else 0.0,
586
+ # deterministic=module.deterministic_flash_attn,
587
+ # deterministic=False,
588
+ window_size=local_attention,
589
+ )
590
+ attn = attn.to(orig_dtype) # type: ignore
591
+ else:
592
+ attn = flash_attn_varlen_qkvpacked_func(
593
+ qkv,
594
+ cu_seqlens=cu_seqlens,
595
+ max_seqlen=max_seqlen,
596
+ dropout_p=module.att_dropout.p if module.training else 0.0,
597
+ # deterministic=module.deterministic_flash_attn,
598
+ window_size=local_attention,
599
+ )
600
+ return (attn.view(bs, dim),)
601
+
602
+ def sdpa_attention_forward(
603
+ module: "SharedGroup",
604
+ qkv: torch.Tensor,
605
+ attention_mask: torch.Tensor,
606
+ sliding_window_mask: torch.Tensor,
607
+ position_ids: Optional[torch.LongTensor],
608
+ local_attention: tuple[int, int],
609
+ bs: int,
610
+ dim: int,
611
+ **_kwargs,
612
+ ) -> tuple[torch.Tensor]:
613
+ # qkv: [batch_size, seqlen, 3, nheads, headdim]
614
+ cos, sin = module.rotary_emb(qkv, position_ids=position_ids)
615
+ query, key, value = qkv.transpose(3, 1).unbind(dim=2)
616
+ # query, key, value: [batch_size, heads, seq_len, head_dim]
617
+ query, key = apply_rotary_pos_emb(query, key, cos, sin)
618
+
619
+ if local_attention != (-1, -1):
620
+ attention_mask = sliding_window_mask
621
+
622
+ attn_output = (
623
+ F.scaled_dot_product_attention(
624
+ query,
625
+ key,
626
+ value,
627
+ dropout_p=module.attention_dropout.p if module.training else 0.0,
628
+ attn_mask=attention_mask,
629
+ )
630
+ .transpose(1, 2)
631
+ .contiguous()
632
+ )
633
+ attn_output = attn_output.view(bs, -1, dim)
634
+ return (attn_output,)
635
+
636
+ class SharedGroup(nn.Module):
637
+ def __init__(self, config): # config: ModernALBERTConfig
638
+ super().__init__()
639
+ self.config = config
640
+
641
+ hs, nh = config.hidden_size, config.num_attention_heads
642
+ self.head_dim = hs // nh
643
+ self.num_heads = nh
644
+ self.use_adapter = config.use_adapter
645
+ eps = config.layer_norm_eps
646
+
647
+ rope_theta = 10000
648
+
649
+ # Norms
650
+ self.att_pre_norm = nn.LayerNorm(hs, eps=eps)
651
+ self.ffn_pre_norm = nn.LayerNorm(hs, eps=eps)
652
+
653
+ # Attention
654
+ self.qkv = nn.Linear(hs, 3 * hs)
655
+ self.out_proj = nn.Linear(hs, hs)
656
+ self.att_dropout = nn.Dropout(config.attention_probs_dropout_prob)
657
+ self.local_attention = (-1, -1)
658
+
659
+ if FLASH_ATTN_AVAILABLE:
660
+ self.rotary_emb = ModernAlbertUnpaddedRotaryEmbedding(
661
+ dim=self.head_dim, max_seqlen=config.max_position_embeddings, base=rope_theta
662
+ )
663
+ else:
664
+ config_copy = copy.deepcopy(config)
665
+ config_copy.rope_theta = rope_theta
666
+ self.rotary_emb = ModernAlbertRotaryEmbedding(config=config_copy)
667
+
668
+ # FFN
669
+ self.mlp = ModernAlbertMLP(config)
670
+
671
+ def forward(self, inputs, mask, config, start_idx=0, use_moa=False, **kwargs):
672
+ outputs = [] if config.output_hidden_states else None
673
+ attn_maps = [] if config.output_attentions else None
674
+
675
+ x = inputs
676
+
677
+ for i in range(config.group_depth):
678
+ h = x
679
+ h_norm = self.att_pre_norm(h)
680
+
681
+ qkv_proj = self.qkv(h_norm)
682
+ bs = h.shape[0]
683
+
684
+ # --- Attention Calculation ---
685
+ if FLASH_ATTN_AVAILABLE:
686
+ qkv = qkv_proj.view(-1, 3, self.num_heads, self.head_dim)
687
+
688
+ attn_outputs = flash_attention_forward(
689
+ self,
690
+ qkv=qkv,
691
+ rotary_emb=self.rotary_emb,
692
+ local_attention=self.local_attention,
693
+ bs=bs,
694
+ dim=self.head_dim * self.num_heads,
695
+ **kwargs,
696
+ )
697
+
698
+ attn_out = attn_outputs[0]
699
+ else: # Fallback to PyTorch Scaled Dot Product Attention
700
+ qkv = qkv_proj.view(bs, -1, 3, self.num_heads, self.head_dim)
701
+ attn_mask = mask[:, None, None, :]
702
+
703
+ attn_outputs = sdpa_attention_forward(
704
+ self,
705
+ qkv=qkv,
706
+ rotary_emb=self.rotary_emb,
707
+ local_attention=self.local_attention,
708
+ bs=bs,
709
+ dim=self.head_dim * self.num_heads,
710
+ **kwargs,
711
+ )
712
+
713
+ attn_out = attn_outputs[0]
714
+
715
+ x = self.att_dropout(self.out_proj(attn_out)) + h
716
+
717
+ if use_moa == True and i == config.group_depth - 1:
718
+ return x, outputs, attn_maps
719
+ else:
720
+ # FFN block
721
+ h2 = x
722
+ h2_norm = self.ffn_pre_norm(h2)
723
+
724
+ x = self.mlp(h2_norm) + h2
725
+
726
+ # Collect hidden state if needed
727
+ if config.output_hidden_states:
728
+ outputs.append(x)
729
+
730
+ return x, outputs, attn_maps
731
+
732
+
733
+ class ModernAlbertEmbeddings(nn.Module):
734
+ """
735
+ Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
736
+ """
737
+
738
+ def __init__(self, config: ModernALBERTConfig):
739
+ super().__init__()
740
+ self.config = config
741
+
742
+ self.tok_embeddings = nn.Embedding(config.vocab_size, config.embedding_size, padding_idx=config.pad_token_id)
743
+ self.embed_proj = nn.Linear(config.embedding_size, config.hidden_size)
744
+
745
+ # self.norm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps, bias=config.norm_bias)
746
+ self.norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps, bias=False)
747
+ self.drop = nn.Dropout(0.0)
748
+
749
+ def forward(
750
+ self, input_ids: Optional[torch.LongTensor] = None, inputs_embeds: Optional[torch.Tensor] = None
751
+ ) -> torch.Tensor:
752
+ if inputs_embeds is not None:
753
+ hidden_states = self.drop(self.norm(self.embed_proj(inputs_embeds)))
754
+ else:
755
+ hidden_states = self.drop(self.norm(self.embed_proj(self.tok_embeddings(input_ids))))
756
+
757
+ return hidden_states
758
+
759
+ @dataclass
760
+ class MoABaseModelOutput(BaseModelOutput):
761
+ load_balancing_loss: Optional[torch.FloatTensor] = None
762
+
763
+ class ModernALBERTModel(ts.PreTrainedModel):
764
+ config_class = ModernALBERTConfig
765
+ base_model_prefix = "modernAlbert"
766
+ _supports_flash_attn_2 = True
767
+ _supports_sdpa = True
768
+ _supports_cache_class = True
769
+
770
+ def __init__(self, config: ModernALBERTConfig):
771
+ super().__init__(config)
772
+ self.config = config
773
+
774
+ # Factorized embeddings
775
+ self.embeddings = ModernAlbertEmbeddings(config)
776
+ self.final_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps, bias=False)
777
+ self.num_groups = config.num_hidden_layers // config.group_depth
778
+ self.groups = nn.ModuleList([SharedGroup(config) for _ in range(self.num_groups)])
779
+
780
+ if config.use_moa:
781
+ self.moa_layers = nn.ModuleList([
782
+ # LoraMoELayerTopK(config) for _ in range(self.num_groups - 1)
783
+ LoraMoELayerTopK(config) for _ in range(config.num_expert_modules)
784
+ ])
785
+
786
+ self.pooler = nn.Linear(config.hidden_size, config.hidden_size)
787
+ self.post_init()
788
+
789
+ def forward(self,
790
+ input_ids: Optional[torch.LongTensor] = None,
791
+ attention_mask: Optional[torch.Tensor] = None,
792
+ sliding_window_mask: Optional[torch.Tensor] = None,
793
+ position_ids: Optional[torch.LongTensor] = None,
794
+ inputs_embeds: Optional[torch.Tensor] = None,
795
+ indices: Optional[torch.Tensor] = None,
796
+ cu_seqlens: Optional[torch.Tensor] = None,
797
+ max_seqlen: Optional[int] = None,
798
+ batch_size: Optional[int] = None,
799
+ seq_len: Optional[int] = None,
800
+ output_attentions: Optional[bool] = None,
801
+ output_hidden_states: Optional[bool] = None,
802
+ return_dict: Optional[bool] = None,
803
+ ):
804
+ all_hidden_states = []
805
+
806
+ if batch_size is None and seq_len is None:
807
+ if inputs_embeds is not None:
808
+ batch_size, seq_len = inputs_embeds.shape[:2]
809
+ else:
810
+ batch_size, seq_len = input_ids.shape[:2]
811
+
812
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
813
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
814
+
815
+ if output_hidden_states:
816
+ self.config.output_hidden_states = True
817
+
818
+ hs, atts = ([] if output_hidden_states else None), ([] if output_attentions else None)
819
+ all_aux_losses = []
820
+
821
+ repad = False
822
+ if FLASH_ATTN_AVAILABLE:
823
+ if indices is None and cu_seqlens is None and max_seqlen is None:
824
+ repad = True
825
+ if inputs_embeds is None:
826
+ with torch.no_grad():
827
+ input_ids, indices, cu_seqlens, max_seqlen, *_ = _unpad_modernbert_input(
828
+ inputs=input_ids, attention_mask=attention_mask
829
+ )
830
+ else:
831
+ inputs_embeds, indices, cu_seqlens, max_seqlen, *_ = _unpad_modernbert_input(
832
+ inputs=inputs_embeds, attention_mask=attention_mask
833
+ )
834
+ else:
835
+ if position_ids is None:
836
+ position_ids = torch.arange(seq_len, device=device).unsqueeze(0)
837
+
838
+ attention_mask, sliding_window_mask = self._update_attention_mask(
839
+ attention_mask, output_attentions=output_attentions
840
+ )
841
+
842
+ hidden_states = self.embeddings(input_ids=input_ids, inputs_embeds=inputs_embeds)
843
+ x = hidden_states
844
+
845
+ if output_hidden_states:
846
+ hs.append(x)
847
+
848
+ # Mask
849
+ mask = None
850
+ if attention_mask is not None:
851
+ mask = attention_mask.to(torch.bool)
852
+
853
+ for i, group in enumerate(self.groups):
854
+
855
+ is_moa = self.config.use_moa and (i > len(self.groups) - len(self.moa_layers) - 1)
856
+ moa_idx = i - (len(self.groups) - len(self.moa_layers))
857
+
858
+ x, layer_hs, layer_atts = group(x,
859
+ mask,
860
+ self.config,
861
+ sliding_window_mask=sliding_window_mask,
862
+ position_ids=position_ids,
863
+ cu_seqlens=cu_seqlens,
864
+ max_seqlen=max_seqlen,
865
+ use_moa=is_moa,
866
+ output_attentions=output_attentions,)
867
+
868
+ if output_hidden_states and layer_hs:
869
+ hs.extend(layer_hs)
870
+ if output_attentions and layer_atts:
871
+ atts.extend(layer_atts)
872
+
873
+ # After each group (except the last), apply the MoA layer
874
+ if self.config.use_moa and is_moa:
875
+ x, aux_loss = self.moa_layers[moa_idx](x)
876
+ if output_hidden_states:
877
+ hs.append(x)
878
+ all_aux_losses.append(aux_loss)
879
+
880
+
881
+ hidden_states = self.final_norm(x)
882
+
883
+ # hidden_states = _pad_modernbert_output(
884
+ # inputs=hidden_states, indices=indices, batch=batch_size, seqlen=seq_len
885
+ # )
886
+
887
+ if repad:
888
+ hidden_states = _pad_modernbert_output(
889
+ inputs=hidden_states, indices=indices, batch=batch_size, seqlen=seq_len
890
+ )
891
+ if all_hidden_states is not None:
892
+ all_hidden_states = tuple(
893
+ _pad_modernbert_output(inputs=hs, indices=indices, batch=batch_size, seqlen=seq_len)
894
+ for hs in all_hidden_states
895
+ )
896
+
897
+
898
+ load_balancing_loss = None
899
+ if all_aux_losses != []:
900
+ load_balancing_loss = torch.stack(all_aux_losses).mean() * self.config.load_balancing_loss_coef
901
+
902
+ return MoABaseModelOutput(last_hidden_state=hidden_states, hidden_states=hs, attentions=atts, load_balancing_loss=load_balancing_loss)
903
+
904
+ class ModernAlbertPredictionHead(nn.Module):
905
+ def __init__(self, config: ModernALBERTConfig):
906
+ super().__init__()
907
+ self.config = config
908
+ self.dense = nn.Linear(config.hidden_size, config.embedding_size, bias=False)
909
+ self.act = ACT2FN["gelu"]
910
+ self.norm = nn.LayerNorm(config.embedding_size, eps=config.layer_norm_eps, bias=False)
911
+
912
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
913
+ return self.norm(self.act(self.dense(hidden_states)))
914
+
915
+ class ModernALBERTForMaskedLM(ts.PreTrainedModel):
916
+ """
917
+ Modern ALBERT model with a Masked Language Modeling (MLM) head,
918
+ optimized to mirror the HuggingFace `AlbertForMaskedLM` API.
919
+ """
920
+ _tied_weights_keys = ["decoder.weight"]
921
+ config_class = ModernALBERTConfig
922
+ base_model_prefix = "modernAlbert"
923
+ _supports_flash_attn_2 = True
924
+ _supports_sdpa = True
925
+ _supports_cache_class = True
926
+
927
+ def __init__(self, config: ModernALBERTConfig):
928
+ super().__init__(config)
929
+ self.config = config
930
+
931
+ # Base encoder without pooling
932
+ self.albert = ModernALBERTModel(config)
933
+
934
+ # MLM head
935
+ self.head = ModernAlbertPredictionHead(config)
936
+ self.decoder = nn.Linear(config.embedding_size, config.vocab_size, bias=False)
937
+
938
+ self.post_init()
939
+
940
+ def get_input_embeddings(self):
941
+ return self.albert.embeddings.tok_embeddings
942
+
943
+ def get_output_embeddings(self):
944
+ return self.decoder
945
+
946
+ def set_output_embeddings(self, new_embeddings: nn.Linear):
947
+ self.decoder = new_embeddings
948
+
949
+ @torch.compile(dynamic=True)
950
+ def compiled_head(self, output: torch.Tensor) -> torch.Tensor:
951
+ return self.decoder(self.head(output))
952
+
953
+ def forward(
954
+ self,
955
+ input_ids: Optional[torch.LongTensor] = None,
956
+ attention_mask: Optional[torch.Tensor] = None,
957
+ sliding_window_mask: Optional[torch.Tensor] = None,
958
+ position_ids: Optional[torch.Tensor] = None,
959
+ inputs_embeds: Optional[torch.Tensor] = None,
960
+ labels: Optional[torch.Tensor] = None,
961
+ indices: Optional[torch.Tensor] = None,
962
+ cu_seqlens: Optional[torch.Tensor] = None,
963
+ max_seqlen: Optional[int] = None,
964
+ batch_size: Optional[int] = None,
965
+ seq_len: Optional[int] = None,
966
+ output_attentions: Optional[bool] = None,
967
+ output_hidden_states: Optional[bool] = None,
968
+ return_dict: Optional[bool] = None,
969
+ **kwargs,
970
+ ):
971
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
972
+
973
+ if FLASH_ATTN_AVAILABLE:
974
+ if indices is None and cu_seqlens is None and max_seqlen is None:
975
+ if batch_size is None and seq_len is None:
976
+ if inputs_embeds is not None:
977
+ batch_size, seq_len = inputs_embeds.shape[:2]
978
+ else:
979
+ batch_size, seq_len = input_ids.shape[:2]
980
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
981
+
982
+ if attention_mask is None:
983
+ attention_mask = torch.ones((batch_size, seq_len), device=device, dtype=torch.bool)
984
+
985
+ if inputs_embeds is None:
986
+ with torch.no_grad():
987
+ input_ids, indices, cu_seqlens, max_seqlen, position_ids, labels = _unpad_modernbert_input(
988
+ inputs=input_ids, attention_mask=attention_mask, position_ids=position_ids, labels=labels
989
+ )
990
+ else:
991
+ inputs_embeds, indices, cu_seqlens, max_seqlen, position_ids, labels = _unpad_modernbert_input(
992
+ inputs=inputs_embeds, attention_mask=attention_mask, position_ids=position_ids, labels=labels
993
+ )
994
+
995
+ # Encode
996
+ outputs = self.albert(
997
+ input_ids=input_ids,
998
+ attention_mask=attention_mask,
999
+ sliding_window_mask=sliding_window_mask,
1000
+ position_ids=position_ids,
1001
+ inputs_embeds=inputs_embeds,
1002
+ indices=indices,
1003
+ cu_seqlens=cu_seqlens,
1004
+ max_seqlen=max_seqlen,
1005
+ batch_size=batch_size,
1006
+ seq_len=seq_len,
1007
+ output_attentions=output_attentions,
1008
+ output_hidden_states=output_hidden_states,
1009
+ return_dict=return_dict,
1010
+ )
1011
+
1012
+ last_hidden_state = outputs[0]
1013
+
1014
+ if FLASH_ATTN_AVAILABLE:
1015
+ last_hidden_state_unpaded = _pad_modernbert_output(inputs=last_hidden_state, indices=indices, batch=batch_size, seqlen=seq_len)
1016
+ if outputs.hidden_states != None:
1017
+ outputs.hidden_states.append(last_hidden_state_unpaded)
1018
+
1019
+ logits = self.decoder(self.head(last_hidden_state))
1020
+
1021
+ loss = None
1022
+
1023
+ if labels is not None:
1024
+ loss = self.loss_function(logits, labels, vocab_size=self.config.vocab_size, **kwargs)
1025
+
1026
+ if outputs.load_balancing_loss != None and self.training:
1027
+ # print(outputs.load_balancing_loss)
1028
+ loss += outputs.load_balancing_loss
1029
+
1030
+ if FLASH_ATTN_AVAILABLE:
1031
+ logits = _pad_modernbert_output(inputs=logits, indices=indices, batch=batch_size, seqlen=seq_len)
1032
+
1033
+ if not return_dict:
1034
+ output = (logits,)
1035
+ return ((loss,) + output) if loss is not None else output
1036
+
1037
+ return MaskedLMOutput(
1038
+ loss=loss,
1039
+ logits=logits,
1040
+ hidden_states=outputs.hidden_states,
1041
+ attentions=outputs.attentions,
1042
+ )
1043
+
1044
+ class ModernALBERTForSequenceClassification(ts.PreTrainedModel):
1045
+ config_class = ModernALBERTConfig
1046
+
1047
+ def __init__(self, config: ModernALBERTConfig):
1048
+ super().__init__(config)
1049
+ self.num_labels = config.num_labels
1050
+ self.config = config
1051
+
1052
+ self.albert = ModernALBERTModel(config)
1053
+ self.head = ModernAlbertPredictionHead(config)
1054
+ self.drop = torch.nn.Dropout(0.0)
1055
+ self.classifier = nn.Linear(config.embedding_size, config.num_labels)
1056
+
1057
+ # Initialize weights and apply final processing
1058
+ self.post_init()
1059
+
1060
+ def forward(
1061
+ self,
1062
+ input_ids: Optional[torch.LongTensor] = None,
1063
+ attention_mask: Optional[torch.Tensor] = None,
1064
+ sliding_window_mask: Optional[torch.Tensor] = None,
1065
+ position_ids: Optional[torch.Tensor] = None,
1066
+ inputs_embeds: Optional[torch.Tensor] = None,
1067
+ labels: Optional[torch.Tensor] = None,
1068
+ indices: Optional[torch.Tensor] = None,
1069
+ cu_seqlens: Optional[torch.Tensor] = None,
1070
+ max_seqlen: Optional[int] = None,
1071
+ batch_size: Optional[int] = None,
1072
+ seq_len: Optional[int] = None,
1073
+ output_attentions: Optional[bool] = None,
1074
+ output_hidden_states: Optional[bool] = None,
1075
+ return_dict: Optional[bool] = None,
1076
+ **kwargs,
1077
+ ) -> Union[tuple[torch.Tensor], SequenceClassifierOutput]:
1078
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1079
+ # self._maybe_set_compile()
1080
+
1081
+ if FLASH_ATTN_AVAILABLE:
1082
+ if indices is None and cu_seqlens is None and max_seqlen is None:
1083
+ if batch_size is None and seq_len is None:
1084
+ if inputs_embeds is not None:
1085
+ batch_size, seq_len = inputs_embeds.shape[:2]
1086
+ else:
1087
+ batch_size, seq_len = input_ids.shape[:2]
1088
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1089
+
1090
+ if attention_mask is None:
1091
+ attention_mask = torch.ones((batch_size, seq_len), device=device, dtype=torch.bool)
1092
+
1093
+ if inputs_embeds is None:
1094
+ with torch.no_grad():
1095
+ input_ids, indices, cu_seqlens, max_seqlen, position_ids, _ = _unpad_modernbert_input(
1096
+ inputs=input_ids, attention_mask=attention_mask, position_ids=position_ids, labels=None
1097
+ )
1098
+ else:
1099
+ inputs_embeds, indices, cu_seqlens, max_seqlen, position_ids, _ = _unpad_modernbert_input(
1100
+ inputs=inputs_embeds, attention_mask=attention_mask, position_ids=position_ids, labels=None
1101
+ )
1102
+
1103
+ outputs = self.albert(
1104
+ input_ids=input_ids,
1105
+ attention_mask=attention_mask,
1106
+ # sliding_window_mask=sliding_window_mask,
1107
+ position_ids=position_ids,
1108
+ inputs_embeds=inputs_embeds,
1109
+ indices=indices,
1110
+ cu_seqlens=cu_seqlens,
1111
+ max_seqlen=max_seqlen,
1112
+ batch_size=batch_size,
1113
+ seq_len=seq_len,
1114
+ output_attentions=output_attentions,
1115
+ output_hidden_states=output_hidden_states,
1116
+ return_dict=return_dict,
1117
+ )
1118
+
1119
+ last_hidden_state = outputs[0]
1120
+ last_hidden_state = _pad_modernbert_output(inputs=last_hidden_state, indices=indices, batch=batch_size, seqlen=seq_len)
1121
+
1122
+ # if self.config.classifier_pooling == "cls":
1123
+ # last_hidden_state = last_hidden_state[:, 0]
1124
+ # elif self.config.classifier_pooling == "mean":
1125
+ last_hidden_state = (last_hidden_state * attention_mask.unsqueeze(-1)).sum(dim=1) / attention_mask.sum(
1126
+ dim=1, keepdim=True
1127
+ )
1128
+
1129
+ pooled_output = self.head(last_hidden_state)
1130
+ pooled_output = self.drop(pooled_output)
1131
+ logits = self.classifier(pooled_output)
1132
+
1133
+ loss = None
1134
+ if labels is not None:
1135
+ if self.config.problem_type is None:
1136
+ if self.num_labels == 1:
1137
+ self.config.problem_type = "regression"
1138
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1139
+ self.config.problem_type = "single_label_classification"
1140
+ else:
1141
+ self.config.problem_type = "multi_label_classification"
1142
+
1143
+ if self.config.problem_type == "regression":
1144
+ loss_fct = MSELoss()
1145
+ if self.num_labels == 1:
1146
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1147
+ else:
1148
+ loss = loss_fct(logits, labels)
1149
+ elif self.config.problem_type == "single_label_classification":
1150
+ loss_fct = CrossEntropyLoss()
1151
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1152
+ elif self.config.problem_type == "multi_label_classification":
1153
+ loss_fct = BCEWithLogitsLoss()
1154
+ loss = loss_fct(logits, labels)
1155
+
1156
+ if not return_dict:
1157
+ output = (logits,)
1158
+ return ((loss,) + output) if loss is not None else output
1159
+
1160
+ return SequenceClassifierOutput(
1161
+ loss=loss,
1162
+ logits=logits,
1163
+ hidden_states=outputs.hidden_states,
1164
+ attentions=outputs.attentions,
1165
+ )
1166
+
1167
+ class ModernALBERTForQuestionAnswering(ts.PreTrainedModel):
1168
+ config_class = ModernALBERTConfig
1169
+
1170
+ def __init__(self, config: ModernALBERTConfig):
1171
+ super().__init__(config)
1172
+ self.num_labels = config.num_labels
1173
+
1174
+ self.albert = ModernALBERTModel(config)
1175
+ self.head = ModernAlbertPredictionHead(config)
1176
+ self.drop = torch.nn.Dropout(0.0)
1177
+ self.classifier_head = nn.Linear(config.embedding_size, config.num_labels)
1178
+
1179
+ self.post_init()
1180
+
1181
+ def forward(
1182
+ self,
1183
+ input_ids: Optional[torch.Tensor],
1184
+ attention_mask: Optional[torch.Tensor] = None,
1185
+ sliding_window_mask: Optional[torch.Tensor] = None,
1186
+ position_ids: Optional[torch.Tensor] = None,
1187
+ start_positions: Optional[torch.Tensor] = None,
1188
+ end_positions: Optional[torch.Tensor] = None,
1189
+ indices: Optional[torch.Tensor] = None,
1190
+ cu_seqlens: Optional[torch.Tensor] = None,
1191
+ max_seqlen: Optional[int] = None,
1192
+ batch_size: Optional[int] = None,
1193
+ seq_len: Optional[int] = None,
1194
+ output_attentions: Optional[bool] = None,
1195
+ output_hidden_states: Optional[bool] = None,
1196
+ return_dict: Optional[bool] = None,
1197
+ **kwargs,
1198
+ ) -> Union[tuple[torch.Tensor], QuestionAnsweringModelOutput]:
1199
+
1200
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1201
+ # self._maybe_set_compile()
1202
+
1203
+ outputs = self.albert(
1204
+ input_ids,
1205
+ attention_mask=attention_mask,
1206
+ sliding_window_mask=sliding_window_mask,
1207
+ position_ids=position_ids,
1208
+ indices=indices,
1209
+ cu_seqlens=cu_seqlens,
1210
+ max_seqlen=max_seqlen,
1211
+ batch_size=batch_size,
1212
+ seq_len=seq_len,
1213
+ output_attentions=output_attentions,
1214
+ output_hidden_states=output_hidden_states,
1215
+ return_dict=return_dict,
1216
+ )
1217
+ last_hidden_state = outputs[0]
1218
+
1219
+ last_hidden_state = self.head(last_hidden_state)
1220
+ last_hidden_state = self.drop(last_hidden_state)
1221
+ logits = self.classifier_head(last_hidden_state)
1222
+
1223
+ start_logits, end_logits = logits.split(1, dim=-1)
1224
+ start_logits = start_logits.squeeze(-1).contiguous()
1225
+ end_logits = end_logits.squeeze(-1).contiguous()
1226
+
1227
+ loss = None
1228
+ if start_positions is not None and end_positions is not None:
1229
+ loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
1230
+
1231
+ if not return_dict:
1232
+ output = (start_logits, end_logits) + outputs[1:]
1233
+ return ((loss,) + output) if loss is not None else output
1234
+
1235
+ return QuestionAnsweringModelOutput(
1236
+ loss=loss,
1237
+ start_logits=start_logits,
1238
+ end_logits=end_logits,
1239
+ hidden_states=outputs.hidden_states,
1240
+ attentions=outputs.attentions,
1241
+ )
1242
+
1243
+
1244
+ # Distillation
1245
+
1246
+ @dataclass
1247
+ class DistillationOutputWithPasts(ModelOutput):
1248
+ loss: Optional[torch.FloatTensor] = None
1249
+ logits: torch.FloatTensor = None
1250
+ last_hidden_state: torch.FloatTensor = None
1251
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
1252
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
1253
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
1254
+ depth_loss: Optional[torch.FloatTensor] = None
1255
+ audio_logits: torch.FloatTensor = None
1256
+ depth_past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
1257
+ depth_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
1258
+ depth_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
1259
+
1260
+ class DistillationWrapper(ts.PreTrainedModel):
1261
+ config_class = ModernALBERTConfig
1262
+ base_model_prefix = "model"
1263
+ _no_split_modules = ["LlamaDecoderLayer", "FlowDecoderLayerGroup", "MimiTransformerLayer"]
1264
+ _keys_to_ignore_on_load_missing = ["speech_tokenizer", "teacher"]
1265
+ _tied_weights_keys = ["llm.decoder.weight"]
1266
+ _supports_flash_attn_2 = True
1267
+ _supports_sdpa = True
1268
+ _supports_cache_class = True
1269
+ _tp_plan = []
1270
+
1271
+ def __init__(self, config, student=None, teacher=None):
1272
+ super().__init__(config)
1273
+ self.llm = ModernALBERTForMaskedLM(config)
1274
+
1275
+ if teacher != None:
1276
+ self.teacher = teacher
1277
+ else:
1278
+ self.teacher = None
1279
+
1280
+ self.attention_loss = nn.KLDivLoss(reduction="mean")
1281
+ self.hidden_loss = nn.CosineEmbeddingLoss(reduction="mean")
1282
+ self.output_loss = nn.KLDivLoss(reduction="batchmean")
1283
+
1284
+ self.temperature = 1.0
1285
+
1286
+
1287
+ @property
1288
+ def device(self):
1289
+ return next(self.parameters()).device
1290
+
1291
+
1292
+
1293
+ def forward(self, input_ids=None, attention_mask=None, labels=None, **kwargs):
1294
+
1295
+ device = self.device
1296
+
1297
+
1298
+
1299
+ input_ids = input_ids.to(device)
1300
+
1301
+ attention_mask = attention_mask.to(device)
1302
+
1303
+
1304
+
1305
+ if labels != None:
1306
+
1307
+ labels = labels.to(device)
1308
+
1309
+
1310
+
1311
+ student_outputs = self.llm(
1312
+
1313
+ input_ids=input_ids,
1314
+
1315
+ attention_mask=attention_mask,
1316
+
1317
+ labels=labels,
1318
+
1319
+ output_hidden_states=True,
1320
+
1321
+ # output_attentions=True,
1322
+
1323
+ **kwargs
1324
+
1325
+ )
1326
+
1327
+
1328
+
1329
+ hidden_loss = None
1330
+
1331
+ output_loss = None
1332
+
1333
+
1334
+
1335
+ if self.teacher != None:
1336
+
1337
+ with torch.no_grad():
1338
+
1339
+ input_ids = input_ids.to(self.teacher.device)
1340
+
1341
+ attention_mask = attention_mask.to(self.teacher.device)
1342
+
1343
+
1344
+
1345
+ teacher_outputs = self.teacher(input_ids=input_ids,
1346
+
1347
+ attention_mask=attention_mask,
1348
+
1349
+ output_hidden_states=True,
1350
+
1351
+ # output_attentions=True,
1352
+
1353
+ **kwargs
1354
+
1355
+ )
1356
+
1357
+
1358
+
1359
+ s_hiddens = student_outputs.hidden_states[-1]
1360
+
1361
+ t_hiddens = teacher_outputs.hidden_states[-1].detach()
1362
+
1363
+
1364
+
1365
+ s_logits = student_outputs.logits
1366
+
1367
+ t_logits = teacher_outputs.logits.detach()
1368
+
1369
+
1370
+
1371
+ hidden_loss = self.compute_hidden_loss(s_hiddens, t_hiddens, attention_mask)
1372
+
1373
+ output_loss = self.compute_output_loss(s_logits, t_logits, labels)
1374
+
1375
+
1376
+
1377
+ if self.teacher != None:
1378
+
1379
+ total_loss = (1.0 * student_outputs.loss) + (3.0 * hidden_loss) + (5.0 * output_loss)
1380
+
1381
+ else:
1382
+
1383
+ total_loss = student_outputs.loss
1384
+
1385
+
1386
+
1387
+ return DistillationOutputWithPasts(
1388
+
1389
+ loss=total_loss,
1390
+
1391
+ logits=student_outputs.logits,
1392
+
1393
+ hidden_states=student_outputs.hidden_states,
1394
+
1395
+ attentions=student_outputs.attentions,
1396
+
1397
+ )
1398
+
1399
+
1400
+
1401
+ def compute_output_loss(self, s_logits, t_logits, labels):
1402
+
1403
+ mask = (labels > -1).unsqueeze(-1)
1404
+
1405
+ s_logits_masked = s_logits.masked_fill(~mask, 0.0)
1406
+
1407
+ t_logits_masked = t_logits.masked_fill(~mask, 0.0)
1408
+
1409
+
1410
+
1411
+ s_logits_slct = s_logits_masked.view(-1, s_logits.size(-1))
1412
+
1413
+ t_logits_slct = t_logits_masked.view(-1, t_logits.size(-1))
1414
+
1415
+
1416
+
1417
+ valid_rows = mask.view(-1)
1418
+
1419
+ s_logits_slct = s_logits_slct[valid_rows]
1420
+
1421
+ t_logits_slct = t_logits_slct[valid_rows]
1422
+
1423
+
1424
+
1425
+ output_loss = (
1426
+
1427
+ self.output_loss(
1428
+
1429
+ nn.functional.log_softmax(s_logits_slct / self.temperature, dim=-1),
1430
+
1431
+ nn.functional.softmax(t_logits_slct / self.temperature, dim=-1),
1432
+
1433
+ )
1434
+
1435
+ * (self.temperature) ** 2
1436
+
1437
+ )
1438
+
1439
+
1440
+
1441
+ return output_loss
1442
+
1443
+
1444
+
1445
+ def compute_hidden_loss(self, s_hiddens, t_hiddens, attention_mask, lambdas=None):
1446
+
1447
+ s_hidden_states = s_hiddens
1448
+
1449
+ t_hidden_states = t_hiddens
1450
+
1451
+
1452
+
1453
+ assert s_hidden_states.size() == t_hidden_states.size()
1454
+
1455
+
1456
+
1457
+ dim = s_hidden_states.size(-1)
1458
+
1459
+ s_hidden_states_slct = s_hidden_states
1460
+
1461
+ t_hidden_states_slct = t_hidden_states
1462
+
1463
+
1464
+
1465
+ target = s_hidden_states_slct.new(s_hidden_states_slct.size(0)).fill_(1) # (bs * seq_length,)
1466
+
1467
+
1468
+
1469
+ hidden_loss = self.hidden_loss(s_hidden_states_slct, t_hidden_states_slct, target)
1470
+
1471
+
1472
+
1473
+ return hidden_loss
1474
+
1475
+
1476
+ class DistillationWrapperForSequenceClassification(ts.PreTrainedModel):
1477
+ config_class = ModernALBERTConfig
1478
+ base_model_prefix = "model"
1479
+ _no_split_modules = ["LlamaDecoderLayer", "FlowDecoderLayerGroup", "MimiTransformerLayer"]
1480
+ _keys_to_ignore_on_load_missing = ["speech_tokenizer", "teacher"]
1481
+ _supports_flash_attn_2 = True
1482
+ _supports_sdpa = True
1483
+ _supports_cache_class = True
1484
+
1485
+ def __init__(self, config):
1486
+ super().__init__(config)
1487
+ self.num_labels = config.num_labels
1488
+ self.llm = ModernALBERTForSequenceClassification(config)
1489
+
1490
+ self.teacher = None
1491
+
1492
+ self.attention_loss = nn.KLDivLoss(reduction="mean")
1493
+ self.hidden_loss = nn.CosineEmbeddingLoss(reduction="mean")
1494
+ self.output_loss = nn.KLDivLoss(reduction="batchmean")
1495
+
1496
+ self.temperature = 1.0
1497
+
1498
+ @property
1499
+ def device(self):
1500
+ return next(self.parameters()).device
1501
+
1502
+ def forward(self, input_ids=None, attention_mask=None, labels=None, **kwargs):
1503
+ device = self.device
1504
+
1505
+ input_ids = input_ids.to(device)
1506
+ attention_mask = attention_mask.to(device)
1507
+
1508
+ if labels != None:
1509
+ labels = labels.to(device)
1510
+
1511
+ student_outputs = self.llm(
1512
+ input_ids=input_ids,
1513
+ attention_mask=attention_mask,
1514
+ labels=labels,
1515
+ output_hidden_states=True,
1516
+ # output_attentions=True,
1517
+ # **kwargs
1518
+ )
1519
+
1520
+ hidden_loss = None
1521
+ output_loss = None
1522
+
1523
+ if self.teacher != None:
1524
+ with torch.no_grad():
1525
+ input_ids = input_ids.to(self.teacher.device)
1526
+ attention_mask = attention_mask.to(self.teacher.device)
1527
+
1528
+ teacher_outputs = self.teacher(input_ids=input_ids,
1529
+ attention_mask=attention_mask,
1530
+ output_hidden_states=True,
1531
+ # output_attentions=True,
1532
+ # **kwargs)
1533
+ )
1534
+
1535
+ s_hiddens = student_outputs.hidden_states[-1]
1536
+ t_hiddens = teacher_outputs.hidden_states[-1].detach()
1537
+
1538
+ # print(s_hiddens.shape)
1539
+ # print(t_hiddens.shape)
1540
+
1541
+ s_logits = student_outputs.logits
1542
+ t_logits = teacher_outputs.logits.detach()
1543
+
1544
+ hidden_loss = self.compute_hidden_loss(s_hiddens, t_hiddens, attention_mask)
1545
+ output_loss = self.compute_output_loss(s_logits, t_logits, labels)
1546
+
1547
+ if self.teacher != None:
1548
+ total_loss = (1.0 * student_outputs.loss) + (3.0 * hidden_loss) + (5.0 * output_loss)
1549
+ else:
1550
+ total_loss = student_outputs.loss
1551
+
1552
+ return DistillationOutputWithPasts(
1553
+ loss=total_loss,
1554
+ logits=student_outputs.logits,
1555
+ hidden_states=student_outputs.hidden_states,
1556
+ attentions=student_outputs.attentions,
1557
+ )
1558
+
1559
+ def compute_output_loss(self, s_logits, t_logits, labels):
1560
+ mask = (labels > -1).unsqueeze(-1).expand_as(s_logits).bool()
1561
+
1562
+ s_logits_slct = torch.masked_select(s_logits, mask)
1563
+ s_logits_slct = s_logits_slct.view(-1, s_logits.size(-1))
1564
+ t_logits_slct = torch.masked_select(t_logits, mask)
1565
+ t_logits_slct = t_logits_slct.view(-1, s_logits.size(-1))
1566
+ assert t_logits_slct.size() == s_logits_slct.size()
1567
+
1568
+ output_loss = (
1569
+ self.output_loss(
1570
+ nn.functional.log_softmax(s_logits_slct / self.temperature, dim=-1),
1571
+ nn.functional.softmax(t_logits_slct / self.temperature, dim=-1),
1572
+ )
1573
+ * (self.temperature) ** 2
1574
+ )
1575
+
1576
+ return output_loss
1577
+
1578
+ def compute_hidden_loss(self, s_hiddens, t_hiddens, attention_mask, lambdas=None):
1579
+ s_hidden_states = s_hiddens
1580
+ t_hidden_states = t_hiddens
1581
+
1582
+ # mask = attention_mask.unsqueeze(-1).expand_as(s_hidden_states).bool() # (bs, seq_length, dim)
1583
+
1584
+ assert s_hidden_states.size() == t_hidden_states.size()
1585
+
1586
+ dim = s_hidden_states.size(-1)
1587
+
1588
+ # s_hidden_states_slct = torch.masked_select(s_hidden_states, mask) # (bs * seq_length * dim)
1589
+ # s_hidden_states_slct = s_hidden_states_slct.view(-1, dim) # (bs * seq_length, dim)
1590
+ # t_hidden_states_slct = torch.masked_select(t_hidden_states, mask) # (bs * seq_length * dim)
1591
+ # t_hidden_states_slct = t_hidden_states_slct.view(-1, dim) # (bs * seq_length, dim)
1592
+
1593
+ s_hidden_states_slct = s_hidden_states
1594
+ t_hidden_states_slct = t_hidden_states
1595
+
1596
+ target = s_hidden_states_slct.new(s_hidden_states_slct.size(0)).fill_(1) # (bs * seq_length,)
1597
+
1598
+ hidden_loss = self.hidden_loss(s_hidden_states_slct, t_hidden_states_slct, target)
1599
+
1600
+ return hidden_loss
1601
+
1602
+ class DistillationWrapperForQuestionAnswering(ts.PreTrainedModel):
1603
+ config_class = ModernALBERTConfig
1604
+ base_model_prefix = "model"
1605
+ _no_split_modules = ["LlamaDecoderLayer", "FlowDecoderLayerGroup", "MimiTransformerLayer"]
1606
+ _keys_to_ignore_on_load_missing = ["speech_tokenizer", "teacher"]
1607
+ _supports_flash_attn_2 = True
1608
+ _supports_sdpa = True
1609
+ _supports_cache_class = True
1610
+
1611
+ def __init__(self, config):
1612
+ super().__init__(config)
1613
+ self.num_labels = config.num_labels
1614
+ self.llm = ModernALBERTForQuestionAnswering(config)
1615
+
1616
+ self.teacher = None
1617
+
1618
+ self.attention_loss = nn.KLDivLoss(reduction="mean")
1619
+ self.hidden_loss = nn.CosineEmbeddingLoss(reduction="mean")
1620
+ self.output_loss = nn.KLDivLoss(reduction="batchmean")
1621
+
1622
+ self.temperature = 1.0
1623
+
1624
+ @property
1625
+ def device(self):
1626
+ return next(self.parameters()).device
1627
+
1628
+ def forward(self, input_ids=None, attention_mask=None, labels=None, **kwargs):
1629
+ device = self.device
1630
+
1631
+ input_ids = input_ids.to(device)
1632
+ attention_mask = attention_mask.to(device)
1633
+
1634
+ if labels != None:
1635
+ labels = labels.to(device)
1636
+
1637
+ student_outputs = self.llm(
1638
+ input_ids=input_ids,
1639
+ attention_mask=attention_mask,
1640
+ labels=labels,
1641
+ output_hidden_states=True,
1642
+ # output_attentions=True,
1643
+ # **kwargs
1644
+ )
1645
+
1646
+ hidden_loss = None
1647
+ output_loss = None
1648
+
1649
+ if self.teacher != None:
1650
+ with torch.no_grad():
1651
+ input_ids = input_ids.to(self.teacher.device)
1652
+ attention_mask = attention_mask.to(self.teacher.device)
1653
+
1654
+ teacher_outputs = self.teacher(input_ids=input_ids,
1655
+ attention_mask=attention_mask,
1656
+ output_hidden_states=True,
1657
+ # output_attentions=True,
1658
+ # **kwargs)
1659
+ )
1660
+
1661
+ s_hiddens = student_outputs.hidden_states[-1]
1662
+ t_hiddens = teacher_outputs.hidden_states[-1].detach()
1663
+
1664
+ # print(s_hiddens.shape)
1665
+ # print(t_hiddens.shape)
1666
+
1667
+ s_logits = student_outputs.logits
1668
+ t_logits = teacher_outputs.logits.detach()
1669
+
1670
+ hidden_loss = self.compute_hidden_loss(s_hiddens, t_hiddens, attention_mask)
1671
+ output_loss = self.compute_output_loss(s_logits, t_logits, labels)
1672
+
1673
+ if self.teacher != None:
1674
+ total_loss = (1.0 * student_outputs.loss) + (3.0 * hidden_loss) + (5.0 * output_loss)
1675
+ else:
1676
+ total_loss = student_outputs.loss
1677
+
1678
+ # return DistillationOutputWithPasts(
1679
+ # loss=total_loss,
1680
+ # logits=student_outputs.logits,
1681
+ # hidden_states=student_outputs.hidden_states,
1682
+ # attentions=student_outputs.attentions,
1683
+ # )
1684
+
1685
+ return student_outputs
1686
+
1687
+ def compute_output_loss(self, s_logits, t_logits, labels):
1688
+ mask = (labels > -1).unsqueeze(-1).expand_as(s_logits).bool()
1689
+
1690
+ s_logits_slct = torch.masked_select(s_logits, mask)
1691
+ s_logits_slct = s_logits_slct.view(-1, s_logits.size(-1))
1692
+ t_logits_slct = torch.masked_select(t_logits, mask)
1693
+ t_logits_slct = t_logits_slct.view(-1, s_logits.size(-1))
1694
+ assert t_logits_slct.size() == s_logits_slct.size()
1695
+
1696
+ output_loss = (
1697
+ self.output_loss(
1698
+ nn.functional.log_softmax(s_logits_slct / self.temperature, dim=-1),
1699
+ nn.functional.softmax(t_logits_slct / self.temperature, dim=-1),
1700
+ )
1701
+ * (self.temperature) ** 2
1702
+ )
1703
+
1704
+ return output_loss
1705
+
1706
+ def compute_hidden_loss(self, s_hiddens, t_hiddens, attention_mask, lambdas=None):
1707
+ s_hidden_states = s_hiddens
1708
+ t_hidden_states = t_hiddens
1709
+
1710
+ # mask = attention_mask.unsqueeze(-1).expand_as(s_hidden_states).bool() # (bs, seq_length, dim)
1711
+
1712
+ assert s_hidden_states.size() == t_hidden_states.size()
1713
+
1714
+ dim = s_hidden_states.size(-1)
1715
+
1716
+ # s_hidden_states_slct = torch.masked_select(s_hidden_states, mask) # (bs * seq_length * dim)
1717
+ # s_hidden_states_slct = s_hidden_states_slct.view(-1, dim) # (bs * seq_length, dim)
1718
+ # t_hidden_states_slct = torch.masked_select(t_hidden_states, mask) # (bs * seq_length * dim)
1719
+ # t_hidden_states_slct = t_hidden_states_slct.view(-1, dim) # (bs * seq_length, dim)
1720
+
1721
+ s_hidden_states_slct = s_hidden_states
1722
+ t_hidden_states_slct = t_hidden_states
1723
+
1724
+ target = s_hidden_states_slct.new(s_hidden_states_slct.size(0)).fill_(1) # (bs * seq_length,)
1725
+
1726
+ hidden_loss = self.hidden_loss(s_hidden_states_slct, t_hidden_states_slct, target)
1727
+
1728
+ return hidden_loss