intervitens commited on
Commit
5e14c8f
·
verified ·
1 Parent(s): 0202cb5

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. LICENSE +21 -0
  2. README.md +103 -0
  3. assets/search_tool_trajectory.html +0 -0
  4. config.json +59 -0
  5. configuration_deepseek.py +199 -0
  6. generation_config.json +9 -0
  7. inference/README.md +13 -0
  8. inference/config_671B_v3.1.json +23 -0
  9. inference/convert.py +96 -0
  10. inference/generate.py +186 -0
  11. inference/kernel.py +274 -0
  12. inference/model.py +822 -0
  13. inference/requirements.txt +4 -0
  14. model-00001-of-000163.safetensors +3 -0
  15. model-00002-of-000163.safetensors +3 -0
  16. model-00003-of-000163.safetensors +3 -0
  17. model-00004-of-000163.safetensors +3 -0
  18. model-00005-of-000163.safetensors +3 -0
  19. model-00006-of-000163.safetensors +3 -0
  20. model-00007-of-000163.safetensors +3 -0
  21. model-00008-of-000163.safetensors +3 -0
  22. model-00009-of-000163.safetensors +3 -0
  23. model-00010-of-000163.safetensors +3 -0
  24. model-00011-of-000163.safetensors +3 -0
  25. model-00012-of-000163.safetensors +3 -0
  26. model-00013-of-000163.safetensors +3 -0
  27. model-00014-of-000163.safetensors +3 -0
  28. model-00015-of-000163.safetensors +3 -0
  29. model-00016-of-000163.safetensors +3 -0
  30. model-00017-of-000163.safetensors +3 -0
  31. model-00018-of-000163.safetensors +3 -0
  32. model-00019-of-000163.safetensors +3 -0
  33. model-00020-of-000163.safetensors +3 -0
  34. model-00021-of-000163.safetensors +3 -0
  35. model-00022-of-000163.safetensors +3 -0
  36. model-00023-of-000163.safetensors +3 -0
  37. model-00024-of-000163.safetensors +3 -0
  38. model-00025-of-000163.safetensors +3 -0
  39. model-00026-of-000163.safetensors +3 -0
  40. model-00027-of-000163.safetensors +3 -0
  41. model-00028-of-000163.safetensors +3 -0
  42. model-00029-of-000163.safetensors +3 -0
  43. model-00030-of-000163.safetensors +3 -0
  44. model-00031-of-000163.safetensors +3 -0
  45. model-00032-of-000163.safetensors +3 -0
  46. model-00033-of-000163.safetensors +3 -0
  47. model-00034-of-000163.safetensors +3 -0
  48. model-00035-of-000163.safetensors +3 -0
  49. model-00036-of-000163.safetensors +3 -0
  50. model-00037-of-000163.safetensors +3 -0
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2023 DeepSeek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ library_name: transformers
4
+ base_model:
5
+ - deepseek-ai/DeepSeek-V3.1-Base
6
+ ---
7
+ # DeepSeek-V3.1-Terminus
8
+
9
+ <!-- markdownlint-disable first-line-h1 -->
10
+ <!-- markdownlint-disable html -->
11
+ <!-- markdownlint-disable no-duplicate-header -->
12
+
13
+ <div align="center">
14
+ <img src="https://github.com/deepseek-ai/DeepSeek-V2/blob/main/figures/logo.svg?raw=true" width="60%" alt="DeepSeek-V3" />
15
+ </div>
16
+ <hr>
17
+ <div align="center" style="line-height: 1;">
18
+ <a href="https://www.deepseek.com/" target="_blank" style="margin: 2px;">
19
+ <img alt="Homepage" src="https://github.com/deepseek-ai/DeepSeek-V2/blob/main/figures/badge.svg?raw=true" style="display: inline-block; vertical-align: middle;"/>
20
+ </a>
21
+ <a href="https://chat.deepseek.com/" target="_blank" style="margin: 2px;">
22
+ <img alt="Chat" src="https://img.shields.io/badge/🤖%20Chat-DeepSeek%20V3-536af5?color=536af5&logoColor=white" style="display: inline-block; vertical-align: middle;"/>
23
+ </a>
24
+ <a href="https://huggingface.co/deepseek-ai" target="_blank" style="margin: 2px;">
25
+ <img alt="Hugging Face" src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-DeepSeek%20AI-ffc107?color=ffc107&logoColor=white" style="display: inline-block; vertical-align: middle;"/>
26
+ </a>
27
+ </div>
28
+
29
+ <div align="center" style="line-height: 1;">
30
+ <a href="https://discord.gg/Tc7c45Zzu5" target="_blank" style="margin: 2px;">
31
+ <img alt="Discord" src="https://img.shields.io/badge/Discord-DeepSeek%20AI-7289da?logo=discord&logoColor=white&color=7289da" style="display: inline-block; vertical-align: middle;"/>
32
+ </a>
33
+ <a href="https://github.com/deepseek-ai/DeepSeek-V2/blob/main/figures/qr.jpeg?raw=true" target="_blank" style="margin: 2px;">
34
+ <img alt="Wechat" src="https://img.shields.io/badge/WeChat-DeepSeek%20AI-brightgreen?logo=wechat&logoColor=white" style="display: inline-block; vertical-align: middle;"/>
35
+ </a>
36
+ <a href="https://twitter.com/deepseek_ai" target="_blank" style="margin: 2px;">
37
+ <img alt="Twitter Follow" src="https://img.shields.io/badge/Twitter-deepseek_ai-white?logo=x&logoColor=white" style="display: inline-block; vertical-align: middle;"/>
38
+ </a>
39
+ </div>
40
+
41
+ <div align="center" style="line-height: 1;">
42
+ <a href="LICENSE" style="margin: 2px;">
43
+ <img alt="License" src="https://img.shields.io/badge/License-MIT-f5de53?&color=f5de53" style="display: inline-block; vertical-align: middle;"/>
44
+ </a>
45
+ </div>
46
+
47
+ ## Introduction
48
+
49
+ This update maintains the model's original capabilities while addressing issues reported by users, including:
50
+
51
+ - Language consistency: Reducing instances of mixed Chinese-English text and occasional abnormal characters;
52
+ - Agent capabilities: Further optimizing the performance of the Code Agent and Search Agent.
53
+
54
+ | Benchmark | DeepSeek-V3.1 | DeepSeek-V3.1-Terminus |
55
+ | :--- | :---: | :---: |
56
+ | **Reasoning Mode w/o Tool Use** | | |
57
+ | MMLU-Pro | 84.8 | 85.0 |
58
+ | GPQA-Diamond | 80.1 | 80.7 |
59
+ | Humanity's Last Exam | 15.9 | 21.7 |
60
+ | LiveCodeBench | 74.8 | 74.9 |
61
+ | Codeforces | 2091 | 2046 |
62
+ | Aider-Polyglot | 76.3 | 76.1 |
63
+ | **Agentic Tool Use** | | |
64
+ | BrowseComp | 30.0 | 38.5 |
65
+ | BrowseComp-zh | 49.2 | 45.0 |
66
+ | SimpleQA | 93.4 | 96.8 |
67
+ | SWE Verified | 66.0 | 68.4 |
68
+ | SWE-bench Multilingual | 54.5 | 57.8 |
69
+ | Terminal-bench | 31.3 | 36.7 |
70
+
71
+ **The template and tool-set of search agent have been updated, which is shown in `assets/search_tool_trajectory.html`.**
72
+
73
+ ## How to Run Locally
74
+
75
+ The model structure of DeepSeek-V3.1-Terminus is the same as DeepSeek-V3. Please visit [DeepSeek-V3](https://github.com/deepseek-ai/DeepSeek-V3) repo for more information about running this model locally.
76
+
77
+ For the model's chat template other than search agent, please refer to the [DeepSeek-V3.1](https://huggingface.co/deepseek-ai/DeepSeek-V3.1) repo.
78
+
79
+ **Here we also provide an updated inference demo code in the `inference` folder to help the community get started with running our model and understand the details of model architecture.**
80
+
81
+ **NOTE: In the current model checkpoint, the parameters of `self_attn.o_proj` do not conform to the UE8M0 FP8 scale data format. This is a known issue and will be corrected in future model releases.**
82
+
83
+ ## License
84
+
85
+ This repository and the model weights are licensed under the [MIT License](LICENSE).
86
+
87
+ ## Citation
88
+
89
+ ```
90
+ @misc{deepseekai2024deepseekv3technicalreport,
91
+ title={DeepSeek-V3 Technical Report},
92
+ author={DeepSeek-AI},
93
+ year={2024},
94
+ eprint={2412.19437},
95
+ archivePrefix={arXiv},
96
+ primaryClass={cs.CL},
97
+ url={https://arxiv.org/abs/2412.19437},
98
+ }
99
+ ```
100
+
101
+ ## Contact
102
+
103
+ If you have any questions, please raise an issue or contact us at [service@deepseek.com](service@deepseek.com).
assets/search_tool_trajectory.html ADDED
The diff for this file is too large to render. See raw diff
 
config.json ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "DeepseekV3ForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "attn_module_list_cfg": [],
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_deepseek.DeepseekV3Config",
10
+ "AutoModel": "modeling_deepseek.DeepseekV3Model",
11
+ "AutoModelForCausalLM": "modeling_deepseek.DeepseekV3ForCausalLM"
12
+ },
13
+ "bos_token_id": 0,
14
+ "eos_token_id": 1,
15
+ "ep_size": 1,
16
+ "first_k_dense_replace": 3,
17
+ "hidden_act": "silu",
18
+ "hidden_size": 7168,
19
+ "initializer_range": 0.02,
20
+ "intermediate_size": 18432,
21
+ "kv_lora_rank": 512,
22
+ "max_position_embeddings": 163840,
23
+ "model_type": "deepseek_v3",
24
+ "moe_intermediate_size": 2048,
25
+ "moe_layer_freq": 1,
26
+ "n_group": 8,
27
+ "n_routed_experts": 256,
28
+ "n_shared_experts": 1,
29
+ "norm_topk_prob": true,
30
+ "num_attention_heads": 128,
31
+ "num_experts_per_tok": 8,
32
+ "num_hidden_layers": 61,
33
+ "num_key_value_heads": 128,
34
+ "num_nextn_predict_layers": 1,
35
+ "q_lora_rank": 1536,
36
+ "qk_nope_head_dim": 128,
37
+ "qk_rope_head_dim": 64,
38
+ "rms_norm_eps": 1e-06,
39
+ "rope_scaling": {
40
+ "beta_fast": 32,
41
+ "beta_slow": 1,
42
+ "factor": 40,
43
+ "mscale": 1.0,
44
+ "mscale_all_dim": 1.0,
45
+ "original_max_position_embeddings": 4096,
46
+ "type": "yarn"
47
+ },
48
+ "rope_theta": 10000,
49
+ "routed_scaling_factor": 2.5,
50
+ "scoring_func": "sigmoid",
51
+ "tie_word_embeddings": false,
52
+ "topk_group": 4,
53
+ "topk_method": "noaux_tc",
54
+ "torch_dtype": "bfloat16",
55
+ "transformers_version": "4.44.2",
56
+ "use_cache": true,
57
+ "v_head_dim": 128,
58
+ "vocab_size": 129280
59
+ }
configuration_deepseek.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.configuration_utils import PretrainedConfig
2
+ from transformers.utils import logging
3
+
4
+ logger = logging.get_logger(__name__)
5
+
6
+ DEEPSEEK_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
7
+ class DeepseekV3Config(PretrainedConfig):
8
+ r"""
9
+ This is the configuration class to store the configuration of a [`DeepseekV3Model`]. It is used to instantiate an DeepSeek
10
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
11
+ defaults will yield a similar configuration to that of the DeepSeek-V3.
12
+
13
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
14
+ documentation from [`PretrainedConfig`] for more information.
15
+
16
+
17
+ Args:
18
+ vocab_size (`int`, *optional*, defaults to 129280):
19
+ Vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the
20
+ `inputs_ids` passed when calling [`DeepseekV3Model`]
21
+ hidden_size (`int`, *optional*, defaults to 4096):
22
+ Dimension of the hidden representations.
23
+ intermediate_size (`int`, *optional*, defaults to 11008):
24
+ Dimension of the MLP representations.
25
+ moe_intermediate_size (`int`, *optional*, defaults to 1407):
26
+ Dimension of the MoE representations.
27
+ num_hidden_layers (`int`, *optional*, defaults to 32):
28
+ Number of hidden layers in the Transformer decoder.
29
+ num_nextn_predict_layers (`int`, *optional*, defaults to 1):
30
+ Number of nextn predict layers in the DeepSeekV3 Model.
31
+ num_attention_heads (`int`, *optional*, defaults to 32):
32
+ Number of attention heads for each attention layer in the Transformer decoder.
33
+ n_shared_experts (`int`, *optional*, defaults to None):
34
+ Number of shared experts, None means dense model.
35
+ n_routed_experts (`int`, *optional*, defaults to None):
36
+ Number of routed experts, None means dense model.
37
+ routed_scaling_factor (`float`, *optional*, defaults to 1.0):
38
+ Scaling factor or routed experts.
39
+ topk_method (`str`, *optional*, defaults to `gready`):
40
+ Topk method used in routed gate.
41
+ n_group (`int`, *optional*, defaults to None):
42
+ Number of groups for routed experts.
43
+ topk_group (`int`, *optional*, defaults to None):
44
+ Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
45
+ num_experts_per_tok (`int`, *optional*, defaults to None):
46
+ Number of selected experts, None means dense model.
47
+ moe_layer_freq (`int`, *optional*, defaults to 1):
48
+ The frequency of the MoE layer: one expert layer for every `moe_layer_freq - 1` dense layers.
49
+ first_k_dense_replace (`int`, *optional*, defaults to 0):
50
+ Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head).
51
+ \--k dense layers--/
52
+ norm_topk_prob (`bool`, *optional*, defaults to False):
53
+ Whether to normalize the weights of the routed experts.
54
+ scoring_func (`str`, *optional*, defaults to 'softmax'):
55
+ Method of computing expert weights.
56
+ aux_loss_alpha (`float`, *optional*, defaults to 0.001):
57
+ Auxiliary loss weight coefficient.
58
+ seq_aux = (`bool`, *optional*, defaults to True):
59
+ Whether to compute the auxiliary loss for each individual sample.
60
+ num_key_value_heads (`int`, *optional*):
61
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
62
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
63
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
64
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
65
+ by meanpooling all the original heads within that group. For more details checkout [this
66
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
67
+ `num_attention_heads`.
68
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
69
+ The non-linear activation function (function or string) in the decoder.
70
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
71
+ The maximum sequence length that this model might ever be used with.
72
+ initializer_range (`float`, *optional*, defaults to 0.02):
73
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
74
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
75
+ The epsilon used by the rms normalization layers.
76
+ use_cache (`bool`, *optional*, defaults to `True`):
77
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
78
+ relevant if `config.is_decoder=True`.
79
+ pad_token_id (`int`, *optional*):
80
+ Padding token id.
81
+ bos_token_id (`int`, *optional*, defaults to 1):
82
+ Beginning of stream token id.
83
+ eos_token_id (`int`, *optional*, defaults to 2):
84
+ End of stream token id.
85
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
86
+ Whether to tie weight embeddings
87
+ rope_theta (`float`, *optional*, defaults to 10000.0):
88
+ The base period of the RoPE embeddings.
89
+ rope_scaling (`Dict`, *optional*):
90
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
91
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
92
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
93
+ `max_position_embeddings` to the expected new maximum.
94
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
95
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
96
+ attention_dropout (`float`, *optional*, defaults to 0.0):
97
+ The dropout ratio for the attention probabilities.
98
+
99
+ ```python
100
+ >>> from transformers import DeepseekV3Model, DeepseekV3Config
101
+
102
+ >>> # Initializing a Deepseek-V3 style configuration
103
+ >>> configuration = DeepseekV3Config()
104
+
105
+ >>> # Accessing the model configuration
106
+ >>> configuration = model.config
107
+ ```"""
108
+
109
+ model_type = "deepseek_v3"
110
+ keys_to_ignore_at_inference = ["past_key_values"]
111
+
112
+ def __init__(
113
+ self,
114
+ vocab_size=129280,
115
+ hidden_size=7168,
116
+ intermediate_size=18432,
117
+ moe_intermediate_size = 2048,
118
+ num_hidden_layers=61,
119
+ num_nextn_predict_layers=1,
120
+ num_attention_heads=128,
121
+ num_key_value_heads=128,
122
+ n_shared_experts = 1,
123
+ n_routed_experts = 256,
124
+ ep_size = 1,
125
+ routed_scaling_factor = 2.5,
126
+ kv_lora_rank = 512,
127
+ q_lora_rank = 1536,
128
+ qk_rope_head_dim = 64,
129
+ v_head_dim = 128,
130
+ qk_nope_head_dim = 128,
131
+ topk_method = 'noaux_tc',
132
+ n_group = 8,
133
+ topk_group = 4,
134
+ num_experts_per_tok = 8,
135
+ moe_layer_freq = 1,
136
+ first_k_dense_replace = 3,
137
+ norm_topk_prob = True,
138
+ scoring_func = 'sigmoid',
139
+ hidden_act="silu",
140
+ max_position_embeddings=4096,
141
+ initializer_range=0.02,
142
+ rms_norm_eps=1e-6,
143
+ use_cache=True,
144
+ pad_token_id=None,
145
+ bos_token_id=0,
146
+ eos_token_id=1,
147
+ tie_word_embeddings=False,
148
+ rope_theta=10000.0,
149
+ rope_scaling=None,
150
+ attention_bias=False,
151
+ attention_dropout=0.0,
152
+ **kwargs,
153
+ ):
154
+ self.vocab_size = vocab_size
155
+ self.max_position_embeddings = max_position_embeddings
156
+ self.hidden_size = hidden_size
157
+ self.intermediate_size = intermediate_size
158
+ self.moe_intermediate_size = moe_intermediate_size
159
+ self.num_hidden_layers = num_hidden_layers
160
+ self.num_nextn_predict_layers = num_nextn_predict_layers
161
+ self.num_attention_heads = num_attention_heads
162
+ self.n_shared_experts = n_shared_experts
163
+ self.n_routed_experts = n_routed_experts
164
+ self.ep_size = ep_size
165
+ self.routed_scaling_factor = routed_scaling_factor
166
+ self.kv_lora_rank = kv_lora_rank
167
+ self.q_lora_rank = q_lora_rank
168
+ self.qk_rope_head_dim = qk_rope_head_dim
169
+ self.v_head_dim = v_head_dim
170
+ self.qk_nope_head_dim = qk_nope_head_dim
171
+ self.topk_method = topk_method
172
+ self.n_group = n_group
173
+ self.topk_group = topk_group
174
+ self.num_experts_per_tok = num_experts_per_tok
175
+ self.moe_layer_freq = moe_layer_freq
176
+ self.first_k_dense_replace = first_k_dense_replace
177
+ self.norm_topk_prob = norm_topk_prob
178
+ self.scoring_func = scoring_func
179
+ # for backward compatibility
180
+ if num_key_value_heads is None:
181
+ num_key_value_heads = num_attention_heads
182
+
183
+ self.num_key_value_heads = num_key_value_heads
184
+ self.hidden_act = hidden_act
185
+ self.initializer_range = initializer_range
186
+ self.rms_norm_eps = rms_norm_eps
187
+ self.use_cache = use_cache
188
+ self.rope_theta = rope_theta
189
+ self.rope_scaling = rope_scaling
190
+ self.attention_bias = attention_bias
191
+ self.attention_dropout = attention_dropout
192
+
193
+ super().__init__(
194
+ pad_token_id=pad_token_id,
195
+ bos_token_id=bos_token_id,
196
+ eos_token_id=eos_token_id,
197
+ tie_word_embeddings=tie_word_embeddings,
198
+ **kwargs,
199
+ )
generation_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 1,
5
+ "do_sample": true,
6
+ "temperature": 0.6,
7
+ "top_p": 0.95,
8
+ "transformers_version": "4.46.3"
9
+ }
inference/README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DeepSeek V3.1
2
+
3
+ First convert huggingface model weight files to the format of this project.
4
+ ```bash
5
+ export EXPERTS=256
6
+ python convert.py --hf-ckpt-path ${HF_CKPT_PATH} --save-path ${SAVE_PATH} --n-experts ${EXPERTS} --model-parallel ${MP}
7
+ ```
8
+
9
+ Then chat with DeepSeek model at will!
10
+ ```bash
11
+ export CONFIG=config_671B_v3.1.json
12
+ torchrun --nproc-per-node ${MP} generate.py --ckpt-path ${SAVE_PATH} --config ${CONFIG} --interactive --temperature {T}
13
+ ```
inference/config_671B_v3.1.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "vocab_size": 129280,
3
+ "dim": 7168,
4
+ "inter_dim": 18432,
5
+ "moe_inter_dim": 2048,
6
+ "n_layers": 61,
7
+ "n_dense_layers": 3,
8
+ "n_heads": 128,
9
+ "n_routed_experts": 256,
10
+ "n_shared_experts": 1,
11
+ "n_activated_experts": 8,
12
+ "n_expert_groups": 8,
13
+ "n_limited_groups": 4,
14
+ "route_scale": 2.5,
15
+ "score_func": "sigmoid",
16
+ "q_lora_rank": 1536,
17
+ "kv_lora_rank": 512,
18
+ "qk_nope_head_dim": 128,
19
+ "qk_rope_head_dim": 64,
20
+ "v_head_dim": 128,
21
+ "dtype": "fp8",
22
+ "scale_fmt": "ue8m0"
23
+ }
inference/convert.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ from argparse import ArgumentParser
4
+ from glob import glob
5
+ from tqdm import tqdm, trange
6
+
7
+ import torch
8
+ from safetensors.torch import safe_open, save_file
9
+
10
+
11
+ mapping = {
12
+ "embed_tokens": ("embed", 0),
13
+ "input_layernorm": ("attn_norm", None),
14
+ "post_attention_layernorm": ("ffn_norm", None),
15
+ "q_proj": ("wq", 0),
16
+ "q_a_proj": ("wq_a", None),
17
+ "q_a_layernorm": ("q_norm", None),
18
+ "q_b_proj": ("wq_b", 0),
19
+ "kv_a_proj_with_mqa": ("wkv_a", None),
20
+ "kv_a_layernorm": ("kv_norm", None),
21
+ "kv_b_proj": ("wkv_b", 0),
22
+ "o_proj": ("wo", 1),
23
+ "gate": ("gate", None),
24
+ "gate_proj": ("w1", 0),
25
+ "down_proj": ("w2", 1),
26
+ "up_proj": ("w3", 0),
27
+ "norm": ("norm", None),
28
+ "lm_head": ("head", 0),
29
+ "scale": ("scale", None),
30
+ }
31
+
32
+
33
+ def main(hf_ckpt_path, save_path, n_experts, mp):
34
+ """
35
+ Converts and saves model checkpoint files into a specified format.
36
+
37
+ Args:
38
+ hf_ckpt_path (str): Path to the directory containing the input checkpoint files.
39
+ save_path (str): Path to the directory where the converted checkpoint files will be saved.
40
+ n_experts (int): Total number of experts in the model.
41
+ mp (int): Model parallelism factor.
42
+
43
+ Returns:
44
+ None
45
+ """
46
+ torch.set_num_threads(8)
47
+ n_local_experts = n_experts // mp
48
+ state_dicts = [{} for _ in range(mp)]
49
+
50
+ for file_path in tqdm(glob(os.path.join(hf_ckpt_path, "*.safetensors"))):
51
+ with safe_open(file_path, framework="pt", device="cpu") as f:
52
+ for name in f.keys():
53
+ if "model.layers.61" in name:
54
+ continue
55
+ param: torch.Tensor = f.get_tensor(name)
56
+ if name.startswith("model."):
57
+ name = name[len("model."):]
58
+ name = name.replace("self_attn", "attn")
59
+ name = name.replace("mlp", "ffn")
60
+ name = name.replace("weight_scale_inv", "scale")
61
+ name = name.replace("e_score_correction_bias", "bias")
62
+ key = name.split(".")[-2]
63
+ assert key in mapping, f"Key {key} not found in mapping"
64
+ new_key, dim = mapping[key]
65
+ name = name.replace(key, new_key)
66
+ for i in range(mp):
67
+ new_param = param
68
+ if "experts" in name and "shared_experts" not in name:
69
+ idx = int(name.split(".")[-3])
70
+ if idx < i * n_local_experts or idx >= (i + 1) * n_local_experts:
71
+ continue
72
+ elif dim is not None:
73
+ assert param.size(dim) % mp == 0, f"Dimension {dim} must be divisible by {mp}"
74
+ shard_size = param.size(dim) // mp
75
+ new_param = param.narrow(dim, i * shard_size, shard_size).contiguous()
76
+ state_dicts[i][name] = new_param
77
+
78
+ os.makedirs(save_path, exist_ok=True)
79
+
80
+ for i in trange(mp):
81
+ save_file(state_dicts[i], os.path.join(save_path, f"model{i}-mp{mp}.safetensors"))
82
+
83
+ for file_path in glob(os.path.join(hf_ckpt_path, "*token*")):
84
+ new_file_path = os.path.join(save_path, os.path.basename(file_path))
85
+ shutil.copyfile(file_path, new_file_path)
86
+
87
+
88
+ if __name__ == "__main__":
89
+ parser = ArgumentParser()
90
+ parser.add_argument("--hf-ckpt-path", type=str, required=True)
91
+ parser.add_argument("--save-path", type=str, required=True)
92
+ parser.add_argument("--n-experts", type=int, required=True)
93
+ parser.add_argument("--model-parallel", type=int, required=True)
94
+ args = parser.parse_args()
95
+ assert args.n_experts % args.model_parallel == 0, "Number of experts must be divisible by model parallelism"
96
+ main(args.hf_ckpt_path, args.save_path, args.n_experts, args.model_parallel)
inference/generate.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from argparse import ArgumentParser
4
+ from typing import List
5
+
6
+ import torch
7
+ import torch.distributed as dist
8
+ from transformers import AutoTokenizer
9
+ from safetensors.torch import load_model
10
+
11
+ from model import Transformer, ModelArgs
12
+
13
+
14
+ def sample(logits, temperature: float = 1.0):
15
+ """
16
+ Samples a token from the logits using temperature scaling.
17
+
18
+ Args:
19
+ logits (torch.Tensor): The logits tensor for token predictions.
20
+ temperature (float, optional): Temperature for scaling logits. Defaults to 1.0.
21
+
22
+ Returns:
23
+ torch.Tensor: The sampled token.
24
+ """
25
+ logits = logits / max(temperature, 1e-5)
26
+ probs = torch.softmax(logits, dim=-1, dtype=torch.float32)
27
+ return probs.div_(torch.empty_like(probs).exponential_(1)).argmax(dim=-1)
28
+
29
+
30
+ @torch.inference_mode()
31
+ def generate(
32
+ model: Transformer,
33
+ prompt_tokens: List[List[int]],
34
+ max_new_tokens: int,
35
+ eos_id: int,
36
+ temperature: float = 1.0
37
+ ) -> List[List[int]]:
38
+ """
39
+ Generates new tokens based on the given prompt tokens using the specified model.
40
+
41
+ Args:
42
+ model (Transformer): The transformer model used for token generation.
43
+ prompt_tokens (List[List[int]]): A list of lists containing the prompt tokens for each sequence.
44
+ max_new_tokens (int): The maximum number of new tokens to generate.
45
+ eos_id (int): The end-of-sequence token ID.
46
+ temperature (float, optional): The temperature value for sampling. Defaults to 1.0.
47
+
48
+ Returns:
49
+ List[List[int]]: A list of lists containing the generated tokens for each sequence.
50
+ """
51
+ prompt_lens = [len(t) for t in prompt_tokens]
52
+ assert max(prompt_lens) <= model.max_seq_len, f"Prompt length exceeds model maximum sequence length (max_seq_len={model.max_seq_len})"
53
+ total_len = min(model.max_seq_len, max_new_tokens + max(prompt_lens))
54
+ tokens = torch.full((len(prompt_tokens), total_len), -1, dtype=torch.long, device="cuda")
55
+ for i, t in enumerate(prompt_tokens):
56
+ tokens[i, :len(t)] = torch.tensor(t, dtype=torch.long, device="cuda")
57
+ prev_pos = 0
58
+ finished = torch.tensor([False] * len(prompt_tokens), device="cuda")
59
+ prompt_mask = tokens != -1
60
+ for cur_pos in range(min(prompt_lens), total_len):
61
+ logits = model.forward(tokens[:, prev_pos:cur_pos], prev_pos)
62
+ if temperature > 0:
63
+ next_token = sample(logits, temperature)
64
+ else:
65
+ next_token = logits.argmax(dim=-1)
66
+ next_token = torch.where(prompt_mask[:, cur_pos], tokens[:, cur_pos], next_token)
67
+ tokens[:, cur_pos] = next_token
68
+ finished |= torch.logical_and(~prompt_mask[:, cur_pos], next_token == eos_id)
69
+ prev_pos = cur_pos
70
+ if finished.all():
71
+ break
72
+ completion_tokens = []
73
+ for i, toks in enumerate(tokens.tolist()):
74
+ toks = toks[prompt_lens[i]:prompt_lens[i]+max_new_tokens]
75
+ if eos_id in toks:
76
+ toks = toks[:toks.index(eos_id)]
77
+ completion_tokens.append(toks)
78
+ return completion_tokens
79
+
80
+
81
+ def main(
82
+ ckpt_path: str,
83
+ config: str,
84
+ input_file: str = "",
85
+ interactive: bool = True,
86
+ max_new_tokens: int = 100,
87
+ temperature: float = 1.0,
88
+ ) -> None:
89
+ """
90
+ Main function to load the model and perform interactive or batch text generation.
91
+
92
+ Args:
93
+ ckpt_path (str): Path to the model checkpoint directory.
94
+ config (str): Path to the model configuration file.
95
+ input_file (str, optional): Path to a file containing input prompts. Defaults to "".
96
+ interactive (bool, optional): Whether to run in interactive mode. Defaults to True.
97
+ max_new_tokens (int, optional): Maximum number of new tokens to generate. Defaults to 100.
98
+ temperature (float, optional): Temperature for sampling. Defaults to 1.0.
99
+ """
100
+ world_size = int(os.getenv("WORLD_SIZE", "1"))
101
+ rank = int(os.getenv("RANK", "0"))
102
+ local_rank = int(os.getenv("LOCAL_RANK", "0"))
103
+ if world_size > 1:
104
+ dist.init_process_group("nccl")
105
+ global print
106
+ if rank != 0:
107
+ print = lambda *_, **__: None
108
+ torch.cuda.set_device(local_rank)
109
+ torch.set_default_dtype(torch.bfloat16)
110
+ torch.set_num_threads(8)
111
+ torch.manual_seed(33377335)
112
+ with open(config) as f:
113
+ args = ModelArgs(**json.load(f))
114
+ print(args)
115
+ with torch.device("cuda"):
116
+ model = Transformer(args)
117
+ tokenizer = AutoTokenizer.from_pretrained(ckpt_path)
118
+ print("load model")
119
+ load_model(model, os.path.join(ckpt_path, f"model{rank}-mp{world_size}.safetensors"))
120
+ print("I'm DeepSeek 👋")
121
+
122
+ if interactive:
123
+ messages = []
124
+ while True:
125
+ if world_size == 1:
126
+ prompt = input(">>> ")
127
+ elif rank == 0:
128
+ prompt = input(">>> ")
129
+ objects = [prompt]
130
+ dist.broadcast_object_list(objects, 0)
131
+ else:
132
+ objects = [None]
133
+ dist.broadcast_object_list(objects, 0)
134
+ prompt = objects[0]
135
+ if prompt == "/exit":
136
+ break
137
+ elif prompt == "/clear":
138
+ messages.clear()
139
+ continue
140
+ messages.append({"role": "user", "content": prompt})
141
+ prompt_tokens = tokenizer.apply_chat_template(messages, add_generation_prompt=True)
142
+ completion_tokens = generate(model, [prompt_tokens], max_new_tokens, tokenizer.eos_token_id, temperature)
143
+ completion = tokenizer.decode(completion_tokens[0], skip_special_tokens=True)
144
+ print(completion)
145
+ messages.append({"role": "assistant", "content": completion})
146
+ else:
147
+ with open(input_file) as f:
148
+ prompts = f.read().split("\n\n")
149
+ assert len(prompts) <= args.max_batch_size, f"Number of prompts exceeds maximum batch size ({args.max_batch_size})"
150
+ prompt_tokens = [tokenizer.apply_chat_template([{"role": "user", "content": prompt}], add_generation_prompt=True) for prompt in prompts]
151
+ completion_tokens = generate(model, prompt_tokens, max_new_tokens, tokenizer.eos_token_id, temperature)
152
+ completions = tokenizer.batch_decode(completion_tokens, skip_special_tokens=True)
153
+ for prompt, completion in zip(prompts, completions):
154
+ print("Prompt:", prompt)
155
+ print("Completion:", completion)
156
+ print()
157
+
158
+ if world_size > 1:
159
+ dist.destroy_process_group()
160
+
161
+
162
+ if __name__ == "__main__":
163
+ """
164
+ Command-line interface for distributed text generation.
165
+
166
+ Arguments:
167
+ --ckpt-path (str): Path to the model checkpoint directory.
168
+ --config (str): Path to the model configuration file.
169
+ --input-file (str, optional): File containing prompts for batch processing.
170
+ --interactive (bool, optional): Enable interactive mode for generating text.
171
+ --max-new-tokens (int, optional): Maximum number of new tokens to generate. Defaults to 200.
172
+ --temperature (float, optional): Temperature for sampling. Defaults to 0.2.
173
+
174
+ Raises:
175
+ AssertionError: If neither input-file nor interactive mode is specified.
176
+ """
177
+ parser = ArgumentParser()
178
+ parser.add_argument("--ckpt-path", type=str, required=True)
179
+ parser.add_argument("--config", type=str, required=True)
180
+ parser.add_argument("--input-file", type=str, default="")
181
+ parser.add_argument("--interactive", action="store_true")
182
+ parser.add_argument("--max-new-tokens", type=int, default=200)
183
+ parser.add_argument("--temperature", type=float, default=0.6)
184
+ args = parser.parse_args()
185
+ assert args.input_file or args.interactive, "Either input-file or interactive mode must be specified"
186
+ main(args.ckpt_path, args.config, args.input_file, args.interactive, args.max_new_tokens, args.temperature)
inference/kernel.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import tilelang
3
+ import tilelang.language as T
4
+ from typing import Tuple, Optional
5
+
6
+
7
+ tilelang.set_log_level("WARNING")
8
+
9
+ pass_configs = {
10
+ tilelang.PassConfigKey.TL_DISABLE_WARP_SPECIALIZED: True,
11
+ tilelang.PassConfigKey.TL_DISABLE_TMA_LOWER: True,
12
+ tilelang.PassConfigKey.TL_DISABLE_FAST_MATH: True,
13
+ }
14
+
15
+ FP8 = "float8_e4m3"
16
+ BF16 = "bfloat16"
17
+ FP32 = "float32"
18
+
19
+
20
+ def fast_log2_ceil(x):
21
+ bits_x = T.reinterpret("uint32", x)
22
+ exp_x = (bits_x >> 23) & 0xFF
23
+ man_bits = bits_x & ((1 << 23) - 1)
24
+ return T.Cast("int32", exp_x - 127 + T.if_then_else(man_bits != 0, 1, 0))
25
+
26
+
27
+ def fast_pow2(x):
28
+ bits_x = (x + 127) << 23
29
+ return T.reinterpret("float32", bits_x)
30
+
31
+
32
+ def fast_round_scale(amax, fp8_max_inv):
33
+ return fast_pow2(fast_log2_ceil(amax * fp8_max_inv))
34
+
35
+
36
+ @tilelang.jit(pass_configs=pass_configs)
37
+ def act_quant_kernel(
38
+ N, in_dtype=BF16, out_dtype=FP8, scale_dtype=FP32, round_scale=False
39
+ ):
40
+ M = T.symbolic("M")
41
+ fp8_min = -448.0
42
+ fp8_max = 448.0
43
+ fp8_max_inv = 1 / fp8_max
44
+ num_stages = 0 if round_scale else 2
45
+ blk_m = 32
46
+ group_size = 128
47
+
48
+ @T.prim_func
49
+ def act_quant_kernel_(
50
+ X: T.Tensor[(M, N), in_dtype],
51
+ Y: T.Tensor[(M, N), out_dtype],
52
+ S: T.Tensor[(M, T.ceildiv(N, group_size)), scale_dtype],
53
+ ):
54
+ with T.Kernel(T.ceildiv(M, blk_m), T.ceildiv(N, group_size), threads=128) as (
55
+ pid_m,
56
+ pid_n,
57
+ ):
58
+ x_shared = T.alloc_shared((blk_m, group_size), in_dtype)
59
+ x_local = T.alloc_fragment((blk_m, group_size), in_dtype)
60
+ amax_local = T.alloc_fragment((blk_m,), scale_dtype)
61
+ s_local = T.alloc_fragment((blk_m,), scale_dtype)
62
+ y_local = T.alloc_fragment((blk_m, group_size), out_dtype)
63
+ y_shared = T.alloc_shared((blk_m, group_size), out_dtype)
64
+
65
+ for _ in T.Pipelined(1, num_stages=num_stages):
66
+ T.copy(X[pid_m * blk_m, pid_n * group_size], x_shared)
67
+ T.copy(x_shared, x_local)
68
+ T.reduce_absmax(x_local, amax_local, dim=1)
69
+ for i in T.Parallel(blk_m):
70
+ amax_local[i] = T.max(amax_local[i], 1e-4)
71
+ if round_scale:
72
+ s_local[i] = fast_round_scale(amax_local[i], fp8_max_inv)
73
+ else:
74
+ s_local[i] = amax_local[i] * fp8_max_inv
75
+ for i, j in T.Parallel(blk_m, group_size):
76
+ y_local[i, j] = T.clamp(
77
+ x_local[i, j] / s_local[i], fp8_min, fp8_max
78
+ )
79
+ for i in T.Parallel(blk_m):
80
+ S[pid_m * blk_m + i, pid_n] = s_local[i]
81
+ T.copy(y_local, y_shared)
82
+ T.copy(y_shared, Y[pid_m * blk_m, pid_n * group_size])
83
+
84
+ return act_quant_kernel_
85
+
86
+
87
+ def act_quant(
88
+ x: torch.Tensor, block_size: int = 128, scale_fmt: Optional[str] = None
89
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
90
+ """
91
+ Quantizes the input tensor `x` using block-wise quantization.
92
+
93
+ Args:
94
+ x (torch.Tensor): The input tensor to be quantized. Must be contiguous and its last dimension size must be divisible by `block_size`.
95
+ block_size (int, optional): The size of the blocks to be used for quantization. Default is 128.
96
+ scale_fmt (Optional[str], optional): The format of the scale. Default is None.
97
+ Returns:
98
+ Tuple[torch.Tensor, torch.Tensor]: A tuple containing:
99
+ - The quantized tensor with dtype `torch.float8_e4m3fn`.
100
+ - A tensor of scaling factors with dtype `torch.float32`.
101
+ """
102
+ assert x.is_contiguous(), "Input tensor must be contiguous"
103
+ assert x.size(-1) % block_size == 0, (
104
+ f"Last dimension size must be divisible by block_size (block_size={block_size})"
105
+ )
106
+ N = x.size(-1)
107
+ y = torch.empty_like(x, dtype=torch.float8_e4m3fn)
108
+ s = x.new_empty(*x.size()[:-1], N // block_size, dtype=torch.float32)
109
+ kernel = act_quant_kernel(N, round_scale=scale_fmt is not None)
110
+ kernel(x.view(-1, N), y.view(-1, N), s.view(-1, N // block_size))
111
+ return y, s
112
+
113
+
114
+ @tilelang.jit(pass_configs=pass_configs)
115
+ def fp8_gemm_kernel(N, K, out_dtype=BF16, accum_dtype="float32"):
116
+ assert out_dtype in [BF16, "float32"]
117
+
118
+ M = T.symbolic("M")
119
+ group_size = 128
120
+ block_M = 32
121
+ block_N = 128
122
+ block_K = 128
123
+
124
+ @T.prim_func
125
+ def fp8_gemm_kernel_(
126
+ A: T.Tensor[(M, K), FP8],
127
+ B: T.Tensor[(N, K), FP8],
128
+ C: T.Tensor[(M, N), out_dtype],
129
+ scales_a: T.Tensor[(M, T.ceildiv(K, group_size)), FP32],
130
+ scales_b: T.Tensor[(T.ceildiv(N, group_size), T.ceildiv(K, group_size)), FP32],
131
+ ):
132
+ with T.Kernel(T.ceildiv(N, block_N), T.ceildiv(M, block_M), threads=128) as (
133
+ bx,
134
+ by,
135
+ ):
136
+ A_shared = T.alloc_shared((block_M, block_K), FP8)
137
+ B_shared = T.alloc_shared((block_N, block_K), FP8)
138
+ C_shared = T.alloc_shared((block_M, block_N), out_dtype)
139
+ Scale_C_shared = T.alloc_shared((block_M), FP32)
140
+ C_local = T.alloc_fragment((block_M, block_N), accum_dtype)
141
+ C_local_accum = T.alloc_fragment((block_M, block_N), accum_dtype)
142
+
143
+ # Improve L2 Cache
144
+ T.use_swizzle(panel_size=10)
145
+
146
+ T.clear(C_local)
147
+ T.clear(C_local_accum)
148
+ K_iters = T.ceildiv(K, block_K)
149
+ for k in T.Pipelined(K_iters, num_stages=4):
150
+ # Load A into shared memory
151
+ T.copy(A[by * block_M, k * block_K], A_shared)
152
+ # Load B into shared memory
153
+ T.copy(B[bx * block_N, k * block_K], B_shared)
154
+ # Load scale into shared memory
155
+ Scale_B = scales_b[bx * block_N // group_size, k]
156
+ for i in T.Parallel(block_M):
157
+ Scale_C_shared[i] = scales_a[by * block_M + i, k] * Scale_B
158
+
159
+ T.gemm(A_shared, B_shared, C_local, transpose_B=True)
160
+ # Promote to enable 2xAcc
161
+ for i, j in T.Parallel(block_M, block_N):
162
+ C_local_accum[i, j] += C_local[i, j] * Scale_C_shared[i]
163
+ T.clear(C_local)
164
+ # TMA store
165
+ T.copy(C_local_accum, C_shared)
166
+ T.copy(C_shared, C[by * block_M, bx * block_N])
167
+
168
+ return fp8_gemm_kernel_
169
+
170
+
171
+ def fp8_gemm(
172
+ a: torch.Tensor, a_s: torch.Tensor, b: torch.Tensor, b_s: torch.Tensor
173
+ ) -> torch.Tensor:
174
+ """
175
+ Perform a matrix multiplication using FP8 precision.
176
+
177
+ Args:
178
+ a (torch.Tensor): The first input matrix, must be contiguous.
179
+ a_s (torch.Tensor): The scaling factor for the first input matrix, must be contiguous.
180
+ b (torch.Tensor): The second input matrix, must be contiguous.
181
+ b_s (torch.Tensor): The scaling factor for the second input matrix, must be contiguous.
182
+
183
+ Returns:
184
+ torch.Tensor: The result of the matrix multiplication.
185
+ """
186
+ assert a.is_contiguous() and b.is_contiguous(), "Input tensors must be contiguous"
187
+ assert a_s.is_contiguous() and b_s.is_contiguous(), (
188
+ "Scaling factor tensors must be contiguous"
189
+ )
190
+ K = a.size(-1)
191
+ M = a.numel() // K
192
+ N = b.size(0)
193
+ c = a.new_empty(*a.size()[:-1], N, dtype=torch.get_default_dtype())
194
+ kernel = fp8_gemm_kernel(N, K)
195
+ kernel(a.view(M, K), b, c.view(M, N), a_s.view(M, -1), b_s)
196
+ return c
197
+
198
+
199
+ @tilelang.jit(out_idx=[4], pass_configs=pass_configs)
200
+ def fp8_index_kernel(h: int, d: int):
201
+ b = T.symbolic("b")
202
+ m = T.symbolic("m")
203
+ n = T.symbolic("n")
204
+
205
+ blk_n1 = 512
206
+ blk_n2 = 128
207
+
208
+ @T.prim_func
209
+ def fp8_index_kernel_(
210
+ q: T.Tensor[(b, m, h, d), FP8],
211
+ q_s: T.Tensor[(b, m, h), FP32],
212
+ k: T.Tensor[(b, n, d), FP8],
213
+ k_s: T.Tensor[(b, n), FP32],
214
+ o: T.Tensor[(b, m, n), FP32],
215
+ ) -> None:
216
+ with T.Kernel(b, m, T.ceildiv(n, blk_n1)) as (i_b, i_m, i1_n):
217
+ q_smem = T.alloc_shared((h, d), FP8)
218
+ T.copy(q[i_b, i_m, 0, 0], q_smem)
219
+
220
+ q_s_frag = T.alloc_fragment(h, FP32)
221
+ T.copy(q_s[i_b, i_m, 0], q_s_frag)
222
+
223
+ for i2_n in T.Pipelined(blk_n1 // blk_n2, num_stages=2):
224
+ k_smem = T.alloc_shared((blk_n2, d), FP8)
225
+ T.copy(k[i_b, i1_n * blk_n1 + i2_n * blk_n2, 0], k_smem)
226
+
227
+ k_s_frag = T.alloc_fragment(blk_n2, FP32)
228
+ T.copy(k_s[i_b, i1_n * blk_n1 + i2_n * blk_n2], k_s_frag)
229
+
230
+ logits = T.alloc_fragment((blk_n2, h), FP32)
231
+ T.gemm(
232
+ k_smem,
233
+ q_smem,
234
+ logits,
235
+ transpose_A=False,
236
+ transpose_B=True,
237
+ clear_accum=True,
238
+ )
239
+
240
+ for i_h, i3_n in T.Parallel(h, blk_n2):
241
+ logits[i3_n, i_h] = T.max(logits[i3_n, i_h], 0) * q_s_frag[i_h]
242
+
243
+ logits_sum = T.alloc_fragment(blk_n2, FP32)
244
+ T.reduce_sum(logits, logits_sum, dim=1)
245
+
246
+ for i3_n in T.Parallel(blk_n2):
247
+ logits_sum[i3_n] *= k_s_frag[i3_n]
248
+
249
+ T.copy(logits_sum, o[i_b, i_m, i1_n * blk_n1 + i2_n * blk_n2])
250
+
251
+ return fp8_index_kernel_
252
+
253
+
254
+ def fp8_index(
255
+ q: torch.Tensor,
256
+ q_s: torch.Tensor,
257
+ k: torch.Tensor,
258
+ k_s: torch.Tensor,
259
+ ) -> torch.Tensor:
260
+ """
261
+ Perform index score using FP8 precision.
262
+
263
+ Args:
264
+ q (torch.Tensor): The Q tensor, must be contiguous.
265
+ q_s (torch.Tensor): The scaling factor for Q (float), must be contiguous.
266
+ k (torch.Tensor): The K tensor, must be contiguous.
267
+ k_s (torch.Tensor): The scaling factor for K (e8m0 here), must be contiguous.
268
+
269
+ fp8 q @ fp8 k -> fp32 logits
270
+ relu(fp32 logits) * q_s (weights) -> fp32 logits
271
+ fp32 logits -> fp32 logits_sum
272
+ fp32 logits_sum * k_s (e8m0) -> fp32 index_score
273
+ """
274
+ return fp8_index_kernel(q.shape[2], q.shape[3])(q, q_s, k, k_s)
inference/model.py ADDED
@@ -0,0 +1,822 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from dataclasses import dataclass
3
+ from typing import Tuple, Optional, Literal
4
+
5
+ import torch
6
+ from torch import nn
7
+ import torch.nn.functional as F
8
+ import torch.distributed as dist
9
+
10
+ from kernel import act_quant, fp8_gemm
11
+
12
+ world_size = 1
13
+ rank = 0
14
+ block_size = 128
15
+
16
+ @dataclass
17
+ class ModelArgs:
18
+ """
19
+ Data class for defining model arguments and hyperparameters.
20
+
21
+ Attributes:
22
+ max_batch_size (int): Maximum batch size.
23
+ max_seq_len (int): Maximum sequence length.
24
+ dtype (Literal["bf16", "fp8"]): Data type for computations.
25
+ scale_fmt (Optional[str]): Format for quantization scale.
26
+ vocab_size (int): Vocabulary size.
27
+ dim (int): Model dimension.
28
+ inter_dim (int): Intermediate dimension for MLP layers.
29
+ moe_inter_dim (int): Intermediate dimension for MoE layers.
30
+ n_layers (int): Number of transformer layers.
31
+ n_dense_layers (int): Number of dense layers in the model.
32
+ n_heads (int): Number of attention heads.
33
+ n_routed_experts (int): Number of routed experts for MoE layers.
34
+ n_shared_experts (int): Number of shared experts for MoE layers.
35
+ n_activated_experts (int): Number of activated experts in MoE layers.
36
+ n_expert_groups (int): Number of expert groups.
37
+ n_limited_groups (int): Number of limited groups for MoE routing.
38
+ score_func (Literal["softmax", "sigmoid"]): Scoring function for MoE routing.
39
+ route_scale (float): Scaling factor for routing scores.
40
+ q_lora_rank (int): LoRA rank for query projections.
41
+ kv_lora_rank (int): LoRA rank for key-value projections.
42
+ qk_nope_head_dim (int): Dimension for query-key projections without positional embeddings.
43
+ qk_rope_head_dim (int): Dimension for query-key projections with rotary embeddings.
44
+ v_head_dim (int): Dimension for value projections.
45
+ original_seq_len (int): Original sequence length.
46
+ rope_theta (float): Base for rotary positional encoding.
47
+ rope_factor (float): Scaling factor for extended sequence lengths.
48
+ beta_fast (int): Fast beta correction factor.
49
+ beta_slow (int): Slow beta correction factor.
50
+ mscale (float): Scaling factor for extended attention.
51
+ """
52
+ max_batch_size: int = 8
53
+ max_seq_len: int = 4096 * 4
54
+ dtype: Literal["bf16", "fp8"] = "bf16"
55
+ scale_fmt: Optional[str] = None
56
+ vocab_size: int = 102400
57
+ dim: int = 2048
58
+ inter_dim: int = 10944
59
+ moe_inter_dim: int = 1408
60
+ n_layers: int = 27
61
+ n_dense_layers: int = 1
62
+ n_heads: int = 16
63
+ # moe
64
+ n_routed_experts: int = 64
65
+ n_shared_experts: int = 2
66
+ n_activated_experts: int = 6
67
+ n_expert_groups: int = 1
68
+ n_limited_groups: int = 1
69
+ score_func: Literal["softmax", "sigmoid"] = "softmax"
70
+ route_scale: float = 1.
71
+ # mla
72
+ q_lora_rank: int = 0
73
+ kv_lora_rank: int = 512
74
+ qk_nope_head_dim: int = 128
75
+ qk_rope_head_dim: int = 64
76
+ v_head_dim: int = 128
77
+ # yarn
78
+ original_seq_len: int = 4096
79
+ rope_theta: float = 10000.0
80
+ rope_factor: float = 40
81
+ beta_fast: int = 32
82
+ beta_slow: int = 1
83
+ mscale: float = 1.
84
+
85
+
86
+ class ParallelEmbedding(nn.Module):
87
+ """
88
+ Embedding layer with parallelism support across distributed processes.
89
+
90
+ Args:
91
+ vocab_size (int): Vocabulary size.
92
+ dim (int): Embedding dimension.
93
+ """
94
+ def __init__(self, vocab_size: int, dim: int):
95
+ super().__init__()
96
+ self.vocab_size = vocab_size
97
+ self.dim = dim
98
+ assert vocab_size % world_size == 0, f"Vocabulary size must be divisible by world size (world_size={world_size})"
99
+ self.part_vocab_size = (vocab_size // world_size)
100
+ self.vocab_start_idx = rank * self.part_vocab_size
101
+ self.vocab_end_idx = self.vocab_start_idx + self.part_vocab_size
102
+ self.weight = nn.Parameter(torch.empty(self.part_vocab_size, self.dim))
103
+
104
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
105
+ """
106
+ Forward pass for parallel embedding layer.
107
+
108
+ Args:
109
+ x (torch.Tensor): Input tensor containing token indices.
110
+
111
+ Returns:
112
+ torch.Tensor: Embedded representations.
113
+
114
+ Raises:
115
+ ValueError: If `world_size` is not defined.
116
+ """
117
+ if world_size > 1:
118
+ mask = (x < self.vocab_start_idx) | (x >= self.vocab_end_idx)
119
+ x = x - self.vocab_start_idx
120
+ x[mask] = 0
121
+ y = F.embedding(x, self.weight)
122
+ if world_size > 1:
123
+ y[mask] = 0
124
+ dist.all_reduce(y)
125
+ return y
126
+
127
+
128
+ def linear(x: torch.Tensor, weight: torch.Tensor, bias: Optional[torch.Tensor] = None,
129
+ scale_fmt: Optional[str] = None) -> torch.Tensor:
130
+ """
131
+ Applies a linear transformation to the incoming data: y = xA^T + b.
132
+ This function supports specialized implementations based on quantization
133
+ and tensor formats.
134
+
135
+ Args:
136
+ x (torch.Tensor): The input tensor.
137
+ weight (torch.Tensor): The weight tensor. It may be quantized and
138
+ requires dequantization for certain cases.
139
+ bias (Optional[torch.Tensor]): The bias tensor to be added. Default is None.
140
+ scale_fmt (Optional[str]): The format of scaling factors.
141
+
142
+ Returns:
143
+ torch.Tensor: The result of the linear transformation, which may involve
144
+ quantization-aware computations depending on the input parameters.
145
+
146
+ Notes:
147
+ - If `weight` is quantized (e.g., `element_size() == 1`), a dequantized version
148
+ is used for computation.
149
+ - For other cases, the function applies quantization to `x` and uses `fp8_gemm` for computation.
150
+ """
151
+ assert bias is None
152
+
153
+ if weight.dtype != torch.float8_e4m3fn:
154
+ return F.linear(x, weight)
155
+ else:
156
+ x, scale = act_quant(x, block_size, scale_fmt)
157
+ return fp8_gemm(x, scale, weight, weight.scale)
158
+
159
+
160
+ class Linear(nn.Module):
161
+ """
162
+ Custom linear layer with support for quantized weights and optional bias.
163
+
164
+ Args:
165
+ in_features (int): Number of input features.
166
+ out_features (int): Number of output features.
167
+ bias (bool): Whether to include a bias term. Defaults to False.
168
+ dtype (optional): Data type for the layer. Defaults to `torch.bfloat16`.
169
+ """
170
+ dtype = torch.bfloat16
171
+ scale_fmt: Optional[str] = None
172
+
173
+ def __init__(self, in_features: int, out_features: int, bias: bool = False, dtype = None):
174
+ super().__init__()
175
+ self.in_features = in_features
176
+ self.out_features = out_features
177
+ self.weight = nn.Parameter(torch.empty(out_features, in_features, dtype=dtype or Linear.dtype))
178
+ if self.weight.element_size() == 1:
179
+ scale_out_features = (out_features + block_size - 1) // block_size
180
+ scale_in_features = (in_features + block_size - 1) // block_size
181
+ self.weight.scale = self.scale = nn.Parameter(torch.empty(scale_out_features, scale_in_features, dtype=torch.float32))
182
+ else:
183
+ self.register_parameter("scale", None)
184
+ if bias:
185
+ self.bias = nn.Parameter(torch.empty(out_features))
186
+ else:
187
+ self.register_parameter("bias", None)
188
+
189
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
190
+ """
191
+ Forward pass for the custom linear layer.
192
+
193
+ Args:
194
+ x (torch.Tensor): Input tensor.
195
+
196
+ Returns:
197
+ torch.Tensor: Transformed tensor after linear computation.
198
+ """
199
+ return linear(x, self.weight, self.bias, self.scale_fmt)
200
+
201
+
202
+ class ColumnParallelLinear(Linear):
203
+ """
204
+ Linear layer with column parallelism, splitting output features across distributed processes.
205
+
206
+ Args:
207
+ in_features (int): Number of input features.
208
+ out_features (int): Total number of output features.
209
+ bias (bool): Whether to include a bias term. Defaults to False.
210
+ dtype (optional): Data type for the layer. Defaults to `torch.bfloat16`.
211
+ """
212
+ def __init__(self, in_features: int, out_features: int, bias: bool = False, dtype = None):
213
+ assert out_features % world_size == 0, f"Output features must be divisible by world size (world_size={world_size})"
214
+ self.part_out_features = out_features // world_size
215
+ super().__init__(in_features, self.part_out_features, bias, dtype)
216
+
217
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
218
+ """
219
+ Forward pass for column parallel linear layer.
220
+
221
+ Args:
222
+ x (torch.Tensor): Input tensor.
223
+
224
+ Returns:
225
+ torch.Tensor: Transformed tensor with column-parallel computation.
226
+ """
227
+ y = linear(x, self.weight, self.bias, self.scale_fmt)
228
+ return y
229
+
230
+
231
+ class RowParallelLinear(Linear):
232
+ """
233
+ Linear layer with row parallelism, splitting input features across distributed processes.
234
+
235
+ Args:
236
+ in_features (int): Total number of input features.
237
+ out_features (int): Number of output features.
238
+ bias (bool): Whether to include a bias term. Defaults to False.
239
+ dtype (optional): Data type for the layer. Defaults to `torch.bfloat16`.
240
+ """
241
+ def __init__(self, in_features: int, out_features: int, bias: bool = False, reduce_output = True, dtype = None):
242
+ assert in_features % world_size == 0, f"Input features must be divisible by world size (world_size={world_size})"
243
+ self.part_in_features = in_features // world_size
244
+ self.reduce_output = reduce_output
245
+ super().__init__(self.part_in_features, out_features, bias, dtype)
246
+
247
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
248
+ """
249
+ Forward pass for row parallel linear layer.
250
+
251
+ Args:
252
+ x (torch.Tensor): Input tensor.
253
+
254
+ Returns:
255
+ torch.Tensor: Transformed tensor with row-parallel computation.
256
+ """
257
+ y = linear(x, self.weight, None, self.scale_fmt)
258
+ if self.reduce_output and world_size > 1:
259
+ y = y.float()
260
+ dist.all_reduce(y)
261
+ if self.bias is not None:
262
+ y += self.bias
263
+ return y.type_as(x)
264
+
265
+
266
+ class RMSNorm(nn.Module):
267
+ """
268
+ Root Mean Square Layer Normalization (RMSNorm).
269
+
270
+ Args:
271
+ dim (int): Dimension of the input tensor.
272
+ eps (float): Epsilon value for numerical stability. Defaults to 1e-6.
273
+ """
274
+ def __init__(self, dim: int, eps: float = 1e-6):
275
+ super().__init__()
276
+ self.dim = dim
277
+ self.eps = eps
278
+ self.weight = nn.Parameter(torch.ones(dim, dtype=torch.float32))
279
+
280
+ def forward(self, x: torch.Tensor, residual: Optional[torch.Tensor] = None):
281
+ """
282
+ Forward pass for RMSNorm.
283
+
284
+ Args:
285
+ x (torch.Tensor): Input tensor.
286
+
287
+ Returns:
288
+ torch.Tensor: Normalized tensor with the same shape as input.
289
+ """
290
+ dtype = x.dtype
291
+ if residual is None:
292
+ x = x.float()
293
+ var = x.pow(2).mean(-1, keepdim=True)
294
+ x = x * torch.rsqrt(var + self.eps)
295
+ return (self.weight * x).to(dtype)
296
+ else:
297
+ x = residual = x.float() + residual.float()
298
+ var = x.pow(2).mean(-1, keepdim=True)
299
+ x = x * torch.rsqrt(var + self.eps)
300
+ return (self.weight * x).to(dtype), residual.to(dtype)
301
+
302
+
303
+ def precompute_freqs_cis(args: ModelArgs) -> torch.Tensor:
304
+ """
305
+ Precomputes frequency-based complex exponential values for rotary positional embeddings.
306
+
307
+ Args:
308
+ args (ModelArgs): Model arguments containing positional embedding parameters.
309
+
310
+ Returns:
311
+ torch.Tensor: Precomputed complex exponential values for positional embeddings.
312
+ """
313
+ dim = args.qk_rope_head_dim
314
+ seqlen = args.max_seq_len
315
+ beta_fast = args.beta_fast
316
+ beta_slow = args.beta_slow
317
+ base = args.rope_theta
318
+ factor = args.rope_factor
319
+
320
+ def find_correction_dim(num_rotations, dim, base, max_seq_len):
321
+ """
322
+ Computes the correction dimension for a given number of rotations in the rotary positional embedding.
323
+
324
+ Args:
325
+ num_rotations (float): Number of rotations to compute the correction for.
326
+ dim (int): Dimensionality of the embedding space.
327
+ base (float): Base value for the exponential computation.
328
+ max_seq_len (int): Maximum sequence length.
329
+
330
+ Returns:
331
+ float: The correction dimension based on the input parameters.
332
+ """
333
+ return dim * math.log(max_seq_len / (num_rotations * 2 * math.pi)) / (2 * math.log(base))
334
+
335
+ def find_correction_range(low_rot, high_rot, dim, base, max_seq_len):
336
+ """
337
+ Computes the range of correction dimensions for rotary positional embeddings.
338
+
339
+ Args:
340
+ low_rot (float): Lower bound for the number of rotations.
341
+ high_rot (float): Upper bound for the number of rotations.
342
+ dim (int): Dimensionality of the embedding space.
343
+ base (float): Base value for the exponential computation.
344
+ max_seq_len (int): Maximum sequence length.
345
+
346
+ Returns:
347
+ Tuple[int, int]: The range of correction dimensions (low, high), clamped to valid indices.
348
+ """
349
+ low = math.floor(find_correction_dim(low_rot, dim, base, max_seq_len))
350
+ high = math.ceil(find_correction_dim(high_rot, dim, base, max_seq_len))
351
+ return max(low, 0), min(high, dim-1)
352
+
353
+ def linear_ramp_factor(min, max, dim):
354
+ """
355
+ Computes a linear ramp function used to smooth values between a minimum and maximum range.
356
+
357
+ Args:
358
+ min (float): Minimum value for the ramp function.
359
+ max (float): Maximum value for the ramp function.
360
+ dim (int): Dimensionality of the ramp tensor.
361
+
362
+ Returns:
363
+ torch.Tensor: A tensor of shape (dim,) with values linearly interpolated between 0 and 1,
364
+ clamped to the range [0, 1].
365
+ """
366
+ if min == max:
367
+ max += 0.001
368
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
369
+ ramp_func = torch.clamp(linear_func, 0, 1)
370
+ return ramp_func
371
+
372
+ freqs = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
373
+ if seqlen > args.original_seq_len:
374
+ low, high = find_correction_range(beta_fast, beta_slow, dim, base, args.original_seq_len)
375
+ smooth = 1 - linear_ramp_factor(low, high, dim // 2)
376
+ freqs = freqs / factor * (1 - smooth) + freqs * smooth
377
+
378
+ t = torch.arange(seqlen)
379
+ freqs = torch.outer(t, freqs)
380
+ freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
381
+ return freqs_cis
382
+
383
+
384
+ def apply_rotary_emb(x: torch.Tensor, freqs_cis: torch.Tensor) -> torch.Tensor:
385
+ """
386
+ Applies rotary positional embeddings to the input tensor.
387
+
388
+ Args:
389
+ x (torch.Tensor): Input tensor with positional embeddings to be applied.
390
+ freqs_cis (torch.Tensor): Precomputed complex exponential values for positional embeddings.
391
+
392
+ Returns:
393
+ torch.Tensor: Tensor with rotary embeddings applied.
394
+ """
395
+ dtype = x.dtype
396
+ x = torch.view_as_complex(x.float().view(*x.shape[:-1], -1, 2))
397
+ freqs_cis = freqs_cis.view(1, x.size(1), 1, x.size(-1))
398
+ y = torch.view_as_real(x * freqs_cis).flatten(3)
399
+ return y.to(dtype)
400
+
401
+
402
+ def weight_dequant(weight, scale):
403
+ original_shape = weight.shape
404
+ assert weight.dim() == 2
405
+ weight = weight.view(original_shape[0] // block_size, block_size, original_shape[1] // block_size, block_size).transpose(1, 2).contiguous().view(-1, block_size * block_size)
406
+ weight = (weight.float() * scale.view(-1, 1).float()).to(torch.get_default_dtype()).view(original_shape[0] // block_size, original_shape[1] // block_size, block_size, block_size).transpose(1, 2).contiguous().view(original_shape)
407
+ return weight
408
+
409
+
410
+ class MLA(nn.Module):
411
+ """
412
+ Multi-Head Latent Attention (MLA) Layer.
413
+
414
+ Attributes:
415
+ dim (int): Dimensionality of the input features.
416
+ n_heads (int): Number of attention heads.
417
+ n_local_heads (int): Number of local attention heads for distributed systems.
418
+ q_lora_rank (int): Rank for low-rank query projection.
419
+ kv_lora_rank (int): Rank for low-rank key/value projection.
420
+ qk_nope_head_dim (int): Dimensionality of non-positional query/key projections.
421
+ qk_rope_head_dim (int): Dimensionality of rotary-positional query/key projections.
422
+ qk_head_dim (int): Total dimensionality of query/key projections.
423
+ v_head_dim (int): Dimensionality of value projections.
424
+ softmax_scale (float): Scaling factor for softmax in attention computation.
425
+ """
426
+ def __init__(self, args: ModelArgs):
427
+ super().__init__()
428
+ self.dim = args.dim
429
+ self.n_heads = args.n_heads
430
+ self.n_local_heads = args.n_heads // world_size
431
+ self.q_lora_rank = args.q_lora_rank
432
+ self.kv_lora_rank = args.kv_lora_rank
433
+ self.qk_nope_head_dim = args.qk_nope_head_dim
434
+ self.qk_rope_head_dim = args.qk_rope_head_dim
435
+ self.qk_head_dim = args.qk_nope_head_dim + args.qk_rope_head_dim
436
+ self.v_head_dim = args.v_head_dim
437
+
438
+ if self.q_lora_rank == 0:
439
+ self.wq = ColumnParallelLinear(self.dim, self.n_heads * self.qk_head_dim)
440
+ else:
441
+ self.wq_a = Linear(self.dim, self.q_lora_rank)
442
+ self.q_norm = RMSNorm(self.q_lora_rank)
443
+ self.wq_b = ColumnParallelLinear(self.q_lora_rank, self.n_heads * self.qk_head_dim)
444
+ self.wkv_a = Linear(self.dim, self.kv_lora_rank + self.qk_rope_head_dim)
445
+ self.kv_norm = RMSNorm(self.kv_lora_rank)
446
+ self.wkv_b = ColumnParallelLinear(self.kv_lora_rank, self.n_heads * (self.qk_nope_head_dim + self.v_head_dim))
447
+ self.wo = RowParallelLinear(self.n_heads * self.v_head_dim, self.dim)
448
+ self.softmax_scale = self.qk_head_dim ** -0.5
449
+ if args.max_seq_len > args.original_seq_len:
450
+ mscale = 0.1 * args.mscale * math.log(args.rope_factor) + 1.0
451
+ self.softmax_scale = self.softmax_scale * mscale * mscale
452
+
453
+ self.register_buffer("kv_cache", torch.zeros(args.max_batch_size, args.max_seq_len, self.kv_lora_rank), persistent=False)
454
+ self.register_buffer("pe_cache", torch.zeros(args.max_batch_size, args.max_seq_len, self.qk_rope_head_dim), persistent=False)
455
+ self.dequant_wkv_b = None
456
+
457
+ def forward(self, x: torch.Tensor, start_pos: int, freqs_cis: torch.Tensor, mask: Optional[torch.Tensor]):
458
+ """
459
+ Forward pass for the Multi-Head Latent Attention (MLA) Layer.
460
+
461
+ Args:
462
+ x (torch.Tensor): Input tensor of shape (batch_size, seq_len, dim).
463
+ start_pos (int): Starting position in the sequence for caching.
464
+ freqs_cis (torch.Tensor): Precomputed complex exponential values for rotary embeddings.
465
+ mask (Optional[torch.Tensor]): Mask tensor to exclude certain positions from attention.
466
+
467
+ Returns:
468
+ torch.Tensor: Output tensor with the same shape as the input.
469
+ """
470
+ bsz, seqlen, _ = x.size()
471
+ end_pos = start_pos + seqlen
472
+ if self.q_lora_rank == 0:
473
+ q = self.wq(x)
474
+ else:
475
+ q = self.wq_b(self.q_norm(self.wq_a(x)))
476
+ q = q.view(bsz, seqlen, self.n_local_heads, self.qk_head_dim)
477
+ q_nope, q_pe = torch.split(q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
478
+ q_pe = apply_rotary_emb(q_pe, freqs_cis)
479
+ kv = self.wkv_a(x)
480
+ kv, k_pe = torch.split(kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
481
+ kv = self.kv_norm(kv)
482
+ k_pe = apply_rotary_emb(k_pe.unsqueeze(2), freqs_cis)
483
+ self.kv_cache[:bsz, start_pos:end_pos] = kv
484
+ self.pe_cache[:bsz, start_pos:end_pos] = k_pe.squeeze(2)
485
+ if mask is not None: # MHA prefill
486
+ q = torch.cat([q_nope, q_pe], dim=-1)
487
+ kv = self.wkv_b(kv)
488
+ kv = kv.view(bsz, seqlen, self.n_local_heads, self.qk_nope_head_dim + self.v_head_dim)
489
+ k_nope, v = torch.split(kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
490
+ k = torch.cat([k_nope, k_pe.expand(-1, -1, self.n_local_heads, -1)], dim=-1)
491
+ scores = torch.einsum("bshd,bthd->bsht", q, k) * self.softmax_scale
492
+ scores += mask.unsqueeze(1)
493
+ scores = scores.softmax(dim=-1, dtype=torch.float32)
494
+ x = torch.einsum("bsht,bthd->bshd", scores.type_as(x), v)
495
+ else: # MHA decode
496
+ if self.dequant_wkv_b is None and self.wkv_b.scale is not None:
497
+ self.dequant_wkv_b = weight_dequant(self.wkv_b.weight, self.wkv_b.scale)
498
+ wkv_b = self.wkv_b.weight if self.dequant_wkv_b is None else self.dequant_wkv_b
499
+ wkv_b = wkv_b.view(self.n_local_heads, -1, self.kv_lora_rank)
500
+ q_nope = torch.einsum("bshd,hdc->bshc", q_nope, wkv_b[:, :self.qk_nope_head_dim])
501
+ scores = (torch.einsum("bshc,btc->bsht", q_nope, self.kv_cache[:bsz, :end_pos]) +
502
+ torch.einsum("bshr,btr->bsht", q_pe, self.pe_cache[:bsz, :end_pos])) * self.softmax_scale
503
+ scores = scores.softmax(dim=-1, dtype=torch.float32)
504
+ x = torch.einsum("bsht,btc->bshc", scores.type_as(x), self.kv_cache[:bsz, :end_pos])
505
+ x = torch.einsum("bshc,hdc->bshd", x, wkv_b[:, -self.v_head_dim:])
506
+ x = self.wo(x.flatten(2))
507
+ return x
508
+
509
+
510
+ class MLP(nn.Module):
511
+ """
512
+ Multi-Layer Perceptron (MLP) used as a feed-forward layer.
513
+
514
+ Attributes:
515
+ w1 (nn.Module): Linear layer for input-to-hidden transformation.
516
+ w2 (nn.Module): Linear layer for hidden-to-output transformation.
517
+ w3 (nn.Module): Additional linear layer for feature transformation.
518
+ """
519
+ def __init__(self, dim: int, inter_dim: int, reduce_output: bool = True):
520
+ """
521
+ Initializes the MLP layer.
522
+
523
+ Args:
524
+ dim (int): Input and output dimensionality.
525
+ inter_dim (int): Hidden layer dimensionality.
526
+ """
527
+ super().__init__()
528
+ self.w1 = ColumnParallelLinear(dim, inter_dim)
529
+ self.w2 = RowParallelLinear(inter_dim, dim, reduce_output=reduce_output)
530
+ self.w3 = ColumnParallelLinear(dim, inter_dim)
531
+
532
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
533
+ """
534
+ Forward pass for the MLP layer.
535
+
536
+ Args:
537
+ x (torch.Tensor): Input tensor.
538
+
539
+ Returns:
540
+ torch.Tensor: Output tensor after MLP computation.
541
+ """
542
+ return self.w2((F.silu(self.w1(x).float()) * self.w3(x).float()).type_as(x))
543
+
544
+
545
+ class Gate(nn.Module):
546
+ """
547
+ Gating mechanism for routing inputs in a mixture-of-experts (MoE) model.
548
+
549
+ Attributes:
550
+ dim (int): Dimensionality of input features.
551
+ topk (int): Number of top experts activated for each input.
552
+ n_groups (int): Number of groups for routing.
553
+ topk_groups (int): Number of groups to route inputs to.
554
+ score_func (str): Scoring function ('softmax' or 'sigmoid').
555
+ route_scale (float): Scaling factor for routing weights.
556
+ weight (torch.nn.Parameter): Learnable weights for the gate.
557
+ bias (Optional[torch.nn.Parameter]): Optional bias term for the gate.
558
+ """
559
+ def __init__(self, args: ModelArgs):
560
+ """
561
+ Initializes the Gate module.
562
+
563
+ Args:
564
+ args (ModelArgs): Model arguments containing gating parameters.
565
+ """
566
+ super().__init__()
567
+ self.dim = args.dim
568
+ self.topk = args.n_activated_experts
569
+ self.n_groups = args.n_expert_groups
570
+ self.topk_groups = args.n_limited_groups
571
+ self.score_func = args.score_func
572
+ self.route_scale = args.route_scale
573
+ self.weight = nn.Parameter(torch.empty(args.n_routed_experts, args.dim))
574
+ self.bias = nn.Parameter(torch.empty(args.n_routed_experts, dtype=torch.float32)) if self.dim == 7168 else None
575
+
576
+ def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
577
+ """
578
+ Forward pass for the gating mechanism.
579
+
580
+ Args:
581
+ x (torch.Tensor): Input tensor.
582
+
583
+ Returns:
584
+ Tuple[torch.Tensor, torch.Tensor]: Routing weights and selected expert indices.
585
+ """
586
+ scores = linear(x.float(), self.weight.float())
587
+ if self.score_func == "softmax":
588
+ scores = scores.softmax(dim=-1)
589
+ else:
590
+ scores = scores.sigmoid()
591
+ original_scores = scores
592
+ if self.bias is not None:
593
+ scores = scores + self.bias
594
+ if self.n_groups > 1:
595
+ scores = scores.view(x.size(0), self.n_groups, -1)
596
+ if self.bias is None:
597
+ group_scores = scores.amax(dim=-1)
598
+ else:
599
+ group_scores = scores.topk(2, dim=-1)[0].sum(dim=-1)
600
+ indices = group_scores.topk(self.topk_groups, dim=-1)[1]
601
+ mask = scores.new_ones(x.size(0), self.n_groups, dtype=bool).scatter_(1, indices, False)
602
+ scores = scores.masked_fill_(mask.unsqueeze(-1), float("-inf")).flatten(1)
603
+ indices = scores.topk(self.topk, dim=-1)[1]
604
+ weights = original_scores.gather(1, indices)
605
+ if self.score_func == "sigmoid":
606
+ weights /= weights.sum(dim=-1, keepdim=True)
607
+ weights *= self.route_scale
608
+ return weights, indices
609
+
610
+
611
+ class Expert(nn.Module):
612
+ """
613
+ Expert layer for Mixture-of-Experts (MoE) models.
614
+
615
+ Attributes:
616
+ w1 (nn.Module): Linear layer for input-to-hidden transformation.
617
+ w2 (nn.Module): Linear layer for hidden-to-output transformation.
618
+ w3 (nn.Module): Additional linear layer for feature transformation.
619
+ """
620
+ def __init__(self, dim: int, inter_dim: int):
621
+ """
622
+ Initializes the Expert layer.
623
+
624
+ Args:
625
+ dim (int): Input and output dimensionality.
626
+ inter_dim (int): Hidden layer dimensionality.
627
+ """
628
+ super().__init__()
629
+ self.w1 = Linear(dim, inter_dim)
630
+ self.w2 = Linear(inter_dim, dim)
631
+ self.w3 = Linear(dim, inter_dim)
632
+
633
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
634
+ """
635
+ Forward pass for the Expert layer.
636
+
637
+ Args:
638
+ x (torch.Tensor): Input tensor.
639
+
640
+ Returns:
641
+ torch.Tensor: Output tensor after expert computation.
642
+ """
643
+ return self.w2((F.silu(self.w1(x).float()) * self.w3(x).float()).type_as(x))
644
+
645
+
646
+ class MoE(nn.Module):
647
+ """
648
+ Mixture-of-Experts (MoE) module.
649
+
650
+ Attributes:
651
+ dim (int): Dimensionality of input features.
652
+ n_routed_experts (int): Total number of experts in the model.
653
+ n_local_experts (int): Number of experts handled locally in distributed systems.
654
+ n_activated_experts (int): Number of experts activated for each input.
655
+ gate (nn.Module): Gating mechanism to route inputs to experts.
656
+ experts (nn.ModuleList): List of expert modules.
657
+ shared_experts (nn.Module): Shared experts applied to all inputs.
658
+ """
659
+ def __init__(self, args: ModelArgs):
660
+ """
661
+ Initializes the MoE module.
662
+
663
+ Args:
664
+ args (ModelArgs): Model arguments containing MoE parameters.
665
+ """
666
+ super().__init__()
667
+ self.dim = args.dim
668
+ assert args.n_routed_experts % world_size == 0, f"Number of experts must be divisible by world size (world_size={world_size})"
669
+ self.n_routed_experts = args.n_routed_experts
670
+ self.n_local_experts = args.n_routed_experts // world_size
671
+ self.n_activated_experts = args.n_activated_experts
672
+ self.experts_start_idx = rank * self.n_local_experts
673
+ self.experts_end_idx = self.experts_start_idx + self.n_local_experts
674
+ self.gate = Gate(args)
675
+ self.experts = nn.ModuleList([Expert(args.dim, args.moe_inter_dim) if self.experts_start_idx <= i < self.experts_end_idx else None
676
+ for i in range(self.n_routed_experts)])
677
+ self.shared_experts = MLP(args.dim, args.n_shared_experts * args.moe_inter_dim, reduce_output=False)
678
+
679
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
680
+ """
681
+ Forward pass for the MoE module.
682
+
683
+ Args:
684
+ x (torch.Tensor): Input tensor.
685
+
686
+ Returns:
687
+ torch.Tensor: Output tensor after expert routing and computation.
688
+ """
689
+ shape = x.size()
690
+ x = x.view(-1, self.dim)
691
+ weights, indices = self.gate(x)
692
+ y = torch.zeros_like(x, dtype=torch.float32)
693
+ counts = torch.bincount(indices.flatten(), minlength=self.n_routed_experts).tolist()
694
+ for i in range(self.experts_start_idx, self.experts_end_idx):
695
+ if counts[i] == 0:
696
+ continue
697
+ expert = self.experts[i]
698
+ idx, top = torch.where(indices == i)
699
+ y[idx] += expert(x[idx]) * weights[idx, top, None]
700
+ y += self.shared_experts(x)
701
+ if world_size > 1:
702
+ dist.all_reduce(y)
703
+ return y.type_as(x).view(shape)
704
+
705
+
706
+ class Block(nn.Module):
707
+ """
708
+ Transformer block combining attention and feed-forward layers.
709
+
710
+ Attributes:
711
+ attn (nn.Module): Attention layer (MLA).
712
+ ffn (nn.Module): Feed-forward network (MLP or MoE).
713
+ attn_norm (nn.Module): Layer normalization for attention.
714
+ ffn_norm (nn.Module): Layer normalization for feed-forward network.
715
+ """
716
+ def __init__(self, layer_id: int, args: ModelArgs):
717
+ """
718
+ Initializes the Transformer block.
719
+
720
+ Args:
721
+ layer_id (int): Layer index in the transformer.
722
+ args (ModelArgs): Model arguments containing block parameters.
723
+ """
724
+ super().__init__()
725
+ self.attn = MLA(args)
726
+ self.ffn = MLP(args.dim, args.inter_dim) if layer_id < args.n_dense_layers else MoE(args)
727
+ self.attn_norm = RMSNorm(args.dim)
728
+ self.ffn_norm = RMSNorm(args.dim)
729
+
730
+ def forward(self, x: torch.Tensor, residual: torch.Tensor, start_pos: int, freqs_cis: torch.Tensor, mask: Optional[torch.Tensor]) -> torch.Tensor:
731
+ """
732
+ Forward pass for the Transformer block.
733
+
734
+ Args:
735
+ x (torch.Tensor): Input tensor.
736
+ start_pos (int): Starting position in the sequence.
737
+ freqs_cis (torch.Tensor): Precomputed complex exponential values for rotary embeddings.
738
+ mask (Optional[torch.Tensor]): Mask tensor to exclude certain positions from attention.
739
+
740
+ Returns:
741
+ torch.Tensor: Output tensor after block computation.
742
+ """
743
+ if residual is None:
744
+ x, residual = self.attn_norm(x), x
745
+ else:
746
+ x, residual = self.attn_norm(x, residual)
747
+ x = self.attn(x, start_pos, freqs_cis, mask)
748
+ x, residual = self.ffn_norm(x, residual)
749
+ x = self.ffn(x)
750
+ return x, residual
751
+
752
+
753
+ class Transformer(nn.Module):
754
+ """
755
+ Transformer model with positional embeddings, multiple layers, and output projection.
756
+
757
+ Attributes:
758
+ max_seq_len (int): Maximum sequence length for the transformer.
759
+ embed (nn.Module): Embedding layer for input tokens.
760
+ layers (torch.nn.ModuleList): List of transformer blocks.
761
+ norm (nn.Module): Layer normalization applied after all blocks.
762
+ head (nn.Module): Output projection layer mapping to vocabulary size.
763
+ freqs_cis (torch.Tensor): Precomputed complex exponential values for rotary embeddings.
764
+ """
765
+ def __init__(self, args: ModelArgs):
766
+ """
767
+ Initializes the Transformer model.
768
+
769
+ Args:
770
+ args (ModelArgs): Model arguments containing transformer parameters.
771
+ """
772
+ global world_size, rank
773
+ world_size = dist.get_world_size() if dist.is_initialized() else 1
774
+ rank = dist.get_rank() if dist.is_initialized() else 0
775
+ Linear.dtype = torch.float8_e4m3fn if args.dtype == "fp8" else torch.bfloat16
776
+ Linear.scale_fmt = args.scale_fmt
777
+ super().__init__()
778
+ self.max_seq_len = args.max_seq_len
779
+ self.embed = ParallelEmbedding(args.vocab_size, args.dim)
780
+ self.layers = torch.nn.ModuleList()
781
+ for layer_id in range(args.n_layers):
782
+ self.layers.append(Block(layer_id, args))
783
+ self.norm = RMSNorm(args.dim)
784
+ # lm_head in the checkpoint is stored in bf16, while the parameter here is stored in fp32 for easier computation of logits later.
785
+ self.head = ColumnParallelLinear(args.dim, args.vocab_size, dtype=torch.float32)
786
+ self.register_buffer("freqs_cis", precompute_freqs_cis(args), persistent=False)
787
+
788
+ @torch.inference_mode()
789
+ def forward(self, tokens: torch.Tensor, start_pos: int = 0):
790
+ """
791
+ Forward pass for the Transformer model.
792
+
793
+ Args:
794
+ tokens (torch.Tensor): Input tensor of token IDs with shape (batch_size, seq_len).
795
+ start_pos (int, optional): Starting position in the sequence for rotary embeddings. Defaults to 0.
796
+
797
+ Returns:
798
+ torch.Tensor: Logits tensor of shape (batch_size, vocab_size).
799
+ """
800
+ seqlen = tokens.size(1)
801
+ freqs_cis = self.freqs_cis[start_pos:start_pos+seqlen]
802
+ mask = torch.full((seqlen, seqlen), float("-inf"), device=tokens.device).triu_(1) if seqlen > 1 else None
803
+ h, residual = self.embed(tokens), None
804
+ for layer in self.layers:
805
+ h, residual = layer(h, residual, start_pos, freqs_cis, mask)
806
+ h, _ = self.norm(h, residual)
807
+ logits = self.head(h[:, -1].float())
808
+ if world_size > 1:
809
+ all_logits = [torch.empty_like(logits) for _ in range(world_size)]
810
+ dist.all_gather(all_logits, logits)
811
+ logits = torch.cat(all_logits, dim=-1)
812
+ return logits
813
+
814
+
815
+ if __name__ == "__main__":
816
+ torch.set_default_dtype(torch.bfloat16)
817
+ torch.set_default_device("cuda")
818
+ torch.manual_seed(0)
819
+ args = ModelArgs()
820
+ x = torch.randint(0, args.vocab_size, (2, 128))
821
+ model = Transformer(args)
822
+ print(model(x).size())
inference/requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ torch
2
+ transformers
3
+ safetensors
4
+ tilelang==0.1.6.post1
model-00001-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:88f278de3e805ce459b9d547967bfaad66392141fe2f585e033e6afbf6e2341f
3
+ size 5236471336
model-00002-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2567ed9d1ca588199b3cf017879503dc28e5c6f32a87530a6acf7487717a6406
3
+ size 4305737040
model-00003-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f0043999b2f089d36d0de86576b23f8e1f5dc18db3df0a2c55b43c9073f1b3c
3
+ size 4305737448
model-00004-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:00144405cc83b3a4727863ae1845d1d7179e1bb34446caedb3dcee13f801046e
3
+ size 4305794312
model-00005-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fe3252d9afd8d217a52ff3859c7c267c2834dc2e9fe0e306fa90fb5c18b10a07
3
+ size 4305737224
model-00006-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:acd94f3598358fc3c96ad7cdee682a32c518060f704e3e37ede02a0f9b39b76e
3
+ size 4375606944
model-00007-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0f5e4e47cc765b1f66d2d58d3d96eefffa2291ed47281eb444a7caaa4d425292
3
+ size 4309387600
model-00008-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3a46a623d6bef2148ce990bb109e2a07518f81472d67510a2bf9dd74dab93680
3
+ size 4305737432
model-00009-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5d2e9406dae73dc90343b601754cb5d4e9da84b806c1a0af7cf3f1e6e3a0e1f8
3
+ size 4305794504
model-00010-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e127ce1a541df3793ecabb3909c3e42bd460fa1d0eb6c968db9221c37faa1499
3
+ size 4305737032
model-00011-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0787d9d8e33b2d2a0a72ee5226f3bd70860b3dd27f1fd34d11734e4750830f19
3
+ size 4305737448
model-00012-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:24ed97a0a7b9fc19f07353fbae7746bdbec905da8f77f447ad1f98849214ed1b
3
+ size 1322636744
model-00013-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5ee61b3614f50591664ba5d73c6f0394dcad3b5648708db949c46e269c474bda
3
+ size 4305736576
model-00014-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7a30a628fc1a78b0bf69710aafabcfc8c99ea701a9c56fb3a4acae9775da6343
3
+ size 4305737400
model-00015-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c4d1f11263c2e3674bf682c3068721cfea2e290684ef355295a39b2ffdeb15f3
3
+ size 4305794536
model-00016-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:db2e22489c71d71e97e5a5774a83e237c5dddf8a9210849c504d96209562e306
3
+ size 4305737008
model-00017-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cf8800936ec152d875819999bf0f319f781acb47fde8dd5dbfd28a992ecd3704
3
+ size 4305716968
model-00018-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d512152a6dac80e16166cf1de0a688ee952f1e765cfa2c4f00c773832c6b11a0
3
+ size 4305814824
model-00019-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:07ba25679187a56c5c68827c7de2fa5712bd87b5bb9d0dcd15c28a5c57dd0a40
3
+ size 4305716712
model-00020-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c20477a8fb65d018dd89750c05e227b5a5fa06adff904ca83e701520985ea32e
3
+ size 4305737456
model-00021-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1a63b9174e86d2bf2a10ced5a4a823b97412fd4a0ab7d8b59139a33cc3e1980e
3
+ size 4305794704
model-00022-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7a358baa289fd92ba6f58b63a1a03d7deddc1535eb89dbfd5353356da777ca25
3
+ size 4305737976
model-00023-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d73afabe03ce8efaba72777ee8a07a5c24c651c9e113690c43c0ec601c05cce4
3
+ size 4305795128
model-00024-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2c6dddfbd18e187b9935a9975d63ad6069bf003e9e3d567400aa50365363c781
3
+ size 4305737584
model-00025-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:296cdf0e465e9857a3429ddeef59b24ae4392782ae25817160398f5a6376ec70
3
+ size 4305738040
model-00026-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e6da7c6acb79496e8f93a24e29b0bd69b4cf1ec9efb236f309e20547830056ad
3
+ size 4305794936
model-00027-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:94a47bd64827df8684bf5341c7babb6d917cfeb94f10d3838fbe1a5171d7d099
3
+ size 4305737768
model-00028-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6a3f71783cc8b36ff64b8c4bccf94f7d9b617e2c82073a4747e54e61505875e1
3
+ size 4305717552
model-00029-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6a1a03d1d46df4dd81a35342d66a9cb0e09a79627e7e41f3cb76fb862ca1aff9
3
+ size 4305815232
model-00030-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:62523bb435a36d5de676fb8dc35213f5d7c348770f16168e8b8490cce6dd8555
3
+ size 4305717472
model-00031-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8bade24cebdf8f06a8abf306f5f289f9a6cb9297472b1b45ce2ca7eb92e455e0
3
+ size 4305815624
model-00032-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e338a4f6ad84b8936a2ef1c85d2f5cf343b95f7532d3ae6a7f1ab088d78763a
3
+ size 4305717080
model-00033-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8fa8bbdfc5fe0dd3f226c2404441924c0485178074578aa63a2957ef45ff8897
3
+ size 4305738048
model-00034-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fbda233955bbfdc65cc7f59957407aec8314588a14fd036cd3e630c5883fca52
3
+ size 1748808304
model-00035-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c540e6bc1cbdf540a5f11f48f8b72634ed6fce85a989a9c45c9c6fa542341a89
3
+ size 4305737144
model-00036-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cc2c92f763a758db0622bce969e4c0129d34834dbc833fcfd6ad5c356c12b942
3
+ size 4305737984
model-00037-of-000163.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ad71f1bcb01a96ea8723b54de42f53a98eaed5ec877ded909f865b35622721df
3
+ size 4305795112