soroushtabesh commited on
Commit
842da8d
·
verified ·
1 Parent(s): ff4d34c

Add files using upload-large-folder tool

Browse files
Files changed (47) hide show
  1. .gitattributes +3 -0
  2. configuration_deepseek.py +214 -0
  3. evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/results_2026-03-12T18-13-57.415988.json +457 -0
  4. evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/results_2026-03-12T18-15-26.173888.json +457 -0
  5. evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/results_2026-03-12T20-16-45.465199.json +461 -0
  6. evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_arc_challenge_2026-03-12T18-13-57.415988.jsonl +0 -0
  7. evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_arc_challenge_2026-03-12T18-15-26.173888.jsonl +0 -0
  8. evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_arc_challenge_2026-03-12T20-16-45.465199.jsonl +0 -0
  9. evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_arc_easy_2026-03-12T18-13-57.415988.jsonl +0 -0
  10. evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_arc_easy_2026-03-12T18-15-26.173888.jsonl +0 -0
  11. evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_arc_easy_2026-03-12T20-16-45.465199.jsonl +0 -0
  12. evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_gsm8k_2026-03-12T18-13-57.415988.jsonl +3 -0
  13. evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_gsm8k_2026-03-12T18-15-26.173888.jsonl +3 -0
  14. evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_gsm8k_2026-03-12T20-16-45.465199.jsonl +3 -0
  15. evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_piqa_2026-03-12T18-13-57.415988.jsonl +0 -0
  16. evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_piqa_2026-03-12T18-15-26.173888.jsonl +0 -0
  17. evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_piqa_2026-03-12T20-16-45.465199.jsonl +0 -0
  18. evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_winogrande_2026-03-12T18-13-57.415988.jsonl +0 -0
  19. evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_winogrande_2026-03-12T18-15-26.173888.jsonl +0 -0
  20. evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_winogrande_2026-03-12T20-16-45.465199.jsonl +0 -0
  21. generation_config.json +4 -0
  22. kimi_k25_vision_processing.py +251 -0
  23. model-00007-of-00062.safetensors +3 -0
  24. model-00015-of-00062.safetensors +3 -0
  25. model-00016-of-00062.safetensors +3 -0
  26. model-00017-of-00062.safetensors +3 -0
  27. model-00018-of-00062.safetensors +3 -0
  28. model-00021-of-00062.safetensors +3 -0
  29. model-00022-of-00062.safetensors +3 -0
  30. model-00023-of-00062.safetensors +3 -0
  31. model-00026-of-00062.safetensors +3 -0
  32. model-00027-of-00062.safetensors +3 -0
  33. model-00029-of-00062.safetensors +3 -0
  34. model-00030-of-00062.safetensors +3 -0
  35. model-00033-of-00062.safetensors +3 -0
  36. model-00038-of-00062.safetensors +3 -0
  37. model-00039-of-00062.safetensors +3 -0
  38. model-00044-of-00062.safetensors +3 -0
  39. model-00046-of-00062.safetensors +3 -0
  40. model-00051-of-00062.safetensors +3 -0
  41. model-00053-of-00062.safetensors +3 -0
  42. model-00054-of-00062.safetensors +3 -0
  43. model-00055-of-00062.safetensors +3 -0
  44. model-00057-of-00062.safetensors +3 -0
  45. model-00059-of-00062.safetensors +3 -0
  46. model-00061-of-00062.safetensors +3 -0
  47. modeling_deepseek.py +1808 -0
.gitattributes CHANGED
@@ -34,3 +34,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  model.safetensors.index.json filter=lfs diff=lfs merge=lfs -text
 
 
 
 
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  model.safetensors.index.json filter=lfs diff=lfs merge=lfs -text
37
+ evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_gsm8k_2026-03-12T18-13-57.415988.jsonl filter=lfs diff=lfs merge=lfs -text
38
+ evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_gsm8k_2026-03-12T18-15-26.173888.jsonl filter=lfs diff=lfs merge=lfs -text
39
+ evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_gsm8k_2026-03-12T20-16-45.465199.jsonl filter=lfs diff=lfs merge=lfs -text
configuration_deepseek.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copy from https://huggingface.co/deepseek-ai/DeepSeek-V3/blob/main/configuration_deepseek.py
2
+
3
+ from transformers.configuration_utils import PretrainedConfig
4
+ from transformers.utils import logging
5
+
6
+ logger = logging.get_logger(__name__)
7
+
8
+ DEEPSEEK_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
9
+
10
+
11
+ class DeepseekV3Config(PretrainedConfig):
12
+ r"""
13
+ This is the configuration class to store the configuration of a [`DeepseekV3Model`]. It is used to instantiate an DeepSeek
14
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
15
+ defaults will yield a similar configuration to that of the DeepSeek-V3.
16
+
17
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
18
+ documentation from [`PretrainedConfig`] for more information.
19
+
20
+
21
+ Args:
22
+ vocab_size (`int`, *optional*, defaults to 129280):
23
+ Vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the
24
+ `inputs_ids` passed when calling [`DeepseekV3Model`]
25
+ hidden_size (`int`, *optional*, defaults to 4096):
26
+ Dimension of the hidden representations.
27
+ intermediate_size (`int`, *optional*, defaults to 11008):
28
+ Dimension of the MLP representations.
29
+ moe_intermediate_size (`int`, *optional*, defaults to 1407):
30
+ Dimension of the MoE representations.
31
+ num_hidden_layers (`int`, *optional*, defaults to 32):
32
+ Number of hidden layers in the Transformer decoder.
33
+ num_nextn_predict_layers (`int`, *optional*, defaults to 1):
34
+ Number of nextn predict layers in the DeepSeekV3 Model.
35
+ num_attention_heads (`int`, *optional*, defaults to 32):
36
+ Number of attention heads for each attention layer in the Transformer decoder.
37
+ n_shared_experts (`int`, *optional*, defaults to None):
38
+ Number of shared experts, None means dense model.
39
+ n_routed_experts (`int`, *optional*, defaults to None):
40
+ Number of routed experts, None means dense model.
41
+ routed_scaling_factor (`float`, *optional*, defaults to 1.0):
42
+ Scaling factor or routed experts.
43
+ topk_method (`str`, *optional*, defaults to `gready`):
44
+ Topk method used in routed gate.
45
+ n_group (`int`, *optional*, defaults to None):
46
+ Number of groups for routed experts.
47
+ topk_group (`int`, *optional*, defaults to None):
48
+ Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
49
+ num_experts_per_tok (`int`, *optional*, defaults to None):
50
+ Number of selected experts, None means dense model.
51
+ moe_layer_freq (`int`, *optional*, defaults to 1):
52
+ The frequency of the MoE layer: one expert layer for every `moe_layer_freq - 1` dense layers.
53
+ first_k_dense_replace (`int`, *optional*, defaults to 0):
54
+ Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
55
+ \--k dense layers--/
56
+ norm_topk_prob (`bool`, *optional*, defaults to False):
57
+ Whether to normalize the weights of the routed experts.
58
+ scoring_func (`str`, *optional*, defaults to 'softmax'):
59
+ Method of computing expert weights.
60
+ aux_loss_alpha (`float`, *optional*, defaults to 0.001):
61
+ Auxiliary loss weight coefficient.
62
+ seq_aux = (`bool`, *optional*, defaults to True):
63
+ Whether to compute the auxiliary loss for each individual sample.
64
+ num_key_value_heads (`int`, *optional*):
65
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
66
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
67
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
68
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
69
+ by meanpooling all the original heads within that group. For more details checkout [this
70
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
71
+ `num_attention_heads`.
72
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
73
+ The non-linear activation function (function or string) in the decoder.
74
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
75
+ The maximum sequence length that this model might ever be used with.
76
+ initializer_range (`float`, *optional*, defaults to 0.02):
77
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
78
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
79
+ The epsilon used by the rms normalization layers.
80
+ use_cache (`bool`, *optional*, defaults to `True`):
81
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
82
+ relevant if `config.is_decoder=True`.
83
+ pad_token_id (`int`, *optional*):
84
+ Padding token id.
85
+ bos_token_id (`int`, *optional*, defaults to 1):
86
+ Beginning of stream token id.
87
+ eos_token_id (`int`, *optional*, defaults to 2):
88
+ End of stream token id.
89
+ pretraining_tp (`int`, *optional*, defaults to 1):
90
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
91
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
92
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
93
+ issue](https://github.com/pytorch/pytorch/issues/76232).
94
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
95
+ Whether to tie weight embeddings
96
+ rope_theta (`float`, *optional*, defaults to 10000.0):
97
+ The base period of the RoPE embeddings.
98
+ rope_scaling (`Dict`, *optional*):
99
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
100
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
101
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
102
+ `max_position_embeddings` to the expected new maximum.
103
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
104
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
105
+ attention_dropout (`float`, *optional*, defaults to 0.0):
106
+ The dropout ratio for the attention probabilities.
107
+
108
+ ```python
109
+ >>> from transformers import DeepseekV3Model, DeepseekV3Config
110
+
111
+ >>> # Initializing a Deepseek-V3 style configuration
112
+ >>> configuration = DeepseekV3Config()
113
+
114
+ >>> # Accessing the model configuration
115
+ >>> configuration = model.config
116
+ ```"""
117
+
118
+ model_type = "deepseek_v3"
119
+ keys_to_ignore_at_inference = ["past_key_values"]
120
+
121
+ def __init__(
122
+ self,
123
+ vocab_size=129280,
124
+ hidden_size=7168,
125
+ intermediate_size=18432,
126
+ moe_intermediate_size=2048,
127
+ num_hidden_layers=61,
128
+ num_nextn_predict_layers=1,
129
+ num_attention_heads=128,
130
+ num_key_value_heads=128,
131
+ n_shared_experts=1,
132
+ n_routed_experts=256,
133
+ ep_size=1,
134
+ routed_scaling_factor=2.5,
135
+ kv_lora_rank=512,
136
+ q_lora_rank=1536,
137
+ qk_rope_head_dim=64,
138
+ v_head_dim=128,
139
+ qk_nope_head_dim=128,
140
+ topk_method='noaux_tc',
141
+ n_group=8,
142
+ topk_group=4,
143
+ num_experts_per_tok=8,
144
+ moe_layer_freq=1,
145
+ first_k_dense_replace=3,
146
+ norm_topk_prob=True,
147
+ scoring_func='sigmoid',
148
+ aux_loss_alpha=0.001,
149
+ seq_aux=True,
150
+ hidden_act="silu",
151
+ max_position_embeddings=4096,
152
+ initializer_range=0.02,
153
+ rms_norm_eps=1e-6,
154
+ use_cache=True,
155
+ pad_token_id=None,
156
+ bos_token_id=0,
157
+ eos_token_id=1,
158
+ pretraining_tp=1,
159
+ tie_word_embeddings=False,
160
+ rope_theta=10000.0,
161
+ rope_scaling=None,
162
+ attention_bias=False,
163
+ attention_dropout=0.0,
164
+ **kwargs,
165
+ ):
166
+ self.vocab_size = vocab_size
167
+ self.max_position_embeddings = max_position_embeddings
168
+ self.hidden_size = hidden_size
169
+ self.intermediate_size = intermediate_size
170
+ self.moe_intermediate_size = moe_intermediate_size
171
+ self.num_hidden_layers = num_hidden_layers
172
+ self.num_nextn_predict_layers = num_nextn_predict_layers
173
+ self.num_attention_heads = num_attention_heads
174
+ self.n_shared_experts = n_shared_experts
175
+ self.n_routed_experts = n_routed_experts
176
+ self.ep_size = ep_size
177
+ self.routed_scaling_factor = routed_scaling_factor
178
+ self.kv_lora_rank = kv_lora_rank
179
+ self.q_lora_rank = q_lora_rank
180
+ self.qk_rope_head_dim = qk_rope_head_dim
181
+ self.v_head_dim = v_head_dim
182
+ self.qk_nope_head_dim = qk_nope_head_dim
183
+ self.topk_method = topk_method
184
+ self.n_group = n_group
185
+ self.topk_group = topk_group
186
+ self.num_experts_per_tok = num_experts_per_tok
187
+ self.moe_layer_freq = moe_layer_freq
188
+ self.first_k_dense_replace = first_k_dense_replace
189
+ self.norm_topk_prob = norm_topk_prob
190
+ self.scoring_func = scoring_func
191
+ self.aux_loss_alpha = aux_loss_alpha
192
+ self.seq_aux = seq_aux
193
+ # for backward compatibility
194
+ if num_key_value_heads is None:
195
+ num_key_value_heads = num_attention_heads
196
+
197
+ self.num_key_value_heads = num_key_value_heads
198
+ self.hidden_act = hidden_act
199
+ self.initializer_range = initializer_range
200
+ self.rms_norm_eps = rms_norm_eps
201
+ self.pretraining_tp = pretraining_tp
202
+ self.use_cache = use_cache
203
+ self.rope_theta = rope_theta
204
+ self.rope_scaling = rope_scaling
205
+ self.attention_bias = attention_bias
206
+ self.attention_dropout = attention_dropout
207
+
208
+ super().__init__(
209
+ pad_token_id=pad_token_id,
210
+ bos_token_id=bos_token_id,
211
+ eos_token_id=eos_token_id,
212
+ tie_word_embeddings=tie_word_embeddings,
213
+ **kwargs,
214
+ )
evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/results_2026-03-12T18-13-57.415988.json ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "results": {
3
+ "arc_challenge": {
4
+ "alias": "arc_challenge",
5
+ "acc,none": 0.5767918088737202,
6
+ "acc_stderr,none": 0.014438036220848036,
7
+ "acc_norm,none": 0.6262798634812287,
8
+ "acc_norm_stderr,none": 0.014137708601759088
9
+ },
10
+ "arc_easy": {
11
+ "alias": "arc_easy",
12
+ "acc,none": 0.8468013468013468,
13
+ "acc_stderr,none": 0.007390714682535135,
14
+ "acc_norm,none": 0.8518518518518519,
15
+ "acc_norm_stderr,none": 0.007289510108394621
16
+ },
17
+ "gsm8k": {
18
+ "alias": "gsm8k",
19
+ "exact_match,strict-match": 0.9234268385140257,
20
+ "exact_match_stderr,strict-match": 0.007324564881451566,
21
+ "exact_match,flexible-extract": 0.9234268385140257,
22
+ "exact_match_stderr,flexible-extract": 0.007324564881451566
23
+ },
24
+ "piqa": {
25
+ "alias": "piqa",
26
+ "acc,none": 0.8177366702937976,
27
+ "acc_stderr,none": 0.009007448933095024,
28
+ "acc_norm,none": 0.8253536452665942,
29
+ "acc_norm_stderr,none": 0.008858194693868615
30
+ },
31
+ "winogrande": {
32
+ "alias": "winogrande",
33
+ "acc,none": 0.7663772691397001,
34
+ "acc_stderr,none": 0.011892194477183524
35
+ }
36
+ },
37
+ "group_subtasks": {
38
+ "gsm8k": [],
39
+ "arc_challenge": [],
40
+ "arc_easy": [],
41
+ "winogrande": [],
42
+ "piqa": []
43
+ },
44
+ "configs": {
45
+ "arc_challenge": {
46
+ "task": "arc_challenge",
47
+ "tag": [
48
+ "ai2_arc"
49
+ ],
50
+ "dataset_path": "allenai/ai2_arc",
51
+ "dataset_name": "ARC-Challenge",
52
+ "training_split": "train",
53
+ "validation_split": "validation",
54
+ "test_split": "test",
55
+ "doc_to_text": "Question: {{question}}\nAnswer:",
56
+ "doc_to_target": "{{choices.label.index(answerKey)}}",
57
+ "unsafe_code": false,
58
+ "doc_to_choice": "{{choices.text}}",
59
+ "description": "",
60
+ "target_delimiter": " ",
61
+ "fewshot_delimiter": "\n\n",
62
+ "fewshot_config": {
63
+ "sampler": "default",
64
+ "split": null,
65
+ "process_docs": null,
66
+ "fewshot_indices": null,
67
+ "samples": null,
68
+ "doc_to_text": "Question: {{question}}\nAnswer:",
69
+ "doc_to_choice": "{{choices.text}}",
70
+ "doc_to_target": "{{choices.label.index(answerKey)}}",
71
+ "gen_prefix": null,
72
+ "fewshot_delimiter": "\n\n",
73
+ "target_delimiter": " "
74
+ },
75
+ "num_fewshot": 0,
76
+ "metric_list": [
77
+ {
78
+ "metric": "acc",
79
+ "aggregation": "mean",
80
+ "higher_is_better": true
81
+ },
82
+ {
83
+ "metric": "acc_norm",
84
+ "aggregation": "mean",
85
+ "higher_is_better": true
86
+ }
87
+ ],
88
+ "output_type": "multiple_choice",
89
+ "repeats": 1,
90
+ "should_decontaminate": true,
91
+ "doc_to_decontamination_query": "Question: {{question}}\nAnswer:",
92
+ "metadata": {
93
+ "version": 1.0,
94
+ "model": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled",
95
+ "base_url": "http://172.28.42.156:8000/v1/completions",
96
+ "num_concurrent": 8,
97
+ "tokenizer": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled"
98
+ }
99
+ },
100
+ "arc_easy": {
101
+ "task": "arc_easy",
102
+ "tag": [
103
+ "ai2_arc"
104
+ ],
105
+ "dataset_path": "allenai/ai2_arc",
106
+ "dataset_name": "ARC-Easy",
107
+ "training_split": "train",
108
+ "validation_split": "validation",
109
+ "test_split": "test",
110
+ "doc_to_text": "Question: {{question}}\nAnswer:",
111
+ "doc_to_target": "{{choices.label.index(answerKey)}}",
112
+ "unsafe_code": false,
113
+ "doc_to_choice": "{{choices.text}}",
114
+ "description": "",
115
+ "target_delimiter": " ",
116
+ "fewshot_delimiter": "\n\n",
117
+ "fewshot_config": {
118
+ "sampler": "default",
119
+ "split": null,
120
+ "process_docs": null,
121
+ "fewshot_indices": null,
122
+ "samples": null,
123
+ "doc_to_text": "Question: {{question}}\nAnswer:",
124
+ "doc_to_choice": "{{choices.text}}",
125
+ "doc_to_target": "{{choices.label.index(answerKey)}}",
126
+ "gen_prefix": null,
127
+ "fewshot_delimiter": "\n\n",
128
+ "target_delimiter": " "
129
+ },
130
+ "num_fewshot": 0,
131
+ "metric_list": [
132
+ {
133
+ "metric": "acc",
134
+ "aggregation": "mean",
135
+ "higher_is_better": true
136
+ },
137
+ {
138
+ "metric": "acc_norm",
139
+ "aggregation": "mean",
140
+ "higher_is_better": true
141
+ }
142
+ ],
143
+ "output_type": "multiple_choice",
144
+ "repeats": 1,
145
+ "should_decontaminate": true,
146
+ "doc_to_decontamination_query": "Question: {{question}}\nAnswer:",
147
+ "metadata": {
148
+ "version": 1.0,
149
+ "model": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled",
150
+ "base_url": "http://172.28.42.156:8000/v1/completions",
151
+ "num_concurrent": 8,
152
+ "tokenizer": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled"
153
+ }
154
+ },
155
+ "gsm8k": {
156
+ "task": "gsm8k",
157
+ "tag": [
158
+ "math_word_problems"
159
+ ],
160
+ "dataset_path": "openai/gsm8k",
161
+ "dataset_name": "main",
162
+ "training_split": "train",
163
+ "test_split": "test",
164
+ "fewshot_split": "train",
165
+ "doc_to_text": "Question: {{question}}\nAnswer:",
166
+ "doc_to_target": "{{answer}}",
167
+ "unsafe_code": false,
168
+ "description": "",
169
+ "target_delimiter": " ",
170
+ "fewshot_delimiter": "\n\n",
171
+ "fewshot_config": {
172
+ "sampler": "default",
173
+ "split": "train",
174
+ "process_docs": null,
175
+ "fewshot_indices": null,
176
+ "samples": null,
177
+ "doc_to_text": "Question: {{question}}\nAnswer:",
178
+ "doc_to_choice": null,
179
+ "doc_to_target": "{{answer}}",
180
+ "gen_prefix": null,
181
+ "fewshot_delimiter": "\n\n",
182
+ "target_delimiter": " "
183
+ },
184
+ "num_fewshot": 5,
185
+ "metric_list": [
186
+ {
187
+ "metric": "exact_match",
188
+ "aggregation": "mean",
189
+ "higher_is_better": true,
190
+ "ignore_case": true,
191
+ "ignore_punctuation": false,
192
+ "regexes_to_ignore": [
193
+ ",",
194
+ "\\$",
195
+ "(?s).*#### ",
196
+ "\\.$"
197
+ ]
198
+ }
199
+ ],
200
+ "output_type": "generate_until",
201
+ "generation_kwargs": {
202
+ "until": [
203
+ "Question:",
204
+ "</s>",
205
+ "<|im_end|>"
206
+ ],
207
+ "do_sample": false,
208
+ "temperature": 0.0
209
+ },
210
+ "repeats": 1,
211
+ "filter_list": [
212
+ {
213
+ "name": "strict-match",
214
+ "filter": [
215
+ {
216
+ "function": "regex",
217
+ "regex_pattern": "#### (\\-?[0-9\\.\\,]+)"
218
+ },
219
+ {
220
+ "function": "take_first"
221
+ }
222
+ ]
223
+ },
224
+ {
225
+ "name": "flexible-extract",
226
+ "filter": [
227
+ {
228
+ "function": "regex",
229
+ "group_select": -1,
230
+ "regex_pattern": "(-?[$0-9.,]{2,})|(-?[0-9]+)"
231
+ },
232
+ {
233
+ "function": "take_first"
234
+ }
235
+ ]
236
+ }
237
+ ],
238
+ "should_decontaminate": false,
239
+ "metadata": {
240
+ "version": 3.0,
241
+ "model": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled",
242
+ "base_url": "http://172.28.42.156:8000/v1/completions",
243
+ "num_concurrent": 8,
244
+ "tokenizer": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled"
245
+ }
246
+ },
247
+ "piqa": {
248
+ "task": "piqa",
249
+ "dataset_path": "baber/piqa",
250
+ "training_split": "train",
251
+ "validation_split": "validation",
252
+ "doc_to_text": "Question: {{goal}}\nAnswer:",
253
+ "doc_to_target": "label",
254
+ "unsafe_code": false,
255
+ "doc_to_choice": "{{[sol1, sol2]}}",
256
+ "description": "",
257
+ "target_delimiter": " ",
258
+ "fewshot_delimiter": "\n\n",
259
+ "fewshot_config": {
260
+ "sampler": "default",
261
+ "split": null,
262
+ "process_docs": null,
263
+ "fewshot_indices": null,
264
+ "samples": null,
265
+ "doc_to_text": "Question: {{goal}}\nAnswer:",
266
+ "doc_to_choice": "{{[sol1, sol2]}}",
267
+ "doc_to_target": "label",
268
+ "gen_prefix": null,
269
+ "fewshot_delimiter": "\n\n",
270
+ "target_delimiter": " "
271
+ },
272
+ "num_fewshot": 0,
273
+ "metric_list": [
274
+ {
275
+ "metric": "acc",
276
+ "aggregation": "mean",
277
+ "higher_is_better": true
278
+ },
279
+ {
280
+ "metric": "acc_norm",
281
+ "aggregation": "mean",
282
+ "higher_is_better": true
283
+ }
284
+ ],
285
+ "output_type": "multiple_choice",
286
+ "repeats": 1,
287
+ "should_decontaminate": true,
288
+ "doc_to_decontamination_query": "goal",
289
+ "metadata": {
290
+ "version": 1.0,
291
+ "model": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled",
292
+ "base_url": "http://172.28.42.156:8000/v1/completions",
293
+ "num_concurrent": 8,
294
+ "tokenizer": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled"
295
+ }
296
+ },
297
+ "winogrande": {
298
+ "task": "winogrande",
299
+ "dataset_path": "allenai/winogrande",
300
+ "dataset_name": "winogrande_xl",
301
+ "training_split": "train",
302
+ "validation_split": "validation",
303
+ "doc_to_text": "def doc_to_text(doc):\n answer_to_num = {\"1\": 0, \"2\": 1}\n return answer_to_num[doc[\"answer\"]]\n",
304
+ "doc_to_target": "def doc_to_target(doc):\n idx = doc[\"sentence\"].index(\"_\") + 1\n return doc[\"sentence\"][idx:].strip()\n",
305
+ "unsafe_code": false,
306
+ "doc_to_choice": "def doc_to_choice(doc):\n idx = doc[\"sentence\"].index(\"_\")\n options = [doc[\"option1\"], doc[\"option2\"]]\n return [doc[\"sentence\"][:idx] + opt for opt in options]\n",
307
+ "description": "",
308
+ "target_delimiter": " ",
309
+ "fewshot_delimiter": "\n\n",
310
+ "fewshot_config": {
311
+ "sampler": "default",
312
+ "split": null,
313
+ "process_docs": null,
314
+ "fewshot_indices": null,
315
+ "samples": null,
316
+ "doc_to_text": "<function doc_to_text at 0x40049ecd8f40>",
317
+ "doc_to_choice": "<function doc_to_choice at 0x40049ecd9d00>",
318
+ "doc_to_target": "<function doc_to_target at 0x40049ecd9a80>",
319
+ "gen_prefix": null,
320
+ "fewshot_delimiter": "\n\n",
321
+ "target_delimiter": " "
322
+ },
323
+ "num_fewshot": 0,
324
+ "metric_list": [
325
+ {
326
+ "metric": "acc",
327
+ "aggregation": "mean",
328
+ "higher_is_better": true
329
+ }
330
+ ],
331
+ "output_type": "multiple_choice",
332
+ "repeats": 1,
333
+ "should_decontaminate": true,
334
+ "doc_to_decontamination_query": "sentence",
335
+ "metadata": {
336
+ "version": 1.0,
337
+ "model": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled",
338
+ "base_url": "http://172.28.42.156:8000/v1/completions",
339
+ "num_concurrent": 8,
340
+ "tokenizer": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled"
341
+ }
342
+ }
343
+ },
344
+ "versions": {
345
+ "arc_challenge": 1.0,
346
+ "arc_easy": 1.0,
347
+ "gsm8k": 3.0,
348
+ "piqa": 1.0,
349
+ "winogrande": 1.0
350
+ },
351
+ "n-shot": {
352
+ "arc_challenge": 0,
353
+ "arc_easy": 0,
354
+ "gsm8k": 5,
355
+ "piqa": 0,
356
+ "winogrande": 0
357
+ },
358
+ "higher_is_better": {
359
+ "arc_challenge": {
360
+ "acc": true,
361
+ "acc_norm": true
362
+ },
363
+ "arc_easy": {
364
+ "acc": true,
365
+ "acc_norm": true
366
+ },
367
+ "gsm8k": {
368
+ "exact_match": true
369
+ },
370
+ "piqa": {
371
+ "acc": true,
372
+ "acc_norm": true
373
+ },
374
+ "winogrande": {
375
+ "acc": true
376
+ }
377
+ },
378
+ "n-samples": {
379
+ "piqa": {
380
+ "original": 1838,
381
+ "effective": 1838
382
+ },
383
+ "winogrande": {
384
+ "original": 1267,
385
+ "effective": 1267
386
+ },
387
+ "arc_easy": {
388
+ "original": 2376,
389
+ "effective": 2376
390
+ },
391
+ "arc_challenge": {
392
+ "original": 1172,
393
+ "effective": 1172
394
+ },
395
+ "gsm8k": {
396
+ "original": 1319,
397
+ "effective": 1319
398
+ }
399
+ },
400
+ "config": {
401
+ "model": "local-completions",
402
+ "model_args": {
403
+ "model": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled",
404
+ "base_url": "http://172.28.42.156:8000/v1/completions",
405
+ "num_concurrent": 8,
406
+ "tokenizer": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled",
407
+ "trust_remote_code": true
408
+ },
409
+ "batch_size": 1,
410
+ "batch_sizes": [],
411
+ "device": "cuda:0",
412
+ "use_cache": null,
413
+ "limit": null,
414
+ "bootstrap_iters": 100000,
415
+ "gen_kwargs": {},
416
+ "random_seed": 0,
417
+ "numpy_seed": 1234,
418
+ "torch_seed": 1234,
419
+ "fewshot_seed": 1234
420
+ },
421
+ "git_hash": "b8f36fc",
422
+ "date": 1773333779.4253557,
423
+ "pretty_env_info": "PyTorch version: 2.8.0+cpu\nIs debug build: False\nCUDA used to build PyTorch: Could not collect\nROCM used to build PyTorch: N/A\n\nOS: SUSE Linux Enterprise Server 15 SP6 (aarch64)\nGCC version: (SUSE Linux) 7.5.0\nClang version: Could not collect\nCMake version: version 3.28.3\nLibc version: glibc-2.38\n\nPython version: 3.11.14 (main, Jan 14 2026, 19:35:38) [Clang 21.1.4 ] (64-bit runtime)\nPython platform: Linux-6.4.0-150600.23.47_15.0.10-cray_shasta_c_64k-aarch64-with-glibc2.38\nIs CUDA available: False\nCUDA runtime version: Could not collect\nCUDA_MODULE_LOADING set to: N/A\nGPU models and configuration: \nGPU 0: NVIDIA GH200 120GB\nGPU 1: NVIDIA GH200 120GB\nGPU 2: NVIDIA GH200 120GB\nGPU 3: NVIDIA GH200 120GB\n\nNvidia driver version: 590.48.01\ncuDNN version: Could not collect\nHIP runtime version: N/A\nMIOpen runtime version: N/A\nIs XNNPACK available: True\n\nCPU:\nArchitecture: aarch64\nCPU op-mode(s): 64-bit\nByte Order: Little Endian\nCPU(s): 288\nOn-line CPU(s) list: 0-287\nVendor ID: ARM\nModel name: Neoverse-V2\nModel: 0\nThread(s) per core: 1\nCore(s) per socket: 72\nSocket(s): 4\nStepping: r0p0\nFrequency boost: disabled\nCPU(s) scaling MHz: 100%\nCPU max MHz: 3465.0000\nCPU min MHz: 81.0000\nBogoMIPS: 2000.00\nFlags: fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh bti\nL1d cache: 18 MiB (288 instances)\nL1i cache: 18 MiB (288 instances)\nL2 cache: 288 MiB (288 instances)\nL3 cache: 456 MiB (4 instances)\nNUMA node(s): 36\nNUMA node0 CPU(s): 0-71\nNUMA node1 CPU(s): 72-143\nNUMA node2 CPU(s): 144-215\nNUMA node3 CPU(s): 216-287\nNUMA node4 CPU(s): \nNUMA node5 CPU(s): \nNUMA node6 CPU(s): \nNUMA node7 CPU(s): \nNUMA node8 CPU(s): \nNUMA node9 CPU(s): \nNUMA node10 CPU(s): \nNUMA node11 CPU(s): \nNUMA node12 CPU(s): \nNUMA node13 CPU(s): \nNUMA node14 CPU(s): \nNUMA node15 CPU(s): \nNUMA node16 CPU(s): \nNUMA node17 CPU(s): \nNUMA node18 CPU(s): \nNUMA node19 CPU(s): \nNUMA node20 CPU(s): \nNUMA node21 CPU(s): \nNUMA node22 CPU(s): \nNUMA node23 CPU(s): \nNUMA node24 CPU(s): \nNUMA node25 CPU(s): \nNUMA node26 CPU(s): \nNUMA node27 CPU(s): \nNUMA node28 CPU(s): \nNUMA node29 CPU(s): \nNUMA node30 CPU(s): \nNUMA node31 CPU(s): \nNUMA node32 CPU(s): \nNUMA node33 CPU(s): \nNUMA node34 CPU(s): \nNUMA node35 CPU(s): \nVulnerability Gather data sampling: Not affected\nVulnerability Itlb multihit: Not affected\nVulnerability L1tf: Not affected\nVulnerability Mds: Not affected\nVulnerability Meltdown: Not affected\nVulnerability Mmio stale data: Not affected\nVulnerability Reg file data sampling: Not affected\nVulnerability Retbleed: Not affected\nVulnerability Spec rstack overflow: Not affected\nVulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl\nVulnerability Spectre v1: Mitigation; __user pointer sanitization\nVulnerability Spectre v2: Mitigation; CSV2, BHB\nVulnerability Srbds: Not affected\nVulnerability Tsx async abort: Not affected\n\nVersions of relevant libraries:\n[pip3] Could not collect\n[conda] Could not collect",
424
+ "transformers_version": "4.57.6",
425
+ "lm_eval_version": "0.4.11",
426
+ "upper_git_hash": null,
427
+ "tokenizer_pad_token": [
428
+ "[PAD]",
429
+ "163839"
430
+ ],
431
+ "tokenizer_eos_token": [
432
+ "[EOS]",
433
+ "163585"
434
+ ],
435
+ "tokenizer_bos_token": [
436
+ "[BOS]",
437
+ "163584"
438
+ ],
439
+ "eot_token_id": 163585,
440
+ "max_length": 2047,
441
+ "task_hashes": {
442
+ "piqa": "74d5a816572c396ad46edbd386954abe5ddb3db2d7195088387d1d5c1b32fd8b",
443
+ "winogrande": "a5ea73eb24ab46d111fe5d21eed85b1e779c0b309d80d080c3caa21a851b6feb",
444
+ "arc_easy": "dce0d9b0f0cecd55bf2ac264042c5e45487df708d13123af3ae9e67bbbefdeb1",
445
+ "arc_challenge": "09f9ae87a0905d63512cffc4aa91a55e44258fc35160e40fa1eb66fb75473e34",
446
+ "gsm8k": "2330f4ebfcccaf66a892922df2819cdb1f118e448d076d3f42bdde4177678ac7"
447
+ },
448
+ "model_source": "local-completions",
449
+ "model_name": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled",
450
+ "model_name_sanitized": "__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled",
451
+ "system_instruction": null,
452
+ "system_instruction_sha": null,
453
+ "fewshot_as_multiturn": null,
454
+ "chat_template": null,
455
+ "chat_template_sha": null,
456
+ "total_evaluation_time_seconds": "1876.7813418899896"
457
+ }
evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/results_2026-03-12T18-15-26.173888.json ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "results": {
3
+ "arc_challenge": {
4
+ "alias": "arc_challenge",
5
+ "acc,none": 0.5870307167235495,
6
+ "acc_stderr,none": 0.014388344935398326,
7
+ "acc_norm,none": 0.6254266211604096,
8
+ "acc_norm_stderr,none": 0.014144193471893446
9
+ },
10
+ "arc_easy": {
11
+ "alias": "arc_easy",
12
+ "acc,none": 0.8468013468013468,
13
+ "acc_stderr,none": 0.007390714682535126,
14
+ "acc_norm,none": 0.8514309764309764,
15
+ "acc_norm_stderr,none": 0.007298053635399502
16
+ },
17
+ "gsm8k": {
18
+ "alias": "gsm8k",
19
+ "exact_match,strict-match": 0.9294920394238059,
20
+ "exact_match_stderr,strict-match": 0.007051543813983619,
21
+ "exact_match,flexible-extract": 0.9294920394238059,
22
+ "exact_match_stderr,flexible-extract": 0.007051543813983619
23
+ },
24
+ "piqa": {
25
+ "alias": "piqa",
26
+ "acc,none": 0.8150163220892275,
27
+ "acc_stderr,none": 0.009059313316508649,
28
+ "acc_norm,none": 0.8210010881392819,
29
+ "acc_norm_stderr,none": 0.008944220220204942
30
+ },
31
+ "winogrande": {
32
+ "alias": "winogrande",
33
+ "acc,none": 0.7632202052091555,
34
+ "acc_stderr,none": 0.011947592365207385
35
+ }
36
+ },
37
+ "group_subtasks": {
38
+ "gsm8k": [],
39
+ "arc_challenge": [],
40
+ "arc_easy": [],
41
+ "winogrande": [],
42
+ "piqa": []
43
+ },
44
+ "configs": {
45
+ "arc_challenge": {
46
+ "task": "arc_challenge",
47
+ "tag": [
48
+ "ai2_arc"
49
+ ],
50
+ "dataset_path": "allenai/ai2_arc",
51
+ "dataset_name": "ARC-Challenge",
52
+ "training_split": "train",
53
+ "validation_split": "validation",
54
+ "test_split": "test",
55
+ "doc_to_text": "Question: {{question}}\nAnswer:",
56
+ "doc_to_target": "{{choices.label.index(answerKey)}}",
57
+ "unsafe_code": false,
58
+ "doc_to_choice": "{{choices.text}}",
59
+ "description": "",
60
+ "target_delimiter": " ",
61
+ "fewshot_delimiter": "\n\n",
62
+ "fewshot_config": {
63
+ "sampler": "default",
64
+ "split": null,
65
+ "process_docs": null,
66
+ "fewshot_indices": null,
67
+ "samples": null,
68
+ "doc_to_text": "Question: {{question}}\nAnswer:",
69
+ "doc_to_choice": "{{choices.text}}",
70
+ "doc_to_target": "{{choices.label.index(answerKey)}}",
71
+ "gen_prefix": null,
72
+ "fewshot_delimiter": "\n\n",
73
+ "target_delimiter": " "
74
+ },
75
+ "num_fewshot": 0,
76
+ "metric_list": [
77
+ {
78
+ "metric": "acc",
79
+ "aggregation": "mean",
80
+ "higher_is_better": true
81
+ },
82
+ {
83
+ "metric": "acc_norm",
84
+ "aggregation": "mean",
85
+ "higher_is_better": true
86
+ }
87
+ ],
88
+ "output_type": "multiple_choice",
89
+ "repeats": 1,
90
+ "should_decontaminate": true,
91
+ "doc_to_decontamination_query": "Question: {{question}}\nAnswer:",
92
+ "metadata": {
93
+ "version": 1.0,
94
+ "model": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled",
95
+ "base_url": "http://172.28.36.148:8000/v1/completions",
96
+ "num_concurrent": 4,
97
+ "tokenizer": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled"
98
+ }
99
+ },
100
+ "arc_easy": {
101
+ "task": "arc_easy",
102
+ "tag": [
103
+ "ai2_arc"
104
+ ],
105
+ "dataset_path": "allenai/ai2_arc",
106
+ "dataset_name": "ARC-Easy",
107
+ "training_split": "train",
108
+ "validation_split": "validation",
109
+ "test_split": "test",
110
+ "doc_to_text": "Question: {{question}}\nAnswer:",
111
+ "doc_to_target": "{{choices.label.index(answerKey)}}",
112
+ "unsafe_code": false,
113
+ "doc_to_choice": "{{choices.text}}",
114
+ "description": "",
115
+ "target_delimiter": " ",
116
+ "fewshot_delimiter": "\n\n",
117
+ "fewshot_config": {
118
+ "sampler": "default",
119
+ "split": null,
120
+ "process_docs": null,
121
+ "fewshot_indices": null,
122
+ "samples": null,
123
+ "doc_to_text": "Question: {{question}}\nAnswer:",
124
+ "doc_to_choice": "{{choices.text}}",
125
+ "doc_to_target": "{{choices.label.index(answerKey)}}",
126
+ "gen_prefix": null,
127
+ "fewshot_delimiter": "\n\n",
128
+ "target_delimiter": " "
129
+ },
130
+ "num_fewshot": 0,
131
+ "metric_list": [
132
+ {
133
+ "metric": "acc",
134
+ "aggregation": "mean",
135
+ "higher_is_better": true
136
+ },
137
+ {
138
+ "metric": "acc_norm",
139
+ "aggregation": "mean",
140
+ "higher_is_better": true
141
+ }
142
+ ],
143
+ "output_type": "multiple_choice",
144
+ "repeats": 1,
145
+ "should_decontaminate": true,
146
+ "doc_to_decontamination_query": "Question: {{question}}\nAnswer:",
147
+ "metadata": {
148
+ "version": 1.0,
149
+ "model": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled",
150
+ "base_url": "http://172.28.36.148:8000/v1/completions",
151
+ "num_concurrent": 4,
152
+ "tokenizer": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled"
153
+ }
154
+ },
155
+ "gsm8k": {
156
+ "task": "gsm8k",
157
+ "tag": [
158
+ "math_word_problems"
159
+ ],
160
+ "dataset_path": "openai/gsm8k",
161
+ "dataset_name": "main",
162
+ "training_split": "train",
163
+ "test_split": "test",
164
+ "fewshot_split": "train",
165
+ "doc_to_text": "Question: {{question}}\nAnswer:",
166
+ "doc_to_target": "{{answer}}",
167
+ "unsafe_code": false,
168
+ "description": "",
169
+ "target_delimiter": " ",
170
+ "fewshot_delimiter": "\n\n",
171
+ "fewshot_config": {
172
+ "sampler": "default",
173
+ "split": "train",
174
+ "process_docs": null,
175
+ "fewshot_indices": null,
176
+ "samples": null,
177
+ "doc_to_text": "Question: {{question}}\nAnswer:",
178
+ "doc_to_choice": null,
179
+ "doc_to_target": "{{answer}}",
180
+ "gen_prefix": null,
181
+ "fewshot_delimiter": "\n\n",
182
+ "target_delimiter": " "
183
+ },
184
+ "num_fewshot": 5,
185
+ "metric_list": [
186
+ {
187
+ "metric": "exact_match",
188
+ "aggregation": "mean",
189
+ "higher_is_better": true,
190
+ "ignore_case": true,
191
+ "ignore_punctuation": false,
192
+ "regexes_to_ignore": [
193
+ ",",
194
+ "\\$",
195
+ "(?s).*#### ",
196
+ "\\.$"
197
+ ]
198
+ }
199
+ ],
200
+ "output_type": "generate_until",
201
+ "generation_kwargs": {
202
+ "until": [
203
+ "Question:",
204
+ "</s>",
205
+ "<|im_end|>"
206
+ ],
207
+ "do_sample": false,
208
+ "temperature": 0.0
209
+ },
210
+ "repeats": 1,
211
+ "filter_list": [
212
+ {
213
+ "name": "strict-match",
214
+ "filter": [
215
+ {
216
+ "function": "regex",
217
+ "regex_pattern": "#### (\\-?[0-9\\.\\,]+)"
218
+ },
219
+ {
220
+ "function": "take_first"
221
+ }
222
+ ]
223
+ },
224
+ {
225
+ "name": "flexible-extract",
226
+ "filter": [
227
+ {
228
+ "function": "regex",
229
+ "group_select": -1,
230
+ "regex_pattern": "(-?[$0-9.,]{2,})|(-?[0-9]+)"
231
+ },
232
+ {
233
+ "function": "take_first"
234
+ }
235
+ ]
236
+ }
237
+ ],
238
+ "should_decontaminate": false,
239
+ "metadata": {
240
+ "version": 3.0,
241
+ "model": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled",
242
+ "base_url": "http://172.28.36.148:8000/v1/completions",
243
+ "num_concurrent": 4,
244
+ "tokenizer": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled"
245
+ }
246
+ },
247
+ "piqa": {
248
+ "task": "piqa",
249
+ "dataset_path": "baber/piqa",
250
+ "training_split": "train",
251
+ "validation_split": "validation",
252
+ "doc_to_text": "Question: {{goal}}\nAnswer:",
253
+ "doc_to_target": "label",
254
+ "unsafe_code": false,
255
+ "doc_to_choice": "{{[sol1, sol2]}}",
256
+ "description": "",
257
+ "target_delimiter": " ",
258
+ "fewshot_delimiter": "\n\n",
259
+ "fewshot_config": {
260
+ "sampler": "default",
261
+ "split": null,
262
+ "process_docs": null,
263
+ "fewshot_indices": null,
264
+ "samples": null,
265
+ "doc_to_text": "Question: {{goal}}\nAnswer:",
266
+ "doc_to_choice": "{{[sol1, sol2]}}",
267
+ "doc_to_target": "label",
268
+ "gen_prefix": null,
269
+ "fewshot_delimiter": "\n\n",
270
+ "target_delimiter": " "
271
+ },
272
+ "num_fewshot": 0,
273
+ "metric_list": [
274
+ {
275
+ "metric": "acc",
276
+ "aggregation": "mean",
277
+ "higher_is_better": true
278
+ },
279
+ {
280
+ "metric": "acc_norm",
281
+ "aggregation": "mean",
282
+ "higher_is_better": true
283
+ }
284
+ ],
285
+ "output_type": "multiple_choice",
286
+ "repeats": 1,
287
+ "should_decontaminate": true,
288
+ "doc_to_decontamination_query": "goal",
289
+ "metadata": {
290
+ "version": 1.0,
291
+ "model": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled",
292
+ "base_url": "http://172.28.36.148:8000/v1/completions",
293
+ "num_concurrent": 4,
294
+ "tokenizer": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled"
295
+ }
296
+ },
297
+ "winogrande": {
298
+ "task": "winogrande",
299
+ "dataset_path": "allenai/winogrande",
300
+ "dataset_name": "winogrande_xl",
301
+ "training_split": "train",
302
+ "validation_split": "validation",
303
+ "doc_to_text": "def doc_to_text(doc):\n answer_to_num = {\"1\": 0, \"2\": 1}\n return answer_to_num[doc[\"answer\"]]\n",
304
+ "doc_to_target": "def doc_to_target(doc):\n idx = doc[\"sentence\"].index(\"_\") + 1\n return doc[\"sentence\"][idx:].strip()\n",
305
+ "unsafe_code": false,
306
+ "doc_to_choice": "def doc_to_choice(doc):\n idx = doc[\"sentence\"].index(\"_\")\n options = [doc[\"option1\"], doc[\"option2\"]]\n return [doc[\"sentence\"][:idx] + opt for opt in options]\n",
307
+ "description": "",
308
+ "target_delimiter": " ",
309
+ "fewshot_delimiter": "\n\n",
310
+ "fewshot_config": {
311
+ "sampler": "default",
312
+ "split": null,
313
+ "process_docs": null,
314
+ "fewshot_indices": null,
315
+ "samples": null,
316
+ "doc_to_text": "<function doc_to_text at 0x400377cf8f40>",
317
+ "doc_to_choice": "<function doc_to_choice at 0x400377cf9d00>",
318
+ "doc_to_target": "<function doc_to_target at 0x400377cf9a80>",
319
+ "gen_prefix": null,
320
+ "fewshot_delimiter": "\n\n",
321
+ "target_delimiter": " "
322
+ },
323
+ "num_fewshot": 0,
324
+ "metric_list": [
325
+ {
326
+ "metric": "acc",
327
+ "aggregation": "mean",
328
+ "higher_is_better": true
329
+ }
330
+ ],
331
+ "output_type": "multiple_choice",
332
+ "repeats": 1,
333
+ "should_decontaminate": true,
334
+ "doc_to_decontamination_query": "sentence",
335
+ "metadata": {
336
+ "version": 1.0,
337
+ "model": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled",
338
+ "base_url": "http://172.28.36.148:8000/v1/completions",
339
+ "num_concurrent": 4,
340
+ "tokenizer": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled"
341
+ }
342
+ }
343
+ },
344
+ "versions": {
345
+ "arc_challenge": 1.0,
346
+ "arc_easy": 1.0,
347
+ "gsm8k": 3.0,
348
+ "piqa": 1.0,
349
+ "winogrande": 1.0
350
+ },
351
+ "n-shot": {
352
+ "arc_challenge": 0,
353
+ "arc_easy": 0,
354
+ "gsm8k": 5,
355
+ "piqa": 0,
356
+ "winogrande": 0
357
+ },
358
+ "higher_is_better": {
359
+ "arc_challenge": {
360
+ "acc": true,
361
+ "acc_norm": true
362
+ },
363
+ "arc_easy": {
364
+ "acc": true,
365
+ "acc_norm": true
366
+ },
367
+ "gsm8k": {
368
+ "exact_match": true
369
+ },
370
+ "piqa": {
371
+ "acc": true,
372
+ "acc_norm": true
373
+ },
374
+ "winogrande": {
375
+ "acc": true
376
+ }
377
+ },
378
+ "n-samples": {
379
+ "piqa": {
380
+ "original": 1838,
381
+ "effective": 1838
382
+ },
383
+ "winogrande": {
384
+ "original": 1267,
385
+ "effective": 1267
386
+ },
387
+ "arc_easy": {
388
+ "original": 2376,
389
+ "effective": 2376
390
+ },
391
+ "arc_challenge": {
392
+ "original": 1172,
393
+ "effective": 1172
394
+ },
395
+ "gsm8k": {
396
+ "original": 1319,
397
+ "effective": 1319
398
+ }
399
+ },
400
+ "config": {
401
+ "model": "local-completions",
402
+ "model_args": {
403
+ "model": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled",
404
+ "base_url": "http://172.28.36.148:8000/v1/completions",
405
+ "num_concurrent": 4,
406
+ "tokenizer": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled",
407
+ "trust_remote_code": true
408
+ },
409
+ "batch_size": 1,
410
+ "batch_sizes": [],
411
+ "device": "cuda:0",
412
+ "use_cache": null,
413
+ "limit": null,
414
+ "bootstrap_iters": 100000,
415
+ "gen_kwargs": {},
416
+ "random_seed": 0,
417
+ "numpy_seed": 1234,
418
+ "torch_seed": 1234,
419
+ "fewshot_seed": 1234
420
+ },
421
+ "git_hash": "b8f36fc",
422
+ "date": 1773333070.1730545,
423
+ "pretty_env_info": "PyTorch version: 2.8.0+cpu\nIs debug build: False\nCUDA used to build PyTorch: Could not collect\nROCM used to build PyTorch: N/A\n\nOS: SUSE Linux Enterprise Server 15 SP6 (aarch64)\nGCC version: (SUSE Linux) 7.5.0\nClang version: Could not collect\nCMake version: version 3.28.3\nLibc version: glibc-2.38\n\nPython version: 3.11.14 (main, Jan 14 2026, 19:35:38) [Clang 21.1.4 ] (64-bit runtime)\nPython platform: Linux-6.4.0-150600.23.47_15.0.10-cray_shasta_c_64k-aarch64-with-glibc2.38\nIs CUDA available: False\nCUDA runtime version: Could not collect\nCUDA_MODULE_LOADING set to: N/A\nGPU models and configuration: \nGPU 0: NVIDIA GH200 120GB\nGPU 1: NVIDIA GH200 120GB\nGPU 2: NVIDIA GH200 120GB\nGPU 3: NVIDIA GH200 120GB\n\nNvidia driver version: 590.48.01\ncuDNN version: Could not collect\nHIP runtime version: N/A\nMIOpen runtime version: N/A\nIs XNNPACK available: True\n\nCPU:\nArchitecture: aarch64\nCPU op-mode(s): 64-bit\nByte Order: Little Endian\nCPU(s): 288\nOn-line CPU(s) list: 0-287\nVendor ID: ARM\nModel name: Neoverse-V2\nModel: 0\nThread(s) per core: 1\nCore(s) per socket: 72\nSocket(s): 4\nStepping: r0p0\nFrequency boost: disabled\nCPU(s) scaling MHz: 100%\nCPU max MHz: 3447.0000\nCPU min MHz: 81.0000\nBogoMIPS: 2000.00\nFlags: fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh bti\nL1d cache: 18 MiB (288 instances)\nL1i cache: 18 MiB (288 instances)\nL2 cache: 288 MiB (288 instances)\nL3 cache: 456 MiB (4 instances)\nNUMA node(s): 36\nNUMA node0 CPU(s): 0-71\nNUMA node1 CPU(s): 72-143\nNUMA node2 CPU(s): 144-215\nNUMA node3 CPU(s): 216-287\nNUMA node4 CPU(s): \nNUMA node5 CPU(s): \nNUMA node6 CPU(s): \nNUMA node7 CPU(s): \nNUMA node8 CPU(s): \nNUMA node9 CPU(s): \nNUMA node10 CPU(s): \nNUMA node11 CPU(s): \nNUMA node12 CPU(s): \nNUMA node13 CPU(s): \nNUMA node14 CPU(s): \nNUMA node15 CPU(s): \nNUMA node16 CPU(s): \nNUMA node17 CPU(s): \nNUMA node18 CPU(s): \nNUMA node19 CPU(s): \nNUMA node20 CPU(s): \nNUMA node21 CPU(s): \nNUMA node22 CPU(s): \nNUMA node23 CPU(s): \nNUMA node24 CPU(s): \nNUMA node25 CPU(s): \nNUMA node26 CPU(s): \nNUMA node27 CPU(s): \nNUMA node28 CPU(s): \nNUMA node29 CPU(s): \nNUMA node30 CPU(s): \nNUMA node31 CPU(s): \nNUMA node32 CPU(s): \nNUMA node33 CPU(s): \nNUMA node34 CPU(s): \nNUMA node35 CPU(s): \nVulnerability Gather data sampling: Not affected\nVulnerability Itlb multihit: Not affected\nVulnerability L1tf: Not affected\nVulnerability Mds: Not affected\nVulnerability Meltdown: Not affected\nVulnerability Mmio stale data: Not affected\nVulnerability Reg file data sampling: Not affected\nVulnerability Retbleed: Not affected\nVulnerability Spec rstack overflow: Not affected\nVulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl\nVulnerability Spectre v1: Mitigation; __user pointer sanitization\nVulnerability Spectre v2: Mitigation; CSV2, BHB\nVulnerability Srbds: Not affected\nVulnerability Tsx async abort: Not affected\n\nVersions of relevant libraries:\n[pip3] Could not collect\n[conda] Could not collect",
424
+ "transformers_version": "4.57.6",
425
+ "lm_eval_version": "0.4.11",
426
+ "upper_git_hash": null,
427
+ "tokenizer_pad_token": [
428
+ "[PAD]",
429
+ "163839"
430
+ ],
431
+ "tokenizer_eos_token": [
432
+ "[EOS]",
433
+ "163585"
434
+ ],
435
+ "tokenizer_bos_token": [
436
+ "[BOS]",
437
+ "163584"
438
+ ],
439
+ "eot_token_id": 163585,
440
+ "max_length": 2047,
441
+ "task_hashes": {
442
+ "piqa": "74d5a816572c396ad46edbd386954abe5ddb3db2d7195088387d1d5c1b32fd8b",
443
+ "winogrande": "a5ea73eb24ab46d111fe5d21eed85b1e779c0b309d80d080c3caa21a851b6feb",
444
+ "arc_easy": "dce0d9b0f0cecd55bf2ac264042c5e45487df708d13123af3ae9e67bbbefdeb1",
445
+ "arc_challenge": "09f9ae87a0905d63512cffc4aa91a55e44258fc35160e40fa1eb66fb75473e34",
446
+ "gsm8k": "2330f4ebfcccaf66a892922df2819cdb1f118e448d076d3f42bdde4177678ac7"
447
+ },
448
+ "model_source": "local-completions",
449
+ "model_name": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled",
450
+ "model_name_sanitized": "__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled",
451
+ "system_instruction": null,
452
+ "system_instruction_sha": null,
453
+ "fewshot_as_multiturn": null,
454
+ "chat_template": null,
455
+ "chat_template_sha": null,
456
+ "total_evaluation_time_seconds": "2672.023873636994"
457
+ }
evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/results_2026-03-12T20-16-45.465199.json ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "results": {
3
+ "arc_challenge": {
4
+ "alias": "arc_challenge",
5
+ "acc,none": 0.5836177474402731,
6
+ "acc_stderr,none": 0.01440561827943618,
7
+ "acc_norm,none": 0.6296928327645052,
8
+ "acc_norm_stderr,none": 0.01411129875167495
9
+ },
10
+ "arc_easy": {
11
+ "alias": "arc_easy",
12
+ "acc,none": 0.8493265993265994,
13
+ "acc_stderr,none": 0.0073404697111406885,
14
+ "acc_norm,none": 0.851010101010101,
15
+ "acc_norm_stderr,none": 0.007306576964809532
16
+ },
17
+ "gsm8k": {
18
+ "alias": "gsm8k",
19
+ "exact_match,strict-match": 0.9257012888551933,
20
+ "exact_match_stderr,strict-match": 0.0072238441728455895,
21
+ "exact_match,flexible-extract": 0.9249431387414708,
22
+ "exact_match_stderr,flexible-extract": 0.007257633145486643
23
+ },
24
+ "piqa": {
25
+ "alias": "piqa",
26
+ "acc,none": 0.8171926006528836,
27
+ "acc_stderr,none": 0.009017881410505958,
28
+ "acc_norm,none": 0.823721436343852,
29
+ "acc_norm_stderr,none": 0.008890687746582126
30
+ },
31
+ "winogrande": {
32
+ "alias": "winogrande",
33
+ "acc,none": 0.7695343330702447,
34
+ "acc_stderr,none": 0.01183587216483666
35
+ }
36
+ },
37
+ "group_subtasks": {
38
+ "gsm8k": [],
39
+ "arc_challenge": [],
40
+ "arc_easy": [],
41
+ "winogrande": [],
42
+ "piqa": []
43
+ },
44
+ "configs": {
45
+ "arc_challenge": {
46
+ "task": "arc_challenge",
47
+ "tag": [
48
+ "ai2_arc"
49
+ ],
50
+ "dataset_path": "allenai/ai2_arc",
51
+ "dataset_name": "ARC-Challenge",
52
+ "training_split": "train",
53
+ "validation_split": "validation",
54
+ "test_split": "test",
55
+ "doc_to_text": "Question: {{question}}\nAnswer:",
56
+ "doc_to_target": "{{choices.label.index(answerKey)}}",
57
+ "unsafe_code": false,
58
+ "doc_to_choice": "{{choices.text}}",
59
+ "description": "",
60
+ "target_delimiter": " ",
61
+ "fewshot_delimiter": "\n\n",
62
+ "fewshot_config": {
63
+ "sampler": "default",
64
+ "split": null,
65
+ "process_docs": null,
66
+ "fewshot_indices": null,
67
+ "samples": null,
68
+ "doc_to_text": "Question: {{question}}\nAnswer:",
69
+ "doc_to_choice": "{{choices.text}}",
70
+ "doc_to_target": "{{choices.label.index(answerKey)}}",
71
+ "gen_prefix": null,
72
+ "fewshot_delimiter": "\n\n",
73
+ "target_delimiter": " "
74
+ },
75
+ "num_fewshot": 0,
76
+ "metric_list": [
77
+ {
78
+ "metric": "acc",
79
+ "aggregation": "mean",
80
+ "higher_is_better": true
81
+ },
82
+ {
83
+ "metric": "acc_norm",
84
+ "aggregation": "mean",
85
+ "higher_is_better": true
86
+ }
87
+ ],
88
+ "output_type": "multiple_choice",
89
+ "repeats": 1,
90
+ "should_decontaminate": true,
91
+ "doc_to_decontamination_query": "Question: {{question}}\nAnswer:",
92
+ "metadata": {
93
+ "version": 1.0,
94
+ "model": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled",
95
+ "base_url": "http://172.28.35.44:8000/v1/completions",
96
+ "num_concurrent": 8,
97
+ "tokenizer": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled"
98
+ }
99
+ },
100
+ "arc_easy": {
101
+ "task": "arc_easy",
102
+ "tag": [
103
+ "ai2_arc"
104
+ ],
105
+ "dataset_path": "allenai/ai2_arc",
106
+ "dataset_name": "ARC-Easy",
107
+ "training_split": "train",
108
+ "validation_split": "validation",
109
+ "test_split": "test",
110
+ "doc_to_text": "Question: {{question}}\nAnswer:",
111
+ "doc_to_target": "{{choices.label.index(answerKey)}}",
112
+ "unsafe_code": false,
113
+ "doc_to_choice": "{{choices.text}}",
114
+ "description": "",
115
+ "target_delimiter": " ",
116
+ "fewshot_delimiter": "\n\n",
117
+ "fewshot_config": {
118
+ "sampler": "default",
119
+ "split": null,
120
+ "process_docs": null,
121
+ "fewshot_indices": null,
122
+ "samples": null,
123
+ "doc_to_text": "Question: {{question}}\nAnswer:",
124
+ "doc_to_choice": "{{choices.text}}",
125
+ "doc_to_target": "{{choices.label.index(answerKey)}}",
126
+ "gen_prefix": null,
127
+ "fewshot_delimiter": "\n\n",
128
+ "target_delimiter": " "
129
+ },
130
+ "num_fewshot": 0,
131
+ "metric_list": [
132
+ {
133
+ "metric": "acc",
134
+ "aggregation": "mean",
135
+ "higher_is_better": true
136
+ },
137
+ {
138
+ "metric": "acc_norm",
139
+ "aggregation": "mean",
140
+ "higher_is_better": true
141
+ }
142
+ ],
143
+ "output_type": "multiple_choice",
144
+ "repeats": 1,
145
+ "should_decontaminate": true,
146
+ "doc_to_decontamination_query": "Question: {{question}}\nAnswer:",
147
+ "metadata": {
148
+ "version": 1.0,
149
+ "model": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled",
150
+ "base_url": "http://172.28.35.44:8000/v1/completions",
151
+ "num_concurrent": 8,
152
+ "tokenizer": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled"
153
+ }
154
+ },
155
+ "gsm8k": {
156
+ "task": "gsm8k",
157
+ "tag": [
158
+ "math_word_problems"
159
+ ],
160
+ "dataset_path": "openai/gsm8k",
161
+ "dataset_name": "main",
162
+ "training_split": "train",
163
+ "test_split": "test",
164
+ "fewshot_split": "train",
165
+ "doc_to_text": "Question: {{question}}\nAnswer:",
166
+ "doc_to_target": "{{answer}}",
167
+ "unsafe_code": false,
168
+ "description": "",
169
+ "target_delimiter": " ",
170
+ "fewshot_delimiter": "\n\n",
171
+ "fewshot_config": {
172
+ "sampler": "default",
173
+ "split": "train",
174
+ "process_docs": null,
175
+ "fewshot_indices": null,
176
+ "samples": null,
177
+ "doc_to_text": "Question: {{question}}\nAnswer:",
178
+ "doc_to_choice": null,
179
+ "doc_to_target": "{{answer}}",
180
+ "gen_prefix": null,
181
+ "fewshot_delimiter": "\n\n",
182
+ "target_delimiter": " "
183
+ },
184
+ "num_fewshot": 5,
185
+ "metric_list": [
186
+ {
187
+ "metric": "exact_match",
188
+ "aggregation": "mean",
189
+ "higher_is_better": true,
190
+ "ignore_case": true,
191
+ "ignore_punctuation": false,
192
+ "regexes_to_ignore": [
193
+ ",",
194
+ "\\$",
195
+ "(?s).*#### ",
196
+ "\\.$"
197
+ ]
198
+ }
199
+ ],
200
+ "output_type": "generate_until",
201
+ "generation_kwargs": {
202
+ "until": [
203
+ "Question:",
204
+ "</s>",
205
+ "<|im_end|>"
206
+ ],
207
+ "do_sample": false,
208
+ "temperature": 0,
209
+ "seed": 42
210
+ },
211
+ "repeats": 1,
212
+ "filter_list": [
213
+ {
214
+ "name": "strict-match",
215
+ "filter": [
216
+ {
217
+ "function": "regex",
218
+ "regex_pattern": "#### (\\-?[0-9\\.\\,]+)"
219
+ },
220
+ {
221
+ "function": "take_first"
222
+ }
223
+ ]
224
+ },
225
+ {
226
+ "name": "flexible-extract",
227
+ "filter": [
228
+ {
229
+ "function": "regex",
230
+ "group_select": -1,
231
+ "regex_pattern": "(-?[$0-9.,]{2,})|(-?[0-9]+)"
232
+ },
233
+ {
234
+ "function": "take_first"
235
+ }
236
+ ]
237
+ }
238
+ ],
239
+ "should_decontaminate": false,
240
+ "metadata": {
241
+ "version": 3.0,
242
+ "model": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled",
243
+ "base_url": "http://172.28.35.44:8000/v1/completions",
244
+ "num_concurrent": 8,
245
+ "tokenizer": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled"
246
+ }
247
+ },
248
+ "piqa": {
249
+ "task": "piqa",
250
+ "dataset_path": "baber/piqa",
251
+ "training_split": "train",
252
+ "validation_split": "validation",
253
+ "doc_to_text": "Question: {{goal}}\nAnswer:",
254
+ "doc_to_target": "label",
255
+ "unsafe_code": false,
256
+ "doc_to_choice": "{{[sol1, sol2]}}",
257
+ "description": "",
258
+ "target_delimiter": " ",
259
+ "fewshot_delimiter": "\n\n",
260
+ "fewshot_config": {
261
+ "sampler": "default",
262
+ "split": null,
263
+ "process_docs": null,
264
+ "fewshot_indices": null,
265
+ "samples": null,
266
+ "doc_to_text": "Question: {{goal}}\nAnswer:",
267
+ "doc_to_choice": "{{[sol1, sol2]}}",
268
+ "doc_to_target": "label",
269
+ "gen_prefix": null,
270
+ "fewshot_delimiter": "\n\n",
271
+ "target_delimiter": " "
272
+ },
273
+ "num_fewshot": 0,
274
+ "metric_list": [
275
+ {
276
+ "metric": "acc",
277
+ "aggregation": "mean",
278
+ "higher_is_better": true
279
+ },
280
+ {
281
+ "metric": "acc_norm",
282
+ "aggregation": "mean",
283
+ "higher_is_better": true
284
+ }
285
+ ],
286
+ "output_type": "multiple_choice",
287
+ "repeats": 1,
288
+ "should_decontaminate": true,
289
+ "doc_to_decontamination_query": "goal",
290
+ "metadata": {
291
+ "version": 1.0,
292
+ "model": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled",
293
+ "base_url": "http://172.28.35.44:8000/v1/completions",
294
+ "num_concurrent": 8,
295
+ "tokenizer": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled"
296
+ }
297
+ },
298
+ "winogrande": {
299
+ "task": "winogrande",
300
+ "dataset_path": "allenai/winogrande",
301
+ "dataset_name": "winogrande_xl",
302
+ "training_split": "train",
303
+ "validation_split": "validation",
304
+ "doc_to_text": "def doc_to_text(doc):\n answer_to_num = {\"1\": 0, \"2\": 1}\n return answer_to_num[doc[\"answer\"]]\n",
305
+ "doc_to_target": "def doc_to_target(doc):\n idx = doc[\"sentence\"].index(\"_\") + 1\n return doc[\"sentence\"][idx:].strip()\n",
306
+ "unsafe_code": false,
307
+ "doc_to_choice": "def doc_to_choice(doc):\n idx = doc[\"sentence\"].index(\"_\")\n options = [doc[\"option1\"], doc[\"option2\"]]\n return [doc[\"sentence\"][:idx] + opt for opt in options]\n",
308
+ "description": "",
309
+ "target_delimiter": " ",
310
+ "fewshot_delimiter": "\n\n",
311
+ "fewshot_config": {
312
+ "sampler": "default",
313
+ "split": null,
314
+ "process_docs": null,
315
+ "fewshot_indices": null,
316
+ "samples": null,
317
+ "doc_to_text": "<function doc_to_text at 0x40048a7c8fe0>",
318
+ "doc_to_choice": "<function doc_to_choice at 0x40048a7c9da0>",
319
+ "doc_to_target": "<function doc_to_target at 0x40048a7c9b20>",
320
+ "gen_prefix": null,
321
+ "fewshot_delimiter": "\n\n",
322
+ "target_delimiter": " "
323
+ },
324
+ "num_fewshot": 0,
325
+ "metric_list": [
326
+ {
327
+ "metric": "acc",
328
+ "aggregation": "mean",
329
+ "higher_is_better": true
330
+ }
331
+ ],
332
+ "output_type": "multiple_choice",
333
+ "repeats": 1,
334
+ "should_decontaminate": true,
335
+ "doc_to_decontamination_query": "sentence",
336
+ "metadata": {
337
+ "version": 1.0,
338
+ "model": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled",
339
+ "base_url": "http://172.28.35.44:8000/v1/completions",
340
+ "num_concurrent": 8,
341
+ "tokenizer": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled"
342
+ }
343
+ }
344
+ },
345
+ "versions": {
346
+ "arc_challenge": 1.0,
347
+ "arc_easy": 1.0,
348
+ "gsm8k": 3.0,
349
+ "piqa": 1.0,
350
+ "winogrande": 1.0
351
+ },
352
+ "n-shot": {
353
+ "arc_challenge": 0,
354
+ "arc_easy": 0,
355
+ "gsm8k": 5,
356
+ "piqa": 0,
357
+ "winogrande": 0
358
+ },
359
+ "higher_is_better": {
360
+ "arc_challenge": {
361
+ "acc": true,
362
+ "acc_norm": true
363
+ },
364
+ "arc_easy": {
365
+ "acc": true,
366
+ "acc_norm": true
367
+ },
368
+ "gsm8k": {
369
+ "exact_match": true
370
+ },
371
+ "piqa": {
372
+ "acc": true,
373
+ "acc_norm": true
374
+ },
375
+ "winogrande": {
376
+ "acc": true
377
+ }
378
+ },
379
+ "n-samples": {
380
+ "piqa": {
381
+ "original": 1838,
382
+ "effective": 1838
383
+ },
384
+ "winogrande": {
385
+ "original": 1267,
386
+ "effective": 1267
387
+ },
388
+ "arc_easy": {
389
+ "original": 2376,
390
+ "effective": 2376
391
+ },
392
+ "arc_challenge": {
393
+ "original": 1172,
394
+ "effective": 1172
395
+ },
396
+ "gsm8k": {
397
+ "original": 1319,
398
+ "effective": 1319
399
+ }
400
+ },
401
+ "config": {
402
+ "model": "local-completions",
403
+ "model_args": {
404
+ "model": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled",
405
+ "base_url": "http://172.28.35.44:8000/v1/completions",
406
+ "num_concurrent": 8,
407
+ "tokenizer": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled",
408
+ "trust_remote_code": true
409
+ },
410
+ "batch_size": 1,
411
+ "batch_sizes": [],
412
+ "device": "cuda:0",
413
+ "use_cache": null,
414
+ "limit": null,
415
+ "bootstrap_iters": 100000,
416
+ "gen_kwargs": {
417
+ "temperature": 0,
418
+ "seed": 42
419
+ },
420
+ "random_seed": 0,
421
+ "numpy_seed": 1234,
422
+ "torch_seed": 1234,
423
+ "fewshot_seed": 1234
424
+ },
425
+ "git_hash": "b8f36fc",
426
+ "date": 1773341141.349453,
427
+ "pretty_env_info": "PyTorch version: 2.8.0+cpu\nIs debug build: False\nCUDA used to build PyTorch: Could not collect\nROCM used to build PyTorch: N/A\n\nOS: SUSE Linux Enterprise Server 15 SP6 (aarch64)\nGCC version: (SUSE Linux) 7.5.0\nClang version: Could not collect\nCMake version: version 3.28.3\nLibc version: glibc-2.38\n\nPython version: 3.11.14 (main, Jan 14 2026, 19:35:38) [Clang 21.1.4 ] (64-bit runtime)\nPython platform: Linux-6.4.0-150600.23.47_15.0.10-cray_shasta_c_64k-aarch64-with-glibc2.38\nIs CUDA available: False\nCUDA runtime version: Could not collect\nCUDA_MODULE_LOADING set to: N/A\nGPU models and configuration: \nGPU 0: NVIDIA GH200 120GB\nGPU 1: NVIDIA GH200 120GB\nGPU 2: NVIDIA GH200 120GB\nGPU 3: NVIDIA GH200 120GB\n\nNvidia driver version: 590.48.01\ncuDNN version: Could not collect\nHIP runtime version: N/A\nMIOpen runtime version: N/A\nIs XNNPACK available: True\n\nCPU:\nArchitecture: aarch64\nCPU op-mode(s): 64-bit\nByte Order: Little Endian\nCPU(s): 288\nOn-line CPU(s) list: 0-287\nVendor ID: ARM\nModel name: Neoverse-V2\nModel: 0\nThread(s) per core: 1\nCore(s) per socket: 72\nSocket(s): 4\nStepping: r0p0\nFrequency boost: disabled\nCPU(s) scaling MHz: 100%\nCPU max MHz: 3429.0000\nCPU min MHz: 81.0000\nBogoMIPS: 2000.00\nFlags: fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh bti\nL1d cache: 18 MiB (288 instances)\nL1i cache: 18 MiB (288 instances)\nL2 cache: 288 MiB (288 instances)\nL3 cache: 456 MiB (4 instances)\nNUMA node(s): 36\nNUMA node0 CPU(s): 0-71\nNUMA node1 CPU(s): 72-143\nNUMA node2 CPU(s): 144-215\nNUMA node3 CPU(s): 216-287\nNUMA node4 CPU(s): \nNUMA node5 CPU(s): \nNUMA node6 CPU(s): \nNUMA node7 CPU(s): \nNUMA node8 CPU(s): \nNUMA node9 CPU(s): \nNUMA node10 CPU(s): \nNUMA node11 CPU(s): \nNUMA node12 CPU(s): \nNUMA node13 CPU(s): \nNUMA node14 CPU(s): \nNUMA node15 CPU(s): \nNUMA node16 CPU(s): \nNUMA node17 CPU(s): \nNUMA node18 CPU(s): \nNUMA node19 CPU(s): \nNUMA node20 CPU(s): \nNUMA node21 CPU(s): \nNUMA node22 CPU(s): \nNUMA node23 CPU(s): \nNUMA node24 CPU(s): \nNUMA node25 CPU(s): \nNUMA node26 CPU(s): \nNUMA node27 CPU(s): \nNUMA node28 CPU(s): \nNUMA node29 CPU(s): \nNUMA node30 CPU(s): \nNUMA node31 CPU(s): \nNUMA node32 CPU(s): \nNUMA node33 CPU(s): \nNUMA node34 CPU(s): \nNUMA node35 CPU(s): \nVulnerability Gather data sampling: Not affected\nVulnerability Itlb multihit: Not affected\nVulnerability L1tf: Not affected\nVulnerability Mds: Not affected\nVulnerability Meltdown: Not affected\nVulnerability Mmio stale data: Not affected\nVulnerability Reg file data sampling: Not affected\nVulnerability Retbleed: Not affected\nVulnerability Spec rstack overflow: Not affected\nVulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl\nVulnerability Spectre v1: Mitigation; __user pointer sanitization\nVulnerability Spectre v2: Mitigation; CSV2, BHB\nVulnerability Srbds: Not affected\nVulnerability Tsx async abort: Not affected\n\nVersions of relevant libraries:\n[pip3] Could not collect\n[conda] Could not collect",
428
+ "transformers_version": "4.57.6",
429
+ "lm_eval_version": "0.4.11",
430
+ "upper_git_hash": null,
431
+ "tokenizer_pad_token": [
432
+ "[PAD]",
433
+ "163839"
434
+ ],
435
+ "tokenizer_eos_token": [
436
+ "[EOS]",
437
+ "163585"
438
+ ],
439
+ "tokenizer_bos_token": [
440
+ "[BOS]",
441
+ "163584"
442
+ ],
443
+ "eot_token_id": 163585,
444
+ "max_length": 2047,
445
+ "task_hashes": {
446
+ "piqa": "74d5a816572c396ad46edbd386954abe5ddb3db2d7195088387d1d5c1b32fd8b",
447
+ "winogrande": "a5ea73eb24ab46d111fe5d21eed85b1e779c0b309d80d080c3caa21a851b6feb",
448
+ "arc_easy": "dce0d9b0f0cecd55bf2ac264042c5e45487df708d13123af3ae9e67bbbefdeb1",
449
+ "arc_challenge": "09f9ae87a0905d63512cffc4aa91a55e44258fc35160e40fa1eb66fb75473e34",
450
+ "gsm8k": "2330f4ebfcccaf66a892922df2819cdb1f118e448d076d3f42bdde4177678ac7"
451
+ },
452
+ "model_source": "local-completions",
453
+ "model_name": "/iopsstor/scratch/cscs/stabesh/gsq/checkpoints/kimi-k2.5/20260309-051218_968da2/assembled",
454
+ "model_name_sanitized": "__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled",
455
+ "system_instruction": null,
456
+ "system_instruction_sha": null,
457
+ "fewshot_as_multiturn": null,
458
+ "chat_template": null,
459
+ "chat_template_sha": null,
460
+ "total_evaluation_time_seconds": "1878.9676014350116"
461
+ }
evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_arc_challenge_2026-03-12T18-13-57.415988.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_arc_challenge_2026-03-12T18-15-26.173888.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_arc_challenge_2026-03-12T20-16-45.465199.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_arc_easy_2026-03-12T18-13-57.415988.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_arc_easy_2026-03-12T18-15-26.173888.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_arc_easy_2026-03-12T20-16-45.465199.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_gsm8k_2026-03-12T18-13-57.415988.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:36f941316abb44a923697451df26a6f0b1ed37d336db62b85b5044fc1aa77f55
3
+ size 12424305
evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_gsm8k_2026-03-12T18-15-26.173888.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:736126fdd61103cfc4d2be0083793bed35073537a881db8e734de2b701bb8834
3
+ size 12426413
evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_gsm8k_2026-03-12T20-16-45.465199.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1441d5bf49ea846ebb87c6edb92b43c696c0d64c33cdefed88ce05b1f7a663fc
3
+ size 12452038
evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_piqa_2026-03-12T18-13-57.415988.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_piqa_2026-03-12T18-15-26.173888.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_piqa_2026-03-12T20-16-45.465199.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_winogrande_2026-03-12T18-13-57.415988.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_winogrande_2026-03-12T18-15-26.173888.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
evals/__iopsstor__scratch__cscs__stabesh__gsq__checkpoints__kimi-k2.5__20260309-051218_968da2__assembled/samples_winogrande_2026-03-12T20-16-45.465199.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "max_length": 262144,
3
+ "eos_token_id": 163586
4
+ }
kimi_k25_vision_processing.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Image processor class for Kimi-K2.5.
2
+ """
3
+
4
+ import json
5
+ from typing import Any, Dict, Optional, Union
6
+
7
+ import numpy as np
8
+ import torch
9
+ from PIL import Image
10
+ from transformers.image_processing_utils import (BaseImageProcessor,
11
+ BatchFeature)
12
+ from transformers.utils import TensorType
13
+
14
+ from .media_utils import (MediaInput, VideoChunkInput, _to_tensor,
15
+ ensure_media_type, get_video_meta, image_to_np,
16
+ navit_patchify, navit_resize_image,
17
+ navit_resize_video, normalize,
18
+ real_sample_fps_and_max_num_frames, timestamp_as_str)
19
+
20
+ try:
21
+ from mecord import VideoReader
22
+ except ImportError:
23
+ VideoReader = None
24
+
25
+
26
+ def resampling(video_bytes: bytes,
27
+ sample_indices: list[int],
28
+ key_indices=None,
29
+ frame_time_info=None,
30
+ num_threads=4) -> str:
31
+ video = VideoReader(video_bytes,
32
+ num_threads=num_threads,
33
+ frame_time_info=frame_time_info,
34
+ key_indices=key_indices)
35
+ # extract target frames
36
+ frames = video[sample_indices]
37
+ frames = [Image.fromarray(frame) for frame in frames]
38
+ return frames
39
+
40
+
41
+ class KimiK25VisionProcessor(BaseImageProcessor):
42
+ model_type = "kimi_k25"
43
+
44
+ def __init__(
45
+ self,
46
+ media_proc_cfg: dict,
47
+ **kwargs,
48
+ ):
49
+ super().__init__(**kwargs)
50
+ self.media_proc_cfg = media_proc_cfg
51
+ self.num_frames_per_chunk = media_proc_cfg[
52
+ 'temporal_merge_kernel_size']
53
+
54
+ def media_tokens_calculator(self, media: MediaInput):
55
+ media = ensure_media_type(media)
56
+ ret = self.get_resize_config(media)
57
+ return ret['num_tokens']
58
+
59
+ @classmethod
60
+ def make_chunk_prompt(cls, timestamp_text: str) -> str:
61
+ return f"{timestamp_text}<|media_begin|>video<|media_content|><|media_pad|><|media_end|>"
62
+
63
+ def split_video_chunks(self,
64
+ video_url: str | bytes) -> list[list[Image.Image]]:
65
+ # video_url should be base64 str or bytes
66
+ video_spec = get_video_meta(video_url)
67
+ sample_fps = min(self.media_proc_cfg['sample_fps'], video_spec.fps)
68
+ sampled_nframes = max(
69
+ round(video_spec.num_frames * sample_fps / video_spec.fps), 1)
70
+ frame_inds = np.linspace(0, video_spec.num_frames - 1,
71
+ sampled_nframes).round().astype(int)
72
+ frame_inds = frame_inds.tolist()
73
+ sampled_frame_ids = []
74
+ temporal_merge_kernel_size = self.media_proc_cfg[
75
+ "temporal_merge_kernel_size"]
76
+ num_chunks = 0
77
+ chunk_timestamp = []
78
+ for i in range(0, len(frame_inds), temporal_merge_kernel_size):
79
+ sampled_frame_ids.extend(frame_inds[i:i +
80
+ temporal_merge_kernel_size])
81
+ start_time = frame_inds[i] / float(video_spec.fps)
82
+ timestamp_text = timestamp_as_str(
83
+ start_time, self.media_proc_cfg["timestamp_mode"])
84
+ chunk_timestamp.append(timestamp_text)
85
+ num_chunks += 1
86
+
87
+ sampled_frames = resampling(video_url, sampled_frame_ids)
88
+ chunks = []
89
+ for chunk_id in range(num_chunks):
90
+ chunk = sampled_frames[chunk_id *
91
+ temporal_merge_kernel_size:(chunk_id + 1) *
92
+ temporal_merge_kernel_size]
93
+ chunks.append(
94
+ VideoChunkInput(type="video_chunk",
95
+ video_chunk=chunk,
96
+ prompt=self.make_chunk_prompt(
97
+ chunk_timestamp[chunk_id])))
98
+ return chunks
99
+
100
+ def get_resize_config(self, media_input: MediaInput) -> dict:
101
+ if media_input['type'] == 'image':
102
+ w, h = media_input['image'].size
103
+ ret = navit_resize_image(
104
+ w, h, self.media_proc_cfg['patch_size'],
105
+ self.media_proc_cfg['merge_kernel_size'],
106
+ self.media_proc_cfg['in_patch_limit'],
107
+ self.media_proc_cfg['patch_limit_on_one_side'],
108
+ self.media_proc_cfg['fixed_output_tokens'])
109
+ return ret
110
+ elif media_input['type'] == 'video_chunk':
111
+ frame = media_input['video_chunk'][0]
112
+ width, height = frame.size
113
+ num_frames = len(media_input["video_chunk"])
114
+ fps = 1.0
115
+
116
+ sample_fps, max_num_frames_each_video = real_sample_fps_and_max_num_frames(
117
+ media_input["type"],
118
+ self.media_proc_cfg['sample_fps'],
119
+ self.media_proc_cfg['max_num_frames_each_video'],
120
+ )
121
+
122
+ in_patch_limit_each_frame = self.media_proc_cfg[
123
+ 'in_patch_limit_each_frame']
124
+ if in_patch_limit_each_frame is None:
125
+ in_patch_limit_each_frame = self.media_proc_cfg[
126
+ 'in_patch_limit']
127
+
128
+ ret = navit_resize_video(
129
+ width,
130
+ height,
131
+ num_frames,
132
+ fps,
133
+ sample_fps,
134
+ self.media_proc_cfg['patch_size'],
135
+ self.media_proc_cfg['merge_kernel_size'],
136
+ in_patch_limit_each_frame,
137
+ self.media_proc_cfg['patch_limit_on_one_side'],
138
+ self.media_proc_cfg['in_patch_limit_video'],
139
+ max_num_frames_each_video,
140
+ self.media_proc_cfg['fixed_output_tokens'],
141
+ )
142
+ return ret
143
+ else:
144
+ raise ValueError("Unsupported type: {}".format(
145
+ media_input['type']))
146
+
147
+ def resize_image(self, image: Image.Image, new_width: int, new_height: int,
148
+ pad_width: int, pad_height: int) -> np.ndarray:
149
+ image_np = image_to_np(image, (new_width, new_height), "resize")
150
+ image_np = np.pad(
151
+ image_np,
152
+ ((0, pad_height), (0, pad_width), (0, 0)),
153
+ mode="constant",
154
+ constant_values=0,
155
+ )
156
+ return image_np
157
+
158
+ def preprocess(
159
+ self,
160
+ medias: list[MediaInput],
161
+ return_tensors: Optional[Union[str, TensorType]] = None,
162
+ ) -> BatchFeature:
163
+ """
164
+ Preprocess a atom vision input (images/video_chunk) into model-ready tensors.
165
+
166
+ Args:
167
+ medias: List of MediaInput.
168
+ return_tensors: Desired output format ('pt', 'np', 'tf', or None).
169
+
170
+ Returns:
171
+ BatchFeature containing 'pixel_values' and 'grid_thws' tensors.
172
+ """
173
+ if not isinstance(medias, list):
174
+ medias = [medias]
175
+ if medias:
176
+ pixel_values = []
177
+ for item in medias:
178
+ item = ensure_media_type(item)
179
+ resize_config = self.get_resize_config(item)
180
+ new_width, new_height, pad_width, pad_height = resize_config[
181
+ 'new_width'], resize_config['new_height'], resize_config[
182
+ 'pad_width'], resize_config['pad_height']
183
+ if item['type'] == 'image':
184
+ image = item['image']
185
+ image_np = self.resize_image(image, new_width, new_height,
186
+ pad_width, pad_height)
187
+ pixel_values.append(np.expand_dims(image_np, axis=0))
188
+ elif item['type'] == 'video_chunk':
189
+ pixels = []
190
+ for frame in item['video_chunk']:
191
+ frame_np = self.resize_image(frame, new_width,
192
+ new_height, pad_width,
193
+ pad_height)
194
+ pixels.append(frame_np)
195
+ pixel_values.append(np.stack(pixels, axis=0))
196
+ else:
197
+ raise ValueError("Unsupported type: {}".format(
198
+ item['type']))
199
+ normalized_pixel_values = []
200
+ image_std_inv = 1.0 / np.array(self.media_proc_cfg['image_std'])
201
+ image_mean = np.array(self.media_proc_cfg['image_mean'])
202
+ for pixels in pixel_values:
203
+ pixels = normalize(pixels, image_mean, image_std_inv)
204
+ pixels_and_thw = navit_patchify(
205
+ pixels,
206
+ self.media_proc_cfg['patch_size'],
207
+ )
208
+ normalized_pixel_values.append(pixels_and_thw)
209
+
210
+ pixel_values = torch.cat([
211
+ _to_tensor(pixel_value['pixel_values'])
212
+ for pixel_value in normalized_pixel_values
213
+ ])
214
+ grid_thws = torch.cat([
215
+ _to_tensor(pixel_value['grid_thw'],
216
+ dtype=torch.int64).unsqueeze(0)
217
+ for pixel_value in normalized_pixel_values
218
+ ])
219
+
220
+ data = {
221
+ 'pixel_values': pixel_values,
222
+ 'grid_thws': grid_thws,
223
+ }
224
+
225
+ else:
226
+ data = {}
227
+
228
+ return BatchFeature(data=data, tensor_type=return_tensors)
229
+
230
+ def __repr__(self):
231
+ return f"KimiK25VisionProcessor(media_proc_cfg={self.media_proc_cfg})"
232
+
233
+ def to_dict(self) -> Dict[str, Any]:
234
+ output = super().to_dict()
235
+ output["media_proc_cfg"] = self.media_proc_cfg
236
+ if "media_processor" in output:
237
+ del output["media_processor"]
238
+ return output
239
+
240
+ @classmethod
241
+ def from_dict(cls, config_dict: Dict[str, Any], **kwargs):
242
+ config = config_dict.copy()
243
+ media_proc_cfg = config.pop("media_proc_cfg", {})
244
+ return cls(media_proc_cfg=media_proc_cfg, **config, **kwargs)
245
+
246
+ def to_json_string(self):
247
+ dictionary = self.to_dict()
248
+ for key, value in dictionary.items():
249
+ if hasattr(value, 'tolist'):
250
+ dictionary[key] = value.tolist()
251
+ return json.dumps(dictionary, indent=2, sort_keys=True) + "\n"
model-00007-of-00062.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:64c4c16f9c998a0f296582c9ecba8684acbaaa9a6ecfd40360f879cf6dc2060d
3
+ size 9016319096
model-00015-of-00062.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:db621894415b5d289ffe7de10c665c8025bc21842adf52d058fc3004211e9364
3
+ size 9016322568
model-00016-of-00062.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3760d9de9d437663aae93bba39c13715b826199e6ec4bd56486eec77d54262f2
3
+ size 9016322568
model-00017-of-00062.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ab70404a78927af3c151bd70e244fbb75254dff45a5e066d4e365c19bfde93d2
3
+ size 9016322568
model-00018-of-00062.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7b5e62b3fa5ffc5e2b2d72be5fe6247e50f2053828c81a26de1b388c590fbc67
3
+ size 9016322568
model-00021-of-00062.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eee7ff3c002f51bed65d055ff36773d095f5b5839fd52ff14ec0b39601270ef2
3
+ size 9016322568
model-00022-of-00062.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2782686f162dddec78025c43581c8434937bde367a3c5e2404b01a26db0669ad
3
+ size 9016322568
model-00023-of-00062.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b902cba6ecbd379a04cddca85ce8c9b0e741cc407605475d2d88e8aa3c215519
3
+ size 9016322568
model-00026-of-00062.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:51918b7cb3f84494eb7f043f4de0b9c9bb484ddbd840c81806f6f64169ff5e44
3
+ size 9016322568
model-00027-of-00062.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a28a8e6db0e1cba444f3cfe6a4d9a2d1e10fef25236112db9f9a565b1e106cb3
3
+ size 9016322568
model-00029-of-00062.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b74260530060782e05e3b88fab072f6562a23b109f84682a4b03fe063437b7ce
3
+ size 9016322568
model-00030-of-00062.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:348f18781a1882e5f50b48b45c90440c4e65936078c6da047ae8d10ecabe1daf
3
+ size 9016322568
model-00033-of-00062.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bf91e50082f1c4660f92733ceea14bf238a9f02a400e55ccf18d725075760f9d
3
+ size 9016322568
model-00038-of-00062.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a7f3e1be7aa0d99b0d6952cf3cf960fe6b7a65575df8fdee3f1dc098290238d
3
+ size 9016322568
model-00039-of-00062.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:029a762d851914537175ebe38deb6770ed45e637e7d05baaac7d5568ff8d8f5d
3
+ size 9016322568
model-00044-of-00062.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9d61765a0d25237e5a66201045c9877cc66e45d8afb590dd032a6f12c0565bcb
3
+ size 9016322568
model-00046-of-00062.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:86ea8bb8ccbfe8b02ebe5e8e306f4ea4c80ba276ca18c420b1bfe045728cd7dd
3
+ size 9016322568
model-00051-of-00062.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:df618eb8e650918520dcd8ec9e3e45b30f53fedb5919cc2f84f5227ac697c822
3
+ size 9016322568
model-00053-of-00062.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:630174280ce31575609f6237858a3edd6a8971d1fc9569d599863b42781a289e
3
+ size 9016322568
model-00054-of-00062.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:18ce9f6363dc61383ad19f51e7d2b413e8f7d0a2c5e550531f7438d7d205aca2
3
+ size 9016322568
model-00055-of-00062.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8b9ced474fce708a2d4e574b7ae53023b81c1b0b778a5b6fedb78c576f159b69
3
+ size 9016322568
model-00057-of-00062.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d3fc1ef7b5a394ccfff0990ceb8065ee875f5b06b663822fb12a90d673675ed3
3
+ size 9016322568
model-00059-of-00062.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cbb36f9dd1794364136bab09410191f40affcf2372b9311737670d48ad76dc4e
3
+ size 9016322568
model-00061-of-00062.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0d2e360f067d3239e88561f3b07d829e4472c046c23afbd33b92378523d6737e
3
+ size 9016322568
modeling_deepseek.py ADDED
@@ -0,0 +1,1808 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 DeepSeek-AI and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch DeepSeek model."""
21
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import numpy as np
26
+ import torch
27
+ import torch.distributed as dist
28
+ import torch.nn.functional as F
29
+ import torch.utils.checkpoint
30
+ from torch import nn
31
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
32
+ from transformers.activations import ACT2FN
33
+ from transformers.cache_utils import Cache, DynamicCache
34
+ from transformers.modeling_attn_mask_utils import \
35
+ _prepare_4d_causal_attention_mask
36
+ from transformers.modeling_outputs import (BaseModelOutputWithPast,
37
+ CausalLMOutputWithPast,
38
+ SequenceClassifierOutputWithPast)
39
+ from transformers.modeling_utils import PreTrainedModel
40
+ from transformers.pytorch_utils import (ALL_LAYERNORM_LAYERS,
41
+ is_torch_greater_or_equal_than_1_13)
42
+ from transformers.utils import (add_start_docstrings,
43
+ add_start_docstrings_to_model_forward,
44
+ is_flash_attn_2_available,
45
+ is_flash_attn_greater_or_equal_2_10, logging,
46
+ replace_return_docstrings)
47
+ from transformers.utils.import_utils import is_torch_fx_available
48
+
49
+ from .configuration_deepseek import DeepseekV3Config
50
+
51
+ if is_flash_attn_2_available():
52
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
53
+ from flash_attn.bert_padding import pad_input # noqa
54
+ from flash_attn.bert_padding import index_first_axis, unpad_input
55
+
56
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
57
+ # It means that the function will not be traced through and simply appear as a node in the graph.
58
+ if is_torch_fx_available():
59
+ if not is_torch_greater_or_equal_than_1_13:
60
+ import torch.fx
61
+
62
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(
63
+ _prepare_4d_causal_attention_mask)
64
+
65
+ logger = logging.get_logger(__name__)
66
+
67
+ _CONFIG_FOR_DOC = "DeepseekV3Config"
68
+
69
+
70
+ def _get_unpad_data(attention_mask):
71
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
72
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
73
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
74
+ cu_seqlens = F.pad(
75
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
76
+ return (
77
+ indices,
78
+ cu_seqlens,
79
+ max_seqlen_in_batch,
80
+ )
81
+
82
+
83
+ # code modified from transformers 4.48.3 to amend breaks in newer transformers versions
84
+ def get_usable_length(past_key_value,
85
+ new_seq_length: int,
86
+ layer_idx: Optional[int] = 0) -> int:
87
+ max_length = past_key_value.get_max_cache_shape()
88
+ previous_seq_length = past_key_value.get_seq_length(layer_idx)
89
+ if max_length is not None and max_length > 0 and previous_seq_length + new_seq_length > max_length:
90
+ return max_length - new_seq_length
91
+ return previous_seq_length
92
+
93
+
94
+ class DeepseekV3RMSNorm(nn.Module):
95
+
96
+ def __init__(self, hidden_size, eps=1e-6):
97
+ """
98
+ DeepseekV3RMSNorm is equivalent to T5LayerNorm
99
+ """
100
+ super().__init__()
101
+ self.weight = nn.Parameter(torch.ones(hidden_size))
102
+ self.variance_epsilon = eps
103
+
104
+ def forward(self, hidden_states):
105
+ input_dtype = hidden_states.dtype
106
+ hidden_states = hidden_states.to(torch.float32)
107
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
108
+ hidden_states = hidden_states * torch.rsqrt(variance +
109
+ self.variance_epsilon)
110
+ return self.weight * hidden_states.to(input_dtype)
111
+
112
+
113
+ ALL_LAYERNORM_LAYERS.append(DeepseekV3RMSNorm)
114
+
115
+
116
+ class DeepseekV3RotaryEmbedding(nn.Module):
117
+
118
+ def __init__(self,
119
+ dim,
120
+ max_position_embeddings=2048,
121
+ base=10000,
122
+ device=None):
123
+ super().__init__()
124
+
125
+ self.dim = dim
126
+ self.max_position_embeddings = max_position_embeddings
127
+ self.base = base
128
+ inv_freq = 1.0 / (self.base**(
129
+ torch.arange(0, self.dim, 2).float().to(device) / self.dim))
130
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
131
+
132
+ # Build here to make `torch.jit.trace` work.
133
+ self._set_cos_sin_cache(
134
+ seq_len=max_position_embeddings,
135
+ device=self.inv_freq.device,
136
+ dtype=torch.get_default_dtype(),
137
+ )
138
+ self.max_seq_len_cached = None
139
+
140
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
141
+ self.max_seq_len_cached = seq_len
142
+ t = torch.arange(self.max_seq_len_cached,
143
+ device=device,
144
+ dtype=self.inv_freq.dtype)
145
+
146
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
147
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
148
+ emb = torch.cat((freqs, freqs), dim=-1)
149
+ self.register_buffer("cos_cached",
150
+ emb.cos().to(dtype),
151
+ persistent=False)
152
+ self.register_buffer("sin_cached",
153
+ emb.sin().to(dtype),
154
+ persistent=False)
155
+
156
+ def forward(self, x, seq_len=None):
157
+ # x: [bs, num_attention_heads, seq_len, head_size]
158
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
159
+ self._set_cos_sin_cache(seq_len=seq_len,
160
+ device=x.device,
161
+ dtype=x.dtype)
162
+
163
+ return (
164
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
165
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
166
+ )
167
+
168
+
169
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->DeepseekV3
170
+ class DeepseekV3LinearScalingRotaryEmbedding(DeepseekV3RotaryEmbedding):
171
+ """DeepseekV3RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
172
+
173
+ def __init__(
174
+ self,
175
+ dim,
176
+ max_position_embeddings=2048,
177
+ base=10000,
178
+ device=None,
179
+ scaling_factor=1.0,
180
+ ):
181
+ self.scaling_factor = scaling_factor
182
+ super().__init__(dim, max_position_embeddings, base, device)
183
+
184
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
185
+ self.max_seq_len_cached = seq_len
186
+ t = torch.arange(self.max_seq_len_cached,
187
+ device=device,
188
+ dtype=self.inv_freq.dtype)
189
+ t = t / self.scaling_factor
190
+
191
+ freqs = torch.outer(t, self.inv_freq)
192
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
193
+ emb = torch.cat((freqs, freqs), dim=-1)
194
+ self.register_buffer("cos_cached",
195
+ emb.cos().to(dtype),
196
+ persistent=False)
197
+ self.register_buffer("sin_cached",
198
+ emb.sin().to(dtype),
199
+ persistent=False)
200
+
201
+
202
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->DeepseekV3
203
+ class DeepseekV3DynamicNTKScalingRotaryEmbedding(DeepseekV3RotaryEmbedding):
204
+ """DeepseekV3RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
205
+
206
+ def __init__(
207
+ self,
208
+ dim,
209
+ max_position_embeddings=2048,
210
+ base=10000,
211
+ device=None,
212
+ scaling_factor=1.0,
213
+ ):
214
+ self.scaling_factor = scaling_factor
215
+ super().__init__(dim, max_position_embeddings, base, device)
216
+
217
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
218
+ self.max_seq_len_cached = seq_len
219
+
220
+ if seq_len > self.max_position_embeddings:
221
+ base = self.base * ((self.scaling_factor * seq_len /
222
+ self.max_position_embeddings) -
223
+ (self.scaling_factor - 1))**(self.dim /
224
+ (self.dim - 2))
225
+ inv_freq = 1.0 / (base**(
226
+ torch.arange(0, self.dim, 2).float().to(device) / self.dim))
227
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
228
+
229
+ t = torch.arange(self.max_seq_len_cached,
230
+ device=device,
231
+ dtype=self.inv_freq.dtype)
232
+
233
+ freqs = torch.outer(t, self.inv_freq)
234
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
235
+ emb = torch.cat((freqs, freqs), dim=-1)
236
+ self.register_buffer("cos_cached",
237
+ emb.cos().to(dtype),
238
+ persistent=False)
239
+ self.register_buffer("sin_cached",
240
+ emb.sin().to(dtype),
241
+ persistent=False)
242
+
243
+
244
+ # Inverse dim formula to find dim based on number of rotations
245
+ def yarn_find_correction_dim(num_rotations,
246
+ dim,
247
+ base=10000,
248
+ max_position_embeddings=2048):
249
+ return (dim * math.log(max_position_embeddings /
250
+ (num_rotations * 2 * math.pi))) / (2 *
251
+ math.log(base))
252
+
253
+
254
+ # Find dim range bounds based on rotations
255
+ def yarn_find_correction_range(low_rot,
256
+ high_rot,
257
+ dim,
258
+ base=10000,
259
+ max_position_embeddings=2048):
260
+ low = math.floor(
261
+ yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings))
262
+ high = math.ceil(
263
+ yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings))
264
+ return max(low, 0), min(high, dim - 1) # Clamp values just in case
265
+
266
+
267
+ def yarn_get_mscale(scale=1, mscale=1):
268
+ if scale <= 1:
269
+ return 1.0
270
+ return 0.1 * mscale * math.log(scale) + 1.0
271
+
272
+
273
+ def yarn_linear_ramp_mask(min, max, dim):
274
+ if min == max:
275
+ max += 0.001 # Prevent singularity
276
+
277
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
278
+ ramp_func = torch.clamp(linear_func, 0, 1)
279
+ return ramp_func
280
+
281
+
282
+ class DeepseekV3YarnRotaryEmbedding(DeepseekV3RotaryEmbedding):
283
+
284
+ def __init__(
285
+ self,
286
+ dim,
287
+ max_position_embeddings=2048,
288
+ base=10000,
289
+ device=None,
290
+ scaling_factor=1.0,
291
+ original_max_position_embeddings=4096,
292
+ beta_fast=32,
293
+ beta_slow=1,
294
+ mscale=1,
295
+ mscale_all_dim=0,
296
+ ):
297
+ self.scaling_factor = scaling_factor
298
+ self.original_max_position_embeddings = original_max_position_embeddings
299
+ self.beta_fast = beta_fast
300
+ self.beta_slow = beta_slow
301
+ self.mscale = mscale
302
+ self.mscale_all_dim = mscale_all_dim
303
+ super().__init__(dim, max_position_embeddings, base, device)
304
+
305
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
306
+ self.max_seq_len_cached = seq_len
307
+ dim = self.dim
308
+
309
+ freq_extra = 1.0 / (self.base**(
310
+ torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim))
311
+ freq_inter = 1.0 / (self.scaling_factor * self.base**(
312
+ torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim))
313
+
314
+ low, high = yarn_find_correction_range(
315
+ self.beta_fast,
316
+ self.beta_slow,
317
+ dim,
318
+ self.base,
319
+ self.original_max_position_embeddings,
320
+ )
321
+ inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
322
+ device=device, dtype=torch.float32)
323
+ inv_freq = freq_inter * (1 -
324
+ inv_freq_mask) + freq_extra * inv_freq_mask
325
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
326
+
327
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
328
+
329
+ freqs = torch.outer(t, inv_freq)
330
+
331
+ _mscale = float(
332
+ yarn_get_mscale(self.scaling_factor, self.mscale) /
333
+ yarn_get_mscale(self.scaling_factor, self.mscale_all_dim))
334
+
335
+ emb = torch.cat((freqs, freqs), dim=-1)
336
+ self.register_buffer("cos_cached", (emb.cos() * _mscale).to(dtype),
337
+ persistent=False)
338
+ self.register_buffer("sin_cached", (emb.sin() * _mscale).to(dtype),
339
+ persistent=False)
340
+
341
+
342
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
343
+ def rotate_half(x):
344
+ """Rotates half the hidden dims of the input."""
345
+ x1 = x[..., :x.shape[-1] // 2]
346
+ x2 = x[..., x.shape[-1] // 2:]
347
+ return torch.cat((-x2, x1), dim=-1)
348
+
349
+
350
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
351
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
352
+ """Applies Rotary Position Embedding to the query and key tensors.
353
+
354
+ Args:
355
+ q (`torch.Tensor`): The query tensor.
356
+ k (`torch.Tensor`): The key tensor.
357
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
358
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
359
+ position_ids (`torch.Tensor`):
360
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
361
+ used to pass offsetted position ids when working with a KV-cache.
362
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
363
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
364
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
365
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
366
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
367
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
368
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
369
+ Returns:
370
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
371
+ """
372
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
373
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
374
+
375
+ b, h, s, d = q.shape
376
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
377
+
378
+ b, h, s, d = k.shape
379
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
380
+
381
+ q_embed = (q * cos) + (rotate_half(q) * sin)
382
+ k_embed = (k * cos) + (rotate_half(k) * sin)
383
+ return q_embed, k_embed
384
+
385
+
386
+ class DeepseekV3MLP(nn.Module):
387
+
388
+ def __init__(self, config, hidden_size=None, intermediate_size=None):
389
+ super().__init__()
390
+ self.config = config
391
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
392
+ self.intermediate_size = (config.intermediate_size if intermediate_size
393
+ is None else intermediate_size)
394
+
395
+ self.gate_proj = nn.Linear(self.hidden_size,
396
+ self.intermediate_size,
397
+ bias=False)
398
+ self.up_proj = nn.Linear(self.hidden_size,
399
+ self.intermediate_size,
400
+ bias=False)
401
+ self.down_proj = nn.Linear(self.intermediate_size,
402
+ self.hidden_size,
403
+ bias=False)
404
+ self.act_fn = ACT2FN[config.hidden_act]
405
+
406
+ def forward(self, x):
407
+ down_proj = self.down_proj(
408
+ self.act_fn(self.gate_proj(x)) * self.up_proj(x))
409
+ return down_proj
410
+
411
+
412
+ class MoEGate(nn.Module):
413
+
414
+ def __init__(self, config):
415
+ super().__init__()
416
+ self.config = config
417
+ self.top_k = config.num_experts_per_tok
418
+ self.n_routed_experts = config.n_routed_experts
419
+ self.routed_scaling_factor = config.routed_scaling_factor
420
+ self.scoring_func = config.scoring_func
421
+ self.seq_aux = config.seq_aux
422
+ self.topk_method = config.topk_method
423
+ self.n_group = config.n_group
424
+ self.topk_group = config.topk_group
425
+
426
+ # topk selection algorithm
427
+ self.norm_topk_prob = config.norm_topk_prob
428
+ self.gating_dim = config.hidden_size
429
+ self.weight = nn.Parameter(
430
+ torch.empty((self.n_routed_experts, self.gating_dim)))
431
+ if self.topk_method == "noaux_tc":
432
+ self.e_score_correction_bias = nn.Parameter(
433
+ torch.empty((self.n_routed_experts)))
434
+ self.reset_parameters()
435
+
436
+ def reset_parameters(self) -> None:
437
+ import torch.nn.init as init
438
+
439
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
440
+
441
+ def forward(self, hidden_states):
442
+ bsz, seq_len, h = hidden_states.shape
443
+ ### compute gating score
444
+ hidden_states = hidden_states.view(-1, h)
445
+ logits = F.linear(hidden_states.type(torch.float32),
446
+ self.weight.type(torch.float32), None)
447
+ if self.scoring_func == "sigmoid":
448
+ scores = logits.sigmoid()
449
+ else:
450
+ raise NotImplementedError(
451
+ f"insupportable scoring function for MoE gating: {self.scoring_func}"
452
+ )
453
+
454
+ ### select top-k experts
455
+ if self.topk_method == "noaux_tc":
456
+ assert not self.training
457
+ scores_for_choice = scores.view(
458
+ bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)
459
+ group_scores = (scores_for_choice.view(
460
+ bsz * seq_len, self.n_group,
461
+ -1).topk(2, dim=-1)[0].sum(dim=-1)) # [n, n_group]
462
+ group_idx = torch.topk(group_scores,
463
+ k=self.topk_group,
464
+ dim=-1,
465
+ sorted=False)[1] # [n, top_k_group]
466
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
467
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
468
+ score_mask = (group_mask.unsqueeze(-1).expand(
469
+ bsz * seq_len, self.n_group,
470
+ self.n_routed_experts // self.n_group).reshape(
471
+ bsz * seq_len, -1)) # [n, e]
472
+ tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(),
473
+ 0.0) # [n, e]
474
+ _, topk_idx = torch.topk(tmp_scores,
475
+ k=self.top_k,
476
+ dim=-1,
477
+ sorted=False)
478
+ topk_weight = scores.gather(1, topk_idx)
479
+ else:
480
+ raise NotImplementedError(
481
+ f"insupportable TopK function for MoE gating: {self.topk_method}"
482
+ )
483
+
484
+ ### norm gate to sum 1
485
+ if self.top_k > 1 and self.norm_topk_prob:
486
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
487
+ topk_weight = topk_weight / denominator
488
+ topk_weight = topk_weight * self.routed_scaling_factor # must multiply the scaling factor
489
+
490
+ return topk_idx, topk_weight
491
+
492
+
493
+ class DeepseekV3MoE(nn.Module):
494
+ """
495
+ A mixed expert module containing shared experts.
496
+ """
497
+
498
+ def __init__(self, config):
499
+ super().__init__()
500
+ self.config = config
501
+ self.num_experts_per_tok = config.num_experts_per_tok
502
+
503
+ if hasattr(config, "ep_size") and config.ep_size > 1:
504
+ assert config.ep_size == dist.get_world_size()
505
+ self.ep_size = config.ep_size
506
+ self.experts_per_rank = config.n_routed_experts // config.ep_size
507
+ self.ep_rank = dist.get_rank()
508
+ self.experts = nn.ModuleList([
509
+ (DeepseekV3MLP(config,
510
+ intermediate_size=config.moe_intermediate_size)
511
+ if i >= self.ep_rank * self.experts_per_rank
512
+ and i < (self.ep_rank + 1) * self.experts_per_rank else None)
513
+ for i in range(config.n_routed_experts)
514
+ ])
515
+ else:
516
+ self.ep_size = 1
517
+ self.experts_per_rank = config.n_routed_experts
518
+ self.ep_rank = 0
519
+ self.experts = nn.ModuleList([
520
+ DeepseekV3MLP(config,
521
+ intermediate_size=config.moe_intermediate_size)
522
+ for i in range(config.n_routed_experts)
523
+ ])
524
+ self.gate = MoEGate(config)
525
+ if config.n_shared_experts is not None:
526
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
527
+ self.shared_experts = DeepseekV3MLP(
528
+ config=config, intermediate_size=intermediate_size)
529
+
530
+ def forward(self, hidden_states):
531
+ identity = hidden_states
532
+ orig_shape = hidden_states.shape
533
+ topk_idx, topk_weight = self.gate(hidden_states)
534
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
535
+ flat_topk_idx = topk_idx.view(-1)
536
+ if not self.training:
537
+ y = self.moe_infer(hidden_states, topk_idx,
538
+ topk_weight).view(*orig_shape)
539
+ if self.config.n_shared_experts is not None:
540
+ y = y + self.shared_experts(identity)
541
+ return y
542
+
543
+ @torch.no_grad()
544
+ def moe_infer(self, x, topk_ids, topk_weight):
545
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
546
+ cnts.scatter_(1, topk_ids, 1)
547
+ tokens_per_expert = cnts.sum(dim=0)
548
+ idxs = topk_ids.view(-1).argsort()
549
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
550
+ sorted_tokens_shape = sorted_tokens.shape
551
+ if self.ep_size > 1:
552
+ tokens_per_ep_rank = tokens_per_expert.view(self.ep_size,
553
+ -1).sum(dim=1)
554
+ tokens_per_expert_group = tokens_per_expert.new_empty(
555
+ tokens_per_expert.shape[0])
556
+ dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
557
+ output_splits = (tokens_per_expert_group.view(
558
+ self.ep_size, -1).sum(1).cpu().numpy().tolist())
559
+ gathered_tokens = sorted_tokens.new_empty(
560
+ tokens_per_expert_group.sum(dim=0).cpu().item(),
561
+ sorted_tokens.shape[1])
562
+ input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
563
+ dist.all_to_all(
564
+ list(gathered_tokens.split(output_splits)),
565
+ list(sorted_tokens.split(input_split_sizes)),
566
+ )
567
+ tokens_per_expert_post_gather = tokens_per_expert_group.view(
568
+ self.ep_size, self.experts_per_rank).sum(dim=0)
569
+ gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0], ),
570
+ dtype=np.int32)
571
+ s = 0
572
+ for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
573
+ gatherd_idxs[s:s + k] = i % self.experts_per_rank
574
+ s += k
575
+ gatherd_idxs = gatherd_idxs.argsort()
576
+ sorted_tokens = gathered_tokens[gatherd_idxs]
577
+ tokens_per_expert = tokens_per_expert_post_gather
578
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
579
+
580
+ outputs = []
581
+ start_idx = 0
582
+ for i, num_tokens in enumerate(tokens_per_expert):
583
+ end_idx = start_idx + num_tokens
584
+ if num_tokens == 0:
585
+ continue
586
+ expert = self.experts[i + self.ep_rank * self.experts_per_rank]
587
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
588
+ expert_out = expert(tokens_for_this_expert)
589
+ outputs.append(expert_out)
590
+ start_idx = end_idx
591
+
592
+ outs = torch.cat(outputs,
593
+ dim=0) if len(outputs) else sorted_tokens.new_empty(0)
594
+ if self.ep_size > 1:
595
+ new_x = torch.empty_like(outs)
596
+ new_x[gatherd_idxs] = outs
597
+ gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
598
+ dist.all_to_all(
599
+ list(gathered_tokens.split(input_split_sizes)),
600
+ list(new_x.split(output_splits)),
601
+ )
602
+ outs = gathered_tokens
603
+
604
+ new_x = torch.empty_like(outs)
605
+ new_x[idxs] = outs
606
+ final_out = (new_x.view(
607
+ *topk_ids.shape, -1).type(topk_weight.dtype).mul_(
608
+ topk_weight.unsqueeze(dim=-1)).sum(dim=1).type(new_x.dtype))
609
+ return final_out
610
+
611
+
612
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
613
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
614
+ """
615
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
616
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
617
+ """
618
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
619
+ if n_rep == 1:
620
+ return hidden_states
621
+ hidden_states = hidden_states[:, :,
622
+ None, :, :].expand(batch,
623
+ num_key_value_heads,
624
+ n_rep, slen, head_dim)
625
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen,
626
+ head_dim)
627
+
628
+
629
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->DeepseekV3
630
+ class DeepseekV3Attention(nn.Module):
631
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
632
+
633
+ def __init__(self,
634
+ config: DeepseekV3Config,
635
+ layer_idx: Optional[int] = None):
636
+ super().__init__()
637
+ self.config = config
638
+ self.layer_idx = layer_idx
639
+ if layer_idx is None:
640
+ logger.warning_once(
641
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
642
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
643
+ "when creating this class.")
644
+
645
+ self.attention_dropout = config.attention_dropout
646
+ self.hidden_size = config.hidden_size
647
+ self.num_heads = config.num_attention_heads
648
+
649
+ self.max_position_embeddings = config.max_position_embeddings
650
+ self.rope_theta = config.rope_theta
651
+ self.q_lora_rank = config.q_lora_rank
652
+ self.qk_rope_head_dim = config.qk_rope_head_dim
653
+ self.kv_lora_rank = config.kv_lora_rank
654
+ self.v_head_dim = config.v_head_dim
655
+ self.qk_nope_head_dim = config.qk_nope_head_dim
656
+ self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
657
+
658
+ self.is_causal = True
659
+
660
+ if self.q_lora_rank is None:
661
+ self.q_proj = nn.Linear(self.hidden_size,
662
+ self.num_heads * self.q_head_dim,
663
+ bias=False)
664
+ else:
665
+ self.q_a_proj = nn.Linear(self.hidden_size,
666
+ config.q_lora_rank,
667
+ bias=config.attention_bias)
668
+ self.q_a_layernorm = DeepseekV3RMSNorm(config.q_lora_rank)
669
+ self.q_b_proj = nn.Linear(config.q_lora_rank,
670
+ self.num_heads * self.q_head_dim,
671
+ bias=False)
672
+
673
+ self.kv_a_proj_with_mqa = nn.Linear(
674
+ self.hidden_size,
675
+ config.kv_lora_rank + config.qk_rope_head_dim,
676
+ bias=config.attention_bias,
677
+ )
678
+ self.kv_a_layernorm = DeepseekV3RMSNorm(config.kv_lora_rank)
679
+ self.kv_b_proj = nn.Linear(
680
+ config.kv_lora_rank,
681
+ self.num_heads *
682
+ (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
683
+ bias=False,
684
+ )
685
+
686
+ self.o_proj = nn.Linear(
687
+ self.num_heads * self.v_head_dim,
688
+ self.hidden_size,
689
+ bias=config.attention_bias,
690
+ )
691
+ self._init_rope()
692
+
693
+ self.softmax_scale = self.q_head_dim**(-0.5)
694
+ if self.config.rope_scaling is not None:
695
+ mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
696
+ scaling_factor = self.config.rope_scaling["factor"]
697
+ if mscale_all_dim:
698
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
699
+ self.softmax_scale = self.softmax_scale * mscale * mscale
700
+
701
+ def _init_rope(self):
702
+ if self.config.rope_scaling is None:
703
+ self.rotary_emb = DeepseekV3RotaryEmbedding(
704
+ self.qk_rope_head_dim,
705
+ max_position_embeddings=self.max_position_embeddings,
706
+ base=self.rope_theta,
707
+ )
708
+ else:
709
+ scaling_type = self.config.rope_scaling["type"]
710
+ scaling_factor = self.config.rope_scaling["factor"]
711
+ if scaling_type == "linear":
712
+ self.rotary_emb = DeepseekV3LinearScalingRotaryEmbedding(
713
+ self.qk_rope_head_dim,
714
+ max_position_embeddings=self.max_position_embeddings,
715
+ scaling_factor=scaling_factor,
716
+ base=self.rope_theta,
717
+ )
718
+ elif scaling_type == "dynamic":
719
+ self.rotary_emb = DeepseekV3DynamicNTKScalingRotaryEmbedding(
720
+ self.qk_rope_head_dim,
721
+ max_position_embeddings=self.max_position_embeddings,
722
+ scaling_factor=scaling_factor,
723
+ base=self.rope_theta,
724
+ )
725
+ elif scaling_type == "yarn":
726
+ kwargs = {
727
+ key: self.config.rope_scaling[key]
728
+ for key in [
729
+ "original_max_position_embeddings",
730
+ "beta_fast",
731
+ "beta_slow",
732
+ "mscale",
733
+ "mscale_all_dim",
734
+ ] if key in self.config.rope_scaling
735
+ }
736
+ self.rotary_emb = DeepseekV3YarnRotaryEmbedding(
737
+ self.qk_rope_head_dim,
738
+ max_position_embeddings=self.max_position_embeddings,
739
+ scaling_factor=scaling_factor,
740
+ base=self.rope_theta,
741
+ **kwargs,
742
+ )
743
+ else:
744
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
745
+
746
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
747
+ return (tensor.view(bsz, seq_len, self.num_heads,
748
+ self.v_head_dim).transpose(1, 2).contiguous())
749
+
750
+ def forward(
751
+ self,
752
+ hidden_states: torch.Tensor,
753
+ attention_mask: Optional[torch.Tensor] = None,
754
+ position_ids: Optional[torch.LongTensor] = None,
755
+ past_key_value: Optional[Cache] = None,
756
+ output_attentions: bool = False,
757
+ use_cache: bool = False,
758
+ **kwargs,
759
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor],
760
+ Optional[Tuple[torch.Tensor]]]:
761
+ if "padding_mask" in kwargs:
762
+ warnings.warn(
763
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
764
+ )
765
+ bsz, q_len, _ = hidden_states.size()
766
+
767
+ if self.q_lora_rank is None:
768
+ q = self.q_proj(hidden_states)
769
+ else:
770
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
771
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
772
+ q_nope, q_pe = torch.split(
773
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
774
+
775
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
776
+ compressed_kv, k_pe = torch.split(
777
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
778
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
779
+ kv = (self.kv_b_proj(self.kv_a_layernorm(compressed_kv)).view(
780
+ bsz, q_len, self.num_heads,
781
+ self.qk_nope_head_dim + self.v_head_dim).transpose(1, 2))
782
+
783
+ k_nope, value_states = torch.split(
784
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
785
+ kv_seq_len = value_states.shape[-2]
786
+ if past_key_value is not None:
787
+ if self.layer_idx is None:
788
+ raise ValueError(
789
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
790
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
791
+ "with a layer index.")
792
+ kv_seq_len += get_usable_length(past_key_value, kv_seq_len,
793
+ self.layer_idx)
794
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
795
+
796
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
797
+
798
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len,
799
+ self.q_head_dim)
800
+ query_states[:, :, :, :self.qk_nope_head_dim] = q_nope
801
+ query_states[:, :, :, self.qk_nope_head_dim:] = q_pe
802
+
803
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len,
804
+ self.q_head_dim)
805
+ key_states[:, :, :, :self.qk_nope_head_dim] = k_nope
806
+ key_states[:, :, :, self.qk_nope_head_dim:] = k_pe
807
+ if past_key_value is not None:
808
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
809
+ key_states, value_states = past_key_value.update(
810
+ key_states, value_states, self.layer_idx, cache_kwargs)
811
+
812
+ attn_weights = (
813
+ torch.matmul(query_states, key_states.transpose(2, 3)) *
814
+ self.softmax_scale)
815
+
816
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
817
+ raise ValueError(
818
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
819
+ f" {attn_weights.size()}")
820
+ assert attention_mask is not None
821
+ if attention_mask is not None:
822
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
823
+ raise ValueError(
824
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
825
+ )
826
+ attn_weights = attn_weights + attention_mask
827
+
828
+ # upcast attention to fp32
829
+ attn_weights = nn.functional.softmax(attn_weights,
830
+ dim=-1,
831
+ dtype=torch.float32).to(
832
+ query_states.dtype)
833
+ attn_weights = nn.functional.dropout(attn_weights,
834
+ p=self.attention_dropout,
835
+ training=self.training)
836
+ attn_output = torch.matmul(attn_weights, value_states)
837
+
838
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
839
+ raise ValueError(
840
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
841
+ f" {attn_output.size()}")
842
+
843
+ attn_output = attn_output.transpose(1, 2).contiguous()
844
+
845
+ attn_output = attn_output.reshape(bsz, q_len,
846
+ self.num_heads * self.v_head_dim)
847
+
848
+ attn_output = self.o_proj(attn_output)
849
+
850
+ if not output_attentions:
851
+ attn_weights = None
852
+
853
+ return attn_output, attn_weights, past_key_value
854
+
855
+
856
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->DeepseekV3
857
+ class DeepseekV3FlashAttention2(DeepseekV3Attention):
858
+ """
859
+ DeepseekV3 flash attention module. This module inherits from `DeepseekV3Attention` as the weights of the module stays
860
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
861
+ flash attention and deal with padding tokens in case the input contains any of them.
862
+ """
863
+
864
+ def __init__(self, *args, **kwargs):
865
+ super().__init__(*args, **kwargs)
866
+
867
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
868
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignment, 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.
869
+ # 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).
870
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10(
871
+ )
872
+
873
+ def forward(
874
+ self,
875
+ hidden_states: torch.Tensor,
876
+ attention_mask: Optional[torch.LongTensor] = None,
877
+ position_ids: Optional[torch.LongTensor] = None,
878
+ past_key_value: Optional[Cache] = None,
879
+ output_attentions: bool = False,
880
+ use_cache: bool = False,
881
+ **kwargs,
882
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor],
883
+ Optional[Tuple[torch.Tensor]]]:
884
+ # DeepseekV3FlashAttention2 attention does not support output_attentions
885
+ if "padding_mask" in kwargs:
886
+ warnings.warn(
887
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
888
+ )
889
+
890
+ # overwrite attention_mask with padding_mask
891
+ attention_mask = kwargs.pop("padding_mask")
892
+
893
+ output_attentions = False
894
+
895
+ bsz, q_len, _ = hidden_states.size()
896
+
897
+ if self.q_lora_rank is None:
898
+ q = self.q_proj(hidden_states)
899
+ else:
900
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
901
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
902
+ q_nope, q_pe = torch.split(
903
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
904
+
905
+ # Flash attention requires the input to have the shape
906
+ # batch_size x seq_length x head_dim x hidden_dim
907
+ # therefore we just need to keep the original shape
908
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
909
+ compressed_kv, k_pe = torch.split(
910
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
911
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
912
+ kv = (self.kv_b_proj(self.kv_a_layernorm(compressed_kv)).view(
913
+ bsz, q_len, self.num_heads,
914
+ self.qk_nope_head_dim + self.v_head_dim).transpose(1, 2))
915
+
916
+ k_nope, value_states = torch.split(
917
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
918
+ kv_seq_len = value_states.shape[-2]
919
+
920
+ kv_seq_len = value_states.shape[-2]
921
+ if past_key_value is not None:
922
+ kv_seq_len += get_usable_length(past_key_value, kv_seq_len,
923
+ self.layer_idx)
924
+
925
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
926
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
927
+
928
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len,
929
+ self.q_head_dim)
930
+ query_states[:, :, :, :self.qk_nope_head_dim] = q_nope
931
+ query_states[:, :, :, self.qk_nope_head_dim:] = q_pe
932
+
933
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len,
934
+ self.q_head_dim)
935
+ key_states[:, :, :, :self.qk_nope_head_dim] = k_nope
936
+ key_states[:, :, :, self.qk_nope_head_dim:] = k_pe
937
+
938
+ if self.q_head_dim != self.v_head_dim:
939
+ value_states = F.pad(value_states,
940
+ [0, self.q_head_dim - self.v_head_dim])
941
+
942
+ if past_key_value is not None:
943
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
944
+ key_states, value_states = past_key_value.update(
945
+ key_states, value_states, self.layer_idx, cache_kwargs)
946
+
947
+ # 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
948
+ # to be able to avoid many of these transpose/reshape/view.
949
+ query_states = query_states.transpose(1, 2)
950
+ key_states = key_states.transpose(1, 2)
951
+ value_states = value_states.transpose(1, 2)
952
+
953
+ dropout_rate = self.attention_dropout if self.training else 0.0
954
+
955
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
956
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
957
+ # cast them back in the correct dtype just to be sure everything works as expected.
958
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
959
+ # in fp32. (DeepseekV3RMSNorm handles it correctly)
960
+
961
+ input_dtype = query_states.dtype
962
+ if input_dtype == torch.float32:
963
+ # Handle the case where the model is quantized
964
+ if hasattr(self.config, "_pre_quantization_dtype"):
965
+ target_dtype = self.config._pre_quantization_dtype
966
+ elif torch.is_autocast_enabled():
967
+ target_dtype = torch.get_autocast_gpu_dtype()
968
+ else:
969
+ target_dtype = (self.q_proj.weight.dtype if self.q_lora_rank
970
+ is None else self.q_a_proj.weight.dtype)
971
+
972
+ logger.warning_once(
973
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
974
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
975
+ f" {target_dtype}.")
976
+
977
+ query_states = query_states.to(target_dtype)
978
+ key_states = key_states.to(target_dtype)
979
+ value_states = value_states.to(target_dtype)
980
+
981
+ attn_output = self._flash_attention_forward(
982
+ query_states,
983
+ key_states,
984
+ value_states,
985
+ attention_mask,
986
+ q_len,
987
+ dropout=dropout_rate,
988
+ softmax_scale=self.softmax_scale,
989
+ )
990
+ if self.q_head_dim != self.v_head_dim:
991
+ attn_output = attn_output[:, :, :, :self.v_head_dim]
992
+
993
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads *
994
+ self.v_head_dim).contiguous()
995
+ attn_output = self.o_proj(attn_output)
996
+
997
+ if not output_attentions:
998
+ attn_weights = None
999
+
1000
+ return attn_output, attn_weights, past_key_value
1001
+
1002
+ def _flash_attention_forward(
1003
+ self,
1004
+ query_states,
1005
+ key_states,
1006
+ value_states,
1007
+ attention_mask,
1008
+ query_length,
1009
+ dropout=0.0,
1010
+ softmax_scale=None,
1011
+ ):
1012
+ """
1013
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1014
+ first unpad the input, then computes the attention scores and pad the final attention scores.
1015
+
1016
+ Args:
1017
+ query_states (`torch.Tensor`):
1018
+ Input query states to be passed to Flash Attention API
1019
+ key_states (`torch.Tensor`):
1020
+ Input key states to be passed to Flash Attention API
1021
+ value_states (`torch.Tensor`):
1022
+ Input value states to be passed to Flash Attention API
1023
+ attention_mask (`torch.Tensor`):
1024
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1025
+ position of padding tokens and 1 for the position of non-padding tokens.
1026
+ dropout (`int`, *optional*):
1027
+ Attention dropout
1028
+ softmax_scale (`float`, *optional*):
1029
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1030
+ """
1031
+ if not self._flash_attn_uses_top_left_mask:
1032
+ causal = self.is_causal
1033
+ else:
1034
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in DeepseekV3FlashAttention2 __init__.
1035
+ causal = self.is_causal and query_length != 1
1036
+
1037
+ # Contains at least one padding token in the sequence
1038
+ if attention_mask is not None:
1039
+ batch_size = query_states.shape[0]
1040
+ (
1041
+ query_states,
1042
+ key_states,
1043
+ value_states,
1044
+ indices_q,
1045
+ cu_seq_lens,
1046
+ max_seq_lens,
1047
+ ) = self._upad_input(query_states, key_states, value_states,
1048
+ attention_mask, query_length)
1049
+
1050
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1051
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1052
+
1053
+ attn_output_unpad = flash_attn_varlen_func(
1054
+ query_states,
1055
+ key_states,
1056
+ value_states,
1057
+ cu_seqlens_q=cu_seqlens_q,
1058
+ cu_seqlens_k=cu_seqlens_k,
1059
+ max_seqlen_q=max_seqlen_in_batch_q,
1060
+ max_seqlen_k=max_seqlen_in_batch_k,
1061
+ dropout_p=dropout,
1062
+ softmax_scale=softmax_scale,
1063
+ causal=causal,
1064
+ )
1065
+
1066
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size,
1067
+ query_length)
1068
+ else:
1069
+ attn_output = flash_attn_func(
1070
+ query_states,
1071
+ key_states,
1072
+ value_states,
1073
+ dropout,
1074
+ softmax_scale=softmax_scale,
1075
+ causal=causal,
1076
+ )
1077
+
1078
+ return attn_output
1079
+
1080
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask,
1081
+ query_length):
1082
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(
1083
+ attention_mask)
1084
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
1085
+
1086
+ key_layer = index_first_axis(
1087
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads,
1088
+ head_dim),
1089
+ indices_k,
1090
+ )
1091
+ value_layer = index_first_axis(
1092
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads,
1093
+ head_dim),
1094
+ indices_k,
1095
+ )
1096
+ if query_length == kv_seq_len:
1097
+ query_layer = index_first_axis(
1098
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads,
1099
+ head_dim),
1100
+ indices_k,
1101
+ )
1102
+ cu_seqlens_q = cu_seqlens_k
1103
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1104
+ indices_q = indices_k
1105
+ elif query_length == 1:
1106
+ max_seqlen_in_batch_q = 1
1107
+ cu_seqlens_q = torch.arange(
1108
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1109
+ ) # There is a memcpy here, that is very bad.
1110
+ indices_q = cu_seqlens_q[:-1]
1111
+ query_layer = query_layer.squeeze(1)
1112
+ else:
1113
+ # The -q_len: slice assumes left padding.
1114
+ attention_mask = attention_mask[:, -query_length:]
1115
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
1116
+ query_layer, attention_mask)
1117
+
1118
+ return (
1119
+ query_layer,
1120
+ key_layer,
1121
+ value_layer,
1122
+ indices_q,
1123
+ (cu_seqlens_q, cu_seqlens_k),
1124
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1125
+ )
1126
+
1127
+
1128
+ ATTENTION_CLASSES = {
1129
+ "eager": DeepseekV3Attention,
1130
+ "flash_attention_2": DeepseekV3FlashAttention2,
1131
+ }
1132
+
1133
+
1134
+ class DeepseekV3DecoderLayer(nn.Module):
1135
+
1136
+ def __init__(self, config: DeepseekV3Config, layer_idx: int):
1137
+ super().__init__()
1138
+ self.hidden_size = config.hidden_size
1139
+
1140
+ self.self_attn = ATTENTION_CLASSES[config._attn_implementation](
1141
+ config=config, layer_idx=layer_idx)
1142
+
1143
+ self.mlp = (DeepseekV3MoE(config) if
1144
+ (config.n_routed_experts is not None
1145
+ and layer_idx >= config.first_k_dense_replace
1146
+ and layer_idx % config.moe_layer_freq == 0) else
1147
+ DeepseekV3MLP(config))
1148
+ self.input_layernorm = DeepseekV3RMSNorm(config.hidden_size,
1149
+ eps=config.rms_norm_eps)
1150
+ self.post_attention_layernorm = DeepseekV3RMSNorm(
1151
+ config.hidden_size, eps=config.rms_norm_eps)
1152
+
1153
+ def forward(
1154
+ self,
1155
+ hidden_states: torch.Tensor,
1156
+ attention_mask: Optional[torch.Tensor] = None,
1157
+ position_ids: Optional[torch.LongTensor] = None,
1158
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1159
+ output_attentions: Optional[bool] = False,
1160
+ use_cache: Optional[bool] = False,
1161
+ **kwargs,
1162
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor,
1163
+ torch.FloatTensor]]]:
1164
+ """
1165
+ Args:
1166
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1167
+ attention_mask (`torch.FloatTensor`, *optional*):
1168
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1169
+ query_sequence_length, key_sequence_length)` if default attention is used.
1170
+ output_attentions (`bool`, *optional*):
1171
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1172
+ returned tensors for more detail.
1173
+ use_cache (`bool`, *optional*):
1174
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1175
+ (see `past_key_values`).
1176
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1177
+ """
1178
+ if "padding_mask" in kwargs:
1179
+ warnings.warn(
1180
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1181
+ )
1182
+ residual = hidden_states
1183
+
1184
+ hidden_states = self.input_layernorm(hidden_states)
1185
+
1186
+ # Self Attention
1187
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1188
+ hidden_states=hidden_states,
1189
+ attention_mask=attention_mask,
1190
+ position_ids=position_ids,
1191
+ past_key_value=past_key_value,
1192
+ output_attentions=output_attentions,
1193
+ use_cache=use_cache,
1194
+ **kwargs,
1195
+ )
1196
+ hidden_states = residual + hidden_states
1197
+
1198
+ # Fully Connected
1199
+ residual = hidden_states
1200
+ hidden_states = self.post_attention_layernorm(hidden_states)
1201
+ hidden_states = self.mlp(hidden_states)
1202
+ hidden_states = residual + hidden_states
1203
+
1204
+ outputs = (hidden_states, )
1205
+
1206
+ if output_attentions:
1207
+ outputs += (self_attn_weights, )
1208
+
1209
+ if use_cache:
1210
+ outputs += (present_key_value, )
1211
+
1212
+ return outputs
1213
+
1214
+
1215
+ DeepseekV3_START_DOCSTRING = r"""
1216
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1217
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1218
+ etc.)
1219
+
1220
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1221
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1222
+ and behavior.
1223
+
1224
+ Parameters:
1225
+ config ([`DeepseekV3Config`]):
1226
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1227
+ load the weights associated with the model, only the configuration. Check out the
1228
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1229
+ """
1230
+
1231
+
1232
+ @add_start_docstrings(
1233
+ "The bare DeepseekV3 Model outputting raw hidden-states without any specific head on top.",
1234
+ DeepseekV3_START_DOCSTRING,
1235
+ )
1236
+ class DeepseekV3PreTrainedModel(PreTrainedModel):
1237
+ config_class = DeepseekV3Config
1238
+ base_model_prefix = "model"
1239
+ supports_gradient_checkpointing = True
1240
+ _no_split_modules = ["DeepseekV3DecoderLayer"]
1241
+ _skip_keys_device_placement = "past_key_values"
1242
+ _supports_flash_attn_2 = True
1243
+ _supports_cache_class = True
1244
+
1245
+ def _init_weights(self, module):
1246
+ std = self.config.initializer_range
1247
+ if isinstance(module, nn.Linear):
1248
+ module.weight.data.normal_(mean=0.0, std=std)
1249
+ if module.bias is not None:
1250
+ module.bias.data.zero_()
1251
+ elif isinstance(module, nn.Embedding):
1252
+ module.weight.data.normal_(mean=0.0, std=std)
1253
+ if module.padding_idx is not None:
1254
+ module.weight.data[module.padding_idx].zero_()
1255
+
1256
+
1257
+ DeepseekV3_INPUTS_DOCSTRING = r"""
1258
+ Args:
1259
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1260
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1261
+ it.
1262
+
1263
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1264
+ [`PreTrainedTokenizer.__call__`] for details.
1265
+
1266
+ [What are input IDs?](../glossary#input-ids)
1267
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1268
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1269
+
1270
+ - 1 for tokens that are **not masked**,
1271
+ - 0 for tokens that are **masked**.
1272
+
1273
+ [What are attention masks?](../glossary#attention-mask)
1274
+
1275
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1276
+ [`PreTrainedTokenizer.__call__`] for details.
1277
+
1278
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1279
+ `past_key_values`).
1280
+
1281
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1282
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1283
+ information on the default strategy.
1284
+
1285
+ - 1 indicates the head is **not masked**,
1286
+ - 0 indicates the head is **masked**.
1287
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1288
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1289
+ config.n_positions - 1]`.
1290
+
1291
+ [What are position IDs?](../glossary#position-ids)
1292
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1293
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1294
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1295
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1296
+
1297
+ Two formats are allowed:
1298
+ - a [`~cache_utils.Cache`] instance;
1299
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1300
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1301
+ cache format.
1302
+
1303
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1304
+ legacy cache format will be returned.
1305
+
1306
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1307
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1308
+ of shape `(batch_size, sequence_length)`.
1309
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1310
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1311
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1312
+ model's internal embedding lookup matrix.
1313
+ use_cache (`bool`, *optional*):
1314
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1315
+ `past_key_values`).
1316
+ output_attentions (`bool`, *optional*):
1317
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1318
+ tensors for more detail.
1319
+ output_hidden_states (`bool`, *optional*):
1320
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1321
+ more detail.
1322
+ return_dict (`bool`, *optional*):
1323
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1324
+ """
1325
+
1326
+
1327
+ @add_start_docstrings(
1328
+ "The bare DeepseekV3 Model outputting raw hidden-states without any specific head on top.",
1329
+ DeepseekV3_START_DOCSTRING,
1330
+ )
1331
+ class DeepseekV3Model(DeepseekV3PreTrainedModel):
1332
+ """
1333
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekV3DecoderLayer`]
1334
+
1335
+ Args:
1336
+ config: DeepseekV3Config
1337
+ """
1338
+
1339
+ def __init__(self, config: DeepseekV3Config):
1340
+ super().__init__(config)
1341
+ self.padding_idx = config.pad_token_id
1342
+ self.vocab_size = config.vocab_size
1343
+
1344
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size,
1345
+ self.padding_idx)
1346
+ self.layers = nn.ModuleList([
1347
+ DeepseekV3DecoderLayer(config, layer_idx)
1348
+ for layer_idx in range(config.num_hidden_layers)
1349
+ ])
1350
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1351
+ self.norm = DeepseekV3RMSNorm(config.hidden_size,
1352
+ eps=config.rms_norm_eps)
1353
+
1354
+ self.gradient_checkpointing = False
1355
+ # Initialize weights and apply final processing
1356
+ self.post_init()
1357
+
1358
+ def get_input_embeddings(self):
1359
+ return self.embed_tokens
1360
+
1361
+ def set_input_embeddings(self, value):
1362
+ self.embed_tokens = value
1363
+
1364
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
1365
+ def forward(
1366
+ self,
1367
+ input_ids: torch.LongTensor = None,
1368
+ attention_mask: Optional[torch.Tensor] = None,
1369
+ position_ids: Optional[torch.LongTensor] = None,
1370
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1371
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1372
+ use_cache: Optional[bool] = None,
1373
+ output_attentions: Optional[bool] = None,
1374
+ output_hidden_states: Optional[bool] = None,
1375
+ return_dict: Optional[bool] = None,
1376
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1377
+ output_attentions = (output_attentions if output_attentions is not None
1378
+ else self.config.output_attentions)
1379
+ output_hidden_states = (output_hidden_states
1380
+ if output_hidden_states is not None else
1381
+ self.config.output_hidden_states)
1382
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1383
+
1384
+ return_dict = (return_dict if return_dict is not None else
1385
+ self.config.use_return_dict)
1386
+
1387
+ # retrieve input_ids and inputs_embeds
1388
+ if input_ids is not None and inputs_embeds is not None:
1389
+ raise ValueError(
1390
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1391
+ )
1392
+ elif input_ids is not None:
1393
+ batch_size, seq_length = input_ids.shape[:2]
1394
+ elif inputs_embeds is not None:
1395
+ batch_size, seq_length = inputs_embeds.shape[:2]
1396
+ else:
1397
+ raise ValueError(
1398
+ "You have to specify either input_ids or inputs_embeds")
1399
+
1400
+ past_key_values_length = 0
1401
+ if use_cache:
1402
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1403
+ if use_legacy_cache:
1404
+ past_key_values = DynamicCache.from_legacy_cache(
1405
+ past_key_values)
1406
+ past_key_values_length = get_usable_length(past_key_values,
1407
+ seq_length)
1408
+
1409
+ if position_ids is None:
1410
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1411
+ position_ids = torch.arange(
1412
+ past_key_values_length,
1413
+ seq_length + past_key_values_length,
1414
+ dtype=torch.long,
1415
+ device=device,
1416
+ )
1417
+ position_ids = position_ids.unsqueeze(0)
1418
+
1419
+ if inputs_embeds is None:
1420
+ inputs_embeds = self.embed_tokens(input_ids)
1421
+
1422
+ if self._use_flash_attention_2:
1423
+ # 2d mask is passed through the layers
1424
+ attention_mask = (attention_mask if
1425
+ (attention_mask is not None
1426
+ and 0 in attention_mask) else None)
1427
+ else:
1428
+ # 4d mask is passed through the layers
1429
+ attention_mask = _prepare_4d_causal_attention_mask(
1430
+ attention_mask,
1431
+ (batch_size, seq_length),
1432
+ inputs_embeds,
1433
+ past_key_values_length,
1434
+ )
1435
+
1436
+ # embed positions
1437
+ hidden_states = inputs_embeds
1438
+
1439
+ # decoder layers
1440
+ all_hidden_states = () if output_hidden_states else None
1441
+ all_self_attns = () if output_attentions else None
1442
+ next_decoder_cache = None
1443
+
1444
+ for decoder_layer in self.layers:
1445
+ if output_hidden_states:
1446
+ all_hidden_states += (hidden_states, )
1447
+
1448
+ layer_outputs = decoder_layer(
1449
+ hidden_states,
1450
+ attention_mask=attention_mask,
1451
+ position_ids=position_ids,
1452
+ past_key_value=past_key_values,
1453
+ output_attentions=output_attentions,
1454
+ use_cache=use_cache,
1455
+ )
1456
+
1457
+ hidden_states = layer_outputs[0]
1458
+
1459
+ if use_cache:
1460
+ next_decoder_cache = layer_outputs[
1461
+ 2 if output_attentions else 1]
1462
+
1463
+ if output_attentions:
1464
+ all_self_attns += (layer_outputs[1], )
1465
+
1466
+ hidden_states = self.norm(hidden_states)
1467
+
1468
+ # add hidden states from the last decoder layer
1469
+ if output_hidden_states:
1470
+ all_hidden_states += (hidden_states, )
1471
+
1472
+ next_cache = None
1473
+ if use_cache:
1474
+ next_cache = (next_decoder_cache.to_legacy_cache()
1475
+ if use_legacy_cache else next_decoder_cache)
1476
+ if not return_dict:
1477
+ return tuple(
1478
+ v for v in
1479
+ [hidden_states, next_cache, all_hidden_states, all_self_attns]
1480
+ if v is not None)
1481
+ return BaseModelOutputWithPast(
1482
+ last_hidden_state=hidden_states,
1483
+ past_key_values=next_cache,
1484
+ hidden_states=all_hidden_states,
1485
+ attentions=all_self_attns,
1486
+ )
1487
+
1488
+
1489
+ class DeepseekV3ForCausalLM(DeepseekV3PreTrainedModel):
1490
+ _tied_weights_keys = ["lm_head.weight"]
1491
+
1492
+ def __init__(self, config):
1493
+ super().__init__(config)
1494
+ self.model = DeepseekV3Model(config)
1495
+ self.vocab_size = config.vocab_size
1496
+ self.lm_head = nn.Linear(config.hidden_size,
1497
+ config.vocab_size,
1498
+ bias=False)
1499
+
1500
+ # Initialize weights and apply final processing
1501
+ self.post_init()
1502
+
1503
+ def get_input_embeddings(self):
1504
+ return self.model.embed_tokens
1505
+
1506
+ def set_input_embeddings(self, value):
1507
+ self.model.embed_tokens = value
1508
+
1509
+ def get_output_embeddings(self):
1510
+ return self.lm_head
1511
+
1512
+ def set_output_embeddings(self, new_embeddings):
1513
+ self.lm_head = new_embeddings
1514
+
1515
+ def set_decoder(self, decoder):
1516
+ self.model = decoder
1517
+
1518
+ def get_decoder(self):
1519
+ return self.model
1520
+
1521
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
1522
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast,
1523
+ config_class=_CONFIG_FOR_DOC)
1524
+ def forward(
1525
+ self,
1526
+ input_ids: torch.LongTensor = None,
1527
+ attention_mask: Optional[torch.Tensor] = None,
1528
+ position_ids: Optional[torch.LongTensor] = None,
1529
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1530
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1531
+ labels: Optional[torch.LongTensor] = None,
1532
+ use_cache: Optional[bool] = None,
1533
+ output_attentions: Optional[bool] = None,
1534
+ output_hidden_states: Optional[bool] = None,
1535
+ return_dict: Optional[bool] = None,
1536
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1537
+ r"""
1538
+ Args:
1539
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1540
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
1541
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1542
+ (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
1543
+
1544
+ Returns:
1545
+
1546
+ Example:
1547
+
1548
+ ```python
1549
+ >>> from transformers import AutoTokenizer, DeepseekV3ForCausalLM
1550
+
1551
+ >>> model = DeepseekV3ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1552
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1553
+
1554
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1555
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1556
+
1557
+ >>> # Generate
1558
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1559
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1560
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1561
+ ```"""
1562
+ output_attentions = (output_attentions if output_attentions is not None
1563
+ else self.config.output_attentions)
1564
+ output_hidden_states = (output_hidden_states
1565
+ if output_hidden_states is not None else
1566
+ self.config.output_hidden_states)
1567
+ return_dict = (return_dict if return_dict is not None else
1568
+ self.config.use_return_dict)
1569
+
1570
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1571
+ outputs = self.model(
1572
+ input_ids=input_ids,
1573
+ attention_mask=attention_mask,
1574
+ position_ids=position_ids,
1575
+ past_key_values=past_key_values,
1576
+ inputs_embeds=inputs_embeds,
1577
+ use_cache=use_cache,
1578
+ output_attentions=output_attentions,
1579
+ output_hidden_states=output_hidden_states,
1580
+ return_dict=return_dict,
1581
+ )
1582
+
1583
+ hidden_states = outputs[0]
1584
+ logits = self.lm_head(hidden_states)
1585
+ logits = logits.float()
1586
+
1587
+ loss = None
1588
+ if labels is not None:
1589
+ # Shift so that tokens < n predict n
1590
+ shift_logits = logits[..., :-1, :].contiguous()
1591
+ shift_labels = labels[..., 1:].contiguous()
1592
+ # Flatten the tokens
1593
+ loss_fct = CrossEntropyLoss()
1594
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1595
+ shift_labels = shift_labels.view(-1)
1596
+ # Enable model parallelism
1597
+ shift_labels = shift_labels.to(shift_logits.device)
1598
+ loss = loss_fct(shift_logits, shift_labels)
1599
+
1600
+ if not return_dict:
1601
+ output = (logits, ) + outputs[1:]
1602
+ return (loss, ) + output if loss is not None else output
1603
+
1604
+ return CausalLMOutputWithPast(
1605
+ loss=loss,
1606
+ logits=logits,
1607
+ past_key_values=outputs.past_key_values,
1608
+ hidden_states=outputs.hidden_states,
1609
+ attentions=outputs.attentions,
1610
+ )
1611
+
1612
+ def prepare_inputs_for_generation(
1613
+ self,
1614
+ input_ids,
1615
+ past_key_values=None,
1616
+ attention_mask=None,
1617
+ inputs_embeds=None,
1618
+ **kwargs,
1619
+ ):
1620
+ if past_key_values is not None:
1621
+ if isinstance(past_key_values, Cache):
1622
+ cache_length = past_key_values.get_seq_length()
1623
+ # seen_tokens 可能在某些 transformers 版本中不存在,使用 getattr 安全访问
1624
+ past_length = getattr(past_key_values, 'seen_tokens',
1625
+ cache_length)
1626
+ max_cache_length = past_key_values.get_max_length()
1627
+ else:
1628
+ cache_length = past_length = past_key_values[0][0].shape[2]
1629
+ max_cache_length = None
1630
+
1631
+ # Keep only the unprocessed tokens:
1632
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1633
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1634
+ # input)
1635
+ if (attention_mask is not None
1636
+ and attention_mask.shape[1] > input_ids.shape[1]):
1637
+ input_ids = input_ids[:, -(attention_mask.shape[1] -
1638
+ past_length):]
1639
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1640
+ # input_ids based on the past_length.
1641
+ elif past_length < input_ids.shape[1]:
1642
+ input_ids = input_ids[:, past_length:]
1643
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1644
+
1645
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1646
+ if (max_cache_length is not None and attention_mask is not None
1647
+ and cache_length + input_ids.shape[1] > max_cache_length):
1648
+ attention_mask = attention_mask[:, -max_cache_length:]
1649
+
1650
+ position_ids = kwargs.get("position_ids", None)
1651
+ if attention_mask is not None and position_ids is None:
1652
+ # create position_ids on the fly for batch generation
1653
+ position_ids = attention_mask.long().cumsum(-1) - 1
1654
+ position_ids.masked_fill_(attention_mask == 0, 1)
1655
+ if past_key_values:
1656
+ position_ids = position_ids[:, -input_ids.shape[1]:]
1657
+
1658
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1659
+ if inputs_embeds is not None and past_key_values is None:
1660
+ model_inputs = {"inputs_embeds": inputs_embeds}
1661
+ else:
1662
+ model_inputs = {"input_ids": input_ids}
1663
+
1664
+ model_inputs.update({
1665
+ "position_ids": position_ids,
1666
+ "past_key_values": past_key_values,
1667
+ "use_cache": kwargs.get("use_cache"),
1668
+ "attention_mask": attention_mask,
1669
+ })
1670
+ return model_inputs
1671
+
1672
+ @staticmethod
1673
+ def _reorder_cache(past_key_values, beam_idx):
1674
+ reordered_past = ()
1675
+ for layer_past in past_key_values:
1676
+ reordered_past += (tuple(
1677
+ past_state.index_select(0, beam_idx.to(past_state.device))
1678
+ for past_state in layer_past), )
1679
+ return reordered_past
1680
+
1681
+
1682
+ @add_start_docstrings(
1683
+ """
1684
+ The DeepseekV3 Model transformer with a sequence classification head on top (linear layer).
1685
+
1686
+ [`DeepseekV3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1687
+ (e.g. GPT-2) do.
1688
+
1689
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1690
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1691
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1692
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1693
+ each row of the batch).
1694
+ """,
1695
+ DeepseekV3_START_DOCSTRING,
1696
+ )
1697
+ class DeepseekV3ForSequenceClassification(DeepseekV3PreTrainedModel):
1698
+
1699
+ def __init__(self, config):
1700
+ super().__init__(config)
1701
+ self.num_labels = config.num_labels
1702
+ self.model = DeepseekV3Model(config)
1703
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1704
+
1705
+ # Initialize weights and apply final processing
1706
+ self.post_init()
1707
+
1708
+ def get_input_embeddings(self):
1709
+ return self.model.embed_tokens
1710
+
1711
+ def set_input_embeddings(self, value):
1712
+ self.model.embed_tokens = value
1713
+
1714
+ @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING)
1715
+ def forward(
1716
+ self,
1717
+ input_ids: torch.LongTensor = None,
1718
+ attention_mask: Optional[torch.Tensor] = None,
1719
+ position_ids: Optional[torch.LongTensor] = None,
1720
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1721
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1722
+ labels: Optional[torch.LongTensor] = None,
1723
+ use_cache: Optional[bool] = None,
1724
+ output_attentions: Optional[bool] = None,
1725
+ output_hidden_states: Optional[bool] = None,
1726
+ return_dict: Optional[bool] = None,
1727
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1728
+ r"""
1729
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1730
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
1731
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1732
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1733
+ """
1734
+ return_dict = (return_dict if return_dict is not None else
1735
+ self.config.use_return_dict)
1736
+
1737
+ transformer_outputs = self.model(
1738
+ input_ids,
1739
+ attention_mask=attention_mask,
1740
+ position_ids=position_ids,
1741
+ past_key_values=past_key_values,
1742
+ inputs_embeds=inputs_embeds,
1743
+ use_cache=use_cache,
1744
+ output_attentions=output_attentions,
1745
+ output_hidden_states=output_hidden_states,
1746
+ return_dict=return_dict,
1747
+ )
1748
+ hidden_states = transformer_outputs[0]
1749
+ logits = self.score(hidden_states)
1750
+
1751
+ if input_ids is not None:
1752
+ batch_size = input_ids.shape[0]
1753
+ else:
1754
+ batch_size = inputs_embeds.shape[0]
1755
+
1756
+ if self.config.pad_token_id is None and batch_size != 1:
1757
+ raise ValueError(
1758
+ "Cannot handle batch sizes > 1 if no padding token is defined."
1759
+ )
1760
+ if self.config.pad_token_id is None:
1761
+ sequence_lengths = -1
1762
+ else:
1763
+ if input_ids is not None:
1764
+ sequence_lengths = (torch.eq(
1765
+ input_ids, self.config.pad_token_id).int().argmax(-1) -
1766
+ 1).to(logits.device)
1767
+ else:
1768
+ sequence_lengths = -1
1769
+
1770
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device),
1771
+ sequence_lengths]
1772
+
1773
+ loss = None
1774
+ if labels is not None:
1775
+ labels = labels.to(logits.device)
1776
+ if self.config.problem_type is None:
1777
+ if self.num_labels == 1:
1778
+ self.config.problem_type = "regression"
1779
+ elif self.num_labels > 1 and (labels.dtype == torch.long
1780
+ or labels.dtype == torch.int):
1781
+ self.config.problem_type = "single_label_classification"
1782
+ else:
1783
+ self.config.problem_type = "multi_label_classification"
1784
+
1785
+ if self.config.problem_type == "regression":
1786
+ loss_fct = MSELoss()
1787
+ if self.num_labels == 1:
1788
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1789
+ else:
1790
+ loss = loss_fct(pooled_logits, labels)
1791
+ elif self.config.problem_type == "single_label_classification":
1792
+ loss_fct = CrossEntropyLoss()
1793
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels),
1794
+ labels.view(-1))
1795
+ elif self.config.problem_type == "multi_label_classification":
1796
+ loss_fct = BCEWithLogitsLoss()
1797
+ loss = loss_fct(pooled_logits, labels)
1798
+ if not return_dict:
1799
+ output = (pooled_logits, ) + transformer_outputs[1:]
1800
+ return ((loss, ) + output) if loss is not None else output
1801
+
1802
+ return SequenceClassifierOutputWithPast(
1803
+ loss=loss,
1804
+ logits=pooled_logits,
1805
+ past_key_values=transformer_outputs.past_key_values,
1806
+ hidden_states=transformer_outputs.hidden_states,
1807
+ attentions=transformer_outputs.attentions,
1808
+ )