Aarushhh commited on
Commit
53272df
·
verified ·
1 Parent(s): a19b00a

Create modular_Sewy2.py

Browse files
Files changed (1) hide show
  1. modular_Sewy2.py +2280 -0
modular_Sewy2.py ADDED
@@ -0,0 +1,2280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.configuration_utils import PretrainedConfig
2
+ from transformers.utils import logging
3
+
4
+ """ PyTorch Sewy model."""
5
+ """Used deepseekv3 as starting point"""
6
+ import math
7
+ import warnings
8
+ from typing import List, Optional, Tuple, Union
9
+
10
+ import torch
11
+ import torch.nn.functional as F
12
+ import torch.utils.checkpoint
13
+ from torch import nn
14
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
15
+
16
+ from transformers.activations import ACT2FN
17
+ from transformers.cache_utils import Cache, DynamicCache
18
+ from transformers.modeling_attn_mask_utils import (
19
+ AttentionMaskConverter,
20
+ _prepare_4d_attention_mask,
21
+ _prepare_4d_causal_attention_mask,
22
+ )
23
+ from transformers.modeling_outputs import (
24
+ BaseModelOutputWithPast,
25
+ CausalLMOutputWithPast,
26
+ SequenceClassifierOutputWithPast,
27
+ )
28
+ from transformers.modeling_utils import PreTrainedModel
29
+ from transformers.pytorch_utils import (
30
+ ALL_LAYERNORM_LAYERS,
31
+ is_torch_greater_or_equal_than_1_13,
32
+ )
33
+ from transformers.utils import (
34
+ add_start_docstrings,
35
+ add_start_docstrings_to_model_forward,
36
+ is_flash_attn_2_available,
37
+ is_flash_attn_greater_or_equal_2_10,
38
+ logging,
39
+ replace_return_docstrings,
40
+ )
41
+ from transformers.utils.import_utils import is_torch_fx_available
42
+ import torch.distributed as dist
43
+ import numpy as np
44
+
45
+ if is_flash_attn_2_available():
46
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
47
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
48
+
49
+
50
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
51
+ # It means that the function will not be traced through and simply appear as a node in the graph.
52
+ # Import torch.fx at the top level if available
53
+ if is_torch_fx_available():
54
+ import torch.fx
55
+ if not is_torch_greater_or_equal_than_1_13:
56
+ # Wrap the function at module level
57
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
58
+
59
+
60
+ logger = logging.get_logger(__name__)
61
+
62
+ _CONFIG_FOR_DOC = "SewyV2Config"
63
+
64
+
65
+
66
+ Sewy_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
67
+ class SewyV2Config(PretrainedConfig):
68
+ r"""
69
+ This is the configuration class to store the configuration of a [`SewyV2Model`]. It is used to instantiate an Sewy
70
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
71
+ defaults will yield a similar configuration to that of the Sewy-V3.
72
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
73
+ documentation from [`PretrainedConfig`] for more information.
74
+ Args:
75
+ vocab_size (`int`, *optional*, defaults to 129280):
76
+ Vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the
77
+ `inputs_ids` passed when calling [`SewyV2Model`]
78
+ hidden_size (`int`, *optional*, defaults to 4096):
79
+ Dimension of the hidden representations.
80
+ intermediate_size (`int`, *optional*, defaults to 11008):
81
+ Dimension of the MLP representations.
82
+ moe_intermediate_size (`int`, *optional*, defaults to 1407):
83
+ Dimension of the MoE representations.
84
+ num_hidden_layers (`int`, *optional*, defaults to 32):
85
+ Number of hidden layers in the Transformer decoder.
86
+ num_nextn_predict_layers (`int`, *optional*, defaults to 1):
87
+ Number of nextn predict layers in the SewyV2 Model.
88
+ num_attention_heads (`int`, *optional*, defaults to 32):
89
+ Number of attention heads for each attention layer in the Transformer decoder.
90
+ n_shared_experts (`int`, *optional*, defaults to None):
91
+ Number of shared experts, None means dense model.
92
+ n_routed_experts (`int`, *optional*, defaults to None):
93
+ Number of routed experts, None means dense model.
94
+ routed_scaling_factor (`float`, *optional*, defaults to 1.0):
95
+ Scaling factor or routed experts.
96
+ topk_method (`str`, *optional*, defaults to `gready`):
97
+ Topk method used in routed gate.
98
+ n_group (`int`, *optional*, defaults to None):
99
+ Number of groups for routed experts.
100
+ topk_group (`int`, *optional*, defaults to None):
101
+ Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
102
+ num_experts_per_tok (`int`, *optional*, defaults to None):
103
+ Number of selected experts, None means dense model.
104
+ moe_layer_freq (`int`, *optional*, defaults to 1):
105
+ The frequency of the MoE layer: one expert layer for every `moe_layer_freq - 1` dense layers.
106
+ first_k_dense_replace (`int`, *optional*, defaults to 0):
107
+ Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
108
+ \--k dense layers--/
109
+ norm_topk_prob (`bool`, *optional*, defaults to False):
110
+ Whether to normalize the weights of the routed experts.
111
+ scoring_func (`str`, *optional*, defaults to 'softmax'):
112
+ Method of computing expert weights.
113
+ aux_loss_alpha (`float`, *optional*, defaults to 0.001):
114
+ Auxiliary loss weight coefficient.
115
+ seq_aux = (`bool`, *optional*, defaults to True):
116
+ Whether to compute the auxiliary loss for each individual sample.
117
+ num_key_value_heads (`int`, *optional*):
118
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
119
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
120
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
121
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
122
+ by meanpooling all the original heads within that group. For more details checkout [this
123
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
124
+ `num_attention_heads`.
125
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
126
+ The non-linear activation function (function or string) in the decoder.
127
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
128
+ The maximum sequence length that this model might ever be used with.
129
+ initializer_range (`float`, *optional*, defaults to 0.02):
130
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
131
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
132
+ The epsilon used by the rms normalization layers.
133
+ use_cache (`bool`, *optional*, defaults to `True`):
134
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
135
+ relevant if `config.is_decoder=True`.
136
+ pad_token_id (`int`, *optional*):
137
+ Padding token id.
138
+ bos_token_id (`int`, *optional*, defaults to 1):
139
+ Beginning of stream token id.
140
+ eos_token_id (`int`, *optional*, defaults to 2):
141
+ End of stream token id.
142
+ pretraining_tp (`int`, *optional*, defaults to 1):
143
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
144
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
145
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
146
+ issue](https://github.com/pytorch/pytorch/issues/76232).
147
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
148
+ Whether to tie weight embeddings
149
+ rope_theta (`float`, *optional*, defaults to 10000.0):
150
+ The base period of the RoPE embeddings.
151
+ rope_scaling (`Dict`, *optional*):
152
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
153
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
154
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
155
+ `max_position_embeddings` to the expected new maximum.
156
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
157
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
158
+ attention_dropout (`float`, *optional*, defaults to 0.0):
159
+ The dropout ratio for the attention probabilities.
160
+ ```python
161
+ >>> from transformers import SewyV2Model, SewyV2Config
162
+ >>> # Initializing a Sewy-V3 style configuration
163
+ >>> configuration = SewyV2Config()
164
+ >>> # Accessing the model configuration
165
+ >>> configuration = model.config
166
+ ```"""
167
+
168
+ model_type = "Sewy_v2"
169
+ keys_to_ignore_at_inference = ["past_key_values"]
170
+
171
+ def __init__(
172
+ self,
173
+ vocab_size=129280,
174
+ hidden_size=7168,
175
+ intermediate_size=18432,
176
+ moe_intermediate_size = 2048,
177
+ num_hidden_layers=61,
178
+ num_nextn_predict_layers=1,
179
+ num_attention_heads=128,
180
+ num_key_value_heads=128,
181
+ n_shared_experts = 1,
182
+ n_routed_experts = 256,
183
+ ep_size = 1,
184
+ routed_scaling_factor = 2.5,
185
+ kv_lora_rank = 512,
186
+ q_lora_rank = 1536,
187
+ qk_rope_head_dim = 64,
188
+ v_head_dim = 128,
189
+ qk_nope_head_dim = 128,
190
+ topk_method = 'noaux_tc',
191
+ n_group = 8,
192
+ topk_group = 4,
193
+ num_experts_per_tok = 8,
194
+ moe_layer_freq = 1,
195
+ first_k_dense_replace = 3,
196
+ norm_topk_prob = True,
197
+ scoring_func = 'sigmoid',
198
+ aux_loss_alpha = 0.001,
199
+ seq_aux = True,
200
+ hidden_act="silu",
201
+ max_position_embeddings=4096,
202
+ initializer_range=0.02,
203
+ rms_norm_eps=1e-6,
204
+ use_cache=True,
205
+ pad_token_id=None,
206
+ bos_token_id=0,
207
+ eos_token_id=1,
208
+ pretraining_tp=1,
209
+ tie_word_embeddings=False,
210
+ rope_theta=10000.0,
211
+ rope_scaling=None,
212
+ attention_bias=False,
213
+ attention_dropout=0.0,
214
+ unit_norm_eps = 1e-6,
215
+ resformer_lambda = 2.0,
216
+ neutreno_lambda=0.4,
217
+ final_logit_softcapping=30.0,
218
+ attn_logit_softcapping=50.0,
219
+ **kwargs,
220
+ ):
221
+ self.vocab_size = vocab_size
222
+ self.max_position_embeddings = max_position_embeddings
223
+ self.hidden_size = hidden_size
224
+ self.intermediate_size = intermediate_size
225
+ self.moe_intermediate_size = moe_intermediate_size
226
+ self.num_hidden_layers = num_hidden_layers
227
+ self.num_nextn_predict_layers = num_nextn_predict_layers
228
+ self.num_attention_heads = num_attention_heads
229
+ self.n_shared_experts = n_shared_experts
230
+ self.n_routed_experts = n_routed_experts
231
+ self.ep_size = ep_size
232
+ self.routed_scaling_factor = routed_scaling_factor
233
+ self.kv_lora_rank = kv_lora_rank
234
+ self.q_lora_rank = q_lora_rank
235
+ self.qk_rope_head_dim = qk_rope_head_dim
236
+ self.v_head_dim = v_head_dim
237
+ self.qk_nope_head_dim = qk_nope_head_dim
238
+ self.topk_method = topk_method
239
+ self.n_group = n_group
240
+ self.topk_group = topk_group
241
+ self.num_experts_per_tok = num_experts_per_tok
242
+ self.moe_layer_freq = moe_layer_freq
243
+ self.first_k_dense_replace = first_k_dense_replace
244
+ self.norm_topk_prob = norm_topk_prob
245
+ self.scoring_func = scoring_func
246
+ self.aux_loss_alpha = aux_loss_alpha
247
+ self.seq_aux = seq_aux
248
+ # for backward compatibility
249
+ if num_key_value_heads is None:
250
+ num_key_value_heads = num_attention_heads
251
+
252
+ self.num_key_value_heads = num_key_value_heads
253
+ self.hidden_act = hidden_act
254
+ self.initializer_range = initializer_range
255
+ self.rms_norm_eps = rms_norm_eps
256
+ self.pretraining_tp = pretraining_tp
257
+ self.use_cache = use_cache
258
+ self.rope_theta = rope_theta
259
+ self.rope_scaling = rope_scaling
260
+ self.attention_bias = attention_bias
261
+ self.attention_dropout = attention_dropout
262
+ self.unit_norm_eps = unit_norm_eps
263
+ self.resformer_lambda = resformer_lambda
264
+ self.neutreno_lambda = neutreno_lambda
265
+ self.final_logit_softcapping = final_logit_softcapping
266
+ self.attn_logit_softcapping = attn_logit_softcapping
267
+ super().__init__(
268
+ pad_token_id=pad_token_id,
269
+ bos_token_id=bos_token_id,
270
+ eos_token_id=eos_token_id,
271
+ tie_word_embeddings=tie_word_embeddings,
272
+ **kwargs,
273
+ )
274
+
275
+ def _get_unpad_data(attention_mask):
276
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
277
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
278
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
279
+ cu_seqlens = F.pad(
280
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
281
+ )
282
+ return (
283
+ indices,
284
+ cu_seqlens,
285
+ max_seqlen_in_batch,
286
+ )
287
+
288
+
289
+ class SewyV2RMSNorm(nn.Module):
290
+ def __init__(self, hidden_size, eps=1e-6):
291
+ """
292
+ SewyV2RMSNorm is equivalent to T5LayerNorm
293
+ """
294
+ super().__init__()
295
+ self.weight = nn.Parameter(torch.ones(hidden_size))
296
+ self.variance_epsilon = eps
297
+
298
+ def forward(self, hidden_states):
299
+ input_dtype = hidden_states.dtype
300
+ hidden_states = hidden_states.to(torch.float32)
301
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
302
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
303
+ return self.weight * hidden_states.to(input_dtype)
304
+
305
+
306
+ ALL_LAYERNORM_LAYERS.append(SewyV2RMSNorm)
307
+
308
+
309
+ class SewyV2RotaryEmbedding(nn.Module):
310
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
311
+ super().__init__()
312
+
313
+ self.dim = dim
314
+ self.max_position_embeddings = max_position_embeddings
315
+ self.base = base
316
+ inv_freq = 1.0 / (
317
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
318
+ )
319
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
320
+
321
+ # Build here to make `torch.jit.trace` work.
322
+ self._set_cos_sin_cache(
323
+ seq_len=max_position_embeddings,
324
+ device=self.inv_freq.device,
325
+ dtype=torch.get_default_dtype(),
326
+ )
327
+ self.max_seq_len_cached = None
328
+
329
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
330
+ self.max_seq_len_cached = seq_len
331
+ t = torch.arange(
332
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
333
+ )
334
+
335
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
336
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
337
+ emb = torch.cat((freqs, freqs), dim=-1)
338
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
339
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
340
+
341
+ def forward(self, x, seq_len=None):
342
+ # x: [bs, num_attention_heads, seq_len, head_size]
343
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
344
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
345
+
346
+ return (
347
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
348
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
349
+ )
350
+
351
+
352
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->SewyV2
353
+ class SewyV2LinearScalingRotaryEmbedding(SewyV2RotaryEmbedding):
354
+ """SewyV2RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
355
+
356
+ def __init__(
357
+ self,
358
+ dim,
359
+ max_position_embeddings=2048,
360
+ base=10000,
361
+ device=None,
362
+ scaling_factor=1.0,
363
+ ):
364
+ self.scaling_factor = scaling_factor
365
+ super().__init__(dim, max_position_embeddings, base, device)
366
+
367
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
368
+ self.max_seq_len_cached = seq_len
369
+ t = torch.arange(
370
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
371
+ )
372
+ t = t / self.scaling_factor
373
+
374
+ freqs = torch.outer(t, self.inv_freq)
375
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
376
+ emb = torch.cat((freqs, freqs), dim=-1)
377
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
378
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
379
+
380
+
381
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->SewyV2
382
+ class SewyV2DynamicNTKScalingRotaryEmbedding(SewyV2RotaryEmbedding):
383
+ """SewyV2RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
384
+
385
+ def __init__(
386
+ self,
387
+ dim,
388
+ max_position_embeddings=2048,
389
+ base=10000,
390
+ device=None,
391
+ scaling_factor=1.0,
392
+ ):
393
+ self.scaling_factor = scaling_factor
394
+ super().__init__(dim, max_position_embeddings, base, device)
395
+
396
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
397
+ self.max_seq_len_cached = seq_len
398
+
399
+ if seq_len > self.max_position_embeddings:
400
+ base = self.base * (
401
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
402
+ - (self.scaling_factor - 1)
403
+ ) ** (self.dim / (self.dim - 2))
404
+ inv_freq = 1.0 / (
405
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
406
+ )
407
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
408
+
409
+ t = torch.arange(
410
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
411
+ )
412
+
413
+ freqs = torch.outer(t, self.inv_freq)
414
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
415
+ emb = torch.cat((freqs, freqs), dim=-1)
416
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
417
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
418
+
419
+
420
+ # Inverse dim formula to find dim based on number of rotations
421
+ def yarn_find_correction_dim(
422
+ num_rotations, dim, base=10000, max_position_embeddings=2048
423
+ ):
424
+ return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (
425
+ 2 * math.log(base)
426
+ )
427
+
428
+
429
+ # Find dim range bounds based on rotations
430
+ def yarn_find_correction_range(
431
+ low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
432
+ ):
433
+ low = math.floor(
434
+ yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)
435
+ )
436
+ high = math.ceil(
437
+ yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings)
438
+ )
439
+ return max(low, 0), min(high, dim - 1) # Clamp values just in case
440
+
441
+
442
+ def yarn_get_mscale(scale=1, mscale=1):
443
+ if scale <= 1:
444
+ return 1.0
445
+ return 0.1 * mscale * math.log(scale) + 1.0
446
+
447
+
448
+ def yarn_linear_ramp_mask(min, max, dim):
449
+ if min == max:
450
+ max += 0.001 # Prevent singularity
451
+
452
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
453
+ ramp_func = torch.clamp(linear_func, 0, 1)
454
+ return ramp_func
455
+
456
+
457
+ class SewyV2YarnRotaryEmbedding(SewyV2RotaryEmbedding):
458
+
459
+ def __init__(
460
+ self,
461
+ dim,
462
+ max_position_embeddings=2048,
463
+ base=10000,
464
+ device=None,
465
+ scaling_factor=1.0,
466
+ original_max_position_embeddings=4096,
467
+ beta_fast=32,
468
+ beta_slow=1,
469
+ mscale=1,
470
+ mscale_all_dim=0,
471
+ ):
472
+ self.scaling_factor = scaling_factor
473
+ self.original_max_position_embeddings = original_max_position_embeddings
474
+ self.beta_fast = beta_fast
475
+ self.beta_slow = beta_slow
476
+ self.mscale = mscale
477
+ self.mscale_all_dim = mscale_all_dim
478
+ super().__init__(dim, max_position_embeddings, base, device)
479
+
480
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
481
+ self.max_seq_len_cached = seq_len
482
+ dim = self.dim
483
+
484
+ freq_extra = 1.0 / (
485
+ self.base
486
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
487
+ )
488
+ freq_inter = 1.0 / (
489
+ self.scaling_factor
490
+ * self.base
491
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
492
+ )
493
+
494
+ low, high = yarn_find_correction_range(
495
+ self.beta_fast,
496
+ self.beta_slow,
497
+ dim,
498
+ self.base,
499
+ self.original_max_position_embeddings,
500
+ )
501
+ inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
502
+ device=device, dtype=torch.float32
503
+ )
504
+ inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
505
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
506
+
507
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
508
+
509
+ freqs = torch.outer(t, inv_freq)
510
+
511
+ _mscale = float(
512
+ yarn_get_mscale(self.scaling_factor, self.mscale)
513
+ / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
514
+ )
515
+
516
+ emb = torch.cat((freqs, freqs), dim=-1)
517
+ self.register_buffer(
518
+ "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False
519
+ )
520
+ self.register_buffer(
521
+ "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False
522
+ )
523
+
524
+
525
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
526
+ def rotate_half(x):
527
+ """Rotates half the hidden dims of the input."""
528
+ x1 = x[..., : x.shape[-1] // 2]
529
+ x2 = x[..., x.shape[-1] // 2 :]
530
+ return torch.cat((-x2, x1), dim=-1)
531
+
532
+
533
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
534
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
535
+ """Applies Rotary Position Embedding to the query and key tensors.
536
+
537
+ Args:
538
+ q (`torch.Tensor`): The query tensor.
539
+ k (`torch.Tensor`): The key tensor.
540
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
541
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
542
+ position_ids (`torch.Tensor`):
543
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
544
+ used to pass offsetted position ids when working with a KV-cache.
545
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
546
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
547
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
548
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
549
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
550
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
551
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
552
+ Returns:
553
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
554
+ """
555
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
556
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
557
+
558
+ b, h, s, d = q.shape
559
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
560
+
561
+ b, h, s, d = k.shape
562
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
563
+
564
+ q_embed = (q * cos) + (rotate_half(q) * sin)
565
+ k_embed = (k * cos) + (rotate_half(k) * sin)
566
+ return q_embed, k_embed
567
+
568
+
569
+ class SewyV2MLP(nn.Module):
570
+ def __init__(self, config, hidden_size=None, intermediate_size=None):
571
+ super().__init__()
572
+ self.config = config
573
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
574
+ self.intermediate_size = (
575
+ config.intermediate_size if intermediate_size is None else intermediate_size
576
+ )
577
+
578
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
579
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
580
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
581
+ self.act_fn = ACT2FN[config.hidden_act]
582
+
583
+ ## nGPT
584
+
585
+ self.s_u = nn.Parameter(torch.ones(self.intermediate_size))
586
+ self.s_v = nn.Parameter(torch.ones(self.intermediate_size))
587
+
588
+ def forward(self, x):
589
+
590
+ up_proj = self.up_proj(x) * self.s_u
591
+ gate_proj = self.gate_proj(x) * (self.s_v * (self.config.hidden_size ** 0.5))
592
+ down_proj = self.down_proj(self.act_fn(gate_proj) * up_proj)
593
+ return down_proj
594
+
595
+
596
+ class MoEGate(nn.Module):
597
+ def __init__(self, config):
598
+ super().__init__()
599
+ self.config = config
600
+ self.top_k = config.num_experts_per_tok
601
+ self.n_routed_experts = config.n_routed_experts
602
+ self.routed_scaling_factor = config.routed_scaling_factor
603
+ self.scoring_func = config.scoring_func
604
+ self.seq_aux = config.seq_aux
605
+ self.topk_method = config.topk_method
606
+ self.n_group = config.n_group
607
+ self.topk_group = config.topk_group
608
+
609
+ # topk selection algorithm
610
+ self.norm_topk_prob = config.norm_topk_prob
611
+ self.gating_dim = config.hidden_size
612
+ self.weight = nn.Parameter(
613
+ torch.empty((self.n_routed_experts, self.gating_dim))
614
+ )
615
+ if self.topk_method == "noaux_tc":
616
+ self.e_score_correction_bias = nn.Parameter(
617
+ torch.empty((self.n_routed_experts))
618
+ )
619
+ self.reset_parameters()
620
+
621
+ def reset_parameters(self) -> None:
622
+ import torch.nn.init as init
623
+
624
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
625
+
626
+ def forward(self, hidden_states):
627
+ bsz, seq_len, h = hidden_states.shape
628
+ ### compute gating score
629
+ hidden_states = hidden_states.view(-1, h)
630
+ logits = F.linear(
631
+ hidden_states.type(torch.float32), self.weight.type(torch.float32), None
632
+ )
633
+ if self.scoring_func == "sigmoid":
634
+ scores = logits.sigmoid()
635
+ else:
636
+ raise NotImplementedError(
637
+ f"insupportable scoring function for MoE gating: {self.scoring_func}"
638
+ )
639
+
640
+ ### select top-k experts
641
+ if self.topk_method == "noaux_tc":
642
+ # assert not self.training
643
+ scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)
644
+ group_scores = (
645
+ scores_for_choice.view(bsz * seq_len, self.n_group, -1).topk(2, dim=-1)[0].sum(dim = -1)
646
+ ) # [n, n_group]
647
+ group_idx = torch.topk(
648
+ group_scores, k=self.topk_group, dim=-1, sorted=False
649
+ )[
650
+ 1
651
+ ] # [n, top_k_group]
652
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
653
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
654
+ score_mask = (
655
+ group_mask.unsqueeze(-1)
656
+ .expand(
657
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
658
+ )
659
+ .reshape(bsz * seq_len, -1)
660
+ ) # [n, e]
661
+ tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(), 0.0) # [n, e]
662
+ _, topk_idx = torch.topk(
663
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
664
+ )
665
+ topk_weight = scores.gather(1, topk_idx)
666
+ else:
667
+ raise NotImplementedError(
668
+ f"insupportable TopK function for MoE gating: {self.topk_method}"
669
+ )
670
+
671
+ ### norm gate to sum 1
672
+ if self.top_k > 1 and self.norm_topk_prob:
673
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
674
+ topk_weight = topk_weight / denominator
675
+ topk_weight = topk_weight * self.routed_scaling_factor # must multiply the scaling factor
676
+
677
+ return topk_idx, topk_weight
678
+
679
+ class SewyV2MoE(nn.Module):
680
+ """
681
+ A mixed expert module containing shared experts.
682
+ """
683
+
684
+ def __init__(self, config):
685
+ super().__init__()
686
+ self.config = config
687
+ self.num_experts_per_tok = config.num_experts_per_tok
688
+
689
+ if hasattr(config, "ep_size") and config.ep_size > 1:
690
+ assert config.ep_size == dist.get_world_size()
691
+ self.ep_size = config.ep_size
692
+ self.experts_per_rank = config.n_routed_experts // config.ep_size
693
+ self.ep_rank = dist.get_rank()
694
+ self.experts = nn.ModuleList(
695
+ [
696
+ (
697
+ SewyV2MLP(
698
+ config, intermediate_size=config.moe_intermediate_size
699
+ )
700
+ if i >= self.ep_rank * self.experts_per_rank
701
+ and i < (self.ep_rank + 1) * self.experts_per_rank
702
+ else None
703
+ )
704
+ for i in range(config.n_routed_experts)
705
+ ]
706
+ )
707
+ else:
708
+ self.ep_size = 1
709
+ self.experts_per_rank = config.n_routed_experts
710
+ self.ep_rank = 0
711
+ self.experts = nn.ModuleList(
712
+ [
713
+ SewyV2MLP(
714
+ config, intermediate_size=config.moe_intermediate_size
715
+ )
716
+ for i in range(config.n_routed_experts)
717
+ ]
718
+ )
719
+ self.gate = MoEGate(config)
720
+ if config.n_shared_experts is not None:
721
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
722
+ self.shared_experts = SewyV2MLP(
723
+ config=config, intermediate_size=intermediate_size
724
+ )
725
+
726
+ def forward(self, hidden_states):
727
+ identity = hidden_states
728
+ orig_shape = hidden_states.shape
729
+ topk_idx, topk_weight = self.gate(hidden_states)
730
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
731
+ flat_topk_idx = topk_idx.view(-1)
732
+ # if not self.training:
733
+ if True:
734
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
735
+ if self.config.n_shared_experts is not None:
736
+ y = y + self.shared_experts(identity)
737
+ return y
738
+
739
+ @torch.no_grad()
740
+ def moe_infer(self, x, topk_ids, topk_weight):
741
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
742
+ cnts.scatter_(1, topk_ids, 1)
743
+ tokens_per_expert = cnts.sum(dim=0)
744
+ idxs = topk_ids.view(-1).argsort()
745
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
746
+ sorted_tokens_shape = sorted_tokens.shape
747
+ if self.ep_size > 1:
748
+ tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1)
749
+ tokens_per_expert_group = tokens_per_expert.new_empty(
750
+ tokens_per_expert.shape[0]
751
+ )
752
+ dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
753
+ output_splits = (
754
+ tokens_per_expert_group.view(self.ep_size, -1)
755
+ .sum(1)
756
+ .cpu()
757
+ .numpy()
758
+ .tolist()
759
+ )
760
+ gathered_tokens = sorted_tokens.new_empty(
761
+ tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1]
762
+ )
763
+ input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
764
+ dist.all_to_all(
765
+ list(gathered_tokens.split(output_splits)),
766
+ list(sorted_tokens.split(input_split_sizes)),
767
+ )
768
+ tokens_per_expert_post_gather = tokens_per_expert_group.view(
769
+ self.ep_size, self.experts_per_rank
770
+ ).sum(dim=0)
771
+ gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32)
772
+ s = 0
773
+ for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
774
+ gatherd_idxs[s : s + k] = i % self.experts_per_rank
775
+ s += k
776
+ gatherd_idxs = gatherd_idxs.argsort()
777
+ sorted_tokens = gathered_tokens[gatherd_idxs]
778
+ tokens_per_expert = tokens_per_expert_post_gather
779
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
780
+
781
+ outputs = []
782
+ start_idx = 0
783
+ for i, num_tokens in enumerate(tokens_per_expert):
784
+ end_idx = start_idx + num_tokens
785
+ if num_tokens == 0:
786
+ continue
787
+ expert = self.experts[i + self.ep_rank * self.experts_per_rank]
788
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
789
+ expert_out = expert(tokens_for_this_expert)
790
+ outputs.append(expert_out)
791
+ start_idx = end_idx
792
+
793
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
794
+ if self.ep_size > 1:
795
+ new_x = torch.empty_like(outs)
796
+ new_x[gatherd_idxs] = outs
797
+ gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
798
+ dist.all_to_all(
799
+ list(gathered_tokens.split(input_split_sizes)),
800
+ list(new_x.split(output_splits)),
801
+ )
802
+ outs = gathered_tokens
803
+
804
+ new_x = torch.empty_like(outs)
805
+ new_x[idxs] = outs
806
+ final_out = (
807
+ new_x.view(*topk_ids.shape, -1)
808
+ .type(topk_weight.dtype)
809
+ .mul_(topk_weight.unsqueeze(dim=-1))
810
+ .sum(dim=1)
811
+ .type(new_x.dtype)
812
+ )
813
+ return final_out
814
+
815
+
816
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
817
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
818
+ """
819
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
820
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
821
+ """
822
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
823
+ if n_rep == 1:
824
+ return hidden_states
825
+ hidden_states = hidden_states[:, :, None, :, :].expand(
826
+ batch, num_key_value_heads, n_rep, slen, head_dim
827
+ )
828
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
829
+
830
+
831
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->SewyV2
832
+ class SewyV2Attention(nn.Module):
833
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
834
+
835
+ def __init__(self, config: SewyV2Config, layer_idx: Optional[int] = None):
836
+ super().__init__()
837
+ self.config = config
838
+ self.layer_idx = layer_idx
839
+ if layer_idx is None:
840
+ logger.warning_once(
841
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
842
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
843
+ "when creating this class."
844
+ )
845
+
846
+ self.attention_dropout = config.attention_dropout
847
+ self.hidden_size = config.hidden_size
848
+ self.num_heads = config.num_attention_heads
849
+
850
+ self.max_position_embeddings = config.max_position_embeddings
851
+ self.rope_theta = config.rope_theta
852
+ self.q_lora_rank = config.q_lora_rank
853
+ self.qk_rope_head_dim = config.qk_rope_head_dim
854
+ self.kv_lora_rank = config.kv_lora_rank
855
+ self.v_head_dim = config.v_head_dim
856
+ self.qk_nope_head_dim = config.qk_nope_head_dim
857
+ self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
858
+
859
+ self.unit_norm_eps = config.unit_norm_eps
860
+
861
+ self.is_causal = True
862
+
863
+ if self.q_lora_rank is None:
864
+ self.q_proj = nn.Linear(
865
+ self.hidden_size, self.num_heads * self.q_head_dim, bias=False
866
+ )
867
+ else:
868
+ self.q_a_proj = nn.Linear(
869
+ self.hidden_size, config.q_lora_rank, bias=config.attention_bias
870
+ )
871
+ # self.q_a_layernorm = SewyV2RMSNorm(config.q_lora_rank)
872
+ self.q_b_proj = nn.Linear(
873
+ config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
874
+ )
875
+
876
+ self.kv_a_proj_with_mqa = nn.Linear(
877
+ self.hidden_size,
878
+ config.kv_lora_rank + config.qk_rope_head_dim,
879
+ bias=config.attention_bias,
880
+ )
881
+ # self.kv_a_layernorm = SewyV2RMSNorm(config.kv_lora_rank)
882
+ self.kv_b_proj = nn.Linear(
883
+ config.kv_lora_rank,
884
+ self.num_heads
885
+ * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
886
+ bias=False,
887
+ )
888
+
889
+ self.o_proj = nn.Linear(
890
+ self.num_heads * self.v_head_dim,
891
+ self.hidden_size,
892
+ bias=config.attention_bias,
893
+ )
894
+ self._init_rope()
895
+ ## nGPT
896
+ self.softmax_scale = self.q_head_dim ** (0.5)
897
+ if self.config.rope_scaling is not None:
898
+ mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
899
+ scaling_factor = self.config.rope_scaling["factor"]
900
+ if mscale_all_dim:
901
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
902
+ self.softmax_scale = self.softmax_scale * mscale * mscale
903
+
904
+ # Initialize trainable scaling factors for each head
905
+ self.s_qk = nn.Parameter(torch.ones(config.num_attention_heads)/config.hidden_size**0.5)
906
+ self.s_qk_init = 1
907
+ self.s_qk_scale = 1/config.hidden_size**0.5
908
+
909
+
910
+ self.resformer_lambda = nn.Parameter(torch.tensor(float(config.resformer_lambda)))
911
+
912
+ self.neutreno_lambda = nn.Parameter(torch.tensor(float(config.neutreno_lambda)))
913
+
914
+ self.attn_logit_softcapping = self.config.attn_logit_softcapping
915
+
916
+
917
+ def _get_unit_norm(self, x,eps=1e-6):
918
+ """
919
+ Normalize a tensor to unit norm
920
+ x: tensor to normalize [batch_size, num_heads, seq_length, head_dim]
921
+ """
922
+ # Calculate norm along head dimension
923
+ norm = torch.norm(x, p=2, dim=-1, keepdim=True)
924
+ # Add small epsilon to avoid division by zero
925
+ # Normalize
926
+ return x / norm + eps
927
+
928
+ def _init_rope(self):
929
+ if self.config.rope_scaling is None:
930
+ self.rotary_emb = SewyV2RotaryEmbedding(
931
+ self.qk_rope_head_dim,
932
+ max_position_embeddings=self.max_position_embeddings,
933
+ base=self.rope_theta,
934
+ )
935
+ else:
936
+ scaling_type = self.config.rope_scaling["type"]
937
+ scaling_factor = self.config.rope_scaling["factor"]
938
+ if scaling_type == "linear":
939
+ self.rotary_emb = SewyV2LinearScalingRotaryEmbedding(
940
+ self.qk_rope_head_dim,
941
+ max_position_embeddings=self.max_position_embeddings,
942
+ scaling_factor=scaling_factor,
943
+ base=self.rope_theta,
944
+ )
945
+ elif scaling_type == "dynamic":
946
+ self.rotary_emb = SewyV2DynamicNTKScalingRotaryEmbedding(
947
+ self.qk_rope_head_dim,
948
+ max_position_embeddings=self.max_position_embeddings,
949
+ scaling_factor=scaling_factor,
950
+ base=self.rope_theta,
951
+ )
952
+ elif scaling_type == "yarn":
953
+ kwargs = {
954
+ key: self.config.rope_scaling[key]
955
+ for key in [
956
+ "original_max_position_embeddings",
957
+ "beta_fast",
958
+ "beta_slow",
959
+ "mscale",
960
+ "mscale_all_dim",
961
+ ]
962
+ if key in self.config.rope_scaling
963
+ }
964
+ self.rotary_emb = SewyV2YarnRotaryEmbedding(
965
+ self.qk_rope_head_dim,
966
+ max_position_embeddings=self.max_position_embeddings,
967
+ scaling_factor=scaling_factor,
968
+ base=self.rope_theta,
969
+ **kwargs,
970
+ )
971
+ else:
972
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
973
+
974
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
975
+ return (
976
+ tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
977
+ .transpose(1, 2)
978
+ .contiguous()
979
+ )
980
+
981
+ def forward(
982
+ self,
983
+ hidden_states: torch.Tensor,
984
+ attention_mask: Optional[torch.Tensor] = None,
985
+ position_ids: Optional[torch.LongTensor] = None,
986
+ past_key_value: Optional[Cache] = None,
987
+ output_attentions: bool = False,
988
+ use_cache: bool = False,
989
+ formal_layer_values: Optional[list] = None,
990
+ **kwargs,
991
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
992
+ if "padding_mask" in kwargs:
993
+ warnings.warn(
994
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
995
+ )
996
+ bsz, q_len, _ = hidden_states.size()
997
+
998
+ if self.q_lora_rank is None:
999
+ q = self.q_proj(hidden_states)
1000
+ else:
1001
+ q = self.q_b_proj(self.q_a_proj(hidden_states))
1002
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
1003
+ q_nope, q_pe = torch.split(
1004
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
1005
+ )
1006
+
1007
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
1008
+ compressed_kv, k_pe = torch.split(
1009
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
1010
+ )
1011
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
1012
+ kv = (
1013
+ self.kv_b_proj(compressed_kv)
1014
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
1015
+ .transpose(1, 2)
1016
+ )
1017
+
1018
+ k_nope, value_states = torch.split(
1019
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
1020
+ )
1021
+
1022
+
1023
+ ### Resformer Neutreno
1024
+
1025
+ if self.layer_idx == 0:
1026
+ formal_layer_values.append(value_states)
1027
+ else:
1028
+ value_states = 0.5*formal_layer_values[0] + self.resformer_lambda*value_states
1029
+ current_value = value_states
1030
+
1031
+
1032
+ kv_seq_len = value_states.shape[-2]
1033
+ if past_key_value is not None:
1034
+ if self.layer_idx is None:
1035
+ raise ValueError(
1036
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
1037
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
1038
+ "with a layer index."
1039
+ )
1040
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1041
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1042
+
1043
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
1044
+
1045
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1046
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
1047
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
1048
+
1049
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1050
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
1051
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
1052
+ if past_key_value is not None:
1053
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1054
+ key_states, value_states = past_key_value.update(
1055
+ key_states, value_states, self.layer_idx, cache_kwargs
1056
+ )
1057
+
1058
+ ### nGPT
1059
+
1060
+ key_states = self._get_unit_norm(key_states)
1061
+ query_states = self._get_unit_norm(query_states)
1062
+
1063
+ ## Add the scaling factor to the query and key states
1064
+
1065
+ s_qk = self.s_qk * (self.s_qk_init/self.s_qk_scale)
1066
+
1067
+ key_states = key_states * s_qk.view(1, -1, 1, 1)
1068
+ query_states = query_states * s_qk.view(1, -1, 1, 1)
1069
+
1070
+
1071
+
1072
+
1073
+ attn_weights = (
1074
+ torch.matmul(query_states, key_states.transpose(2, 3)) * self.softmax_scale
1075
+ )
1076
+
1077
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
1078
+ raise ValueError(
1079
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
1080
+ f" {attn_weights.size()}"
1081
+ )
1082
+ assert attention_mask is not None
1083
+ if attention_mask is not None:
1084
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
1085
+ raise ValueError(
1086
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
1087
+ )
1088
+ attn_weights = attn_weights + attention_mask
1089
+
1090
+ ## tanh softcapping
1091
+
1092
+ attn_weights = self.attn_logit_softcapping * torch.tanh(attn_weights/self.attn_logit_softcapping)
1093
+
1094
+ # upcast attention to fp32
1095
+ attn_weights = nn.functional.softmax(
1096
+ attn_weights, dim=-1, dtype=torch.float32
1097
+ ).to(query_states.dtype)
1098
+ attn_weights = nn.functional.dropout(
1099
+ attn_weights, p=self.attention_dropout, training=self.training
1100
+ )
1101
+ attn_output = torch.matmul(attn_weights, value_states)
1102
+
1103
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
1104
+ raise ValueError(
1105
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
1106
+ f" {attn_output.size()}"
1107
+ )
1108
+
1109
+ # print("attn_output shape before reshape", attn_output.shape)
1110
+
1111
+
1112
+ ## neutreno
1113
+
1114
+ if self.layer_idx != 0:
1115
+ # print("formal_layer_values shape", formal_layer_values[0].shape)
1116
+ # print("current_value shape", current_value.shape)
1117
+ # print("attn_output shape", attn_output.shape)
1118
+ attn_output = attn_output + self.neutreno_lambda*(formal_layer_values[0]-current_value)
1119
+
1120
+
1121
+
1122
+ attn_output = attn_output.transpose(1, 2).contiguous()
1123
+
1124
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
1125
+
1126
+ attn_output = self.o_proj(attn_output)
1127
+
1128
+ if not output_attentions:
1129
+ attn_weights = None
1130
+
1131
+ return attn_output, attn_weights, past_key_value, formal_layer_values
1132
+
1133
+
1134
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->SewyV2
1135
+ class SewyV2FlashAttention2(SewyV2Attention):
1136
+ """
1137
+ SewyV2 flash attention module. This module inherits from `SewyV2Attention` as the weights of the module stays
1138
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
1139
+ flash attention and deal with padding tokens in case the input contains any of them.
1140
+ """
1141
+
1142
+ def __init__(self, *args, **kwargs):
1143
+ super().__init__(*args, **kwargs)
1144
+
1145
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
1146
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
1147
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
1148
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
1149
+
1150
+ def forward(
1151
+ self,
1152
+ hidden_states: torch.Tensor,
1153
+ attention_mask: Optional[torch.LongTensor] = None,
1154
+ position_ids: Optional[torch.LongTensor] = None,
1155
+ past_key_value: Optional[Cache] = None,
1156
+ output_attentions: bool = False,
1157
+ use_cache: bool = False,
1158
+ formal_layer_values: Optional[list] = None,
1159
+
1160
+ **kwargs,
1161
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1162
+ # SewyV2FlashAttention2 attention does not support output_attentions
1163
+ if "padding_mask" in kwargs:
1164
+ warnings.warn(
1165
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1166
+ )
1167
+
1168
+ # overwrite attention_mask with padding_mask
1169
+ attention_mask = kwargs.pop("padding_mask")
1170
+
1171
+ output_attentions = False
1172
+
1173
+ bsz, q_len, _ = hidden_states.size()
1174
+
1175
+ if self.q_lora_rank is None:
1176
+ q = self.q_proj(hidden_states)
1177
+ else:
1178
+ q = self.q_b_proj(self.q_a_proj(hidden_states))
1179
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
1180
+ q_nope, q_pe = torch.split(
1181
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
1182
+ )
1183
+
1184
+ # Flash attention requires the input to have the shape
1185
+ # batch_size x seq_length x head_dim x hidden_dim
1186
+ # therefore we just need to keep the original shape
1187
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
1188
+ compressed_kv, k_pe = torch.split(
1189
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
1190
+ )
1191
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
1192
+ kv = (
1193
+ self.kv_b_proj(compressed_kv)
1194
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
1195
+ .transpose(1, 2)
1196
+ )
1197
+
1198
+ k_nope, value_states = torch.split(
1199
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
1200
+ )
1201
+
1202
+ ## Resformer Neutreno
1203
+
1204
+ if self.layer_idx == 0:
1205
+ formal_layer_values.append(value_states)
1206
+ else:
1207
+ value_states = 0.5*formal_layer_values[0] + self.resformer_lambda*value_states
1208
+ current_value = value_states
1209
+
1210
+ kv_seq_len = value_states.shape[-2]
1211
+
1212
+ kv_seq_len = value_states.shape[-2]
1213
+ if past_key_value is not None:
1214
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1215
+
1216
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1217
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
1218
+
1219
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1220
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
1221
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
1222
+
1223
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
1224
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
1225
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
1226
+
1227
+ if self.q_head_dim != self.v_head_dim:
1228
+ value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
1229
+
1230
+ if past_key_value is not None:
1231
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1232
+ key_states, value_states = past_key_value.update(
1233
+ key_states, value_states, self.layer_idx, cache_kwargs
1234
+ )
1235
+
1236
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
1237
+ # to be able to avoid many of these transpose/reshape/view.
1238
+ query_states = query_states.transpose(1, 2)
1239
+ key_states = key_states.transpose(1, 2)
1240
+ value_states = value_states.transpose(1, 2)
1241
+
1242
+ dropout_rate = self.attention_dropout if self.training else 0.0
1243
+
1244
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
1245
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
1246
+ # cast them back in the correct dtype just to be sure everything works as expected.
1247
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
1248
+ # in fp32. (SewyV2RMSNorm handles it correctly)
1249
+
1250
+ input_dtype = query_states.dtype
1251
+ if input_dtype == torch.float32:
1252
+ # Handle the case where the model is quantized
1253
+ if hasattr(self.config, "_pre_quantization_dtype"):
1254
+ target_dtype = self.config._pre_quantization_dtype
1255
+ elif torch.is_autocast_enabled():
1256
+ target_dtype = torch.get_autocast_gpu_dtype()
1257
+ else:
1258
+ target_dtype = (
1259
+ self.q_proj.weight.dtype
1260
+ if self.q_lora_rank is None
1261
+ else self.q_a_proj.weight.dtype
1262
+ )
1263
+
1264
+ logger.warning_once(
1265
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
1266
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
1267
+ f" {target_dtype}."
1268
+ )
1269
+
1270
+ query_states = query_states.to(target_dtype)
1271
+ key_states = key_states.to(target_dtype)
1272
+ value_states = value_states.to(target_dtype)
1273
+
1274
+ ## nGPT
1275
+ key_states = self._get_unit_norm(key_states)
1276
+ query_states = self._get_unit_norm(query_states)
1277
+
1278
+ ## Add the scaling factor to the query and key states
1279
+
1280
+ s_qk = self.s_qk * (self.s_qk_init/self.s_qk_scale)
1281
+
1282
+ key_states = key_states * s_qk.view(1, -1, 1, 1)
1283
+ query_states = query_states * s_qk.view(1, -1, 1, 1)
1284
+
1285
+ attn_output = self._flash_attention_forward(
1286
+ query_states,
1287
+ key_states,
1288
+ value_states,
1289
+ attention_mask,
1290
+ q_len,
1291
+ dropout=dropout_rate,
1292
+ softmax_scale=self.softmax_scale,
1293
+ softcap=self.attn_logit_softcapping,
1294
+ )
1295
+ if self.q_head_dim != self.v_head_dim:
1296
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
1297
+
1298
+ attn_output = attn_output.reshape(
1299
+ bsz, q_len, self.num_heads * self.v_head_dim
1300
+ ).contiguous()
1301
+
1302
+ ## neutreno
1303
+ if self.layer_idx != 0:
1304
+ attn_output = attn_output + self.neutreno_lambda*(formal_layer_values[0]-current_value)
1305
+
1306
+
1307
+ attn_output = self.o_proj(attn_output)
1308
+
1309
+ if not output_attentions:
1310
+ attn_weights = None
1311
+
1312
+ return attn_output, attn_weights, past_key_value, formal_layer_values
1313
+
1314
+ def _flash_attention_forward(
1315
+ self,
1316
+ query_states,
1317
+ key_states,
1318
+ value_states,
1319
+ attention_mask,
1320
+ query_length,
1321
+ dropout=0.0,
1322
+ softmax_scale=None,
1323
+ ):
1324
+ """
1325
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1326
+ first unpad the input, then computes the attention scores and pad the final attention scores.
1327
+
1328
+ Args:
1329
+ query_states (`torch.Tensor`):
1330
+ Input query states to be passed to Flash Attention API
1331
+ key_states (`torch.Tensor`):
1332
+ Input key states to be passed to Flash Attention API
1333
+ value_states (`torch.Tensor`):
1334
+ Input value states to be passed to Flash Attention API
1335
+ attention_mask (`torch.Tensor`):
1336
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1337
+ position of padding tokens and 1 for the position of non-padding tokens.
1338
+ dropout (`int`, *optional*):
1339
+ Attention dropout
1340
+ softmax_scale (`float`, *optional*):
1341
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1342
+ """
1343
+ if not self._flash_attn_uses_top_left_mask:
1344
+ causal = self.is_causal
1345
+ else:
1346
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in SewyV2FlashAttention2 __init__.
1347
+ causal = self.is_causal and query_length != 1
1348
+
1349
+ # Contains at least one padding token in the sequence
1350
+ if attention_mask is not None:
1351
+ batch_size = query_states.shape[0]
1352
+ (
1353
+ query_states,
1354
+ key_states,
1355
+ value_states,
1356
+ indices_q,
1357
+ cu_seq_lens,
1358
+ max_seq_lens,
1359
+ ) = self._upad_input(
1360
+ query_states, key_states, value_states, attention_mask, query_length
1361
+ )
1362
+
1363
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1364
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1365
+
1366
+ attn_output_unpad = flash_attn_varlen_func(
1367
+ query_states,
1368
+ key_states,
1369
+ value_states,
1370
+ cu_seqlens_q=cu_seqlens_q,
1371
+ cu_seqlens_k=cu_seqlens_k,
1372
+ max_seqlen_q=max_seqlen_in_batch_q,
1373
+ max_seqlen_k=max_seqlen_in_batch_k,
1374
+ dropout_p=dropout,
1375
+ softmax_scale=softmax_scale,
1376
+ causal=causal,
1377
+ )
1378
+
1379
+ attn_output = pad_input(
1380
+ attn_output_unpad, indices_q, batch_size, query_length
1381
+ )
1382
+ else:
1383
+ attn_output = flash_attn_func(
1384
+ query_states,
1385
+ key_states,
1386
+ value_states,
1387
+ dropout,
1388
+ softmax_scale=softmax_scale,
1389
+ causal=causal,
1390
+ )
1391
+
1392
+ return attn_output
1393
+
1394
+ def _upad_input(
1395
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
1396
+ ):
1397
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
1398
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
1399
+
1400
+ key_layer = index_first_axis(
1401
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1402
+ indices_k,
1403
+ )
1404
+ value_layer = index_first_axis(
1405
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1406
+ indices_k,
1407
+ )
1408
+ if query_length == kv_seq_len:
1409
+ query_layer = index_first_axis(
1410
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
1411
+ indices_k,
1412
+ )
1413
+ cu_seqlens_q = cu_seqlens_k
1414
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1415
+ indices_q = indices_k
1416
+ elif query_length == 1:
1417
+ max_seqlen_in_batch_q = 1
1418
+ cu_seqlens_q = torch.arange(
1419
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1420
+ ) # There is a memcpy here, that is very bad.
1421
+ indices_q = cu_seqlens_q[:-1]
1422
+ query_layer = query_layer.squeeze(1)
1423
+ else:
1424
+ # The -q_len: slice assumes left padding.
1425
+ attention_mask = attention_mask[:, -query_length:]
1426
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
1427
+ query_layer, attention_mask
1428
+ )
1429
+
1430
+ return (
1431
+ query_layer,
1432
+ key_layer,
1433
+ value_layer,
1434
+ indices_q,
1435
+ (cu_seqlens_q, cu_seqlens_k),
1436
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1437
+ )
1438
+
1439
+
1440
+ ATTENTION_CLASSES = {
1441
+ "eager": SewyV2Attention,
1442
+ "flash_attention_2": SewyV2FlashAttention2,
1443
+ }
1444
+
1445
+
1446
+ class SewyV2DecoderLayer(nn.Module):
1447
+ def __init__(self, config: SewyV2Config, layer_idx: int):
1448
+ super().__init__()
1449
+ self.hidden_size = config.hidden_size
1450
+
1451
+ self.self_attn = ATTENTION_CLASSES[config._attn_implementation](
1452
+ config=config, layer_idx=layer_idx
1453
+ )
1454
+
1455
+ self.mlp = (
1456
+ SewyV2MoE(config)
1457
+ if (
1458
+ config.n_routed_experts is not None
1459
+ and layer_idx >= config.first_k_dense_replace
1460
+ and layer_idx % config.moe_layer_freq == 0
1461
+ )
1462
+ else SewyV2MLP(config)
1463
+ )
1464
+ # self.input_layernorm = SewyV2RMSNorm(
1465
+ # config.hidden_size, eps=config.rms_norm_eps
1466
+ # )
1467
+ # self.post_attention_layernorm = SewyV2RMSNorm(
1468
+ # config.hidden_size, eps=config.rms_norm_eps
1469
+ # )
1470
+
1471
+ self.alpha_attenion = nn.Parameter(torch.ones(config.hidden_size) / config.num_hidden_layers)
1472
+
1473
+ self.alpha_mlp = nn.Parameter(torch.ones(config.hidden_size) / config.num_hidden_layers)
1474
+
1475
+ self.alpha_attenion_init = 1/config.num_hidden_layers
1476
+ self.alpha_mlp_init = 1/config.num_hidden_layers
1477
+
1478
+ self.alpha_attenion_scale = 1/config.hidden_size ** 0.5
1479
+ self.alpha_mlp_scale = 1/config.hidden_size ** 0.5
1480
+
1481
+
1482
+
1483
+
1484
+
1485
+
1486
+ def _get_unit_norm(self, x, eps=1e-6):
1487
+ """
1488
+ Normalize a tensor to unit norm
1489
+ x: tensor to normalize [batch_size, num_heads, seq_length, head_dim]
1490
+ """
1491
+ # Calculate norm along head dimension
1492
+ norm = torch.norm(x, p=2, dim=-1, keepdim=True)
1493
+ # Add small epsilon to avoid division by zero
1494
+ norm = norm + eps
1495
+ # Normalize
1496
+ return x / norm
1497
+
1498
+ def forward(
1499
+ self,
1500
+ hidden_states: torch.Tensor,
1501
+ attention_mask: Optional[torch.Tensor] = None,
1502
+ position_ids: Optional[torch.LongTensor] = None,
1503
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1504
+ output_attentions: Optional[bool] = False,
1505
+ use_cache: Optional[bool] = False,
1506
+ formal_layer_values: Optional[list] = None,
1507
+
1508
+ **kwargs,
1509
+ ) -> Tuple[
1510
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1511
+ ]:
1512
+ """
1513
+ Args:
1514
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1515
+ attention_mask (`torch.FloatTensor`, *optional*):
1516
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1517
+ query_sequence_length, key_sequence_length)` if default attention is used.
1518
+ output_attentions (`bool`, *optional*):
1519
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1520
+ returned tensors for more detail.
1521
+ use_cache (`bool`, *optional*):
1522
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1523
+ (see `past_key_values`).
1524
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1525
+ """
1526
+ if "padding_mask" in kwargs:
1527
+ warnings.warn(
1528
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1529
+ )
1530
+ residual = hidden_states
1531
+
1532
+ # hidden_states = self.input_layernorm(hidden_states)
1533
+
1534
+ # Self Attention
1535
+ hidden_states, self_attn_weights, present_key_value,formal_layer_values = self.self_attn(
1536
+ hidden_states=hidden_states,
1537
+ attention_mask=attention_mask,
1538
+ position_ids=position_ids,
1539
+ past_key_value=past_key_value,
1540
+ output_attentions=output_attentions,
1541
+ use_cache=use_cache,
1542
+ formal_layer_values=formal_layer_values,
1543
+ **kwargs,
1544
+ )
1545
+
1546
+ ## nGPT
1547
+
1548
+ alpha_attention = self.alpha_attenion * (self.alpha_attenion_init/self.alpha_attenion_scale)
1549
+ hidden_states = self._get_unit_norm(hidden_states)
1550
+
1551
+ hidden_states = self._get_unit_norm(residual + alpha_attention.view(1, 1, -1) * (hidden_states - residual))
1552
+
1553
+ # Fully Connected
1554
+ residual = hidden_states
1555
+ # hidden_states = self.post_attention_layernorm(hidden_states)
1556
+ hidden_states = self.mlp(hidden_states)
1557
+
1558
+ ## nGPT
1559
+
1560
+ alpha_mlp = self.alpha_mlp * (self.alpha_mlp_init/self.alpha_mlp_scale)
1561
+
1562
+ hidden_states = self._get_unit_norm(hidden_states)
1563
+
1564
+ hidden_states = self._get_unit_norm(residual + alpha_mlp.view(1, 1, -1) * (hidden_states - residual))
1565
+
1566
+
1567
+ outputs = (hidden_states,)
1568
+
1569
+ if output_attentions:
1570
+ outputs += (self_attn_weights,)
1571
+
1572
+ if use_cache:
1573
+ outputs += (present_key_value,)
1574
+
1575
+ return outputs, formal_layer_values
1576
+
1577
+
1578
+ SewyV2_START_DOCSTRING = r"""
1579
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1580
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1581
+ etc.)
1582
+
1583
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1584
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1585
+ and behavior.
1586
+
1587
+ Parameters:
1588
+ config ([`SewyV2Config`]):
1589
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1590
+ load the weights associated with the model, only the configuration. Check out the
1591
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1592
+ """
1593
+
1594
+
1595
+ @add_start_docstrings(
1596
+ "The bare SewyV2 Model outputting raw hidden-states without any specific head on top.",
1597
+ SewyV2_START_DOCSTRING,
1598
+ )
1599
+ class SewyV2PreTrainedModel(PreTrainedModel):
1600
+ config_class = SewyV2Config
1601
+ base_model_prefix = "model"
1602
+ supports_gradient_checkpointing = True
1603
+ _no_split_modules = ["SewyV2DecoderLayer"]
1604
+ _skip_keys_device_placement = "past_key_values"
1605
+ _supports_flash_attn_2 = True
1606
+ _supports_cache_class = True
1607
+
1608
+ def _init_weights(self, module):
1609
+ std = self.config.initializer_range
1610
+ if isinstance(module, nn.Linear):
1611
+ module.weight.data.normal_(mean=0.0, std=std)
1612
+ if module.bias is not None:
1613
+ module.bias.data.zero_()
1614
+ elif isinstance(module, nn.Embedding):
1615
+ module.weight.data.normal_(mean=0.0, std=std)
1616
+ if module.padding_idx is not None:
1617
+ module.weight.data[module.padding_idx].zero_()
1618
+
1619
+
1620
+ SewyV2_INPUTS_DOCSTRING = r"""
1621
+ Args:
1622
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1623
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1624
+ it.
1625
+
1626
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1627
+ [`PreTrainedTokenizer.__call__`] for details.
1628
+
1629
+ [What are input IDs?](../glossary#input-ids)
1630
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1631
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1632
+
1633
+ - 1 for tokens that are **not masked**,
1634
+ - 0 for tokens that are **masked**.
1635
+
1636
+ [What are attention masks?](../glossary#attention-mask)
1637
+
1638
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1639
+ [`PreTrainedTokenizer.__call__`] for details.
1640
+
1641
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1642
+ `past_key_values`).
1643
+
1644
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1645
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1646
+ information on the default strategy.
1647
+
1648
+ - 1 indicates the head is **not masked**,
1649
+ - 0 indicates the head is **masked**.
1650
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1651
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1652
+ config.n_positions - 1]`.
1653
+
1654
+ [What are position IDs?](../glossary#position-ids)
1655
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1656
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1657
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1658
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1659
+
1660
+ Two formats are allowed:
1661
+ - a [`~cache_utils.Cache`] instance;
1662
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1663
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1664
+ cache format.
1665
+
1666
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1667
+ legacy cache format will be returned.
1668
+
1669
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1670
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1671
+ of shape `(batch_size, sequence_length)`.
1672
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1673
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1674
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1675
+ model's internal embedding lookup matrix.
1676
+ use_cache (`bool`, *optional*):
1677
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1678
+ `past_key_values`).
1679
+ output_attentions (`bool`, *optional*):
1680
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1681
+ tensors for more detail.
1682
+ output_hidden_states (`bool`, *optional*):
1683
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1684
+ more detail.
1685
+ return_dict (`bool`, *optional*):
1686
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1687
+ """
1688
+
1689
+
1690
+ @add_start_docstrings(
1691
+ "The bare SewyV2 Model outputting raw hidden-states without any specific head on top.",
1692
+ SewyV2_START_DOCSTRING,
1693
+ )
1694
+ class SewyV2Model(SewyV2PreTrainedModel):
1695
+ """
1696
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`SewyV2DecoderLayer`]
1697
+
1698
+ Args:
1699
+ config: SewyV2Config
1700
+ """
1701
+
1702
+ def __init__(self, config: SewyV2Config):
1703
+ super().__init__(config)
1704
+ self.padding_idx = config.pad_token_id
1705
+ self.vocab_size = config.vocab_size
1706
+
1707
+ self.embed_tokens = nn.Embedding(
1708
+ config.vocab_size, config.hidden_size, self.padding_idx
1709
+ )
1710
+ self.layers = nn.ModuleList(
1711
+ [
1712
+ SewyV2DecoderLayer(config, layer_idx)
1713
+ for layer_idx in range(config.num_hidden_layers)
1714
+ ]
1715
+ )
1716
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1717
+ # self.norm = SewyV2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1718
+
1719
+ self.gradient_checkpointing = False
1720
+ # Initialize weights and apply final processing
1721
+ self.post_init()
1722
+
1723
+ def get_input_embeddings(self):
1724
+ return self.embed_tokens
1725
+
1726
+ def set_input_embeddings(self, value):
1727
+ self.embed_tokens = value
1728
+
1729
+ @add_start_docstrings_to_model_forward(SewyV2_INPUTS_DOCSTRING)
1730
+ def forward(
1731
+ self,
1732
+ input_ids: torch.LongTensor = None,
1733
+ attention_mask: Optional[torch.Tensor] = None,
1734
+ position_ids: Optional[torch.LongTensor] = None,
1735
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1736
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1737
+ use_cache: Optional[bool] = None,
1738
+ output_attentions: Optional[bool] = None,
1739
+ output_hidden_states: Optional[bool] = None,
1740
+ return_dict: Optional[bool] = None,
1741
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1742
+ output_attentions = (
1743
+ output_attentions
1744
+ if output_attentions is not None
1745
+ else self.config.output_attentions
1746
+ )
1747
+ output_hidden_states = (
1748
+ output_hidden_states
1749
+ if output_hidden_states is not None
1750
+ else self.config.output_hidden_states
1751
+ )
1752
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1753
+
1754
+ return_dict = (
1755
+ return_dict if return_dict is not None else self.config.use_return_dict
1756
+ )
1757
+
1758
+ # retrieve input_ids and inputs_embeds
1759
+ if input_ids is not None and inputs_embeds is not None:
1760
+ raise ValueError(
1761
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1762
+ )
1763
+ elif input_ids is not None:
1764
+ batch_size, seq_length = input_ids.shape[:2]
1765
+ elif inputs_embeds is not None:
1766
+ batch_size, seq_length = inputs_embeds.shape[:2]
1767
+ else:
1768
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1769
+
1770
+ past_key_values_length = 0
1771
+ if use_cache:
1772
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1773
+ if use_legacy_cache:
1774
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1775
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1776
+
1777
+ if position_ids is None:
1778
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1779
+ position_ids = torch.arange(
1780
+ past_key_values_length,
1781
+ seq_length + past_key_values_length,
1782
+ dtype=torch.long,
1783
+ device=device,
1784
+ )
1785
+ position_ids = position_ids.unsqueeze(0)
1786
+
1787
+ if inputs_embeds is None:
1788
+ inputs_embeds = self.embed_tokens(input_ids)
1789
+
1790
+ if self._use_flash_attention_2:
1791
+ # 2d mask is passed through the layers
1792
+ attention_mask = (
1793
+ attention_mask
1794
+ if (attention_mask is not None and 0 in attention_mask)
1795
+ else None
1796
+ )
1797
+ else:
1798
+ # 4d mask is passed through the layers
1799
+ attention_mask = _prepare_4d_causal_attention_mask(
1800
+ attention_mask,
1801
+ (batch_size, seq_length),
1802
+ inputs_embeds,
1803
+ past_key_values_length,
1804
+ )
1805
+
1806
+ # embed positions
1807
+ hidden_states = inputs_embeds
1808
+
1809
+ # decoder layers
1810
+ all_hidden_states = () if output_hidden_states else None
1811
+ all_self_attns = () if output_attentions else None
1812
+ next_decoder_cache = None
1813
+
1814
+ formal_layer_values = []
1815
+
1816
+ for decoder_layer in self.layers:
1817
+ if output_hidden_states:
1818
+ all_hidden_states += (hidden_states,)
1819
+
1820
+ layer_outputs,formal_layer_values = decoder_layer(
1821
+ hidden_states,
1822
+ attention_mask=attention_mask,
1823
+ position_ids=position_ids,
1824
+ past_key_value=past_key_values,
1825
+ output_attentions=output_attentions,
1826
+ use_cache=use_cache,
1827
+ formal_layer_values=formal_layer_values,
1828
+
1829
+ )
1830
+
1831
+ hidden_states = layer_outputs[0]
1832
+
1833
+ if use_cache:
1834
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1835
+
1836
+ if output_attentions:
1837
+ all_self_attns += (layer_outputs[1],)
1838
+
1839
+ # hidden_states = self.norm(hidden_states)
1840
+
1841
+ # add hidden states from the last decoder layer
1842
+ if output_hidden_states:
1843
+ all_hidden_states += (hidden_states,)
1844
+
1845
+ next_cache = None
1846
+ if use_cache:
1847
+ next_cache = (
1848
+ next_decoder_cache.to_legacy_cache()
1849
+ if use_legacy_cache
1850
+ else next_decoder_cache
1851
+ )
1852
+ if not return_dict:
1853
+ return tuple(
1854
+ v
1855
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1856
+ if v is not None
1857
+ )
1858
+ return BaseModelOutputWithPast(
1859
+ last_hidden_state=hidden_states,
1860
+ past_key_values=next_cache,
1861
+ hidden_states=all_hidden_states,
1862
+ attentions=all_self_attns,
1863
+ )
1864
+
1865
+
1866
+ class SewyV2ForCausalLM(SewyV2PreTrainedModel):
1867
+ _tied_weights_keys = ["lm_head.weight"]
1868
+
1869
+ def __init__(self, config):
1870
+ super().__init__(config)
1871
+ self.model = SewyV2Model(config)
1872
+ self.vocab_size = config.vocab_size
1873
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1874
+
1875
+ ## nGPT
1876
+
1877
+ self.s_z = nn.Parameter(torch.ones(self.vocab_size) * (1/config.hidden_size ** 0.5))
1878
+ self.s_z_init = 1
1879
+ self.s_z_scale = 1/config.hidden_size ** 0.5
1880
+
1881
+ # tanh softcapping
1882
+
1883
+ self.tanh_softcapping = config.final_logit_softcapping
1884
+ # Initialize weights and apply final processing
1885
+ self.post_init()
1886
+
1887
+ def get_input_embeddings(self):
1888
+ return self.model.embed_tokens
1889
+
1890
+ def set_input_embeddings(self, value):
1891
+ self.model.embed_tokens = value
1892
+
1893
+ def get_output_embeddings(self):
1894
+ return self.lm_head
1895
+
1896
+ def set_output_embeddings(self, new_embeddings):
1897
+ self.lm_head = new_embeddings
1898
+
1899
+ def set_decoder(self, decoder):
1900
+ self.model = decoder
1901
+
1902
+ def get_decoder(self):
1903
+ return self.model
1904
+
1905
+ ## TODO: Normalize all weights along embedding dimension.
1906
+
1907
+ def _get_unit_norm(self, x, eps=1e-6):
1908
+ """
1909
+ Normalize a tensor to unit norm along embedding dimension (last dimension)
1910
+ x: tensor to normalize [*dims, hidden_dim]
1911
+ """
1912
+ # Calculate norm along embedding dimension (last dimension)
1913
+ norm = torch.norm(x, p=2, dim=-1, keepdim=True)
1914
+ # Add small epsilon to avoid division by zero
1915
+ norm = norm + eps
1916
+ # Normalize
1917
+ return x / norm
1918
+
1919
+ def normalize_model(self):
1920
+ """Normalize all projection matrices and embeddings to have unit norm along hidden dimension"""
1921
+ # Normalize embeddings
1922
+ self.model.embed_tokens.weight.data = self._get_unit_norm(self.model.embed_tokens.weight.data.T).T
1923
+ self.lm_head.weight.data = self._get_unit_norm(self.lm_head.weight.data.T).T
1924
+
1925
+ # Normalize all layers
1926
+ for layer in self.model.layers:
1927
+ # Normalize attention projections
1928
+ # Q projections
1929
+ if hasattr(layer.self_attn, 'q_proj'):
1930
+ layer.self_attn.q_proj.weight.data = self._get_unit_norm(layer.self_attn.q_proj.weight.data.T).T
1931
+ else:
1932
+ layer.self_attn.q_a_proj.weight.data = self._get_unit_norm(layer.self_attn.q_a_proj.weight.data.T).T
1933
+ layer.self_attn.q_b_proj.weight.data = self._get_unit_norm(layer.self_attn.q_b_proj.weight.data.T).T
1934
+
1935
+ # KV projections
1936
+ layer.self_attn.kv_a_proj_with_mqa.weight.data = self._get_unit_norm(layer.self_attn.kv_a_proj_with_mqa.weight.data.T).T
1937
+ layer.self_attn.kv_b_proj.weight.data = self._get_unit_norm(layer.self_attn.kv_b_proj.weight.data.T).T
1938
+
1939
+ # Output projection
1940
+ layer.self_attn.o_proj.weight.data = self._get_unit_norm(layer.self_attn.o_proj.weight.data.T).T
1941
+
1942
+ # Normalize MLP/MoE projections
1943
+ if isinstance(layer.mlp, SewyV2MoE):
1944
+ # print("moe is here")
1945
+ # Normalize experts
1946
+ for expert in layer.mlp.experts:
1947
+ # print("expert is here")
1948
+ if expert is not None: # Handle distributed case where some experts are None
1949
+ expert.gate_proj.weight.data = self._get_unit_norm(expert.gate_proj.weight.data.T).T
1950
+ expert.up_proj.weight.data = self._get_unit_norm(expert.up_proj.weight.data.T).T
1951
+ expert.down_proj.weight.data = self._get_unit_norm(expert.down_proj.weight.data.T).T
1952
+ # Normalize shared experts
1953
+ if hasattr(layer.mlp, 'shared_experts'):
1954
+ # print("shared expert is here")
1955
+ layer.mlp.shared_experts.gate_proj.weight.data = self._get_unit_norm(layer.mlp.shared_experts.gate_proj.weight.data.T).T
1956
+ layer.mlp.shared_experts.up_proj.weight.data = self._get_unit_norm(layer.mlp.shared_experts.up_proj.weight.data.T).T
1957
+ layer.mlp.shared_experts.down_proj.weight.data = self._get_unit_norm(layer.mlp.shared_experts.down_proj.weight.data.T).T
1958
+ else:
1959
+ layer.mlp.gate_proj.weight.data = self._get_unit_norm(layer.mlp.gate_proj.weight.data.T).T
1960
+ layer.mlp.up_proj.weight.data = self._get_unit_norm(layer.mlp.up_proj.weight.data.T).T
1961
+ layer.mlp.down_proj.weight.data = self._get_unit_norm(layer.mlp.down_proj.weight.data.T).T
1962
+
1963
+ @add_start_docstrings_to_model_forward(SewyV2_INPUTS_DOCSTRING)
1964
+ @replace_return_docstrings(
1965
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1966
+ )
1967
+ def forward(
1968
+ self,
1969
+ input_ids: torch.LongTensor = None,
1970
+ attention_mask: Optional[torch.Tensor] = None,
1971
+ position_ids: Optional[torch.LongTensor] = None,
1972
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1973
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1974
+ labels: Optional[torch.LongTensor] = None,
1975
+ use_cache: Optional[bool] = None,
1976
+ output_attentions: Optional[bool] = None,
1977
+ output_hidden_states: Optional[bool] = None,
1978
+ return_dict: Optional[bool] = None,
1979
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1980
+ r"""
1981
+ Args:
1982
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1983
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
1984
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1985
+ (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
1986
+
1987
+ Returns:
1988
+
1989
+ Example:
1990
+
1991
+ ```python
1992
+ >>> from transformers import AutoTokenizer, SewyV2ForCausalLM
1993
+
1994
+ >>> model = SewyV2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1995
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1996
+
1997
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1998
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1999
+
2000
+ >>> # Generate
2001
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
2002
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
2003
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
2004
+ ```"""
2005
+ output_attentions = (
2006
+ output_attentions
2007
+ if output_attentions is not None
2008
+ else self.config.output_attentions
2009
+ )
2010
+ output_hidden_states = (
2011
+ output_hidden_states
2012
+ if output_hidden_states is not None
2013
+ else self.config.output_hidden_states
2014
+ )
2015
+ return_dict = (
2016
+ return_dict if return_dict is not None else self.config.use_return_dict
2017
+ )
2018
+
2019
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
2020
+ outputs = self.model(
2021
+ input_ids=input_ids,
2022
+ attention_mask=attention_mask,
2023
+ position_ids=position_ids,
2024
+ past_key_values=past_key_values,
2025
+ inputs_embeds=inputs_embeds,
2026
+ use_cache=use_cache,
2027
+ output_attentions=output_attentions,
2028
+ output_hidden_states=output_hidden_states,
2029
+ return_dict=return_dict,
2030
+ )
2031
+
2032
+ hidden_states = outputs[0]
2033
+ logits = self.lm_head(hidden_states)
2034
+ logits = logits.float()
2035
+
2036
+ ## tanh softcapping
2037
+
2038
+ logits = self.tanh_softcapping * torch.tanh(logits/self.tanh_softcapping)
2039
+
2040
+
2041
+ ## nGPT
2042
+
2043
+ s_z = self.s_z * (self.s_z_init/self.s_z_scale)
2044
+
2045
+ s_z = s_z.to(logits.device)
2046
+
2047
+ logits = logits * s_z.view(1, 1, -1)
2048
+
2049
+ loss = None
2050
+ if labels is not None:
2051
+ # Shift so that tokens < n predict n
2052
+ shift_logits = logits[..., :-1, :].contiguous()
2053
+ shift_labels = labels[..., 1:].contiguous()
2054
+ # Flatten the tokens
2055
+ loss_fct = CrossEntropyLoss()
2056
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
2057
+ shift_labels = shift_labels.view(-1)
2058
+ # Enable model parallelism
2059
+ shift_labels = shift_labels.to(shift_logits.device)
2060
+ loss = loss_fct(shift_logits, shift_labels)
2061
+
2062
+ if not return_dict:
2063
+ output = (logits,) + outputs[1:]
2064
+ return (loss,) + output if loss is not None else output
2065
+
2066
+ return CausalLMOutputWithPast(
2067
+ loss=loss,
2068
+ logits=logits,
2069
+ past_key_values=outputs.past_key_values,
2070
+ hidden_states=outputs.hidden_states,
2071
+ attentions=outputs.attentions,
2072
+ )
2073
+
2074
+ def prepare_inputs_for_generation(
2075
+ self,
2076
+ input_ids,
2077
+ past_key_values=None,
2078
+ attention_mask=None,
2079
+ inputs_embeds=None,
2080
+ **kwargs,
2081
+ ):
2082
+ if past_key_values is not None:
2083
+ if isinstance(past_key_values, Cache):
2084
+ cache_length = past_key_values.get_seq_length()
2085
+ past_length = past_key_values.seen_tokens
2086
+ max_cache_length = past_key_values.get_max_length()
2087
+ else:
2088
+ cache_length = past_length = past_key_values[0][0].shape[2]
2089
+ max_cache_length = None
2090
+
2091
+ # Keep only the unprocessed tokens:
2092
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
2093
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
2094
+ # input)
2095
+ if (
2096
+ attention_mask is not None
2097
+ and attention_mask.shape[1] > input_ids.shape[1]
2098
+ ):
2099
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
2100
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
2101
+ # input_ids based on the past_length.
2102
+ elif past_length < input_ids.shape[1]:
2103
+ input_ids = input_ids[:, past_length:]
2104
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
2105
+
2106
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
2107
+ if (
2108
+ max_cache_length is not None
2109
+ and attention_mask is not None
2110
+ and cache_length + input_ids.shape[1] > max_cache_length
2111
+ ):
2112
+ attention_mask = attention_mask[:, -max_cache_length:]
2113
+
2114
+ position_ids = kwargs.get("position_ids", None)
2115
+ if attention_mask is not None and position_ids is None:
2116
+ # create position_ids on the fly for batch generation
2117
+ position_ids = attention_mask.long().cumsum(-1) - 1
2118
+ position_ids.masked_fill_(attention_mask == 0, 1)
2119
+ if past_key_values:
2120
+ position_ids = position_ids[:, -input_ids.shape[1] :]
2121
+
2122
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
2123
+ if inputs_embeds is not None and past_key_values is None:
2124
+ model_inputs = {"inputs_embeds": inputs_embeds}
2125
+ else:
2126
+ model_inputs = {"input_ids": input_ids}
2127
+
2128
+ model_inputs.update(
2129
+ {
2130
+ "position_ids": position_ids,
2131
+ "past_key_values": past_key_values,
2132
+ "use_cache": kwargs.get("use_cache"),
2133
+ "attention_mask": attention_mask,
2134
+ }
2135
+ )
2136
+ return model_inputs
2137
+
2138
+ @staticmethod
2139
+ def _reorder_cache(past_key_values, beam_idx):
2140
+ reordered_past = ()
2141
+ for layer_past in past_key_values:
2142
+ reordered_past += (
2143
+ tuple(
2144
+ past_state.index_select(0, beam_idx.to(past_state.device))
2145
+ for past_state in layer_past
2146
+ ),
2147
+ )
2148
+ return reordered_past
2149
+
2150
+
2151
+ @add_start_docstrings(
2152
+ """
2153
+ The SewyV2 Model transformer with a sequence classification head on top (linear layer).
2154
+
2155
+ [`SewyV2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
2156
+ (e.g. GPT-2) do.
2157
+
2158
+ Since it does classification on the last token, it requires to know the position of the last token. If a
2159
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
2160
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
2161
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
2162
+ each row of the batch).
2163
+ """,
2164
+ SewyV2_START_DOCSTRING,
2165
+ )
2166
+ class SewyV2ForSequenceClassification(SewyV2PreTrainedModel):
2167
+ def __init__(self, config):
2168
+ super().__init__(config)
2169
+ self.num_labels = config.num_labels
2170
+ self.model = SewyV2Model(config)
2171
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
2172
+
2173
+ # Initialize weights and apply final processing
2174
+ self.post_init()
2175
+
2176
+ def get_input_embeddings(self):
2177
+ return self.model.embed_tokens
2178
+
2179
+ def set_input_embeddings(self, value):
2180
+ self.model.embed_tokens = value
2181
+
2182
+ @add_start_docstrings_to_model_forward(SewyV2_INPUTS_DOCSTRING)
2183
+ def forward(
2184
+ self,
2185
+ input_ids: torch.LongTensor = None,
2186
+ attention_mask: Optional[torch.Tensor] = None,
2187
+ position_ids: Optional[torch.LongTensor] = None,
2188
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
2189
+ inputs_embeds: Optional[torch.FloatTensor] = None,
2190
+ labels: Optional[torch.LongTensor] = None,
2191
+ use_cache: Optional[bool] = None,
2192
+ output_attentions: Optional[bool] = None,
2193
+ output_hidden_states: Optional[bool] = None,
2194
+ return_dict: Optional[bool] = None,
2195
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
2196
+ r"""
2197
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
2198
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
2199
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
2200
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
2201
+ """
2202
+ return_dict = (
2203
+ return_dict if return_dict is not None else self.config.use_return_dict
2204
+ )
2205
+
2206
+ transformer_outputs = self.model(
2207
+ input_ids,
2208
+ attention_mask=attention_mask,
2209
+ position_ids=position_ids,
2210
+ past_key_values=past_key_values,
2211
+ inputs_embeds=inputs_embeds,
2212
+ use_cache=use_cache,
2213
+ output_attentions=output_attentions,
2214
+ output_hidden_states=output_hidden_states,
2215
+ return_dict=return_dict,
2216
+ )
2217
+ hidden_states = transformer_outputs[0]
2218
+ logits = self.score(hidden_states)
2219
+
2220
+ if input_ids is not None:
2221
+ batch_size = input_ids.shape[0]
2222
+ else:
2223
+ batch_size = inputs_embeds.shape[0]
2224
+
2225
+ if self.config.pad_token_id is None and batch_size != 1:
2226
+ raise ValueError(
2227
+ "Cannot handle batch sizes > 1 if no padding token is defined."
2228
+ )
2229
+ if self.config.pad_token_id is None:
2230
+ sequence_lengths = -1
2231
+ else:
2232
+ if input_ids is not None:
2233
+ sequence_lengths = (
2234
+ torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
2235
+ ).to(logits.device)
2236
+ else:
2237
+ sequence_lengths = -1
2238
+
2239
+ pooled_logits = logits[
2240
+ torch.arange(batch_size, device=logits.device), sequence_lengths
2241
+ ]
2242
+
2243
+ loss = None
2244
+ if labels is not None:
2245
+ labels = labels.to(logits.device)
2246
+ if self.config.problem_type is None:
2247
+ if self.num_labels == 1:
2248
+ self.config.problem_type = "regression"
2249
+ elif self.num_labels > 1 and (
2250
+ labels.dtype == torch.long or labels.dtype == torch.int
2251
+ ):
2252
+ self.config.problem_type = "single_label_classification"
2253
+ else:
2254
+ self.config.problem_type = "multi_label_classification"
2255
+
2256
+ if self.config.problem_type == "regression":
2257
+ loss_fct = MSELoss()
2258
+ if self.num_labels == 1:
2259
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
2260
+ else:
2261
+ loss = loss_fct(pooled_logits, labels)
2262
+ elif self.config.problem_type == "single_label_classification":
2263
+ loss_fct = CrossEntropyLoss()
2264
+ loss = loss_fct(
2265
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
2266
+ )
2267
+ elif self.config.problem_type == "multi_label_classification":
2268
+ loss_fct = BCEWithLogitsLoss()
2269
+ loss = loss_fct(pooled_logits, labels)
2270
+ if not return_dict:
2271
+ output = (pooled_logits,) + transformer_outputs[1:]
2272
+ return ((loss,) + output) if loss is not None else output
2273
+
2274
+ return SequenceClassifierOutputWithPast(
2275
+ loss=loss,
2276
+ logits=pooled_logits,
2277
+ past_key_values=transformer_outputs.past_key_values,
2278
+ hidden_states=transformer_outputs.hidden_states,
2279
+ attentions=transformer_outputs.attentions,
2280
+ )