iMiW commited on
Commit
4da8ea9
·
verified ·
1 Parent(s): aed4032

Upload model

Browse files
Files changed (5) hide show
  1. README.md +199 -0
  2. config.json +233 -0
  3. configuration_gigarembed.py +306 -0
  4. model.safetensors +3 -0
  5. modeling_gigarembed.py +1015 -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,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_non_freeze_layers_idxs": null,
3
+ "activation_checkpoint_layers_num": null,
4
+ "add_eos": true,
5
+ "add_pad_token": true,
6
+ "apply_torch_compile_to_projections": true,
7
+ "architectures": [
8
+ "GigarEmbedModel"
9
+ ],
10
+ "auto_map": {
11
+ "AutoConfig": "configuration_gigarembed.GigarEmbedConfig",
12
+ "AutoModel": "modeling_gigarembed.GigarEmbedModel"
13
+ },
14
+ "dtype": "float16",
15
+ "hidden_size": 2048,
16
+ "is_mask_instruction": true,
17
+ "latent_attention_config": {
18
+ "_attn_implementation_autoset": false,
19
+ "_name_or_path": "",
20
+ "add_cross_attention": false,
21
+ "architectures": null,
22
+ "bad_words_ids": null,
23
+ "begin_suppress_tokens": null,
24
+ "bos_token_id": null,
25
+ "chunk_size_feed_forward": 0,
26
+ "cross_attention_hidden_size": null,
27
+ "cross_dim_head": 2048,
28
+ "decoder_start_token_id": null,
29
+ "diversity_penalty": 0.0,
30
+ "do_sample": false,
31
+ "dtype": null,
32
+ "early_stopping": false,
33
+ "encoder_no_repeat_ngram_size": 0,
34
+ "eos_token_id": null,
35
+ "exponential_decay_length_penalty": null,
36
+ "finetuning_task": null,
37
+ "forced_bos_token_id": null,
38
+ "forced_eos_token_id": null,
39
+ "hidden_dim": 2048,
40
+ "id2label": {
41
+ "0": "LABEL_0",
42
+ "1": "LABEL_1"
43
+ },
44
+ "is_decoder": false,
45
+ "is_encoder_decoder": false,
46
+ "label2id": {
47
+ "LABEL_0": 0,
48
+ "LABEL_1": 1
49
+ },
50
+ "latent_dim": 2048,
51
+ "length_penalty": 1.0,
52
+ "max_length": 20,
53
+ "min_length": 0,
54
+ "model_type": "latent_attention",
55
+ "mult": 4,
56
+ "no_repeat_ngram_size": 0,
57
+ "num_beam_groups": 1,
58
+ "num_beams": 1,
59
+ "num_cross_heads": 8,
60
+ "num_latents_value": 512,
61
+ "num_return_sequences": 1,
62
+ "output_attentions": false,
63
+ "output_hidden_states": false,
64
+ "output_scores": false,
65
+ "pad_token_id": null,
66
+ "prefix": null,
67
+ "problem_type": null,
68
+ "pruned_heads": {},
69
+ "remove_invalid_values": false,
70
+ "repetition_penalty": 1.0,
71
+ "return_dict": true,
72
+ "return_dict_in_generate": false,
73
+ "sep_token_id": null,
74
+ "suppress_tokens": null,
75
+ "task_specific_params": null,
76
+ "temperature": 1.0,
77
+ "tf_legacy_loss": false,
78
+ "tie_encoder_decoder": false,
79
+ "tie_word_embeddings": true,
80
+ "tokenizer_class": null,
81
+ "top_k": 50,
82
+ "top_p": 1.0,
83
+ "torchscript": false,
84
+ "typical_p": 1.0,
85
+ "use_bfloat16": false
86
+ },
87
+ "mask_type": "b",
88
+ "model_type": "gigarembed",
89
+ "padding_side": "right",
90
+ "quantization_config": {
91
+ "_load_in_4bit": true,
92
+ "_load_in_8bit": false,
93
+ "bnb_4bit_compute_dtype": "bfloat16",
94
+ "bnb_4bit_quant_storage": "uint8",
95
+ "bnb_4bit_quant_type": "nf4",
96
+ "bnb_4bit_use_double_quant": true,
97
+ "llm_int8_enable_fp32_cpu_offload": false,
98
+ "llm_int8_has_fp16_weight": false,
99
+ "llm_int8_skip_modules": null,
100
+ "llm_int8_threshold": 6.0,
101
+ "load_in_4bit": true,
102
+ "load_in_8bit": false,
103
+ "quant_method": "bitsandbytes"
104
+ },
105
+ "text_config": {
106
+ "_attn_implementation_autoset": false,
107
+ "_name_or_path": "ai-sage/Giga-Embeddings-instruct",
108
+ "add_cross_attention": false,
109
+ "apply_qk_norm": true,
110
+ "architectures": null,
111
+ "attention_bias": false,
112
+ "attention_dropout": 0.0,
113
+ "attention_hidden_size": null,
114
+ "attention_type": "LlamaLatentAttention",
115
+ "bad_words_ids": null,
116
+ "begin_suppress_tokens": null,
117
+ "bos_token_id": 1,
118
+ "chunk_size_feed_forward": 0,
119
+ "cross_attention_hidden_size": null,
120
+ "decoder_start_token_id": null,
121
+ "delete_logits": true,
122
+ "deterministic_attention": false,
123
+ "diversity_penalty": 0.0,
124
+ "do_sample": false,
125
+ "dtype": null,
126
+ "early_stopping": false,
127
+ "enable_async_tp": false,
128
+ "encoder_no_repeat_ngram_size": 0,
129
+ "eos_token_id": 2,
130
+ "exponential_decay_length_penalty": null,
131
+ "finetuning_task": null,
132
+ "forced_bos_token_id": null,
133
+ "forced_eos_token_id": null,
134
+ "freeze_non_embed": false,
135
+ "fused_mlp": true,
136
+ "fused_mlp_checkpoint_lvl": 3,
137
+ "head_dim": 64,
138
+ "hidden_act": "silu",
139
+ "hidden_size": 2048,
140
+ "id2label": {
141
+ "0": "LABEL_0",
142
+ "1": "LABEL_1"
143
+ },
144
+ "ignore_index": -100,
145
+ "init_device": "meta",
146
+ "initializer_range": 0.02,
147
+ "intermediate_size": 11008,
148
+ "is_decoder": false,
149
+ "is_encoder_decoder": false,
150
+ "kv_lora_rank": 1024,
151
+ "label2id": {
152
+ "LABEL_0": 0,
153
+ "LABEL_1": 1
154
+ },
155
+ "length_penalty": 1.0,
156
+ "lora_alpha": null,
157
+ "lora_r": null,
158
+ "loss_inplace_backward": false,
159
+ "max_length": 20,
160
+ "max_position_embeddings": 4096,
161
+ "max_window_layers": 36,
162
+ "min_length": 0,
163
+ "mla_config": {
164
+ "kv_lora_rank": 1024,
165
+ "q_lora_rank": 0,
166
+ "qk_nope_head_dim": 64,
167
+ "qk_rope_head_dim": 64,
168
+ "v_head_dim": 128
169
+ },
170
+ "mlp_bias": false,
171
+ "model_type": "gigar",
172
+ "mtp_loss_weight": 0.1,
173
+ "mtp_predictor_num": 1,
174
+ "no_repeat_ngram_size": 0,
175
+ "norm_type": "LlamaRMSNorm",
176
+ "num_attention_heads": 16,
177
+ "num_beam_groups": 1,
178
+ "num_beams": 1,
179
+ "num_hidden_layers": 36,
180
+ "num_key_value_heads": 16,
181
+ "num_return_sequences": 1,
182
+ "output_attentions": false,
183
+ "output_hidden_states": false,
184
+ "output_scores": false,
185
+ "pad_token_id": 2,
186
+ "parallel_embedding_type": "EmbeddingParallelEmbedding",
187
+ "prefix": null,
188
+ "pretraining_tp": 1,
189
+ "problem_type": null,
190
+ "pruned_heads": {},
191
+ "q_lora_rank": 0,
192
+ "qk_nope_head_dim": 64,
193
+ "qk_rope_head_dim": 64,
194
+ "remove_invalid_values": false,
195
+ "repetition_penalty": 1.0,
196
+ "return_dict": true,
197
+ "return_dict_in_generate": false,
198
+ "rms_norm_eps": 1e-06,
199
+ "rope_scaling": null,
200
+ "rope_theta": 100000.0,
201
+ "sep_token_id": null,
202
+ "skip_init_tp_modules": true,
203
+ "sliding_window": null,
204
+ "sp_split_type": "equal",
205
+ "suppress_tokens": null,
206
+ "task_specific_params": null,
207
+ "temperature": 1.0,
208
+ "tf_legacy_loss": false,
209
+ "tie_encoder_decoder": false,
210
+ "tie_word_embeddings": false,
211
+ "tokenizer_class": null,
212
+ "top_k": 50,
213
+ "top_p": 1.0,
214
+ "torchscript": false,
215
+ "tp_group": null,
216
+ "tp_size": 1,
217
+ "typical_p": 1.0,
218
+ "unk_token_id": 0,
219
+ "use_bfloat16": false,
220
+ "use_cache": false,
221
+ "use_cache_force": false,
222
+ "use_custom_rotary_kernel": false,
223
+ "use_liger": false,
224
+ "use_mrope": false,
225
+ "use_mtp": true,
226
+ "use_sliding_window": false,
227
+ "v_head_dim": 128,
228
+ "varlen_input": true,
229
+ "vocab_size": 128256,
230
+ "z_loss_eps": 5e-05
231
+ },
232
+ "transformers_version": "4.57.0"
233
+ }
configuration_gigarembed.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+
3
+ from typing import Literal
4
+ from transformers import AutoConfig
5
+ from transformers.models.auto import CONFIG_MAPPING
6
+ from transformers.configuration_utils import PretrainedConfig
7
+ from transformers.modeling_rope_utils import rope_config_validation
8
+
9
+ GIGAREMBED_TYPE = "gigarembed"
10
+ LATENT_ATTENTION_TYPE = "latent_attention"
11
+
12
+
13
+ class GigarConfig(PretrainedConfig):
14
+ r"""
15
+ This is the configuration class to store the configuration of a [`GigarModel`]. It is used to instantiate an Gigar
16
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
17
+ defaults will yield a similar configuration to that of the Gigar-7B.
18
+
19
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
20
+ documentation from [`PretrainedConfig`] for more information.
21
+
22
+
23
+ Args:
24
+ vocab_size (`int`, *optional*, defaults to 32000):
25
+ Vocabulary size of the Gigar model. Defines the number of different tokens that can be represented by the
26
+ `inputs_ids` passed when calling [`GigarModel`]
27
+ hidden_size (`int`, *optional*, defaults to 4096):
28
+ Dimension of the hidden representations.
29
+ intermediate_size (`int`, *optional*, defaults to 11008):
30
+ Dimension of the MLP representations.
31
+ num_hidden_layers (`int`, *optional*, defaults to 32):
32
+ Number of hidden layers in the Transformer decoder.
33
+ num_attention_heads (`int`, *optional*, defaults to 32):
34
+ Number of attention heads for each attention layer in the Transformer decoder.
35
+ num_key_value_heads (`int`, *optional*):
36
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
37
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
38
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
39
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
40
+ by meanpooling all the original heads within that group. For more details checkout [this
41
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
42
+ `num_attention_heads`.
43
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
44
+ The non-linear activation function (function or string) in the decoder.
45
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
46
+ The maximum sequence length that this model might ever be used with. Gigar 1 supports up to 2048 tokens,
47
+ Gigar 2 up to 4096, CodeLlama up to 16384.
48
+ initializer_range (`float`, *optional*, defaults to 0.02):
49
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
50
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
51
+ The epsilon used by the rms normalization layers.
52
+ use_cache (`bool`, *optional*, defaults to `True`):
53
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
54
+ relevant if `config.is_decoder=True`.
55
+ pad_token_id (`int`, *optional*):
56
+ Padding token id.
57
+ bos_token_id (`int`, *optional*, defaults to 1):
58
+ Beginning of stream token id.
59
+ eos_token_id (`int`, *optional*, defaults to 2):
60
+ End of stream token id.
61
+ pretraining_tp (`int`, *optional*, defaults to 1):
62
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
63
+ document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to
64
+ understand more about it. This value is necessary to ensure exact reproducibility of the pretraining
65
+ results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232).
66
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
67
+ Whether to tie weight embeddings
68
+ rope_theta (`float`, *optional*, defaults to 10000.0):
69
+ The base period of the RoPE embeddings.
70
+ rope_scaling (`Dict`, *optional*):
71
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
72
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
73
+ accordingly.
74
+ Expected contents:
75
+ `rope_type` (`str`):
76
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
77
+ 'gigar3'], with 'default' being the original RoPE implementation.
78
+ `factor` (`float`, *optional*):
79
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
80
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
81
+ original maximum pre-trained length.
82
+ `original_max_position_embeddings` (`int`, *optional*):
83
+ Used with 'dynamic', 'longrope' and 'gigar3'. The original max position embeddings used during
84
+ pretraining.
85
+ `attention_factor` (`float`, *optional*):
86
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
87
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
88
+ `factor` field to infer the suggested value.
89
+ `beta_fast` (`float`, *optional*):
90
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
91
+ ramp function. If unspecified, it defaults to 32.
92
+ `beta_slow` (`float`, *optional*):
93
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
94
+ ramp function. If unspecified, it defaults to 1.
95
+ `short_factor` (`List[float]`, *optional*):
96
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
97
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
98
+ size divided by the number of attention heads divided by 2
99
+ `long_factor` (`List[float]`, *optional*):
100
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
101
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
102
+ size divided by the number of attention heads divided by 2
103
+ `low_freq_factor` (`float`, *optional*):
104
+ Only used with 'gigar3'. Scaling factor applied to low frequency components of the RoPE
105
+ `high_freq_factor` (`float`, *optional*):
106
+ Only used with 'gigar3'. Scaling factor applied to high frequency components of the RoPE
107
+ attention_bias (`bool`, *optional*, defaults to `False`):
108
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
109
+ attention_dropout (`float`, *optional*, defaults to 0.0):
110
+ The dropout ratio for the attention probabilities.
111
+ mlp_bias (`bool`, *optional*, defaults to `False`):
112
+ Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
113
+ head_dim (`int`, *optional*):
114
+ The attention head dimension. If None, it will default to hidden_size // num_attention_heads
115
+
116
+ ```python
117
+ >>> from transformers import GigarModel, GigarConfig
118
+
119
+ >>> # Initializing a Gigar gigar-7b style configuration
120
+ >>> configuration = GigarConfig()
121
+
122
+ >>> # Initializing a model from the gigar-7b style configuration
123
+ >>> model = GigarModel(configuration)
124
+
125
+ >>> # Accessing the model configuration
126
+ >>> configuration = model.config
127
+ ```"""
128
+
129
+ model_type = "gigar"
130
+ keys_to_ignore_at_inference = ["past_key_values"]
131
+ # Default tensor parallel plan for base model `GigarModel`
132
+ base_model_tp_plan = {
133
+ "layers.*.self_attn.q_proj": "colwise",
134
+ "layers.*.self_attn.k_proj": "colwise",
135
+ "layers.*.self_attn.v_proj": "colwise",
136
+ "layers.*.self_attn.o_proj": "rowwise",
137
+ "layers.*.mlp.gate_proj": "colwise",
138
+ "layers.*.mlp.up_proj": "colwise",
139
+ "layers.*.mlp.down_proj": "rowwise",
140
+ }
141
+
142
+ def __init__(
143
+ self,
144
+ vocab_size=32000,
145
+ hidden_size=4096,
146
+ intermediate_size=11008,
147
+ num_hidden_layers=32,
148
+ num_attention_heads=32,
149
+ num_key_value_heads=None,
150
+ hidden_act="silu",
151
+ max_position_embeddings=2048,
152
+ initializer_range=0.02,
153
+ rms_norm_eps=1e-6,
154
+ use_cache=True,
155
+ pad_token_id=None,
156
+ bos_token_id=1,
157
+ eos_token_id=2,
158
+ pretraining_tp=1,
159
+ tie_word_embeddings=False,
160
+ rope_theta=10000.0,
161
+ rope_scaling=None,
162
+ attention_bias=False,
163
+ attention_dropout=0.0,
164
+ mlp_bias=False,
165
+ head_dim=None,
166
+ apply_qk_norm=False,
167
+ mla_config=None,
168
+ **kwargs,
169
+ ):
170
+ super().__init__(
171
+ pad_token_id=pad_token_id,
172
+ bos_token_id=bos_token_id,
173
+ eos_token_id=eos_token_id,
174
+ tie_word_embeddings=tie_word_embeddings,
175
+ **kwargs,
176
+ )
177
+
178
+ self.vocab_size = vocab_size
179
+ self.max_position_embeddings = max_position_embeddings
180
+ self.hidden_size = hidden_size
181
+ self.intermediate_size = intermediate_size
182
+ self.num_hidden_layers = num_hidden_layers
183
+ self.num_attention_heads = num_attention_heads
184
+
185
+ # for backward compatibility
186
+ if num_key_value_heads is None:
187
+ num_key_value_heads = num_attention_heads
188
+
189
+ self.num_key_value_heads = num_key_value_heads
190
+ self.hidden_act = hidden_act
191
+ self.initializer_range = initializer_range
192
+ self.rms_norm_eps = rms_norm_eps
193
+ self.pretraining_tp = pretraining_tp
194
+ self.use_cache = use_cache
195
+ self.rope_theta = rope_theta
196
+ self.rope_scaling = rope_scaling
197
+ self.attention_bias = attention_bias
198
+ self.attention_dropout = attention_dropout
199
+ self.mlp_bias = mlp_bias
200
+ self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
201
+ # Validate the correctness of rotary position embeddings parameters
202
+ # BC: if there is a 'type' field, copy it it to 'rope_type'.
203
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
204
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
205
+ rope_config_validation(self)
206
+
207
+ self.apply_qk_norm = apply_qk_norm
208
+ self.mla_config = mla_config
209
+
210
+ self._validate_mla_config()
211
+
212
+ def _validate_mla_config(self):
213
+ if self.mla_config is None:
214
+ warnings.warn("MLA config is None!")
215
+ return
216
+
217
+ EXPECTED_KEYS = [
218
+ "qk_nope_head_dim",
219
+ "qk_rope_head_dim",
220
+ "v_head_dim",
221
+ "kv_lora_rank",
222
+ "q_lora_rank",
223
+ ]
224
+ if not all((key in self.mla_config for key in EXPECTED_KEYS)):
225
+ raise ValueError(
226
+ f"MLA config is expected to have the following keys {EXPECTED_KEYS} but got {self.mla_config.keys()}."
227
+ )
228
+
229
+ if self.mla_config["qk_nope_head_dim"] + self.mla_config["qk_rope_head_dim"] != self.mla_config["v_head_dim"]:
230
+ err_msg = (
231
+ f"QK and V head dims do not match! Got {self.mla_config['qk_nope_head_dim']} + {self.mla_config['qk_rope_head_dim']} "
232
+ f"= {self.mla_config['qk_rope_head_dim'] + self.mla_config['qk_nope_head_dim']} and {self.mla_config['v_head_dim']}."
233
+ )
234
+ raise ValueError(err_msg)
235
+
236
+
237
+ class GigarEmbedConfig(PretrainedConfig):
238
+ model_type = "gigarembed"
239
+ is_composition = False
240
+
241
+ def __init__(
242
+ self,
243
+ latent_attention_config=None,
244
+ text_config=None,
245
+ padding_side: Literal["right", "left"]="right",
246
+ add_pad_token: bool=True,
247
+ is_mask_instruction: bool = True,
248
+ add_eos: bool=True,
249
+ mask_type: str="b",
250
+ **kwargs,
251
+ ):
252
+ if isinstance(latent_attention_config, dict):
253
+ latent_attention_config["model_type"] = (
254
+ latent_attention_config["model_type"] if "model_type" in latent_attention_config else LATENT_ATTENTION_TYPE
255
+ )
256
+ latent_attention_config = CONFIG_MAPPING[latent_attention_config["model_type"]](**latent_attention_config)
257
+
258
+ self.latent_attention_config = latent_attention_config
259
+
260
+ if isinstance(text_config, dict):
261
+ text_config = GigarConfig(**text_config)
262
+ elif text_config is None:
263
+ text_config = None
264
+
265
+ self.text_config = text_config
266
+ self.padding_side = padding_side
267
+ self.is_mask_instruction = is_mask_instruction
268
+ self.add_pad_token = add_pad_token
269
+ self.add_eos = add_eos
270
+ self.mask_type = mask_type
271
+ if "hidden_size" in kwargs:
272
+ self.hidden_size = kwargs["hidden_size"]
273
+
274
+ super().__init__(**kwargs)
275
+
276
+
277
+ class LatentAttentionConfig(PretrainedConfig):
278
+ model_type = LATENT_ATTENTION_TYPE
279
+ is_composition = False
280
+ _name_or_path = "latent_attention"
281
+
282
+ def __init__(
283
+ self,
284
+ num_latents_value: int,
285
+ num_cross_heads: int,
286
+ hidden_dim: int,
287
+ latent_dim: int,
288
+ cross_dim_head: int,
289
+ mult: int,
290
+ **kwargs,
291
+ ):
292
+ self.num_latents_value = num_latents_value
293
+ self.num_cross_heads = num_cross_heads
294
+ self.hidden_dim = hidden_dim
295
+ self.latent_dim = latent_dim
296
+ self.cross_dim_head = cross_dim_head
297
+ self.mult = mult
298
+
299
+ super().__init__(**kwargs)
300
+
301
+
302
+ AutoConfig.register(GIGAREMBED_TYPE, GigarEmbedConfig)
303
+ AutoConfig.register(LATENT_ATTENTION_TYPE, LatentAttentionConfig)
304
+
305
+ GigarEmbedConfig.register_for_auto_class()
306
+ LatentAttentionConfig.register_for_auto_class()
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4fde33de39f7749887f5487b85af2672683bf875d68b40c46039b1ac435691e2
3
+ size 2172114460
modeling_gigarembed.py ADDED
@@ -0,0 +1,1015 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import logging
3
+ from typing import Callable, List, Optional, Tuple, Union, Mapping
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ import numpy as np
8
+ import torch.nn.functional as F
9
+
10
+ from einops import rearrange, repeat
11
+ from transformers import AutoModel, AutoTokenizer
12
+
13
+ from transformers.cache_utils import Cache
14
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS
15
+
16
+ from transformers.activations import ACT2FN
17
+ from transformers.cache_utils import DynamicCache, StaticCache
18
+ from transformers.generation import GenerationMixin
19
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
20
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
21
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
22
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
23
+ from transformers.modeling_utils import PreTrainedModel
24
+ from transformers.processing_utils import Unpack
25
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings
26
+
27
+ from .configuration_gigarembed import GigarConfig, GigarEmbedConfig, LatentAttentionConfig
28
+
29
+
30
+ logger = logging.getLogger(__name__)
31
+ _CONFIG_FOR_DOC = "GigarEmbedConfig"
32
+
33
+
34
+ class GigarMLP(nn.Module):
35
+ def __init__(self, config):
36
+ super().__init__()
37
+ self.config = config
38
+ self.hidden_size = config.hidden_size
39
+ self.intermediate_size = config.intermediate_size
40
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
41
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
42
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
43
+ self.act_fn = ACT2FN[config.hidden_act]
44
+
45
+ def forward(self, x):
46
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
47
+ return down_proj
48
+
49
+
50
+ class GigarRMSNorm(nn.Module):
51
+ def __init__(self, hidden_size, eps=1e-6):
52
+ """
53
+ GigarRMSNorm is equivalent to T5LayerNorm
54
+ """
55
+ super().__init__()
56
+ self.weight = nn.Parameter(torch.ones(hidden_size))
57
+ self.variance_epsilon = eps
58
+
59
+ def forward(self, hidden_states):
60
+ input_dtype = hidden_states.dtype
61
+ hidden_states = hidden_states.to(torch.float32)
62
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
63
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
64
+ return self.weight * hidden_states.to(input_dtype)
65
+
66
+ def extra_repr(self):
67
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
68
+
69
+
70
+ def rotate_half(x):
71
+ """Rotates half the hidden dims of the input."""
72
+ x1 = x[..., : x.shape[-1] // 2]
73
+ x2 = x[..., x.shape[-1] // 2 :]
74
+ return torch.cat((-x2, x1), dim=-1)
75
+
76
+
77
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
78
+ """Applies Rotary Position Embedding to the query and key tensors.
79
+
80
+ Args:
81
+ q (`torch.Tensor`): The query tensor.
82
+ k (`torch.Tensor`): The key tensor.
83
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
84
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
85
+ position_ids (`torch.Tensor`, *optional*):
86
+ Deprecated and unused.
87
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
88
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
89
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
90
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
91
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
92
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
93
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
94
+ Returns:
95
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
96
+ """
97
+ cos = cos.unsqueeze(unsqueeze_dim)
98
+ sin = sin.unsqueeze(unsqueeze_dim)
99
+ q_embed = (q * cos) + (rotate_half(q) * sin)
100
+ k_embed = (k * cos) + (rotate_half(k) * sin)
101
+ return q_embed, k_embed
102
+
103
+
104
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
105
+ """
106
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
107
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
108
+ """
109
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
110
+ if n_rep == 1:
111
+ return hidden_states
112
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
113
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
114
+
115
+
116
+ def eager_attention_forward(
117
+ module: nn.Module,
118
+ query: torch.Tensor,
119
+ key: torch.Tensor,
120
+ value: torch.Tensor,
121
+ attention_mask: Optional[torch.Tensor],
122
+ scaling: float,
123
+ dropout: float = 0.0,
124
+ **kwargs,
125
+ ):
126
+ key_states = repeat_kv(key, module.num_key_value_groups)
127
+ value_states = repeat_kv(value, module.num_key_value_groups)
128
+
129
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
130
+ if attention_mask is not None:
131
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
132
+ attn_weights = attn_weights + causal_mask
133
+
134
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
135
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
136
+ attn_output = torch.matmul(attn_weights, value_states)
137
+ attn_output = attn_output.transpose(1, 2).contiguous()
138
+
139
+ return attn_output, attn_weights
140
+
141
+
142
+ class GigarLatentAttention(nn.Module):
143
+ """
144
+ Multi-headed Latent Attention (MLA)
145
+
146
+ Check out the original paper: https://arxiv.org/pdf/2405.04434,
147
+ and the reference implementation: https://github.com/deepseek-ai/DeepSeek-V3/blob/main/inference/model.py
148
+ """
149
+
150
+ def __init__(self, config: GigarConfig, layer_idx: Optional[int] = None):
151
+ super().__init__()
152
+ self.config = config
153
+ self.hidden_size = config.hidden_size
154
+ self.num_heads = config.num_attention_heads
155
+ self.layer_idx = layer_idx
156
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
157
+
158
+ assert config.num_attention_heads == config.num_key_value_heads, (
159
+ "GQA for MLA is not supported (does it even make sense?)"
160
+ )
161
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
162
+
163
+ self.max_position_embeddings = config.max_position_embeddings
164
+ self.rope_theta = config.rope_theta
165
+ self.apply_qk_norm = config.apply_qk_norm
166
+ self.attention_dropout = config.attention_dropout
167
+
168
+ assert config.mla_config is not None
169
+ self.qk_nope_head_dim = config.mla_config["qk_nope_head_dim"]
170
+ self.qk_rope_head_dim = config.mla_config["qk_rope_head_dim"]
171
+ self.v_head_dim = config.mla_config["v_head_dim"] # V has no rope part
172
+ self.kv_lora_rank = config.mla_config["kv_lora_rank"]
173
+ self.q_lora_rank = config.mla_config["q_lora_rank"]
174
+
175
+ self.qk_head_dim = self.qk_nope_head_dim + self.qk_rope_head_dim
176
+
177
+ self.scaling = self.qk_head_dim**-0.5
178
+
179
+ if self.q_lora_rank == 0:
180
+ self.q_proj = nn.Linear(
181
+ self.hidden_size,
182
+ self.num_heads * self.qk_head_dim,
183
+ bias=config.attention_bias,
184
+ )
185
+ else:
186
+ self.dq_proj = nn.Linear(
187
+ self.hidden_size,
188
+ self.q_lora_rank,
189
+ bias=config.attention_bias,
190
+ )
191
+ self.q_norm = GigarRMSNorm(self.q_lora_rank)
192
+ self.uq_proj = nn.Linear(
193
+ self.q_lora_rank,
194
+ self.num_heads * self.qk_head_dim,
195
+ bias=config.attention_bias,
196
+ )
197
+
198
+ self.kv_norm = GigarRMSNorm(self.kv_lora_rank)
199
+ self.dkv_proj = nn.Linear(
200
+ self.hidden_size,
201
+ self.kv_lora_rank,
202
+ bias=config.attention_bias,
203
+ )
204
+ self.uk_proj = nn.Linear(
205
+ config.kv_lora_rank,
206
+ self.num_heads * self.qk_nope_head_dim,
207
+ bias=config.attention_bias,
208
+ )
209
+ self.uv_proj = nn.Linear(
210
+ config.kv_lora_rank,
211
+ self.num_heads * self.v_head_dim,
212
+ bias=config.attention_bias,
213
+ )
214
+ self.kr_proj = nn.Linear(
215
+ self.hidden_size,
216
+ self.num_heads * self.qk_rope_head_dim,
217
+ bias=config.attention_bias,
218
+ )
219
+
220
+ self.o_proj = nn.Linear(
221
+ self.num_heads * self.v_head_dim,
222
+ self.hidden_size,
223
+ bias=config.attention_bias,
224
+ )
225
+
226
+ if self.apply_qk_norm:
227
+ self.qk_q_norm = nn.LayerNorm(self.num_heads * self.qk_head_dim, bias=False)
228
+ self.qk_k_norm = nn.LayerNorm(self.num_heads * self.qk_head_dim, bias=False)
229
+
230
+ config_for_rope = copy.copy(self.config)
231
+ config_for_rope.head_dim = self.config.qk_rope_head_dim
232
+
233
+ self.is_causal = False
234
+
235
+ def _compute_qkv(
236
+ self,
237
+ hidden_states: torch.Tensor,
238
+ ):
239
+ """Compute query, key, and value tensors from hidden states."""
240
+ bsz, seq_len, _ = hidden_states.size()
241
+
242
+ if self.q_lora_rank == 0:
243
+ query = self.q_proj(hidden_states)
244
+ else:
245
+ query = self.uq_proj(self.q_norm(self.dq_proj(hidden_states)))
246
+
247
+ latent = self.dkv_proj(hidden_states)
248
+ latent = self.kv_norm(latent)
249
+ k_rope = self.kr_proj(hidden_states)
250
+
251
+ k_nope = self.uk_proj(latent)
252
+ value = self.uv_proj(latent)
253
+
254
+ if self.apply_qk_norm:
255
+ query = self.qk_q_norm(query).to(query.dtype)
256
+ key = self.qk_k_norm(torch.cat([k_nope, k_rope], dim=-1)).to(k_nope.dtype)
257
+ k_nope, k_rope = torch.split(key, [k_nope.shape[-1], k_rope.shape[-1]], dim=-1)
258
+
259
+ # Reshape tensors
260
+ query = query.view(bsz, seq_len, self.num_heads, self.qk_head_dim).transpose(1, 2)
261
+ k_nope = k_nope.view(bsz, seq_len, self.num_heads, self.qk_nope_head_dim).transpose(1, 2)
262
+ k_rope = k_rope.view(bsz, seq_len, self.num_heads, self.qk_rope_head_dim).transpose(1, 2)
263
+ value = value.view(bsz, seq_len, self.num_heads, self.v_head_dim).transpose(1, 2)
264
+
265
+ q_nope, q_rope = torch.split(query, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
266
+
267
+ return q_nope, q_rope, k_nope, k_rope, value
268
+
269
+ def forward(
270
+ self,
271
+ hidden_states: torch.Tensor,
272
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
273
+ attention_mask: Optional[torch.Tensor],
274
+ past_key_value: Optional[Cache] = None,
275
+ cache_position: Optional[torch.LongTensor] = None,
276
+ **kwargs,
277
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
278
+ """
279
+ hidden_states: [bsz, seq_len, hidden_size]
280
+ attention_mask: [bsz, seq_len]
281
+ """
282
+ batch_size, seq_len, _ = hidden_states.size()
283
+
284
+ q_nope, q_rope, k_nope, k_rope, value_states = self._compute_qkv(hidden_states)
285
+
286
+ # cos, sin = self.rotary_emb(q_rope, seq_len=seq_len)
287
+ cos, sin = position_embeddings
288
+ q_rope, k_rope = apply_rotary_pos_emb(q_rope, k_rope, cos, sin)
289
+ query_states = torch.cat([q_nope, q_rope], dim=-1)
290
+ key_states = torch.cat([k_nope, k_rope], dim=-1)
291
+
292
+ if past_key_value is not None:
293
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
294
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
295
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
296
+
297
+ attention_interface: Callable = eager_attention_forward
298
+ if self.config._attn_implementation != "eager":
299
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
300
+
301
+ attn_output, attn_weights = attention_interface(
302
+ self,
303
+ query_states,
304
+ key_states,
305
+ value_states,
306
+ attention_mask,
307
+ dropout=0.0 if not self.training else self.attention_dropout,
308
+ scaling=self.scaling,
309
+ **kwargs,
310
+ )
311
+
312
+ attn_output = attn_output.reshape(batch_size, seq_len, -1).contiguous()
313
+ attn_output = self.o_proj(attn_output)
314
+
315
+ return attn_output, attn_weights
316
+
317
+
318
+ class GigarDecoderLayer(nn.Module):
319
+ def __init__(self, config: GigarConfig, layer_idx: Optional[int] = None):
320
+ super().__init__()
321
+ self.hidden_size = config.hidden_size
322
+
323
+ self.self_attn = GigarLatentAttention(config, layer_idx)
324
+ self.mlp = GigarMLP(config)
325
+ self.input_layernorm = GigarRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
326
+ self.post_attention_layernorm = GigarRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
327
+
328
+ def forward(
329
+ self,
330
+ hidden_states: torch.Tensor,
331
+ attention_mask: Optional[torch.Tensor] = None,
332
+ position_ids: Optional[torch.LongTensor] = None,
333
+ past_key_value: Optional[Cache] = None,
334
+ output_attentions: Optional[bool] = False,
335
+ use_cache: Optional[bool] = False,
336
+ cache_position: Optional[torch.LongTensor] = None,
337
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
338
+ **kwargs: Unpack[FlashAttentionKwargs],
339
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
340
+ residual = hidden_states
341
+
342
+ hidden_states = self.input_layernorm(hidden_states)
343
+
344
+ # Self Attention
345
+ hidden_states, self_attn_weights = self.self_attn(
346
+ hidden_states=hidden_states,
347
+ attention_mask=attention_mask,
348
+ position_ids=position_ids,
349
+ past_key_value=past_key_value,
350
+ output_attentions=output_attentions,
351
+ use_cache=use_cache,
352
+ cache_position=cache_position,
353
+ position_embeddings=position_embeddings,
354
+ **kwargs,
355
+ )
356
+ hidden_states = residual + hidden_states
357
+
358
+ # Fully Connected
359
+ residual = hidden_states
360
+ hidden_states = self.post_attention_layernorm(hidden_states)
361
+ hidden_states = self.mlp(hidden_states)
362
+ hidden_states = residual + hidden_states
363
+
364
+ outputs = (hidden_states,)
365
+ if output_attentions:
366
+ outputs += (self_attn_weights,)
367
+
368
+ return outputs
369
+
370
+
371
+ class GigarRotaryEmbedding(nn.Module):
372
+ def __init__(self, config: GigarConfig, device=None):
373
+ super().__init__()
374
+ # BC: "rope_type" was originally "type"
375
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
376
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
377
+ else:
378
+ self.rope_type = "default"
379
+ self.max_seq_len_cached = config.max_position_embeddings
380
+ self.original_max_seq_len = config.max_position_embeddings
381
+
382
+ self.config = config
383
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
384
+
385
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
386
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
387
+ self.original_inv_freq = self.inv_freq
388
+
389
+ def _dynamic_frequency_update(self, position_ids, device):
390
+ """
391
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
392
+ 1 - growing beyond the cached sequence length (allow scaling)
393
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
394
+ """
395
+ seq_len = torch.max(position_ids) + 1
396
+ if seq_len > self.max_seq_len_cached: # growth
397
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
398
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
399
+ self.max_seq_len_cached = seq_len
400
+
401
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
402
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
403
+ self.max_seq_len_cached = self.original_max_seq_len
404
+
405
+ @torch.no_grad()
406
+ def forward(self, x, position_ids):
407
+ if "dynamic" in self.rope_type:
408
+ self._dynamic_frequency_update(position_ids, device=x.device)
409
+
410
+ # Core RoPE block
411
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
412
+ position_ids_expanded = position_ids[:, None, :].float()
413
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
414
+ device_type = x.device.type
415
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
416
+ with torch.autocast(device_type=device_type, enabled=False):
417
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
418
+ emb = torch.cat((freqs, freqs), dim=-1)
419
+ cos = emb.cos()
420
+ sin = emb.sin()
421
+
422
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
423
+ cos = cos * self.attention_scaling
424
+ sin = sin * self.attention_scaling
425
+
426
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
427
+
428
+
429
+ GIGAR_START_DOCSTRING = r"""
430
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
431
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
432
+ etc.)
433
+
434
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
435
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
436
+ and behavior.
437
+
438
+ Parameters:
439
+ config ([`GigarConfig`]):
440
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
441
+ load the weights associated with the model, only the configuration. Check out the
442
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
443
+ """
444
+
445
+
446
+ @add_start_docstrings(
447
+ "The bare Gigar Model outputting raw hidden-states without any specific head on top.",
448
+ GIGAR_START_DOCSTRING,
449
+ )
450
+ class GigarPreTrainedModel(PreTrainedModel):
451
+ config_class = GigarConfig
452
+ base_model_prefix = "model"
453
+ supports_gradient_checkpointing = True
454
+ _no_split_modules = ["GigarDecoderLayer"]
455
+ _skip_keys_device_placement = ["past_key_values"]
456
+ _supports_flash_attn_2 = True
457
+ _supports_sdpa = True
458
+ _supports_flex_attn = True
459
+ _supports_cache_class = True
460
+ _supports_quantized_cache = True
461
+ _supports_static_cache = True
462
+
463
+ def _init_weights(self, module):
464
+ std = self.config.initializer_range
465
+ if isinstance(module, nn.Linear):
466
+ module.weight.data.normal_(mean=0.0, std=std)
467
+ if module.bias is not None:
468
+ module.bias.data.zero_()
469
+ elif isinstance(module, nn.Embedding):
470
+ module.weight.data.normal_(mean=0.0, std=std)
471
+ if module.padding_idx is not None:
472
+ module.weight.data[module.padding_idx].zero_()
473
+
474
+
475
+ GIGAR_INPUTS_DOCSTRING = r"""
476
+ Args:
477
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
478
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
479
+ it.
480
+
481
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
482
+ [`PreTrainedTokenizer.__call__`] for details.
483
+
484
+ [What are input IDs?](../glossary#input-ids)
485
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
486
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
487
+
488
+ - 1 for tokens that are **not masked**,
489
+ - 0 for tokens that are **masked**.
490
+
491
+ [What are attention masks?](../glossary#attention-mask)
492
+
493
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
494
+ [`PreTrainedTokenizer.__call__`] for details.
495
+
496
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
497
+ `past_key_values`).
498
+
499
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
500
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
501
+ information on the default strategy.
502
+
503
+ - 1 indicates the head is **not masked**,
504
+ - 0 indicates the head is **masked**.
505
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
506
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
507
+ config.n_positions - 1]`.
508
+
509
+ [What are position IDs?](../glossary#position-ids)
510
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
511
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
512
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
513
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
514
+
515
+ Two formats are allowed:
516
+ - a [`~cache_utils.Cache`] instance, see our
517
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
518
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
519
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
520
+ cache format.
521
+
522
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
523
+ legacy cache format will be returned.
524
+
525
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
526
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
527
+ of shape `(batch_size, sequence_length)`.
528
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
529
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
530
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
531
+ model's internal embedding lookup matrix.
532
+ use_cache (`bool`, *optional*):
533
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
534
+ `past_key_values`).
535
+ output_attentions (`bool`, *optional*):
536
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
537
+ tensors for more detail.
538
+ output_hidden_states (`bool`, *optional*):
539
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
540
+ more detail.
541
+ return_dict (`bool`, *optional*):
542
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
543
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
544
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
545
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
546
+ the complete sequence length.
547
+ """
548
+
549
+ @add_start_docstrings(
550
+ "The bare Gigar Model outputting raw hidden-states without any specific head on top.",
551
+ GIGAR_START_DOCSTRING,
552
+ )
553
+ class GigarModel(GigarPreTrainedModel):
554
+ """
555
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`GigarDecoderLayer`]
556
+
557
+ Args:
558
+ config: GigarConfig
559
+ """
560
+
561
+ def __init__(self, config: GigarConfig):
562
+ super().__init__(config)
563
+ self.padding_idx = config.pad_token_id
564
+ self.vocab_size = config.vocab_size
565
+
566
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
567
+ self.layers = nn.ModuleList(
568
+ [GigarDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
569
+ )
570
+ self.norm = GigarRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
571
+ self.rotary_emb = GigarRotaryEmbedding(config=config)
572
+ self.gradient_checkpointing = False
573
+
574
+ # Initialize weights and apply final processing
575
+ self.post_init()
576
+
577
+ def get_input_embeddings(self):
578
+ return self.embed_tokens
579
+
580
+ def set_input_embeddings(self, value):
581
+ self.embed_tokens = value
582
+
583
+ @add_start_docstrings_to_model_forward(GIGAR_INPUTS_DOCSTRING)
584
+ def forward(
585
+ self,
586
+ input_ids: torch.LongTensor = None,
587
+ attention_mask: Optional[torch.Tensor] = None,
588
+ position_ids: Optional[torch.LongTensor] = None,
589
+ past_key_values: Optional[Cache] = None,
590
+ inputs_embeds: Optional[torch.FloatTensor] = None,
591
+ use_cache: Optional[bool] = None,
592
+ output_attentions: Optional[bool] = None,
593
+ output_hidden_states: Optional[bool] = None,
594
+ return_dict: Optional[bool] = None,
595
+ cache_position: Optional[torch.LongTensor] = None,
596
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
597
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
598
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
599
+ output_hidden_states = (
600
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
601
+ )
602
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
603
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
604
+
605
+ if (input_ids is None) ^ (inputs_embeds is not None):
606
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
607
+
608
+ if self.gradient_checkpointing and self.training and use_cache:
609
+ logger.warning_once(
610
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
611
+ )
612
+ use_cache = False
613
+
614
+ if inputs_embeds is None:
615
+ inputs_embeds = self.embed_tokens(input_ids)
616
+
617
+ if use_cache and past_key_values is None:
618
+ past_key_values = DynamicCache()
619
+
620
+ if cache_position is None:
621
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
622
+ cache_position = torch.arange(
623
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
624
+ )
625
+
626
+ if position_ids is None:
627
+ position_ids = cache_position.unsqueeze(0)
628
+
629
+ attention_mask = self._update_encoder_mask(attention_mask, inputs_embeds)
630
+
631
+ hidden_states = inputs_embeds
632
+
633
+ # create position embeddings to be shared across the decoder layers
634
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
635
+
636
+ # decoder layers
637
+ all_hidden_states = () if output_hidden_states else None
638
+ all_self_attns = () if output_attentions else None
639
+
640
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
641
+ if output_hidden_states:
642
+ all_hidden_states += (hidden_states,)
643
+
644
+ if self.gradient_checkpointing and self.training:
645
+ layer_outputs = self._gradient_checkpointing_func(
646
+ decoder_layer.__call__,
647
+ hidden_states,
648
+ attention_mask, # causal_mask
649
+ position_ids,
650
+ past_key_values,
651
+ output_attentions,
652
+ use_cache,
653
+ cache_position,
654
+ position_embeddings,
655
+ )
656
+ else:
657
+ layer_outputs = decoder_layer(
658
+ hidden_states,
659
+ attention_mask=attention_mask, # causal_mask
660
+ position_ids=position_ids,
661
+ past_key_value=past_key_values,
662
+ output_attentions=output_attentions,
663
+ use_cache=use_cache,
664
+ cache_position=cache_position,
665
+ position_embeddings=position_embeddings,
666
+ **flash_attn_kwargs,
667
+ )
668
+
669
+ hidden_states = layer_outputs[0]
670
+
671
+ if output_attentions:
672
+ all_self_attns += (layer_outputs[1],)
673
+
674
+ hidden_states = self.norm(hidden_states)
675
+
676
+ # add hidden states from the last decoder layer
677
+ if output_hidden_states:
678
+ all_hidden_states += (hidden_states,)
679
+
680
+ output = BaseModelOutputWithPast(
681
+ last_hidden_state=hidden_states,
682
+ past_key_values=past_key_values if use_cache else None,
683
+ hidden_states=all_hidden_states,
684
+ attentions=all_self_attns,
685
+ )
686
+ return output if return_dict else output.to_tuple()
687
+
688
+ def _update_encoder_mask(
689
+ self,
690
+ attention_mask: torch.Tensor,
691
+ input_tensor: torch.Tensor,
692
+ ):
693
+ # Для flash_attention_2 возвращаем исходную маску
694
+ if self.config._attn_implementation == "flash_attention_2":
695
+ if attention_mask is not None and (attention_mask == 0).any():
696
+ return attention_mask
697
+ return None
698
+
699
+ dtype, device = input_tensor.dtype, input_tensor.device
700
+ batch_size, sequence_length = input_tensor.shape[:2]
701
+
702
+ # 1. Создаём базовую маску без ограничений (все токены видят друг друга)
703
+ encoder_mask = torch.full(
704
+ (batch_size, 1, sequence_length, sequence_length),
705
+ fill_value=1.0,
706
+ dtype=dtype,
707
+ device=device
708
+ )
709
+
710
+ # 2. Применяем padding-маску если есть
711
+ if attention_mask is not None:
712
+ # Создаём 4D padding-маску [batch, 1, 1, seq_len]
713
+ padding_mask = attention_mask[:, None, None, :].to(dtype=dtype)
714
+
715
+ # Комбинируем: обнуляем позиции где padding_mask == 0
716
+ encoder_mask = encoder_mask * padding_mask
717
+
718
+ # Конвертируем в формат для softmax (0 = -inf)
719
+ min_dtype = torch.finfo(dtype).min
720
+ encoder_mask = encoder_mask.masked_fill(encoder_mask == 0.0, min_dtype)
721
+
722
+ return encoder_mask
723
+
724
+ def _update_causal_mask(
725
+ self,
726
+ attention_mask: torch.Tensor,
727
+ input_tensor: torch.Tensor,
728
+ cache_position: torch.Tensor,
729
+ past_key_values: Cache,
730
+ output_attentions: bool,
731
+ ):
732
+ if self.config._attn_implementation == "flash_attention_2":
733
+ if attention_mask is not None and (attention_mask == 0.0).any():
734
+ return attention_mask
735
+ return None
736
+
737
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
738
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
739
+ # to infer the attention mask.
740
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
741
+ using_static_cache = isinstance(past_key_values, StaticCache)
742
+
743
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
744
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
745
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
746
+ attention_mask,
747
+ inputs_embeds=input_tensor,
748
+ past_key_values_length=past_seen_tokens,
749
+ is_training=self.training,
750
+ ):
751
+ return None
752
+
753
+ dtype, device = input_tensor.dtype, input_tensor.device
754
+ sequence_length = input_tensor.shape[1]
755
+ if using_static_cache:
756
+ target_length = past_key_values.get_max_cache_shape()
757
+ else:
758
+ target_length = (
759
+ attention_mask.shape[-1]
760
+ if isinstance(attention_mask, torch.Tensor)
761
+ else past_seen_tokens + sequence_length + 1
762
+ )
763
+
764
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
765
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
766
+ attention_mask,
767
+ sequence_length=sequence_length,
768
+ target_length=target_length,
769
+ dtype=dtype,
770
+ device=device,
771
+ cache_position=cache_position,
772
+ batch_size=input_tensor.shape[0],
773
+ )
774
+
775
+ if (
776
+ self.config._attn_implementation == "sdpa"
777
+ and attention_mask is not None
778
+ and attention_mask.device.type == "cuda"
779
+ and not output_attentions
780
+ ):
781
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
782
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
783
+ # Details: https://github.com/pytorch/pytorch/issues/110213
784
+ min_dtype = torch.finfo(dtype).min
785
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
786
+
787
+ return causal_mask
788
+
789
+ @staticmethod
790
+ def _prepare_4d_causal_attention_mask_with_cache_position(
791
+ attention_mask: torch.Tensor,
792
+ sequence_length: int,
793
+ target_length: int,
794
+ dtype: torch.dtype,
795
+ device: torch.device,
796
+ cache_position: torch.Tensor,
797
+ batch_size: int,
798
+ **kwargs,
799
+ ):
800
+ """
801
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
802
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
803
+
804
+ Args:
805
+ attention_mask (`torch.Tensor`):
806
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
807
+ `(batch_size, 1, query_length, key_value_length)`.
808
+ sequence_length (`int`):
809
+ The sequence length being processed.
810
+ target_length (`int`):
811
+ The target length: when generating with static cache, the mask should be as long as the static cache,
812
+ to account for the 0 padding, the part of the cache that is not filled yet.
813
+ dtype (`torch.dtype`):
814
+ The dtype to use for the 4D attention mask.
815
+ device (`torch.device`):
816
+ The device to plcae the 4D attention mask on.
817
+ cache_position (`torch.Tensor`):
818
+ Indices depicting the position of the input sequence tokens in the sequence.
819
+ batch_size (`torch.Tensor`):
820
+ Batch size.
821
+ """
822
+ if attention_mask is not None and attention_mask.dim() == 4:
823
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
824
+ causal_mask = attention_mask
825
+ else:
826
+ min_dtype = torch.finfo(dtype).min
827
+ causal_mask = torch.full(
828
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
829
+ )
830
+ if sequence_length != 1:
831
+ causal_mask = torch.triu(causal_mask, diagonal=1)
832
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
833
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
834
+ if attention_mask is not None:
835
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
836
+ mask_length = attention_mask.shape[-1]
837
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
838
+ padding_mask = padding_mask == 0
839
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
840
+ padding_mask, min_dtype
841
+ )
842
+
843
+ return causal_mask
844
+
845
+
846
+ class FeedForward(nn.Module):
847
+ def __init__(self, dim, mult = 4):
848
+ super().__init__()
849
+ self.hidden_size = dim
850
+ self.intermediate_size = dim * mult
851
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
852
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
853
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
854
+ self.act_fn = nn.SiLU()
855
+
856
+ def forward(self, x):
857
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
858
+
859
+
860
+ class Attention(nn.Module):
861
+ def __init__(self, query_dimension, context_dimension=None, num_heads=8, head_dim=64):
862
+ super().__init__()
863
+ inner_dimension = head_dim * num_heads
864
+ context_dimension = context_dimension if context_dimension is not None else query_dimension
865
+
866
+ self.scaling_factor = head_dim ** -0.5
867
+ self.num_heads = num_heads
868
+
869
+ self.to_q = nn.Linear(query_dimension, inner_dimension, bias=False)
870
+ self.to_kv = nn.Linear(context_dimension, inner_dimension * 2, bias=False)
871
+ self.to_out = nn.Linear(inner_dimension, query_dimension, bias=False)
872
+
873
+ def forward(self, input_tensor, context=None, attention_mask=None):
874
+ batch_size, seq_len, _ = input_tensor.shape
875
+ num_heads = self.num_heads
876
+
877
+ # Project input to query
878
+ query = self.to_q(input_tensor)
879
+
880
+ # Use input as context if not provided
881
+ context = input_tensor if context is None else context
882
+ key, value = self.to_kv(context).chunk(2, dim=-1)
883
+
884
+ # Rearrange for multi-head attention
885
+ query = rearrange(query, 'b n (h d) -> (b h) n d', h=num_heads)
886
+ key = rearrange(key, 'b n (h d) -> (b h) n d', h=num_heads)
887
+ value = rearrange(value, 'b n (h d) -> (b h) n d', h=num_heads)
888
+
889
+ # Compute scaled dot-product attention
890
+ with torch.backends.cuda.sdp_kernel(
891
+ enable_flash=True,
892
+ enable_math=True,
893
+ enable_mem_efficient=True
894
+ ):
895
+ attention_output = F.scaled_dot_product_attention(query, key, value)
896
+
897
+ # Rearrange back to original shape
898
+ attention_output = rearrange(attention_output, '(b h) n d -> b n (h d)', h=num_heads)
899
+
900
+ return self.to_out(attention_output)
901
+
902
+
903
+ class LatentAttentionModel(PreTrainedModel):
904
+ config_class = LatentAttentionConfig
905
+
906
+ def __init__(self, configuration: LatentAttentionConfig):
907
+ super().__init__(configuration)
908
+
909
+ # Extract configuration parameters
910
+ num_latents = configuration.num_latents_value
911
+ latent_dimension = configuration.latent_dim
912
+ cross_attention_heads = configuration.num_cross_heads
913
+ cross_head_dimension = configuration.cross_dim_head
914
+ hidden_dimension = configuration.hidden_dim
915
+
916
+ # Initialize cross-attention components
917
+ self.cross_attend_blocks = nn.ModuleList([
918
+ Attention(
919
+ query_dimension=latent_dimension,
920
+ context_dimension=hidden_dimension,
921
+ num_heads=cross_attention_heads,
922
+ head_dim=cross_head_dimension
923
+ ),
924
+ FeedForward(latent_dimension)
925
+ ])
926
+
927
+ # Register learnable latents as model parameter
928
+ self.latents = nn.Parameter(torch.randn(num_latents, latent_dimension))
929
+
930
+ def forward(self, hidden_states, attention_mask: Optional[torch.Tensor] = None):
931
+ cross_attention, feed_forward = self.cross_attend_blocks
932
+
933
+ batch_size, device = hidden_states.size(0), hidden_states.device
934
+
935
+ # Expand latents to match batch size
936
+ expanded_latents = self.latents.repeat(batch_size, 1, 1)
937
+
938
+ # Apply cross-attention with residual connection
939
+ attended_output = cross_attention(
940
+ hidden_states, context=expanded_latents, attention_mask=attention_mask) + hidden_states
941
+
942
+ # Apply feed-forward with residual connection
943
+ processed_output = feed_forward(attended_output) + attended_output
944
+
945
+ return processed_output
946
+
947
+
948
+ class GigarEmbedModel(PreTrainedModel):
949
+ config_class = GigarEmbedConfig
950
+ _supports_flash_attn_2 = True
951
+ _no_split_modules = ["GigarDecoderLayer", "LatentAttentionModel"]
952
+
953
+ def __init__(self, configuration: GigarEmbedConfig):
954
+ super().__init__(configuration)
955
+
956
+ # Initialize latent attention model
957
+ self.latent_attention_model = AutoModel.from_config(
958
+ configuration.latent_attention_config
959
+ )
960
+
961
+ self.tokenizer, self.text_encoder = None, None
962
+ if configuration.text_config is not None:
963
+ # Initialize text model if provided in config
964
+ self.model = AutoModel.from_config(configuration.text_config)
965
+
966
+ # Initialize tokenizer if text config is available
967
+ self.tokenizer = AutoTokenizer.from_pretrained(
968
+ configuration.text_config.name_or_path
969
+ )
970
+
971
+ # Set configuration parameters
972
+ self.padding_side = configuration.padding_side
973
+ self.add_eos = configuration.add_eos
974
+ self.mask_type = configuration.mask_type
975
+
976
+ # Add padding token if configured
977
+ if configuration.add_pad_token and self.tokenizer is not None:
978
+ self.add_pad_token()
979
+
980
+ def add_pad_token(self):
981
+ self.tokenizer.pad_token_id = 0
982
+ self.tokenizer.padding_side = self.padding_side
983
+
984
+ def gradient_checkpointing_enable(self, *args, **kwargs):
985
+ self.model.gradient_checkpointing_enable(*args, **kwargs)
986
+
987
+ def forward(self, input_ids: torch.Tensor, attention_mask: torch.Tensor,
988
+ return_embeddings: bool = False, **kwargs):
989
+ kwargs.pop('token_type_ids', None)
990
+
991
+ with torch.autocast('cuda', dtype=torch.bfloat16):
992
+ outputs = self.model(input_ids=input_ids, attention_mask=attention_mask, **kwargs)
993
+
994
+ last_hidden = self.latent_attention_model(outputs.last_hidden_state, attention_mask)
995
+
996
+ if return_embeddings:
997
+ return self.mean_pool(last_hidden, attention_mask)
998
+
999
+ return BaseModelOutputWithPast(last_hidden_state=last_hidden)
1000
+
1001
+ def mean_pool(self, last_hidden: torch.Tensor, attention_mask: torch.Tensor):
1002
+ last_hidden = last_hidden.masked_fill(~attention_mask[..., None].bool(), 0.0)
1003
+ embeddings = last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]
1004
+ return F.normalize(embeddings, p=2, dim=-1)
1005
+
1006
+
1007
+ ## AutoModel Register
1008
+ AutoModel.register(GigarConfig, GigarModel)
1009
+ AutoModel.register(GigarEmbedConfig, GigarEmbedModel)
1010
+ AutoModel.register(LatentAttentionConfig, LatentAttentionModel)
1011
+
1012
+ ## Register for auto class
1013
+ GigarModel.register_for_auto_class("AutoModel")
1014
+ GigarEmbedModel.register_for_auto_class("AutoModel")
1015
+ LatentAttentionModel.register_for_auto_class("AutoModel")