agupta-sarvam commited on
Commit
417cf26
·
0 Parent(s):

Sarvam-Prism release

Browse files
.gitattributes ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip 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
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
37
+ assets/sarvam-prism.avif filter=lfs diff=lfs merge=lfs -text
38
+ assets/sarvam-prism.png filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ pipeline_tag: text-classification
4
+ language:
5
+ - en
6
+ - hi
7
+ - bn
8
+ - ta
9
+ - te
10
+ - mr
11
+ - gu
12
+ - kn
13
+ - ml
14
+ - or
15
+ - pa
16
+ tags:
17
+ - decision-model
18
+ - classification
19
+ - calibration
20
+ ---
21
+
22
+ # Sarvam-Prism
23
+
24
+ <p align="center"><img src="assets/sarvam-prism.png" alt="A glass prism splitting a beam of light into a spectrum, framed by carved stone arches" width="720"></p>
25
+
26
+ Sarvam-Prism is a decision model built on Sarvam-105B. You give it a context and one or more questions, each with a
27
+ fixed set of possible answers. It returns a probability for every answer in a single forward pass. It does not
28
+ generate text, so the answer is always one of your options.
29
+
30
+ **Release blog:** [sarvam.ai/blogs/sarvam-prism](https://www.sarvam.ai/blogs/sarvam-prism): evaluation results, comparisons with other
31
+ decision models, calibration, and how the model was built and made fast.
32
+
33
+ **API:** Sarvam-Prism is also available as a hosted API from Sarvam, with no GPU needed: see the
34
+ [API documentation](https://docs.sarvam.ai/api/token-factory/models/sarvam-prism).
35
+
36
+ ## Requirements
37
+
38
+ - One NVIDIA GPU with FP8 support and about 120 GB of free memory, such as a B200 or H200. Tested on B200.
39
+ - Python 3.10+ and a C compiler (Triton builds its kernels on first use).
40
+ - About 106 GB of disk for the weights.
41
+
42
+ ## Quick start
43
+
44
+ **1. Download the model and code:**
45
+
46
+ ```bash
47
+ pip install -U huggingface_hub
48
+ huggingface-cli download sarvamai/prism --local-dir sarvam-prism
49
+ cd sarvam-prism
50
+ ```
51
+
52
+ **2. Install the dependencies:**
53
+
54
+ ```bash
55
+ pip install -r requirements.txt
56
+ ```
57
+
58
+ **3. Run the example:**
59
+
60
+ ```bash
61
+ python example.py .
62
+ ```
63
+
64
+ Loading takes about two minutes on a B200 (Triton compiles its kernels the first time, then CUDA graphs are captured). It prints the
65
+ answers to the request below.
66
+
67
+ **Use it from Python** (run from the `sarvam-prism` folder, or put it on your `PYTHONPATH`):
68
+
69
+ ```python
70
+ from prism import Prism
71
+
72
+ model = Prism.from_pretrained(".") # the downloaded folder; loads on cuda:0
73
+
74
+ answers = model.decide(
75
+ state={"ticket": "My card was charged twice for the same order and I still haven't got a refund."},
76
+ questions={
77
+ "team": {"type": "choice", "instructions": "Which team should handle this ticket?",
78
+ "criteria": {"billing": "payments, charges and refunds",
79
+ "tech": "app or website problems",
80
+ "delivery": "shipping and order status"}},
81
+ "urgent": {"type": "yes_no", "instructions": "Does this need a reply within the hour?"},
82
+ "anger": {"type": "score", "instructions": "How upset is the customer?",
83
+ "criteria": ["calm", "annoyed", "angry", "furious"]},
84
+ },
85
+ )
86
+ ```
87
+
88
+ The output has one entry per question:
89
+
90
+ ```python
91
+ {
92
+ "team": {"type": "choice", "choice": "billing",
93
+ "probabilities": {"billing": 0.986, "delivery": 0.006, "tech": 0.007}},
94
+ "urgent": {"type": "yes_no", "yes": 0.45},
95
+ "anger": {"type": "score", "score": 1.86, "level": "2",
96
+ "probabilities": {"0": 0.032, "1": 0.267, "2": 0.510, "3": 0.191}}
97
+ }
98
+ ```
99
+
100
+ `Prism.from_pretrained("sarvamai/prism")` also accepts the repo id and downloads the weights into the Hugging Face
101
+ cache on first use (you still need `prism.py` from this repository).
102
+
103
+ Load the model with `prism.py` as shown. The weights are stored in a custom FP8 layout for this code, so they cannot be
104
+ loaded with `AutoModelForCausalLM` or served by general-purpose inference servers.
105
+
106
+ ## Speed
107
+
108
+ Median 44 ms per request (95th percentile 420 ms) on one NVIDIA B200, measured on 1,000 random requests from the
109
+ public Decision Index benchmark, sent one at a time after loading. All questions in a request are scored together.
110
+
111
+ ## Request format
112
+
113
+ - **`state`**: the context to decide about. Any text or JSON-serialisable value; JSON is rendered compactly.
114
+ - **`questions`**: a map from your question names to questions. Each question has:
115
+ - **`type`**: one of the three below.
116
+ - **`instructions`**: what to decide, in plain language.
117
+ - **`criteria`**: the possible answers.
118
+
119
+ | type | `criteria` | output |
120
+ |---|---|---|
121
+ | `choice` | `{key: description}`; the description may be `null` | `choice` (most likely key) and `probabilities` per key |
122
+ | `yes_no` | none | `yes`: probability of yes |
123
+ | `score` | a list of ordered levels, or an ordered `{key: level}` map | `score` (expected level index), `level` (most likely key) and `probabilities` per key; for a list, the keys are the level indices `"0"`, `"1"`, … |
124
+
125
+ All questions in a request are scored together, in batches of up to `batch_size` (default 16, set in
126
+ `from_pretrained`), and each question is scored independently of the others. Choice options are scored in a fixed order
127
+ (sorted by key), so the same options always give the same answer, whatever order you send them in. The context limit is
128
+ 131,072 tokens per question.
129
+
130
+ Loading captures CUDA graphs for common batch sizes and lengths, which takes a few minutes and makes most requests much
131
+ faster; pass `cuda_graphs=False` to skip it.
132
+
133
+ ## How it works
134
+
135
+ Each question becomes one sequence: the state, the instructions, and every option, followed by an answer marker. Every
136
+ option starts at the same position and cannot see the other options; only the answer marker sees all of them. A small
137
+ decision head reads the hidden state at the end of each option and at the answer marker, and turns them into one
138
+ probability per option. `prism.py` contains the full inference code: the input encoding, the attention mask, the
139
+ decision head, two small changes to the base model's attention for this mask, and the FP8 kernels.
140
+
141
+ The weights are stored in FP8 (float8_e4m3fn) with one scale per output row; activations are scaled per token at run
142
+ time. The 128 routed experts of each layer run as two grouped FP8 matrix multiplications (a Triton kernel), and the
143
+ other projections use `torch._scaled_mm`. Embeddings and norms are bf16, and the MoE router is fp32.
144
+
145
+ ## Files
146
+
147
+ | file | contents |
148
+ |---|---|
149
+ | `model-*.safetensors`, `config.json`, `*_sarvam_moe.py` | the fine-tuned Sarvam-105B backbone in FP8 (one file per layer) |
150
+ | `decision_head.safetensors` | the decision head and segment embedding |
151
+ | `tokenizer*.json`, `special_tokens_map.json` | tokenizer |
152
+ | `prism.py`, `example.py`, `requirements.txt` | inference code |
153
+ | `LICENSE` | Apache License 2.0 |
154
+
155
+ ## License
156
+
157
+ Apache 2.0 (see `LICENSE`).
assets/sarvam-prism.png ADDED

Git LFS Details

  • SHA256: aed1306570d04220db70c3edd53a5cf3296a0f9a02e5b42758e6a2870091fe34
  • Pointer size: 132 Bytes
  • Size of remote file: 2.41 MB
config.json ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "SarvamMLAForCausalLM"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "attn_implementation": null,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_sarvam_moe.SarvamMLAConfig",
9
+ "AutoModel": "modeling_sarvam_moe.SarvamMLAModel",
10
+ "AutoModelForCausalLM": "modeling_sarvam_moe.SarvamMLAForCausalLM"
11
+ },
12
+ "default_theta": 10000.0,
13
+ "dtype": "bfloat16",
14
+ "embedding_dropout": 0.0,
15
+ "eos_token_id": 1,
16
+ "first_k_dense_replace": 1,
17
+ "head_dim": 576,
18
+ "hidden_act": "silu",
19
+ "hidden_size": 4096,
20
+ "initializer_range": 0.006,
21
+ "intermediate_size": 16384,
22
+ "kv_lora_rank": 512,
23
+ "max_position_embeddings": 131072,
24
+ "model_type": "sarvam_mla",
25
+ "moe_intermediate_size": 2048,
26
+ "moe_router_enable_expert_bias": true,
27
+ "num_attention_heads": 64,
28
+ "num_experts": 128,
29
+ "num_experts_per_tok": 8,
30
+ "num_hidden_layers": 32,
31
+ "num_shared_experts": 1,
32
+ "output_dropout": 0.0,
33
+ "output_router_logits": false,
34
+ "pad_token_id": 0,
35
+ "q_head_dim": 192,
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": "deepseek_yarn"
47
+ },
48
+ "rope_theta": 10000.0,
49
+ "routed_scaling_factor": 2.5,
50
+ "tie_word_embeddings": false,
51
+ "transformers_version": "4.57.2",
52
+ "use_cache": false,
53
+ "use_qk_norm": true,
54
+ "v_head_dim": 128,
55
+ "vocab_size": 262144,
56
+ "torch_dtype": "bfloat16",
57
+ "quantization": {
58
+ "format": "float8_e4m3fn",
59
+ "weight_scale": "per output row (absmax / 448)",
60
+ "activations": "per token, dynamic"
61
+ }
62
+ }
configuration_sarvam_moe.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.configuration_utils import PretrainedConfig
2
+
3
+
4
+ class SarvamMLAConfig(PretrainedConfig):
5
+ model_type = "sarvam_mla"
6
+
7
+ base_model_pp_plan = {
8
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
9
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
10
+ "norm": (["hidden_states"], ["hidden_states"]),
11
+ }
12
+
13
+ base_model_tp_plan = {
14
+ "layers.*.self_attn.q_proj": "colwise",
15
+ "layers.*.self_attn.kv_b_proj": "colwise",
16
+ "layers.*.self_attn.o_proj": "rowwise",
17
+ }
18
+
19
+ def __init__(
20
+ self,
21
+ vocab_size: int = 262144,
22
+ hidden_size: int = 4096,
23
+ num_hidden_layers: int = 32,
24
+ intermediate_size: int = 16384,
25
+ moe_intermediate_size: int = 2048,
26
+ num_experts: int = 128,
27
+ num_experts_per_tok: int = 8,
28
+ num_shared_experts: int = 1,
29
+ first_k_dense_replace: int = 1,
30
+ num_attention_heads: int = 64,
31
+ qk_rope_head_dim: int = 64,
32
+ qk_nope_head_dim: int = 128,
33
+ kv_lora_rank: int = 512,
34
+ v_head_dim: int = 128,
35
+ max_position_embeddings: int = 4096,
36
+ rope_theta: float = 10000.0,
37
+ rope_scaling: dict = None,
38
+ attention_dropout: float = 0.0,
39
+ output_dropout: float = 0.0,
40
+ rms_norm_eps: float = 1e-6,
41
+ hidden_act: str = "silu",
42
+ use_cache: bool = True,
43
+ use_qk_norm: bool = True,
44
+ moe_router_enable_expert_bias: bool = True,
45
+ routed_scaling_factor: float = 2.5,
46
+ output_router_logits: bool = False,
47
+ tie_word_embeddings: bool = False,
48
+ pad_token_id: int = 0,
49
+ eos_token_id: int = 1,
50
+ embedding_dropout: float = 0.0,
51
+ initializer_range: float = 0.006,
52
+ attn_implementation: str = "eager",
53
+ **kwargs,
54
+ ):
55
+ # core geometry
56
+ self.vocab_size = vocab_size
57
+ self.hidden_size = hidden_size
58
+ self.num_hidden_layers = num_hidden_layers
59
+ self.intermediate_size = intermediate_size
60
+ self.num_attention_heads = num_attention_heads
61
+ self.max_position_embeddings = max_position_embeddings
62
+
63
+ # MLA geometry
64
+ self.qk_rope_head_dim = qk_rope_head_dim
65
+ self.qk_nope_head_dim = qk_nope_head_dim
66
+ self.kv_lora_rank = kv_lora_rank
67
+ self.v_head_dim = v_head_dim
68
+ # convenient derived dim
69
+ self.q_head_dim = qk_rope_head_dim + qk_nope_head_dim
70
+ # vLLM MLA expects "head size" = Lkv + R, not hidden_size/num_heads.
71
+ self.head_dim = int(self.kv_lora_rank + self.qk_rope_head_dim)
72
+
73
+ # MoE
74
+ self.moe_intermediate_size = moe_intermediate_size
75
+ self.num_experts = num_experts
76
+ self.num_experts_per_tok = num_experts_per_tok
77
+ self.num_shared_experts = num_shared_experts
78
+ self.first_k_dense_replace = first_k_dense_replace
79
+
80
+ # Router
81
+ self.moe_router_enable_expert_bias = moe_router_enable_expert_bias
82
+ self.routed_scaling_factor = routed_scaling_factor
83
+ self.output_router_logits = output_router_logits
84
+
85
+ # dropouts / norms / init
86
+ self.attention_dropout = attention_dropout
87
+ self.output_dropout = output_dropout
88
+ self.embedding_dropout = embedding_dropout
89
+ self.rms_norm_eps = rms_norm_eps
90
+ self.initializer_range = initializer_range
91
+ self.hidden_act = hidden_act
92
+
93
+ # rope / cache
94
+ self.rope_theta = rope_theta
95
+ self.use_cache = use_cache
96
+ self.use_qk_norm = use_qk_norm
97
+ self.rope_scaling = rope_scaling
98
+ self.default_theta = 10000.0
99
+
100
+ if self.rope_scaling is None:
101
+ self.rope_scaling = {
102
+ 'beta_fast': 32,
103
+ 'beta_slow': 1,
104
+ 'factor': 40,
105
+ 'mscale': 1.0,
106
+ 'mscale_all_dim': 1.0,
107
+ 'original_max_position_embeddings': 4096,
108
+ 'rope_type': 'deepseek_yarn',
109
+ }
110
+
111
+ self.attn_implementation = attn_implementation
112
+ self._attn_implementation = attn_implementation
113
+
114
+ if "_attn_implementation" in kwargs:
115
+ self._attn_implementation = kwargs.pop("_attn_implementation")
116
+ if hasattr(self, "attn_implementation"):
117
+ self.attn_implementation = self._attn_implementation
118
+
119
+ super().__init__(
120
+ pad_token_id=pad_token_id,
121
+ eos_token_id=eos_token_id,
122
+ tie_word_embeddings=tie_word_embeddings,
123
+ **kwargs,
124
+ )
125
+
126
+ def convert_rope_params_to_dict(self, ignore_keys_at_rope_validation: set | None = None, **kwargs):
127
+ rope_scaling = kwargs.pop("rope_scaling", None)
128
+ self.rope_parameters = rope_scaling or self.rope_parameters
129
+ self.rope_parameters = self.rope_parameters if self.rope_parameters is not None else {}
130
+
131
+ # Standardize and validate the correctness of rotary position embeddings parameters
132
+ self.rope_parameters.setdefault("rope_theta", kwargs.pop("rope_theta", self.default_theta))
133
+ self.standardize_rope_params()
134
+ self.validate_rope(ignore_keys=ignore_keys_at_rope_validation)
135
+
136
+ # Convert to float because RoPE fn expect a float. Models on the hub were saved as int
137
+ for key in ["beta_fast", "beta_slow", "factor"]:
138
+ if key in self.rope_parameters:
139
+ self.rope_parameters[key] = float(self.rope_parameters[key])
140
+ return kwargs
decision_head.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a84038851eafcf30ddd086f331fcda944fa8cb1b5a9aa780c078c3f6c5b5df10
3
+ size 117841696
example.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run one request through Sarvam-Prism. Downloads the model (~106 GB) on first use when given the repo id.
2
+ python example.py # from the Hugging Face Hub
3
+ python example.py /path/to/sarvam-prism # from a local copy
4
+ """
5
+ import json, sys
6
+ from prism import Prism
7
+
8
+ model = Prism.from_pretrained(sys.argv[1] if len(sys.argv) > 1 else "sarvamai/prism")
9
+ answers = model.decide(
10
+ state={"ticket": "My card was charged twice for the same order and I still haven't got a refund."},
11
+ questions={
12
+ "team": {"type": "choice", "instructions": "Which team should handle this ticket?",
13
+ "criteria": {"billing": "payments, charges and refunds", "tech": "app or website problems",
14
+ "delivery": "shipping and order status"}},
15
+ "urgent": {"type": "yes_no", "instructions": "Does this need a reply within the hour?"},
16
+ "anger": {"type": "score", "instructions": "How upset is the customer?",
17
+ "criteria": ["calm", "annoyed", "angry", "furious"]},
18
+ })
19
+ print(json.dumps(answers, indent=2))
model-embed.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5c1e74d14913aa92d5e66728229976f3a0532393118ec4ace49cc16eeaf79ed0
3
+ size 2147492072
model-layer-00.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6b5b39439385eb5912b2ee14d1451ef269340cf1f2125386e941b3a9b6db896c
3
+ size 296260776
model-layer-01.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8abbaad710dd8239097ae033117fac374547de30e00d0ef77ea55a9ee7ef0173
3
+ size 3347503576
model-layer-02.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:53350d52337b19eaab77b4909f8a5aaeff40803831132941dadc728b2227cb16
3
+ size 3347503576
model-layer-03.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ef760139b7c17a467bb6e51e856dfb4e4d127e58104a33da2c77f3bfc5bb4ffe
3
+ size 3347503576
model-layer-04.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a97952e44757024f7e5371dcd22c265ddbda114b01949e285ebaf6da7843e0e6
3
+ size 3347503576
model-layer-05.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:61079ad4bbea56e516a5a14eb2d688a15f0235b0b2274c41487687bf481e0046
3
+ size 3347503576
model-layer-06.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:982e7417c6d7e995bc12d2e4da969df4e2886ecabbd089f6d6c593094dc5f5f6
3
+ size 3347503576
model-layer-07.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:95efd4afef99db19ba00fae411f1ac80e0d11faedde5e4eb5fcb273ba2ab31ef
3
+ size 3347503576
model-layer-08.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7b6c93f59f8b68b00c3f6c98e671685293fa828ba905b04bc44ad3dd7ea9879f
3
+ size 3347503576
model-layer-09.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2aaa9b4b0f55ad6f048529bd0eee36e8f54a544a16451e2d1bb40c4dae8ad3cd
3
+ size 3347503576
model-layer-10.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:26d75c332c71ba4a56653fde28263bdaf440deff4a5baa466fff98d8870bab28
3
+ size 3347503592
model-layer-11.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ae1d37a8122132cca67c88b322470df5aa76056e4aa2bd9c16dbe161fa1f8d35
3
+ size 3347503592
model-layer-12.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e1eee905e3f67eefe1b597e0e2a13f9a2dbb8a95a16e18aad69086b4b76247a7
3
+ size 3347503592
model-layer-13.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3c89161ba38bd8e8bb311a90e7b6327e637dfead5286badf93ee82e1cc38873c
3
+ size 3347503592
model-layer-14.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2fdbdbf1fb9813b1fc2d79981efa7ed904bc018a141f176912a50f863f12c5b6
3
+ size 3347503592
model-layer-15.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b93ab8a07be98042f3ad4bb979ba24c4d290adc16d7b3e58094d950d64d7b2f5
3
+ size 3347503592
model-layer-16.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:07d2e166037b388cfe5ff944ec4196da1d9aeb1a6c0a63e8b44534779d2ba2ac
3
+ size 3347503592
model-layer-17.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:354ae9a5b9e6754dd7a9444319b5e551779fb02329383009a3e5877410ea8cd8
3
+ size 3347503592
model-layer-18.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1a3845ae7b81fe2f3b2af3c8567f8140c758c36a3abb0328ccae65ccb7529fb5
3
+ size 3347503592
model-layer-19.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:96f00baecc8436e90fda6d0895585b2be844e0cb0895d0026e80a545fbb03be6
3
+ size 3347503592
model-layer-20.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2099d6730997ddbc863ecf2e6d8738a0f24aed9e97aefbb589293e79f273efa9
3
+ size 3347503592
model-layer-21.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:51368a73a93e57a1009a4f39410c9391154e7115781dc5065d170fbab4bfb72b
3
+ size 3347503592
model-layer-22.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e7dd3c030debf4960254b91116056dd359bf30041b15fc01b69634a7c13e04e7
3
+ size 3347503592
model-layer-23.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f3f5a2651814f94b9322dfe6625260fc10b5017af0309f425c38ddf715aaf18
3
+ size 3347503592
model-layer-24.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5200bdfd0eca3f531a2bc3f2f5359d819228bca1aeee0df03f565ae2932b45c5
3
+ size 3347503592
model-layer-25.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:78a945d90832e94174545666f5b435c232e9c1b692b6f4ec83e7e1f5f5b437d8
3
+ size 3347503592
model-layer-26.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:26f70dcd78cb3dc51f8259be70b124bc85ed60d3c4b8949e638620c00a5523a4
3
+ size 3347503592
model-layer-27.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6861179c12fe1bd64a5c7cd7e362250279e12e242735dc0f7b857a8e548983bc
3
+ size 3347503592
model-layer-28.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:040333d802be804435ff5e244ea0eee80bf998558b0df39a4af2f54e90436333
3
+ size 3347503592
model-layer-29.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6684cf69e0d81130eb14175d2e122f092258016e67b1f63862ac77aa64179e4e
3
+ size 3347503592
model-layer-30.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:889ec213ad37712701bc0565d5c0a9d619975b9a8f9b3c59771d1bd8cf93f854
3
+ size 3347503592
model-layer-31.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dccc1b4a47866ea33410f381e5f8acf8fec90fa07f4506a8c185b1737a173e6d
3
+ size 3347503592
model.safetensors.index.json ADDED
@@ -0,0 +1,739 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 106216275456
4
+ },
5
+ "weight_map": {
6
+ "model.norm.weight": "model-embed.safetensors",
7
+ "model.embed_tokens.weight": "model-embed.safetensors",
8
+ "model.layers.0.mlp.gate_proj.weight": "model-layer-00.safetensors",
9
+ "model.layers.0.mlp.gate_proj.weight_scale": "model-layer-00.safetensors",
10
+ "model.layers.0.post_attention_layernorm.weight": "model-layer-00.safetensors",
11
+ "model.layers.0.mlp.down_proj.weight": "model-layer-00.safetensors",
12
+ "model.layers.0.mlp.down_proj.weight_scale": "model-layer-00.safetensors",
13
+ "model.layers.0.self_attn.kv_a_proj_with_mqa.weight": "model-layer-00.safetensors",
14
+ "model.layers.0.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-00.safetensors",
15
+ "model.layers.0.self_attn.kv_b_proj.weight": "model-layer-00.safetensors",
16
+ "model.layers.0.self_attn.kv_b_proj.weight_scale": "model-layer-00.safetensors",
17
+ "model.layers.0.self_attn.q_proj.weight": "model-layer-00.safetensors",
18
+ "model.layers.0.self_attn.q_proj.weight_scale": "model-layer-00.safetensors",
19
+ "model.layers.0.mlp.up_proj.weight": "model-layer-00.safetensors",
20
+ "model.layers.0.mlp.up_proj.weight_scale": "model-layer-00.safetensors",
21
+ "model.layers.0.self_attn.o_proj.weight": "model-layer-00.safetensors",
22
+ "model.layers.0.self_attn.o_proj.weight_scale": "model-layer-00.safetensors",
23
+ "model.layers.0.input_layernorm.weight": "model-layer-00.safetensors",
24
+ "model.layers.0.self_attn.kv_a_layernorm.weight": "model-layer-00.safetensors",
25
+ "model.layers.1.mlp.gate.weight": "model-layer-01.safetensors",
26
+ "model.layers.1.self_attn.o_proj.weight": "model-layer-01.safetensors",
27
+ "model.layers.1.self_attn.o_proj.weight_scale": "model-layer-01.safetensors",
28
+ "model.layers.1.self_attn.q_proj.weight": "model-layer-01.safetensors",
29
+ "model.layers.1.self_attn.q_proj.weight_scale": "model-layer-01.safetensors",
30
+ "model.layers.1.self_attn.kv_a_proj_with_mqa.weight": "model-layer-01.safetensors",
31
+ "model.layers.1.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-01.safetensors",
32
+ "model.layers.1.mlp.shared_experts.gate_proj.weight": "model-layer-01.safetensors",
33
+ "model.layers.1.mlp.shared_experts.gate_proj.weight_scale": "model-layer-01.safetensors",
34
+ "model.layers.1.mlp.gate.e_score_correction_bias": "model-layer-01.safetensors",
35
+ "model.layers.1.self_attn.kv_b_proj.weight": "model-layer-01.safetensors",
36
+ "model.layers.1.self_attn.kv_b_proj.weight_scale": "model-layer-01.safetensors",
37
+ "model.layers.1.mlp.shared_experts.down_proj.weight": "model-layer-01.safetensors",
38
+ "model.layers.1.mlp.shared_experts.down_proj.weight_scale": "model-layer-01.safetensors",
39
+ "model.layers.1.self_attn.kv_a_layernorm.weight": "model-layer-01.safetensors",
40
+ "model.layers.1.mlp.shared_experts.up_proj.weight": "model-layer-01.safetensors",
41
+ "model.layers.1.mlp.shared_experts.up_proj.weight_scale": "model-layer-01.safetensors",
42
+ "model.layers.1.post_attention_layernorm.weight": "model-layer-01.safetensors",
43
+ "model.layers.1.input_layernorm.weight": "model-layer-01.safetensors",
44
+ "model.layers.1.mlp.experts.gate_up_proj": "model-layer-01.safetensors",
45
+ "model.layers.1.mlp.experts.gate_up_proj_scale": "model-layer-01.safetensors",
46
+ "model.layers.1.mlp.experts.down_proj": "model-layer-01.safetensors",
47
+ "model.layers.1.mlp.experts.down_proj_scale": "model-layer-01.safetensors",
48
+ "model.layers.2.self_attn.kv_a_proj_with_mqa.weight": "model-layer-02.safetensors",
49
+ "model.layers.2.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-02.safetensors",
50
+ "model.layers.2.self_attn.o_proj.weight": "model-layer-02.safetensors",
51
+ "model.layers.2.self_attn.o_proj.weight_scale": "model-layer-02.safetensors",
52
+ "model.layers.2.mlp.shared_experts.gate_proj.weight": "model-layer-02.safetensors",
53
+ "model.layers.2.mlp.shared_experts.gate_proj.weight_scale": "model-layer-02.safetensors",
54
+ "model.layers.2.mlp.shared_experts.up_proj.weight": "model-layer-02.safetensors",
55
+ "model.layers.2.mlp.shared_experts.up_proj.weight_scale": "model-layer-02.safetensors",
56
+ "model.layers.2.post_attention_layernorm.weight": "model-layer-02.safetensors",
57
+ "model.layers.2.input_layernorm.weight": "model-layer-02.safetensors",
58
+ "model.layers.2.self_attn.kv_b_proj.weight": "model-layer-02.safetensors",
59
+ "model.layers.2.self_attn.kv_b_proj.weight_scale": "model-layer-02.safetensors",
60
+ "model.layers.2.self_attn.kv_a_layernorm.weight": "model-layer-02.safetensors",
61
+ "model.layers.2.self_attn.q_proj.weight": "model-layer-02.safetensors",
62
+ "model.layers.2.self_attn.q_proj.weight_scale": "model-layer-02.safetensors",
63
+ "model.layers.2.mlp.shared_experts.down_proj.weight": "model-layer-02.safetensors",
64
+ "model.layers.2.mlp.shared_experts.down_proj.weight_scale": "model-layer-02.safetensors",
65
+ "model.layers.2.mlp.gate.weight": "model-layer-02.safetensors",
66
+ "model.layers.2.mlp.gate.e_score_correction_bias": "model-layer-02.safetensors",
67
+ "model.layers.2.mlp.experts.gate_up_proj": "model-layer-02.safetensors",
68
+ "model.layers.2.mlp.experts.gate_up_proj_scale": "model-layer-02.safetensors",
69
+ "model.layers.2.mlp.experts.down_proj": "model-layer-02.safetensors",
70
+ "model.layers.2.mlp.experts.down_proj_scale": "model-layer-02.safetensors",
71
+ "model.layers.3.self_attn.kv_b_proj.weight": "model-layer-03.safetensors",
72
+ "model.layers.3.self_attn.kv_b_proj.weight_scale": "model-layer-03.safetensors",
73
+ "model.layers.3.self_attn.kv_a_proj_with_mqa.weight": "model-layer-03.safetensors",
74
+ "model.layers.3.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-03.safetensors",
75
+ "model.layers.3.post_attention_layernorm.weight": "model-layer-03.safetensors",
76
+ "model.layers.3.self_attn.kv_a_layernorm.weight": "model-layer-03.safetensors",
77
+ "model.layers.3.mlp.gate.weight": "model-layer-03.safetensors",
78
+ "model.layers.3.mlp.shared_experts.gate_proj.weight": "model-layer-03.safetensors",
79
+ "model.layers.3.mlp.shared_experts.gate_proj.weight_scale": "model-layer-03.safetensors",
80
+ "model.layers.3.input_layernorm.weight": "model-layer-03.safetensors",
81
+ "model.layers.3.mlp.shared_experts.up_proj.weight": "model-layer-03.safetensors",
82
+ "model.layers.3.mlp.shared_experts.up_proj.weight_scale": "model-layer-03.safetensors",
83
+ "model.layers.3.self_attn.o_proj.weight": "model-layer-03.safetensors",
84
+ "model.layers.3.self_attn.o_proj.weight_scale": "model-layer-03.safetensors",
85
+ "model.layers.3.self_attn.q_proj.weight": "model-layer-03.safetensors",
86
+ "model.layers.3.self_attn.q_proj.weight_scale": "model-layer-03.safetensors",
87
+ "model.layers.3.mlp.shared_experts.down_proj.weight": "model-layer-03.safetensors",
88
+ "model.layers.3.mlp.shared_experts.down_proj.weight_scale": "model-layer-03.safetensors",
89
+ "model.layers.3.mlp.gate.e_score_correction_bias": "model-layer-03.safetensors",
90
+ "model.layers.3.mlp.experts.gate_up_proj": "model-layer-03.safetensors",
91
+ "model.layers.3.mlp.experts.gate_up_proj_scale": "model-layer-03.safetensors",
92
+ "model.layers.3.mlp.experts.down_proj": "model-layer-03.safetensors",
93
+ "model.layers.3.mlp.experts.down_proj_scale": "model-layer-03.safetensors",
94
+ "model.layers.4.mlp.shared_experts.down_proj.weight": "model-layer-04.safetensors",
95
+ "model.layers.4.mlp.shared_experts.down_proj.weight_scale": "model-layer-04.safetensors",
96
+ "model.layers.4.mlp.shared_experts.up_proj.weight": "model-layer-04.safetensors",
97
+ "model.layers.4.mlp.shared_experts.up_proj.weight_scale": "model-layer-04.safetensors",
98
+ "model.layers.4.mlp.shared_experts.gate_proj.weight": "model-layer-04.safetensors",
99
+ "model.layers.4.mlp.shared_experts.gate_proj.weight_scale": "model-layer-04.safetensors",
100
+ "model.layers.4.self_attn.kv_a_proj_with_mqa.weight": "model-layer-04.safetensors",
101
+ "model.layers.4.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-04.safetensors",
102
+ "model.layers.4.mlp.gate.weight": "model-layer-04.safetensors",
103
+ "model.layers.4.mlp.gate.e_score_correction_bias": "model-layer-04.safetensors",
104
+ "model.layers.4.self_attn.kv_a_layernorm.weight": "model-layer-04.safetensors",
105
+ "model.layers.4.self_attn.o_proj.weight": "model-layer-04.safetensors",
106
+ "model.layers.4.self_attn.o_proj.weight_scale": "model-layer-04.safetensors",
107
+ "model.layers.4.input_layernorm.weight": "model-layer-04.safetensors",
108
+ "model.layers.4.self_attn.kv_b_proj.weight": "model-layer-04.safetensors",
109
+ "model.layers.4.self_attn.kv_b_proj.weight_scale": "model-layer-04.safetensors",
110
+ "model.layers.4.self_attn.q_proj.weight": "model-layer-04.safetensors",
111
+ "model.layers.4.self_attn.q_proj.weight_scale": "model-layer-04.safetensors",
112
+ "model.layers.4.post_attention_layernorm.weight": "model-layer-04.safetensors",
113
+ "model.layers.4.mlp.experts.gate_up_proj": "model-layer-04.safetensors",
114
+ "model.layers.4.mlp.experts.gate_up_proj_scale": "model-layer-04.safetensors",
115
+ "model.layers.4.mlp.experts.down_proj": "model-layer-04.safetensors",
116
+ "model.layers.4.mlp.experts.down_proj_scale": "model-layer-04.safetensors",
117
+ "model.layers.5.mlp.shared_experts.down_proj.weight": "model-layer-05.safetensors",
118
+ "model.layers.5.mlp.shared_experts.down_proj.weight_scale": "model-layer-05.safetensors",
119
+ "model.layers.5.mlp.shared_experts.up_proj.weight": "model-layer-05.safetensors",
120
+ "model.layers.5.mlp.shared_experts.up_proj.weight_scale": "model-layer-05.safetensors",
121
+ "model.layers.5.mlp.gate.weight": "model-layer-05.safetensors",
122
+ "model.layers.5.mlp.gate.e_score_correction_bias": "model-layer-05.safetensors",
123
+ "model.layers.5.self_attn.kv_b_proj.weight": "model-layer-05.safetensors",
124
+ "model.layers.5.self_attn.kv_b_proj.weight_scale": "model-layer-05.safetensors",
125
+ "model.layers.5.input_layernorm.weight": "model-layer-05.safetensors",
126
+ "model.layers.5.self_attn.kv_a_layernorm.weight": "model-layer-05.safetensors",
127
+ "model.layers.5.post_attention_layernorm.weight": "model-layer-05.safetensors",
128
+ "model.layers.5.self_attn.q_proj.weight": "model-layer-05.safetensors",
129
+ "model.layers.5.self_attn.q_proj.weight_scale": "model-layer-05.safetensors",
130
+ "model.layers.5.mlp.shared_experts.gate_proj.weight": "model-layer-05.safetensors",
131
+ "model.layers.5.mlp.shared_experts.gate_proj.weight_scale": "model-layer-05.safetensors",
132
+ "model.layers.5.self_attn.kv_a_proj_with_mqa.weight": "model-layer-05.safetensors",
133
+ "model.layers.5.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-05.safetensors",
134
+ "model.layers.5.self_attn.o_proj.weight": "model-layer-05.safetensors",
135
+ "model.layers.5.self_attn.o_proj.weight_scale": "model-layer-05.safetensors",
136
+ "model.layers.5.mlp.experts.gate_up_proj": "model-layer-05.safetensors",
137
+ "model.layers.5.mlp.experts.gate_up_proj_scale": "model-layer-05.safetensors",
138
+ "model.layers.5.mlp.experts.down_proj": "model-layer-05.safetensors",
139
+ "model.layers.5.mlp.experts.down_proj_scale": "model-layer-05.safetensors",
140
+ "model.layers.6.mlp.shared_experts.down_proj.weight": "model-layer-06.safetensors",
141
+ "model.layers.6.mlp.shared_experts.down_proj.weight_scale": "model-layer-06.safetensors",
142
+ "model.layers.6.self_attn.q_proj.weight": "model-layer-06.safetensors",
143
+ "model.layers.6.self_attn.q_proj.weight_scale": "model-layer-06.safetensors",
144
+ "model.layers.6.post_attention_layernorm.weight": "model-layer-06.safetensors",
145
+ "model.layers.6.self_attn.kv_a_proj_with_mqa.weight": "model-layer-06.safetensors",
146
+ "model.layers.6.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-06.safetensors",
147
+ "model.layers.6.mlp.gate.e_score_correction_bias": "model-layer-06.safetensors",
148
+ "model.layers.6.self_attn.o_proj.weight": "model-layer-06.safetensors",
149
+ "model.layers.6.self_attn.o_proj.weight_scale": "model-layer-06.safetensors",
150
+ "model.layers.6.mlp.shared_experts.up_proj.weight": "model-layer-06.safetensors",
151
+ "model.layers.6.mlp.shared_experts.up_proj.weight_scale": "model-layer-06.safetensors",
152
+ "model.layers.6.self_attn.kv_b_proj.weight": "model-layer-06.safetensors",
153
+ "model.layers.6.self_attn.kv_b_proj.weight_scale": "model-layer-06.safetensors",
154
+ "model.layers.6.input_layernorm.weight": "model-layer-06.safetensors",
155
+ "model.layers.6.self_attn.kv_a_layernorm.weight": "model-layer-06.safetensors",
156
+ "model.layers.6.mlp.shared_experts.gate_proj.weight": "model-layer-06.safetensors",
157
+ "model.layers.6.mlp.shared_experts.gate_proj.weight_scale": "model-layer-06.safetensors",
158
+ "model.layers.6.mlp.gate.weight": "model-layer-06.safetensors",
159
+ "model.layers.6.mlp.experts.gate_up_proj": "model-layer-06.safetensors",
160
+ "model.layers.6.mlp.experts.gate_up_proj_scale": "model-layer-06.safetensors",
161
+ "model.layers.6.mlp.experts.down_proj": "model-layer-06.safetensors",
162
+ "model.layers.6.mlp.experts.down_proj_scale": "model-layer-06.safetensors",
163
+ "model.layers.7.self_attn.q_proj.weight": "model-layer-07.safetensors",
164
+ "model.layers.7.self_attn.q_proj.weight_scale": "model-layer-07.safetensors",
165
+ "model.layers.7.post_attention_layernorm.weight": "model-layer-07.safetensors",
166
+ "model.layers.7.self_attn.kv_a_proj_with_mqa.weight": "model-layer-07.safetensors",
167
+ "model.layers.7.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-07.safetensors",
168
+ "model.layers.7.self_attn.kv_a_layernorm.weight": "model-layer-07.safetensors",
169
+ "model.layers.7.mlp.shared_experts.up_proj.weight": "model-layer-07.safetensors",
170
+ "model.layers.7.mlp.shared_experts.up_proj.weight_scale": "model-layer-07.safetensors",
171
+ "model.layers.7.mlp.shared_experts.down_proj.weight": "model-layer-07.safetensors",
172
+ "model.layers.7.mlp.shared_experts.down_proj.weight_scale": "model-layer-07.safetensors",
173
+ "model.layers.7.mlp.gate.weight": "model-layer-07.safetensors",
174
+ "model.layers.7.self_attn.kv_b_proj.weight": "model-layer-07.safetensors",
175
+ "model.layers.7.self_attn.kv_b_proj.weight_scale": "model-layer-07.safetensors",
176
+ "model.layers.7.mlp.gate.e_score_correction_bias": "model-layer-07.safetensors",
177
+ "model.layers.7.mlp.shared_experts.gate_proj.weight": "model-layer-07.safetensors",
178
+ "model.layers.7.mlp.shared_experts.gate_proj.weight_scale": "model-layer-07.safetensors",
179
+ "model.layers.7.self_attn.o_proj.weight": "model-layer-07.safetensors",
180
+ "model.layers.7.self_attn.o_proj.weight_scale": "model-layer-07.safetensors",
181
+ "model.layers.7.input_layernorm.weight": "model-layer-07.safetensors",
182
+ "model.layers.7.mlp.experts.gate_up_proj": "model-layer-07.safetensors",
183
+ "model.layers.7.mlp.experts.gate_up_proj_scale": "model-layer-07.safetensors",
184
+ "model.layers.7.mlp.experts.down_proj": "model-layer-07.safetensors",
185
+ "model.layers.7.mlp.experts.down_proj_scale": "model-layer-07.safetensors",
186
+ "model.layers.8.self_attn.o_proj.weight": "model-layer-08.safetensors",
187
+ "model.layers.8.self_attn.o_proj.weight_scale": "model-layer-08.safetensors",
188
+ "model.layers.8.input_layernorm.weight": "model-layer-08.safetensors",
189
+ "model.layers.8.mlp.shared_experts.down_proj.weight": "model-layer-08.safetensors",
190
+ "model.layers.8.mlp.shared_experts.down_proj.weight_scale": "model-layer-08.safetensors",
191
+ "model.layers.8.mlp.shared_experts.gate_proj.weight": "model-layer-08.safetensors",
192
+ "model.layers.8.mlp.shared_experts.gate_proj.weight_scale": "model-layer-08.safetensors",
193
+ "model.layers.8.mlp.gate.e_score_correction_bias": "model-layer-08.safetensors",
194
+ "model.layers.8.post_attention_layernorm.weight": "model-layer-08.safetensors",
195
+ "model.layers.8.self_attn.kv_a_layernorm.weight": "model-layer-08.safetensors",
196
+ "model.layers.8.self_attn.kv_b_proj.weight": "model-layer-08.safetensors",
197
+ "model.layers.8.self_attn.kv_b_proj.weight_scale": "model-layer-08.safetensors",
198
+ "model.layers.8.self_attn.kv_a_proj_with_mqa.weight": "model-layer-08.safetensors",
199
+ "model.layers.8.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-08.safetensors",
200
+ "model.layers.8.mlp.gate.weight": "model-layer-08.safetensors",
201
+ "model.layers.8.mlp.shared_experts.up_proj.weight": "model-layer-08.safetensors",
202
+ "model.layers.8.mlp.shared_experts.up_proj.weight_scale": "model-layer-08.safetensors",
203
+ "model.layers.8.self_attn.q_proj.weight": "model-layer-08.safetensors",
204
+ "model.layers.8.self_attn.q_proj.weight_scale": "model-layer-08.safetensors",
205
+ "model.layers.8.mlp.experts.gate_up_proj": "model-layer-08.safetensors",
206
+ "model.layers.8.mlp.experts.gate_up_proj_scale": "model-layer-08.safetensors",
207
+ "model.layers.8.mlp.experts.down_proj": "model-layer-08.safetensors",
208
+ "model.layers.8.mlp.experts.down_proj_scale": "model-layer-08.safetensors",
209
+ "model.layers.9.input_layernorm.weight": "model-layer-09.safetensors",
210
+ "model.layers.9.self_attn.o_proj.weight": "model-layer-09.safetensors",
211
+ "model.layers.9.self_attn.o_proj.weight_scale": "model-layer-09.safetensors",
212
+ "model.layers.9.self_attn.kv_b_proj.weight": "model-layer-09.safetensors",
213
+ "model.layers.9.self_attn.kv_b_proj.weight_scale": "model-layer-09.safetensors",
214
+ "model.layers.9.mlp.shared_experts.up_proj.weight": "model-layer-09.safetensors",
215
+ "model.layers.9.mlp.shared_experts.up_proj.weight_scale": "model-layer-09.safetensors",
216
+ "model.layers.9.post_attention_layernorm.weight": "model-layer-09.safetensors",
217
+ "model.layers.9.self_attn.kv_a_proj_with_mqa.weight": "model-layer-09.safetensors",
218
+ "model.layers.9.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-09.safetensors",
219
+ "model.layers.9.mlp.shared_experts.down_proj.weight": "model-layer-09.safetensors",
220
+ "model.layers.9.mlp.shared_experts.down_proj.weight_scale": "model-layer-09.safetensors",
221
+ "model.layers.9.mlp.gate.weight": "model-layer-09.safetensors",
222
+ "model.layers.9.mlp.gate.e_score_correction_bias": "model-layer-09.safetensors",
223
+ "model.layers.9.self_attn.kv_a_layernorm.weight": "model-layer-09.safetensors",
224
+ "model.layers.9.mlp.shared_experts.gate_proj.weight": "model-layer-09.safetensors",
225
+ "model.layers.9.mlp.shared_experts.gate_proj.weight_scale": "model-layer-09.safetensors",
226
+ "model.layers.9.self_attn.q_proj.weight": "model-layer-09.safetensors",
227
+ "model.layers.9.self_attn.q_proj.weight_scale": "model-layer-09.safetensors",
228
+ "model.layers.9.mlp.experts.gate_up_proj": "model-layer-09.safetensors",
229
+ "model.layers.9.mlp.experts.gate_up_proj_scale": "model-layer-09.safetensors",
230
+ "model.layers.9.mlp.experts.down_proj": "model-layer-09.safetensors",
231
+ "model.layers.9.mlp.experts.down_proj_scale": "model-layer-09.safetensors",
232
+ "model.layers.10.self_attn.kv_b_proj.weight": "model-layer-10.safetensors",
233
+ "model.layers.10.self_attn.kv_b_proj.weight_scale": "model-layer-10.safetensors",
234
+ "model.layers.10.post_attention_layernorm.weight": "model-layer-10.safetensors",
235
+ "model.layers.10.self_attn.q_proj.weight": "model-layer-10.safetensors",
236
+ "model.layers.10.self_attn.q_proj.weight_scale": "model-layer-10.safetensors",
237
+ "model.layers.10.self_attn.kv_a_layernorm.weight": "model-layer-10.safetensors",
238
+ "model.layers.10.self_attn.o_proj.weight": "model-layer-10.safetensors",
239
+ "model.layers.10.self_attn.o_proj.weight_scale": "model-layer-10.safetensors",
240
+ "model.layers.10.mlp.shared_experts.up_proj.weight": "model-layer-10.safetensors",
241
+ "model.layers.10.mlp.shared_experts.up_proj.weight_scale": "model-layer-10.safetensors",
242
+ "model.layers.10.mlp.gate.e_score_correction_bias": "model-layer-10.safetensors",
243
+ "model.layers.10.mlp.gate.weight": "model-layer-10.safetensors",
244
+ "model.layers.10.input_layernorm.weight": "model-layer-10.safetensors",
245
+ "model.layers.10.mlp.shared_experts.gate_proj.weight": "model-layer-10.safetensors",
246
+ "model.layers.10.mlp.shared_experts.gate_proj.weight_scale": "model-layer-10.safetensors",
247
+ "model.layers.10.self_attn.kv_a_proj_with_mqa.weight": "model-layer-10.safetensors",
248
+ "model.layers.10.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-10.safetensors",
249
+ "model.layers.10.mlp.shared_experts.down_proj.weight": "model-layer-10.safetensors",
250
+ "model.layers.10.mlp.shared_experts.down_proj.weight_scale": "model-layer-10.safetensors",
251
+ "model.layers.10.mlp.experts.gate_up_proj": "model-layer-10.safetensors",
252
+ "model.layers.10.mlp.experts.gate_up_proj_scale": "model-layer-10.safetensors",
253
+ "model.layers.10.mlp.experts.down_proj": "model-layer-10.safetensors",
254
+ "model.layers.10.mlp.experts.down_proj_scale": "model-layer-10.safetensors",
255
+ "model.layers.11.self_attn.kv_a_layernorm.weight": "model-layer-11.safetensors",
256
+ "model.layers.11.mlp.shared_experts.up_proj.weight": "model-layer-11.safetensors",
257
+ "model.layers.11.mlp.shared_experts.up_proj.weight_scale": "model-layer-11.safetensors",
258
+ "model.layers.11.post_attention_layernorm.weight": "model-layer-11.safetensors",
259
+ "model.layers.11.self_attn.o_proj.weight": "model-layer-11.safetensors",
260
+ "model.layers.11.self_attn.o_proj.weight_scale": "model-layer-11.safetensors",
261
+ "model.layers.11.self_attn.kv_a_proj_with_mqa.weight": "model-layer-11.safetensors",
262
+ "model.layers.11.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-11.safetensors",
263
+ "model.layers.11.self_attn.q_proj.weight": "model-layer-11.safetensors",
264
+ "model.layers.11.self_attn.q_proj.weight_scale": "model-layer-11.safetensors",
265
+ "model.layers.11.mlp.shared_experts.down_proj.weight": "model-layer-11.safetensors",
266
+ "model.layers.11.mlp.shared_experts.down_proj.weight_scale": "model-layer-11.safetensors",
267
+ "model.layers.11.self_attn.kv_b_proj.weight": "model-layer-11.safetensors",
268
+ "model.layers.11.self_attn.kv_b_proj.weight_scale": "model-layer-11.safetensors",
269
+ "model.layers.11.input_layernorm.weight": "model-layer-11.safetensors",
270
+ "model.layers.11.mlp.gate.weight": "model-layer-11.safetensors",
271
+ "model.layers.11.mlp.gate.e_score_correction_bias": "model-layer-11.safetensors",
272
+ "model.layers.11.mlp.shared_experts.gate_proj.weight": "model-layer-11.safetensors",
273
+ "model.layers.11.mlp.shared_experts.gate_proj.weight_scale": "model-layer-11.safetensors",
274
+ "model.layers.11.mlp.experts.gate_up_proj": "model-layer-11.safetensors",
275
+ "model.layers.11.mlp.experts.gate_up_proj_scale": "model-layer-11.safetensors",
276
+ "model.layers.11.mlp.experts.down_proj": "model-layer-11.safetensors",
277
+ "model.layers.11.mlp.experts.down_proj_scale": "model-layer-11.safetensors",
278
+ "model.layers.12.self_attn.o_proj.weight": "model-layer-12.safetensors",
279
+ "model.layers.12.self_attn.o_proj.weight_scale": "model-layer-12.safetensors",
280
+ "model.layers.12.mlp.shared_experts.up_proj.weight": "model-layer-12.safetensors",
281
+ "model.layers.12.mlp.shared_experts.up_proj.weight_scale": "model-layer-12.safetensors",
282
+ "model.layers.12.mlp.shared_experts.gate_proj.weight": "model-layer-12.safetensors",
283
+ "model.layers.12.mlp.shared_experts.gate_proj.weight_scale": "model-layer-12.safetensors",
284
+ "model.layers.12.mlp.gate.e_score_correction_bias": "model-layer-12.safetensors",
285
+ "model.layers.12.post_attention_layernorm.weight": "model-layer-12.safetensors",
286
+ "model.layers.12.input_layernorm.weight": "model-layer-12.safetensors",
287
+ "model.layers.12.self_attn.q_proj.weight": "model-layer-12.safetensors",
288
+ "model.layers.12.self_attn.q_proj.weight_scale": "model-layer-12.safetensors",
289
+ "model.layers.12.mlp.shared_experts.down_proj.weight": "model-layer-12.safetensors",
290
+ "model.layers.12.mlp.shared_experts.down_proj.weight_scale": "model-layer-12.safetensors",
291
+ "model.layers.12.self_attn.kv_a_layernorm.weight": "model-layer-12.safetensors",
292
+ "model.layers.12.self_attn.kv_b_proj.weight": "model-layer-12.safetensors",
293
+ "model.layers.12.self_attn.kv_b_proj.weight_scale": "model-layer-12.safetensors",
294
+ "model.layers.12.self_attn.kv_a_proj_with_mqa.weight": "model-layer-12.safetensors",
295
+ "model.layers.12.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-12.safetensors",
296
+ "model.layers.12.mlp.gate.weight": "model-layer-12.safetensors",
297
+ "model.layers.12.mlp.experts.gate_up_proj": "model-layer-12.safetensors",
298
+ "model.layers.12.mlp.experts.gate_up_proj_scale": "model-layer-12.safetensors",
299
+ "model.layers.12.mlp.experts.down_proj": "model-layer-12.safetensors",
300
+ "model.layers.12.mlp.experts.down_proj_scale": "model-layer-12.safetensors",
301
+ "model.layers.13.self_attn.kv_a_proj_with_mqa.weight": "model-layer-13.safetensors",
302
+ "model.layers.13.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-13.safetensors",
303
+ "model.layers.13.post_attention_layernorm.weight": "model-layer-13.safetensors",
304
+ "model.layers.13.self_attn.kv_a_layernorm.weight": "model-layer-13.safetensors",
305
+ "model.layers.13.self_attn.q_proj.weight": "model-layer-13.safetensors",
306
+ "model.layers.13.self_attn.q_proj.weight_scale": "model-layer-13.safetensors",
307
+ "model.layers.13.mlp.shared_experts.up_proj.weight": "model-layer-13.safetensors",
308
+ "model.layers.13.mlp.shared_experts.up_proj.weight_scale": "model-layer-13.safetensors",
309
+ "model.layers.13.mlp.shared_experts.down_proj.weight": "model-layer-13.safetensors",
310
+ "model.layers.13.mlp.shared_experts.down_proj.weight_scale": "model-layer-13.safetensors",
311
+ "model.layers.13.input_layernorm.weight": "model-layer-13.safetensors",
312
+ "model.layers.13.self_attn.o_proj.weight": "model-layer-13.safetensors",
313
+ "model.layers.13.self_attn.o_proj.weight_scale": "model-layer-13.safetensors",
314
+ "model.layers.13.mlp.shared_experts.gate_proj.weight": "model-layer-13.safetensors",
315
+ "model.layers.13.mlp.shared_experts.gate_proj.weight_scale": "model-layer-13.safetensors",
316
+ "model.layers.13.mlp.gate.weight": "model-layer-13.safetensors",
317
+ "model.layers.13.self_attn.kv_b_proj.weight": "model-layer-13.safetensors",
318
+ "model.layers.13.self_attn.kv_b_proj.weight_scale": "model-layer-13.safetensors",
319
+ "model.layers.13.mlp.gate.e_score_correction_bias": "model-layer-13.safetensors",
320
+ "model.layers.13.mlp.experts.gate_up_proj": "model-layer-13.safetensors",
321
+ "model.layers.13.mlp.experts.gate_up_proj_scale": "model-layer-13.safetensors",
322
+ "model.layers.13.mlp.experts.down_proj": "model-layer-13.safetensors",
323
+ "model.layers.13.mlp.experts.down_proj_scale": "model-layer-13.safetensors",
324
+ "model.layers.14.mlp.shared_experts.gate_proj.weight": "model-layer-14.safetensors",
325
+ "model.layers.14.mlp.shared_experts.gate_proj.weight_scale": "model-layer-14.safetensors",
326
+ "model.layers.14.mlp.gate.weight": "model-layer-14.safetensors",
327
+ "model.layers.14.post_attention_layernorm.weight": "model-layer-14.safetensors",
328
+ "model.layers.14.self_attn.kv_b_proj.weight": "model-layer-14.safetensors",
329
+ "model.layers.14.self_attn.kv_b_proj.weight_scale": "model-layer-14.safetensors",
330
+ "model.layers.14.self_attn.kv_a_proj_with_mqa.weight": "model-layer-14.safetensors",
331
+ "model.layers.14.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-14.safetensors",
332
+ "model.layers.14.input_layernorm.weight": "model-layer-14.safetensors",
333
+ "model.layers.14.mlp.gate.e_score_correction_bias": "model-layer-14.safetensors",
334
+ "model.layers.14.self_attn.o_proj.weight": "model-layer-14.safetensors",
335
+ "model.layers.14.self_attn.o_proj.weight_scale": "model-layer-14.safetensors",
336
+ "model.layers.14.self_attn.kv_a_layernorm.weight": "model-layer-14.safetensors",
337
+ "model.layers.14.mlp.shared_experts.down_proj.weight": "model-layer-14.safetensors",
338
+ "model.layers.14.mlp.shared_experts.down_proj.weight_scale": "model-layer-14.safetensors",
339
+ "model.layers.14.self_attn.q_proj.weight": "model-layer-14.safetensors",
340
+ "model.layers.14.self_attn.q_proj.weight_scale": "model-layer-14.safetensors",
341
+ "model.layers.14.mlp.shared_experts.up_proj.weight": "model-layer-14.safetensors",
342
+ "model.layers.14.mlp.shared_experts.up_proj.weight_scale": "model-layer-14.safetensors",
343
+ "model.layers.14.mlp.experts.gate_up_proj": "model-layer-14.safetensors",
344
+ "model.layers.14.mlp.experts.gate_up_proj_scale": "model-layer-14.safetensors",
345
+ "model.layers.14.mlp.experts.down_proj": "model-layer-14.safetensors",
346
+ "model.layers.14.mlp.experts.down_proj_scale": "model-layer-14.safetensors",
347
+ "model.layers.15.mlp.shared_experts.down_proj.weight": "model-layer-15.safetensors",
348
+ "model.layers.15.mlp.shared_experts.down_proj.weight_scale": "model-layer-15.safetensors",
349
+ "model.layers.15.self_attn.o_proj.weight": "model-layer-15.safetensors",
350
+ "model.layers.15.self_attn.o_proj.weight_scale": "model-layer-15.safetensors",
351
+ "model.layers.15.mlp.shared_experts.gate_proj.weight": "model-layer-15.safetensors",
352
+ "model.layers.15.mlp.shared_experts.gate_proj.weight_scale": "model-layer-15.safetensors",
353
+ "model.layers.15.input_layernorm.weight": "model-layer-15.safetensors",
354
+ "model.layers.15.mlp.shared_experts.up_proj.weight": "model-layer-15.safetensors",
355
+ "model.layers.15.mlp.shared_experts.up_proj.weight_scale": "model-layer-15.safetensors",
356
+ "model.layers.15.post_attention_layernorm.weight": "model-layer-15.safetensors",
357
+ "model.layers.15.mlp.gate.e_score_correction_bias": "model-layer-15.safetensors",
358
+ "model.layers.15.self_attn.kv_b_proj.weight": "model-layer-15.safetensors",
359
+ "model.layers.15.self_attn.kv_b_proj.weight_scale": "model-layer-15.safetensors",
360
+ "model.layers.15.self_attn.kv_a_layernorm.weight": "model-layer-15.safetensors",
361
+ "model.layers.15.mlp.gate.weight": "model-layer-15.safetensors",
362
+ "model.layers.15.self_attn.kv_a_proj_with_mqa.weight": "model-layer-15.safetensors",
363
+ "model.layers.15.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-15.safetensors",
364
+ "model.layers.15.self_attn.q_proj.weight": "model-layer-15.safetensors",
365
+ "model.layers.15.self_attn.q_proj.weight_scale": "model-layer-15.safetensors",
366
+ "model.layers.15.mlp.experts.gate_up_proj": "model-layer-15.safetensors",
367
+ "model.layers.15.mlp.experts.gate_up_proj_scale": "model-layer-15.safetensors",
368
+ "model.layers.15.mlp.experts.down_proj": "model-layer-15.safetensors",
369
+ "model.layers.15.mlp.experts.down_proj_scale": "model-layer-15.safetensors",
370
+ "model.layers.16.mlp.gate.e_score_correction_bias": "model-layer-16.safetensors",
371
+ "model.layers.16.input_layernorm.weight": "model-layer-16.safetensors",
372
+ "model.layers.16.self_attn.kv_b_proj.weight": "model-layer-16.safetensors",
373
+ "model.layers.16.self_attn.kv_b_proj.weight_scale": "model-layer-16.safetensors",
374
+ "model.layers.16.post_attention_layernorm.weight": "model-layer-16.safetensors",
375
+ "model.layers.16.self_attn.q_proj.weight": "model-layer-16.safetensors",
376
+ "model.layers.16.self_attn.q_proj.weight_scale": "model-layer-16.safetensors",
377
+ "model.layers.16.mlp.shared_experts.up_proj.weight": "model-layer-16.safetensors",
378
+ "model.layers.16.mlp.shared_experts.up_proj.weight_scale": "model-layer-16.safetensors",
379
+ "model.layers.16.self_attn.kv_a_proj_with_mqa.weight": "model-layer-16.safetensors",
380
+ "model.layers.16.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-16.safetensors",
381
+ "model.layers.16.mlp.gate.weight": "model-layer-16.safetensors",
382
+ "model.layers.16.mlp.shared_experts.down_proj.weight": "model-layer-16.safetensors",
383
+ "model.layers.16.mlp.shared_experts.down_proj.weight_scale": "model-layer-16.safetensors",
384
+ "model.layers.16.mlp.shared_experts.gate_proj.weight": "model-layer-16.safetensors",
385
+ "model.layers.16.mlp.shared_experts.gate_proj.weight_scale": "model-layer-16.safetensors",
386
+ "model.layers.16.self_attn.kv_a_layernorm.weight": "model-layer-16.safetensors",
387
+ "model.layers.16.self_attn.o_proj.weight": "model-layer-16.safetensors",
388
+ "model.layers.16.self_attn.o_proj.weight_scale": "model-layer-16.safetensors",
389
+ "model.layers.16.mlp.experts.gate_up_proj": "model-layer-16.safetensors",
390
+ "model.layers.16.mlp.experts.gate_up_proj_scale": "model-layer-16.safetensors",
391
+ "model.layers.16.mlp.experts.down_proj": "model-layer-16.safetensors",
392
+ "model.layers.16.mlp.experts.down_proj_scale": "model-layer-16.safetensors",
393
+ "model.layers.17.input_layernorm.weight": "model-layer-17.safetensors",
394
+ "model.layers.17.mlp.gate.weight": "model-layer-17.safetensors",
395
+ "model.layers.17.self_attn.o_proj.weight": "model-layer-17.safetensors",
396
+ "model.layers.17.self_attn.o_proj.weight_scale": "model-layer-17.safetensors",
397
+ "model.layers.17.mlp.shared_experts.down_proj.weight": "model-layer-17.safetensors",
398
+ "model.layers.17.mlp.shared_experts.down_proj.weight_scale": "model-layer-17.safetensors",
399
+ "model.layers.17.self_attn.kv_a_layernorm.weight": "model-layer-17.safetensors",
400
+ "model.layers.17.self_attn.kv_a_proj_with_mqa.weight": "model-layer-17.safetensors",
401
+ "model.layers.17.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-17.safetensors",
402
+ "model.layers.17.mlp.shared_experts.gate_proj.weight": "model-layer-17.safetensors",
403
+ "model.layers.17.mlp.shared_experts.gate_proj.weight_scale": "model-layer-17.safetensors",
404
+ "model.layers.17.self_attn.kv_b_proj.weight": "model-layer-17.safetensors",
405
+ "model.layers.17.self_attn.kv_b_proj.weight_scale": "model-layer-17.safetensors",
406
+ "model.layers.17.mlp.gate.e_score_correction_bias": "model-layer-17.safetensors",
407
+ "model.layers.17.mlp.shared_experts.up_proj.weight": "model-layer-17.safetensors",
408
+ "model.layers.17.mlp.shared_experts.up_proj.weight_scale": "model-layer-17.safetensors",
409
+ "model.layers.17.post_attention_layernorm.weight": "model-layer-17.safetensors",
410
+ "model.layers.17.self_attn.q_proj.weight": "model-layer-17.safetensors",
411
+ "model.layers.17.self_attn.q_proj.weight_scale": "model-layer-17.safetensors",
412
+ "model.layers.17.mlp.experts.gate_up_proj": "model-layer-17.safetensors",
413
+ "model.layers.17.mlp.experts.gate_up_proj_scale": "model-layer-17.safetensors",
414
+ "model.layers.17.mlp.experts.down_proj": "model-layer-17.safetensors",
415
+ "model.layers.17.mlp.experts.down_proj_scale": "model-layer-17.safetensors",
416
+ "model.layers.18.mlp.gate.weight": "model-layer-18.safetensors",
417
+ "model.layers.18.mlp.shared_experts.gate_proj.weight": "model-layer-18.safetensors",
418
+ "model.layers.18.mlp.shared_experts.gate_proj.weight_scale": "model-layer-18.safetensors",
419
+ "model.layers.18.self_attn.q_proj.weight": "model-layer-18.safetensors",
420
+ "model.layers.18.self_attn.q_proj.weight_scale": "model-layer-18.safetensors",
421
+ "model.layers.18.input_layernorm.weight": "model-layer-18.safetensors",
422
+ "model.layers.18.self_attn.kv_b_proj.weight": "model-layer-18.safetensors",
423
+ "model.layers.18.self_attn.kv_b_proj.weight_scale": "model-layer-18.safetensors",
424
+ "model.layers.18.post_attention_layernorm.weight": "model-layer-18.safetensors",
425
+ "model.layers.18.mlp.shared_experts.up_proj.weight": "model-layer-18.safetensors",
426
+ "model.layers.18.mlp.shared_experts.up_proj.weight_scale": "model-layer-18.safetensors",
427
+ "model.layers.18.self_attn.kv_a_layernorm.weight": "model-layer-18.safetensors",
428
+ "model.layers.18.mlp.shared_experts.down_proj.weight": "model-layer-18.safetensors",
429
+ "model.layers.18.mlp.shared_experts.down_proj.weight_scale": "model-layer-18.safetensors",
430
+ "model.layers.18.mlp.gate.e_score_correction_bias": "model-layer-18.safetensors",
431
+ "model.layers.18.self_attn.o_proj.weight": "model-layer-18.safetensors",
432
+ "model.layers.18.self_attn.o_proj.weight_scale": "model-layer-18.safetensors",
433
+ "model.layers.18.self_attn.kv_a_proj_with_mqa.weight": "model-layer-18.safetensors",
434
+ "model.layers.18.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-18.safetensors",
435
+ "model.layers.18.mlp.experts.gate_up_proj": "model-layer-18.safetensors",
436
+ "model.layers.18.mlp.experts.gate_up_proj_scale": "model-layer-18.safetensors",
437
+ "model.layers.18.mlp.experts.down_proj": "model-layer-18.safetensors",
438
+ "model.layers.18.mlp.experts.down_proj_scale": "model-layer-18.safetensors",
439
+ "model.layers.19.post_attention_layernorm.weight": "model-layer-19.safetensors",
440
+ "model.layers.19.mlp.gate.weight": "model-layer-19.safetensors",
441
+ "model.layers.19.mlp.gate.e_score_correction_bias": "model-layer-19.safetensors",
442
+ "model.layers.19.self_attn.kv_a_layernorm.weight": "model-layer-19.safetensors",
443
+ "model.layers.19.self_attn.kv_a_proj_with_mqa.weight": "model-layer-19.safetensors",
444
+ "model.layers.19.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-19.safetensors",
445
+ "model.layers.19.self_attn.kv_b_proj.weight": "model-layer-19.safetensors",
446
+ "model.layers.19.self_attn.kv_b_proj.weight_scale": "model-layer-19.safetensors",
447
+ "model.layers.19.mlp.shared_experts.up_proj.weight": "model-layer-19.safetensors",
448
+ "model.layers.19.mlp.shared_experts.up_proj.weight_scale": "model-layer-19.safetensors",
449
+ "model.layers.19.input_layernorm.weight": "model-layer-19.safetensors",
450
+ "model.layers.19.mlp.shared_experts.gate_proj.weight": "model-layer-19.safetensors",
451
+ "model.layers.19.mlp.shared_experts.gate_proj.weight_scale": "model-layer-19.safetensors",
452
+ "model.layers.19.self_attn.o_proj.weight": "model-layer-19.safetensors",
453
+ "model.layers.19.self_attn.o_proj.weight_scale": "model-layer-19.safetensors",
454
+ "model.layers.19.self_attn.q_proj.weight": "model-layer-19.safetensors",
455
+ "model.layers.19.self_attn.q_proj.weight_scale": "model-layer-19.safetensors",
456
+ "model.layers.19.mlp.shared_experts.down_proj.weight": "model-layer-19.safetensors",
457
+ "model.layers.19.mlp.shared_experts.down_proj.weight_scale": "model-layer-19.safetensors",
458
+ "model.layers.19.mlp.experts.gate_up_proj": "model-layer-19.safetensors",
459
+ "model.layers.19.mlp.experts.gate_up_proj_scale": "model-layer-19.safetensors",
460
+ "model.layers.19.mlp.experts.down_proj": "model-layer-19.safetensors",
461
+ "model.layers.19.mlp.experts.down_proj_scale": "model-layer-19.safetensors",
462
+ "model.layers.20.input_layernorm.weight": "model-layer-20.safetensors",
463
+ "model.layers.20.mlp.gate.weight": "model-layer-20.safetensors",
464
+ "model.layers.20.mlp.shared_experts.down_proj.weight": "model-layer-20.safetensors",
465
+ "model.layers.20.mlp.shared_experts.down_proj.weight_scale": "model-layer-20.safetensors",
466
+ "model.layers.20.self_attn.q_proj.weight": "model-layer-20.safetensors",
467
+ "model.layers.20.self_attn.q_proj.weight_scale": "model-layer-20.safetensors",
468
+ "model.layers.20.mlp.shared_experts.up_proj.weight": "model-layer-20.safetensors",
469
+ "model.layers.20.mlp.shared_experts.up_proj.weight_scale": "model-layer-20.safetensors",
470
+ "model.layers.20.mlp.gate.e_score_correction_bias": "model-layer-20.safetensors",
471
+ "model.layers.20.self_attn.o_proj.weight": "model-layer-20.safetensors",
472
+ "model.layers.20.self_attn.o_proj.weight_scale": "model-layer-20.safetensors",
473
+ "model.layers.20.mlp.shared_experts.gate_proj.weight": "model-layer-20.safetensors",
474
+ "model.layers.20.mlp.shared_experts.gate_proj.weight_scale": "model-layer-20.safetensors",
475
+ "model.layers.20.self_attn.kv_b_proj.weight": "model-layer-20.safetensors",
476
+ "model.layers.20.self_attn.kv_b_proj.weight_scale": "model-layer-20.safetensors",
477
+ "model.layers.20.self_attn.kv_a_proj_with_mqa.weight": "model-layer-20.safetensors",
478
+ "model.layers.20.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-20.safetensors",
479
+ "model.layers.20.post_attention_layernorm.weight": "model-layer-20.safetensors",
480
+ "model.layers.20.self_attn.kv_a_layernorm.weight": "model-layer-20.safetensors",
481
+ "model.layers.20.mlp.experts.gate_up_proj": "model-layer-20.safetensors",
482
+ "model.layers.20.mlp.experts.gate_up_proj_scale": "model-layer-20.safetensors",
483
+ "model.layers.20.mlp.experts.down_proj": "model-layer-20.safetensors",
484
+ "model.layers.20.mlp.experts.down_proj_scale": "model-layer-20.safetensors",
485
+ "model.layers.21.input_layernorm.weight": "model-layer-21.safetensors",
486
+ "model.layers.21.self_attn.kv_a_layernorm.weight": "model-layer-21.safetensors",
487
+ "model.layers.21.mlp.gate.weight": "model-layer-21.safetensors",
488
+ "model.layers.21.self_attn.o_proj.weight": "model-layer-21.safetensors",
489
+ "model.layers.21.self_attn.o_proj.weight_scale": "model-layer-21.safetensors",
490
+ "model.layers.21.mlp.shared_experts.gate_proj.weight": "model-layer-21.safetensors",
491
+ "model.layers.21.mlp.shared_experts.gate_proj.weight_scale": "model-layer-21.safetensors",
492
+ "model.layers.21.self_attn.q_proj.weight": "model-layer-21.safetensors",
493
+ "model.layers.21.self_attn.q_proj.weight_scale": "model-layer-21.safetensors",
494
+ "model.layers.21.post_attention_layernorm.weight": "model-layer-21.safetensors",
495
+ "model.layers.21.self_attn.kv_a_proj_with_mqa.weight": "model-layer-21.safetensors",
496
+ "model.layers.21.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-21.safetensors",
497
+ "model.layers.21.mlp.gate.e_score_correction_bias": "model-layer-21.safetensors",
498
+ "model.layers.21.self_attn.kv_b_proj.weight": "model-layer-21.safetensors",
499
+ "model.layers.21.self_attn.kv_b_proj.weight_scale": "model-layer-21.safetensors",
500
+ "model.layers.21.mlp.shared_experts.down_proj.weight": "model-layer-21.safetensors",
501
+ "model.layers.21.mlp.shared_experts.down_proj.weight_scale": "model-layer-21.safetensors",
502
+ "model.layers.21.mlp.shared_experts.up_proj.weight": "model-layer-21.safetensors",
503
+ "model.layers.21.mlp.shared_experts.up_proj.weight_scale": "model-layer-21.safetensors",
504
+ "model.layers.21.mlp.experts.gate_up_proj": "model-layer-21.safetensors",
505
+ "model.layers.21.mlp.experts.gate_up_proj_scale": "model-layer-21.safetensors",
506
+ "model.layers.21.mlp.experts.down_proj": "model-layer-21.safetensors",
507
+ "model.layers.21.mlp.experts.down_proj_scale": "model-layer-21.safetensors",
508
+ "model.layers.22.post_attention_layernorm.weight": "model-layer-22.safetensors",
509
+ "model.layers.22.mlp.shared_experts.up_proj.weight": "model-layer-22.safetensors",
510
+ "model.layers.22.mlp.shared_experts.up_proj.weight_scale": "model-layer-22.safetensors",
511
+ "model.layers.22.mlp.gate.weight": "model-layer-22.safetensors",
512
+ "model.layers.22.self_attn.o_proj.weight": "model-layer-22.safetensors",
513
+ "model.layers.22.self_attn.o_proj.weight_scale": "model-layer-22.safetensors",
514
+ "model.layers.22.self_attn.kv_b_proj.weight": "model-layer-22.safetensors",
515
+ "model.layers.22.self_attn.kv_b_proj.weight_scale": "model-layer-22.safetensors",
516
+ "model.layers.22.mlp.shared_experts.down_proj.weight": "model-layer-22.safetensors",
517
+ "model.layers.22.mlp.shared_experts.down_proj.weight_scale": "model-layer-22.safetensors",
518
+ "model.layers.22.input_layernorm.weight": "model-layer-22.safetensors",
519
+ "model.layers.22.self_attn.kv_a_proj_with_mqa.weight": "model-layer-22.safetensors",
520
+ "model.layers.22.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-22.safetensors",
521
+ "model.layers.22.mlp.shared_experts.gate_proj.weight": "model-layer-22.safetensors",
522
+ "model.layers.22.mlp.shared_experts.gate_proj.weight_scale": "model-layer-22.safetensors",
523
+ "model.layers.22.self_attn.kv_a_layernorm.weight": "model-layer-22.safetensors",
524
+ "model.layers.22.mlp.gate.e_score_correction_bias": "model-layer-22.safetensors",
525
+ "model.layers.22.self_attn.q_proj.weight": "model-layer-22.safetensors",
526
+ "model.layers.22.self_attn.q_proj.weight_scale": "model-layer-22.safetensors",
527
+ "model.layers.22.mlp.experts.gate_up_proj": "model-layer-22.safetensors",
528
+ "model.layers.22.mlp.experts.gate_up_proj_scale": "model-layer-22.safetensors",
529
+ "model.layers.22.mlp.experts.down_proj": "model-layer-22.safetensors",
530
+ "model.layers.22.mlp.experts.down_proj_scale": "model-layer-22.safetensors",
531
+ "model.layers.23.mlp.shared_experts.up_proj.weight": "model-layer-23.safetensors",
532
+ "model.layers.23.mlp.shared_experts.up_proj.weight_scale": "model-layer-23.safetensors",
533
+ "model.layers.23.self_attn.o_proj.weight": "model-layer-23.safetensors",
534
+ "model.layers.23.self_attn.o_proj.weight_scale": "model-layer-23.safetensors",
535
+ "model.layers.23.self_attn.kv_a_proj_with_mqa.weight": "model-layer-23.safetensors",
536
+ "model.layers.23.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-23.safetensors",
537
+ "model.layers.23.post_attention_layernorm.weight": "model-layer-23.safetensors",
538
+ "model.layers.23.input_layernorm.weight": "model-layer-23.safetensors",
539
+ "model.layers.23.mlp.shared_experts.gate_proj.weight": "model-layer-23.safetensors",
540
+ "model.layers.23.mlp.shared_experts.gate_proj.weight_scale": "model-layer-23.safetensors",
541
+ "model.layers.23.mlp.gate.weight": "model-layer-23.safetensors",
542
+ "model.layers.23.self_attn.kv_a_layernorm.weight": "model-layer-23.safetensors",
543
+ "model.layers.23.mlp.shared_experts.down_proj.weight": "model-layer-23.safetensors",
544
+ "model.layers.23.mlp.shared_experts.down_proj.weight_scale": "model-layer-23.safetensors",
545
+ "model.layers.23.mlp.gate.e_score_correction_bias": "model-layer-23.safetensors",
546
+ "model.layers.23.self_attn.q_proj.weight": "model-layer-23.safetensors",
547
+ "model.layers.23.self_attn.q_proj.weight_scale": "model-layer-23.safetensors",
548
+ "model.layers.23.self_attn.kv_b_proj.weight": "model-layer-23.safetensors",
549
+ "model.layers.23.self_attn.kv_b_proj.weight_scale": "model-layer-23.safetensors",
550
+ "model.layers.23.mlp.experts.gate_up_proj": "model-layer-23.safetensors",
551
+ "model.layers.23.mlp.experts.gate_up_proj_scale": "model-layer-23.safetensors",
552
+ "model.layers.23.mlp.experts.down_proj": "model-layer-23.safetensors",
553
+ "model.layers.23.mlp.experts.down_proj_scale": "model-layer-23.safetensors",
554
+ "model.layers.24.mlp.shared_experts.down_proj.weight": "model-layer-24.safetensors",
555
+ "model.layers.24.mlp.shared_experts.down_proj.weight_scale": "model-layer-24.safetensors",
556
+ "model.layers.24.post_attention_layernorm.weight": "model-layer-24.safetensors",
557
+ "model.layers.24.self_attn.o_proj.weight": "model-layer-24.safetensors",
558
+ "model.layers.24.self_attn.o_proj.weight_scale": "model-layer-24.safetensors",
559
+ "model.layers.24.input_layernorm.weight": "model-layer-24.safetensors",
560
+ "model.layers.24.mlp.gate.weight": "model-layer-24.safetensors",
561
+ "model.layers.24.self_attn.kv_a_proj_with_mqa.weight": "model-layer-24.safetensors",
562
+ "model.layers.24.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-24.safetensors",
563
+ "model.layers.24.mlp.shared_experts.up_proj.weight": "model-layer-24.safetensors",
564
+ "model.layers.24.mlp.shared_experts.up_proj.weight_scale": "model-layer-24.safetensors",
565
+ "model.layers.24.self_attn.q_proj.weight": "model-layer-24.safetensors",
566
+ "model.layers.24.self_attn.q_proj.weight_scale": "model-layer-24.safetensors",
567
+ "model.layers.24.self_attn.kv_b_proj.weight": "model-layer-24.safetensors",
568
+ "model.layers.24.self_attn.kv_b_proj.weight_scale": "model-layer-24.safetensors",
569
+ "model.layers.24.mlp.gate.e_score_correction_bias": "model-layer-24.safetensors",
570
+ "model.layers.24.mlp.shared_experts.gate_proj.weight": "model-layer-24.safetensors",
571
+ "model.layers.24.mlp.shared_experts.gate_proj.weight_scale": "model-layer-24.safetensors",
572
+ "model.layers.24.self_attn.kv_a_layernorm.weight": "model-layer-24.safetensors",
573
+ "model.layers.24.mlp.experts.gate_up_proj": "model-layer-24.safetensors",
574
+ "model.layers.24.mlp.experts.gate_up_proj_scale": "model-layer-24.safetensors",
575
+ "model.layers.24.mlp.experts.down_proj": "model-layer-24.safetensors",
576
+ "model.layers.24.mlp.experts.down_proj_scale": "model-layer-24.safetensors",
577
+ "model.layers.25.self_attn.kv_b_proj.weight": "model-layer-25.safetensors",
578
+ "model.layers.25.self_attn.kv_b_proj.weight_scale": "model-layer-25.safetensors",
579
+ "model.layers.25.self_attn.o_proj.weight": "model-layer-25.safetensors",
580
+ "model.layers.25.self_attn.o_proj.weight_scale": "model-layer-25.safetensors",
581
+ "model.layers.25.mlp.shared_experts.down_proj.weight": "model-layer-25.safetensors",
582
+ "model.layers.25.mlp.shared_experts.down_proj.weight_scale": "model-layer-25.safetensors",
583
+ "model.layers.25.mlp.shared_experts.gate_proj.weight": "model-layer-25.safetensors",
584
+ "model.layers.25.mlp.shared_experts.gate_proj.weight_scale": "model-layer-25.safetensors",
585
+ "model.layers.25.input_layernorm.weight": "model-layer-25.safetensors",
586
+ "model.layers.25.self_attn.q_proj.weight": "model-layer-25.safetensors",
587
+ "model.layers.25.self_attn.q_proj.weight_scale": "model-layer-25.safetensors",
588
+ "model.layers.25.mlp.gate.e_score_correction_bias": "model-layer-25.safetensors",
589
+ "model.layers.25.mlp.shared_experts.up_proj.weight": "model-layer-25.safetensors",
590
+ "model.layers.25.mlp.shared_experts.up_proj.weight_scale": "model-layer-25.safetensors",
591
+ "model.layers.25.post_attention_layernorm.weight": "model-layer-25.safetensors",
592
+ "model.layers.25.mlp.gate.weight": "model-layer-25.safetensors",
593
+ "model.layers.25.self_attn.kv_a_proj_with_mqa.weight": "model-layer-25.safetensors",
594
+ "model.layers.25.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-25.safetensors",
595
+ "model.layers.25.self_attn.kv_a_layernorm.weight": "model-layer-25.safetensors",
596
+ "model.layers.25.mlp.experts.gate_up_proj": "model-layer-25.safetensors",
597
+ "model.layers.25.mlp.experts.gate_up_proj_scale": "model-layer-25.safetensors",
598
+ "model.layers.25.mlp.experts.down_proj": "model-layer-25.safetensors",
599
+ "model.layers.25.mlp.experts.down_proj_scale": "model-layer-25.safetensors",
600
+ "model.layers.26.mlp.gate.e_score_correction_bias": "model-layer-26.safetensors",
601
+ "model.layers.26.self_attn.q_proj.weight": "model-layer-26.safetensors",
602
+ "model.layers.26.self_attn.q_proj.weight_scale": "model-layer-26.safetensors",
603
+ "model.layers.26.post_attention_layernorm.weight": "model-layer-26.safetensors",
604
+ "model.layers.26.mlp.shared_experts.down_proj.weight": "model-layer-26.safetensors",
605
+ "model.layers.26.mlp.shared_experts.down_proj.weight_scale": "model-layer-26.safetensors",
606
+ "model.layers.26.self_attn.o_proj.weight": "model-layer-26.safetensors",
607
+ "model.layers.26.self_attn.o_proj.weight_scale": "model-layer-26.safetensors",
608
+ "model.layers.26.self_attn.kv_a_layernorm.weight": "model-layer-26.safetensors",
609
+ "model.layers.26.self_attn.kv_a_proj_with_mqa.weight": "model-layer-26.safetensors",
610
+ "model.layers.26.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-26.safetensors",
611
+ "model.layers.26.mlp.shared_experts.gate_proj.weight": "model-layer-26.safetensors",
612
+ "model.layers.26.mlp.shared_experts.gate_proj.weight_scale": "model-layer-26.safetensors",
613
+ "model.layers.26.self_attn.kv_b_proj.weight": "model-layer-26.safetensors",
614
+ "model.layers.26.self_attn.kv_b_proj.weight_scale": "model-layer-26.safetensors",
615
+ "model.layers.26.mlp.gate.weight": "model-layer-26.safetensors",
616
+ "model.layers.26.mlp.shared_experts.up_proj.weight": "model-layer-26.safetensors",
617
+ "model.layers.26.mlp.shared_experts.up_proj.weight_scale": "model-layer-26.safetensors",
618
+ "model.layers.26.input_layernorm.weight": "model-layer-26.safetensors",
619
+ "model.layers.26.mlp.experts.gate_up_proj": "model-layer-26.safetensors",
620
+ "model.layers.26.mlp.experts.gate_up_proj_scale": "model-layer-26.safetensors",
621
+ "model.layers.26.mlp.experts.down_proj": "model-layer-26.safetensors",
622
+ "model.layers.26.mlp.experts.down_proj_scale": "model-layer-26.safetensors",
623
+ "model.layers.27.mlp.shared_experts.gate_proj.weight": "model-layer-27.safetensors",
624
+ "model.layers.27.mlp.shared_experts.gate_proj.weight_scale": "model-layer-27.safetensors",
625
+ "model.layers.27.self_attn.kv_a_proj_with_mqa.weight": "model-layer-27.safetensors",
626
+ "model.layers.27.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-27.safetensors",
627
+ "model.layers.27.self_attn.o_proj.weight": "model-layer-27.safetensors",
628
+ "model.layers.27.self_attn.o_proj.weight_scale": "model-layer-27.safetensors",
629
+ "model.layers.27.self_attn.q_proj.weight": "model-layer-27.safetensors",
630
+ "model.layers.27.self_attn.q_proj.weight_scale": "model-layer-27.safetensors",
631
+ "model.layers.27.mlp.shared_experts.up_proj.weight": "model-layer-27.safetensors",
632
+ "model.layers.27.mlp.shared_experts.up_proj.weight_scale": "model-layer-27.safetensors",
633
+ "model.layers.27.mlp.gate.e_score_correction_bias": "model-layer-27.safetensors",
634
+ "model.layers.27.mlp.shared_experts.down_proj.weight": "model-layer-27.safetensors",
635
+ "model.layers.27.mlp.shared_experts.down_proj.weight_scale": "model-layer-27.safetensors",
636
+ "model.layers.27.self_attn.kv_a_layernorm.weight": "model-layer-27.safetensors",
637
+ "model.layers.27.self_attn.kv_b_proj.weight": "model-layer-27.safetensors",
638
+ "model.layers.27.self_attn.kv_b_proj.weight_scale": "model-layer-27.safetensors",
639
+ "model.layers.27.mlp.gate.weight": "model-layer-27.safetensors",
640
+ "model.layers.27.input_layernorm.weight": "model-layer-27.safetensors",
641
+ "model.layers.27.post_attention_layernorm.weight": "model-layer-27.safetensors",
642
+ "model.layers.27.mlp.experts.gate_up_proj": "model-layer-27.safetensors",
643
+ "model.layers.27.mlp.experts.gate_up_proj_scale": "model-layer-27.safetensors",
644
+ "model.layers.27.mlp.experts.down_proj": "model-layer-27.safetensors",
645
+ "model.layers.27.mlp.experts.down_proj_scale": "model-layer-27.safetensors",
646
+ "model.layers.28.mlp.shared_experts.gate_proj.weight": "model-layer-28.safetensors",
647
+ "model.layers.28.mlp.shared_experts.gate_proj.weight_scale": "model-layer-28.safetensors",
648
+ "model.layers.28.self_attn.kv_a_layernorm.weight": "model-layer-28.safetensors",
649
+ "model.layers.28.mlp.gate.weight": "model-layer-28.safetensors",
650
+ "model.layers.28.self_attn.o_proj.weight": "model-layer-28.safetensors",
651
+ "model.layers.28.self_attn.o_proj.weight_scale": "model-layer-28.safetensors",
652
+ "model.layers.28.self_attn.kv_a_proj_with_mqa.weight": "model-layer-28.safetensors",
653
+ "model.layers.28.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-28.safetensors",
654
+ "model.layers.28.post_attention_layernorm.weight": "model-layer-28.safetensors",
655
+ "model.layers.28.self_attn.kv_b_proj.weight": "model-layer-28.safetensors",
656
+ "model.layers.28.self_attn.kv_b_proj.weight_scale": "model-layer-28.safetensors",
657
+ "model.layers.28.self_attn.q_proj.weight": "model-layer-28.safetensors",
658
+ "model.layers.28.self_attn.q_proj.weight_scale": "model-layer-28.safetensors",
659
+ "model.layers.28.mlp.shared_experts.up_proj.weight": "model-layer-28.safetensors",
660
+ "model.layers.28.mlp.shared_experts.up_proj.weight_scale": "model-layer-28.safetensors",
661
+ "model.layers.28.mlp.gate.e_score_correction_bias": "model-layer-28.safetensors",
662
+ "model.layers.28.mlp.shared_experts.down_proj.weight": "model-layer-28.safetensors",
663
+ "model.layers.28.mlp.shared_experts.down_proj.weight_scale": "model-layer-28.safetensors",
664
+ "model.layers.28.input_layernorm.weight": "model-layer-28.safetensors",
665
+ "model.layers.28.mlp.experts.gate_up_proj": "model-layer-28.safetensors",
666
+ "model.layers.28.mlp.experts.gate_up_proj_scale": "model-layer-28.safetensors",
667
+ "model.layers.28.mlp.experts.down_proj": "model-layer-28.safetensors",
668
+ "model.layers.28.mlp.experts.down_proj_scale": "model-layer-28.safetensors",
669
+ "model.layers.29.self_attn.q_proj.weight": "model-layer-29.safetensors",
670
+ "model.layers.29.self_attn.q_proj.weight_scale": "model-layer-29.safetensors",
671
+ "model.layers.29.self_attn.o_proj.weight": "model-layer-29.safetensors",
672
+ "model.layers.29.self_attn.o_proj.weight_scale": "model-layer-29.safetensors",
673
+ "model.layers.29.mlp.gate.weight": "model-layer-29.safetensors",
674
+ "model.layers.29.self_attn.kv_a_proj_with_mqa.weight": "model-layer-29.safetensors",
675
+ "model.layers.29.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-29.safetensors",
676
+ "model.layers.29.input_layernorm.weight": "model-layer-29.safetensors",
677
+ "model.layers.29.mlp.shared_experts.up_proj.weight": "model-layer-29.safetensors",
678
+ "model.layers.29.mlp.shared_experts.up_proj.weight_scale": "model-layer-29.safetensors",
679
+ "model.layers.29.self_attn.kv_a_layernorm.weight": "model-layer-29.safetensors",
680
+ "model.layers.29.mlp.gate.e_score_correction_bias": "model-layer-29.safetensors",
681
+ "model.layers.29.mlp.shared_experts.gate_proj.weight": "model-layer-29.safetensors",
682
+ "model.layers.29.mlp.shared_experts.gate_proj.weight_scale": "model-layer-29.safetensors",
683
+ "model.layers.29.post_attention_layernorm.weight": "model-layer-29.safetensors",
684
+ "model.layers.29.self_attn.kv_b_proj.weight": "model-layer-29.safetensors",
685
+ "model.layers.29.self_attn.kv_b_proj.weight_scale": "model-layer-29.safetensors",
686
+ "model.layers.29.mlp.shared_experts.down_proj.weight": "model-layer-29.safetensors",
687
+ "model.layers.29.mlp.shared_experts.down_proj.weight_scale": "model-layer-29.safetensors",
688
+ "model.layers.29.mlp.experts.gate_up_proj": "model-layer-29.safetensors",
689
+ "model.layers.29.mlp.experts.gate_up_proj_scale": "model-layer-29.safetensors",
690
+ "model.layers.29.mlp.experts.down_proj": "model-layer-29.safetensors",
691
+ "model.layers.29.mlp.experts.down_proj_scale": "model-layer-29.safetensors",
692
+ "model.layers.30.self_attn.q_proj.weight": "model-layer-30.safetensors",
693
+ "model.layers.30.self_attn.q_proj.weight_scale": "model-layer-30.safetensors",
694
+ "model.layers.30.self_attn.kv_a_layernorm.weight": "model-layer-30.safetensors",
695
+ "model.layers.30.mlp.shared_experts.gate_proj.weight": "model-layer-30.safetensors",
696
+ "model.layers.30.mlp.shared_experts.gate_proj.weight_scale": "model-layer-30.safetensors",
697
+ "model.layers.30.mlp.shared_experts.down_proj.weight": "model-layer-30.safetensors",
698
+ "model.layers.30.mlp.shared_experts.down_proj.weight_scale": "model-layer-30.safetensors",
699
+ "model.layers.30.input_layernorm.weight": "model-layer-30.safetensors",
700
+ "model.layers.30.mlp.shared_experts.up_proj.weight": "model-layer-30.safetensors",
701
+ "model.layers.30.mlp.shared_experts.up_proj.weight_scale": "model-layer-30.safetensors",
702
+ "model.layers.30.self_attn.kv_a_proj_with_mqa.weight": "model-layer-30.safetensors",
703
+ "model.layers.30.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-30.safetensors",
704
+ "model.layers.30.mlp.gate.weight": "model-layer-30.safetensors",
705
+ "model.layers.30.self_attn.kv_b_proj.weight": "model-layer-30.safetensors",
706
+ "model.layers.30.self_attn.kv_b_proj.weight_scale": "model-layer-30.safetensors",
707
+ "model.layers.30.post_attention_layernorm.weight": "model-layer-30.safetensors",
708
+ "model.layers.30.self_attn.o_proj.weight": "model-layer-30.safetensors",
709
+ "model.layers.30.self_attn.o_proj.weight_scale": "model-layer-30.safetensors",
710
+ "model.layers.30.mlp.gate.e_score_correction_bias": "model-layer-30.safetensors",
711
+ "model.layers.30.mlp.experts.gate_up_proj": "model-layer-30.safetensors",
712
+ "model.layers.30.mlp.experts.gate_up_proj_scale": "model-layer-30.safetensors",
713
+ "model.layers.30.mlp.experts.down_proj": "model-layer-30.safetensors",
714
+ "model.layers.30.mlp.experts.down_proj_scale": "model-layer-30.safetensors",
715
+ "model.layers.31.self_attn.kv_a_layernorm.weight": "model-layer-31.safetensors",
716
+ "model.layers.31.self_attn.kv_a_proj_with_mqa.weight": "model-layer-31.safetensors",
717
+ "model.layers.31.self_attn.kv_a_proj_with_mqa.weight_scale": "model-layer-31.safetensors",
718
+ "model.layers.31.self_attn.q_proj.weight": "model-layer-31.safetensors",
719
+ "model.layers.31.self_attn.q_proj.weight_scale": "model-layer-31.safetensors",
720
+ "model.layers.31.self_attn.o_proj.weight": "model-layer-31.safetensors",
721
+ "model.layers.31.self_attn.o_proj.weight_scale": "model-layer-31.safetensors",
722
+ "model.layers.31.mlp.shared_experts.gate_proj.weight": "model-layer-31.safetensors",
723
+ "model.layers.31.mlp.shared_experts.gate_proj.weight_scale": "model-layer-31.safetensors",
724
+ "model.layers.31.mlp.shared_experts.down_proj.weight": "model-layer-31.safetensors",
725
+ "model.layers.31.mlp.shared_experts.down_proj.weight_scale": "model-layer-31.safetensors",
726
+ "model.layers.31.post_attention_layernorm.weight": "model-layer-31.safetensors",
727
+ "model.layers.31.mlp.shared_experts.up_proj.weight": "model-layer-31.safetensors",
728
+ "model.layers.31.mlp.shared_experts.up_proj.weight_scale": "model-layer-31.safetensors",
729
+ "model.layers.31.self_attn.kv_b_proj.weight": "model-layer-31.safetensors",
730
+ "model.layers.31.self_attn.kv_b_proj.weight_scale": "model-layer-31.safetensors",
731
+ "model.layers.31.input_layernorm.weight": "model-layer-31.safetensors",
732
+ "model.layers.31.mlp.gate.weight": "model-layer-31.safetensors",
733
+ "model.layers.31.mlp.gate.e_score_correction_bias": "model-layer-31.safetensors",
734
+ "model.layers.31.mlp.experts.gate_up_proj": "model-layer-31.safetensors",
735
+ "model.layers.31.mlp.experts.gate_up_proj_scale": "model-layer-31.safetensors",
736
+ "model.layers.31.mlp.experts.down_proj": "model-layer-31.safetensors",
737
+ "model.layers.31.mlp.experts.down_proj_scale": "model-layer-31.safetensors"
738
+ }
739
+ }
modeling_sarvam_moe.py ADDED
@@ -0,0 +1,1002 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Sarvam AI team. All rights reserved.
2
+ #
3
+ # This code is based on Llama and Deepseek MoE implementations
4
+ # in this library. It has been modified from its original forms to
5
+ # accommodate Sarvam's MLA (multi-latent attention) MoE architecture.
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+
19
+ import math
20
+ import warnings
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.nn.functional as F
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.cache_utils import Cache, DynamicCache
31
+ from transformers.modeling_attn_mask_utils import (
32
+ AttentionMaskConverter,
33
+ _prepare_4d_attention_mask,
34
+ _prepare_4d_causal_attention_mask,
35
+ )
36
+ from transformers.modeling_outputs import (
37
+ BaseModelOutputWithPast,
38
+ CausalLMOutputWithPast,
39
+ )
40
+ from transformers.modeling_utils import PreTrainedModel, ALL_ATTENTION_FUNCTIONS
41
+ from transformers.pytorch_utils import (
42
+ ALL_LAYERNORM_LAYERS,
43
+ is_torch_greater_or_equal_than_1_13,
44
+ )
45
+ from transformers.utils import (
46
+ add_start_docstrings,
47
+ add_start_docstrings_to_model_forward,
48
+ logging,
49
+ replace_return_docstrings,
50
+ )
51
+ from transformers.utils.import_utils import is_torch_fx_available
52
+
53
+ import torch.distributed as dist
54
+ import numpy as np
55
+
56
+ from .configuration_sarvam_moe import SarvamMLAConfig
57
+
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(_prepare_4d_causal_attention_mask)
63
+
64
+
65
+ logger = logging.get_logger(__name__)
66
+
67
+ _CONFIG_FOR_DOC = "SarvamMLAConfig"
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(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
75
+ return (
76
+ indices,
77
+ cu_seqlens,
78
+ max_seqlen_in_batch,
79
+ )
80
+
81
+
82
+ def _get_usable_past_kv_length(cache: Cache, new_seq_length: int, layer_idx: int = 0) -> int:
83
+ previous_length = cache.get_seq_length(layer_idx)
84
+ # Dynamic layers return -1, static layers return an int
85
+ max_length = cache.get_max_cache_shape(layer_idx)
86
+ if max_length is not None and max_length != -1 and previous_length + new_seq_length > max_length:
87
+ return max_length - new_seq_length
88
+ return previous_length
89
+
90
+
91
+ class SarvamMLARMSNorm(nn.Module):
92
+ def __init__(self, hidden_size, eps=1e-6):
93
+ """
94
+ SarvamMLARMSNorm is equivalent to T5LayerNorm
95
+ """
96
+ super().__init__()
97
+ self.weight = nn.Parameter(torch.ones(hidden_size))
98
+ self.variance_epsilon = eps
99
+
100
+ def forward(self, hidden_states):
101
+ input_dtype = hidden_states.dtype
102
+ hidden_states = hidden_states.to(torch.float32)
103
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
104
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
105
+ return self.weight * hidden_states.to(input_dtype)
106
+
107
+
108
+ ALL_LAYERNORM_LAYERS.append(SarvamMLARMSNorm)
109
+
110
+
111
+ class SarvamMLARotaryEmbedding(nn.Module):
112
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
113
+ super().__init__()
114
+
115
+ self.dim = dim
116
+ self.max_position_embeddings = max_position_embeddings
117
+ self.base = base
118
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
119
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
120
+
121
+ self._set_cos_sin_cache(
122
+ seq_len=max_position_embeddings,
123
+ device=self.inv_freq.device,
124
+ dtype=torch.get_default_dtype(),
125
+ )
126
+ self.max_seq_len_cached = None
127
+
128
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
129
+ self.max_seq_len_cached = seq_len
130
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
131
+
132
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
133
+ emb = torch.cat((freqs, freqs), dim=-1)
134
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
135
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
136
+
137
+ def forward(self, x, seq_len=None):
138
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
139
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
140
+
141
+ return (
142
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
143
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
144
+ )
145
+
146
+
147
+ def yarn_find_correction_dim(num_rotations, dim, base=10000, max_position_embeddings=2048):
148
+ return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (2 * math.log(base))
149
+
150
+
151
+ def yarn_find_correction_range(low_rot, high_rot, dim, base=10000, max_position_embeddings=2048):
152
+ low = math.floor(yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings))
153
+ high = math.ceil(yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings))
154
+ return max(low, 0), min(high, dim - 1)
155
+
156
+
157
+ def yarn_get_mscale(scale=1, mscale=1):
158
+ if scale <= 1:
159
+ return 1.0
160
+ return 0.1 * mscale * math.log(scale) + 1.0
161
+
162
+
163
+ def yarn_linear_ramp_mask(min_val, max_val, dim):
164
+ if min_val == max_val:
165
+ max_val += 0.001
166
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min_val) / (max_val - min_val)
167
+ return torch.clamp(linear_func, 0, 1)
168
+
169
+
170
+ class SarvamMLAYarnRotaryEmbedding(SarvamMLARotaryEmbedding):
171
+ def __init__(
172
+ self,
173
+ dim,
174
+ max_position_embeddings=2048,
175
+ base=10000,
176
+ device=None,
177
+ scaling_factor=40.0,
178
+ original_max_position_embeddings=4096,
179
+ beta_fast=32,
180
+ beta_slow=1,
181
+ mscale=1.0,
182
+ mscale_all_dim=1.0,
183
+ ):
184
+ self.scaling_factor = float(scaling_factor)
185
+ self.original_max_position_embeddings = int(original_max_position_embeddings)
186
+ self.beta_fast = float(beta_fast)
187
+ self.beta_slow = float(beta_slow)
188
+ self.mscale = float(mscale)
189
+ self.mscale_all_dim = float(mscale_all_dim)
190
+ super().__init__(dim, max_position_embeddings, base, device)
191
+
192
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
193
+ self.max_seq_len_cached = seq_len
194
+ dim = self.dim
195
+
196
+ freq_extra = 1.0 / (self.base ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim))
197
+ freq_inter = 1.0 / (
198
+ self.scaling_factor * self.base ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
199
+ )
200
+
201
+ low, high = yarn_find_correction_range(
202
+ self.beta_fast,
203
+ self.beta_slow,
204
+ dim,
205
+ self.base,
206
+ self.original_max_position_embeddings,
207
+ )
208
+
209
+ inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(device=device, dtype=torch.float32)
210
+ inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
211
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
212
+
213
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
214
+ freqs = torch.outer(t, inv_freq)
215
+
216
+ _mscale = float(
217
+ yarn_get_mscale(self.scaling_factor, self.mscale)
218
+ / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
219
+ )
220
+
221
+ emb = torch.cat((freqs, freqs), dim=-1)
222
+ self.register_buffer("cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False)
223
+ self.register_buffer("sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False)
224
+
225
+
226
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
227
+ def rotate_half(x):
228
+ """Rotates half the hidden dims of the input."""
229
+ x1 = x[..., : x.shape[-1] // 2]
230
+ x2 = x[..., x.shape[-1] // 2 :]
231
+ return torch.cat((-x2, x1), dim=-1)
232
+
233
+
234
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
235
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
236
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
237
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
238
+
239
+ b, h, s, d = q.shape
240
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
241
+
242
+ b, h, s, d = k.shape
243
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
244
+
245
+ q_embed = (q * cos) + (rotate_half(q) * sin)
246
+ k_embed = (k * cos) + (rotate_half(k) * sin)
247
+ return q_embed, k_embed
248
+
249
+
250
+ class SarvamMLAMLP(nn.Module):
251
+ def __init__(self, config, hidden_size=None, intermediate_size=None):
252
+ super().__init__()
253
+ self.config = config
254
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
255
+ self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
256
+
257
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
258
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
259
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
260
+ self.act_fn = ACT2FN[config.hidden_act]
261
+
262
+ def forward(self, x):
263
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
264
+ return down_proj
265
+
266
+
267
+ class MoEGate(nn.Module):
268
+ def __init__(self, config):
269
+ super().__init__()
270
+ self.config = config
271
+ self.top_k = config.num_experts_per_tok
272
+ self.n_routed_experts = config.num_experts
273
+ self.routed_scaling_factor = config.routed_scaling_factor
274
+ self.scoring_func = "sigmoid"
275
+ self.topk_method = "noaux_tc"
276
+ if (
277
+ getattr(config, "n_group", None) is not None
278
+ or getattr(config, "topk_group", None) is not None
279
+ ):
280
+ raise NotImplementedError(
281
+ "Grouped routing is not supported; n_group and topk_group must both be None"
282
+ )
283
+ self.n_group = None
284
+ self.topk_group = None
285
+ self.use_grouped_topk = False
286
+ if not 1 <= self.top_k <= self.n_routed_experts:
287
+ raise ValueError("num_experts_per_tok must be between 1 and num_experts")
288
+
289
+ self.norm_topk_prob = True
290
+ self.gating_dim = config.hidden_size
291
+ self.weight = nn.Parameter(torch.empty((self.n_routed_experts, self.gating_dim)))
292
+ if self.topk_method == "noaux_tc":
293
+ # This bias only changes discrete expert selection. It is persistent
294
+ # checkpoint state, but does not have a backpropagation gradient.
295
+ self.register_buffer(
296
+ "e_score_correction_bias", torch.empty((self.n_routed_experts)), persistent=True
297
+ )
298
+ self.reset_parameters()
299
+
300
+ def reset_parameters(self) -> None:
301
+ import torch.nn.init as init
302
+
303
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
304
+ if hasattr(self, "e_score_correction_bias"):
305
+ init.zeros_(self.e_score_correction_bias)
306
+
307
+ def forward(self, hidden_states):
308
+ bsz, seq_len, h = hidden_states.shape
309
+ hidden_states = hidden_states.view(-1, h)
310
+ logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32), None)
311
+ if self.scoring_func == "sigmoid":
312
+ scores = logits.sigmoid()
313
+ else:
314
+ raise NotImplementedError(f"insupportable scoring function for MoE gating: {self.scoring_func}")
315
+
316
+ if self.topk_method == "noaux_tc":
317
+ scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)
318
+ _, topk_idx = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)
319
+ topk_weight = scores.gather(1, topk_idx)
320
+ else:
321
+ raise NotImplementedError(f"insupportable TopK function for MoE gating: {self.topk_method}")
322
+
323
+ ### norm gate to sum 1
324
+ if self.top_k > 1 and self.norm_topk_prob:
325
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
326
+ topk_weight = topk_weight / denominator
327
+ topk_weight = topk_weight * self.routed_scaling_factor # must multiply the scaling factor
328
+
329
+ return topk_idx, topk_weight
330
+
331
+
332
+ class SarvamMLAMoE(nn.Module):
333
+ def __init__(self, config):
334
+ super().__init__()
335
+ self.config = config
336
+ self.num_experts_per_tok = config.num_experts_per_tok
337
+
338
+ if hasattr(config, "ep_size") and config.ep_size > 1:
339
+ assert config.ep_size == dist.get_world_size()
340
+ self.ep_size = config.ep_size
341
+ self.experts_per_rank = config.num_experts // config.ep_size
342
+ self.ep_rank = dist.get_rank()
343
+ self.experts = nn.ModuleList(
344
+ [
345
+ (
346
+ SarvamMLAMLP(config, intermediate_size=config.moe_intermediate_size)
347
+ if i >= self.ep_rank * self.experts_per_rank and i < (self.ep_rank + 1) * self.experts_per_rank
348
+ else None
349
+ )
350
+ for i in range(config.num_experts)
351
+ ]
352
+ )
353
+ else:
354
+ self.ep_size = 1
355
+ self.experts_per_rank = config.num_experts
356
+ self.ep_rank = 0
357
+ self.experts = nn.ModuleList(
358
+ [
359
+ SarvamMLAMLP(config, intermediate_size=config.moe_intermediate_size)
360
+ for i in range(config.num_experts)
361
+ ]
362
+ )
363
+ self.gate = MoEGate(config)
364
+ if (
365
+ hasattr(config, "num_shared_experts")
366
+ and config.num_shared_experts is not None
367
+ and config.num_shared_experts > 0
368
+ ):
369
+ intermediate_size = config.moe_intermediate_size * config.num_shared_experts
370
+ self.shared_experts = SarvamMLAMLP(config=config, intermediate_size=intermediate_size)
371
+ else:
372
+ self.shared_experts = None
373
+
374
+ def forward(self, hidden_states):
375
+ identity = hidden_states
376
+ orig_shape = hidden_states.shape
377
+ topk_idx, topk_weight = self.gate(hidden_states)
378
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
379
+ if not self.training:
380
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
381
+ else:
382
+ y = self.moe_train(hidden_states, topk_idx, topk_weight).view(*orig_shape)
383
+ if self.shared_experts is not None:
384
+ y = y + self.shared_experts(identity)
385
+ return y
386
+
387
+ def moe_train(self, x, topk_ids, topk_weight):
388
+ if self.ep_size > 1:
389
+ raise NotImplementedError(
390
+ "Expert-parallel MoE training requires autograd-aware all-to-all collectives; "
391
+ "the current distributed inference dispatch is not differentiable"
392
+ )
393
+ return self._moe_dispatch(x, topk_ids, topk_weight)
394
+
395
+ @torch.no_grad()
396
+ def moe_infer(self, x, topk_ids, topk_weight):
397
+ return self._moe_dispatch(x, topk_ids, topk_weight)
398
+
399
+ def _moe_dispatch(self, x, topk_ids, topk_weight):
400
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
401
+ cnts.scatter_(1, topk_ids, 1)
402
+ tokens_per_expert = cnts.sum(dim=0)
403
+ idxs = topk_ids.view(-1).argsort()
404
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
405
+ sorted_tokens_shape = sorted_tokens.shape
406
+ if self.ep_size > 1:
407
+ tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1)
408
+ tokens_per_expert_group = tokens_per_expert.new_empty(tokens_per_expert.shape[0])
409
+ dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
410
+ output_splits = tokens_per_expert_group.view(self.ep_size, -1).sum(1).cpu().numpy().tolist()
411
+ gathered_tokens = sorted_tokens.new_empty(
412
+ tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1]
413
+ )
414
+ input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
415
+ dist.all_to_all(
416
+ list(gathered_tokens.split(output_splits)),
417
+ list(sorted_tokens.split(input_split_sizes)),
418
+ )
419
+ tokens_per_expert_post_gather = tokens_per_expert_group.view(self.ep_size, self.experts_per_rank).sum(dim=0)
420
+ gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32)
421
+ s = 0
422
+ for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
423
+ gatherd_idxs[s : s + k] = i % self.experts_per_rank
424
+ s += k
425
+ gatherd_idxs = gatherd_idxs.argsort()
426
+ sorted_tokens = gathered_tokens[gatherd_idxs]
427
+ tokens_per_expert = tokens_per_expert_post_gather
428
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
429
+
430
+ outputs = []
431
+ start_idx = 0
432
+ for i, num_tokens in enumerate(tokens_per_expert):
433
+ end_idx = start_idx + num_tokens
434
+ if num_tokens == 0:
435
+ continue
436
+ expert = self.experts[i + self.ep_rank * self.experts_per_rank]
437
+ if expert is None:
438
+ continue
439
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
440
+ expert_out = expert(tokens_for_this_expert)
441
+ outputs.append(expert_out)
442
+ start_idx = end_idx
443
+
444
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
445
+ if self.ep_size > 1:
446
+ new_x = torch.empty_like(outs)
447
+ new_x[gatherd_idxs] = outs
448
+ gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
449
+ dist.all_to_all(
450
+ list(gathered_tokens.split(input_split_sizes)),
451
+ list(new_x.split(output_splits)),
452
+ )
453
+ outs = gathered_tokens
454
+
455
+ new_x = torch.empty_like(outs)
456
+ new_x[idxs] = outs
457
+ final_out = (
458
+ new_x.view(*topk_ids.shape, -1)
459
+ .type(topk_weight.dtype)
460
+ .mul_(topk_weight.unsqueeze(dim=-1))
461
+ .sum(dim=1)
462
+ .type(new_x.dtype)
463
+ )
464
+ return final_out
465
+
466
+
467
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
468
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
469
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
470
+ if n_rep == 1:
471
+ return hidden_states
472
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
473
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
474
+
475
+
476
+ class SarvamMLAAttention(nn.Module):
477
+ is_causal = True
478
+ def __init__(self, config: SarvamMLAConfig, layer_idx: Optional[int] = None):
479
+ super().__init__()
480
+ self.config = config
481
+ self.layer_idx = layer_idx
482
+ if layer_idx is None:
483
+ logger.warning_once(
484
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
485
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
486
+ "when creating this class."
487
+ )
488
+
489
+ self.attention_dropout = config.attention_dropout
490
+ self.hidden_size = config.hidden_size
491
+ self.num_heads = config.num_attention_heads
492
+
493
+ self.max_position_embeddings = config.max_position_embeddings
494
+ self.rope_theta = config.rope_theta
495
+ self.q_lora_rank = getattr(config, "q_lora_rank", None)
496
+ self.qk_rope_head_dim = config.qk_rope_head_dim
497
+ self.kv_lora_rank = config.kv_lora_rank
498
+ self.v_head_dim = config.v_head_dim
499
+ self.qk_nope_head_dim = config.qk_nope_head_dim
500
+ self.q_head_dim = config.q_head_dim
501
+
502
+ if self.q_lora_rank is None:
503
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.q_head_dim, bias=False)
504
+ else:
505
+ self.q_a_proj = nn.Linear(
506
+ self.hidden_size, config.q_lora_rank, bias=getattr(config, "attention_bias", False)
507
+ )
508
+ self.q_a_layernorm = SarvamMLARMSNorm(config.q_lora_rank)
509
+ self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False)
510
+
511
+ self.kv_a_proj_with_mqa = nn.Linear(
512
+ self.hidden_size,
513
+ config.kv_lora_rank + config.qk_rope_head_dim,
514
+ bias=getattr(config, "attention_bias", False),
515
+ )
516
+ self.kv_a_layernorm = SarvamMLARMSNorm(config.kv_lora_rank)
517
+ self.kv_b_proj = nn.Linear(
518
+ config.kv_lora_rank,
519
+ self.num_heads * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
520
+ bias=False,
521
+ )
522
+
523
+ self.o_proj = nn.Linear(
524
+ self.num_heads * self.v_head_dim,
525
+ self.hidden_size,
526
+ bias=getattr(config, "attention_bias", False),
527
+ )
528
+ self._init_rope()
529
+
530
+ self.softmax_scale = self.q_head_dim ** (-0.5)
531
+ if self.config.rope_scaling is not None:
532
+ mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
533
+ scaling_factor = self.config.rope_scaling["factor"]
534
+ if mscale_all_dim:
535
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
536
+ self.softmax_scale = self.softmax_scale * mscale * mscale
537
+
538
+ def _init_rope(self):
539
+ rope_scaling = getattr(self.config, "rope_scaling", None)
540
+ if rope_scaling is None or rope_scaling.get("type", None) in (None, "default"):
541
+ self.rotary_emb = SarvamMLARotaryEmbedding(
542
+ self.qk_rope_head_dim,
543
+ max_position_embeddings=self.max_position_embeddings,
544
+ base=self.rope_theta,
545
+ )
546
+ return
547
+
548
+ rope_type = rope_scaling.get("type")
549
+ if rope_type == "deepseek_yarn":
550
+ self.rotary_emb = SarvamMLAYarnRotaryEmbedding(
551
+ self.qk_rope_head_dim,
552
+ max_position_embeddings=self.max_position_embeddings,
553
+ base=self.rope_theta,
554
+ scaling_factor=rope_scaling.get("factor", 40.0),
555
+ original_max_position_embeddings=rope_scaling.get("original_max_position_embeddings", 4096),
556
+ beta_fast=rope_scaling.get("beta_fast", 32),
557
+ beta_slow=rope_scaling.get("beta_slow", 1),
558
+ mscale=rope_scaling.get("mscale", 1.0),
559
+ mscale_all_dim=rope_scaling.get("mscale_all_dim", 1.0),
560
+ )
561
+ return
562
+ raise ValueError(f"Unknown rope_scaling type: {rope_type}")
563
+
564
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
565
+ return tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim).transpose(1, 2).contiguous()
566
+
567
+ def forward(
568
+ self,
569
+ hidden_states: torch.Tensor,
570
+ attention_mask: Optional[torch.Tensor] = None,
571
+ position_ids: Optional[torch.LongTensor] = None,
572
+ past_key_value: Optional[Cache] = None,
573
+ output_attentions: bool = False,
574
+ use_cache: bool = False,
575
+ **kwargs,
576
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
577
+ bsz, q_len, _ = hidden_states.size()
578
+
579
+ if self.q_lora_rank is None:
580
+ q = self.q_proj(hidden_states)
581
+ else:
582
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
583
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
584
+ q_nope, q_pe = torch.split(q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
585
+
586
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
587
+ compressed_kv, k_pe = torch.split(compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
588
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
589
+ kv = (
590
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
591
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
592
+ .transpose(1, 2)
593
+ )
594
+
595
+ k_nope, value_states = torch.split(kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
596
+ kv_seq_len = value_states.shape[-2]
597
+ if past_key_value is not None:
598
+ if self.layer_idx is None:
599
+ raise ValueError(
600
+ f"The cache structure has changed in a previous version. If you are using {self.__class__.__name__} "
601
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
602
+ "with a layer index."
603
+ )
604
+ kv_seq_len += _get_usable_past_kv_length(past_key_value, kv_seq_len, self.layer_idx)
605
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
606
+
607
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
608
+
609
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
610
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
611
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
612
+
613
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
614
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
615
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
616
+ if past_key_value is not None:
617
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
618
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
619
+
620
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.softmax_scale
621
+
622
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
623
+ raise ValueError(
624
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
625
+ f" {attn_weights.size()}"
626
+ )
627
+ assert attention_mask is not None
628
+ if attention_mask is not None:
629
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
630
+ raise ValueError(
631
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
632
+ )
633
+ attn_weights = attn_weights + attention_mask
634
+
635
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
636
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
637
+ attn_output = torch.matmul(attn_weights, value_states)
638
+
639
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
640
+ raise ValueError(
641
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
642
+ f" {attn_output.size()}"
643
+ )
644
+ attn_output = attn_output.transpose(1, 2).contiguous()
645
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
646
+ attn_output = self.o_proj(attn_output)
647
+
648
+ if not output_attentions:
649
+ attn_weights = None
650
+
651
+ return attn_output, attn_weights, past_key_value
652
+
653
+
654
+ class SarvamMLADecoderLayer(nn.Module):
655
+ def __init__(self, config: SarvamMLAConfig, layer_idx: int):
656
+ super().__init__()
657
+ self.hidden_size = config.hidden_size
658
+ self.self_attn = SarvamMLAAttention(config=config, layer_idx=layer_idx)
659
+
660
+ use_moe = (
661
+ hasattr(config, "num_experts")
662
+ and config.num_experts is not None
663
+ and layer_idx >= getattr(config, "first_k_dense_replace", 0)
664
+ and layer_idx % getattr(config, "moe_layer_freq", 1) == 0
665
+ )
666
+
667
+ self.mlp = SarvamMLAMoE(config) if use_moe else SarvamMLAMLP(config)
668
+ self.input_layernorm = SarvamMLARMSNorm(config.hidden_size, eps=config.rms_norm_eps)
669
+ self.post_attention_layernorm = SarvamMLARMSNorm(config.hidden_size, eps=config.rms_norm_eps)
670
+
671
+ def forward(
672
+ self,
673
+ hidden_states: torch.Tensor,
674
+ attention_mask: Optional[torch.Tensor] = None,
675
+ position_ids: Optional[torch.LongTensor] = None,
676
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
677
+ output_attentions: Optional[bool] = False,
678
+ use_cache: Optional[bool] = False,
679
+ **kwargs,
680
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
681
+ residual = hidden_states
682
+ hidden_states = self.input_layernorm(hidden_states)
683
+
684
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
685
+ hidden_states=hidden_states,
686
+ attention_mask=attention_mask,
687
+ position_ids=position_ids,
688
+ past_key_value=past_key_value,
689
+ output_attentions=output_attentions,
690
+ use_cache=use_cache,
691
+ **kwargs,
692
+ )
693
+ hidden_states = residual + hidden_states
694
+
695
+ residual = hidden_states
696
+ hidden_states = self.post_attention_layernorm(hidden_states)
697
+ hidden_states = self.mlp(hidden_states)
698
+ hidden_states = residual + hidden_states
699
+
700
+ outputs = (hidden_states,)
701
+
702
+ if output_attentions:
703
+ outputs += (self_attn_weights,)
704
+ if use_cache:
705
+ outputs += (present_key_value,)
706
+ return outputs
707
+
708
+
709
+ class SarvamMLAPreTrainedModel(PreTrainedModel):
710
+ config_class = SarvamMLAConfig
711
+ base_model_prefix = "model"
712
+ supports_gradient_checkpointing = True
713
+ _no_split_modules = ["SarvamMLADecoderLayer"]
714
+ _skip_keys_device_placement = "past_key_values"
715
+ _supports_flash_attn_2 = False # Not implemented yet
716
+ _supports_cache_class = True
717
+
718
+ def _init_weights(self, module):
719
+ std = self.config.initializer_range
720
+ if isinstance(module, nn.Linear):
721
+ module.weight.data.normal_(mean=0.0, std=std)
722
+ if module.bias is not None:
723
+ module.bias.data.zero_()
724
+ elif isinstance(module, nn.Embedding):
725
+ module.weight.data.normal_(mean=0.0, std=std)
726
+ if module.padding_idx is not None:
727
+ module.weight.data[module.padding_idx].zero_()
728
+
729
+
730
+ class SarvamMLAModel(SarvamMLAPreTrainedModel):
731
+ def __init__(self, config: SarvamMLAConfig):
732
+ super().__init__(config)
733
+ self.padding_idx = config.pad_token_id
734
+ self.vocab_size = config.vocab_size
735
+
736
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
737
+ self.layers = nn.ModuleList(
738
+ [SarvamMLADecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
739
+ )
740
+ self._use_flash_attention_2 = False # Not implemented yet
741
+ self.norm = SarvamMLARMSNorm(config.hidden_size, eps=config.rms_norm_eps)
742
+
743
+ self.gradient_checkpointing = False
744
+ # Initialize weights and apply final processing
745
+ self.post_init()
746
+
747
+ def get_input_embeddings(self):
748
+ return self.embed_tokens
749
+
750
+ def set_input_embeddings(self, value):
751
+ self.embed_tokens = value
752
+
753
+ def forward(
754
+ self,
755
+ input_ids: torch.LongTensor = None,
756
+ attention_mask: Optional[torch.Tensor] = None,
757
+ position_ids: Optional[torch.LongTensor] = None,
758
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
759
+ inputs_embeds: Optional[torch.FloatTensor] = None,
760
+ use_cache: Optional[bool] = None,
761
+ output_attentions: Optional[bool] = None,
762
+ output_hidden_states: Optional[bool] = None,
763
+ return_dict: Optional[bool] = None,
764
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
765
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
766
+ output_hidden_states = (
767
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
768
+ )
769
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
770
+
771
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
772
+
773
+ # retrieve input_ids and inputs_embeds
774
+ if input_ids is not None and inputs_embeds is not None:
775
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
776
+ elif input_ids is not None:
777
+ batch_size, seq_length = input_ids.shape[:2]
778
+ elif inputs_embeds is not None:
779
+ batch_size, seq_length = inputs_embeds.shape[:2]
780
+ else:
781
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
782
+
783
+ past_key_values_length = 0
784
+ if use_cache:
785
+ use_legacy_cache = not isinstance(past_key_values, Cache)
786
+ if use_legacy_cache:
787
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
788
+ past_key_values_length = _get_usable_past_kv_length(past_key_values, seq_length)
789
+
790
+ if position_ids is None:
791
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
792
+ position_ids = torch.arange(
793
+ past_key_values_length,
794
+ seq_length + past_key_values_length,
795
+ dtype=torch.long,
796
+ device=device,
797
+ )
798
+ position_ids = position_ids.unsqueeze(0)
799
+
800
+ if inputs_embeds is None:
801
+ inputs_embeds = self.embed_tokens(input_ids)
802
+
803
+ attention_mask = _prepare_4d_causal_attention_mask(
804
+ attention_mask,
805
+ (batch_size, seq_length),
806
+ inputs_embeds,
807
+ past_key_values_length,
808
+ )
809
+
810
+ hidden_states = inputs_embeds
811
+ all_hidden_states = () if output_hidden_states else None
812
+ all_self_attns = () if output_attentions else None
813
+ next_decoder_cache = None
814
+
815
+ for decoder_layer in self.layers:
816
+ if output_hidden_states:
817
+ all_hidden_states += (hidden_states,)
818
+
819
+ layer_outputs = decoder_layer(
820
+ hidden_states,
821
+ attention_mask=attention_mask,
822
+ position_ids=position_ids,
823
+ past_key_value=past_key_values,
824
+ output_attentions=output_attentions,
825
+ use_cache=use_cache,
826
+ )
827
+
828
+ hidden_states = layer_outputs[0]
829
+ if use_cache:
830
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
831
+ if output_attentions:
832
+ all_self_attns += (layer_outputs[1],)
833
+
834
+ hidden_states = self.norm(hidden_states)
835
+
836
+ if output_hidden_states:
837
+ all_hidden_states += (hidden_states,)
838
+
839
+ next_cache = None
840
+ if use_cache:
841
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
842
+ if not return_dict:
843
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
844
+ return BaseModelOutputWithPast(
845
+ last_hidden_state=hidden_states,
846
+ past_key_values=next_cache,
847
+ hidden_states=all_hidden_states,
848
+ attentions=all_self_attns,
849
+ )
850
+
851
+
852
+ class SarvamMLAForCausalLM(SarvamMLAPreTrainedModel):
853
+ _tied_weights_keys = ["lm_head.weight"]
854
+
855
+ def __init__(self, config):
856
+ super().__init__(config)
857
+ self.model = SarvamMLAModel(config)
858
+ self.vocab_size = config.vocab_size
859
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
860
+ self.post_init()
861
+
862
+ def get_input_embeddings(self):
863
+ return self.model.embed_tokens
864
+
865
+ def set_input_embeddings(self, value):
866
+ self.model.embed_tokens = value
867
+
868
+ def get_output_embeddings(self):
869
+ return self.lm_head
870
+
871
+ def set_output_embeddings(self, new_embeddings):
872
+ self.lm_head = new_embeddings
873
+
874
+ def set_decoder(self, decoder):
875
+ self.model = decoder
876
+
877
+ def get_decoder(self):
878
+ return self.model
879
+
880
+ def forward(
881
+ self,
882
+ input_ids: torch.LongTensor = None,
883
+ attention_mask: Optional[torch.Tensor] = None,
884
+ position_ids: Optional[torch.LongTensor] = None,
885
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
886
+ inputs_embeds: Optional[torch.FloatTensor] = None,
887
+ labels: Optional[torch.LongTensor] = None,
888
+ use_cache: Optional[bool] = None,
889
+ output_attentions: Optional[bool] = None,
890
+ output_hidden_states: Optional[bool] = None,
891
+ return_dict: Optional[bool] = None,
892
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
893
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
894
+ output_hidden_states = (
895
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
896
+ )
897
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
898
+
899
+ outputs = self.model(
900
+ input_ids=input_ids,
901
+ attention_mask=attention_mask,
902
+ position_ids=position_ids,
903
+ past_key_values=past_key_values,
904
+ inputs_embeds=inputs_embeds,
905
+ use_cache=use_cache,
906
+ output_attentions=output_attentions,
907
+ output_hidden_states=output_hidden_states,
908
+ return_dict=return_dict,
909
+ )
910
+
911
+ hidden_states = outputs[0]
912
+ logits = self.lm_head(hidden_states)
913
+ logits = logits.float()
914
+
915
+ loss = None
916
+ if labels is not None:
917
+ # Shift so that tokens < n predict n
918
+ shift_logits = logits[..., :-1, :].contiguous()
919
+ shift_labels = labels[..., 1:].contiguous()
920
+ # Flatten the tokens
921
+ loss_fct = CrossEntropyLoss()
922
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
923
+ shift_labels = shift_labels.view(-1)
924
+ # Enable model parallelism
925
+ shift_labels = shift_labels.to(shift_logits.device)
926
+ loss = loss_fct(shift_logits, shift_labels)
927
+
928
+ if not return_dict:
929
+ output = (logits,) + outputs[1:]
930
+ return (loss,) + output if loss is not None else output
931
+
932
+ return CausalLMOutputWithPast(
933
+ loss=loss,
934
+ logits=logits,
935
+ past_key_values=outputs.past_key_values,
936
+ hidden_states=outputs.hidden_states,
937
+ attentions=outputs.attentions,
938
+ )
939
+
940
+ def prepare_inputs_for_generation(
941
+ self,
942
+ input_ids,
943
+ past_key_values=None,
944
+ attention_mask=None,
945
+ inputs_embeds=None,
946
+ **kwargs,
947
+ ):
948
+ if past_key_values is not None:
949
+ if isinstance(past_key_values, Cache):
950
+ cache_length = past_key_values.get_seq_length()
951
+ past_length = past_key_values.get_seq_length() if past_key_values is not None else 0
952
+ if hasattr(past_key_values, "get_max_length"):
953
+ max_cache_length = past_key_values.get_max_length()
954
+ else:
955
+ max_cache_length = None
956
+ else:
957
+ cache_length = past_length = past_key_values[0][0].shape[2]
958
+ max_cache_length = None
959
+
960
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
961
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
962
+ elif past_length < input_ids.shape[1]:
963
+ input_ids = input_ids[:, past_length:]
964
+
965
+ if (
966
+ max_cache_length is not None
967
+ and attention_mask is not None
968
+ and cache_length + input_ids.shape[1] > max_cache_length
969
+ ):
970
+ attention_mask = attention_mask[:, -max_cache_length:]
971
+
972
+ position_ids = kwargs.get("position_ids", None)
973
+ if attention_mask is not None and position_ids is None:
974
+ position_ids = attention_mask.long().cumsum(-1) - 1
975
+ position_ids.masked_fill_(attention_mask == 0, 1)
976
+ if past_key_values:
977
+ position_ids = position_ids[:, -input_ids.shape[1] :]
978
+
979
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
980
+ if inputs_embeds is not None and past_key_values is None:
981
+ model_inputs = {"inputs_embeds": inputs_embeds}
982
+ else:
983
+ model_inputs = {"input_ids": input_ids}
984
+
985
+ model_inputs.update(
986
+ {
987
+ "position_ids": position_ids,
988
+ "past_key_values": past_key_values,
989
+ "use_cache": kwargs.get("use_cache"),
990
+ "attention_mask": attention_mask,
991
+ }
992
+ )
993
+ return model_inputs
994
+
995
+ @staticmethod
996
+ def _reorder_cache(past_key_values, beam_idx):
997
+ reordered_past = ()
998
+ for layer_past in past_key_values:
999
+ reordered_past += (
1000
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1001
+ )
1002
+ return reordered_past
prism.py ADDED
@@ -0,0 +1,624 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sarvam-Prism inference (FP8, one GPU).
2
+
3
+ Prism reads a context (the "state") and one or more typed questions, and returns a probability for every option of
4
+ every question in a single forward pass. It generates no text.
5
+
6
+ from prism import Prism
7
+ model = Prism.from_pretrained("sarvamai/prism")
8
+ model.decide(state={"ticket": "I was charged twice."},
9
+ questions={"team": {"type": "choice", "instructions": "Route this ticket.",
10
+ "criteria": {"billing": "payments and refunds", "tech": "app problems"}}})
11
+
12
+ Question types:
13
+ choice criteria: {key: description or None} -> {"choice": key, "probabilities": {key: p}}
14
+ yes_no no criteria -> {"yes": p}
15
+ score criteria: [level, ...] or {key: level} -> {"score": expected level index, "level": key,
16
+ "probabilities": {key: p}}
17
+
18
+ The weights are stored in FP8 (float8_e4m3fn, one scale per output row). Matrix multiplications run in FP8 with
19
+ per-token activation scales: torch._scaled_mm for the dense projections and a Triton grouped kernel for the 128
20
+ routed experts. Small and medium batches replay captured CUDA graphs; larger ones run eagerly, with attention split
21
+ into an unmasked part (the context) and a masked part (options and answer).
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import gc
26
+ import json
27
+ import math
28
+ import os
29
+ import sys
30
+ import types
31
+ from dataclasses import dataclass
32
+
33
+ import torch
34
+ import torch.nn as nn
35
+ import torch.nn.functional as F
36
+ import triton
37
+ import triton.language as tl
38
+ from torch.nn.attention import SDPBackend, sdpa_kernel
39
+
40
+ F8, F8_MAX = torch.float8_e4m3fn, 448.0
41
+
42
+ # ---------------------------------------------------------------------------------------------------------------------
43
+ # Input encoding
44
+ # ---------------------------------------------------------------------------------------------------------------------
45
+ # Each question becomes one sequence:
46
+ # State: <state>\nQuestion: <instructions>\n<option>A</option>\n<option>B</option> ...\nAnswer:
47
+ # Every option starts at the same position id and cannot see the other options, so the result does not depend on where
48
+ # an option sits in the list. Only the final "Answer:" token sees every option.
49
+
50
+ TAGS = {"state": "State:", "question": "\nQuestion:", "open": "\n<option>", "close": "</option>", "answer": "\nAnswer:"}
51
+ CONTEXT, ANSWER_ROLE, PAD = -1, -2, -3 # per-token role; 0..K-1 = index of the option the token belongs to
52
+ SEG_STATE, SEG_QUESTION, SEG_OPTION, SEG_ANSWER = range(4) # segment ids for the learned segment embedding
53
+ TYPES = {"choice": 0, "yes_no": 1, "score": 2}
54
+
55
+
56
+ def _text(x):
57
+ return x if isinstance(x, str) else json.dumps(x, ensure_ascii=False, separators=(",", ":"))
58
+
59
+
60
+ @dataclass
61
+ class Encoded:
62
+ ids: list
63
+ pos: list
64
+ role: list
65
+ seg: list
66
+ close_idx: list
67
+ answer_idx: int
68
+ n_context: int
69
+
70
+
71
+ class Encoder:
72
+ def __init__(self, tok):
73
+ self.tok = tok
74
+ self.tags = {k: tok(v, add_special_tokens=False).input_ids for k, v in TAGS.items()}
75
+
76
+ def _ids(self, s):
77
+ for t in ("</option>", "<option>"): # user text never spells an option tag
78
+ s = s.replace(t, t.replace("<", "‹"))
79
+ return self.tok(s, add_special_tokens=False).input_ids
80
+
81
+ def __call__(self, state: str, instructions: str, options: list) -> Encoded:
82
+ t = self.tags
83
+ ids = t["state"] + self._ids(" " + state)
84
+ seg = [SEG_STATE] * len(ids)
85
+ q = t["question"] + self._ids(" " + instructions)
86
+ ids += q
87
+ seg += [SEG_QUESTION] * len(q)
88
+ role, pos = [CONTEXT] * len(ids), list(range(len(ids)))
89
+ p0, close, longest = len(ids), [], 0
90
+ for j, o in enumerate(options):
91
+ span = t["open"] + self._ids(o) + t["close"]
92
+ ids += span
93
+ role += [j] * len(span)
94
+ seg += [SEG_OPTION] * len(span)
95
+ pos += range(p0, p0 + len(span))
96
+ close.append(len(ids) - 1)
97
+ longest = max(longest, len(span))
98
+ a, p1 = t["answer"], p0 + longest # "Answer:" starts after the longest option
99
+ ids += a
100
+ role += [ANSWER_ROLE] * len(a)
101
+ seg += [SEG_ANSWER] * len(a)
102
+ pos += range(p1, p1 + len(a))
103
+ return Encoded(ids, pos, role, seg, close, len(ids) - 1, p0)
104
+
105
+
106
+ def attention_mask(roles, L, device, dtype):
107
+ """Additive [B, 1, L, L] mask (0 = attend). Causal, except: the context (state + question) attends to the whole
108
+ context, and each option attends to the context and its whole self. Options never see each other; the answer tokens
109
+ see everything before them. Padding is never attended to."""
110
+ r = torch.full((len(roles), L), PAD, device=device)
111
+ for b, x in enumerate(roles):
112
+ if len(x):
113
+ r[b, : len(x)] = torch.tensor(x, device=device)
114
+ rq, rk = r[:, :, None], r[:, None, :]
115
+ causal = torch.tril(torch.ones(L, L, dtype=torch.bool, device=device))[None]
116
+ allow = causal & (rk != PAD) & ((rk < 0) | (rq == ANSWER_ROLE) | (rq == rk))
117
+ allow |= (rq == rk) & ((rq == CONTEXT) | (rq >= 0)) # bidirectional inside the context and inside each option
118
+ allow |= torch.eye(L, dtype=torch.bool, device=device)[None]
119
+ return torch.zeros(len(roles), 1, L, L, device=device, dtype=dtype).masked_fill(~allow[:, None], torch.finfo(dtype).min)
120
+
121
+
122
+ def to_options(q):
123
+ """A question -> (type, option keys, option texts). Choice options are scored in a fixed order (sorted by key), so
124
+ the same set of options always gives the same answer whatever order it is sent in."""
125
+ kind = q["type"]
126
+ if kind == "choice":
127
+ items = sorted(q["criteria"].items(), key=lambda kv: str(kv[0]))
128
+ keys, opts = [k for k, _ in items], []
129
+ for k, v in items:
130
+ v = None if v is None else _text(v)
131
+ opts.append(f"{k}: {v}" if v and v != k else str(k))
132
+ return kind, keys, opts
133
+ if kind == "yes_no":
134
+ return kind, ["no", "yes"], ["no", "yes"]
135
+ if kind == "score":
136
+ c = q["criteria"]
137
+ keys = [str(i) for i in range(len(c))] if isinstance(c, list) else list(c)
138
+ levels = [_text(v) for v in (c if isinstance(c, list) else c.values())]
139
+ return kind, keys, [f"{i}: {lvl}" for i, lvl in enumerate(levels)]
140
+ raise ValueError(f"unknown question type {q['type']!r} (choice, yes_no or score)")
141
+
142
+
143
+ # ---------------------------------------------------------------------------------------------------------------------
144
+ # Decision head: [question type, option_1..K, answer] -> two self-attention blocks -> one score per option
145
+ # ---------------------------------------------------------------------------------------------------------------------
146
+ class AttnBlock(nn.Module):
147
+ def __init__(self, d, dh):
148
+ super().__init__()
149
+ self.n1, self.n2 = nn.LayerNorm(d), nn.LayerNorm(d)
150
+ self.q, self.k, self.v, self.o = nn.Linear(d, dh), nn.Linear(d, dh), nn.Linear(d, dh), nn.Linear(dh, d)
151
+ self.mlp = nn.Sequential(nn.Linear(d, dh), nn.GELU(), nn.Linear(dh, d))
152
+ self.scale = 1 / math.sqrt(dh)
153
+
154
+ def forward(self, x):
155
+ y = self.n1(x)
156
+ x = x + self.o(F.softmax(self.q(y) @ self.k(y).T * self.scale, -1) @ self.v(y))
157
+ return x + self.mlp(self.n2(x))
158
+
159
+
160
+ class DecisionHead(nn.Module):
161
+ def __init__(self, d, dh=512, layers=2):
162
+ super().__init__()
163
+ self.task = nn.Embedding(len(TYPES), d)
164
+ self.norm_in, self.norm_out = nn.LayerNorm(d), nn.LayerNorm(d)
165
+ self.blocks = nn.ModuleList(AttnBlock(d, dh) for _ in range(layers))
166
+ self.pd, self.po = nn.Linear(d, dh), nn.Linear(d, dh)
167
+ self.scale = 1 / math.sqrt(dh)
168
+
169
+ def forward(self, h_answer, h_opts, qtype):
170
+ x = self.norm_in(torch.cat([self.task.weight[TYPES[qtype]][None], h_opts, h_answer[None]]))
171
+ for b in self.blocks:
172
+ x = b(x)
173
+ x = self.norm_out(x)
174
+ return self.po(x[1:-1]) @ self.pd(x[-1]) * self.scale
175
+
176
+
177
+ # ---------------------------------------------------------------------------------------------------------------------
178
+ # FP8 kernels
179
+ # ---------------------------------------------------------------------------------------------------------------------
180
+ @triton.jit
181
+ def _q_rows_kernel(X, Q, S, M, K, s_x, s_q, BM: tl.constexpr, BK: tl.constexpr):
182
+ """Per-row FP8 quantization: s = absmax / 448, q = x / s."""
183
+ pid = tl.program_id(0)
184
+ rm = pid * BM + tl.arange(0, BM); mm = rm < M
185
+ rm64 = rm.to(tl.int64)
186
+ amax = tl.zeros((BM,), dtype=tl.float32)
187
+ for k0 in range(0, K, BK):
188
+ rk = k0 + tl.arange(0, BK)
189
+ x = tl.load(X + rm64[:, None] * s_x + rk[None, :], mask=mm[:, None] & (rk[None, :] < K), other=0.0).to(tl.float32)
190
+ amax = tl.maximum(amax, tl.max(tl.abs(x), axis=1))
191
+ s = tl.maximum(amax / 448.0, 1e-12)
192
+ for k0 in range(0, K, BK):
193
+ rk = k0 + tl.arange(0, BK)
194
+ mk = mm[:, None] & (rk[None, :] < K)
195
+ x = tl.load(X + rm64[:, None] * s_x + rk[None, :], mask=mk, other=0.0).to(tl.float32)
196
+ tl.store(Q + rm64[:, None] * s_q + rk[None, :], (x / s[:, None]).to(tl.float8e4nv), mask=mk)
197
+ tl.store(S + rm64, s, mask=mm)
198
+
199
+
200
+ @triton.jit
201
+ def _gather_q_rows_kernel(X, SRC, Q, S, M, K, s_x, s_q, BM: tl.constexpr, BK: tl.constexpr):
202
+ """Row r of the output = FP8 quantization of X[SRC[r]] (tokens gathered into expert order)."""
203
+ pid = tl.program_id(0)
204
+ rm = pid * BM + tl.arange(0, BM); mm = rm < M
205
+ src = tl.load(SRC + rm, mask=mm, other=0).to(tl.int64)
206
+ amax = tl.zeros((BM,), dtype=tl.float32)
207
+ for k0 in range(0, K, BK):
208
+ rk = k0 + tl.arange(0, BK)
209
+ x = tl.load(X + src[:, None] * s_x + rk[None, :], mask=mm[:, None], other=0.0).to(tl.float32)
210
+ amax = tl.maximum(amax, tl.max(tl.abs(x), axis=1))
211
+ s = tl.maximum(amax / 448.0, 1e-12)
212
+ rm64 = rm.to(tl.int64)
213
+ for k0 in range(0, K, BK):
214
+ rk = k0 + tl.arange(0, BK)
215
+ x = tl.load(X + src[:, None] * s_x + rk[None, :], mask=mm[:, None], other=0.0).to(tl.float32)
216
+ tl.store(Q + rm64[:, None] * s_q + rk[None, :], (x / s[:, None]).to(tl.float8e4nv), mask=mm[:, None])
217
+ tl.store(S + rm64, s, mask=mm)
218
+
219
+
220
+ @triton.jit
221
+ def _swiglu_q_rows_kernel(Hh, Q, S, M, I, s_h, s_q, BM: tl.constexpr, BK: tl.constexpr):
222
+ """out = FP8 quantization of silu(g) * u for h = [g | u], with bf16 rounding where PyTorch would round."""
223
+ pid = tl.program_id(0)
224
+ rm = pid * BM + tl.arange(0, BM); mm = rm < M
225
+ rm64 = rm.to(tl.int64)
226
+ amax = tl.zeros((BM,), dtype=tl.float32)
227
+ for k0 in range(0, I, BK):
228
+ rk = k0 + tl.arange(0, BK)
229
+ g = tl.load(Hh + rm64[:, None] * s_h + rk[None, :], mask=mm[:, None], other=0.0).to(tl.float32)
230
+ u = tl.load(Hh + rm64[:, None] * s_h + I + rk[None, :], mask=mm[:, None], other=0.0).to(tl.float32)
231
+ x = ((g / (1.0 + tl.exp(-g))).to(tl.bfloat16).to(tl.float32) * u).to(tl.bfloat16).to(tl.float32)
232
+ amax = tl.maximum(amax, tl.max(tl.abs(x), axis=1))
233
+ s = tl.maximum(amax / 448.0, 1e-12)
234
+ for k0 in range(0, I, BK):
235
+ rk = k0 + tl.arange(0, BK)
236
+ g = tl.load(Hh + rm64[:, None] * s_h + rk[None, :], mask=mm[:, None], other=0.0).to(tl.float32)
237
+ u = tl.load(Hh + rm64[:, None] * s_h + I + rk[None, :], mask=mm[:, None], other=0.0).to(tl.float32)
238
+ x = ((g / (1.0 + tl.exp(-g))).to(tl.bfloat16).to(tl.float32) * u).to(tl.bfloat16).to(tl.float32)
239
+ tl.store(Q + rm64[:, None] * s_q + rk[None, :], (x / s[:, None]).to(tl.float8e4nv), mask=mm[:, None])
240
+ tl.store(S + rm64, s, mask=mm)
241
+
242
+
243
+ @triton.jit
244
+ def _grouped_fp8_kernel(A, AS, W, WS, C, BE, BR0, BR1, N_OUT, K, s_am, s_we, s_wn, s_cm, s_wse,
245
+ BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr):
246
+ """One block of one expert's rows: C[rows] = (A[rows] * AS) @ (W[e] * WS[e]).T, in FP8 with fp32 accumulation."""
247
+ pid_m, pid_n = tl.program_id(0), tl.program_id(1)
248
+ e, r0, r1 = tl.load(BE + pid_m), tl.load(BR0 + pid_m), tl.load(BR1 + pid_m)
249
+ if r1 <= r0:
250
+ return
251
+ rm = r0 + tl.arange(0, BM); mm = rm < r1
252
+ rn = pid_n * BN + tl.arange(0, BN); mn = rn < N_OUT
253
+ rk = tl.arange(0, BK)
254
+ rm64, rn64, e64 = rm.to(tl.int64), rn.to(tl.int64), e.to(tl.int64)
255
+ acc = tl.zeros((BM, BN), dtype=tl.float32)
256
+ for k0 in range(0, K, BK):
257
+ a = tl.load(A + rm64[:, None] * s_am + (k0 + rk)[None, :], mask=mm[:, None], other=0.0)
258
+ b = tl.load(W + e64 * s_we + rn64[None, :] * s_wn + (k0 + rk)[:, None], mask=mn[None, :], other=0.0)
259
+ acc += tl.dot(a, b)
260
+ sa = tl.load(AS + rm, mask=mm, other=0.0)
261
+ sb = tl.load(WS + e64 * s_wse + rn64, mask=mn, other=0.0)
262
+ acc = acc * sa[:, None] * sb[None, :]
263
+ tl.store(C + rm64[:, None] * s_cm + rn64[None, :], acc.to(tl.bfloat16), mask=mm[:, None] & mn[None, :])
264
+
265
+
266
+ def q_rows(x, BM=16, BK=512):
267
+ x = x.contiguous()
268
+ m, k = x.shape
269
+ q = torch.empty(m, k, dtype=F8, device=x.device)
270
+ s = torch.empty(m, 1, dtype=torch.float32, device=x.device)
271
+ if m:
272
+ _q_rows_kernel[(triton.cdiv(m, BM),)](x, q, s, m, k, x.stride(0), q.stride(0), BM=BM, BK=BK)
273
+ return q, s
274
+
275
+
276
+ def gather_q_rows(x, src, BM=16, BK=512):
277
+ x = x.contiguous()
278
+ n, k = src.numel(), x.shape[1]
279
+ q = torch.empty(n, k, dtype=F8, device=x.device)
280
+ s = torch.empty(n, dtype=torch.float32, device=x.device)
281
+ if n:
282
+ _gather_q_rows_kernel[(triton.cdiv(n, BM),)](x, src, q, s, n, k, x.stride(0), q.stride(0), BM=BM, BK=BK)
283
+ return q, s
284
+
285
+
286
+ def swiglu_q_rows(h, BM=16, BK=512):
287
+ n, i2 = h.shape
288
+ i = i2 // 2
289
+ q = torch.empty(n, i, dtype=F8, device=h.device)
290
+ s = torch.empty(n, dtype=torch.float32, device=h.device)
291
+ if n:
292
+ _swiglu_q_rows_kernel[(triton.cdiv(n, BM),)](h, q, s, n, i, h.stride(0), q.stride(0), BM=BM, BK=BK)
293
+ return q, s
294
+
295
+
296
+ def _expert_blocks(counts, N, BM):
297
+ """Per-block (expert, first row, end row), built on the GPU from per-expert token counts (no host sync)."""
298
+ E = counts.numel()
299
+ nb = (counts + BM - 1) // BM
300
+ cnb = torch.cumsum(nb, 0)
301
+ nbmax = triton.cdiv(N, BM) + E
302
+ j = torch.arange(nbmax, device=counts.device)
303
+ e = torch.searchsorted(cnb, j, right=True)
304
+ valid = e < E
305
+ e = e.clamp(max=E - 1)
306
+ start = torch.cumsum(counts, 0) - counts
307
+ r0 = start[e] + (j - (cnb[e] - nb[e])) * BM
308
+ r1 = torch.minimum(r0 + BM, start[e] + counts[e])
309
+ r0, r1 = torch.where(valid, r0, 0), torch.where(valid, r1, 0)
310
+ return (e.to(torch.int32), r0.to(torch.int32), r1.to(torch.int32)), nbmax
311
+
312
+
313
+ def grouped_fp8_mm(a8, a_s, w8, w_s, blocks, BM=128, BN=256, BK=128, warps=8, stages=4):
314
+ N, K = a8.shape
315
+ E, n_out, _ = w8.shape
316
+ out = torch.empty(N, n_out, dtype=torch.bfloat16, device=a8.device)
317
+ (be, br0, br1), nb = blocks
318
+ if nb:
319
+ _grouped_fp8_kernel[(nb, triton.cdiv(n_out, BN))](a8, a_s, w8, w_s, out, be, br0, br1, n_out, K,
320
+ a8.stride(0), w8.stride(0), w8.stride(1), out.stride(0),
321
+ w_s.stride(0), BM=BM, BN=BN, BK=BK, num_warps=warps,
322
+ num_stages=stages)
323
+ return out
324
+
325
+
326
+ class FP8Linear(nn.Module):
327
+ """A projection with an FP8 weight (one scale per output row) and per-token FP8 activations."""
328
+ def __init__(self, w8, scale):
329
+ super().__init__()
330
+ self.register_buffer("w8", w8) # [out, in] float8_e4m3fn
331
+ self.register_buffer("ws", scale.float()[None].contiguous()) # [1, out] fp32
332
+ self.out_features, self.in_features = w8.shape
333
+
334
+ def forward(self, x):
335
+ shape = x.shape
336
+ x2 = x.reshape(-1, shape[-1])
337
+ m = x2.shape[0]
338
+ pad = (-m) % 16 # _scaled_mm wants rows divisible by 16
339
+ if pad:
340
+ x2 = F.pad(x2, (0, 0, 0, pad))
341
+ x8, xs = q_rows(x2)
342
+ y = torch._scaled_mm(x8, self.w8.t(), scale_a=xs, scale_b=self.ws, out_dtype=torch.bfloat16)[:m]
343
+ return y.to(x.dtype).reshape(*shape[:-1], self.out_features)
344
+
345
+
346
+ def _fp8_experts(moe):
347
+ """Replacement for the MoE layer's expert loop: tokens sorted by expert, two grouped FP8 matmuls."""
348
+ def dispatch(x, topk_ids, topk_weight):
349
+ T, K = topk_ids.shape
350
+ flat = topk_ids.reshape(-1)
351
+ idxs = flat.argsort()
352
+ counts = torch.zeros(moe.gu8.shape[0], dtype=torch.long, device=flat.device).scatter_add_(0, flat, torch.ones_like(flat))
353
+ blocks = _expert_blocks(counts, flat.numel(), 128)
354
+ a8, a_s = gather_q_rows(x, idxs // K)
355
+ h = grouped_fp8_mm(a8, a_s, moe.gu8, moe.gus, blocks) # [N, 2I]
356
+ m8, m_s = swiglu_q_rows(h)
357
+ out = grouped_fp8_mm(m8, m_s, moe.d8, moe.ds, blocks) # [N, H]
358
+ y = torch.empty_like(out)
359
+ y[idxs] = out
360
+ return y.view(T, K, -1).type(topk_weight.dtype).mul_(topk_weight.unsqueeze(-1)).sum(dim=1).type(x.dtype)
361
+ return dispatch
362
+
363
+
364
+ # ---------------------------------------------------------------------------------------------------------------------
365
+ # Attention for the decision mask (prefill only)
366
+ # ---------------------------------------------------------------------------------------------------------------------
367
+ MASKED = [SDPBackend.EFFICIENT_ATTENTION, SDPBackend.CUDNN_ATTENTION]
368
+ UNMASKED = [SDPBackend.FLASH_ATTENTION, SDPBackend.CUDNN_ATTENTION, SDPBackend.EFFICIENT_ATTENTION]
369
+ SPLIT = {"ctx": None, "len": None} # set for one eager forward: context length and real length of each row
370
+
371
+
372
+ def _split_attention(q, k, v, mask, scale):
373
+ """The context attends only to itself (no mask needed: a fast kernel); only option and answer rows use the mask."""
374
+ out = torch.zeros_like(q)
375
+ for b, (c, n) in enumerate(zip(SPLIT["ctx"], SPLIT["len"])):
376
+ with sdpa_kernel(UNMASKED):
377
+ out[b:b + 1, :, :c] = F.scaled_dot_product_attention(q[b:b + 1, :, :c], k[b:b + 1, :, :c], v[b:b + 1, :, :c],
378
+ is_causal=False, scale=scale)
379
+ if n > c:
380
+ with sdpa_kernel(MASKED):
381
+ out[b:b + 1, :, c:n] = F.scaled_dot_product_attention(
382
+ q[b:b + 1, :, c:n], k[b:b + 1, :, :n], v[b:b + 1, :, :n],
383
+ attn_mask=mask[b:b + 1, :, c:n, :n].contiguous(), scale=scale)
384
+ return out
385
+
386
+
387
+ def _attention(self, hidden_states, attention_mask=None, position_ids=None, past_key_value=None,
388
+ output_attentions=False, use_cache=False, **kwargs):
389
+ mod = sys.modules[type(self).__module__]
390
+ bsz, n, _ = hidden_states.size()
391
+ if self.q_lora_rank is None:
392
+ q = self.q_proj(hidden_states)
393
+ else:
394
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
395
+ q = q.view(bsz, n, self.num_heads, self.q_head_dim).transpose(1, 2)
396
+ q_nope, q_pe = torch.split(q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
397
+ ckv = self.kv_a_proj_with_mqa(hidden_states)
398
+ ckv, k_pe = torch.split(ckv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
399
+ k_pe = k_pe.view(bsz, n, 1, self.qk_rope_head_dim).transpose(1, 2)
400
+ kv = (self.kv_b_proj(self.kv_a_layernorm(ckv))
401
+ .view(bsz, n, self.num_heads, self.qk_nope_head_dim + self.v_head_dim).transpose(1, 2))
402
+ k_nope, v = torch.split(kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
403
+ cos, sin = self.rotary_emb(v, seq_len=n)
404
+ q_pe, k_pe = mod.apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
405
+ q = torch.cat([q_nope, q_pe], dim=-1)
406
+ k = torch.cat([k_nope, k_pe.expand(-1, self.num_heads, -1, -1)], dim=-1)
407
+ pad = self.q_head_dim - self.v_head_dim # pad v to the q/k head dim so a memory-efficient kernel runs
408
+ vp = F.pad(v, (0, pad)) if pad > 0 else v
409
+ if SPLIT["ctx"] is not None:
410
+ out = _split_attention(q, k, vp, attention_mask, self.softmax_scale)
411
+ else:
412
+ with sdpa_kernel(MASKED):
413
+ out = F.scaled_dot_product_attention(q, k, vp, attn_mask=attention_mask, scale=self.softmax_scale)
414
+ out = out[..., : self.v_head_dim].transpose(1, 2).reshape(bsz, n, self.num_heads * self.v_head_dim)
415
+ return self.o_proj(out), None, past_key_value
416
+
417
+
418
+ def _passthrough_4d(orig):
419
+ def prepare(attention_mask, input_shape, inputs_embeds, past_key_values_length, sliding_window=None):
420
+ if attention_mask is not None and attention_mask.dim() == 4:
421
+ return attention_mask.to(inputs_embeds.dtype)
422
+ return orig(attention_mask, input_shape, inputs_embeds, past_key_values_length, sliding_window)
423
+ return prepare
424
+
425
+
426
+ # ---------------------------------------------------------------------------------------------------------------------
427
+ # CUDA graphs: the backbone is captured once per (batch, length) bucket and replayed with a single launch
428
+ # ---------------------------------------------------------------------------------------------------------------------
429
+ class Graphs:
430
+ def __init__(self, backbone, hidden, device, lengths=(128, 256, 384, 512, 768, 1024, 1536, 2048),
431
+ batches=(1, 2, 4, 8, 16), max_tokens=16384):
432
+ self.backbone, self.hidden, self.device = backbone, hidden, device
433
+ self.lengths, self.batches, self.max_tokens = sorted(lengths), sorted(batches), max_tokens
434
+ self.graphs, self.pool = {}, None
435
+
436
+ def bucket(self, B, L):
437
+ b = next((x for x in self.batches if x >= B), None)
438
+ l = next((x for x in self.lengths if x >= L), None)
439
+ return None if b is None or l is None or b * l > self.max_tokens else (b, l)
440
+
441
+ @torch.no_grad()
442
+ def capture_all(self):
443
+ for B in sorted(self.batches, reverse=True):
444
+ for L in sorted(self.lengths, reverse=True):
445
+ if B * L <= self.max_tokens:
446
+ st = {"x": torch.zeros(B, L, self.hidden, device=self.device, dtype=torch.bfloat16),
447
+ "pos": torch.zeros(B, L, dtype=torch.long, device=self.device),
448
+ "mask": torch.zeros(B, 1, L, L, device=self.device, dtype=torch.bfloat16)}
449
+ fwd = lambda: self.backbone(inputs_embeds=st["x"], position_ids=st["pos"],
450
+ attention_mask=st["mask"]).last_hidden_state
451
+ s = torch.cuda.Stream()
452
+ s.wait_stream(torch.cuda.current_stream())
453
+ with torch.cuda.stream(s): # warm-up (allocator, Triton autotune) outside the graph
454
+ for _ in range(2):
455
+ fwd()
456
+ torch.cuda.current_stream().wait_stream(s)
457
+ g = torch.cuda.CUDAGraph()
458
+ with torch.cuda.graph(g, pool=self.pool):
459
+ st["out"] = fwd()
460
+ self.pool = g.pool()
461
+ self.graphs[(B, L)] = (g, st)
462
+ torch.cuda.synchronize()
463
+ return len(self.graphs)
464
+
465
+ @torch.no_grad()
466
+ def run(self, x, pos, mask):
467
+ g, st = self.graphs[(x.shape[0], x.shape[1])]
468
+ st["x"].copy_(x); st["pos"].copy_(pos); st["mask"].copy_(mask)
469
+ g.replay()
470
+ return st["out"]
471
+
472
+
473
+ # ---------------------------------------------------------------------------------------------------------------------
474
+ # Loading
475
+ # ---------------------------------------------------------------------------------------------------------------------
476
+ def _load_backbone(path, cfg, device):
477
+ """Build the backbone without allocating weights, swap in FP8 projections and experts, then load every tensor
478
+ straight onto the GPU."""
479
+ from accelerate import init_empty_weights
480
+ from safetensors import safe_open
481
+ from transformers import AutoModel
482
+ with init_empty_weights(include_buffers=False):
483
+ backbone = AutoModel.from_config(cfg, trust_remote_code=True, torch_dtype=torch.bfloat16)
484
+ mod = sys.modules[type(backbone).__module__]
485
+ index = json.load(open(os.path.join(path, "model.safetensors.index.json")))["weight_map"]
486
+ files = {}
487
+ for k, f in index.items():
488
+ files.setdefault(f, []).append(k)
489
+ tensors = {}
490
+ for f, keys in files.items():
491
+ with safe_open(os.path.join(path, f), framework="pt", device=str(device)) as sf:
492
+ for k in keys:
493
+ tensors[k[len("model."):] if k.startswith("model.") else k] = sf.get_tensor(k)
494
+ # routed experts: stacked FP8 buffers + the grouped kernel
495
+ for name, m in list(backbone.named_modules()):
496
+ if type(m).__name__ == "SarvamMLAMoE":
497
+ m.experts = nn.ModuleList()
498
+ for b, key in (("gu8", "gate_up_proj"), ("gus", "gate_up_proj_scale"), ("d8", "down_proj"), ("ds", "down_proj_scale")):
499
+ m.register_buffer(b, tensors.pop(f"{name}.experts.{key}").contiguous())
500
+ m._moe_dispatch = _fp8_experts(m)
501
+ # every other projection: FP8Linear
502
+ for name, m in list(backbone.named_modules()):
503
+ if type(m) is nn.Linear:
504
+ parent, attr = name.rsplit(".", 1)
505
+ setattr(backbone.get_submodule(parent), attr, FP8Linear(tensors.pop(name + ".weight"), tensors.pop(name + ".weight_scale")))
506
+ # embeddings, norms (bf16) and the MoE router (fp32)
507
+ for name, t in tensors.items():
508
+ mname, attr = name.rsplit(".", 1)
509
+ m = backbone.get_submodule(mname)
510
+ if attr in m._buffers:
511
+ m._buffers[attr] = t
512
+ else:
513
+ m._parameters[attr] = nn.Parameter(t, requires_grad=False)
514
+ for m in backbone.modules():
515
+ for k, b in list(m._buffers.items()):
516
+ if b is not None and b.device != device:
517
+ m._buffers[k] = b.to(device)
518
+ if hasattr(m, "_set_cos_sin_cache"): # rotary tables for the full context, on the GPU
519
+ m._set_cos_sin_cache(cfg.max_position_embeddings, device, torch.bfloat16)
520
+ left = [n for n, p in list(backbone.named_parameters()) + list(backbone.named_buffers()) if p.device.type == "meta"]
521
+ assert not left, f"weights missing from the checkpoint, e.g. {left[:3]}"
522
+ backbone.config.use_cache = False
523
+ mod._prepare_4d_causal_attention_mask = _passthrough_4d(mod._prepare_4d_causal_attention_mask)
524
+ mod.SarvamMLAAttention.forward = _attention
525
+ for m in backbone.modules():
526
+ if isinstance(m, mod.SarvamMLAAttention):
527
+ m.forward = types.MethodType(_attention, m)
528
+ gc.collect()
529
+ torch.cuda.empty_cache()
530
+ return backbone.eval()
531
+
532
+
533
+ class Prism(nn.Module):
534
+ @classmethod
535
+ def from_pretrained(cls, path="sarvamai/prism", device="cuda:0", batch_size=16, cuda_graphs=True):
536
+ """path: a local directory or a Hugging Face repo id. Needs one GPU with FP8 support and ~120 GB of memory
537
+ (tested on NVIDIA B200). cuda_graphs: capture the backbone for small and medium batches (a few minutes at load;
538
+ much lower latency per request)."""
539
+ from safetensors.torch import load_file
540
+ from transformers import AutoConfig, AutoTokenizer
541
+ if not os.path.isdir(path):
542
+ from huggingface_hub import snapshot_download
543
+ path = snapshot_download(path)
544
+ self = cls()
545
+ self.device, self.batch_size = torch.device(device), batch_size
546
+ torch.cuda.set_device(self.device)
547
+ self.tok = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
548
+ self.enc = Encoder(self.tok)
549
+ cfg = AutoConfig.from_pretrained(path, trust_remote_code=True)
550
+ self.backbone = _load_backbone(path, cfg, self.device)
551
+ w = load_file(os.path.join(path, "decision_head.safetensors"))
552
+ d = cfg.hidden_size
553
+ self.segment = nn.Embedding(4, d)
554
+ self.segment.weight.data.copy_(w["segment_embedding.weight"])
555
+ layers = len({key.split(".")[2] for key in w if key.startswith("head.blocks.")})
556
+ self.head = DecisionHead(d, dh=w["head.pd.weight"].shape[0], layers=layers)
557
+ self.head.load_state_dict({key[len("head."):]: v for key, v in w.items() if key.startswith("head.")})
558
+ self.segment.to(self.device)
559
+ self.head.to(self.device).float()
560
+ self.max_tokens = cfg.max_position_embeddings
561
+ self.graphs = None
562
+ if cuda_graphs:
563
+ self.graphs = Graphs(self.backbone, d, self.device)
564
+ self.graphs.capture_all()
565
+ return self.eval()
566
+
567
+ @torch.no_grad()
568
+ def _probabilities(self, items):
569
+ """items: [(state, type, option texts, instructions)] -> list of probability tensors."""
570
+ encs = [self.enc(s, ins, opts) for s, _, opts, ins in items]
571
+ B, L = len(encs), max(len(e.ids) for e in encs)
572
+ bucket = self.graphs.bucket(B, L) if self.graphs is not None else None
573
+ Bp, Lp = bucket or (B, L)
574
+ ids = torch.full((Bp, Lp), self.tok.pad_token_id or 0, device=self.device)
575
+ pos = torch.zeros((Bp, Lp), dtype=torch.long, device=self.device)
576
+ seg = torch.zeros((Bp, Lp), dtype=torch.long, device=self.device)
577
+ for b, e in enumerate(encs):
578
+ ids[b, : len(e.ids)] = torch.tensor(e.ids, device=self.device)
579
+ pos[b, : len(e.pos)] = torch.tensor(e.pos, device=self.device)
580
+ seg[b, : len(e.seg)] = torch.tensor(e.seg, device=self.device)
581
+ x = self.backbone.get_input_embeddings()(ids)
582
+ x = x + self.segment(seg).to(x.dtype)
583
+ roles = [e.role for e in encs] + [[] for _ in range(Bp - B)]
584
+ mask = attention_mask(roles, Lp, self.device, x.dtype)
585
+ if bucket is not None: # padded rows and tokens are masked out
586
+ h = self.graphs.run(x, pos, mask).float()
587
+ else:
588
+ SPLIT.update(ctx=[e.n_context for e in encs], len=[len(e.ids) for e in encs])
589
+ try:
590
+ h = self.backbone(inputs_embeds=x, position_ids=pos, attention_mask=mask).last_hidden_state.float()
591
+ finally:
592
+ SPLIT.update(ctx=None, len=None)
593
+ return [F.softmax(self.head(h[b, e.answer_idx], h[b, torch.tensor(e.close_idx, device=self.device)], t), -1).cpu()
594
+ for b, (e, (_, t, _, _)) in enumerate(zip(encs, items))]
595
+
596
+ def decide(self, state, questions):
597
+ """state: any text or JSON-serialisable value; questions: {name: {"type", "instructions", "criteria"}}."""
598
+ s = _text(state) if state not in (None, "", {}, []) else ""
599
+ items, meta = [], []
600
+ for name, q in questions.items():
601
+ kind, keys, opts = to_options(q)
602
+ ins = _text(q.get("instructions", ""))
603
+ n = len(self.enc(s, ins, opts).ids)
604
+ if n > self.max_tokens:
605
+ raise ValueError(f"question {name!r} is {n} tokens, over the {self.max_tokens}-token limit")
606
+ items.append((s, kind, opts, ins))
607
+ meta.append((name, kind, keys, n))
608
+ order = sorted(range(len(items)), key=lambda i: meta[i][3]) # similar lengths share a batch
609
+ P = [None] * len(items)
610
+ for i in range(0, len(order), self.batch_size):
611
+ chunk = order[i: i + self.batch_size]
612
+ for j, p in zip(chunk, self._probabilities([items[j] for j in chunk])):
613
+ P[j] = p.tolist()
614
+ out = {}
615
+ for (name, kind, keys, _), p in zip(meta, P):
616
+ probs = dict(zip(keys, p))
617
+ if kind == "yes_no":
618
+ out[name] = {"type": "yes_no", "yes": p[1]}
619
+ elif kind == "score":
620
+ out[name] = {"type": "score", "score": sum(i * v for i, v in enumerate(p)),
621
+ "level": max(keys, key=probs.get), "probabilities": probs}
622
+ else:
623
+ out[name] = {"type": "choice", "choice": max(keys, key=probs.get), "probabilities": probs}
624
+ return out
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ torch>=2.8
2
+ triton>=3.4
3
+ transformers==4.52.1
4
+ accelerate>=1.0
5
+ safetensors>=0.4
6
+ huggingface_hub>=0.30
special_tokens_map.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "boi_token": "<|start_of_image|>",
3
+ "bos_token": {
4
+ "content": "[@BOS@]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false
9
+ },
10
+ "eoi_token": "<|end_of_image|>",
11
+ "eos_token": {
12
+ "content": "<|end_of_turn|>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false
17
+ },
18
+ "image_token": "<|image_soft_token|>",
19
+ "pad_token": {
20
+ "content": "<pad>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false
25
+ },
26
+ "unk_token": {
27
+ "content": "<unk>",
28
+ "lstrip": false,
29
+ "normalized": false,
30
+ "rstrip": false,
31
+ "single_word": false
32
+ }
33
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a574ceaaff7c7a8f091179c53fd17ae33567089c099d4ff37d4cb3bc1a87e80e
3
+ size 33627251
tokenizer_config.json ADDED
The diff for this file is too large to render. See raw diff