Aarushhh commited on
Commit
8206924
·
verified ·
1 Parent(s): 497fa3b

Upload modular_Sewy2.py

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