ej2 commited on
Commit
c5415ab
·
verified ·
1 Parent(s): 0710922

Upload 10 files

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