turboderp commited on
Commit
a011219
·
verified ·
1 Parent(s): 77e430a

Upload folder using huggingface_hub

Browse files
.done ADDED
File without changes
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* 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
 
 
 
 
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
+ step-bar-chart.png filter=lfs diff=lfs merge=lfs -text
37
+ model.safetensors.index.json filter=lfs diff=lfs merge=lfs -text
38
+ quantization_config.json filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,581 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ base_model:
4
+ - stepfun-ai/step-3.5-flash
5
+ library_name: transformers
6
+ ---
7
+
8
+ # Step 3.5 Flash
9
+
10
+ <div align="center">
11
+
12
+ <div align="center" style="display: flex; justify-content: center; align-items: center;">
13
+ <img src="stepfun.svg" width="25" style="margin-right: 10px;"/>
14
+ <h1 style="margin: 0; border-bottom: none;">Step 3.5 Flash</h1>
15
+ </div>
16
+
17
+ [![GitHub](https://img.shields.io/badge/GitHub-181717?style=flat&logo=github&logoColor=white)](https://github.com/stepfun-ai/Step-3.5-Flash)
18
+ [![Hugging Face](https://img.shields.io/badge/%F0%9F%A4%97%20HF-StepFun/STEP3p5-preview)](https://huggingface.co/stepfun-ai/Step-3.5-Flash)
19
+ [![ModelScope](https://img.shields.io/badge/ModelScope-StepFun/STEP3p5-preview)](https://modelscope.cn/models/stepfun-ai/Step-3.5-Flash)
20
+ [![Discord](https://img.shields.io/badge/Discord-Join-5865F2?logo=discord&logoColor=white)](https://discord.gg/RcMJhNVAQc)
21
+ [![Webpage](https://img.shields.io/badge/Webpage-Blog-blue)](https://static.stepfun.com/blog/step-3.5-flash/)
22
+ [![Paper](https://img.shields.io/badge/Arxiv-TechReport-red)](https://arxiv.org/abs/2602.10604)
23
+ [![License](https://img.shields.io/badge/License-Apache%202.0-green)]()
24
+ [![Chat with the model on OpenRouter](https://img.shields.io/badge/Chat%20with%20the%20model-OpenRouter-5B3DF5?logo=chatbot&logoColor=white)](https://openrouter.ai/chat?models=stepfun/step-3.5-flash:free)
25
+ [![Chat with the model on HuggingfaceSpace](https://img.shields.io/badge/Chat%20with%20the%20model-HuggingfaceSpace-5B3DF5?logo=chatbot&logoColor=white)](https://huggingface.co/spaces/stepfun-ai/Step-3.5-Flash)
26
+ </div>
27
+
28
+
29
+
30
+ ## 1. Introduction
31
+
32
+ **Step 3.5 Flash** ([visit website](https://static.stepfun.com/blog/step-3.5-flash/)) is our most capable open-source foundation model, engineered to deliver frontier reasoning and agentic capabilities with exceptional efficiency. Built on a sparse Mixture of Experts (MoE) architecture, it selectively activates only 11B of its 196B parameters per token. This "intelligence density" allows it to rival the reasoning depth of top-tier proprietary models, while maintaining the agility required for real-time interaction.
33
+
34
+ ## 2. Key Capabilities
35
+
36
+ - **Deep Reasoning at Speed**: While chatbots are built for reading, agents must reason fast. Powered by 3-way Multi-Token Prediction (MTP-3), Step 3.5 Flash achieves a generation throughput of **100–300 tok/s** in typical usage (peaking at **350 tok/s** for single-stream coding tasks). This allows for complex, multi-step reasoning chains with immediate responsiveness.
37
+
38
+ - **A Robust Engine for Coding & Agents**: Step 3.5 Flash is purpose-built for agentic tasks, integrating a scalable RL framework that drives consistent self-improvement. It achieves **74.4% on SWE-bench Verified** and **51.0% on Terminal-Bench 2.0**, proving its ability to handle sophisticated, long-horizon tasks with unwavering stability.
39
+
40
+ - **Efficient Long Context**: The model supports a cost-efficient **256K context window** by employing a 3:1 Sliding Window Attention (SWA) ratio—integrating three SWA layers for every full-attention layer. This hybrid approach ensures consistent performance across massive datasets or long codebases while significantly reducing the computational overhead typical of standard long-context models.
41
+
42
+ - **Accessible Local Deployment**: Optimized for accessibility, Step 3.5 Flash brings elite-level intelligence to local environments. It runs securely on high-end consumer hardware (e.g., Mac Studio M4 Max, NVIDIA DGX Spark), ensuring data privacy without sacrificing performance.
43
+
44
+ ## 3. Performance
45
+
46
+ Step 3.5 Flash delivers performance parity with leading closed-source systems while remaining open and efficient.
47
+
48
+ ![](step-bar-chart.png)
49
+
50
+ Performance of Step 3.5 Flash measured across **Reasoning**, **Coding**, and **Agentic Abilities**. Open-source models (left) are sorted by their total parameter count, while top-tier proprietary models are shown on the right. xbench-DeepSearch scores are sourced from [official publications](https://xbench.org/agi/aisearch) for consistency. The shadowed bars represent the enhanced performance of Step 3.5 Flash using [Parallel Thinking](https://arxiv.org/pdf/2601.05593).
51
+
52
+ ### Detailed Benchmarks
53
+
54
+ | Benchmark | Step 3.5 Flash | DeepSeek V3.2 | Kimi K2 Thinking / K2.5 | GLM-4.7 | MiniMax M2.1 | MiMo-V2 Flash |
55
+ | --- | --- | --- | --- | --- | --- | --- |
56
+ | # Activated Params | 11B | 37B | 32B | 32B | 10B | 15B |
57
+ | # Total Params (MoE) | 196B | 671B | 1T | 355B | 230B | 309B |
58
+ | Est. decoding cost @ 128K context, Hopper GPU** | **1.0x**<br>100 tok/s, MTP-3, EP8 | **6.0x**<br>33 tok/s, MTP-1, EP32 | **18.9x**<br>33 tok/s, no MTP, EP32 | **18.9x**<br>100 tok/s, MTP-3, EP8 | **3.9x**<br>100 tok/s, MTP-3, EP8 | **1.2x**<br>100 tok/s, MTP-3, EP8 |
59
+ | | | | **Agent** | | | |
60
+ | τ²-Bench | 88.2 | 80.3 (85.2*) | 74.3*/85.4* | 87.4 | 86.6* | 80.3 (84.1*) |
61
+ | BrowseComp | 51.6 | 51.4 | 41.5* / 60.6 | 52.0 | 47.4 | 45.4 |
62
+ | BrowseComp (w/ Context Manager) | 69.0 | 67.6 | 60.2/74.9 | 67.5 | 62.0 | 58.3 |
63
+ | BrowseComp-ZH | 66.9 | 65.0 | 62.3 / 62.3* | 66.6 | 47.8* | 51.2* |
64
+ | BrowseComp-ZH (w/ Context Manager) | 73.7 | — | —/— | — | — | — |
65
+ | GAIA (no file) | 84.5 | 75.1* | 75.6*/75.9* | 61.9* | 64.3* | 78.2* |
66
+ | xbench-DeepSearch (2025.05) | 83.7 | 78.0* | 76.0*/76.7* | 72.0* | 68.7* | 69.3* |
67
+ | xbench-DeepSearch (2025.10) | 56.3 | 55.7* | —/40+ | 52.3* | 43.0* | 44.0* |
68
+ | ResearchRubrics | 65.3 | 55.8* | 56.2*/59.5* | 62.0* | 60.2* | 54.3* |
69
+ | | | | **Reasoning** | | | |
70
+ | AIME 2025 | 97.3 | 93.1 | 94.5/96.1 | 95.7 | 83.0 | 94.1 (95.1*) |
71
+ | HMMT 2025 (Feb.) | 98.4 | 92.5 | 89.4/95.4 | 97.1 | 71.0* | 84.4 (95.4*) |
72
+ | HMMT 2025 (Nov.) | 94.0 | 90.2 | 89.2*/— | 93.5 | 74.3* | 91.0* |
73
+ | IMOAnswerBench | 85.4 | 78.3 | 78.6/81.8 | 82.0 | 60.4* | 80.9* |
74
+ | | | | **Coding** | | | |
75
+ | LiveCodeBench-V6 | 86.4 | 83.3 | 83.1/85.0 | 84.9 | — | 80.6 (81.6*) |
76
+ | SWE-bench Verified | 74.4 | 73.1 | 71.3/76.8 | 73.8 | 74.0 | 73.4 |
77
+ | Terminal-Bench 2.0 | 51.0 | 46.4 | 35.7*/50.8 | 41.0 | 47.9 | 38.5 |
78
+
79
+ **Notes**:
80
+ 1. "—" indicates the score is not publicly available or not tested.
81
+ 2. "*" indicates the original score was inaccessible or lower than our reproduced, so we report the evaluation under the same test conditions as Step 3.5 Flash to ensure fair comparability.
82
+ 3. **BrowseComp (with Context Manager)**: When the effective context length exceeds a predefined threshold, the agent resets the context and restarts the agent loop. By contrast, Kimi K2.5 and DeepSeek-V3.2 used a "discard-all" strategy.
83
+ 4. **Decoding Cost**: Estimates are based on a methodology similar to, but more accurate than, the approach described arxiv.org/abs/2507.19427
84
+
85
+ ### Recommended Inference Parameters
86
+ 1. For general chat domain, we suggest: `temperature=0.6, top_p=0.95`
87
+ 2. For reasoning / agent scenario, we recommend: `temperature=1.0, top_p=0.95`.
88
+
89
+ ## 4. Architecture Details
90
+
91
+ Step 3.5 Flash is built on a **Sparse Mixture-of-Experts (MoE)** transformer architecture, optimized for high throughput and low VRAM usage during inference.
92
+
93
+ ### 4.1 Technical Specifications
94
+
95
+ | Component | Specification |
96
+ | :--- | :--- |
97
+ | **Backbone** | 45-layer Transformer (4,096 hidden dim) |
98
+ | **Context Window** | 256K |
99
+ | **Vocabulary** | 128,896 tokens |
100
+ | **Total Parameters** | **196.81B** (196B Backbone + 0.81B Head) |
101
+ | **Active Parameters** | **~11B** (per token generation) |
102
+
103
+ ### 4.2 Mixture of Experts (MoE) Routing
104
+
105
+ Unlike traditional dense models, Step 3.5 Flash uses a fine-grained routing strategy to maximize efficiency:
106
+ - **Fine-Grained Experts**: 288 routed experts per layer + 1 shared expert (always active).
107
+ - **Sparse Activation**: Only the Top-8 experts are selected per token.
108
+ - **Result**: The model retains the "memory" of a 196B parameter model but executes with the speed of an 11B model.
109
+
110
+ ### 4.3 Multi-Token Prediction (MTP)
111
+
112
+ To improve inference speed, we utilize a specialized MTP Head consisting of a sliding-window attention mechanism and a dense Feed-Forward Network (FFN). This module predicts 4 tokens simultaneously in a single forward pass, significantly accelerating inference without degrading quality.
113
+
114
+ ## 5. Quick Start
115
+
116
+ You can get started with Step 3.5 Flash in minutes using Cloud API via our supported providers.
117
+
118
+ ### 5.1 Get Your API Key.
119
+
120
+ Sign up at [OpenRouter](https://openrouter.ai) or [platform.stepfun.ai](https://platform.stepfun.ai), and grab your API key.
121
+
122
+ > OpenRouter now offers free trial for Step 3.5 Flash.
123
+
124
+ | Provider | Website | Base URL |
125
+ | :--- | :--- | :--- |
126
+ | OpenRouter | https://openrouter.ai | https://openrouter.ai/api/v1 |
127
+ | StepFun | https://platform.stepfun.ai | https://api.stepfun.ai/v1 |
128
+
129
+ ### 5.2 Setup
130
+
131
+ Install the standard OpenAI SDK (compatible with both platforms).
132
+
133
+ ```bash
134
+ pip install --upgrade "openai>=1.0"
135
+ ```
136
+
137
+ Note: OpenRouter supports multiple SDKs. Learn more [here](https://openrouter.ai/docs/quickstart).
138
+
139
+ ### 5.3 Implementation Example
140
+
141
+ This example shows starting a chat with Step 3.5 Flash.
142
+
143
+ ```python
144
+ from openai import OpenAI
145
+
146
+ client = OpenAI(
147
+ api_key="YOUR_API_KEY",
148
+ base_url="https://api.stepfun.ai/v1", # or "https://openrouter.ai/api/v1"
149
+ # Optional: OpenRouter headers for app rankings
150
+ default_headers={
151
+ "HTTP-Referer": "<YOUR_SITE_URL>",
152
+ "X-Title": "<YOUR_SITE_NAME>",
153
+ }
154
+ )
155
+
156
+ completion = client.chat.completions.create(
157
+ model="step-3.5-flash", # Use "stepfun/step-3.5-flash" for OpenRouter
158
+ messages=[
159
+ {
160
+ "role": "system",
161
+ "content": "You are an AI chat assistant provided by StepFun. You are good at Chinese, English, and many other languages.",
162
+ },
163
+ {
164
+ "role": "user",
165
+ "content": "Introduce StepFun's artificial intelligence capabilities."
166
+ },
167
+ ],
168
+ )
169
+
170
+ print(completion.choices[0].message.content)
171
+ ```
172
+
173
+ ## 6. Local Deployment
174
+
175
+ Step 3.5 Flash is optimized for local inference and supports industry-standard backends including vLLM, SGLang, Hugging Face Transformers and llama.cpp.
176
+
177
+ ### 6.1 vLLM
178
+ We recommend using the latest nightly build of vLLM.
179
+ 1. Install vLLM.
180
+
181
+ ```bash
182
+ # via Docker
183
+ docker pull vllm/vllm-openai:nightly
184
+
185
+ # or via pip (nightly wheels)
186
+ pip install -U vllm --pre \
187
+ --index-url https://pypi.org/simple \
188
+ --extra-index-url https://wheels.vllm.ai/nightly
189
+ ```
190
+ 2. Launch the server.
191
+
192
+ **Note**: Full MTP3 support is not yet available in vLLM. We are actively working on a Pull Request to integrate this feature, which is expected to significantly enhance decoding performance.
193
+
194
+ - For fp8 model
195
+ ```bash
196
+ vllm serve <MODEL_PATH_OR_HF_ID> \
197
+ --served-model-name step3p5-flash \
198
+ --tensor-parallel-size 8 \
199
+ --enable-expert-parallel \
200
+ --disable-cascade-attn \
201
+ --reasoning-parser step3p5 \
202
+ --enable-auto-tool-choice \
203
+ --tool-call-parser step3p5 \
204
+ --hf-overrides '{"num_nextn_predict_layers": 1}' \
205
+ --speculative_config '{"method": "step3p5_mtp", "num_speculative_tokens": 1}' \
206
+ --trust-remote-code \
207
+ --quantization fp8
208
+ ```
209
+
210
+ - For bf16 model
211
+ ```bash
212
+ vllm serve <MODEL_PATH_OR_HF_ID> \
213
+ --served-model-name step3p5-flash \
214
+ --tensor-parallel-size 8 \
215
+ --enable-expert-parallel \
216
+ --disable-cascade-attn \
217
+ --reasoning-parser step3p5 \
218
+ --enable-auto-tool-choice \
219
+ --tool-call-parser step3p5 \
220
+ --hf-overrides '{"num_nextn_predict_layers": 1}' \
221
+ --speculative_config '{"method": "step3p5_mtp", "num_speculative_tokens": 1}' \
222
+ --trust-remote-code
223
+ ```
224
+ You can also refer to the [Step-3.5-Flash](https://github.com/vllm-project/recipes/blob/main/StepFun/Step-3.5-Flash.md) recipe.
225
+
226
+ ### 6.2 SGLang
227
+
228
+ 1. Install SGLang.
229
+ ```bash
230
+ # via Docker
231
+ docker pull lmsysorg/sglang:dev-pr-18084
232
+ # or from source (pip)
233
+ pip install "sglang[all] @ git+https://github.com/sgl-project/sglang.git"
234
+ ```
235
+
236
+ 2. Launch the server.
237
+ - For bf16 model
238
+
239
+ ```bash
240
+ sglang serve --model-path <MODEL_PATH_OR_HF_ID> \
241
+ --served-model-name step3p5-flash \
242
+ --tp-size 8 \
243
+ --tool-call-parser step3p5 \
244
+ --reasoning-parser step3p5 \
245
+ --speculative-algorithm EAGLE \
246
+ --speculative-num-steps 3 \
247
+ --speculative-eagle-topk 1 \
248
+ --speculative-num-draft-tokens 4 \
249
+ --enable-multi-layer-eagle \
250
+ --host 0.0.0.0 \
251
+ --port 8000
252
+ ```
253
+ - For fp8 model
254
+ ```bash
255
+ sglang serve --model-path <MODEL_PATH_OR_HF_ID> \
256
+ --served-model-name step3p5-flash \
257
+ --tp-size 8 \
258
+ --ep-size 8 \
259
+ --tool-call-parser step3p5 \
260
+ --reasoning-parser step3p5 \
261
+ --speculative-algorithm EAGLE \
262
+ --speculative-num-steps 3 \
263
+ --speculative-eagle-topk 1 \
264
+ --speculative-num-draft-tokens 4 \
265
+ --enable-multi-layer-eagle \
266
+ --host 0.0.0.0 \
267
+ --port 8000
268
+ ```
269
+
270
+ ### 6.3 Transformers (Debug / Verification)
271
+
272
+ Use this snippet for quick functional verification. For high-throughput serving, use vLLM or SGLang.
273
+ ```python
274
+ from transformers import AutoModelForCausalLM, AutoTokenizer
275
+
276
+ MODEL_PATH = "<MODEL_PATH_OR_HF_ID>"
277
+
278
+ # 1. Setup
279
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
280
+ model = AutoModelForCausalLM.from_pretrained(
281
+ MODEL_PATH,
282
+ trust_remote_code=True,
283
+ torch_dtype="auto",
284
+ device_map="auto",
285
+ )
286
+
287
+ # 2. Prepare Input
288
+ messages = [{"role": "user", "content": "Explain the significance of the number 42."}]
289
+ inputs = tokenizer.apply_chat_template(
290
+ messages,
291
+ tokenize=True,
292
+ add_generation_prompt=True,
293
+ return_dict=True,
294
+ return_tensors="pt",
295
+ ).to(model.device)
296
+
297
+ # 3. Generate
298
+ generated_ids = model.generate(**inputs, max_new_tokens=128, do_sample=False)
299
+ output_text = tokenizer.decode(generated_ids[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
300
+
301
+ print(output_text)
302
+ ```
303
+
304
+ ### 6.4 llama.cpp
305
+
306
+ #### System Requirements
307
+ - GGUF Model Weights(int4): 111.5 GB
308
+ - Runtime Overhead: ~7 GB
309
+ - Minimum VRAM: 120 GB (e.g., Mac studio, DGX-Spark, AMD Ryzen AI Max+ 395)
310
+ - Recommended: 128GB unified memory
311
+ #### Steps
312
+ 1. Use official llama.cpp:
313
+ > the folder `Step-3.5-Flash/tree/main/llama.cpp` is **obsolete**
314
+ ```bash
315
+ git clone https://github.com/ggml-org/llama.cpp
316
+ cd llama.cpp
317
+ ```
318
+ 2. Build llama.cpp on Mac:
319
+ ```bash
320
+ cmake -S . -B build-macos \
321
+ -DCMAKE_BUILD_TYPE=Release \
322
+ -DGGML_METAL=ON \
323
+ -DGGML_ACCELERATE=ON \
324
+ -DLLAMA_BUILD_EXAMPLES=ON \
325
+ -DLLAMA_BUILD_COMMON=ON \
326
+ -DGGML_LTO=ON
327
+ cmake --build build-macos -j8
328
+ ```
329
+ 3. Build llama.cpp on DGX-Spark:
330
+ ```bash
331
+ cmake -S . -B build-cuda \
332
+ -DCMAKE_BUILD_TYPE=Release \
333
+ -DGGML_CUDA=ON \
334
+ -DGGML_CUDA_GRAPHS=ON \
335
+ -DLLAMA_CURL=OFF \
336
+ -DLLAMA_BUILD_EXAMPLES=ON \
337
+ -DLLAMA_BUILD_COMMON=ON
338
+ cmake --build build-cuda -j8
339
+ ```
340
+ 4. Build llama.cpp on AMD Windows:
341
+ ```bash
342
+ cmake -S . -B build-vulkan \
343
+ -DCMAKE_BUILD_TYPE=Release \
344
+ -DLLAMA_CURL=OFF \
345
+ -DGGML_OPENMP=ON \
346
+ -DGGML_VULKAN=ON
347
+ cmake --build build-vulkan -j8
348
+ ```
349
+ 5. Run with llama-cli
350
+ ```bash
351
+ ./llama-cli -m step3.5_flash_Q4_K_S.gguf -c 16384 -b 2048 -ub 2048 -fa on --temp 1.0 -p "What's your name?"
352
+ ```
353
+ 6. Test performance with llama-batched-bench:
354
+ ```bash
355
+ ./llama-batched-bench -m step3.5_flash_Q4_K_S.gguf -c 32768 -b 2048 -ub 2048 -npp 0,2048,8192,16384,32768 -ntg 128 -npl 1
356
+ ```
357
+
358
+ ## 7. Using Step 3.5 Flash on Agent Platforms
359
+
360
+ ### 7.1 Claude Code & Codex
361
+ It's straightforward to add Step 3.5 Flash to the list of models in most coding environments. See below for the instructions for configuring Claude Code and Codex to use Step 3.5 Flash.
362
+
363
+ #### 7.1.1 Prerequisites
364
+ Sign up at StepFun.ai or OpenRouter and grab an API key, as mentioned in the Quick Start.
365
+
366
+ #### 7.1.2 Environment setup
367
+ Claude Code and Codex rely on Node.js. We recommend installing Node.js version > v20. You can install Node via nvm.
368
+
369
+ **Mac/Linux**:
370
+ ```bash
371
+ # Install nvm on Mac/Linux via curl:
372
+ # Step 1
373
+ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
374
+
375
+ # Copy the full command
376
+ export NVM_DIR="$HOME/.nvm"
377
+ [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
378
+ [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"
379
+
380
+ # Users in China can set up npm mirror
381
+ config set registry https://registry.npmmirror.com
382
+
383
+ # Step 2
384
+ nvm install v22
385
+
386
+ # Make sure Node.js is installed
387
+ node --version
388
+
389
+ npm --version
390
+ ```
391
+
392
+ **Windows**:
393
+ You can download the installation file (`nvm-setup.exe`) from [https://github.com/coreybutler/nvm-windows/releases](https://github.com/coreybutler/nvm-windows/releases). Follow the instructions to install nvm. Run nvm commands to make sure it is installed.
394
+
395
+ #### 7.1.3 Use Step 3.5 Flash on Claude Code
396
+
397
+ 1. Install Claude Code.
398
+ ```bash
399
+ # install claude code via npm
400
+ npm install -g @anthropic-ai/claude-code
401
+
402
+ # test if the installation is successful
403
+ claude --version
404
+ ```
405
+
406
+ 2. Configure Claude Code.
407
+
408
+ To accommodate diverse workflows in Claude Code, we support both **Anthropic-style** and **OpenAI-style** APIs.
409
+
410
+ **Option A: Anthropic API style**:
411
+
412
+ > If you intend to use the **OpenRouter** API, refer to the OpenRouter integration guide.
413
+
414
+ Step 1: Edit Claude Settings. Update `~/.claude/settings.json`.
415
+ > You only need to modify the fields shown below. Leave the rest of the file unchanged.
416
+
417
+ ```json
418
+ {
419
+ "env": {
420
+ "ANTHROPIC_API_KEY": "API_KEY_from_StepFun",
421
+ "ANTHROPIC_BASE_URL": "https://api.stepfun.ai/"
422
+ },
423
+ "model": "step-3.5-flash"
424
+ }
425
+ ```
426
+ Step 2: Start Claude Code.
427
+
428
+ Save the file, and then start Claude Code. Run `/status` to confirm the model and base URL.
429
+
430
+ ```txt
431
+ ❯ /status
432
+ ─────────────────────────────────────────────────────────────────────────────────
433
+ Settings: Status Config Usage (←/→ or tab to cycle)
434
+
435
+ Version: 2.1.1
436
+ Session name: /rename to add a name
437
+ Session ID: 676dae61-259d-4eef-8c2f-0f1641600553
438
+ cwd: /Users/step-test/
439
+ Auth token: none
440
+ API key: ANTHROPIC_API_KEY
441
+ Anthropic base URL: https://api.stepfun.ai/
442
+
443
+ Model: step-3.5-flash
444
+ Setting sources: User settings
445
+ ```
446
+
447
+ **Option B: OpenAI API style**
448
+
449
+ > Note: OpenAI API style here refers to the `chat/completions/` format.
450
+
451
+ > We recommend using `claude-code-router`. For details, see [https://github.com/musistudio/claude-code-router](https://github.com/musistudio/claude-code-router).
452
+
453
+ After Claude Code is installed, install `claude-code-router` :
454
+
455
+ ```bash
456
+ # install ccr via npm
457
+ npm install -g @musistudio/claude-code-router
458
+
459
+ # validate it is installed
460
+ ccr -v
461
+ ```
462
+
463
+ Add the following configurations to `~/.claude-code-router/config.json`.
464
+
465
+ ```json
466
+ {
467
+ "PORT": 3456,
468
+ "Providers": [
469
+ {
470
+ "name": "stepfun-api",
471
+ "api_base_url": "https://api.stepfun.com/v1/chat/completions",
472
+ "api_key": "StepFun_API_KEY",
473
+ "models": ["step-3.5-flash"],
474
+ "transformer":{
475
+ "step-3.5-flash": { "use": ["OpenAI"]}
476
+ }
477
+ }
478
+ ],
479
+ "Router": {
480
+ "default": "stepfun-api,step-3.5-flash",
481
+ "background": "stepfun-api,step-3.5-flash",
482
+ "think": "stepfun-api,step-3.5-flash",
483
+ "longContext": "stepfun-api,step-3.5-flash",
484
+ "webSearch": "stepfun-api,step-3.5-flash"
485
+ }
486
+ }
487
+ ```
488
+ You can now start Claude Code:
489
+
490
+ ```bash
491
+ # Start Claude
492
+ ccr code
493
+
494
+ # restart ccr if configs are changed
495
+ ccr restart
496
+ ```
497
+
498
+ #### 7.1.4 Use Step 3.5 Flash on Codex
499
+ 1. Install Codex
500
+ ```bash
501
+ # Install codex via npm
502
+ npm install -g @openai/codex
503
+
504
+ # Test if it is installed
505
+ codex --version
506
+ ```
507
+
508
+ 2. Configure Codex
509
+ Add the following settings to `~/.codex/config.toml`, keeping the rest of the settings as they are.
510
+
511
+ ```json
512
+ model="step-3.5-flash"
513
+ model_provider = "stepfun-chat"
514
+ preferred_auth_method = "apikey"
515
+
516
+ # configure the provider
517
+ [model_providers.stepfun-chat]
518
+ name = "OpenAI using response"
519
+ base_url = "https://api.stepfun.com/v1"
520
+ env_key = "OPENAI_API_KEY"
521
+ wire_api = "chat"
522
+ query_params = {}
523
+ ```
524
+
525
+ For Codex, `wire_api` only supports `chat` . If you use the `responses` mode, you'll need to change to `chat`. Please also switch `model_provider` to the newly configured `stepfun-chat`.
526
+
527
+ When finishing the configuration, run codex in a new Terminal window to start Codex. Run `/status` to check the configuration.
528
+
529
+ ```bash
530
+ /status
531
+ 📂 Workspace
532
+ • Path: /Users/step-test/
533
+ • Approval Mode: on-request
534
+ • Sandbox: workspace-write
535
+ • AGENTS files: (none)
536
+
537
+ 🧠 Model
538
+ • Name: step-3.5-flash
539
+ • Provider: Stepfun-chat
540
+
541
+ 💻 Client
542
+ • CLI Version: 0.40.0
543
+ ```
544
+
545
+ #### 7.1.5 Use Step 3.5 Flash on Step-DeepResearch (DeepResearch)
546
+ 1. Use the reference environment setup below and configure `MODEL_NAME` to `Step-3.5-Flash`. [https://github.com/stepfun-ai/StepDeepResearch?tab=readme-ov-file#1-environment-setup](https://github.com/stepfun-ai/StepDeepResearch?tab=readme-ov-file#1-environment-setup)
547
+
548
+
549
+ ## 8. Known Issues and Future Directions
550
+
551
+ 1. **Token Efficiency**. Step 3.5 Flash achieves frontier-level agentic intelligence but currently relies on longer generation trajectories than Gemini 3.0 Pro to reach comparable quality.
552
+ 2. **Efficient Universal Mastery**. We aim to unify generalist versatility with deep domain expertise. To achieve this efficiently, we are advancing variants of on-policy distillation, allowing the model to internalize expert behaviors with higher sample efficiency.
553
+ 3. **RL for More Agentic Tasks**. While Step 3.5 Flash demonstrates competitive performance on academic agentic benchmarks, the next frontier of agentic AI necessitates the application of RL to intricate, expert-level tasks found in professional work, engineering, and research.
554
+ 4. **Operational Scope and Constraints**. Step 3.5 Flash is tailored for coding and work-centric tasks, but may experience reduced stability during distribution shifts. This typically occurs in highly specialized domains or long-horizon, multi-turn dialogues, where the model may exhibit repetitive reasoning, mixed-language outputs, or inconsistencies in time and identity awareness.
555
+
556
+ ## 9. Co-Developing the Future
557
+
558
+ We view our roadmap as a living document, evolving continuously based on real-world usage and developer feedback.
559
+ As we work to shape the future of AGI by expanding broad model capabilities, we want to ensure we are solving the right problems. We invite you to be part of this continuous feedback loop—your insights directly influence our priorities.
560
+
561
+ - **Join the Conversation**: Our Discord community is the primary hub for brainstorming future architectures, proposing capabilities, and getting early access updates 🚀
562
+ - **Report Friction**: Encountering limitations? You can open an issue on GitHub or flag it directly in our Discord support channels.
563
+
564
+ ## 📜 Citation
565
+
566
+ If you find this project useful in your research, please cite our technical report:
567
+
568
+ ```tex
569
+ @misc{huang2026step35flashopen,
570
+ title={Step 3.5 Flash: Open Frontier-Level Intelligence with 11B Active Parameters},
571
+ author={Ailin Huang and Ang Li and Aobo Kong and Bin Wang and Binxing Jiao and Bo Dong and Bojun Wang and Boyu Chen and Brian Li and Buyun Ma and Chang Su and Changxin Miao and Changyi Wan and Chao Lou and Chen Hu and Chen Xu and Chenfeng Yu and Chengting Feng and Chengyuan Yao and Chunrui Han and Dan Ma and Dapeng Shi and Daxin Jiang and Dehua Ma and Deshan Sun and Di Qi and Enle Liu and Fajie Zhang and Fanqi Wan and Guanzhe Huang and Gulin Yan and Guoliang Cao and Guopeng Li and Han Cheng and Hangyu Guo and Hanshan Zhang and Hao Nie and Haonan Jia and Haoran Lv and Hebin Zhou and Hekun Lv and Heng Wang and Heung-Yeung Shum and Hongbo Huang and Hongbo Peng and Hongyu Zhou and Hongyuan Wang and Houyong Chen and Huangxi Zhu and Huimin Wu and Huiyong Guo and Jia Wang and Jian Zhou and Jianjian Sun and Jiaoren Wu and Jiaran Zhang and Jiashu Lv and Jiashuo Liu and Jiayi Fu and Jiayu Liu and Jie Cheng and Jie Luo and Jie Yang and Jie Zhou and Jieyi Hou and Jing Bai and Jingcheng Hu and Jingjing Xie and Jingwei Wu and Jingyang Zhang and Jishi Zhou and Junfeng Liu and Junzhe Lin and Ka Man Lo and Kai Liang and Kaibo Liu and Kaijun Tan and Kaiwen Yan and Kaixiang Li and Kang An and Kangheng Lin and Lei Yang and Liang Lv and Liang Zhao and Liangyu Chen and Lieyu Shi and Liguo Tan and Lin Lin and Lina Chen and Luck Ma and Mengqiang Ren and Michael Li and Ming Li and Mingliang Li and Mingming Zhang and Mingrui Chen and Mitt Huang and Na Wang and Peng Liu and Qi Han and Qian Zhao and Qinglin He and Qinxin Du and Qiuping Wu and Quan Sun and Rongqiu Yang and Ruihang Miao and Ruixin Han and Ruosi Wan and Ruyan Guo and Shan Wang and Shaoliang Pang and Shaowen Yang and Shengjie Fan and Shijie Shang and Shiliang Yang and Shiwei Li and Shuangshuang Tian and Siqi Liu and Siye Wu and Siyu Chen and Song Yuan and Tiancheng Cao and Tianchi Yue and Tianhao Cheng and Tianning Li and Tingdan Luo and Wang You and Wei Ji and Wei Yuan and Wei Zhang and Weibo Wu and Weihao Xie and Wen Sun and Wenjin Deng and Wenzhen Zheng and Wuxun Xie and Xiangfeng Wang and Xiangwen Kong and Xiangyu Liu and Xiangyu Zhang and Xiaobo Yang and Xiaojia Liu and Xiaolan Yuan and Xiaoran Jiao and Xiaoxiao Ren and Xiaoyun Zhang and Xin Li and Xin Liu and Xin Wu and Xing Chen and Xingping Yang and Xinran Wang and Xu Zhao and Xuan He and Xuanti Feng and Xuedan Cai and Xuqiang Zhou and Yanbo Yu and Yang Li and Yang Xu and Yanlin Lai and Yanming Xu and Yaoyu Wang and Yeqing Shen and Yibo Zhu and Yichen Lv and Yicheng Cao and Yifeng Gong and Yijing Yang and Yikun Yang and Yin Zhao and Yingxiu Zhao and Yinmin Zhang and Yitong Zhang and Yixuan Zhang and Yiyang Chen and Yongchi Zhao and Yongshen Long and Yongyao Wang and Yousong Guan and Yu Zhou and Yuang Peng and Yuanhao Ding and Yuantao Fan and Yuanzhen Yang and Yuchu Luo and Yudi Zhao and Yue Peng and Yueqiang Lin and Yufan Lu and Yuling Zhao and Yunzhou Ju and Yurong Zhang and Yusheng Li and Yuxiang Yang and Yuyang Chen and Yuzhu Cai and Zejia Weng and Zetao Hong and Zexi Li and Zhe Xie and Zheng Ge and Zheng Gong and Zheng Zeng and Zhenyi Lu and Zhewei Huang and Zhichao Chang and Zhiguo Huang and Zhiheng Hu and Zidong Yang and Zili Wang and Ziqi Ren and Zixin Zhang and Zixuan Wang},
572
+ year={2026},
573
+ eprint={2602.10604},
574
+ archivePrefix={arXiv},
575
+ primaryClass={cs.CL},
576
+ url={https://arxiv.org/abs/2602.10604},
577
+ }
578
+ ```
579
+
580
+ ## License
581
+ This project is open-sourced under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0).
chat_template.jinja ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% macro render_content(content) %}{% if content is none %}{{- '' }}{% elif content is string %}{{- content }}{% elif content is mapping %}{{- content['value'] if 'value' in content else content['text'] }}{% elif content is iterable %}{% for item in content %}{% if item.type == 'text' %}{{- item['value'] if 'value' in item else item['text'] }}{% elif item.type == 'image' %}<im_patch>{% endif %}{% endfor %}{% endif %}{% endmacro %}
2
+ {{bos_token}}{%- if tools %}
3
+ {{- '<|im_start|>system\n' }}
4
+ {%- if messages[0].role == 'system' %}
5
+ {{- render_content(messages[0].content) + '\n\n' }}
6
+ {%- endif %}
7
+ {{- "# Tools\n\nYou have access to the following functions in JSONSchema format:\n\n<tools>" }}
8
+ {%- for tool in tools %}
9
+ {{- "\n" }}
10
+ {{- tool | tojson(ensure_ascii=False) }}
11
+ {%- endfor %}
12
+ {{- "\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...>\n...\n</function> block must be nested within <tool_call>\n...\n</tool_call> XML tags\n- Required parameters MUST be specified\n</IMPORTANT><|im_end|>\n" }}
13
+ {%- else %}
14
+ {%- if messages[0].role == 'system' %}
15
+ {{- '<|im_start|>system\n' + render_content(messages[0].content) + '<|im_end|>\n' }}
16
+ {%- endif %}
17
+ {%- endif %}
18
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
19
+ {%- for message in messages[::-1] %}
20
+ {%- set index = (messages|length - 1) - loop.index0 %}
21
+ {%- if ns.multi_step_tool and message.role == "user" and render_content(message.content) is string and not(render_content(message.content).startswith('<tool_response>') and render_content(message.content).endswith('</tool_response>')) %}
22
+ {%- set ns.multi_step_tool = false %}
23
+ {%- set ns.last_query_index = index %}
24
+ {%- endif %}
25
+ {%- endfor %}
26
+ {%- for message in messages %}
27
+ {%- set content = render_content(message.content) %}
28
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
29
+ {%- set role_name = 'observation' if (message.role == "system" and not loop.first and message.name == 'observation') else message.role %}
30
+ {{- '<|im_start|>' + role_name + '\n' + content + '<|im_end|>' + '\n' }}
31
+ {%- elif message.role == "assistant" %}
32
+ {%- if message.reasoning_content is string %}
33
+ {%- set reasoning_content = render_content(message.reasoning_content) %}
34
+ {%- else %}
35
+ {%- if '</think>' in content %}
36
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
37
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
38
+ {%- else %}
39
+ {%- set reasoning_content = '' %}
40
+ {%- endif %}
41
+ {%- endif %}
42
+ {%- if loop.index0 > ns.last_query_index %}
43
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n' + content }}
44
+ {%- else %}
45
+ {{- '<|im_start|>' + message.role + '\n' + content }}
46
+ {%- endif %}
47
+ {%- if message.tool_calls %}
48
+ {%- for tool_call in message.tool_calls %}
49
+ {%- if tool_call.function is defined %}
50
+ {%- set tool_call = tool_call.function %}
51
+ {%- endif %}
52
+ {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
53
+ {%- if tool_call.arguments is defined %}
54
+ {%- set arguments = tool_call.arguments %}
55
+ {%- for args_name, args_value in arguments|items %}
56
+ {{- '<parameter=' + args_name + '>\n' }}
57
+ {%- set args_value = args_value | tojson(ensure_ascii=False) | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
58
+ {{- args_value }}
59
+ {{- '\n</parameter>\n' }}
60
+ {%- endfor %}
61
+ {%- endif %}
62
+ {{- '</function>\n</tool_call>' }}
63
+ {%- endfor %}
64
+ {%- endif %}
65
+ {{- '<|im_end|>\n' }}
66
+ {%- elif message.role == "tool" %}
67
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
68
+ {{- '<|im_start|>tool_response\n' }}
69
+ {%- endif %}
70
+ {{- '<tool_response>' }}
71
+ {{- content }}
72
+ {{- '</tool_response>' }}
73
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
74
+ {{- '<|im_end|>\n' }}
75
+ {%- endif %}
76
+ {%- endif %}
77
+ {%- endfor %}
78
+ {%- if add_generation_prompt %}
79
+ {{- '<|im_start|>assistant\n<think>\n' }}
80
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Step3p5ForCausalLM"
4
+ ],
5
+ "model_type": "step3p5",
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_step3p5.Step3p5Config",
8
+ "AutoModelForCausalLM": "modeling_step3p5.Step3p5ForCausalLM"
9
+ },
10
+ "rope_scaling": {
11
+ "rope_type": "llama3",
12
+ "factor": 2.0,
13
+ "original_max_position_embeddings": 131072,
14
+ "low_freq_factor": 1.0,
15
+ "high_freq_factor": 32.0
16
+ },
17
+ "yarn_only_types": [
18
+ "full_attention"
19
+ ],
20
+ "hidden_size": 4096,
21
+ "intermediate_size": 11264,
22
+ "num_hidden_layers": 45,
23
+ "max_seq_len": 262144,
24
+ "vocab_size": 128896,
25
+ "torch_dtype": "bfloat16",
26
+ "use_qk_norm": true,
27
+ "moe_layers_enum": "3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44",
28
+ "num_attention_heads": 64,
29
+ "num_attention_groups": 8,
30
+ "head_dim": 128,
31
+ "use_moe": true,
32
+ "moe_num_experts": 288,
33
+ "moe_top_k": 8,
34
+ "moe_intermediate_size": 1280,
35
+ "share_expert_dim": 1280,
36
+ "moe_layer_offset": 0,
37
+ "moe_every_n_layer": 1,
38
+ "norm_expert_weight": true,
39
+ "moe_router_activation": "sigmoid",
40
+ "moe_router_scaling_factor": 3.0,
41
+ "att_impl_type": "GQA",
42
+ "rope_theta": [
43
+ 5000000.0,
44
+ 10000.0,
45
+ 10000.0,
46
+ 10000.0,
47
+ 5000000.0,
48
+ 10000.0,
49
+ 10000.0,
50
+ 10000.0,
51
+ 5000000.0,
52
+ 10000.0,
53
+ 10000.0,
54
+ 10000.0,
55
+ 5000000.0,
56
+ 10000.0,
57
+ 10000.0,
58
+ 10000.0,
59
+ 5000000.0,
60
+ 10000.0,
61
+ 10000.0,
62
+ 10000.0,
63
+ 5000000.0,
64
+ 10000.0,
65
+ 10000.0,
66
+ 10000.0,
67
+ 5000000.0,
68
+ 10000.0,
69
+ 10000.0,
70
+ 10000.0,
71
+ 5000000.0,
72
+ 10000.0,
73
+ 10000.0,
74
+ 10000.0,
75
+ 5000000.0,
76
+ 10000.0,
77
+ 10000.0,
78
+ 10000.0,
79
+ 5000000.0,
80
+ 10000.0,
81
+ 10000.0,
82
+ 10000.0,
83
+ 5000000.0,
84
+ 10000.0,
85
+ 10000.0,
86
+ 10000.0,
87
+ 5000000.0,
88
+ 10000.0,
89
+ 10000.0,
90
+ 10000.0
91
+ ],
92
+ "use_head_wise_attn_gate": true,
93
+ "sliding_window": 512,
94
+ "use_moe_router_bias": true,
95
+ "need_fp32_gate": true,
96
+ "sink": false,
97
+ "layer_types": [
98
+ "full_attention",
99
+ "sliding_attention",
100
+ "sliding_attention",
101
+ "sliding_attention",
102
+ "full_attention",
103
+ "sliding_attention",
104
+ "sliding_attention",
105
+ "sliding_attention",
106
+ "full_attention",
107
+ "sliding_attention",
108
+ "sliding_attention",
109
+ "sliding_attention",
110
+ "full_attention",
111
+ "sliding_attention",
112
+ "sliding_attention",
113
+ "sliding_attention",
114
+ "full_attention",
115
+ "sliding_attention",
116
+ "sliding_attention",
117
+ "sliding_attention",
118
+ "full_attention",
119
+ "sliding_attention",
120
+ "sliding_attention",
121
+ "sliding_attention",
122
+ "full_attention",
123
+ "sliding_attention",
124
+ "sliding_attention",
125
+ "sliding_attention",
126
+ "full_attention",
127
+ "sliding_attention",
128
+ "sliding_attention",
129
+ "sliding_attention",
130
+ "full_attention",
131
+ "sliding_attention",
132
+ "sliding_attention",
133
+ "sliding_attention",
134
+ "full_attention",
135
+ "sliding_attention",
136
+ "sliding_attention",
137
+ "sliding_attention",
138
+ "full_attention",
139
+ "sliding_attention",
140
+ "sliding_attention",
141
+ "sliding_attention",
142
+ "full_attention",
143
+ "sliding_attention",
144
+ "sliding_attention",
145
+ "sliding_attention"
146
+ ],
147
+ "use_rope_layers": [],
148
+ "num_nextn_predict_layers": 3,
149
+ "partial_rotary_factors": [
150
+ 0.5,
151
+ 1.0,
152
+ 1.0,
153
+ 1.0,
154
+ 0.5,
155
+ 1.0,
156
+ 1.0,
157
+ 1.0,
158
+ 0.5,
159
+ 1.0,
160
+ 1.0,
161
+ 1.0,
162
+ 0.5,
163
+ 1.0,
164
+ 1.0,
165
+ 1.0,
166
+ 0.5,
167
+ 1.0,
168
+ 1.0,
169
+ 1.0,
170
+ 0.5,
171
+ 1.0,
172
+ 1.0,
173
+ 1.0,
174
+ 0.5,
175
+ 1.0,
176
+ 1.0,
177
+ 1.0,
178
+ 0.5,
179
+ 1.0,
180
+ 1.0,
181
+ 1.0,
182
+ 0.5,
183
+ 1.0,
184
+ 1.0,
185
+ 1.0,
186
+ 0.5,
187
+ 1.0,
188
+ 1.0,
189
+ 1.0,
190
+ 0.5,
191
+ 1.0,
192
+ 1.0,
193
+ 1.0,
194
+ 0.5,
195
+ 1.0,
196
+ 1.0,
197
+ 1.0
198
+ ],
199
+ "eos_token_id": [
200
+ 1,
201
+ 2,
202
+ 128007
203
+ ],
204
+ "bos_token_id": 0,
205
+ "pad_token_id": 0,
206
+ "attention_other_setting": {
207
+ "attention_type": "sliding_attention",
208
+ "num_attention_heads": 96,
209
+ "num_attention_groups": 8,
210
+ "head_dim": 128,
211
+ "true_head_dim": 128
212
+ },
213
+ "swiglu_limits": [
214
+ 0.0,
215
+ 0.0,
216
+ 0.0,
217
+ 0.0,
218
+ 0.0,
219
+ 0.0,
220
+ 0.0,
221
+ 0.0,
222
+ 0.0,
223
+ 0.0,
224
+ 0.0,
225
+ 0.0,
226
+ 0.0,
227
+ 0.0,
228
+ 0.0,
229
+ 0.0,
230
+ 0.0,
231
+ 0.0,
232
+ 0.0,
233
+ 0.0,
234
+ 0.0,
235
+ 0.0,
236
+ 0.0,
237
+ 0.0,
238
+ 0.0,
239
+ 0.0,
240
+ 0.0,
241
+ 0.0,
242
+ 0.0,
243
+ 0.0,
244
+ 0.0,
245
+ 0.0,
246
+ 0.0,
247
+ 0.0,
248
+ 0.0,
249
+ 0.0,
250
+ 0.0,
251
+ 0.0,
252
+ 0.0,
253
+ 0.0,
254
+ 0.0,
255
+ 0.0,
256
+ 0.0,
257
+ 7,
258
+ 7,
259
+ 0.0,
260
+ 0.0,
261
+ 0.0
262
+ ],
263
+ "swiglu_limits_shared": [
264
+ 0.0,
265
+ 0.0,
266
+ 0.0,
267
+ 0.0,
268
+ 0.0,
269
+ 0.0,
270
+ 0.0,
271
+ 0.0,
272
+ 0.0,
273
+ 0.0,
274
+ 0.0,
275
+ 0.0,
276
+ 0.0,
277
+ 0.0,
278
+ 0.0,
279
+ 0.0,
280
+ 0.0,
281
+ 0.0,
282
+ 0.0,
283
+ 0.0,
284
+ 0.0,
285
+ 0.0,
286
+ 0.0,
287
+ 0.0,
288
+ 0.0,
289
+ 0.0,
290
+ 0.0,
291
+ 0.0,
292
+ 0.0,
293
+ 0.0,
294
+ 0.0,
295
+ 0.0,
296
+ 0.0,
297
+ 0.0,
298
+ 0.0,
299
+ 0.0,
300
+ 0.0,
301
+ 0.0,
302
+ 0.0,
303
+ 0.0,
304
+ 0.0,
305
+ 0.0,
306
+ 0.0,
307
+ 0.0,
308
+ 16,
309
+ 0.0,
310
+ 0.0,
311
+ 0.0
312
+ ],
313
+ "zero_centered": true,
314
+ "max_position_embeddings": 262144,
315
+ "quantization_config": {
316
+ "quant_method": "exl3",
317
+ "version": "0.0.22",
318
+ "bits": 3.0,
319
+ "head_bits": 6,
320
+ "calibration": {
321
+ "rows": 250,
322
+ "cols": 2048
323
+ },
324
+ "out_scales": "always",
325
+ "codebook": "mcg"
326
+ }
327
+ }
configuration_step3p5.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Optional, Union
2
+
3
+ from transformers.configuration_utils import PretrainedConfig
4
+
5
+
6
+
7
+ class Step3p5Config(PretrainedConfig):
8
+ model_type = "step3p5"
9
+ architectures = ["Step3p5ForCausalLM"]
10
+
11
+ def __init__(
12
+ self,
13
+ hidden_size: int = 4096,
14
+ intermediate_size: int = 11264,
15
+ num_attention_heads: int = 64,
16
+ num_attention_groups: int = 8,
17
+ num_hidden_layers: int = 45,
18
+ max_seq_len: int = 128000,
19
+ vocab_size: int = 128815,
20
+ rms_norm_eps: float = 1e-5,
21
+ moe_intermediate_size: int = 1280,
22
+ moe_num_experts: int = 288,
23
+ moe_top_k: int = 8,
24
+ rope_theta: float = 10000,
25
+ rope_scaling: Optional[dict[str, Any]] = None,
26
+ max_position_embeddings: int = 128000,
27
+ share_expert_dims: int = 1280,
28
+ head_dim: int = 128,
29
+ norm_expert_weight: bool = True,
30
+ layer_types: list[str] = None,
31
+ sliding_window: Optional[int] = None,
32
+ moe_layers_enum: tuple[int] = (3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
33
+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
34
+ 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
35
+ 35, 36, 37, 38, 39, 40, 41, 42, 43, 44),
36
+ **kwargs,
37
+ ) -> None:
38
+ self.hidden_size = hidden_size
39
+ self.intermediate_size = intermediate_size
40
+ self.num_attention_heads = num_attention_heads
41
+ self.num_attention_groups = num_attention_groups
42
+ self.num_hidden_layers = num_hidden_layers
43
+ self.max_seq_len = max_seq_len
44
+ self.vocab_size = vocab_size
45
+ self.rms_norm_eps = rms_norm_eps
46
+ self.moe_intermediate_size = moe_intermediate_size
47
+ self.moe_num_experts = moe_num_experts
48
+ self.moe_top_k = moe_top_k
49
+ self.rope_theta = rope_theta
50
+ self.rope_scaling = rope_scaling
51
+ self.max_position_embeddings = max_position_embeddings
52
+ self.share_expert_dim = share_expert_dims
53
+ self.head_dim = head_dim
54
+ self.norm_expert_weight = norm_expert_weight
55
+ self.moe_layers_enum = moe_layers_enum
56
+ self.layer_types = layer_types
57
+ self.sliding_window = sliding_window
58
+ self.use_cache = True
59
+ super().__init__(**kwargs)
60
+
model-00001-of-00011.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:df8e12f0932a196c7c1c3a000c1cf61dc30b31b48cba12340b2e4ba8e7bdf5cd
3
+ size 8345423429
model-00002-of-00011.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eacc0fa73340dbcaf5d44bc2d68a5faf7264a9d628c6f54ecb51757abf75ff3c
3
+ size 7021015425
model-00003-of-00011.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c92ee7816e7ffafc3f8181d3946d206c673406cf8e0cbe1c8dc01bbbe3ab491e
3
+ size 7021025898
model-00004-of-00011.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0fb089a6aea4c503587606216ebc55096ff9fddd5bb5cc95b7a1a69040855423
3
+ size 7021025898
model-00005-of-00011.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4d459a78da9947ac7137cb03560ea96f980f23f2e531b79369b84ba26441a19a
3
+ size 7021025898
model-00006-of-00011.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d86dac4c2eedbd6b880d398b836db5b74c68d5d92af0f6740d45ad2f1f5d8eb6
3
+ size 7021025898
model-00007-of-00011.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e7f477e02ac7976ac922158c149e5f54e4a6ff2530bf79334857fc8d78f61d4b
3
+ size 7021025898
model-00008-of-00011.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:59e4e130cd44396626eba4efec086790241b15502b7ddf9833617ddbbce720a6
3
+ size 7021025898
model-00009-of-00011.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9b6031033e0f7384307c67a2b56a0b9a8cb0c4278f0b9c01c702fa36530d7769
3
+ size 7021025898
model-00010-of-00011.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:888980ee35bfc7b35aae5b5030269697bedbf7b661f44d503827a3d929fde4a0
3
+ size 7021025898
model-00011-of-00011.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c94a7ddc675f9c4c2ef2124de16dcb7c8ae7f993523e03f4a76c49f2a2d5d5bd
3
+ size 3900323099
model.safetensors.index.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b3d066152700a34baa6c114d2aa7c6420a5dcf08a3cde4f2fcae3f8529855105
3
+ size 13604905
modeling_step3p5.py ADDED
@@ -0,0 +1,899 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # # Copyright 2025 The LLAMA4 and HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ from dataclasses import dataclass
16
+ from typing import Callable, Optional, Tuple, Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+ from transformers.activations import ACT2FN
22
+ from transformers.cache_utils import Cache, DynamicCache
23
+ from transformers.generation import GenerationMixin
24
+ from transformers.masking_utils import (create_causal_mask,
25
+ create_sliding_window_causal_mask)
26
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
27
+ from transformers.modeling_layers import GradientCheckpointingLayer
28
+ from transformers.modeling_outputs import BaseModelOutputWithPast, ModelOutput
29
+ from transformers.modeling_rope_utils import (ROPE_INIT_FUNCTIONS,
30
+ dynamic_rope_update)
31
+ from transformers.modeling_utils import (ALL_ATTENTION_FUNCTIONS,
32
+ PreTrainedModel)
33
+ from transformers.processing_utils import Unpack
34
+ from transformers.utils import TransformersKwargs, can_return_tuple, logging
35
+
36
+ from .configuration_step3p5 import Step3p5Config
37
+
38
+ logger = logging.get_logger(__name__)
39
+
40
+ __all__ = ["Step3p5Model", "Step3p5ForCausalLM"]
41
+
42
+ class Step3p5RotaryEmbedding(nn.Module):
43
+
44
+ def __init__(self, config: Step3p5Config, device=None, layer_idx=None):
45
+ super().__init__()
46
+ # BC: "rope_type" was originally "type"
47
+ self.layer_idx = layer_idx
48
+ if config.rope_parameters is not None:
49
+ self.rope_type = config.rope_parameters.get(
50
+ "rope_type", config.rope_parameters.get("type"))
51
+ else:
52
+ self.rope_type = "default"
53
+ self.max_seq_len_cached = config.max_position_embeddings
54
+ self.original_max_seq_len = config.max_position_embeddings
55
+
56
+ partial_rotary_factors = getattr(config, "partial_rotary_factors",
57
+ None)
58
+ if partial_rotary_factors is not None:
59
+ config.partial_rotary_factor = partial_rotary_factors[
60
+ self.layer_idx]
61
+ else:
62
+ config.partial_rotary_factor = 1.0
63
+
64
+ self.rope_theta = config.rope_theta
65
+ if isinstance(config.rope_theta, list):
66
+ self.rope_theta = config.rope_theta.copy()
67
+ config.rope_theta = self.rope_theta[self.layer_idx]
68
+
69
+ self.config = config
70
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
71
+ inv_freq, self.attention_scaling = self.rope_init_fn(
72
+ self.config, device)
73
+
74
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
75
+ self.original_inv_freq = self.inv_freq
76
+ config.rope_theta = self.rope_theta
77
+
78
+ @torch.no_grad()
79
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
80
+ def forward(self, x, position_ids):
81
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(
82
+ position_ids.shape[0], -1, 1).to(x.device)
83
+ position_ids_expanded = position_ids[:, None, :].float().to(x.device)
84
+
85
+ device_type = x.device.type if isinstance(
86
+ x.device.type, str) and x.device.type != "mps" else "cpu"
87
+ with torch.autocast(device_type=device_type,
88
+ enabled=False): # Force float32
89
+ freqs = (inv_freq_expanded.float()
90
+ @ position_ids_expanded.float()).transpose(1, 2)
91
+ emb = torch.cat((freqs, freqs), dim=-1)
92
+ cos = emb.cos() * self.attention_scaling
93
+ sin = emb.sin() * self.attention_scaling
94
+
95
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
96
+
97
+
98
+ def rotate_half(x):
99
+ """Rotates half the hidden dims of the input."""
100
+ x1 = x[..., :x.shape[-1] // 2]
101
+ x2 = x[..., x.shape[-1] // 2:]
102
+ return torch.cat((-x2, x1), dim=-1)
103
+
104
+
105
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
106
+ """Applies Rotary Position Embedding to the query and key tensors.
107
+ Args:
108
+ q (`torch.Tensor`): The query tensor.
109
+ k (`torch.Tensor`): The key tensor.
110
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
111
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
112
+ position_ids (`torch.Tensor`, *optional*):
113
+ Deprecated and unused.
114
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
115
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
116
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
117
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
118
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
119
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
120
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
121
+ Returns:
122
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
123
+ """
124
+ rotary_dim = cos.shape[-1]
125
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
126
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
127
+
128
+ # Apply rotary embeddings on the first half or full tensor
129
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
130
+ k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
131
+
132
+ # Concatenate back to full shape
133
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
134
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
135
+ return q_embed, k_embed
136
+
137
+
138
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
139
+ """
140
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
141
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
142
+ """
143
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
144
+ if n_rep == 1:
145
+ return hidden_states
146
+ hidden_states = hidden_states[:, :,
147
+ None, :, :].expand(batch,
148
+ num_key_value_heads,
149
+ n_rep, slen, head_dim)
150
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen,
151
+ head_dim)
152
+
153
+
154
+ # Adapted from transformers.models.llama.modeling_llama.eager_attention_forward -> llama4 doesn't cast attn weights to fp32
155
+ def eager_attention_forward(
156
+ module: nn.Module,
157
+ query: torch.Tensor,
158
+ key: torch.Tensor,
159
+ value: torch.Tensor,
160
+ attention_mask: Optional[torch.Tensor],
161
+ scaling: float,
162
+ dropout: float = 0.0,
163
+ **kwargs,
164
+ ):
165
+ key_states = repeat_kv(key, module.num_key_value_groups)
166
+ value_states = repeat_kv(value, module.num_key_value_groups)
167
+ # breakpoint()
168
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
169
+ if attention_mask is not None:
170
+ causal_mask = attention_mask[:, :, :, :key_states.shape[-2]]
171
+ attn_weights = attn_weights + causal_mask
172
+
173
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
174
+ attn_weights = nn.functional.dropout(attn_weights,
175
+ p=dropout,
176
+ training=module.training)
177
+ attn_output = torch.matmul(attn_weights, value_states)
178
+ attn_output = attn_output.transpose(1, 2).contiguous()
179
+
180
+ return attn_output, attn_weights
181
+
182
+ @dataclass
183
+ class Step3p5CausalLMOutputWithPast(ModelOutput):
184
+ r"""
185
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
186
+ Language modeling loss (for next-token prediction).
187
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
188
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
189
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
190
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
191
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
192
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
193
+ `past_key_values` input) to speed up sequential decoding.
194
+ """
195
+
196
+ loss: Optional[torch.FloatTensor] = None
197
+ last_hidden_state: Optional[torch.FloatTensor] = None
198
+ logits: torch.FloatTensor = None
199
+ past_key_values: Optional[list[torch.FloatTensor]] = None
200
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
201
+ attentions: Optional[tuple[torch.FloatTensor]] = None
202
+
203
+
204
+ class Step3p5MLP(nn.Module):
205
+
206
+ def __init__(self, config, intermediate_size=None, swiglu_limit=None):
207
+ super().__init__()
208
+ self.config = config
209
+ self.hidden_size = config.hidden_size
210
+ self.intermediate_size = intermediate_size if intermediate_size is not None else config.intermediate_size
211
+ self.gate_proj = nn.Linear(self.hidden_size,
212
+ self.intermediate_size,
213
+ bias=False)
214
+ self.up_proj = nn.Linear(self.hidden_size,
215
+ self.intermediate_size,
216
+ bias=False)
217
+ self.down_proj = nn.Linear(self.intermediate_size,
218
+ self.hidden_size,
219
+ bias=False)
220
+ self.act_fn = ACT2FN["silu"]
221
+ self.limit = swiglu_limit
222
+
223
+ def forward(self, x):
224
+ up = self.up_proj(x)
225
+ gate = self.act_fn(self.gate_proj(x))
226
+ if self.limit is not None:
227
+ gate = gate.clamp(min=None, max=self.limit)
228
+ up = up.clamp(min=-self.limit, max=self.limit)
229
+
230
+ return self.down_proj(gate * up)
231
+
232
+
233
+ def sigmoid_routing_function(gating_output: torch.Tensor, topk: int,
234
+ renormalize: bool):
235
+ gating_output = gating_output.float()
236
+ gate_prob = torch.sigmoid(gating_output)
237
+ gate_prob = gate_prob / gate_prob.sum(dim=-1, keepdim=True)
238
+ topk_prob, indices = torch.topk(gate_prob, k=topk, dim=1)
239
+ expert_topk_weight = topk_prob
240
+ if renormalize:
241
+ expert_topk_weight = expert_topk_weight / torch.sum(
242
+ expert_topk_weight, dim=-1, keepdim=True)
243
+ return expert_topk_weight, indices
244
+
245
+
246
+ def softmax_routing_function(gating_output: torch.Tensor, top_k: int,
247
+ renormalize: bool):
248
+ gating_output = gating_output.float()
249
+ gate_prob = torch.softmax(gating_output, dim=-1)
250
+ gate_prob = gate_prob / gate_prob.sum(dim=-1, keepdim=True)
251
+ topk_prob, indices = torch.topk(gate_prob, k=top_k, dim=1)
252
+ expert_topk_weight = topk_prob
253
+ if renormalize:
254
+ expert_topk_weight = expert_topk_weight / torch.sum(
255
+ expert_topk_weight, dim=-1, keepdim=True)
256
+ return expert_topk_weight, indices.to(torch.int32)
257
+
258
+
259
+ class MoELinear(nn.Module):
260
+
261
+ def __init__(self, num_experts, in_features, out_features):
262
+ super().__init__()
263
+ self.num_experts = num_experts
264
+ self.in_features = in_features
265
+ self.out_features = out_features
266
+ self.weight = nn.Parameter(
267
+ torch.empty(num_experts, out_features, in_features))
268
+
269
+ def forward(self, x, expert_id):
270
+ x = F.linear(x.float(), self.weight[expert_id].float())
271
+ return x
272
+
273
+
274
+ class Step3p5MoEMLP(nn.Module):
275
+
276
+ def __init__(self, config, swiglu_limit=None):
277
+ super().__init__()
278
+ self.num_experts = config.moe_num_experts
279
+ self.top_k = config.moe_top_k
280
+ self.hidden_size = config.hidden_size
281
+ self.moe_intermediate_size = config.moe_intermediate_size
282
+
283
+ self.use_moe_router_bias = config.use_moe_router_bias
284
+ if self.use_moe_router_bias:
285
+ self.router_bias = nn.Parameter(torch.zeros(config.moe_num_experts,
286
+ dtype=torch.float32),
287
+ requires_grad=False)
288
+ self.custom_routing_function = self.router_bias_func
289
+ elif config.moe_router_activation == "sigmoid":
290
+ self.custom_routing_function = sigmoid_routing_function
291
+ else:
292
+ self.custom_routing_function = None
293
+ self.need_fp32_gate = config.need_fp32_gate
294
+ self.routed_scaling_factor = getattr(config,
295
+ "moe_router_scaling_factor", 1.0)
296
+
297
+ # gating
298
+ self.gate = nn.Linear(self.hidden_size, self.num_experts, bias=False)
299
+
300
+ self.act_fn = ACT2FN["silu"]
301
+ self.limit = swiglu_limit
302
+
303
+ self.up_proj = MoELinear(self.num_experts, self.hidden_size,
304
+ self.moe_intermediate_size)
305
+ self.gate_proj = MoELinear(self.num_experts, self.hidden_size,
306
+ self.moe_intermediate_size)
307
+ self.down_proj = MoELinear(self.num_experts,
308
+ self.moe_intermediate_size,
309
+ self.hidden_size)
310
+
311
+ def router_bias_func(self, gating_output: torch.Tensor, topk: int,
312
+ renormalize: bool):
313
+ gate_prob = torch.sigmoid(gating_output.float())
314
+ gate_prob_with_bias = gate_prob + self.router_bias.unsqueeze(0)
315
+ _, indices = torch.topk(gate_prob_with_bias, k=topk, dim=1)
316
+ topk_prob = torch.gather(gate_prob, 1, indices)
317
+ expert_topk_weight = topk_prob
318
+ if renormalize:
319
+ expert_topk_weight = expert_topk_weight / (
320
+ torch.sum(expert_topk_weight, dim=-1, keepdim=True) + 1e-20)
321
+ return expert_topk_weight, indices
322
+
323
+ def get_expert_output(self, inputs: torch.Tensor, expert_id):
324
+ #if self.limit is None:
325
+ up = self.up_proj(inputs, expert_id)
326
+ gate = self.act_fn(self.gate_proj(inputs, expert_id))
327
+ if self.limit is not None:
328
+ gate = gate.clamp(min=None, max=self.limit)
329
+ up = up.clamp(min=-self.limit, max=self.limit)
330
+
331
+ return self.down_proj(gate * up, expert_id)
332
+
333
+ def forward(self, hidden_states):
334
+ """ """
335
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
336
+ hidden_states = hidden_states.view(-1, hidden_dim)
337
+ if self.need_fp32_gate:
338
+ router_logits = torch.matmul(hidden_states.to(torch.float32), self.gate.weight.t().to(torch.float32))
339
+ else:
340
+ # router_logits: (batch * sequence_length, n_experts)
341
+ router_logits = self.gate(hidden_states)
342
+
343
+ if self.custom_routing_function:
344
+ routing_weights, selected_experts = self.custom_routing_function(
345
+ router_logits, self.top_k, renormalize=True)
346
+ else:
347
+ routing_weights = F.softmax(router_logits,
348
+ dim=1,
349
+ dtype=torch.float)
350
+ routing_weights, selected_experts = torch.topk(routing_weights,
351
+ self.top_k,
352
+ dim=-1)
353
+
354
+ routing_weights = routing_weights * self.routed_scaling_factor
355
+
356
+ final_hidden_states = torch.zeros(
357
+ (batch_size * sequence_length, hidden_dim),
358
+ dtype=hidden_states.dtype,
359
+ device=hidden_states.device)
360
+
361
+ # One hot encode the selected experts to create an expert mask
362
+ # this will be used to easily index which expert is going to be sollicitated
363
+ expert_mask = torch.nn.functional.one_hot(
364
+ selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
365
+
366
+ # Loop over all available experts in the model and perform the computation on each expert
367
+ for expert_idx in range(self.num_experts):
368
+ idx, top_x = torch.where(expert_mask[expert_idx])
369
+
370
+ # Index the correct hidden states and compute the expert hidden state for
371
+ # the current expert. We need to make sure to multiply the output hidden
372
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
373
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
374
+ current_hidden_states = (
375
+ self.get_expert_output(current_state, expert_idx) *
376
+ routing_weights[top_x, idx, None])
377
+
378
+ # However `index_add_` only support torch tensors for indexing so we'll use
379
+ # the `top_x` tensor here.
380
+ final_hidden_states.index_add_(
381
+ 0, top_x, current_hidden_states.to(hidden_states.dtype))
382
+ final_hidden_states = final_hidden_states.reshape(
383
+ batch_size, sequence_length, hidden_dim)
384
+ return final_hidden_states
385
+
386
+
387
+ class Step3p5RMSNorm(nn.Module):
388
+
389
+ def __init__(
390
+ self,
391
+ hidden_size: int,
392
+ eps: float = 1e-5,
393
+ ) -> None:
394
+ super().__init__()
395
+ self.weight = nn.Parameter(torch.ones(hidden_size))
396
+ self.variance_epsilon = eps
397
+
398
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
399
+ dtype = x.dtype
400
+ x = x.float()
401
+ variance = x.pow(2).mean(dim=-1, keepdim=True)
402
+ normed = x * torch.rsqrt(variance + self.variance_epsilon)
403
+ normed = normed * (self.weight.float() + 1)
404
+ return normed.to(dtype)
405
+ class Step3p5Attention(nn.Module):
406
+
407
+ def __init__(self, config: Step3p5Config, layer_idx):
408
+ super().__init__()
409
+ self.config = config
410
+ self.layer_idx = layer_idx
411
+ self.num_attention_heads = config.num_attention_heads
412
+ self.num_key_value_heads = config.num_attention_groups
413
+
414
+ layer_types = getattr(config, "layer_types", [])
415
+ if layer_types:
416
+ enable_sliding_window = layer_types[
417
+ self.layer_idx] == "sliding_attention"
418
+ else:
419
+ enable_sliding_window = self.layer_idx % 2 == 0
420
+
421
+ if hasattr(config, "yarn_only_types") and layer_types[
422
+ self.layer_idx] not in config.yarn_only_types:
423
+ config.rope_parameters = None
424
+ else:
425
+ config.rope_parameters = getattr(config, "rope_scaling", None)
426
+
427
+ self.sliding_window = config.sliding_window
428
+ if enable_sliding_window:
429
+ self.num_attention_heads = config.attention_other_setting[
430
+ "num_attention_heads"]
431
+ self.num_key_value_heads = config.attention_other_setting[
432
+ "num_attention_groups"]
433
+
434
+ if self.sliding_window is not None and enable_sliding_window:
435
+ self.sliding_window = (self.sliding_window)
436
+ else:
437
+ self.sliding_window = None
438
+ self.head_dim = getattr(config, "head_dim",
439
+ config.hidden_size // self.num_attention_heads)
440
+ self.num_key_value_groups = self.num_attention_heads // self.num_key_value_heads
441
+
442
+ self.rotary_emb = Step3p5RotaryEmbedding(config, layer_idx=layer_idx)
443
+
444
+ self.q_size = self.num_attention_heads * self.head_dim
445
+ self.kv_size = self.num_key_value_heads * self.head_dim
446
+ self.scaling = self.head_dim**-0.5
447
+
448
+ self.q_proj = nn.Linear(config.hidden_size, self.q_size, bias=False)
449
+ self.k_proj = nn.Linear(config.hidden_size, self.kv_size, bias=False)
450
+ self.v_proj = nn.Linear(config.hidden_size, self.kv_size, bias=False)
451
+ self.o_proj = nn.Linear(self.q_size, config.hidden_size, bias=False)
452
+ self.q_norm = Step3p5RMSNorm(self.head_dim,
453
+ eps=config.rms_norm_eps)
454
+ self.k_norm = Step3p5RMSNorm(self.head_dim,
455
+ eps=config.rms_norm_eps)
456
+
457
+ self.use_head_wise_attn_gate = config.use_head_wise_attn_gate
458
+ if self.use_head_wise_attn_gate:
459
+ self.g_proj = nn.Linear(config.hidden_size,
460
+ self.num_attention_heads,
461
+ bias=False)
462
+
463
+ self.use_rope = True
464
+ use_rope_layers = getattr(config, "use_rope_layers", None)
465
+ if use_rope_layers:
466
+ self.use_rope = use_rope_layers[self.layer_idx]
467
+
468
+ def forward(
469
+ self,
470
+ hidden_states: torch.Tensor,
471
+ attention_mask: Optional[torch.Tensor],
472
+ past_key_value: Optional[Cache] = None,
473
+ cache_position: Optional[torch.LongTensor] = None,
474
+ position_ids: Optional[torch.LongTensor] = None,
475
+ **kwargs: Unpack[FlashAttentionKwargs],
476
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor],
477
+ Optional[Tuple[torch.Tensor]]]:
478
+ input_shape = hidden_states.shape[:-1]
479
+ hidden_shape = (*input_shape, -1, self.head_dim)
480
+
481
+ query_states = self.q_norm(
482
+ self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
483
+ key_states = self.k_norm(
484
+ self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
485
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(
486
+ 1, 2)
487
+ if self.use_head_wise_attn_gate:
488
+ gate_states = self.g_proj(hidden_states)
489
+ cos, sin = self.rotary_emb(hidden_states, position_ids)
490
+
491
+ # cos, sin = position_embeddings
492
+ query_states, key_states = apply_rotary_pos_emb(
493
+ query_states, key_states, cos, sin)
494
+
495
+ # query_states, key_states = apply_rotary_pos_emb(query_norm_states, key_norm_states, cos, sin)
496
+ if past_key_value is not None:
497
+ # sin and cos are specific to RoPE models; position_ids needed for the static cache
498
+ cache_kwargs = {
499
+ "sin": sin,
500
+ "cos": cos,
501
+ "cache_position": cache_position
502
+ }
503
+ key_states, value_states = past_key_value.update(
504
+ key_states, value_states, self.layer_idx, cache_kwargs)
505
+
506
+ attention_interface: Callable = eager_attention_forward
507
+ # TODO: considering FP8;
508
+ # RuntimeError: Expected attn_mask dtype to be bool or float or to match query dtype,
509
+ # but got attn_mask.dtype: long int and query.dtype: c10::BFloat16 instead.
510
+ if self.config._attn_implementation != "eager":
511
+ attention_interface = ALL_ATTENTION_FUNCTIONS[
512
+ self.config._attn_implementation]
513
+
514
+ attn_output, attn_weights = attention_interface(
515
+ self,
516
+ query_states,
517
+ key_states,
518
+ value_states,
519
+ attention_mask,
520
+ dropout=0.0 if not self.training else self.attention_dropout,
521
+ scaling=self.scaling,
522
+ sliding_window=self.sliding_window, # main diff with Llama
523
+ **kwargs,
524
+ )
525
+ attn_output = attn_output.reshape(*input_shape, -1)
526
+ if self.use_head_wise_attn_gate:
527
+ output = attn_output.view(
528
+ *attn_output.shape[:-1], self.num_attention_heads,
529
+ self.head_dim) * gate_states.unsqueeze(-1).sigmoid()
530
+ attn_output = output.view(*attn_output.shape)
531
+ attn_output = self.o_proj(attn_output)
532
+
533
+ return attn_output, attn_weights
534
+
535
+
536
+ class Step3p5DecoderLayer(GradientCheckpointingLayer):
537
+
538
+ def __init__(self, config, layer_idx):
539
+ super().__init__()
540
+ self.hidden_size = config.hidden_size
541
+ self.layer_idx = layer_idx
542
+ self.self_attn = Step3p5Attention(config, layer_idx)
543
+ self.attention_type = config.layer_types[layer_idx]
544
+
545
+ moe_layers_enum = getattr(config, "moe_layers_enum", None)
546
+ if moe_layers_enum is not None:
547
+ moe_layers_idx = [
548
+ int(i) for i in moe_layers_enum.strip().split(',')
549
+ ]
550
+ else:
551
+ moe_layers_idx = [i for i in range(1, config.num_hidden_layers)]
552
+ self.is_moe_layer = layer_idx in moe_layers_idx
553
+ self.use_moe = False
554
+
555
+ if config.swiglu_limits_shared and config.swiglu_limits_shared[
556
+ layer_idx] is not None and config.swiglu_limits_shared[
557
+ layer_idx] != 0:
558
+ swiglu_limit_shared = config.swiglu_limits_shared[layer_idx]
559
+ else:
560
+ swiglu_limit_shared = None
561
+ if config.swiglu_limits and config.swiglu_limits[
562
+ layer_idx] is not None and config.swiglu_limits[layer_idx] != 0:
563
+ swiglu_limit = config.swiglu_limits[layer_idx]
564
+ else:
565
+ swiglu_limit = None
566
+ if self.is_moe_layer:
567
+ self.moe = Step3p5MoEMLP(config, swiglu_limit=swiglu_limit) #
568
+ self.share_expert = Step3p5MLP(
569
+ config,
570
+ intermediate_size=config.share_expert_dim,
571
+ swiglu_limit=swiglu_limit_shared)
572
+ self.use_moe = True
573
+ else:
574
+ self.mlp = Step3p5MLP(config,
575
+ intermediate_size=config.intermediate_size,
576
+ swiglu_limit=swiglu_limit_shared)
577
+
578
+ self.input_layernorm = Step3p5RMSNorm(
579
+ config.hidden_size,
580
+ eps=config.rms_norm_eps)
581
+ self.post_attention_layernorm = Step3p5RMSNorm(
582
+ config.hidden_size,
583
+ eps=config.rms_norm_eps)
584
+
585
+ def forward(
586
+ self,
587
+ hidden_states: torch.Tensor,
588
+ attention_mask: Optional[torch.Tensor] = None,
589
+ position_ids: Optional[torch.LongTensor] = None,
590
+ past_key_value: Optional[tuple[torch.Tensor]] = None,
591
+ cache_position: Optional[torch.LongTensor] = None,
592
+ **kwargs: Unpack[FlashAttentionKwargs],
593
+ ) -> torch.FloatTensor:
594
+ residual = hidden_states
595
+ hidden_states = self.input_layernorm(hidden_states)
596
+ hidden_states, _ = self.self_attn(
597
+ hidden_states=hidden_states,
598
+ attention_mask=attention_mask,
599
+ position_ids=position_ids,
600
+ past_key_value=past_key_value,
601
+ cache_position=cache_position,
602
+ **kwargs,
603
+ )
604
+ hidden_states = residual + hidden_states
605
+
606
+ # Fully Connected
607
+ residual = hidden_states
608
+ hidden_states = self.post_attention_layernorm(hidden_states)
609
+ if self.use_moe:
610
+ share_output = self.share_expert(hidden_states)
611
+ moe_output = self.moe(hidden_states)
612
+ ffn_output = moe_output + share_output
613
+ else:
614
+ ffn_output = self.mlp(hidden_states)
615
+ if isinstance(ffn_output, tuple):
616
+ hidden_states, _ = ffn_output
617
+ else:
618
+ hidden_states = ffn_output
619
+
620
+ hidden_states = residual + hidden_states
621
+ return hidden_states
622
+
623
+
624
+ class Step3p5PreTrainedModel(PreTrainedModel):
625
+ # Link this model family to its configuration class so PreTrainedModel.from_pretrained
626
+ # can load the config instead of failing with a NoneType error.
627
+ config_class = Step3p5Config
628
+ supports_gradient_checkpointing = True
629
+ _skip_keys_device_placement = ["past_key_values"]
630
+ _keys_to_ignore_on_load_unexpected = [
631
+ r"model\.layers\.45\.*",
632
+ r"model\.layers\.46\.*",
633
+ r"model\.layers\.47\.*"
634
+ ]
635
+ _supports_flash_attn = False
636
+ _supports_sdpa = True
637
+ _supports_flex_attn = True
638
+ _supports_static_cache = True
639
+ _supports_attention_backend = True
640
+
641
+
642
+ class Step3p5Model(Step3p5PreTrainedModel, GenerationMixin):
643
+ _no_split_modules = ["Step3p5DecoderLayer"]
644
+ base_model_prefix = "model"
645
+ _tied_weights_keys = ["lm_head.weight"]
646
+ config: Step3p5Config
647
+ def __init__(self, config: Step3p5Config):
648
+ super().__init__(config)
649
+ self.padding_idx = config.pad_token_id
650
+ self.vocab_size = config.vocab_size
651
+
652
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size,
653
+ self.padding_idx)
654
+ self.layers = nn.ModuleList([
655
+ Step3p5DecoderLayer(config, layer_idx)
656
+ for layer_idx in range(config.num_hidden_layers)
657
+ ])
658
+ self.norm = Step3p5RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
659
+ self.gradient_checkpointing = False
660
+ self.has_sliding_layers = "sliding_attention" in self.config.layer_types
661
+
662
+ # Initialize weights and apply final processing
663
+ self.post_init()
664
+
665
+ def get_input_embeddings(self, input_ids):
666
+ return self.embed_tokens(input_ids)
667
+
668
+ @can_return_tuple
669
+ def forward(
670
+ self,
671
+ input_ids: torch.LongTensor = None,
672
+ attention_mask: Optional[torch.Tensor] = None,
673
+ position_ids: Optional[torch.LongTensor] = None,
674
+ past_key_values: Optional[Cache] = None,
675
+ inputs_embeds: Optional[torch.FloatTensor] = None,
676
+ use_cache: Optional[bool] = None,
677
+ output_attentions: Optional[bool] = None,
678
+ output_hidden_states: Optional[bool] = None,
679
+ return_dict: Optional[bool] = None,
680
+ cache_position: Optional[torch.LongTensor] = None,
681
+ **kwargs: Unpack[TransformersKwargs],
682
+ ) -> Union[tuple, BaseModelOutputWithPast]:
683
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
684
+ output_hidden_states = (output_hidden_states
685
+ if output_hidden_states is not None else
686
+ self.config.output_hidden_states)
687
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
688
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
689
+ if (input_ids is None) ^ (inputs_embeds is not None):
690
+ raise ValueError(
691
+ "You must specify exactly one of input_ids or inputs_embeds")
692
+
693
+ if self.gradient_checkpointing and self.training and use_cache:
694
+ logger.warning_once(
695
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
696
+ )
697
+ use_cache = False
698
+
699
+ if inputs_embeds is None:
700
+ inputs_embeds = self.embed_tokens(
701
+ input_ids.to(self.embed_tokens.weight.device))
702
+
703
+ if use_cache and past_key_values is None:
704
+ past_key_values = DynamicCache()
705
+
706
+ if cache_position is None:
707
+ past_seen_tokens = past_key_values.get_seq_length(
708
+ ) if past_key_values is not None else 0
709
+ cache_position = torch.arange(past_seen_tokens,
710
+ past_seen_tokens +
711
+ inputs_embeds.shape[1],
712
+ device=inputs_embeds.device)
713
+
714
+ if position_ids is None:
715
+ position_ids = cache_position.unsqueeze(0)
716
+
717
+ hidden_states = inputs_embeds
718
+
719
+ # It may already have been prepared by e.g. `generate`
720
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
721
+ # Prepare mask arguments
722
+ mask_kwargs = {
723
+ "config": self.config,
724
+ "input_embeds": inputs_embeds,
725
+ "attention_mask": attention_mask,
726
+ "cache_position": cache_position,
727
+ "past_key_values": past_key_values,
728
+ "position_ids": position_ids,
729
+ }
730
+ # Create the masks
731
+ causal_mask_mapping = {
732
+ "full_attention": create_causal_mask(**mask_kwargs),
733
+ }
734
+
735
+ # The sliding window alternating layers are not always activated depending on the config
736
+ if self.has_sliding_layers:
737
+ causal_mask_mapping[
738
+ "sliding_attention"] = create_sliding_window_causal_mask(
739
+ **mask_kwargs)
740
+
741
+ # # create position embeddings to be shared across the decoder layers
742
+ # decoder layers
743
+ all_hidden_states = () if output_hidden_states else None
744
+ all_self_attns = () if output_attentions else None
745
+ for decoder_layer in self.layers[:self.config.num_hidden_layers]:
746
+ if output_hidden_states:
747
+ all_hidden_states += (hidden_states, )
748
+
749
+ layer_outputs = decoder_layer(
750
+ hidden_states,
751
+ attention_mask=causal_mask_mapping[
752
+ decoder_layer.attention_type],
753
+ position_ids=position_ids,
754
+ past_key_value=past_key_values,
755
+ output_attentions=output_attentions,
756
+ use_cache=use_cache,
757
+ cache_position=cache_position,
758
+ **kwargs,
759
+ )
760
+
761
+ hidden_states = layer_outputs
762
+
763
+ hidden_states = self.norm(hidden_states)
764
+
765
+ return BaseModelOutputWithPast(
766
+ last_hidden_state=hidden_states,
767
+ past_key_values=past_key_values if use_cache else None,
768
+ hidden_states=all_hidden_states,
769
+ attentions=all_self_attns,
770
+ )
771
+
772
+
773
+ class Step3p5ForCausalLM(Step3p5PreTrainedModel, GenerationMixin):
774
+ _tied_weights_keys = ["lm_head.weight"]
775
+ config: Step3p5Config
776
+
777
+ def __init__(self, config: Step3p5Config):
778
+ super().__init__(config)
779
+ self.model = Step3p5Model(config)
780
+ self.lm_head = nn.Linear(config.hidden_size,
781
+ config.vocab_size,
782
+ bias=False)
783
+
784
+ self.post_init()
785
+
786
+ def get_input_embeddings(self):
787
+ return self.model.get_input_embeddings()
788
+
789
+ def set_input_embeddings(self, value):
790
+ self.model.set_input_embeddings(value)
791
+
792
+ def get_output_embeddings(self):
793
+ return self.model.get_output_embeddings()
794
+
795
+ def set_output_embeddings(self, new_embeddings):
796
+ self.model.set_output_embeddings(new_embeddings)
797
+
798
+ def set_decoder(self, decoder):
799
+ self.model.set_decoder(decoder)
800
+
801
+ def get_decoder(self):
802
+ return self.model.get_decoder()
803
+
804
+ def forward(
805
+ self,
806
+ input_ids: torch.LongTensor = None,
807
+ num_patches=None,
808
+ patch_pixel_values=None,
809
+ patch_newline_mask=None,
810
+ attention_mask: Optional[torch.Tensor] = None,
811
+ position_ids: Optional[torch.LongTensor] = None,
812
+ past_key_values: Optional[Cache] = None,
813
+ inputs_embeds: Optional[torch.FloatTensor] = None,
814
+ labels: Optional[torch.LongTensor] = None,
815
+ use_cache: Optional[bool] = None,
816
+ output_attentions: Optional[bool] = None,
817
+ output_hidden_states: Optional[bool] = None,
818
+ return_dict: Optional[bool] = None,
819
+ cache_position: Optional[torch.LongTensor] = None,
820
+ **kwargs: Unpack[TransformersKwargs],
821
+ ) -> Union[tuple, Step3p5CausalLMOutputWithPast]:
822
+ r"""
823
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
824
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
825
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
826
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
827
+ Example:
828
+ ```python
829
+ >>> from transformers import AutoTokenizer, Llama4ForCausalLM
830
+ >>> model = Llama4ForCausalLM.from_pretrained("meta-llama4/Llama4-2-7b-hf")
831
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama4/Llama4-2-7b-hf")
832
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
833
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
834
+ >>> # Generate
835
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
836
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
837
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
838
+ ```"""
839
+
840
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
841
+ output_hidden_states = (output_hidden_states
842
+ if output_hidden_states is not None else
843
+ self.config.output_hidden_states)
844
+ # breakpoint()
845
+ outputs = self.model(
846
+ input_ids=input_ids,
847
+ num_patches=num_patches,
848
+ patch_pixel_values=patch_pixel_values,
849
+ patch_newline_mask=patch_newline_mask,
850
+ position_ids=position_ids,
851
+ attention_mask=attention_mask,
852
+ past_key_values=past_key_values,
853
+ inputs_embeds=inputs_embeds,
854
+ use_cache=use_cache,
855
+ output_attentions=output_attentions,
856
+ output_hidden_states=output_hidden_states,
857
+ return_dict=return_dict,
858
+ cache_position=cache_position,
859
+ **kwargs,
860
+ )
861
+ hidden_states = outputs.last_hidden_state
862
+ logits = self.lm_head(hidden_states)
863
+
864
+ return Step3p5CausalLMOutputWithPast(logits=logits, )
865
+
866
+ def prepare_inputs_for_generation(
867
+ self,
868
+ input_ids,
869
+ past_key_values=None,
870
+ inputs_embeds=None,
871
+ pixel_values=None,
872
+ attention_mask=None,
873
+ cache_position=None,
874
+ logits_to_keep=None,
875
+ **kwargs,
876
+ ):
877
+
878
+ model_inputs = super().prepare_inputs_for_generation(
879
+ input_ids,
880
+ past_key_values=past_key_values,
881
+ inputs_embeds=inputs_embeds,
882
+ attention_mask=attention_mask,
883
+ cache_position=cache_position,
884
+ logits_to_keep=logits_to_keep,
885
+ **kwargs,
886
+ )
887
+
888
+ if cache_position[0] == 0:
889
+ # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
890
+ # Otherwise we need pixel values to be passed to model
891
+ model_inputs["pixel_values"] = pixel_values
892
+
893
+ return model_inputs
894
+
895
+ def _fix_state_dict_key_on_load(self, key: str) -> tuple[str, bool]:
896
+ if key.startswith("language_model."):
897
+ return key[len("language_model."):], True
898
+
899
+ return key, False
quantization_config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:257f6665a7d41fcbb7e6cad3c563ee3579e97bc145ba05ffae71bc59eeb51a7a
3
+ size 44970995
special_tokens_map.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|begin▁of▁sentence|>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|im_end|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<|end▁of▁sentence|>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
step-bar-chart.png ADDED

Git LFS Details

  • SHA256: 3fa283dc9c139edc3331aaafa21d69de212a241f03262f09acf96fbc0123a93d
  • Pointer size: 131 Bytes
  • Size of remote file: 647 kB
stepfun.svg ADDED
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
The diff for this file is too large to render. See raw diff