Mapika commited on
Commit
6684358
·
verified ·
1 Parent(s): 64aa1cd

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ 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
+ figures/benchmark.jpeg filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MINIMAX COMMUNITY LICENSE
2
+ Copyright (c) 2026 MiniMax
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software for non-commercial purposes, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or provide copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+ 1. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
5
+ 2. If the Software (or any derivative works thereof) is used for any Commercial Use for your products or services:
6
+ 1. you shall prominently display “Built with MiniMax M3” on a related website, user interface, blogpost, about page or product documentation.
7
+ 2. you shall obtain a separate, prior written authorization from MiniMax by contacting api@minimax.io with the subject line “M3 licensing - authorization request”, if such products and services generate more than 20 million US dollars (or equivalent in other currencies) in yearly revenue; otherwise, you only need to send a one-time notice to api@minimax.io with the subject “M3 licensing — notice”.
8
+ 3. “Commercial Use” means any use of the Software or any derivative work thereof that is primarily intended for commercial advantage or monetary compensation, which includes, without limitation: (i) offering products or services to third parties for a fee, which utilize, incorporate, or rely on the Software or its derivatives, (ii) the commercial use of APIs provided by or for the Software or its derivatives, including to support or enable commercial products, services, or operations, whether in a cloud-based, hosted, or other similar environment, and (iii) the deployment or provision of the Software or its derivatives that have been subjected to post-training, fine-tuning, instruction-tuning, or any other form of modification, for any commercial purpose.
9
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
10
+
11
+ Appendix: Prohibited Uses
12
+ You agree you will not use, or allow others to use, the Software or any derivatives of the Software to:
13
+ 1. Generate or disseminate content prohibited by applicable laws or regulations.
14
+ 2. Assist with, engage in or otherwise support any military purpose.
15
+ 3. Exploit, harm, or attempt to exploit or harm minors.
16
+ 4. Generate or disseminate false or misleading information with the intent to cause harm.
17
+ 5. Promote discrimination, hate speech, or harmful behavior against individuals or groups based on race or ethnic origin, religion, disability, age, nationality and national origin, veteran status, sexual orientation, gender or gender identity, caste, immigration status, or any other characteristic that is associated with systemic discrimination or marginalization.
README.md ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ license_name: minimax
4
+ license_link: https://huggingface.co/MiniMaxAI/MiniMax-M3/blob/main/LICENSE
5
+ base_model: MiniMaxAI/MiniMax-M3
6
+ base_model_relation: quantized
7
+ tags:
8
+ - nvfp4
9
+ - fp4
10
+ - modelopt
11
+ - minimax
12
+ - moe
13
+ - quantized
14
+ ---
15
+
16
+ # MiniMax-M3-NVFP4
17
+
18
+ **The first NVFP4 quantization of [MiniMaxAI/MiniMax-M3](https://huggingface.co/MiniMaxAI/MiniMax-M3)** — 428B-total / 23B-active MoE with MiniMax Sparse Attention (MSA), quantized 2026-06-12.
19
+
20
+ - **~256 GB** on disk (vs 854 GB BF16, 444 GB MXFP8) → serves on **2× B300/GB300** with huge KV headroom, or fits tighter Blackwell pairs
21
+ - Routed + shared **experts in NVFP4** (group 16, two-level scaling); attention, MSA indexer, router, embeddings, lm_head and the vision tower kept in **original BF16** (no quantization round-trip — copied verbatim from the source checkpoint)
22
+ - Same recipe family as `nvidia/MiniMax-M2.7-NVFP4` (experts-only NVFP4), produced with **TensorRT Model Optimizer 0.44.0**
23
+
24
+ ## Quantization recipe
25
+
26
+ | | |
27
+ |---|---|
28
+ | Method | PTQ, NVFP4 (FP4 weights+activations, FP8 per-16 block scales + FP32 global) |
29
+ | Tool | nvidia-modelopt 0.44.0, transformers main (native `minimax_m3_vl`) |
30
+ | Calibration | 512 samples × 2048 tokens: cnn_dailymail + nvidia/OpenCodeReasoning + nvidia/OpenMathReasoning |
31
+ | Quantized | routed experts (w1/w2/w3) + shared experts, all 57 MoE layers |
32
+ | Excluded | attention (incl. MSA indexer), router/gate, embeddings, lm_head, vision tower, projectors |
33
+ | KV cache | not quantized (v1; MSA is young in engines — don't stack experiments) |
34
+
35
+ Calibration deliberately uses longer sequences and reasoning traces than the modelopt defaults: NVFP4 activation scales are per-block *dynamic* at runtime, so calibration only pins the per-tensor global scales — reasoning-heavy data exposes the activation extremes a thinking model actually produces.
36
+
37
+ ## Evals
38
+
39
+ Measured via lm-evaluation-harness against the official **MiniMax-M3-MXFP8** endpoint as baseline, same engine (SGLang), same sampling (temperature 1.0, top-p 0.95, model-card settings), thinking enabled. Generation caps: 16384 tokens (GPQA, MMLU), 8192 (GSM8K); at these caps truncation is negligible (<0.25% of samples).
40
+
41
+ | Task | MXFP8 (official) | **NVFP4 (this repo)** |
42
+ |---|---|---|
43
+ | GSM8K (5-shot, strict) | 93.93 | 92.57 |
44
+ | GPQA diamond (CoT zero-shot) | 76.26 | 69.70 |
45
+ | MMLU (flan CoT few-shot, 25% sample) | 77.36 | 74.16 |
46
+
47
+ ## Serving (SGLang)
48
+
49
+ Requires the MiniMax-M3 bring-up image and **one patch**: SGLang's NVFP4 cutlass MoE path does not yet forward M3's clamped-swiglu activation parameters (`swiglu_alpha=1.702`, `swiglu_limit=7.0`, `+1` beta — same family as GPT-OSS). Without the patch the model loads but generates garbage. The patched files ship in this repo under `sglang_patch/` (upstream PR pending; the second file makes the unsupported flashinfer-trtllm MoE backend fail fast instead of producing garbage).
50
+
51
+ ```bash
52
+ docker run --runtime=nvidia --gpus '"device=0,1"' --ipc=host --shm-size 32g \
53
+ -v $MODEL_DIR:/model \
54
+ -v $MODEL_DIR/sglang_patch/modelopt_quant.py:/sgl-workspace/sglang/python/sglang/srt/layers/quantization/modelopt_quant.py:ro \
55
+ -v $MODEL_DIR/sglang_patch/flashinfer_trtllm.py:/sgl-workspace/sglang/python/sglang/srt/layers/moe/moe_runner/flashinfer_trtllm.py:ro \
56
+ -p 30014:30014 lmsysorg/sglang:dev-cu13-minimax-m3 \
57
+ sglang serve --model-path /model --tp 2 \
58
+ --quantization modelopt_fp4 \
59
+ --attention-backend fa4 --page-size 128 \
60
+ --moe-runner-backend flashinfer_cutlass \
61
+ --context-length 131072 --mem-fraction-static 0.90 \
62
+ --reasoning-parser auto --tool-call-parser auto \
63
+ --trust-remote-code --host 0.0.0.0 --port 30014
64
+ ```
65
+
66
+ `--page-size 128` is mandatory (MSA indexing). Sampling: temperature 1.0, top-p 0.95, top-k 40.
67
+
68
+ `--moe-runner-backend flashinfer_cutlass` is the only supported MoE backend: the flashinfer-trtllm FP4 kernels cannot run M3's parameterized clamped swiglu (they ignore `gemm1_alpha`/`gemm1_beta`; the patched code fails fast with a clear error instead of generating garbage).
69
+
70
+ ## Known limitations
71
+
72
+ - Engine support is bleeding-edge: M3 itself has not shipped in stable SGLang/vLLM; this NVFP4 additionally needs the swiglu-parameter fix (upstream PR pending).
73
+ - Vision tower is BF16 and untested under this serving path beyond loading; the eval table is text-only.
74
+ - KV cache quantization intentionally omitted in v1.
75
+
76
+ ## Provenance
77
+
78
+ Quantized from `MiniMaxAI/MiniMax-M3` (revision 3a41b31) on 8× NVIDIA B300. During bring-up, two upstream gaps were found and fixed: modelopt's fused-experts detector did not recognize M3's `_apply_gate` expert module (experts silently skipped — PR pending), and SGLang's NVFP4 cutlass MoE path dropped custom swiglu parameters (PR pending).
added_tokens.json ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "]!p~[": 200000,
3
+ "<fim_prefix>": 200001,
4
+ "<fim_middle>": 200002,
5
+ "<fim_suffix>": 200003,
6
+ "<fim_pad>": 200004,
7
+ "<reponame>": 200005,
8
+ "<filename>": 200006,
9
+ "<gh_stars>": 200007,
10
+ "<issue_start>": 200008,
11
+ "<issue_comment>": 200009,
12
+ "<issue_closed>": 200010,
13
+ "<jupyter_start>": 200011,
14
+ "<jupyter_text>": 200012,
15
+ "<jupyter_code>": 200013,
16
+ "<jupyter_output>": 200014,
17
+ "<empty_output>": 200015,
18
+ "<commit_before>": 200016,
19
+ "<commit_msg>": 200017,
20
+ "<commit_after>": 200018,
21
+ "]~b]": 200019,
22
+ "[e~[": 200020,
23
+ "]!d~[": 200021,
24
+ "<function_call>": 200022,
25
+ "<code_interpreter>": 200023,
26
+ "]<]speech[>[": 200024,
27
+ "]<]image[>[": 200025,
28
+ "]<]video[>[": 200026,
29
+ "]<]start of speech[>[": 200027,
30
+ "]<]end of speech[>[": 200028,
31
+ "]<]start of image[>[": 200029,
32
+ "]<]end of image[>[": 200030,
33
+ "]<]start of video[>[": 200031,
34
+ "]<]end of video[>[": 200032,
35
+ "]<]vision pad[>[": 200033,
36
+ "]~!b[": 200034,
37
+ "<jupyter_error>": 200035,
38
+ "<add_file>": 200036,
39
+ "<delete_file>": 200037,
40
+ "<rename_file>": 200038,
41
+ "<edit_file>": 200039,
42
+ "<commit_message>": 200040,
43
+ "<empty_source_file>": 200041,
44
+ "<repo_struct>": 200042,
45
+ "<code_context>": 200043,
46
+ "<file_content>": 200044,
47
+ "<source_files>": 200045,
48
+ "<pr_start>": 200046,
49
+ "<review_comment>": 200047,
50
+ "<filepath>": 200048,
51
+ "<file_sep>": 200049,
52
+ "<think>": 200050,
53
+ "</think>": 200051,
54
+ "<tool_call>": 200052,
55
+ "</tool_call>": 200053,
56
+ "]<]frame[>[": 200054,
57
+ "]<]start of frame[>[": 200055,
58
+ "]<]end of frame[>[": 200056,
59
+ "<|content_altered_placeholder|>": 200057,
60
+ "]<]minimax[>[": 200058,
61
+ "<mm:think>": 200059,
62
+ "</mm:think>": 200060
63
+ }
chat_template.jinja ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {# ---------- special token variables ---------- #}
2
+ {%- set ns_token = ']<]minimax[>[' -%}
3
+ {%- set bod_token = ']~!b[' -%}
4
+ {%- set bos_token = ']~b]' -%}
5
+ {%- set eos_token = '[e~[' -%}
6
+ {%- set toolcall_begin_token = ns_token ~ '<tool_call>' -%}
7
+ {%- set toolcall_end_token = ns_token ~ '</tool_call>' -%}
8
+ {%- set think_begin_token = '<mm:think>' -%}
9
+ {%- set think_end_token = '</mm:think>' -%}
10
+ {%- set image_token = ']<]image[>[' -%}
11
+ {%- set video_token = ']<]video[>[' -%}
12
+ {#- Thinking mode: "enabled" / "disabled" / "adaptive" / not defined -#}
13
+ {#- Recursive XML renderer for tool_call arguments ======================== -#}
14
+ {#- None values are intentionally skipped in mapping iteration so that
15
+ `<key>null</key>` (which would round-trip to the literal string "null")
16
+ never appears in the rendered tool_call. The convention is: omit the
17
+ field entirely. The top-level `_args` loop applies the same rule.
18
+ The `val is none` branch below is a safety net only — upstream cleaning
19
+ (drop_none_in_tool_arguments) should ensure no None ever reaches here. -#}
20
+ {%- macro to_xml(val, ns) -%}
21
+ {%- if val is mapping -%}
22
+ {%- for k, v in val.items() if v is not none -%}
23
+ {{ ns }}<{{ k }}>{{ to_xml(v, ns) }}{{ ns }}</{{ k }}>
24
+ {%- endfor -%}
25
+ {%- elif val is iterable and val is not string -%}
26
+ {%- for item in val -%}
27
+ {{ ns }}<item>{{ to_xml(item, ns) }}{{ ns }}</item>
28
+ {%- endfor -%}
29
+ {%- elif val is none -%}
30
+ {#- Should be unreachable when upstream cleaning is applied. -#}
31
+ {%- elif val is boolean -%}
32
+ {{ val | tojson }}
33
+ {%- else -%}
34
+ {{ val }}
35
+ {%- endif -%}
36
+ {%- endmacro -%}
37
+ {#- Tool Rendering Functions ============================================== -#}
38
+ {%- macro render_tool_namespace(namespace_name, tool_list) -%}
39
+ {%- for tool in tool_list -%}
40
+ <tool>{{ tool.function | tojson(ensure_ascii=False) }}</tool>
41
+ {% endfor -%}
42
+ {%- endmacro -%}
43
+ {%- macro visible_text(content) -%}
44
+ {%- if content is string -%}
45
+ {{ content }}
46
+ {%- elif content is iterable and content is not mapping -%}
47
+ {%- for item in content -%}
48
+ {%- if item is mapping and item.type == 'text' -%}
49
+ {{- item.text }}
50
+ {%- elif item is mapping and item.type == 'image' -%}
51
+ {{- image_token }}
52
+ {%- elif item is mapping and item.type == 'video' -%}
53
+ {{- video_token}}
54
+ {%- elif item is string -%}
55
+ {{- item }}
56
+ {%- endif -%}
57
+ {%- endfor -%}
58
+ {%- elif content is none -%}
59
+ {{- '' }}
60
+ {%- else -%}
61
+ {{- content }}
62
+ {%- endif -%}
63
+ {%- endmacro -%}
64
+ {#- System Message Construction ============================================ -#}
65
+ {%- macro build_system_message(system_message) -%}
66
+ {%- if system_message and system_message.content -%}
67
+ {{- visible_text(system_message.content) }}
68
+ {%- else -%}
69
+ {{- 'Your model version is MiniMax-M3, developed by MiniMax. Knowledge cutoff: January 2026. Founded in early 2022, MiniMax is a global AI foundation model company committed to advancing the frontiers of AI towards AGI.' }}
70
+ {%- endif -%}
71
+
72
+ {#- Thinking mode instructions -#}
73
+ {{- '\n\n<thinking_instructions>\n' }}
74
+ {{- 'You have a thinking capability that allows you to reason step by step before responding. When thinking is enabled, wrap your reasoning in ' ~ think_begin_token ~ think_end_token ~ ' tags before your response. When thinking is disabled, begin your response directly after the ' ~ think_end_token ~ ' prefix. When thinking is adaptive, decide on your own whether to think for the current turn.\n' }}
75
+ {%- if thinking_mode is defined -%}
76
+ {%- if thinking_mode == "enabled" -%}
77
+ {{- 'Current thinking mode: enabled. You MUST think step by step before every response, including after receiving function/tool results.\n' }}
78
+ {%- elif thinking_mode == "disabled" -%}
79
+ {{- 'Current thinking mode: disabled. Do not output any thinking process.\n' }}
80
+ {%- elif thinking_mode == "adaptive" -%}
81
+ {{- 'Current thinking mode: adaptive. You are encouraged to think for complex decision-making, multi-step reasoning, or when analyzing function/tool results.\n' }}
82
+ {%- endif -%}
83
+ {%- else -%}
84
+ {{- 'Current thinking mode: adaptive. You are encouraged to think for complex decision-making, multi-step reasoning, or when analyzing function/tool results.\n' }}
85
+ {%- endif -%}
86
+ {{- '</thinking_instructions>' }}
87
+ {%- endmacro -%}
88
+ {%- macro build_developer_message(developer_message) -%}
89
+ {%- if developer_message and developer_message.content -%}
90
+ {{- visible_text(developer_message.content) }}
91
+ {%- else -%}
92
+ {%- if model_identity is not defined -%}
93
+ {%- set model_identity = "You are a helpful assistant." -%}
94
+ {%- endif -%}
95
+ {{- model_identity }}
96
+ {%- endif -%}
97
+ {%- endmacro -%}
98
+ {#- Main Template Logic ================================================= -#}
99
+ {#- Role mapping: root -> system sp (high priority), system/developer -> developer sp (low priority) -#}
100
+ {%- set system_message = none -%}
101
+ {%- set developer_message = none -%}
102
+ {%- set conversation_messages = messages -%}
103
+ {%- if messages and messages[0].role == "root" -%}
104
+ {%- set system_message = messages[0] -%}
105
+ {%- set conversation_messages = messages[1:] -%}
106
+ {%- if conversation_messages and conversation_messages[0].role in ["system", "developer"] -%}
107
+ {%- set developer_message = conversation_messages[0] -%}
108
+ {%- set conversation_messages = conversation_messages[1:] -%}
109
+ {%- endif -%}
110
+ {%- elif messages and messages[0].role in ["system", "developer"] -%}
111
+ {%- set developer_message = messages[0] -%}
112
+ {%- set conversation_messages = messages[1:] -%}
113
+ {%- endif -%}
114
+ {#- Render system sp (higher priority, root role only) -#}
115
+ {{- bod_token ~ bos_token ~ 'system' ~ '\n' }}
116
+ {{- build_system_message(system_message) }}
117
+ {{- eos_token ~ '\n' }}
118
+
119
+ {#- Render developer sp (lower priority: system/developer role + tools) -#}
120
+ {{- bos_token ~ 'developer' ~ '\n' }}
121
+ {{- build_developer_message(developer_message) }}
122
+ {%- if tools -%}
123
+ {{- '\n\n' ~ '# Tools' ~ '\n' ~ 'You may call one or more tools to assist with the user query.\nHere are the tools available in JSONSchema format:' ~ '\n' }}
124
+ {{- '\n' ~ '<tools>' ~ '\n' }}
125
+ {{- render_tool_namespace("functions", tools) }}
126
+ {{- '</tools>' ~ '\n\n' }}
127
+ {{- 'To call tools, wrap all invocations in a single ' ~ toolcall_begin_token ~ toolcall_end_token ~ ' block. Parameter values containing nested objects or arrays are recursively expanded into XML elements. Example:\n' }}
128
+ {{- '\n' ~ toolcall_begin_token ~ '\n' }}
129
+ {{- ns_token + '<invoke name="tool-name-1">' }}
130
+ {{- ns_token + '<param-1>value-1' + ns_token + '</param-1>' }}
131
+ {{- ns_token + '<param-2>' }}
132
+ {{- ns_token + '<item>' }}
133
+ {{- ns_token + '<key-a>val-a' + ns_token + '</key-a>' }}
134
+ {{- ns_token + '<key-b>val-b' + ns_token + '</key-b>' }}
135
+ {{- ns_token + '</item>' }}
136
+ {{- ns_token + '</param-2>' }}
137
+ {{- ns_token + '</invoke>\n' }}
138
+ {{- ns_token + '<invoke name="tool-name-2">' }}
139
+ {{- ns_token + '<param-1>value-1' + ns_token + '</param-1>' }}
140
+ {{- ns_token + '</invoke>\n' }}
141
+ {{- toolcall_end_token }}
142
+ {%- endif -%}
143
+ {{- eos_token ~ '\n' }}
144
+
145
+ {#- Render messages -#}
146
+ {%- set last_tool_call = namespace(name=none) -%}
147
+ {%- for message in conversation_messages -%}
148
+ {%- if message.role == 'assistant' -%}
149
+ {{- bos_token ~ 'ai' ~ '\n' }}
150
+
151
+ {%- set reasoning_content = '' %}
152
+ {%- set content = visible_text(message.content) %}
153
+ {%- if message.reasoning_content is string %}
154
+ {%- set reasoning_content = message.reasoning_content %}
155
+ {%- else %}
156
+ {%- if think_end_token in content %}
157
+ {%- set reasoning_content = content.split(think_end_token)[0].strip('\n').split(think_begin_token)[-1].strip('\n') %}
158
+ {%- set content = content.split(think_end_token)[-1].strip('\n') %}
159
+ {%- endif %}
160
+ {%- endif %}
161
+
162
+ {%- if reasoning_content -%}
163
+ {#- Render thinking for every assistant turn (all-turn visible) -#}
164
+ {{- think_begin_token ~ reasoning_content ~ think_end_token }}
165
+ {%- else -%}
166
+ {#- No thinking rendered → prefix with think_end_token -#}
167
+ {{- think_end_token }}
168
+ {%- endif -%}
169
+
170
+ {%- if content -%}
171
+ {{- content }}
172
+ {%- endif -%}
173
+ {%- if message.tool_calls -%}
174
+ {{- toolcall_begin_token ~ '\n' }}
175
+
176
+ {%- for tool_call in message.tool_calls -%}
177
+ {%- if tool_call.function -%}
178
+ {%- set tool_call = tool_call.function -%}
179
+ {%- endif -%}
180
+ {{- ns_token + '<invoke name="' + tool_call.name + '">' }}
181
+ {%- set _args = tool_call.arguments -%}
182
+ {%- for k, v in _args.items() if v is not none %}
183
+ {{- ns_token + '<' + k + '>' -}}
184
+ {{- to_xml(v, ns_token) -}}
185
+ {{- ns_token + '</' + k + '>' }}
186
+ {%- endfor -%}
187
+ {{- ns_token + '</invoke>' ~ '\n' }}
188
+ {%- endfor -%}
189
+
190
+ {{- toolcall_end_token }}
191
+ {%- if message.tool_calls[-1].function -%}
192
+ {%- set last_tool_call.name = message.tool_calls[-1].function.name -%}
193
+ {%- else -%}
194
+ {%- set last_tool_call.name = message.tool_calls[-1].name -%}
195
+ {%- endif -%}
196
+ {%- else -%}
197
+ {%- set last_tool_call.name = none -%}
198
+ {%- endif -%}
199
+ {{- eos_token ~ '\n' }}
200
+
201
+ {%- elif message.role == 'tool' -%}
202
+ {%- if last_tool_call.name is none -%}
203
+ {{- raise_exception("Message has tool role, but there was no previous assistant message with a tool call!") }}
204
+ {%- endif -%}
205
+ {%- if loop.first or (conversation_messages[loop.index0 - 1].role != 'tool') -%}
206
+ {{- bos_token ~ 'tool' }}
207
+ {%- endif -%}
208
+ {{- '\n<response>' }}
209
+ {%- if message.content is string -%}
210
+ {{- message.content }}
211
+ {%- else -%}
212
+ {%- for tr in message.content -%}
213
+ {%- if tr is mapping and tr.type is defined and tr.type == 'image' -%}
214
+ {{- image_token }}
215
+ {%- elif tr is mapping and tr.type is defined and tr.type == 'video' -%}
216
+ {{- video_token }}
217
+ {%- else -%}
218
+ {{- tr.output if tr.output is defined else (tr.text if tr.type == 'text' and tr.text is defined else tr) }}
219
+ {%- endif -%}
220
+ {%- endfor -%}
221
+ {%- endif -%}
222
+ {{- '</response>' }}
223
+ {%- if loop.last or (conversation_messages[loop.index0 + 1].role != 'tool') -%}
224
+ {{- eos_token ~ '\n' -}}
225
+ {%- endif -%}
226
+
227
+ {%- elif message.role == 'user' -%}
228
+ {{- bos_token ~ 'user' ~ '\n' }}
229
+ {{- visible_text(message.content) }}
230
+ {{- eos_token ~ '\n' }}
231
+ {%- endif -%}
232
+ {%- endfor -%}
233
+
234
+ {#- Generation prompt -#}
235
+ {%- if add_generation_prompt -%}
236
+ {{- bos_token ~ 'ai' ~ '\n' }}
237
+ {%- if thinking_mode is defined and thinking_mode == "disabled" -%}
238
+ {{- think_end_token }}
239
+ {%- elif thinking_mode is defined and thinking_mode == "adaptive" -%}
240
+ {#- adaptive: no prefix, let model decide -#}
241
+ {%- elif thinking_mode is defined and thinking_mode == "enabled" -%}
242
+ {#- enabled or not defined: default to think -#}
243
+ {{- think_begin_token }}
244
+ {%- else -%}
245
+ {#- adaptive: no prefix, let model decide -#}
246
+ {%- endif -%}
247
+ {%- endif -%}
config.json ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "MiniMaxM3SparseForConditionalGeneration"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_minimax_m3_vl.MiniMaxM3VLConfig"
7
+ },
8
+ "model_type": "minimax_m3_vl",
9
+ "text_config": {
10
+ "hidden_size": 6144,
11
+ "intermediate_size": 3072,
12
+ "num_hidden_layers": 60,
13
+ "num_attention_heads": 64,
14
+ "num_key_value_heads": 4,
15
+ "head_dim": 128,
16
+ "vocab_size": 200064,
17
+ "max_position_embeddings": 1048576,
18
+ "rms_norm_eps": 1e-06,
19
+ "use_gemma_norm": true,
20
+ "attention_output_gate": false,
21
+ "rope_theta": 5000000,
22
+ "rotary_dim": 64,
23
+ "partial_rotary_factor": 0.5,
24
+ "hidden_act": "swigluoai",
25
+ "use_qk_norm": true,
26
+ "tie_word_embeddings": false,
27
+ "dense_intermediate_size": 12288,
28
+ "shared_intermediate_size": 3072,
29
+ "num_local_experts": 128,
30
+ "num_experts_per_tok": 4,
31
+ "n_shared_experts": 1,
32
+ "scoring_func": "sigmoid",
33
+ "use_routing_bias": true,
34
+ "moe_layer_freq": [
35
+ 0,
36
+ 0,
37
+ 0,
38
+ 1,
39
+ 1,
40
+ 1,
41
+ 1,
42
+ 1,
43
+ 1,
44
+ 1,
45
+ 1,
46
+ 1,
47
+ 1,
48
+ 1,
49
+ 1,
50
+ 1,
51
+ 1,
52
+ 1,
53
+ 1,
54
+ 1,
55
+ 1,
56
+ 1,
57
+ 1,
58
+ 1,
59
+ 1,
60
+ 1,
61
+ 1,
62
+ 1,
63
+ 1,
64
+ 1,
65
+ 1,
66
+ 1,
67
+ 1,
68
+ 1,
69
+ 1,
70
+ 1,
71
+ 1,
72
+ 1,
73
+ 1,
74
+ 1,
75
+ 1,
76
+ 1,
77
+ 1,
78
+ 1,
79
+ 1,
80
+ 1,
81
+ 1,
82
+ 1,
83
+ 1,
84
+ 1,
85
+ 1,
86
+ 1,
87
+ 1,
88
+ 1,
89
+ 1,
90
+ 1,
91
+ 1,
92
+ 1,
93
+ 1,
94
+ 1
95
+ ],
96
+ "qk_norm_type": "per_head",
97
+ "num_mtp_modules": 7,
98
+ "num_nextn_predict_layers": 1,
99
+ "swiglu_alpha": 1.702,
100
+ "swiglu_limit": 7.0,
101
+ "routed_scaling_factor": 2.0,
102
+ "sparse_attention_config": {
103
+ "use_sparse_attention": true,
104
+ "sparse_index_dim": 128,
105
+ "sparse_num_index_heads": 4,
106
+ "sparse_topk_blocks": 16,
107
+ "sparse_block_size": 128,
108
+ "sparse_disable_index_value": [
109
+ 0,
110
+ 0,
111
+ 0,
112
+ 1,
113
+ 1,
114
+ 1,
115
+ 1,
116
+ 1,
117
+ 1,
118
+ 1,
119
+ 1,
120
+ 1,
121
+ 1,
122
+ 1,
123
+ 1,
124
+ 1,
125
+ 1,
126
+ 1,
127
+ 1,
128
+ 1,
129
+ 1,
130
+ 1,
131
+ 1,
132
+ 1,
133
+ 1,
134
+ 1,
135
+ 1,
136
+ 1,
137
+ 1,
138
+ 1,
139
+ 1,
140
+ 1,
141
+ 1,
142
+ 1,
143
+ 1,
144
+ 1,
145
+ 1,
146
+ 1,
147
+ 1,
148
+ 1,
149
+ 1,
150
+ 1,
151
+ 1,
152
+ 1,
153
+ 1,
154
+ 1,
155
+ 1,
156
+ 1,
157
+ 1,
158
+ 1,
159
+ 1,
160
+ 1,
161
+ 1,
162
+ 1,
163
+ 1,
164
+ 1,
165
+ 1,
166
+ 1,
167
+ 1,
168
+ 1
169
+ ],
170
+ "sparse_score_type": "max",
171
+ "sparse_init_block": 0,
172
+ "sparse_local_block": 1,
173
+ "sparse_attention_freq": [
174
+ 0,
175
+ 0,
176
+ 0,
177
+ 1,
178
+ 1,
179
+ 1,
180
+ 1,
181
+ 1,
182
+ 1,
183
+ 1,
184
+ 1,
185
+ 1,
186
+ 1,
187
+ 1,
188
+ 1,
189
+ 1,
190
+ 1,
191
+ 1,
192
+ 1,
193
+ 1,
194
+ 1,
195
+ 1,
196
+ 1,
197
+ 1,
198
+ 1,
199
+ 1,
200
+ 1,
201
+ 1,
202
+ 1,
203
+ 1,
204
+ 1,
205
+ 1,
206
+ 1,
207
+ 1,
208
+ 1,
209
+ 1,
210
+ 1,
211
+ 1,
212
+ 1,
213
+ 1,
214
+ 1,
215
+ 1,
216
+ 1,
217
+ 1,
218
+ 1,
219
+ 1,
220
+ 1,
221
+ 1,
222
+ 1,
223
+ 1,
224
+ 1,
225
+ 1,
226
+ 1,
227
+ 1,
228
+ 1,
229
+ 1,
230
+ 1,
231
+ 1,
232
+ 1,
233
+ 1
234
+ ]
235
+ },
236
+ "architectures": [
237
+ "MiniMaxM3SparseForCausalLM"
238
+ ]
239
+ },
240
+ "vision_config": {
241
+ "hidden_size": 1280,
242
+ "num_attention_heads": 16,
243
+ "num_hidden_layers": 32,
244
+ "intermediate_size": 5120,
245
+ "patch_size": 14,
246
+ "image_size": 2016,
247
+ "projection_dim": 6144,
248
+ "position_embedding_type": "rope",
249
+ "rope_mode": "3d",
250
+ "rope_theta": 10000.0,
251
+ "attention_dropout": 0.0,
252
+ "hidden_act": "gelu",
253
+ "initializer_factor": 1.0,
254
+ "initializer_range": 0.02,
255
+ "layer_norm_eps": 1e-05,
256
+ "model_type": "clip_vision_model",
257
+ "num_channels": 3,
258
+ "vocab_size": 32000,
259
+ "img_token_compression_config": {
260
+ "image_token_compression_method": "patch_merge",
261
+ "spatial_merge_size": 2,
262
+ "temporal_patch_size": 2
263
+ },
264
+ "vision_segment_max_frames": 4
265
+ },
266
+ "img_token_compression_config": {
267
+ "image_token_compression_method": "patch_merge",
268
+ "spatial_merge_size": 2,
269
+ "temporal_patch_size": 2
270
+ },
271
+ "image_grid_pinpoints": "[(336, 336), (336, 672), (336, 1008), (336, 1344), (336, 1680), (336, 2016), (672, 336), (672, 672), (672, 1008), (672, 1344), (672, 1680), (672, 2016), (1008, 336), (1008, 672), (1008, 1008), (1008, 1344), (1008, 1680), (1008, 2016), (1344, 336), (1344, 672), (1344, 1008), (1344, 1344), (1344, 1680), (1344, 2016), (1680, 336), (1680, 672), (1680, 1008), (1680, 1344), (1680, 1680), (1680, 2016), (2016, 336), (2016, 672), (2016, 1008), (2016, 1344), (2016, 1680), (2016, 2016)]",
272
+ "image_seq_length": 576,
273
+ "image_token_index": 200025,
274
+ "video_token_index": 200026,
275
+ "multimodal_projector_bias": true,
276
+ "num_reward_heads": 0,
277
+ "process_image_mode": "dynamic_res",
278
+ "projector_hidden_act": "gelu",
279
+ "vision_feature_layer": -1,
280
+ "vision_feature_select_strategy": "full",
281
+ "torch_dtype": "bfloat16",
282
+ "transformers_version": "4.52.4",
283
+ "projector_hidden_size": 6144,
284
+ "quantization_config": {
285
+ "config_groups": {
286
+ "group_0": {
287
+ "input_activations": {
288
+ "dynamic": false,
289
+ "num_bits": 4,
290
+ "type": "float",
291
+ "group_size": 16
292
+ },
293
+ "weights": {
294
+ "dynamic": false,
295
+ "num_bits": 4,
296
+ "type": "float",
297
+ "group_size": 16
298
+ },
299
+ "targets": [
300
+ "Linear"
301
+ ]
302
+ }
303
+ },
304
+ "ignore": [
305
+ "lm_head",
306
+ "model.embed_tokens",
307
+ "vision_tower",
308
+ "multi_modal_projector",
309
+ "patch_merge_mlp",
310
+ "language_model.model.layers.3.block_sparse_moe.gate",
311
+ "language_model.model.layers.3.self_attn*",
312
+ "language_model.model.layers.4.block_sparse_moe.gate",
313
+ "language_model.model.layers.4.self_attn*",
314
+ "language_model.model.layers.5.block_sparse_moe.gate",
315
+ "language_model.model.layers.5.self_attn*",
316
+ "language_model.model.layers.6.block_sparse_moe.gate",
317
+ "language_model.model.layers.6.self_attn*",
318
+ "language_model.model.layers.7.block_sparse_moe.gate",
319
+ "language_model.model.layers.7.self_attn*",
320
+ "language_model.model.layers.8.block_sparse_moe.gate",
321
+ "language_model.model.layers.8.self_attn*",
322
+ "language_model.model.layers.9.block_sparse_moe.gate",
323
+ "language_model.model.layers.9.self_attn*",
324
+ "language_model.model.layers.10.block_sparse_moe.gate",
325
+ "language_model.model.layers.10.self_attn*",
326
+ "language_model.model.layers.11.block_sparse_moe.gate",
327
+ "language_model.model.layers.11.self_attn*",
328
+ "language_model.model.layers.12.block_sparse_moe.gate",
329
+ "language_model.model.layers.12.self_attn*",
330
+ "language_model.model.layers.13.block_sparse_moe.gate",
331
+ "language_model.model.layers.13.self_attn*",
332
+ "language_model.model.layers.14.block_sparse_moe.gate",
333
+ "language_model.model.layers.14.self_attn*",
334
+ "language_model.model.layers.15.block_sparse_moe.gate",
335
+ "language_model.model.layers.15.self_attn*",
336
+ "language_model.model.layers.16.block_sparse_moe.gate",
337
+ "language_model.model.layers.16.self_attn*",
338
+ "language_model.model.layers.17.block_sparse_moe.gate",
339
+ "language_model.model.layers.17.self_attn*",
340
+ "language_model.model.layers.18.block_sparse_moe.gate",
341
+ "language_model.model.layers.18.self_attn*",
342
+ "language_model.model.layers.19.block_sparse_moe.gate",
343
+ "language_model.model.layers.19.self_attn*",
344
+ "language_model.model.layers.20.block_sparse_moe.gate",
345
+ "language_model.model.layers.20.self_attn*",
346
+ "language_model.model.layers.21.block_sparse_moe.gate",
347
+ "language_model.model.layers.21.self_attn*",
348
+ "language_model.model.layers.22.block_sparse_moe.gate",
349
+ "language_model.model.layers.22.self_attn*",
350
+ "language_model.model.layers.23.block_sparse_moe.gate",
351
+ "language_model.model.layers.23.self_attn*",
352
+ "language_model.model.layers.24.block_sparse_moe.gate",
353
+ "language_model.model.layers.24.self_attn*",
354
+ "language_model.model.layers.25.block_sparse_moe.gate",
355
+ "language_model.model.layers.25.self_attn*",
356
+ "language_model.model.layers.26.block_sparse_moe.gate",
357
+ "language_model.model.layers.26.self_attn*",
358
+ "language_model.model.layers.27.block_sparse_moe.gate",
359
+ "language_model.model.layers.27.self_attn*",
360
+ "language_model.model.layers.28.block_sparse_moe.gate",
361
+ "language_model.model.layers.28.self_attn*",
362
+ "language_model.model.layers.29.block_sparse_moe.gate",
363
+ "language_model.model.layers.29.self_attn*",
364
+ "language_model.model.layers.30.block_sparse_moe.gate",
365
+ "language_model.model.layers.30.self_attn*",
366
+ "language_model.model.layers.31.block_sparse_moe.gate",
367
+ "language_model.model.layers.31.self_attn*",
368
+ "language_model.model.layers.32.block_sparse_moe.gate",
369
+ "language_model.model.layers.32.self_attn*",
370
+ "language_model.model.layers.33.block_sparse_moe.gate",
371
+ "language_model.model.layers.33.self_attn*",
372
+ "language_model.model.layers.34.block_sparse_moe.gate",
373
+ "language_model.model.layers.34.self_attn*",
374
+ "language_model.model.layers.35.block_sparse_moe.gate",
375
+ "language_model.model.layers.35.self_attn*",
376
+ "language_model.model.layers.36.block_sparse_moe.gate",
377
+ "language_model.model.layers.36.self_attn*",
378
+ "language_model.model.layers.37.block_sparse_moe.gate",
379
+ "language_model.model.layers.37.self_attn*",
380
+ "language_model.model.layers.38.block_sparse_moe.gate",
381
+ "language_model.model.layers.38.self_attn*",
382
+ "language_model.model.layers.39.block_sparse_moe.gate",
383
+ "language_model.model.layers.39.self_attn*",
384
+ "language_model.model.layers.40.block_sparse_moe.gate",
385
+ "language_model.model.layers.40.self_attn*",
386
+ "language_model.model.layers.41.block_sparse_moe.gate",
387
+ "language_model.model.layers.41.self_attn*",
388
+ "language_model.model.layers.42.block_sparse_moe.gate",
389
+ "language_model.model.layers.42.self_attn*",
390
+ "language_model.model.layers.43.block_sparse_moe.gate",
391
+ "language_model.model.layers.43.self_attn*",
392
+ "language_model.model.layers.44.block_sparse_moe.gate",
393
+ "language_model.model.layers.44.self_attn*",
394
+ "language_model.model.layers.45.block_sparse_moe.gate",
395
+ "language_model.model.layers.45.self_attn*",
396
+ "language_model.model.layers.46.block_sparse_moe.gate",
397
+ "language_model.model.layers.46.self_attn*",
398
+ "language_model.model.layers.47.block_sparse_moe.gate",
399
+ "language_model.model.layers.47.self_attn*",
400
+ "language_model.model.layers.48.block_sparse_moe.gate",
401
+ "language_model.model.layers.48.self_attn*",
402
+ "language_model.model.layers.49.block_sparse_moe.gate",
403
+ "language_model.model.layers.49.self_attn*",
404
+ "language_model.model.layers.50.block_sparse_moe.gate",
405
+ "language_model.model.layers.50.self_attn*",
406
+ "language_model.model.layers.51.block_sparse_moe.gate",
407
+ "language_model.model.layers.51.self_attn*",
408
+ "language_model.model.layers.52.block_sparse_moe.gate",
409
+ "language_model.model.layers.52.self_attn*",
410
+ "language_model.model.layers.53.block_sparse_moe.gate",
411
+ "language_model.model.layers.53.self_attn*",
412
+ "language_model.model.layers.54.block_sparse_moe.gate",
413
+ "language_model.model.layers.54.self_attn*",
414
+ "language_model.model.layers.55.block_sparse_moe.gate",
415
+ "language_model.model.layers.55.self_attn*",
416
+ "language_model.model.layers.56.block_sparse_moe.gate",
417
+ "language_model.model.layers.56.self_attn*",
418
+ "language_model.model.layers.57.block_sparse_moe.gate",
419
+ "language_model.model.layers.57.self_attn*",
420
+ "language_model.model.layers.58.block_sparse_moe.gate",
421
+ "language_model.model.layers.58.self_attn*",
422
+ "language_model.model.layers.59.block_sparse_moe.gate",
423
+ "language_model.model.layers.59.self_attn*",
424
+ "language_model.model.layers.0.*",
425
+ "language_model.model.layers.1.*",
426
+ "language_model.model.layers.2.*"
427
+ ],
428
+ "quant_algo": "NVFP4",
429
+ "quant_method": "modelopt"
430
+ }
431
+ }
configuration_minimax_m3_vl.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HuggingFace configs for the MiniMax VL family (M2 VL / M3 VL).
2
+
3
+ This file is bundled into every converted HF checkpoint so that loading via
4
+ ``AutoConfig.from_pretrained(..., trust_remote_code=True)`` works without any
5
+ runtime dependency on sglang or other internal packages — only stock
6
+ ``transformers`` is required.
7
+
8
+ The class definitions intentionally mirror
9
+ ``sglang.srt.configs.minimax_vl``; if either side changes, keep them in sync.
10
+
11
+ The file is named ``configuration_minimax_m3_vl.py`` (matching the legacy
12
+ ``model_type="minimax_m3_vl"`` and the converter's ``auto_map`` entry) so
13
+ that ckpts produced by this converter remain loadable by older sglang versions
14
+ that only know the ``MiniMaxM3VL*`` names. The canonical class is
15
+ ``MiniMaxM3VLConfig``; ``MiniMaxM3VLConfig`` is a thin BC alias whose only
16
+ purpose is to be referenced from ``auto_map``.
17
+ """
18
+
19
+ from typing import Optional
20
+
21
+ from transformers.configuration_utils import PretrainedConfig
22
+ from transformers.models.auto import CONFIG_MAPPING
23
+
24
+
25
+ def _coerce_sub_config(
26
+ sub_config: Optional[dict], default_model_type: str
27
+ ) -> Optional[PretrainedConfig]:
28
+ """Convert a config dict to a ``PretrainedConfig`` instance.
29
+
30
+ If ``model_type`` is registered in HF ``CONFIG_MAPPING`` the corresponding
31
+ config class is used; otherwise we fall back to a generic
32
+ ``PretrainedConfig`` so all dict keys still become real attributes (M3's
33
+ text backbone uses ``model_type="minimax_m2"`` which is not in
34
+ ``CONFIG_MAPPING``).
35
+ """
36
+ if not isinstance(sub_config, dict):
37
+ return sub_config
38
+ model_type = sub_config.get("model_type", default_model_type)
39
+ cls = CONFIG_MAPPING.get(model_type, PretrainedConfig)
40
+ return cls(**sub_config)
41
+
42
+
43
+ class MiniMaxVLBaseConfig(PretrainedConfig):
44
+ """Base config shared by every MiniMax VL variant.
45
+
46
+ Handles vision/text sub-config coercion. Concrete subclasses only need to
47
+ declare a unique ``model_type`` string.
48
+ """
49
+
50
+ def __init__(
51
+ self,
52
+ vision_config: Optional[dict] = None,
53
+ text_config: Optional[dict] = None,
54
+ image_token_index: int = 200025,
55
+ video_token_index: int = 200026,
56
+ image_seq_length: int = 576,
57
+ process_image_mode: str = "dynamic_res",
58
+ projector_hidden_act: str = "gelu",
59
+ multimodal_projector_bias: bool = True,
60
+ vision_feature_layer: int = -1,
61
+ vision_feature_select_strategy: str = "full",
62
+ img_token_compression_config: Optional[dict] = None,
63
+ image_grid_pinpoints: Optional[str] = None,
64
+ **kwargs,
65
+ ):
66
+ self.vision_config = _coerce_sub_config(vision_config, "clip_vision_model")
67
+ self.text_config = _coerce_sub_config(text_config, "mixtral")
68
+
69
+ self.image_token_index = image_token_index
70
+ self.video_token_index = video_token_index
71
+ self.image_seq_length = image_seq_length
72
+ self.process_image_mode = process_image_mode
73
+ self.projector_hidden_act = projector_hidden_act
74
+ self.multimodal_projector_bias = multimodal_projector_bias
75
+ self.vision_feature_layer = vision_feature_layer
76
+ self.vision_feature_select_strategy = vision_feature_select_strategy
77
+ self.img_token_compression_config = img_token_compression_config or {}
78
+ self.image_grid_pinpoints = image_grid_pinpoints
79
+
80
+ super().__init__(**kwargs)
81
+
82
+ def __post_init__(self, **kwargs):
83
+ super().__post_init__(**kwargs)
84
+ if hasattr(self, "vision_config"):
85
+ self.vision_config = _coerce_sub_config(self.vision_config, "clip_vision_model")
86
+ if hasattr(self, "text_config"):
87
+ self.text_config = _coerce_sub_config(self.text_config, "mixtral")
88
+
89
+
90
+ class MiniMaxM2VLConfig(MiniMaxVLBaseConfig):
91
+ """MiniMax M2 VL: vision tower + M2 (Mixtral-style MoE) text backbone."""
92
+
93
+ model_type = "minimax_m2_vl"
94
+
95
+
96
+ class MiniMaxM3VLConfig(MiniMaxVLBaseConfig):
97
+ """MiniMax M3 VL: vision tower + M3 (mixed sparse/dense MoE) text backbone."""
98
+
99
+ model_type = "minimax_m3_vl"
100
+
101
+
102
+ class MiniMaxM2MiniVLConfig(MiniMaxM2VLConfig):
103
+ """Legacy alias kept so old ``model_type="minimax_m2_mini_vl"`` ckpts load."""
104
+
105
+ model_type = "minimax_m2_mini_vl"
106
+
107
+
108
+ class MiniMaxM3VLConfig(MiniMaxM3VLConfig):
109
+ """Legacy alias kept so old ``model_type="minimax_m3_vl"`` ckpts load."""
110
+
111
+ model_type = "minimax_m3_vl"
generation_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 200019,
3
+ "do_sample": true,
4
+ "eos_token_id": 200020,
5
+ "temperature": 1.0,
6
+ "top_p": 0.95,
7
+ "transformers_version": "4.46.1"
8
+ }
hf_quant_config.json ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "producer": {
3
+ "name": "modelopt",
4
+ "version": "0.44.0"
5
+ },
6
+ "quantization": {
7
+ "quant_algo": "NVFP4",
8
+ "kv_cache_quant_algo": null,
9
+ "group_size": 16,
10
+ "exclude_modules": [
11
+ "lm_head",
12
+ "model.embed_tokens",
13
+ "vision_tower",
14
+ "multi_modal_projector",
15
+ "patch_merge_mlp",
16
+ "language_model.model.layers.3.block_sparse_moe.gate",
17
+ "language_model.model.layers.3.self_attn*",
18
+ "language_model.model.layers.4.block_sparse_moe.gate",
19
+ "language_model.model.layers.4.self_attn*",
20
+ "language_model.model.layers.5.block_sparse_moe.gate",
21
+ "language_model.model.layers.5.self_attn*",
22
+ "language_model.model.layers.6.block_sparse_moe.gate",
23
+ "language_model.model.layers.6.self_attn*",
24
+ "language_model.model.layers.7.block_sparse_moe.gate",
25
+ "language_model.model.layers.7.self_attn*",
26
+ "language_model.model.layers.8.block_sparse_moe.gate",
27
+ "language_model.model.layers.8.self_attn*",
28
+ "language_model.model.layers.9.block_sparse_moe.gate",
29
+ "language_model.model.layers.9.self_attn*",
30
+ "language_model.model.layers.10.block_sparse_moe.gate",
31
+ "language_model.model.layers.10.self_attn*",
32
+ "language_model.model.layers.11.block_sparse_moe.gate",
33
+ "language_model.model.layers.11.self_attn*",
34
+ "language_model.model.layers.12.block_sparse_moe.gate",
35
+ "language_model.model.layers.12.self_attn*",
36
+ "language_model.model.layers.13.block_sparse_moe.gate",
37
+ "language_model.model.layers.13.self_attn*",
38
+ "language_model.model.layers.14.block_sparse_moe.gate",
39
+ "language_model.model.layers.14.self_attn*",
40
+ "language_model.model.layers.15.block_sparse_moe.gate",
41
+ "language_model.model.layers.15.self_attn*",
42
+ "language_model.model.layers.16.block_sparse_moe.gate",
43
+ "language_model.model.layers.16.self_attn*",
44
+ "language_model.model.layers.17.block_sparse_moe.gate",
45
+ "language_model.model.layers.17.self_attn*",
46
+ "language_model.model.layers.18.block_sparse_moe.gate",
47
+ "language_model.model.layers.18.self_attn*",
48
+ "language_model.model.layers.19.block_sparse_moe.gate",
49
+ "language_model.model.layers.19.self_attn*",
50
+ "language_model.model.layers.20.block_sparse_moe.gate",
51
+ "language_model.model.layers.20.self_attn*",
52
+ "language_model.model.layers.21.block_sparse_moe.gate",
53
+ "language_model.model.layers.21.self_attn*",
54
+ "language_model.model.layers.22.block_sparse_moe.gate",
55
+ "language_model.model.layers.22.self_attn*",
56
+ "language_model.model.layers.23.block_sparse_moe.gate",
57
+ "language_model.model.layers.23.self_attn*",
58
+ "language_model.model.layers.24.block_sparse_moe.gate",
59
+ "language_model.model.layers.24.self_attn*",
60
+ "language_model.model.layers.25.block_sparse_moe.gate",
61
+ "language_model.model.layers.25.self_attn*",
62
+ "language_model.model.layers.26.block_sparse_moe.gate",
63
+ "language_model.model.layers.26.self_attn*",
64
+ "language_model.model.layers.27.block_sparse_moe.gate",
65
+ "language_model.model.layers.27.self_attn*",
66
+ "language_model.model.layers.28.block_sparse_moe.gate",
67
+ "language_model.model.layers.28.self_attn*",
68
+ "language_model.model.layers.29.block_sparse_moe.gate",
69
+ "language_model.model.layers.29.self_attn*",
70
+ "language_model.model.layers.30.block_sparse_moe.gate",
71
+ "language_model.model.layers.30.self_attn*",
72
+ "language_model.model.layers.31.block_sparse_moe.gate",
73
+ "language_model.model.layers.31.self_attn*",
74
+ "language_model.model.layers.32.block_sparse_moe.gate",
75
+ "language_model.model.layers.32.self_attn*",
76
+ "language_model.model.layers.33.block_sparse_moe.gate",
77
+ "language_model.model.layers.33.self_attn*",
78
+ "language_model.model.layers.34.block_sparse_moe.gate",
79
+ "language_model.model.layers.34.self_attn*",
80
+ "language_model.model.layers.35.block_sparse_moe.gate",
81
+ "language_model.model.layers.35.self_attn*",
82
+ "language_model.model.layers.36.block_sparse_moe.gate",
83
+ "language_model.model.layers.36.self_attn*",
84
+ "language_model.model.layers.37.block_sparse_moe.gate",
85
+ "language_model.model.layers.37.self_attn*",
86
+ "language_model.model.layers.38.block_sparse_moe.gate",
87
+ "language_model.model.layers.38.self_attn*",
88
+ "language_model.model.layers.39.block_sparse_moe.gate",
89
+ "language_model.model.layers.39.self_attn*",
90
+ "language_model.model.layers.40.block_sparse_moe.gate",
91
+ "language_model.model.layers.40.self_attn*",
92
+ "language_model.model.layers.41.block_sparse_moe.gate",
93
+ "language_model.model.layers.41.self_attn*",
94
+ "language_model.model.layers.42.block_sparse_moe.gate",
95
+ "language_model.model.layers.42.self_attn*",
96
+ "language_model.model.layers.43.block_sparse_moe.gate",
97
+ "language_model.model.layers.43.self_attn*",
98
+ "language_model.model.layers.44.block_sparse_moe.gate",
99
+ "language_model.model.layers.44.self_attn*",
100
+ "language_model.model.layers.45.block_sparse_moe.gate",
101
+ "language_model.model.layers.45.self_attn*",
102
+ "language_model.model.layers.46.block_sparse_moe.gate",
103
+ "language_model.model.layers.46.self_attn*",
104
+ "language_model.model.layers.47.block_sparse_moe.gate",
105
+ "language_model.model.layers.47.self_attn*",
106
+ "language_model.model.layers.48.block_sparse_moe.gate",
107
+ "language_model.model.layers.48.self_attn*",
108
+ "language_model.model.layers.49.block_sparse_moe.gate",
109
+ "language_model.model.layers.49.self_attn*",
110
+ "language_model.model.layers.50.block_sparse_moe.gate",
111
+ "language_model.model.layers.50.self_attn*",
112
+ "language_model.model.layers.51.block_sparse_moe.gate",
113
+ "language_model.model.layers.51.self_attn*",
114
+ "language_model.model.layers.52.block_sparse_moe.gate",
115
+ "language_model.model.layers.52.self_attn*",
116
+ "language_model.model.layers.53.block_sparse_moe.gate",
117
+ "language_model.model.layers.53.self_attn*",
118
+ "language_model.model.layers.54.block_sparse_moe.gate",
119
+ "language_model.model.layers.54.self_attn*",
120
+ "language_model.model.layers.55.block_sparse_moe.gate",
121
+ "language_model.model.layers.55.self_attn*",
122
+ "language_model.model.layers.56.block_sparse_moe.gate",
123
+ "language_model.model.layers.56.self_attn*",
124
+ "language_model.model.layers.57.block_sparse_moe.gate",
125
+ "language_model.model.layers.57.self_attn*",
126
+ "language_model.model.layers.58.block_sparse_moe.gate",
127
+ "language_model.model.layers.58.self_attn*",
128
+ "language_model.model.layers.59.block_sparse_moe.gate",
129
+ "language_model.model.layers.59.self_attn*",
130
+ "language_model.model.layers.0.*",
131
+ "language_model.model.layers.1.*",
132
+ "language_model.model.layers.2.*"
133
+ ]
134
+ }
135
+ }
image_processor.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-2024 SGLang Team
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ """
4
+ MiniMax VL family HuggingFace-compatible Processor, ImageProcessor, VideoProcessor.
5
+ """
6
+ import math
7
+ from typing import List, Tuple
8
+
9
+ import torch
10
+ from torchvision.transforms import InterpolationMode
11
+ from transformers import BatchFeature
12
+ from transformers.image_processing_utils_fast import (
13
+ BaseImageProcessorFast,
14
+ group_images_by_shape,
15
+ reorder_images,
16
+ )
17
+ from transformers.image_utils import PILImageResampling, SizeDict
18
+ from transformers.processing_utils import (
19
+ ImagesKwargs,
20
+ Unpack,
21
+ )
22
+ from transformers.utils import TensorType
23
+
24
+ MAX_RATIO = 200
25
+
26
+
27
+ def round_by_factor(number: int, factor: int) -> int:
28
+ return round(number / factor) * factor
29
+
30
+
31
+ def ceil_by_factor(number: int, factor: int) -> int:
32
+ return math.ceil(number / factor) * factor
33
+
34
+
35
+ def floor_by_factor(number: int, factor: int) -> int:
36
+ return math.floor(number / factor) * factor
37
+
38
+
39
+ def smart_resize(
40
+ height: int,
41
+ width: int,
42
+ factor: int = 28,
43
+ min_pixels: int = 4 * 28 * 28,
44
+ max_pixels: int = 451584,
45
+ ) -> tuple[int, int]:
46
+ if max(height, width) / min(height, width) > MAX_RATIO:
47
+ raise ValueError(
48
+ f"absolute aspect ratio must be smaller than {MAX_RATIO}, "
49
+ f"got {max(height, width) / min(height, width)}"
50
+ )
51
+ h_bar = max(factor, round_by_factor(height, factor))
52
+ w_bar = max(factor, round_by_factor(width, factor))
53
+ if h_bar * w_bar > max_pixels:
54
+ beta = math.sqrt((height * width) / max_pixels)
55
+ h_bar = floor_by_factor(height / beta, factor)
56
+ w_bar = floor_by_factor(width / beta, factor)
57
+ elif h_bar * w_bar < min_pixels:
58
+ beta = math.sqrt(min_pixels / (height * width))
59
+ h_bar = ceil_by_factor(height * beta, factor)
60
+ w_bar = ceil_by_factor(width * beta, factor)
61
+ return h_bar, w_bar
62
+
63
+
64
+ # ==============================================================================
65
+ # MiniMax M3 VL Image Processor Fast (Fast Mode - Torch based)
66
+ # ==============================================================================
67
+
68
+
69
+ class MiniMaxM3VLImageProcessorKwargs(ImagesKwargs, total=False):
70
+ patch_size: int
71
+ temporal_patch_size: int
72
+ merge_size: int
73
+ max_pixels: int
74
+
75
+
76
+ class MiniMaxM3VLImageProcessor(BaseImageProcessorFast):
77
+ do_resize = True
78
+ resample = PILImageResampling.BICUBIC
79
+ size = {"height": 672, "width": 672} # required by base class validation, not used as resize bound
80
+ default_to_square = False
81
+ do_rescale = True
82
+ rescale_factor = 1 / 255
83
+ do_normalize = True
84
+ image_mean = [0.48145466, 0.4578275, 0.40821073]
85
+ image_std = [0.26862954, 0.26130258, 0.27577711]
86
+ do_convert_rgb = True
87
+ patch_size = 14
88
+ temporal_patch_size = 2
89
+ merge_size = 2
90
+ max_pixels = 451584 # 672*672
91
+ valid_kwargs = MiniMaxM3VLImageProcessorKwargs
92
+ model_input_names = ["pixel_values", "image_grid_thw"]
93
+
94
+ def __init__(self, **kwargs: Unpack[MiniMaxM3VLImageProcessorKwargs]):
95
+ super().__init__(**kwargs)
96
+
97
+ def preprocess(
98
+ self, images, **kwargs: Unpack[MiniMaxM3VLImageProcessorKwargs]
99
+ ) -> BatchFeature:
100
+ return super().preprocess(images, **kwargs)
101
+
102
+ def _preprocess(
103
+ self,
104
+ images: List[torch.Tensor],
105
+ do_resize: bool,
106
+ size: SizeDict,
107
+ resample: PILImageResampling | InterpolationMode | int | None,
108
+ do_rescale: bool,
109
+ rescale_factor: float,
110
+ do_normalize: bool,
111
+ image_mean: float | List[float] | None,
112
+ image_std: float | List[float] | None,
113
+ patch_size: int,
114
+ temporal_patch_size: int,
115
+ merge_size: int,
116
+ max_pixels: int,
117
+ disable_grouping: bool | None,
118
+ return_tensors: str | TensorType | None,
119
+ **kwargs,
120
+ ) -> BatchFeature:
121
+ grouped_images, grouped_images_index = group_images_by_shape(
122
+ images, disable_grouping=disable_grouping
123
+ )
124
+ resized_images_grouped = {}
125
+ factor = patch_size * merge_size
126
+ for shape, stacked_images in grouped_images.items():
127
+ height, width = stacked_images.shape[-2:]
128
+ if do_resize:
129
+ resized_height, resized_width = smart_resize(
130
+ height, width, factor=factor,
131
+ max_pixels=max_pixels,
132
+ )
133
+ stacked_images = self.resize(
134
+ stacked_images,
135
+ size=SizeDict(height=resized_height, width=resized_width),
136
+ resample=resample,
137
+ )
138
+ resized_images_grouped[shape] = stacked_images
139
+
140
+ resized_images = reorder_images(resized_images_grouped, grouped_images_index)
141
+
142
+ grouped_images, grouped_images_index = group_images_by_shape(
143
+ resized_images, disable_grouping=disable_grouping
144
+ )
145
+ processed_images_grouped = {}
146
+ processed_grids = {}
147
+
148
+ for shape, stacked_images in grouped_images.items():
149
+ resized_height, resized_width = stacked_images.shape[-2:]
150
+
151
+ patches = self.rescale_and_normalize(
152
+ stacked_images,
153
+ do_rescale,
154
+ rescale_factor,
155
+ do_normalize,
156
+ image_mean,
157
+ image_std,
158
+ )
159
+ if patches.ndim == 4:
160
+ patches = patches.unsqueeze(1)
161
+
162
+ if patches.shape[1] % temporal_patch_size != 0:
163
+ repeats = patches[:, -1:].repeat(
164
+ 1,
165
+ temporal_patch_size - (patches.shape[1] % temporal_patch_size),
166
+ 1,
167
+ 1,
168
+ 1,
169
+ )
170
+ patches = torch.cat([patches, repeats], dim=1)
171
+
172
+ batch_size, grid_t, channel = patches.shape[:3]
173
+ grid_t = grid_t // temporal_patch_size
174
+ grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
175
+
176
+ patches = patches.view(
177
+ batch_size,
178
+ grid_t,
179
+ temporal_patch_size,
180
+ channel,
181
+ grid_h // merge_size,
182
+ merge_size,
183
+ patch_size,
184
+ grid_w // merge_size,
185
+ merge_size,
186
+ patch_size,
187
+ )
188
+ patches = patches.permute(0, 1, 4, 7, 5, 8, 3, 2, 6, 9)
189
+
190
+ flatten_patches = patches.reshape(
191
+ batch_size,
192
+ grid_t * grid_h * grid_w,
193
+ channel * temporal_patch_size * patch_size * patch_size,
194
+ )
195
+
196
+ processed_images_grouped[shape] = flatten_patches
197
+ processed_grids[shape] = [[grid_t, grid_h, grid_w]] * batch_size
198
+
199
+ processed_images = reorder_images(
200
+ processed_images_grouped, grouped_images_index
201
+ )
202
+ processed_grids = reorder_images(processed_grids, grouped_images_index)
203
+
204
+ pixel_values = torch.cat(processed_images, dim=0)
205
+ image_grid_thw = torch.tensor(processed_grids, dtype=torch.long)
206
+
207
+ return BatchFeature(
208
+ data={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw},
209
+ tensor_type=return_tensors,
210
+ )
211
+
212
+ def get_number_of_image_patches(self, height: int, width: int, images_kwargs=None):
213
+ images_kwargs = images_kwargs or {}
214
+ patch_size = images_kwargs.get("patch_size", self.patch_size)
215
+ merge_size = images_kwargs.get("merge_size", self.merge_size)
216
+ max_pixels = images_kwargs.get("max_pixels", self.max_pixels)
217
+
218
+ resized_height, resized_width = smart_resize(
219
+ height, width, factor=patch_size * merge_size,
220
+ max_pixels=max_pixels,
221
+ )
222
+ grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
223
+ return grid_h * grid_w
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c3e7d72ba0de5bb55f48da9f438663bf9ac7e01ba23f2c24ccbe95f4737e815f
3
+ size 16106357520
model-00002-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9a3ccc511702a9f06382aa77865db578a6ff1d3331aea9126d8289ec2001adc3
3
+ size 16040620504
model-00003-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:48f1d297e3e18b9168d8eebfb26fb1ecfb8dcc572eaecad336a05234f571bcdc
3
+ size 16102725336
model-00004-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:519eb2760973b7ab63972551a6db73bd9d868fcae89aebecadffba1ce9dd305a
3
+ size 16101953448
model-00005-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:32c74c5f75f5f6f4f2358a117ca56ea0d2a9fb230edf8d357f71d18babd8251d
3
+ size 16034333072
model-00006-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:32f27f29e3252105ccc20a273070b2072ba16086e0afa7a2727a6467e686be70
3
+ size 16106651408
model-00007-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7424c3cf546bdbefd03c6eea75005a79359ee1b15f86b179e1da2c6a25e9d9c3
3
+ size 16105109184
model-00008-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:41a30539511453248be8bff050bef77de62828b5cec531f7cf5b5dc9846c99f5
3
+ size 16103927448
model-00009-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:441f2237f5319710aac480149832bee84d5f3107a8b42a51ef5c8033ceffa95c
3
+ size 16101942360
model-00010-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7a102ed6255f7aa3fa20390163f2ea2ca45808b5b2303da2c41fcafcc3c1f817
3
+ size 16103930568
model-00011-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:741a1739b84e71cc8a05b1d7fa58d899ed616a4e21eb242af56f99c3213ea859
3
+ size 16103928640
model-00012-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fa4ba3c63614cda1a8012a1d0f7cf8e9e9ae79c2f7b49cb9fbf2c61b769b7730
3
+ size 16055566328
model-00013-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:118c6f9ea3c67f35e9b6e737a371c6ab66a93173438f3c1a0990ffbcea73d25c
3
+ size 16106652488
model-00014-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ebc57aac69600e127519138785b8066ce3c8cb752beee620233bb02c639e65e6
3
+ size 16105109656
model-00015-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:77af9a60bc4d2ddfd3061a5d2da8e89ec6ada01863cb1ac6e02cf8d25c3fca6f
3
+ size 16103925720
model-00016-of-00016.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:94e2c3022cb33a6f38db119b79014f3986e63f83b81f71d307d3ca9e35831207
3
+ size 14300568744
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
preprocessor_config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "processor_class": "MiniMaxVLProcessor",
3
+ "auto_map": {
4
+ "AutoImageProcessor": "image_processor.MiniMaxM3VLImageProcessor",
5
+ "AutoProcessor": "processing_minimax.MiniMaxVLProcessor",
6
+ "AutoVideoProcessor": "video_processor.MiniMaxM3VLVideoProcessor"
7
+ },
8
+ "process_image_mode": "dynamic_res",
9
+ "image_mean": [
10
+ 0.48145466,
11
+ 0.4578275,
12
+ 0.40821073
13
+ ],
14
+ "image_std": [
15
+ 0.26862954,
16
+ 0.26130258,
17
+ 0.27577711
18
+ ],
19
+ "size": [
20
+ 672,
21
+ 672
22
+ ],
23
+ "patch_size": 14,
24
+ "img_token_compression_config": {
25
+ "image_token_compression_threshold": 1.1,
26
+ "image_token_compression_method": "patch_merge",
27
+ "max_image_resolution": 1008,
28
+ "spatial_merge_size": 2,
29
+ "temporal_patch_size": 2
30
+ },
31
+ "add_start_end_special_tokens": true
32
+ }
processing_minimax.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-2024 SGLang Team
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ """
4
+ MiniMax VL family HuggingFace-compatible Processor, ImageProcessor, VideoProcessor.
5
+ """
6
+
7
+ import math
8
+ import re
9
+ from typing import List, Optional, Tuple, Union
10
+
11
+ import torch
12
+ import torchvision
13
+ from torchvision.transforms import InterpolationMode
14
+ from transformers import BatchFeature
15
+ from transformers.image_processing_utils_fast import (
16
+ BaseImageProcessorFast,
17
+ group_images_by_shape,
18
+ reorder_images,
19
+ )
20
+ from transformers.image_utils import PILImageResampling, SizeDict
21
+ from transformers.processing_utils import (
22
+ ImagesKwargs,
23
+ ProcessingKwargs,
24
+ ProcessorMixin,
25
+ Unpack,
26
+ VideosKwargs,
27
+ )
28
+ from transformers.utils import TensorType
29
+ from transformers.video_processing_utils import BaseVideoProcessor
30
+ from transformers.video_utils import group_videos_by_shape, reorder_videos
31
+
32
+
33
+ class MiniMaxVLProcessorKwargs(ProcessingKwargs, total=False):
34
+ _defaults = {
35
+ "videos_kwargs": {
36
+ "do_resize": False,
37
+ "return_metadata": True,
38
+ },
39
+ }
40
+
41
+
42
+ class MiniMaxVLProcessor(ProcessorMixin):
43
+ IMAGE_TOKEN = "]<]image[>["
44
+ VIDEO_TOKEN = "]<]video[>["
45
+ VISION_START_TOKEN = "]<]start of image[>["
46
+ VISION_END_TOKEN = "]<]end of image[>["
47
+
48
+ def __init__(
49
+ self, image_processor=None, tokenizer=None, video_processor=None, **kwargs
50
+ ):
51
+ self.image_token_id = tokenizer.convert_tokens_to_ids(self.IMAGE_TOKEN)
52
+ self.video_token_id = tokenizer.convert_tokens_to_ids(self.VIDEO_TOKEN)
53
+ super().__init__(image_processor, tokenizer, video_processor)
54
+ # Video expansion also uses image start/end tokens. Separate video
55
+ # start/end tokens exist in the tokenizer, but the original MiniMax
56
+ # serving path did not use them; keep that behavior for compatibility.
57
+ self.vision_start_token_id = tokenizer.convert_tokens_to_ids(
58
+ self.VISION_START_TOKEN
59
+ )
60
+ self.vision_end_token_id = tokenizer.convert_tokens_to_ids(
61
+ self.VISION_END_TOKEN
62
+ )
63
+
64
+ def _prune_video_tokens(
65
+ self,
66
+ input_text: str,
67
+ video_segments: List[int],
68
+ video_token: str,
69
+ ) -> str:
70
+ """
71
+ Prune video tokens by temporal_patch_size (e.g., 2:1).
72
+
73
+ Expects the prompt to carry exactly sum(video_segments) video
74
+ tokens — i.e. one token per *sampled* frame. Then drops token.
75
+
76
+ Args:
77
+ input_text: prompt with N video_tokens per segment
78
+ video_segments: actual sampled frame count per video segment
79
+ video_token: the video token string, e.g. ']<]video[>['
80
+
81
+ Returns:
82
+ Pruned input_text with ~N/temporal_patch_size tokens per segment.
83
+ """
84
+ # If no videos or temporal_patch_size <= 1, no pruning needed
85
+ if not video_segments or self.video_processor.temporal_patch_size <= 1:
86
+ return input_text
87
+
88
+ # Split while keeping delimiters
89
+ special_tokens = [video_token] # , image_token]
90
+ pattern = "|".join(map(re.escape, special_tokens))
91
+ parts = re.split(f"({pattern})", input_text)
92
+
93
+ def is_timestamp(text: str) -> bool:
94
+ """Check if text ends with timestamp format like ']<]0.0 seconds[>['"""
95
+ return (
96
+ text.endswith("seconds[>[")
97
+ or text.endswith("seconds[>[ ")
98
+ or text.endswith("seconds [>[")
99
+ or text.endswith("seconds [>[ ")
100
+ )
101
+
102
+ def extract_timestamp(text: str) -> str:
103
+ """Extract timestamp text from the end, starting from ']<]'"""
104
+ start_index = text.rfind("]<]")
105
+ if start_index == -1:
106
+ raise ValueError(f"Failed to extract timestamp: {text}")
107
+ return text[start_index:]
108
+
109
+ # Build new text with pruned video tokens
110
+ final_parts = []
111
+ current_seg_idx = 0 # Which video segment we're in
112
+ frame_in_seg = 0 # Frame index within current segment
113
+ last_timestamp_len = 0 # Length of timestamp to potentially remove
114
+
115
+ for part in parts:
116
+ if part == video_token:
117
+ if current_seg_idx < len(video_segments):
118
+ if frame_in_seg % self.video_processor.temporal_patch_size == 0:
119
+ # Keep this video token
120
+ final_parts.append(part)
121
+ frame_in_seg += 1
122
+ if frame_in_seg >= video_segments[current_seg_idx]:
123
+ current_seg_idx += 1
124
+ frame_in_seg = 0
125
+ last_timestamp_len = 0
126
+ else:
127
+ # Skip this video token
128
+ frame_in_seg += 1
129
+ if frame_in_seg >= video_segments[current_seg_idx]:
130
+ current_seg_idx += 1
131
+ frame_in_seg = 0
132
+ # Remove the timestamp that was already appended
133
+ if last_timestamp_len > 0:
134
+ # Truncate the last part to remove timestamp
135
+ assert len(final_parts) > 0
136
+ final_parts[-1] = final_parts[-1][:-last_timestamp_len]
137
+ last_timestamp_len = 0
138
+ else:
139
+ # No more video segments, keep as is
140
+ final_parts.append(part)
141
+ last_timestamp_len = 0
142
+ else:
143
+ # Text part
144
+ final_parts.append(part)
145
+ # Check if this text ends with a timestamp
146
+ if is_timestamp(part):
147
+ last_timestamp_len = len(extract_timestamp(part))
148
+ else:
149
+ last_timestamp_len = 0
150
+
151
+ return "".join(final_parts)
152
+
153
+ def __call__(
154
+ self,
155
+ images=None,
156
+ text=None,
157
+ videos=None,
158
+ **kwargs: Unpack[MiniMaxVLProcessorKwargs],
159
+ ) -> BatchFeature:
160
+ output_kwargs = self._merge_kwargs(
161
+ MiniMaxVLProcessorKwargs,
162
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
163
+ **kwargs,
164
+ )
165
+
166
+ if images is not None:
167
+ images_kwargs = output_kwargs["images_kwargs"]
168
+ image_inputs = self.image_processor(images=images, **images_kwargs)
169
+ image_grid_thw = image_inputs["image_grid_thw"]
170
+
171
+ else:
172
+ image_inputs = {}
173
+ image_grid_thw = None
174
+
175
+ if videos is not None:
176
+ videos_kwargs = output_kwargs["videos_kwargs"]
177
+ video_inputs = self.video_processor(videos=videos, **videos_kwargs)
178
+ video_grid_thw = video_inputs["video_grid_thw"]
179
+ if not kwargs.get("return_metadata"):
180
+ video_metadata = video_inputs.pop("video_metadata")
181
+ else:
182
+ video_metadata = video_inputs["video_metadata"]
183
+ else:
184
+ video_inputs = {}
185
+ video_grid_thw = None
186
+
187
+ if not isinstance(text, list):
188
+ text = [text]
189
+ text = text.copy()
190
+
191
+ # Expand image tokens
192
+ if image_grid_thw is not None:
193
+ merge_length = self.image_processor.merge_size**2
194
+ placeholder = "]<]placeholder[>["
195
+ index = 0
196
+ for i in range(len(text)):
197
+ while self.IMAGE_TOKEN in text[i]:
198
+ num_tokens = image_grid_thw[index].prod() // merge_length
199
+ text[i] = text[i].replace(
200
+ self.IMAGE_TOKEN,
201
+ self.VISION_START_TOKEN
202
+ + placeholder * num_tokens
203
+ + self.VISION_END_TOKEN,
204
+ 1,
205
+ )
206
+ index += 1
207
+ text[i] = text[i].replace(placeholder, self.IMAGE_TOKEN)
208
+
209
+ # Expand video tokens
210
+ if video_grid_thw is not None:
211
+ merge_length = self.image_processor.merge_size**2
212
+ placeholder = "]<]placeholder[>["
213
+ index = 0
214
+ for i in range(len(text)):
215
+ while self.VIDEO_TOKEN in text[i]:
216
+ metadata = video_metadata[index]
217
+ grid_t = video_grid_thw[index][0]
218
+ frame_seqlen = video_grid_thw[index][1:].prod() // merge_length
219
+
220
+ video_placeholder = ""
221
+ for frame_idx in range(grid_t):
222
+ if (
223
+ metadata.fps is not None
224
+ and metadata.frames_indices is not None
225
+ ):
226
+ ts = (
227
+ metadata.frames_indices[
228
+ min(
229
+ frame_idx
230
+ * self.video_processor.temporal_patch_size,
231
+ len(metadata.frames_indices) - 1,
232
+ )
233
+ ]
234
+ / metadata.fps
235
+ )
236
+ video_placeholder += f"]<]{ts:.1f} seconds[>["
237
+ video_placeholder += (
238
+ self.VISION_START_TOKEN
239
+ + placeholder * frame_seqlen
240
+ + self.VISION_END_TOKEN
241
+ )
242
+
243
+ text[i] = text[i].replace(self.VIDEO_TOKEN, video_placeholder, 1)
244
+ index += 1
245
+ text[i] = text[i].replace(placeholder, self.VIDEO_TOKEN)
246
+
247
+ # Tokenize
248
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
249
+ text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
250
+
251
+ return BatchFeature(
252
+ data={**text_inputs, **image_inputs, **video_inputs},
253
+ tensor_type=return_tensors,
254
+ )
sglang_patch/flashinfer_trtllm.py ADDED
@@ -0,0 +1,1239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import TYPE_CHECKING, cast
5
+
6
+ import torch
7
+ from torch.nn import Module
8
+ from torch.nn.parameter import Parameter
9
+
10
+ # Import to register custom ops for torch.compile compatibility
11
+ from sglang.srt.distributed import get_tp_group
12
+ from sglang.srt.distributed.device_communicators.pynccl_allocator import (
13
+ is_symmetric_memory_enabled,
14
+ is_tensor_in_symmetric_mempool,
15
+ use_symmetric_memory,
16
+ )
17
+ from sglang.srt.environ import envs
18
+ from sglang.srt.layers.dp_attention import is_allocation_symmetric
19
+ from sglang.srt.layers.moe.flashinfer_trtllm_moe import (
20
+ trtllm_fp8_block_scale_moe_wrapper,
21
+ trtllm_fp8_block_scale_routed_moe_wrapper,
22
+ trtllm_fp8_per_tensor_scale_moe_wrapper,
23
+ )
24
+ from sglang.srt.layers.moe.moe_runner.base import (
25
+ MoeQuantInfo,
26
+ MoeRunnerConfig,
27
+ _moe_output_buf,
28
+ register_fused_func,
29
+ )
30
+ from sglang.srt.layers.quantization.fp8_kernel import (
31
+ per_token_group_quant_fp8,
32
+ scaled_fp8_quant,
33
+ )
34
+ from sglang.srt.layers.utils import copy_or_rebind_param
35
+ from sglang.srt.utils.common import (
36
+ is_cuda_alike,
37
+ is_flashinfer_available,
38
+ next_power_of_2,
39
+ )
40
+
41
+ _SGLANG_EXPERIMENTAL_LORA_OPTI = envs.SGLANG_EXPERIMENTAL_LORA_OPTI.get()
42
+
43
+ logger = __import__("logging").getLogger(__name__)
44
+
45
+
46
+ def round_up_to_multiple(x: int, m: int) -> int:
47
+ """Round up *x* to the nearest multiple of *m*."""
48
+ return (x + m - 1) // m * m
49
+
50
+
51
+ if TYPE_CHECKING:
52
+ from sglang.srt.layers.moe.token_dispatcher import (
53
+ StandardCombineInput,
54
+ StandardDispatchOutput,
55
+ )
56
+
57
+ if is_flashinfer_available():
58
+ from sglang.srt.layers.quantization.fp4_utils import fp4_quantize
59
+ elif is_cuda_alike():
60
+ from sglang.jit_kernel.nvfp4 import scaled_fp4_quant as fp4_quantize
61
+ else:
62
+ fp4_quantize = None
63
+
64
+ _flashinfer_trtllm_shuffle_row_indices_cache_mxfp8: dict[
65
+ tuple, dict[str, torch.Tensor]
66
+ ] = {}
67
+
68
+
69
+ def _is_gated(layer: Module) -> bool:
70
+ """Return whether the MoE layer uses a gated activation (default True)."""
71
+ is_gated = (
72
+ getattr(layer, "moe_runner_config", None) and layer.moe_runner_config.is_gated
73
+ )
74
+ return True if is_gated is None else is_gated
75
+
76
+
77
+ def _align_fp8_moe_weights(
78
+ w13: torch.Tensor,
79
+ w2: torch.Tensor,
80
+ is_gated: bool,
81
+ min_alignment: int = 16,
82
+ ) -> tuple[torch.Tensor, torch.Tensor, int]:
83
+ """Pad intermediate size so FlashInfer TRTLLM FP8 kernels' alignment holds.
84
+
85
+ Returns (w13, w2, padded_intermediate).
86
+ """
87
+ num_experts, hidden_size, intermediate = w2.shape
88
+
89
+ padded_intermediate = round_up_to_multiple(intermediate, min_alignment)
90
+ if padded_intermediate == intermediate:
91
+ return w13, w2, intermediate
92
+
93
+ logger.info(
94
+ "FP8 MoE: padding intermediate size from %d to %d (alignment=%d)",
95
+ intermediate,
96
+ padded_intermediate,
97
+ min_alignment,
98
+ )
99
+
100
+ up_mult = 2 if is_gated else 1
101
+ padded_gate_up = up_mult * padded_intermediate
102
+
103
+ padded_w13 = w13.new_zeros((num_experts, padded_gate_up, w13.shape[2]))
104
+ padded_w13[:, : w13.shape[1], :] = w13
105
+
106
+ padded_w2 = w2.new_zeros((num_experts, hidden_size, padded_intermediate))
107
+ padded_w2[:, :, :intermediate] = w2
108
+
109
+ return padded_w13, padded_w2, padded_intermediate
110
+
111
+
112
+ def align_fp8_moe_weights_for_flashinfer_trtllm(
113
+ layer: Module, swap_w13_halves: bool = False
114
+ ) -> None:
115
+ """Prepare FP8 MoE weights/scales for FlashInfer TRT-LLM kernels.
116
+
117
+ Args:
118
+ layer: The MoE layer to process.
119
+ swap_w13_halves: If True, swap W13 halves from [Up, Gate] to [Gate, Up].
120
+ This is needed for ModelOpt FP8 checkpoints which store weights in
121
+ [Up, Gate] order, while regular FP8 checkpoints store them in [Gate, Up].
122
+ """
123
+ from flashinfer import shuffle_matrix_a
124
+
125
+ is_gated = _is_gated(layer)
126
+
127
+ w13_weight = cast(torch.Tensor, layer.w13_weight)
128
+ w2_weight = cast(torch.Tensor, layer.w2_weight)
129
+ num_experts, gate_up_dim, hidden = w13_weight.shape
130
+
131
+ # Optionally swap W13 halves: [Up, Gate] -> [Gate, Up] (only for gated)
132
+ if swap_w13_halves and is_gated:
133
+ inter = gate_up_dim // 2
134
+ w13_weight = (
135
+ w13_weight.reshape(num_experts, 2, inter, hidden)
136
+ .flip(dims=[1])
137
+ .reshape(num_experts, gate_up_dim, hidden)
138
+ )
139
+
140
+ # Pad for kernel alignment (non-gated needs 128, gated needs 16)
141
+ min_alignment = 16 if is_gated else 128
142
+ w13_weight, w2_weight, _ = _align_fp8_moe_weights(
143
+ w13_weight, w2_weight, is_gated, min_alignment
144
+ )
145
+ num_experts, gate_up_dim, hidden = w13_weight.shape
146
+
147
+ epilogue_tile_m = 128
148
+
149
+ if is_gated:
150
+ from flashinfer import reorder_rows_for_gated_act_gemm
151
+
152
+ w13_interleaved_list = [
153
+ reorder_rows_for_gated_act_gemm(w13_weight[i]) for i in range(num_experts)
154
+ ]
155
+ w13_processed: torch.Tensor = torch.stack(w13_interleaved_list).reshape(
156
+ num_experts, gate_up_dim, hidden
157
+ )
158
+ else:
159
+ w13_processed = w13_weight
160
+
161
+ # Shuffle weights for transposed MMA output (both W13, W2)
162
+ w13_shuffled = [
163
+ shuffle_matrix_a(w13_processed[i].view(torch.uint8), epilogue_tile_m)
164
+ for i in range(num_experts)
165
+ ]
166
+ w2_shuffled = [
167
+ shuffle_matrix_a(w2_weight[i].view(torch.uint8), epilogue_tile_m)
168
+ for i in range(num_experts)
169
+ ]
170
+
171
+ layer.w13_weight = Parameter(
172
+ torch.stack(w13_shuffled).view(torch.float8_e4m3fn),
173
+ requires_grad=False,
174
+ )
175
+ layer.w2_weight = Parameter(
176
+ torch.stack(w2_shuffled).view(torch.float8_e4m3fn),
177
+ requires_grad=False,
178
+ )
179
+
180
+ # Precompute and register per-expert output scaling factors for FI MoE.
181
+ # Note: w13_input_scale and w2_input_scale are scalar Parameters post-reduction.
182
+ assert hasattr(layer, "w13_input_scale") and layer.w13_input_scale is not None
183
+ assert hasattr(layer, "w2_input_scale") and layer.w2_input_scale is not None
184
+ assert hasattr(layer, "w13_weight_scale") and layer.w13_weight_scale is not None
185
+ assert hasattr(layer, "w2_weight_scale") and layer.w2_weight_scale is not None
186
+
187
+ input_scale = cast(torch.Tensor, layer.w13_input_scale).to(torch.float32)
188
+ activation_scale = cast(torch.Tensor, layer.w2_input_scale).to(torch.float32)
189
+ w13_weight_scale = cast(torch.Tensor, layer.w13_weight_scale).to(torch.float32)
190
+ w2_weight_scale = cast(torch.Tensor, layer.w2_weight_scale).to(torch.float32)
191
+
192
+ # For gated (SwiGLU): g1_alphas = w1_scale * a1_scale, g1_scale_c = g1_alphas / a2_scale
193
+ # For non-gated (Relu2): g1_scale_c = 1 / a2_scale (no gate dequant contribution)
194
+ if is_gated:
195
+ output1_scales_scalar = (
196
+ w13_weight_scale * input_scale * (1.0 / activation_scale)
197
+ )
198
+ else:
199
+ output1_scales_scalar = torch.ones_like(w13_weight_scale) * (
200
+ 1.0 / activation_scale
201
+ )
202
+ output1_scales_gate_scalar = w13_weight_scale * input_scale
203
+ output2_scales_scalar = activation_scale * w2_weight_scale
204
+
205
+ layer.output1_scales_scalar = Parameter(output1_scales_scalar, requires_grad=False)
206
+ layer.output1_scales_gate_scalar = Parameter(
207
+ output1_scales_gate_scalar, requires_grad=False
208
+ )
209
+ layer.output2_scales_scalar = Parameter(output2_scales_scalar, requires_grad=False)
210
+
211
+
212
+ def _align_mxfp8_moe_weights(
213
+ w13: torch.Tensor,
214
+ w13_scale: torch.Tensor,
215
+ w2: torch.Tensor,
216
+ w2_scale: torch.Tensor,
217
+ is_gated: bool,
218
+ min_alignment: int = 16,
219
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, int]:
220
+ """Pad intermediate size so FlashInfer TRTLLM MXFP8 kernels' alignment holds.
221
+
222
+ Returns (w13, w13_scale, w2, w2_scale, padded_intermediate).
223
+ """
224
+ num_experts, hidden_size, intermediate = w2.shape
225
+
226
+ padded_intermediate = round_up_to_multiple(intermediate, min_alignment)
227
+ if padded_intermediate == intermediate:
228
+ return w13, w13_scale, w2, w2_scale, intermediate
229
+
230
+ logger.info(
231
+ "MXFP8 MoE: padding intermediate size from %d to %d (alignment=%d)",
232
+ intermediate,
233
+ padded_intermediate,
234
+ min_alignment,
235
+ )
236
+
237
+ up_mult = 2 if is_gated else 1
238
+ padded_gate_up = up_mult * padded_intermediate
239
+
240
+ padded_w13 = w13.new_zeros((num_experts, padded_gate_up, w13.shape[2]))
241
+ padded_w13[:, : w13.shape[1], :] = w13
242
+
243
+ padded_w2 = w2.new_zeros((num_experts, hidden_size, padded_intermediate))
244
+ padded_w2[:, :, :intermediate] = w2
245
+
246
+ padded_w13_scale = w13_scale.new_zeros(
247
+ (num_experts, padded_gate_up, w13_scale.shape[2])
248
+ )
249
+ padded_w13_scale[:, : w13_scale.shape[1], :] = w13_scale
250
+
251
+ # Scale's last dim tracks intermediate / block_size (MXFP8 block_size = 32)
252
+ scale_block_k = intermediate // w2_scale.shape[2] if w2_scale.shape[2] > 0 else 32
253
+ padded_w2_scale = w2_scale.new_zeros(
254
+ (num_experts, hidden_size, padded_intermediate // scale_block_k)
255
+ )
256
+ padded_w2_scale[:, :, : w2_scale.shape[2]] = w2_scale
257
+
258
+ return padded_w13, padded_w13_scale, padded_w2, padded_w2_scale, padded_intermediate
259
+
260
+
261
+ def align_mxfp8_moe_weights_for_flashinfer_trtllm(layer: Module) -> None:
262
+ """Prepare MXFP8 MoE weights/scales for FlashInfer TRT-LLM kernels."""
263
+ from flashinfer import block_scale_interleave
264
+ from flashinfer.fused_moe.core import (
265
+ get_reorder_rows_for_gated_act_gemm_row_indices,
266
+ )
267
+ from flashinfer.utils import (
268
+ get_shuffle_matrix_a_row_indices,
269
+ get_shuffle_matrix_sf_a_row_indices,
270
+ )
271
+
272
+ is_gated = _is_gated(layer)
273
+
274
+ w13_weight = cast(torch.Tensor, layer.w13_weight).contiguous()
275
+ w2_weight = cast(torch.Tensor, layer.w2_weight).contiguous()
276
+ w13_scale = cast(torch.Tensor, layer.w13_weight_scale_inv).contiguous()
277
+ w2_scale = cast(torch.Tensor, layer.w2_weight_scale_inv).contiguous()
278
+
279
+ assert w13_scale.dtype == torch.uint8
280
+ assert w2_scale.dtype == torch.uint8
281
+
282
+ # Pad for kernel alignment (non-gated needs 128, gated needs 16)
283
+ min_alignment = 16 if is_gated else 128
284
+ w13_weight, w13_scale, w2_weight, w2_scale, _ = _align_mxfp8_moe_weights(
285
+ w13_weight, w13_scale, w2_weight, w2_scale, is_gated, min_alignment
286
+ )
287
+
288
+ num_experts, gate_up_dim, _ = w13_weight.shape
289
+ _, hidden_size, _ = w2_weight.shape
290
+ epilogue_tile_m = 128
291
+
292
+ # Reuse precomputed row-index transforms whenever shape/device are unchanged.
293
+ w13_weight_u8 = w13_weight.view(torch.uint8)
294
+ w2_weight_u8 = w2_weight.view(torch.uint8)
295
+ cache_key = (
296
+ gate_up_dim,
297
+ hidden_size,
298
+ w2_weight.shape[-1],
299
+ w13_scale.shape[-1],
300
+ w2_scale.shape[-1],
301
+ epilogue_tile_m,
302
+ (w13_weight.device.type, w13_weight.device.index),
303
+ (w2_weight.device.type, w2_weight.device.index),
304
+ (w13_scale.device.type, w13_scale.device.index),
305
+ (w2_scale.device.type, w2_scale.device.index),
306
+ )
307
+ cache = _flashinfer_trtllm_shuffle_row_indices_cache_mxfp8.get(cache_key)
308
+ if cache is None:
309
+ if is_gated:
310
+ reorder_row_indices = get_reorder_rows_for_gated_act_gemm_row_indices(
311
+ w13_weight_u8[0]
312
+ ).to(w13_weight.device)
313
+ else:
314
+ reorder_row_indices = torch.arange(
315
+ gate_up_dim, device=w13_weight.device, dtype=torch.long
316
+ )
317
+ w13_shuffle_row_indices = get_shuffle_matrix_a_row_indices(
318
+ w13_weight_u8[0], epilogue_tile_m
319
+ ).to(w13_weight.device)
320
+ w2_shuffle_row_indices = get_shuffle_matrix_a_row_indices(
321
+ w2_weight_u8[0], epilogue_tile_m
322
+ ).to(w2_weight.device)
323
+ w13_scale_shuffle_row_indices = get_shuffle_matrix_sf_a_row_indices(
324
+ w13_scale[0].reshape(gate_up_dim, -1), epilogue_tile_m
325
+ ).to(w13_scale.device)
326
+ w2_scale_shuffle_row_indices = get_shuffle_matrix_sf_a_row_indices(
327
+ w2_scale[0].reshape(hidden_size, -1), epilogue_tile_m
328
+ ).to(w2_scale.device)
329
+ cache = {
330
+ "reorder_row_indices": reorder_row_indices,
331
+ "w13_shuffle_row_indices": w13_shuffle_row_indices,
332
+ "w2_shuffle_row_indices": w2_shuffle_row_indices,
333
+ "w13_scale_shuffle_row_indices": w13_scale_shuffle_row_indices,
334
+ "w2_scale_shuffle_row_indices": w2_scale_shuffle_row_indices,
335
+ }
336
+ _flashinfer_trtllm_shuffle_row_indices_cache_mxfp8[cache_key] = cache
337
+
338
+ reorder_row_indices = cache["reorder_row_indices"]
339
+ w13_shuffle_row_indices = cache["w13_shuffle_row_indices"]
340
+ w2_shuffle_row_indices = cache["w2_shuffle_row_indices"]
341
+ w13_scale_shuffle_row_indices = cache["w13_scale_shuffle_row_indices"]
342
+ w2_scale_shuffle_row_indices = cache["w2_scale_shuffle_row_indices"]
343
+
344
+ w13_shuffled_u8 = torch.empty_like(w13_weight_u8)
345
+ w2_shuffled_u8 = torch.empty_like(w2_weight_u8)
346
+ w13_scale_shuffled = torch.empty_like(w13_scale)
347
+ w2_scale_shuffled = torch.empty_like(w2_scale)
348
+
349
+ for i in range(num_experts):
350
+ w13_interleaved_u8 = w13_weight_u8[i].index_select(0, reorder_row_indices)
351
+ w13_scale_interleaved = w13_scale[i].index_select(0, reorder_row_indices)
352
+
353
+ w13_shuffled_u8[i].copy_(
354
+ w13_interleaved_u8.index_select(0, w13_shuffle_row_indices)
355
+ )
356
+ w2_shuffled_u8[i].copy_(w2_weight_u8[i].index_select(0, w2_shuffle_row_indices))
357
+
358
+ w13_scale_linear = w13_scale_interleaved.reshape(gate_up_dim, -1)
359
+ w13_scale_shuffled[i].copy_(
360
+ block_scale_interleave(
361
+ w13_scale_linear.index_select(0, w13_scale_shuffle_row_indices)
362
+ ).reshape_as(w13_scale_shuffled[i])
363
+ )
364
+
365
+ w2_scale_linear = w2_scale[i].reshape(hidden_size, -1)
366
+ w2_scale_shuffled[i].copy_(
367
+ block_scale_interleave(
368
+ w2_scale_linear.index_select(0, w2_scale_shuffle_row_indices)
369
+ ).reshape_as(w2_scale_shuffled[i])
370
+ )
371
+
372
+ # Keep parameter identities stable for CUDA graph capture reuse.
373
+ copy_or_rebind_param(layer, "w13_weight", w13_shuffled_u8.view(torch.float8_e4m3fn))
374
+ copy_or_rebind_param(layer, "w2_weight", w2_shuffled_u8.view(torch.float8_e4m3fn))
375
+ copy_or_rebind_param(
376
+ layer,
377
+ "w13_weight_scale_inv",
378
+ w13_scale_shuffled.contiguous(),
379
+ )
380
+ copy_or_rebind_param(
381
+ layer,
382
+ "w2_weight_scale_inv",
383
+ w2_scale_shuffled.contiguous(),
384
+ )
385
+ layer.w13_weight_scale_inv.format_ue8m0 = True
386
+ layer.w2_weight_scale_inv.format_ue8m0 = True
387
+
388
+
389
+ def _align_fp4_moe_weights(
390
+ w13: torch.Tensor,
391
+ w13_scale: torch.Tensor,
392
+ w2: torch.Tensor,
393
+ w2_scale: torch.Tensor,
394
+ is_gated: bool,
395
+ min_alignment: int = 16,
396
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, int]:
397
+ """Pad intermediate size so FlashInfer TRTLLM FP4 kernels' alignment holds.
398
+
399
+ Returns (w13, w13_scale, w2, w2_scale, padded_intermediate).
400
+ """
401
+ num_experts, hidden_size, intermediate_packed = w2.shape
402
+ intermediate = intermediate_packed * 2 # FP4 packs 2 values per byte
403
+
404
+ padded_intermediate = round_up_to_multiple(intermediate, min_alignment)
405
+ if padded_intermediate == intermediate:
406
+ return w13, w13_scale, w2, w2_scale, intermediate
407
+
408
+ logger.info(
409
+ "FP4 MoE: padding intermediate size from %d to %d (alignment=%d)",
410
+ intermediate,
411
+ padded_intermediate,
412
+ min_alignment,
413
+ )
414
+
415
+ up_mult = 2 if is_gated else 1
416
+ padded_gate_up = up_mult * padded_intermediate
417
+
418
+ padded_w13 = w13.new_zeros((num_experts, padded_gate_up, w13.shape[2]))
419
+ padded_w13[:, : w13.shape[1], :] = w13
420
+
421
+ padded_w2 = w2.new_zeros((num_experts, hidden_size, padded_intermediate // 2))
422
+ padded_w2[:, :, : w2.shape[2]] = w2
423
+
424
+ padded_w13_scale = w13_scale.new_zeros(
425
+ (num_experts, padded_gate_up, w13_scale.shape[2])
426
+ )
427
+ padded_w13_scale[:, : w13_scale.shape[1], :] = w13_scale
428
+
429
+ padded_w2_scale = w2_scale.new_zeros(
430
+ (num_experts, hidden_size, padded_intermediate // 16)
431
+ )
432
+ padded_w2_scale[:, :, : w2_scale.shape[2]] = w2_scale
433
+
434
+ return padded_w13, padded_w13_scale, padded_w2, padded_w2_scale, padded_intermediate
435
+
436
+
437
+ def align_fp4_moe_weights_for_flashinfer_trtllm(layer: Module) -> None:
438
+ """Prepare FP4 MoE weights/scales for FlashInfer TRT-LLM kernels.
439
+
440
+ This function handles the weight transformation needed for FP4 TRTLLM MoE:
441
+ - Pads intermediate dimension for kernel alignment constraints
442
+ - Reorders weights for gated activation GEMM
443
+ - Shuffles weights and scales for transposed MMA output
444
+ - Computes the output scale factors
445
+ """
446
+ from sglang.srt.layers.quantization.utils import (
447
+ prepare_static_weights_for_trtllm_fp4_moe,
448
+ )
449
+
450
+ w13_weight = cast(torch.Tensor, layer.w13_weight)
451
+ w2_weight = cast(torch.Tensor, layer.w2_weight)
452
+ w13_weight_scale = cast(torch.Tensor, layer.w13_weight_scale)
453
+ w2_weight_scale = cast(torch.Tensor, layer.w2_weight_scale)
454
+
455
+ is_gated = layer.moe_runner_config.is_gated
456
+ min_alignment = 16 if is_gated else 128
457
+
458
+ # Pad for kernel alignment before shuffle/reorder
459
+ w13_weight, w13_weight_scale, w2_weight, w2_weight_scale, intermediate_size = (
460
+ _align_fp4_moe_weights(
461
+ w13_weight,
462
+ w13_weight_scale,
463
+ w2_weight,
464
+ w2_weight_scale,
465
+ is_gated,
466
+ min_alignment,
467
+ )
468
+ )
469
+
470
+ (
471
+ gemm1_weights_fp4_shuffled,
472
+ gemm1_scales_fp4_shuffled,
473
+ gemm2_weights_fp4_shuffled,
474
+ gemm2_scales_fp4_shuffled,
475
+ ) = prepare_static_weights_for_trtllm_fp4_moe(
476
+ w13_weight,
477
+ w2_weight,
478
+ w13_weight_scale,
479
+ w2_weight_scale,
480
+ w2_weight.size(-2), # hidden_size
481
+ intermediate_size, # padded intermediate_size
482
+ w13_weight.size(0), # num_experts
483
+ is_gated=is_gated,
484
+ )
485
+
486
+ # Set flashinfer parameters in-place
487
+ copy_or_rebind_param(layer, "w13_weight", gemm1_weights_fp4_shuffled.contiguous())
488
+ copy_or_rebind_param(layer, "w2_weight", gemm2_weights_fp4_shuffled.contiguous())
489
+ copy_or_rebind_param(
490
+ layer, "w13_weight_scale", gemm1_scales_fp4_shuffled.contiguous()
491
+ )
492
+ copy_or_rebind_param(
493
+ layer, "w2_weight_scale", gemm2_scales_fp4_shuffled.contiguous()
494
+ )
495
+
496
+ # Compute additional scaling factor needed for TRT-LLM.
497
+ # For gated (SwiGLU): g1_scale_c = g1_alphas * a2_gscale
498
+ # For non-gated (Relu2): g1_scale_c = a2_gscale (no gate dequant contribution)
499
+ w2_input_scale_quant = cast(torch.Tensor, layer.w2_input_scale_quant)
500
+ g1_alphas = cast(torch.Tensor, layer.g1_alphas)
501
+ if layer.moe_runner_config.is_gated:
502
+ g1_scale_c = (w2_input_scale_quant * g1_alphas).to(torch.float32)
503
+ else:
504
+ num_experts = g1_alphas.shape[0]
505
+ g1_scale_c = (
506
+ w2_input_scale_quant.to(torch.float32).expand(num_experts).contiguous()
507
+ )
508
+ copy_or_rebind_param(layer, "g1_scale_c", g1_scale_c)
509
+
510
+ # Update intermediate_size_per_partition to reflect any padding applied
511
+ layer.intermediate_size_per_partition = intermediate_size
512
+
513
+
514
+ def get_activation_type(activation: str, is_gated: bool = True) -> int:
515
+ """Map SGLang activation string to FlashInfer ActivationType int value."""
516
+ from flashinfer.fused_moe.core import ActivationType
517
+
518
+ if is_gated:
519
+ _ACTIVATION_STR_TO_TYPE = {
520
+ "silu": ActivationType.Swiglu,
521
+ "gelu": ActivationType.Geglu,
522
+ }
523
+ else:
524
+ _ACTIVATION_STR_TO_TYPE = {
525
+ "silu": ActivationType.Silu,
526
+ "gelu": ActivationType.Gelu,
527
+ "relu2": ActivationType.Relu2,
528
+ }
529
+ act = _ACTIVATION_STR_TO_TYPE.get(activation)
530
+ if act is None:
531
+ raise ValueError(
532
+ f"Unsupported activation '{activation}' for TRTLLM MoE "
533
+ f"(is_gated={is_gated}). "
534
+ f"Expected one of {list(_ACTIVATION_STR_TO_TYPE.keys())}."
535
+ )
536
+ return act.value
537
+
538
+
539
+ @dataclass
540
+ class FlashInferTrtllmFp8MoeQuantInfo(MoeQuantInfo):
541
+ """Quantization payload consumed by FlashInfer TRT-LLM FP8 MoE kernels."""
542
+
543
+ # Weights
544
+ w13_weight: torch.Tensor
545
+ w2_weight: torch.Tensor
546
+
547
+ # Expert-parallel metadata
548
+ global_num_experts: int
549
+ local_expert_offset: int
550
+ local_num_experts: int
551
+ intermediate_size: int
552
+
553
+ routing_method_type: int
554
+
555
+ # Block-quant path
556
+ block_quant: bool
557
+ use_mxfp8: bool = False
558
+ weight_block_k: int | None = None
559
+ w13_weight_scale_inv: torch.Tensor | None = None
560
+ w2_weight_scale_inv: torch.Tensor | None = None
561
+
562
+ # Per-tensor path
563
+ w13_input_scale: torch.Tensor | None = None
564
+ output1_scales_scalar: torch.Tensor | None = None
565
+ output1_scales_gate_scalar: torch.Tensor | None = None
566
+ output2_scales_scalar: torch.Tensor | None = None
567
+ use_routing_scales_on_input: bool = False
568
+
569
+ # Activation type (None = kernel default / Swiglu)
570
+ activation_type: int | None = None
571
+
572
+
573
+ def _pack_topk_for_flashinfer_routed(
574
+ topk_ids: torch.Tensor, topk_weights: torch.Tensor
575
+ ) -> torch.Tensor:
576
+ """Pack routed top-k tensors into FlashInfer's int32 format."""
577
+ packed_ids = topk_ids.to(torch.int32)
578
+ packed_weights = topk_weights.to(torch.bfloat16)
579
+ packed = (packed_ids << 16) | packed_weights.view(torch.int16).to(torch.int32)
580
+ return packed
581
+
582
+
583
+ def fused_experts_none_to_flashinfer_trtllm_fp8(
584
+ dispatch_output: StandardDispatchOutput,
585
+ quant_info: FlashInferTrtllmFp8MoeQuantInfo,
586
+ runner_config: MoeRunnerConfig,
587
+ use_routed_topk: bool = False,
588
+ ) -> StandardCombineInput:
589
+ from flashinfer.fused_moe import Fp8QuantizationType
590
+
591
+ from sglang.srt.layers.moe.token_dispatcher.standard import StandardCombineInput
592
+ from sglang.srt.layers.moe.topk import TopKOutputChecker
593
+ from sglang.srt.layers.moe.utils import RoutingMethodType
594
+
595
+ _SUPPORTED_FP8_ACTIVATIONS = {"silu", "relu2"}
596
+ assert runner_config.activation in _SUPPORTED_FP8_ACTIVATIONS, (
597
+ f"Only {_SUPPORTED_FP8_ACTIVATIONS} are supported for FP8 MoE, "
598
+ f"got '{runner_config.activation}'."
599
+ )
600
+ assert not runner_config.no_combine, "no_combine is not supported for flashinfer."
601
+
602
+ hidden_states = dispatch_output.hidden_states
603
+ topk_output = dispatch_output.topk_output
604
+ if TopKOutputChecker.format_is_bypassed(topk_output):
605
+ router_logits = topk_output.router_logits
606
+ topk_config = topk_output.topk_config
607
+ correction_bias = (
608
+ None
609
+ if topk_config.correction_bias is None
610
+ else topk_config.correction_bias.to(hidden_states.dtype)
611
+ )
612
+ else:
613
+ router_logits = None
614
+ topk_config = None
615
+ correction_bias = None
616
+
617
+ routing_method_type = quant_info.routing_method_type
618
+ fp8_quantization_type = (
619
+ Fp8QuantizationType.MxFp8
620
+ if quant_info.use_mxfp8
621
+ else Fp8QuantizationType.DeepSeekFp8
622
+ )
623
+ use_shuffled_weight = quant_info.use_mxfp8
624
+
625
+ if quant_info.block_quant:
626
+ assert quant_info.weight_block_k is not None
627
+ assert quant_info.w13_weight_scale_inv is not None
628
+ assert quant_info.w2_weight_scale_inv is not None
629
+
630
+ if quant_info.use_mxfp8:
631
+ assert quant_info.weight_block_k == 32
632
+ from flashinfer import mxfp8_quantize
633
+
634
+ a_q, a_sf = mxfp8_quantize(hidden_states, False)
635
+ # FlashInfer TRT-LLM MxFP8 expects token-major activation scales:
636
+ # [num_tokens, hidden_size // 32] (no transpose).
637
+ a_sf_t = a_sf.view(torch.uint8).reshape(hidden_states.shape[0], -1)
638
+ else:
639
+ a_q, a_sf = per_token_group_quant_fp8(
640
+ hidden_states, quant_info.weight_block_k
641
+ )
642
+ a_sf_t = a_sf.t().contiguous()
643
+
644
+ # Allocate output inside symmetric memory context
645
+ with use_symmetric_memory(
646
+ get_tp_group(), disabled=not is_allocation_symmetric()
647
+ ):
648
+ symm_output = torch.empty(
649
+ hidden_states.shape[0],
650
+ hidden_states.shape[1],
651
+ dtype=hidden_states.dtype,
652
+ device=hidden_states.device,
653
+ )
654
+
655
+ # Move kernel call outside context manager to avoid graph breaks
656
+ # during torch.compile for piecewise cuda graph.
657
+ # Use custom op wrapper for torch.compile compatibility.
658
+ if use_routed_topk:
659
+ assert (
660
+ runner_config.top_k is not None
661
+ ), "runner_config.top_k is required for flashinfer_trtllm_routed."
662
+ assert TopKOutputChecker.format_is_standard(topk_output)
663
+ packed_topk_ids = _pack_topk_for_flashinfer_routed(
664
+ topk_ids=topk_output.topk_ids,
665
+ topk_weights=topk_output.topk_weights,
666
+ )
667
+
668
+ output = trtllm_fp8_block_scale_routed_moe_wrapper(
669
+ topk_ids=packed_topk_ids,
670
+ routing_bias=None,
671
+ hidden_states=a_q,
672
+ hidden_states_scale=a_sf_t,
673
+ gemm1_weights=quant_info.w13_weight,
674
+ gemm1_weights_scale=quant_info.w13_weight_scale_inv,
675
+ gemm2_weights=quant_info.w2_weight,
676
+ gemm2_weights_scale=quant_info.w2_weight_scale_inv,
677
+ num_experts=quant_info.global_num_experts,
678
+ top_k=runner_config.top_k,
679
+ n_group=None,
680
+ topk_group=None,
681
+ intermediate_size=quant_info.intermediate_size,
682
+ local_expert_offset=quant_info.local_expert_offset,
683
+ local_num_experts=quant_info.local_num_experts,
684
+ routed_scaling_factor=(
685
+ runner_config.routed_scaling_factor
686
+ if runner_config.routed_scaling_factor is not None
687
+ else 1.0
688
+ ),
689
+ routing_method_type=(
690
+ RoutingMethodType.TopK
691
+ if routing_method_type == RoutingMethodType.DeepSeekV3
692
+ else routing_method_type
693
+ ),
694
+ use_shuffled_weight=use_shuffled_weight,
695
+ tune_max_num_tokens=next_power_of_2(a_q.shape[0]),
696
+ fp8_quantization_type=int(fp8_quantization_type),
697
+ activation_type=quant_info.activation_type,
698
+ )
699
+ else:
700
+ assert TopKOutputChecker.format_is_bypassed(topk_output)
701
+
702
+ output = trtllm_fp8_block_scale_moe_wrapper(
703
+ routing_logits=router_logits,
704
+ routing_bias=correction_bias,
705
+ hidden_states=a_q,
706
+ hidden_states_scale=a_sf_t,
707
+ gemm1_weights=quant_info.w13_weight,
708
+ gemm1_weights_scale=quant_info.w13_weight_scale_inv,
709
+ gemm2_weights=quant_info.w2_weight,
710
+ gemm2_weights_scale=quant_info.w2_weight_scale_inv,
711
+ num_experts=quant_info.global_num_experts,
712
+ top_k=topk_config.top_k,
713
+ n_group=topk_config.num_expert_group,
714
+ topk_group=topk_config.topk_group,
715
+ intermediate_size=quant_info.intermediate_size,
716
+ local_expert_offset=quant_info.local_expert_offset,
717
+ local_num_experts=quant_info.local_num_experts,
718
+ routed_scaling_factor=(
719
+ runner_config.routed_scaling_factor
720
+ if runner_config.routed_scaling_factor is not None
721
+ else 1.0
722
+ ),
723
+ routing_method_type=routing_method_type,
724
+ use_shuffled_weight=use_shuffled_weight,
725
+ tune_max_num_tokens=next_power_of_2(a_q.shape[0]),
726
+ fp8_quantization_type=int(fp8_quantization_type),
727
+ activation_type=quant_info.activation_type,
728
+ )
729
+ # TODO: Once https://github.com/flashinfer-ai/flashinfer/issues/2703 is fixed, pass output to moe kernel and remove this copy.
730
+ symm_output.copy_(output)
731
+ output = symm_output
732
+ else:
733
+ assert TopKOutputChecker.format_is_bypassed(topk_output)
734
+ assert quant_info.w13_input_scale is not None
735
+ assert quant_info.output1_scales_scalar is not None
736
+ assert quant_info.output1_scales_gate_scalar is not None
737
+ assert quant_info.output2_scales_scalar is not None
738
+
739
+ a_q, _ = scaled_fp8_quant(hidden_states, quant_info.w13_input_scale)
740
+ routing_bias_cast = (
741
+ None if correction_bias is None else correction_bias.to(torch.bfloat16)
742
+ )
743
+
744
+ # Allocate output inside symmetric memory context
745
+ with use_symmetric_memory(
746
+ get_tp_group(), disabled=not is_allocation_symmetric()
747
+ ):
748
+ symm_output = torch.empty(
749
+ hidden_states.shape[0],
750
+ hidden_states.shape[1],
751
+ dtype=torch.bfloat16,
752
+ device=hidden_states.device,
753
+ )
754
+
755
+ # Move kernel call outside context manager to avoid graph breaks
756
+ # during torch.compile for piecewise cuda graph.
757
+ # Use custom op wrapper for torch.compile compatibility.
758
+
759
+ router_logits = router_logits.to(torch.bfloat16)
760
+
761
+ output = trtllm_fp8_per_tensor_scale_moe_wrapper(
762
+ routing_logits=router_logits,
763
+ routing_bias=routing_bias_cast,
764
+ hidden_states=a_q,
765
+ gemm1_weights=quant_info.w13_weight,
766
+ output1_scales_scalar=quant_info.output1_scales_scalar,
767
+ output1_scales_gate_scalar=quant_info.output1_scales_gate_scalar,
768
+ gemm2_weights=quant_info.w2_weight,
769
+ output2_scales_scalar=quant_info.output2_scales_scalar,
770
+ num_experts=quant_info.global_num_experts,
771
+ top_k=topk_config.top_k,
772
+ n_group=topk_config.num_expert_group,
773
+ topk_group=topk_config.topk_group,
774
+ intermediate_size=int(quant_info.w2_weight.shape[2]),
775
+ local_expert_offset=quant_info.local_expert_offset,
776
+ local_num_experts=quant_info.local_num_experts,
777
+ routed_scaling_factor=(
778
+ runner_config.routed_scaling_factor
779
+ if runner_config.routed_scaling_factor is not None
780
+ else 1.0
781
+ ),
782
+ use_routing_scales_on_input=False,
783
+ routing_method_type=routing_method_type,
784
+ tune_max_num_tokens=next_power_of_2(a_q.shape[0]),
785
+ activation_type=quant_info.activation_type,
786
+ )
787
+ symm_output.copy_(output)
788
+ output = symm_output
789
+
790
+ return StandardCombineInput(hidden_states=output)
791
+
792
+
793
+ @dataclass
794
+ class FlashInferTrtllmFp4MoeQuantInfo(MoeQuantInfo):
795
+ """Quantization payload consumed by FlashInfer TRT-LLM FP4 MoE kernels."""
796
+
797
+ w13_weight: torch.Tensor
798
+ w2_weight: torch.Tensor
799
+ w13_weight_scale: torch.Tensor
800
+ w2_weight_scale: torch.Tensor
801
+
802
+ # Scaling factors
803
+ g1_scale_c: torch.Tensor
804
+ g1_alphas: torch.Tensor
805
+ g2_alphas: torch.Tensor
806
+ w13_input_scale_quant: torch.Tensor
807
+
808
+ # Expert-parallel metadata
809
+ global_num_experts: int
810
+ local_expert_offset: int
811
+ local_num_experts: int
812
+ intermediate_size_per_partition: int
813
+
814
+ routing_method_type: int
815
+ use_per_token_activation: bool = False
816
+
817
+
818
+ def quantize_hidden_states_fp4(
819
+ hidden_states: torch.Tensor,
820
+ input_scale_quant: torch.Tensor,
821
+ ) -> tuple[torch.Tensor, torch.Tensor]:
822
+ """
823
+ Quantize hidden states to FP4 for TRTLLM MoE.
824
+
825
+ Global scale factor is set by ModelOptNvFp4FusedMoEMethod during weight loading.
826
+ Only block scales are computed at runtime for efficiency.
827
+
828
+ Returns (packed_fp4_uint8, scale_float8_e4m3fn_runtime)
829
+ """
830
+
831
+ # flashinfer.fp4_quantize returns (packed_uint8, scale_fp8)
832
+ # Only the block scales are computed at runtime
833
+ hs_fp4_bytes, hs_sf_bytes = fp4_quantize(
834
+ hidden_states,
835
+ input_scale_quant,
836
+ 16, # sf_vec_size
837
+ False, # use_ue8m0
838
+ False, # is_sf_swizzled_layout
839
+ )
840
+
841
+ seq_len, hidden_size = hidden_states.shape
842
+ hs_fp4 = hs_fp4_bytes.reshape(seq_len, hidden_size // 2)
843
+ # TRT-LLM expects hidden state scales shaped as [seq_len, hidden_size // 16]
844
+ hs_sf = hs_sf_bytes.view(torch.float8_e4m3fn).reshape(seq_len, hidden_size // 16)
845
+
846
+ return hs_fp4, hs_sf
847
+
848
+
849
+ def fused_experts_none_to_flashinfer_trtllm_fp4(
850
+ dispatch_output: StandardDispatchOutput,
851
+ quant_info: FlashInferTrtllmFp4MoeQuantInfo,
852
+ runner_config: MoeRunnerConfig,
853
+ use_routed_topk: bool = False,
854
+ ) -> StandardCombineInput:
855
+ """FlashInfer TRTLLM FP4 MoE forward pass.
856
+
857
+ This function handles the FP4 TRTLLM MoE path that was previously in
858
+ ModelOptNvFp4FusedMoEMethod.apply.
859
+ """
860
+ from flashinfer.fused_moe import (
861
+ trtllm_fp4_block_scale_moe,
862
+ trtllm_fp4_block_scale_routed_moe,
863
+ )
864
+
865
+ from sglang.srt.layers.moe.token_dispatcher.standard import StandardCombineInput
866
+ from sglang.srt.layers.moe.topk import TopKOutputChecker
867
+ from sglang.srt.layers.moe.utils import RoutingMethodType
868
+
869
+ _SUPPORTED_FP4_ACTIVATIONS = {"silu", "relu2", "gelu"}
870
+ assert runner_config.activation in _SUPPORTED_FP4_ACTIVATIONS, (
871
+ f"Only {_SUPPORTED_FP4_ACTIVATIONS} are supported for FP4 MoE, "
872
+ f"got '{runner_config.activation}'."
873
+ )
874
+
875
+ hidden_states = dispatch_output.hidden_states
876
+ topk_output = dispatch_output.topk_output
877
+
878
+ # Quantize hidden states to FP4
879
+ if quant_info.use_per_token_activation:
880
+ from flashinfer import SfLayout, nvfp4_quantize
881
+
882
+ e4m3_max = 448.0
883
+ if (
884
+ envs.FLASHINFER_NVFP4_4OVER6.get()
885
+ and envs.FLASHINFER_NVFP4_4OVER6_E4M3_USE_256.get()
886
+ ):
887
+ e4m3_max = 256.0
888
+
889
+ hs_fp4_bytes, hs_sf_bytes, per_token_scale = nvfp4_quantize(
890
+ hidden_states,
891
+ 1.0 / (e4m3_max * 6.0),
892
+ sfLayout=SfLayout.layout_linear,
893
+ per_token_activation=True,
894
+ )
895
+
896
+ seq_len, hidden_size = hidden_states.shape
897
+ hs_fp4 = hs_fp4_bytes.reshape(seq_len, hidden_size // 2)
898
+ hs_scale_linear = hs_sf_bytes.view(torch.float8_e4m3fn).reshape(
899
+ seq_len, hidden_size // 16
900
+ )
901
+ else:
902
+ per_token_scale = None
903
+ hs_fp4, hs_scale_linear = quantize_hidden_states_fp4(
904
+ hidden_states, quant_info.w13_input_scale_quant
905
+ )
906
+ hs_scale = hs_scale_linear.view(torch.float8_e4m3fn).reshape(
907
+ *hs_scale_linear.shape[:-1], -1
908
+ )
909
+ activation_type = get_activation_type(
910
+ runner_config.activation, is_gated=runner_config.is_gated
911
+ )
912
+
913
+ # Build per-expert clamp-limit tensor from the per-layer scalar.
914
+ _clamp_val = runner_config.gemm1_clamp_limit
915
+ if _clamp_val is not None:
916
+ gemm1_clamp_limit = torch.full(
917
+ (quant_info.local_num_experts,),
918
+ _clamp_val,
919
+ dtype=torch.float32,
920
+ device=hs_fp4.device,
921
+ )
922
+ else:
923
+ gemm1_clamp_limit = None
924
+
925
+ # The TRTLLM FP4 kernels cannot run a parameterized swiglu: the
926
+ # gemm1_alpha/gemm1_beta tensors are ignored under ActivationType.Swiglu
927
+ # (verified bit-identical outputs with and without them), and
928
+ # ActivationType.SwigluBias is rejected by activationTypeToGatedActType.
929
+ # Fail fast instead of silently generating garbage.
930
+ if runner_config.gemm1_alpha is not None:
931
+ raise NotImplementedError(
932
+ "flashinfer_trtllm FP4 MoE does not support parameterized "
933
+ "(GPT-OSS-style) SwiGLU (gemm1_alpha is set); use "
934
+ "--moe-runner-backend flashinfer_cutlass instead."
935
+ )
936
+
937
+ num_tokens = hs_fp4.shape[0]
938
+ hidden_size = (
939
+ hs_fp4.shape[-1] * 2 if hs_fp4.dtype == torch.uint8 else hs_fp4.shape[-1]
940
+ )
941
+ _provided = _moe_output_buf.get()
942
+ _symm_required = is_allocation_symmetric()
943
+ if (
944
+ _provided is not None
945
+ and _provided.shape == (num_tokens, hidden_size)
946
+ and _provided.dtype == hidden_states.dtype
947
+ and _provided.device == hs_fp4.device
948
+ and (
949
+ not _symm_required
950
+ or not is_symmetric_memory_enabled()
951
+ or is_tensor_in_symmetric_mempool(_provided)
952
+ )
953
+ ):
954
+ symm_output = _provided
955
+ else:
956
+ with use_symmetric_memory(get_tp_group(), disabled=not _symm_required):
957
+ symm_output = torch.empty(
958
+ num_tokens, hidden_size, dtype=hidden_states.dtype, device=hs_fp4.device
959
+ )
960
+
961
+ # Fall back to routed path when topk was already materialized (e.g. sigmoid routing).
962
+ if not use_routed_topk and TopKOutputChecker.format_is_standard(topk_output):
963
+ use_routed_topk = True
964
+
965
+ if use_routed_topk:
966
+ assert TopKOutputChecker.format_is_standard(topk_output)
967
+
968
+ packed_topk_ids = _pack_topk_for_flashinfer_routed(
969
+ topk_output.topk_ids, topk_output.topk_weights
970
+ )
971
+ result = trtllm_fp4_block_scale_routed_moe(
972
+ topk_ids=packed_topk_ids,
973
+ routing_bias=None,
974
+ hidden_states=hs_fp4,
975
+ hidden_states_scale=hs_scale,
976
+ gemm1_weights=quant_info.w13_weight,
977
+ gemm1_weights_scale=quant_info.w13_weight_scale.view(torch.float8_e4m3fn),
978
+ gemm1_bias=None,
979
+ gemm1_alpha=None,
980
+ gemm1_beta=None,
981
+ gemm1_clamp_limit=gemm1_clamp_limit,
982
+ gemm2_weights=quant_info.w2_weight,
983
+ gemm2_weights_scale=quant_info.w2_weight_scale.view(torch.float8_e4m3fn),
984
+ gemm2_bias=None,
985
+ output1_scale_scalar=quant_info.g1_scale_c,
986
+ output1_scale_gate_scalar=quant_info.g1_alphas,
987
+ output2_scale_scalar=quant_info.g2_alphas,
988
+ per_token_scale=per_token_scale,
989
+ num_experts=quant_info.global_num_experts,
990
+ top_k=topk_output.topk_ids.shape[1],
991
+ n_group=0,
992
+ topk_group=0,
993
+ intermediate_size=quant_info.intermediate_size_per_partition,
994
+ local_expert_offset=quant_info.local_expert_offset,
995
+ local_num_experts=quant_info.local_num_experts,
996
+ routed_scaling_factor=None,
997
+ routing_method_type=1, # Unused, but must be 1 to pass validation.
998
+ do_finalize=True,
999
+ activation_type=activation_type,
1000
+ tune_max_num_tokens=next_power_of_2(hs_fp4.shape[0]),
1001
+ output=symm_output,
1002
+ )[0]
1003
+ else:
1004
+ assert TopKOutputChecker.format_is_bypassed(topk_output)
1005
+
1006
+ router_logits = topk_output.router_logits
1007
+ topk_config = topk_output.topk_config
1008
+ routing_method_type = quant_info.routing_method_type
1009
+
1010
+ correction_bias = (
1011
+ None
1012
+ if topk_config.correction_bias is None
1013
+ else topk_config.correction_bias.to(hidden_states.dtype)
1014
+ )
1015
+ result = trtllm_fp4_block_scale_moe(
1016
+ routing_logits=router_logits,
1017
+ routing_bias=correction_bias,
1018
+ hidden_states=hs_fp4,
1019
+ hidden_states_scale=hs_scale,
1020
+ gemm1_weights=quant_info.w13_weight,
1021
+ gemm1_weights_scale=quant_info.w13_weight_scale.view(torch.float8_e4m3fn),
1022
+ gemm1_bias=None,
1023
+ gemm1_alpha=None,
1024
+ gemm1_beta=None,
1025
+ gemm1_clamp_limit=gemm1_clamp_limit,
1026
+ gemm2_weights=quant_info.w2_weight,
1027
+ gemm2_weights_scale=quant_info.w2_weight_scale.view(torch.float8_e4m3fn),
1028
+ gemm2_bias=None,
1029
+ output1_scale_scalar=quant_info.g1_scale_c,
1030
+ output1_scale_gate_scalar=quant_info.g1_alphas,
1031
+ output2_scale_scalar=quant_info.g2_alphas,
1032
+ per_token_scale=per_token_scale,
1033
+ num_experts=quant_info.global_num_experts,
1034
+ top_k=topk_config.top_k,
1035
+ n_group=topk_config.num_expert_group,
1036
+ topk_group=topk_config.topk_group,
1037
+ intermediate_size=quant_info.intermediate_size_per_partition,
1038
+ local_expert_offset=quant_info.local_expert_offset,
1039
+ local_num_experts=quant_info.local_num_experts,
1040
+ routed_scaling_factor=runner_config.routed_scaling_factor,
1041
+ routing_method_type=(
1042
+ routing_method_type
1043
+ if routing_method_type is not None
1044
+ else RoutingMethodType.Default
1045
+ ),
1046
+ do_finalize=True,
1047
+ activation_type=activation_type,
1048
+ tune_max_num_tokens=next_power_of_2(hs_fp4.shape[0]),
1049
+ output=symm_output,
1050
+ )[0]
1051
+
1052
+ return StandardCombineInput(hidden_states=result)
1053
+
1054
+
1055
+ @dataclass
1056
+ class FlashInferTrtllmBf16MoeQuantInfo(MoeQuantInfo):
1057
+ """Quantization payload consumed by FlashInfer TRT-LLM BF16 MoE kernels."""
1058
+
1059
+ gemm1_weights: torch.Tensor
1060
+ gemm2_weights: torch.Tensor
1061
+
1062
+ # Expert-parallel metadata
1063
+ global_num_experts: int
1064
+ local_expert_offset: int
1065
+
1066
+
1067
+ def fused_experts_none_to_flashinfer_trtllm_bf16(
1068
+ dispatch_output: StandardDispatchOutput,
1069
+ quant_info: FlashInferTrtllmBf16MoeQuantInfo,
1070
+ runner_config: MoeRunnerConfig,
1071
+ use_routed_topk: bool = False,
1072
+ ) -> StandardCombineInput:
1073
+ # lazy import
1074
+ from sglang.srt.layers.moe.token_dispatcher.standard import StandardCombineInput
1075
+ from sglang.srt.layers.moe.topk import TopKOutputChecker
1076
+ from sglang.srt.layers.moe.utils import RoutingMethodType
1077
+
1078
+ trtllm_bf16_routed_moe = None
1079
+ trtllm_bf16_moe = None
1080
+ if use_routed_topk:
1081
+ try:
1082
+ from flashinfer.fused_moe import trtllm_bf16_routed_moe
1083
+ except ImportError as e:
1084
+ raise ImportError(
1085
+ "Can't import trtllm_bf16_routed_moe from flashinfer. "
1086
+ "Please check flashinfer version to use bf16 with flashinfer_trtllm_routed backend."
1087
+ ) from e
1088
+ else:
1089
+ try:
1090
+ from flashinfer.fused_moe import trtllm_bf16_moe
1091
+ except ImportError as e:
1092
+ raise ImportError(
1093
+ "Can't import trtllm_bf16_moe from flashinfer. "
1094
+ "Please check flashinfer version to use bf16 with flashinfer_trtllm backend."
1095
+ ) from e
1096
+
1097
+ _SUPPORTED_BF16_ACTIVATIONS = {"silu", "relu2"}
1098
+ assert runner_config.activation in _SUPPORTED_BF16_ACTIVATIONS, (
1099
+ f"Only {_SUPPORTED_BF16_ACTIVATIONS} are supported for flashinfer trtllm bf16 moe, "
1100
+ f"got '{runner_config.activation}'."
1101
+ )
1102
+ if not use_routed_topk:
1103
+ assert (
1104
+ dispatch_output.topk_output.topk_config.renormalize
1105
+ ), "Renormalize is required for flashinfer trtllm moe"
1106
+ assert (
1107
+ runner_config.num_fused_shared_experts == 0
1108
+ ), "Fused shared experts are not supported for flashinfer trtllm moe"
1109
+ activation_type = get_activation_type(
1110
+ runner_config.activation, is_gated=runner_config.is_gated
1111
+ )
1112
+
1113
+ hidden_states = dispatch_output.hidden_states
1114
+ topk_output = dispatch_output.topk_output
1115
+
1116
+ with use_symmetric_memory(get_tp_group(), disabled=not is_allocation_symmetric()):
1117
+ if use_routed_topk:
1118
+ assert (
1119
+ runner_config.top_k is not None
1120
+ ), "runner_config.top_k is required for flashinfer_trtllm_routed."
1121
+ assert TopKOutputChecker.format_is_standard(topk_output)
1122
+ routing_method_type = runner_config.routing_method_type
1123
+ if routing_method_type is None:
1124
+ routing_method_type = RoutingMethodType.Default
1125
+ elif routing_method_type == RoutingMethodType.DeepSeekV3:
1126
+ routing_method_type = RoutingMethodType.TopK
1127
+
1128
+ packed_topk_ids = _pack_topk_for_flashinfer_routed(
1129
+ topk_ids=topk_output.topk_ids,
1130
+ topk_weights=topk_output.topk_weights,
1131
+ )
1132
+ final_hidden_states = trtllm_bf16_routed_moe(
1133
+ topk_ids=packed_topk_ids,
1134
+ hidden_states=hidden_states,
1135
+ gemm1_weights=quant_info.gemm1_weights,
1136
+ gemm2_weights=quant_info.gemm2_weights,
1137
+ num_experts=quant_info.global_num_experts,
1138
+ top_k=runner_config.top_k,
1139
+ n_group=None,
1140
+ topk_group=None,
1141
+ intermediate_size=runner_config.intermediate_size_per_partition,
1142
+ local_expert_offset=quant_info.local_expert_offset,
1143
+ local_num_experts=runner_config.num_local_experts,
1144
+ routing_method_type=routing_method_type,
1145
+ routed_scaling_factor=(
1146
+ runner_config.routed_scaling_factor
1147
+ if runner_config.routed_scaling_factor is not None
1148
+ else 1.0
1149
+ ),
1150
+ tune_max_num_tokens=next_power_of_2(hidden_states.shape[0]),
1151
+ activation_type=activation_type,
1152
+ )
1153
+ else:
1154
+ assert TopKOutputChecker.format_is_bypassed(topk_output)
1155
+ topk_config = topk_output.topk_config
1156
+
1157
+ # Call the fused kernel
1158
+ final_hidden_states = trtllm_bf16_moe(
1159
+ routing_logits=topk_output.router_logits,
1160
+ routing_bias=topk_config.correction_bias,
1161
+ hidden_states=hidden_states,
1162
+ gemm1_weights=quant_info.gemm1_weights,
1163
+ gemm2_weights=quant_info.gemm2_weights,
1164
+ num_experts=quant_info.global_num_experts,
1165
+ top_k=topk_config.top_k,
1166
+ n_group=topk_config.num_expert_group,
1167
+ topk_group=topk_config.topk_group,
1168
+ intermediate_size=runner_config.intermediate_size_per_partition,
1169
+ local_expert_offset=quant_info.local_expert_offset,
1170
+ local_num_experts=runner_config.num_local_experts,
1171
+ routing_method_type=runner_config.routing_method_type,
1172
+ routed_scaling_factor=runner_config.routed_scaling_factor,
1173
+ tune_max_num_tokens=next_power_of_2(hidden_states.shape[0]),
1174
+ activation_type=activation_type,
1175
+ )
1176
+
1177
+ return StandardCombineInput(hidden_states=final_hidden_states)
1178
+
1179
+
1180
+ @register_fused_func("none", "flashinfer_trtllm")
1181
+ def fused_experts_none_to_flashinfer_trtllm(
1182
+ dispatch_output: StandardDispatchOutput,
1183
+ quant_info: MoeQuantInfo,
1184
+ runner_config: MoeRunnerConfig,
1185
+ ) -> StandardCombineInput:
1186
+ """Dispatch to FP8 or FP4 FlashInfer TRT-LLM MoE based on quant_info type."""
1187
+ if isinstance(quant_info, FlashInferTrtllmFp4MoeQuantInfo):
1188
+ return fused_experts_none_to_flashinfer_trtllm_fp4(
1189
+ dispatch_output, quant_info, runner_config
1190
+ )
1191
+ if isinstance(quant_info, FlashInferTrtllmFp8MoeQuantInfo):
1192
+ return fused_experts_none_to_flashinfer_trtllm_fp8(
1193
+ dispatch_output, quant_info, runner_config
1194
+ )
1195
+ if isinstance(quant_info, FlashInferTrtllmBf16MoeQuantInfo):
1196
+ return fused_experts_none_to_flashinfer_trtllm_bf16(
1197
+ dispatch_output, quant_info, runner_config
1198
+ )
1199
+ raise TypeError(
1200
+ f"Unexpected quant_info type for flashinfer_trtllm: {type(quant_info)}"
1201
+ )
1202
+
1203
+
1204
+ @register_fused_func("none", "flashinfer_trtllm_routed")
1205
+ def fused_experts_none_to_flashinfer_trtllm_routed(
1206
+ dispatch_output: StandardDispatchOutput,
1207
+ quant_info: MoeQuantInfo,
1208
+ runner_config: MoeRunnerConfig,
1209
+ ) -> StandardCombineInput:
1210
+ if isinstance(quant_info, FlashInferTrtllmFp4MoeQuantInfo):
1211
+ return fused_experts_none_to_flashinfer_trtllm_fp4(
1212
+ dispatch_output,
1213
+ quant_info,
1214
+ runner_config,
1215
+ use_routed_topk=True,
1216
+ )
1217
+ if isinstance(quant_info, FlashInferTrtllmFp8MoeQuantInfo):
1218
+ return fused_experts_none_to_flashinfer_trtllm_fp8(
1219
+ dispatch_output,
1220
+ quant_info,
1221
+ runner_config,
1222
+ use_routed_topk=True,
1223
+ )
1224
+ if isinstance(quant_info, FlashInferTrtllmBf16MoeQuantInfo):
1225
+ return fused_experts_none_to_flashinfer_trtllm_bf16(
1226
+ dispatch_output,
1227
+ quant_info,
1228
+ runner_config,
1229
+ use_routed_topk=True,
1230
+ )
1231
+ raise TypeError(
1232
+ f"Unexpected quant_info type for flashinfer_trtllm_routed: {type(quant_info)}"
1233
+ )
1234
+
1235
+
1236
+ # Register the experimental experimental_sgl_trtllm MoE fused-func (MoeRunner needs it at
1237
+ # build time even for LoRA); gated by the master switch so the upstream path is untouched.
1238
+ if _SGLANG_EXPERIMENTAL_LORA_OPTI:
1239
+ from sglang.srt.lora.trtllm_lora_temp import sgl_backend # noqa: E402,F401
sglang_patch/modelopt_quant.py ADDED
The diff for this file is too large to render. See raw diff
 
special_tokens_map.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "]~b]",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "[e~[",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ }
16
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "200000": {
5
+ "content": "]!p~[",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "200001": {
13
+ "content": "<fim_prefix>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "200002": {
21
+ "content": "<fim_middle>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ },
28
+ "200003": {
29
+ "content": "<fim_suffix>",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": true
35
+ },
36
+ "200004": {
37
+ "content": "<fim_pad>",
38
+ "lstrip": false,
39
+ "normalized": false,
40
+ "rstrip": false,
41
+ "single_word": false,
42
+ "special": true
43
+ },
44
+ "200005": {
45
+ "content": "<reponame>",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false,
50
+ "special": true
51
+ },
52
+ "200006": {
53
+ "content": "<filename>",
54
+ "lstrip": false,
55
+ "normalized": false,
56
+ "rstrip": false,
57
+ "single_word": false,
58
+ "special": true
59
+ },
60
+ "200007": {
61
+ "content": "<gh_stars>",
62
+ "lstrip": false,
63
+ "normalized": false,
64
+ "rstrip": false,
65
+ "single_word": false,
66
+ "special": true
67
+ },
68
+ "200008": {
69
+ "content": "<issue_start>",
70
+ "lstrip": false,
71
+ "normalized": false,
72
+ "rstrip": false,
73
+ "single_word": false,
74
+ "special": true
75
+ },
76
+ "200009": {
77
+ "content": "<issue_comment>",
78
+ "lstrip": false,
79
+ "normalized": false,
80
+ "rstrip": false,
81
+ "single_word": false,
82
+ "special": true
83
+ },
84
+ "200010": {
85
+ "content": "<issue_closed>",
86
+ "lstrip": false,
87
+ "normalized": false,
88
+ "rstrip": false,
89
+ "single_word": false,
90
+ "special": true
91
+ },
92
+ "200011": {
93
+ "content": "<jupyter_start>",
94
+ "lstrip": false,
95
+ "normalized": false,
96
+ "rstrip": false,
97
+ "single_word": false,
98
+ "special": true
99
+ },
100
+ "200012": {
101
+ "content": "<jupyter_text>",
102
+ "lstrip": false,
103
+ "normalized": false,
104
+ "rstrip": false,
105
+ "single_word": false,
106
+ "special": true
107
+ },
108
+ "200013": {
109
+ "content": "<jupyter_code>",
110
+ "lstrip": false,
111
+ "normalized": false,
112
+ "rstrip": false,
113
+ "single_word": false,
114
+ "special": true
115
+ },
116
+ "200014": {
117
+ "content": "<jupyter_output>",
118
+ "lstrip": false,
119
+ "normalized": false,
120
+ "rstrip": false,
121
+ "single_word": false,
122
+ "special": true
123
+ },
124
+ "200015": {
125
+ "content": "<empty_output>",
126
+ "lstrip": false,
127
+ "normalized": false,
128
+ "rstrip": false,
129
+ "single_word": false,
130
+ "special": true
131
+ },
132
+ "200016": {
133
+ "content": "<commit_before>",
134
+ "lstrip": false,
135
+ "normalized": false,
136
+ "rstrip": false,
137
+ "single_word": false,
138
+ "special": true
139
+ },
140
+ "200017": {
141
+ "content": "<commit_msg>",
142
+ "lstrip": false,
143
+ "normalized": false,
144
+ "rstrip": false,
145
+ "single_word": false,
146
+ "special": true
147
+ },
148
+ "200018": {
149
+ "content": "<commit_after>",
150
+ "lstrip": false,
151
+ "normalized": false,
152
+ "rstrip": false,
153
+ "single_word": false,
154
+ "special": true
155
+ },
156
+ "200019": {
157
+ "content": "]~b]",
158
+ "lstrip": false,
159
+ "normalized": false,
160
+ "rstrip": false,
161
+ "single_word": false,
162
+ "special": true
163
+ },
164
+ "200020": {
165
+ "content": "[e~[",
166
+ "lstrip": false,
167
+ "normalized": false,
168
+ "rstrip": false,
169
+ "single_word": false,
170
+ "special": true
171
+ },
172
+ "200021": {
173
+ "content": "]!d~[",
174
+ "lstrip": false,
175
+ "normalized": false,
176
+ "rstrip": false,
177
+ "single_word": false,
178
+ "special": true
179
+ },
180
+ "200022": {
181
+ "content": "<function_call>",
182
+ "lstrip": false,
183
+ "normalized": false,
184
+ "rstrip": false,
185
+ "single_word": false,
186
+ "special": true
187
+ },
188
+ "200023": {
189
+ "content": "<code_interpreter>",
190
+ "lstrip": false,
191
+ "normalized": false,
192
+ "rstrip": false,
193
+ "single_word": false,
194
+ "special": true
195
+ },
196
+ "200024": {
197
+ "content": "]<]speech[>[",
198
+ "lstrip": false,
199
+ "normalized": false,
200
+ "rstrip": false,
201
+ "single_word": false,
202
+ "special": true
203
+ },
204
+ "200025": {
205
+ "content": "]<]image[>[",
206
+ "lstrip": false,
207
+ "normalized": false,
208
+ "rstrip": false,
209
+ "single_word": false,
210
+ "special": true
211
+ },
212
+ "200026": {
213
+ "content": "]<]video[>[",
214
+ "lstrip": false,
215
+ "normalized": false,
216
+ "rstrip": false,
217
+ "single_word": false,
218
+ "special": true
219
+ },
220
+ "200027": {
221
+ "content": "]<]start of speech[>[",
222
+ "lstrip": false,
223
+ "normalized": false,
224
+ "rstrip": false,
225
+ "single_word": false,
226
+ "special": true
227
+ },
228
+ "200028": {
229
+ "content": "]<]end of speech[>[",
230
+ "lstrip": false,
231
+ "normalized": false,
232
+ "rstrip": false,
233
+ "single_word": false,
234
+ "special": true
235
+ },
236
+ "200029": {
237
+ "content": "]<]start of image[>[",
238
+ "lstrip": false,
239
+ "normalized": false,
240
+ "rstrip": false,
241
+ "single_word": false,
242
+ "special": true
243
+ },
244
+ "200030": {
245
+ "content": "]<]end of image[>[",
246
+ "lstrip": false,
247
+ "normalized": false,
248
+ "rstrip": false,
249
+ "single_word": false,
250
+ "special": true
251
+ },
252
+ "200031": {
253
+ "content": "]<]start of video[>[",
254
+ "lstrip": false,
255
+ "normalized": false,
256
+ "rstrip": false,
257
+ "single_word": false,
258
+ "special": true
259
+ },
260
+ "200032": {
261
+ "content": "]<]end of video[>[",
262
+ "lstrip": false,
263
+ "normalized": false,
264
+ "rstrip": false,
265
+ "single_word": false,
266
+ "special": true
267
+ },
268
+ "200033": {
269
+ "content": "]<]vision pad[>[",
270
+ "lstrip": false,
271
+ "normalized": false,
272
+ "rstrip": false,
273
+ "single_word": false,
274
+ "special": true
275
+ },
276
+ "200034": {
277
+ "content": "]~!b[",
278
+ "lstrip": false,
279
+ "normalized": false,
280
+ "rstrip": false,
281
+ "single_word": false,
282
+ "special": true
283
+ },
284
+ "200035": {
285
+ "content": "<jupyter_error>",
286
+ "lstrip": false,
287
+ "normalized": false,
288
+ "rstrip": false,
289
+ "single_word": false,
290
+ "special": true
291
+ },
292
+ "200036": {
293
+ "content": "<add_file>",
294
+ "lstrip": false,
295
+ "normalized": false,
296
+ "rstrip": false,
297
+ "single_word": false,
298
+ "special": true
299
+ },
300
+ "200037": {
301
+ "content": "<delete_file>",
302
+ "lstrip": false,
303
+ "normalized": false,
304
+ "rstrip": false,
305
+ "single_word": false,
306
+ "special": true
307
+ },
308
+ "200038": {
309
+ "content": "<rename_file>",
310
+ "lstrip": false,
311
+ "normalized": false,
312
+ "rstrip": false,
313
+ "single_word": false,
314
+ "special": true
315
+ },
316
+ "200039": {
317
+ "content": "<edit_file>",
318
+ "lstrip": false,
319
+ "normalized": false,
320
+ "rstrip": false,
321
+ "single_word": false,
322
+ "special": true
323
+ },
324
+ "200040": {
325
+ "content": "<commit_message>",
326
+ "lstrip": false,
327
+ "normalized": false,
328
+ "rstrip": false,
329
+ "single_word": false,
330
+ "special": true
331
+ },
332
+ "200041": {
333
+ "content": "<empty_source_file>",
334
+ "lstrip": false,
335
+ "normalized": false,
336
+ "rstrip": false,
337
+ "single_word": false,
338
+ "special": true
339
+ },
340
+ "200042": {
341
+ "content": "<repo_struct>",
342
+ "lstrip": false,
343
+ "normalized": false,
344
+ "rstrip": false,
345
+ "single_word": false,
346
+ "special": true
347
+ },
348
+ "200043": {
349
+ "content": "<code_context>",
350
+ "lstrip": false,
351
+ "normalized": false,
352
+ "rstrip": false,
353
+ "single_word": false,
354
+ "special": true
355
+ },
356
+ "200044": {
357
+ "content": "<file_content>",
358
+ "lstrip": false,
359
+ "normalized": false,
360
+ "rstrip": false,
361
+ "single_word": false,
362
+ "special": true
363
+ },
364
+ "200045": {
365
+ "content": "<source_files>",
366
+ "lstrip": false,
367
+ "normalized": false,
368
+ "rstrip": false,
369
+ "single_word": false,
370
+ "special": true
371
+ },
372
+ "200046": {
373
+ "content": "<pr_start>",
374
+ "lstrip": false,
375
+ "normalized": false,
376
+ "rstrip": false,
377
+ "single_word": false,
378
+ "special": true
379
+ },
380
+ "200047": {
381
+ "content": "<review_comment>",
382
+ "lstrip": false,
383
+ "normalized": false,
384
+ "rstrip": false,
385
+ "single_word": false,
386
+ "special": true
387
+ },
388
+ "200048": {
389
+ "content": "<filepath>",
390
+ "lstrip": false,
391
+ "normalized": false,
392
+ "rstrip": false,
393
+ "single_word": false,
394
+ "special": true
395
+ },
396
+ "200049": {
397
+ "content": "<file_sep>",
398
+ "lstrip": false,
399
+ "normalized": false,
400
+ "rstrip": false,
401
+ "single_word": false,
402
+ "special": true
403
+ },
404
+ "200050": {
405
+ "content": "<think>",
406
+ "lstrip": false,
407
+ "normalized": false,
408
+ "rstrip": false,
409
+ "single_word": false,
410
+ "special": false
411
+ },
412
+ "200051": {
413
+ "content": "</think>",
414
+ "lstrip": false,
415
+ "normalized": false,
416
+ "rstrip": false,
417
+ "single_word": false,
418
+ "special": false
419
+ },
420
+ "200052": {
421
+ "content": "<tool_call>",
422
+ "lstrip": false,
423
+ "normalized": false,
424
+ "rstrip": false,
425
+ "single_word": false,
426
+ "special": false
427
+ },
428
+ "200053": {
429
+ "content": "</tool_call>",
430
+ "lstrip": false,
431
+ "normalized": false,
432
+ "rstrip": false,
433
+ "single_word": false,
434
+ "special": false
435
+ },
436
+ "200054": {
437
+ "content": "]<]frame[>[",
438
+ "lstrip": false,
439
+ "normalized": false,
440
+ "rstrip": false,
441
+ "single_word": false,
442
+ "special": true
443
+ },
444
+ "200055": {
445
+ "content": "]<]start of frame[>[",
446
+ "lstrip": false,
447
+ "normalized": false,
448
+ "rstrip": false,
449
+ "single_word": false,
450
+ "special": true
451
+ },
452
+ "200056": {
453
+ "content": "]<]end of frame[>[",
454
+ "lstrip": false,
455
+ "normalized": false,
456
+ "rstrip": false,
457
+ "single_word": false,
458
+ "special": true
459
+ },
460
+ "200057": {
461
+ "content": "<|content_altered_placeholder|>",
462
+ "lstrip": false,
463
+ "normalized": false,
464
+ "rstrip": false,
465
+ "single_word": false,
466
+ "special": true
467
+ },
468
+ "200058": {
469
+ "content": "]<]minimax[>[",
470
+ "lstrip": false,
471
+ "normalized": false,
472
+ "rstrip": false,
473
+ "single_word": false,
474
+ "special": false
475
+ },
476
+ "200059": {
477
+ "content": "<mm:think>",
478
+ "lstrip": false,
479
+ "normalized": false,
480
+ "rstrip": false,
481
+ "single_word": false,
482
+ "special": false
483
+ },
484
+ "200060": {
485
+ "content": "</mm:think>",
486
+ "lstrip": false,
487
+ "normalized": false,
488
+ "rstrip": false,
489
+ "single_word": false,
490
+ "special": false
491
+ }
492
+ },
493
+ "bos_token": "]~b]",
494
+ "clean_up_tokenization_spaces": false,
495
+ "eos_token": "[e~[",
496
+ "pad_token": "]!p~[",
497
+ "model_max_length": 40960000,
498
+ "tokenizer_class": "PreTrainedTokenizerFast",
499
+ "unk_token": "[e~["
500
+ }
501
+
video_processor.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023-2024 SGLang Team
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ """
4
+ MiniMax VL family HuggingFace-compatible VideoProcessor.
5
+ """
6
+
7
+ import math
8
+ from typing import List, Optional, Tuple, Union
9
+
10
+ import torch
11
+ import torchvision
12
+ from torchvision.transforms import InterpolationMode
13
+ from transformers import BatchFeature
14
+ from transformers.image_utils import PILImageResampling, SizeDict
15
+ from transformers.processing_utils import (
16
+ Unpack,
17
+ VideosKwargs,
18
+ )
19
+ from transformers.utils import TensorType
20
+ from transformers.video_processing_utils import BaseVideoProcessor
21
+ from transformers.video_utils import group_videos_by_shape, reorder_videos
22
+
23
+ MAX_RATIO = 200
24
+
25
+
26
+ def round_by_factor(number: int, factor: int) -> int:
27
+ return round(number / factor) * factor
28
+
29
+
30
+ def ceil_by_factor(number: int, factor: int) -> int:
31
+ return math.ceil(number / factor) * factor
32
+
33
+
34
+ def floor_by_factor(number: int, factor: int) -> int:
35
+ return math.floor(number / factor) * factor
36
+
37
+
38
+ def smart_resize(
39
+ height: int,
40
+ width: int,
41
+ factor: int = 28,
42
+ min_pixels: int = 4 * 28 * 28,
43
+ max_pixels: int = 451584,
44
+ ) -> tuple[int, int]:
45
+ if max(height, width) / min(height, width) > MAX_RATIO:
46
+ raise ValueError(
47
+ f"absolute aspect ratio must be smaller than {MAX_RATIO}, "
48
+ f"got {max(height, width) / min(height, width)}"
49
+ )
50
+ h_bar = max(factor, round_by_factor(height, factor))
51
+ w_bar = max(factor, round_by_factor(width, factor))
52
+ if h_bar * w_bar > max_pixels:
53
+ beta = math.sqrt((height * width) / max_pixels)
54
+ h_bar = floor_by_factor(height / beta, factor)
55
+ w_bar = floor_by_factor(width / beta, factor)
56
+ elif h_bar * w_bar < min_pixels:
57
+ beta = math.sqrt(min_pixels / (height * width))
58
+ h_bar = ceil_by_factor(height * beta, factor)
59
+ w_bar = ceil_by_factor(width * beta, factor)
60
+ return h_bar, w_bar
61
+
62
+
63
+ class MiniMaxM3VLVideoProcessorKwargs(VideosKwargs, total=False):
64
+ patch_size: int
65
+ temporal_patch_size: int
66
+ merge_size: int
67
+ min_pixels: int
68
+ max_pixels: int
69
+ total_pixels: int
70
+ min_frames: int
71
+ max_frames: int
72
+ fps: float | int
73
+
74
+
75
+ class MiniMaxM3VLVideoProcessor(BaseVideoProcessor):
76
+ do_resize = True
77
+ resample = PILImageResampling.BICUBIC
78
+ size = {"height": 672, "width": 672}
79
+ default_to_square = False
80
+ do_rescale = True
81
+ rescale_factor = 1 / 255
82
+ do_normalize = True
83
+ image_mean = [0.48145466, 0.4578275, 0.40821073]
84
+ image_std = [0.26862954, 0.26130258, 0.27577711]
85
+ do_convert_rgb = True
86
+ do_sample_frames = False
87
+ patch_size = 14
88
+ temporal_patch_size = 2
89
+ merge_size = 2
90
+ min_pixels = 4 * 28 * 28
91
+ max_pixels = 768 * 28 * 28 # 602,112
92
+ total_pixels = int(64000 * 28 * 28 * 0.9) # ~45M, ~64k tokens budget
93
+ fps = 1.0
94
+ min_frames = 4
95
+ max_frames = 768
96
+ valid_kwargs = MiniMaxM3VLVideoProcessorKwargs
97
+ model_input_names = ["pixel_values_videos", "video_grid_thw"]
98
+
99
+ def __init__(self, **kwargs: Unpack[MiniMaxM3VLVideoProcessorKwargs]):
100
+ super().__init__(**kwargs)
101
+
102
+ def _preprocess(
103
+ self,
104
+ videos: List[torch.Tensor],
105
+ do_convert_rgb: bool,
106
+ do_resize: bool,
107
+ size: SizeDict,
108
+ resample: PILImageResampling | InterpolationMode | int | None,
109
+ do_rescale: bool,
110
+ rescale_factor: float,
111
+ do_normalize: bool,
112
+ image_mean: float | List[float] | None,
113
+ image_std: float | List[float] | None,
114
+ patch_size: int,
115
+ temporal_patch_size: int,
116
+ merge_size: int,
117
+ min_pixels: int,
118
+ max_pixels: int,
119
+ return_tensors: str | TensorType | None = None,
120
+ **kwargs,
121
+ ) -> BatchFeature:
122
+ grouped_videos, grouped_videos_index = group_videos_by_shape(videos)
123
+ resized_videos_grouped = {}
124
+ factor = patch_size * merge_size
125
+ for shape, stacked_videos in grouped_videos.items():
126
+ batch_size, num_frames, channels, height, width = stacked_videos.shape
127
+ resized_height, resized_width = height, width
128
+ if do_resize:
129
+ resized_height, resized_width = smart_resize(
130
+ height, width, factor=factor,
131
+ min_pixels=min_pixels, max_pixels=max_pixels,
132
+ )
133
+ stacked_videos = stacked_videos.view(
134
+ batch_size * num_frames, channels, height, width
135
+ )
136
+ stacked_videos = self.resize(
137
+ stacked_videos,
138
+ size=SizeDict(height=resized_height, width=resized_width),
139
+ resample=resample,
140
+ )
141
+ stacked_videos = stacked_videos.view(
142
+ batch_size,
143
+ num_frames,
144
+ channels,
145
+ resized_height,
146
+ resized_width,
147
+ )
148
+ resized_videos_grouped[shape] = stacked_videos
149
+ resized_videos = reorder_videos(resized_videos_grouped, grouped_videos_index)
150
+
151
+ grouped_videos, grouped_videos_index = group_videos_by_shape(resized_videos)
152
+ processed_videos_grouped = {}
153
+ processed_grids = {}
154
+ for shape, stacked_videos in grouped_videos.items():
155
+ resized_height, resized_width = stacked_videos.shape[-2:]
156
+ patches = self.rescale_and_normalize(
157
+ stacked_videos,
158
+ do_rescale,
159
+ rescale_factor,
160
+ do_normalize,
161
+ image_mean,
162
+ image_std,
163
+ )
164
+
165
+ if pad := -patches.shape[1] % temporal_patch_size:
166
+ repeats = patches[:, -1:].expand(-1, pad, -1, -1, -1)
167
+ patches = torch.cat([patches, repeats], dim=1)
168
+
169
+ batch_size, grid_t, channels = patches.shape[:3]
170
+ grid_t = grid_t // temporal_patch_size
171
+ grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
172
+
173
+ patches = patches.view(
174
+ batch_size,
175
+ grid_t,
176
+ temporal_patch_size,
177
+ channels,
178
+ grid_h // merge_size,
179
+ merge_size,
180
+ patch_size,
181
+ grid_w // merge_size,
182
+ merge_size,
183
+ patch_size,
184
+ )
185
+ patches = patches.permute(0, 1, 4, 7, 5, 8, 3, 2, 6, 9)
186
+ flatten_patches = patches.reshape(
187
+ batch_size,
188
+ grid_t * grid_h * grid_w,
189
+ channels * temporal_patch_size * patch_size * patch_size,
190
+ )
191
+
192
+ processed_videos_grouped[shape] = flatten_patches
193
+ processed_grids[shape] = [[grid_t, grid_h, grid_w]] * batch_size
194
+
195
+ processed_videos = reorder_videos(
196
+ processed_videos_grouped, grouped_videos_index
197
+ )
198
+ processed_grids = reorder_videos(processed_grids, grouped_videos_index)
199
+ pixel_values_videos = torch.cat(processed_videos, dim=0)
200
+ video_grid_thw = torch.tensor(processed_grids, dtype=torch.long)
201
+
202
+ return BatchFeature(
203
+ data={
204
+ "pixel_values_videos": pixel_values_videos,
205
+ "video_grid_thw": video_grid_thw,
206
+ },
207
+ tensor_type=return_tensors,
208
+ )
vocab.json ADDED
The diff for this file is too large to render. See raw diff