Coder40-95 cyijun2k commited on
Commit
963e33f
·
0 Parent(s):

Duplicate from cyijun2k/glm-5.3-flash-tiny-random-nvfp4

Browse files

Co-authored-by: Chen Yijun <cyijun2k@users.noreply.huggingface.co>

.gitattributes ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ model.safetensors.index.json filter=lfs diff=lfs merge=lfs -text
37
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
BUILD_INFO.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "base_model": "LibertAIDAI/GLM-5.3-Flash-NVFP4",
3
+ "base_revision": "9e0d74e3cef17f634e84fb8e2223707e02616290",
4
+ "builder_seed": 42,
5
+ "expert_payload_seed": 4242,
6
+ "model_sha256": "d0f8a670c6d96be8984db205a4bfb32c947f09182d6b327fab8d4f1088b66810",
7
+ "model_size_bytes": 1010842392,
8
+ "tensor_count": 5342,
9
+ "nvfp4_projection_count": 1728,
10
+ "fixture_profile": {
11
+ "hidden_size": 256,
12
+ "base_layers": 4,
13
+ "mtp_layers": 1,
14
+ "vocab_size": 154880,
15
+ "max_position_embeddings": 8192
16
+ },
17
+ "notes": "Random debug fixture; routed experts use ModelOpt-compatible NVFP4 weight-only tensors."
18
+ }
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Z.AI Co., Ltd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ base_model: LibertAIDAI/GLM-5.3-Flash-NVFP4
4
+ library_name: transformers
5
+ pipeline_tag: image-text-to-text
6
+ tags:
7
+ - glm5-next
8
+ - glm-5.3-flash
9
+ - tiny-random
10
+ - nvfp4
11
+ - vllm
12
+ - gb10
13
+ ---
14
+
15
+ # GLM-5.3 Flash tiny-random NVFP4 fixture
16
+
17
+ This is a deterministic, randomly initialized test checkpoint derived from the
18
+ configuration and tensor schema of
19
+ [`LibertAIDAI/GLM-5.3-Flash-NVFP4`](https://huggingface.co/LibertAIDAI/GLM-5.3-Flash-NVFP4),
20
+ pinned at revision `9e0d74e3cef17f634e84fb8e2223707e02616290`.
21
+
22
+ It is intended to reproduce vLLM loader, cache-layout, sparse-attention, NVFP4
23
+ MoE, and MTP compatibility problems on GB10/SM121 without loading the full
24
+ checkpoint. It is **not** useful for language or vision tasks, and its output is
25
+ deliberately meaningless.
26
+
27
+ The companion GB10 runtime and source patch live at
28
+ [`cyijun/glm-5.3-flash-nvfp4-gb10`](https://github.com/cyijun/glm-5.3-flash-nvfp4-gb10).
29
+
30
+ ## What remains architecture-faithful
31
+
32
+ The fixture keeps dimensions that select execution branches, kernels, packed
33
+ weight layouts, or cache ABIs:
34
+
35
+ | Contract | Fixture and target value |
36
+ | --- | ---: |
37
+ | layer pattern | 3 KDA + 1 sparse MLA |
38
+ | attention / KV heads | 64 / 64 |
39
+ | Q LoRA / KV LoRA rank | 1536 / 512 |
40
+ | QK NoPE / RoPE dimension | 256 / 0 |
41
+ | V head dimension | 256 |
42
+ | KDA heads / head dimension / convolution | 64 / 128 / 4 |
43
+ | index heads / head dimension | 32 / 128 |
44
+ | index top-k / k-pool | 2048 / 4 |
45
+ | routed / selected / shared experts | 288 / 8 / 1 |
46
+ | MoE intermediate size | 2048 |
47
+ | dense MLP intermediate size | 12288 |
48
+ | dense prefix | first 3 layers |
49
+ | MTP layers | 1 |
50
+ | vocabulary and tokenizer | 154880 |
51
+
52
+ The routed-expert tensors use the same ModelOpt NVFP4 storage ABI as the source
53
+ checkpoint: packed `U8` weights, `F8_E4M3` per-block scales, and scalar `F32`
54
+ global scales. All 1,728 expert projections are present.
55
+
56
+ To keep the artifact under 1 GiB, `hidden_size` is reduced from 4096 to 256,
57
+ the 45-layer stack is reduced to its first four-layer cycle, maximum positions
58
+ are reduced to 8192, and the vision tower is reduced to one small layer. The
59
+ four base layers plus one copied MTP layer still cover KDA, dense MLP, sparse
60
+ MLA, routed NVFP4 MoE, shared experts, and speculative decoding.
61
+
62
+ ## What the fixture exposed on GB10
63
+
64
+ The pinned base image
65
+ `vllm/vllm-openai:glm53-flash-arm64-cu130@sha256:905c02933be6021301db2dc284e24e3727467aa3a0f63b41d609885778a07bce`
66
+ loads the checkpoint but needs three compatibility changes:
67
+
68
+ 1. GLM-5.3 is logically NoPE (`qk_rope_head_dim=0`), while the SM120
69
+ `fp8_ds_mla` cache writer requires a physical 64-BF16 positional region.
70
+ The adapter writes zeros into that region and pads the absorbed 512-wide
71
+ query to 576. This preserves the NoPE dot product.
72
+ 2. `index_topk=2048`, `index_kpool=4`, the always-selected tail, and
73
+ `BLOCK_N=128` alignment produce a physical sparse-index buffer of 2176
74
+ columns. The bundled FlashInfer AOT module only instantiates 2048. The
75
+ adapter adds the exact `num_heads=64, topk=2176` decode specialization.
76
+ 3. Requests with more than 64 query tokens use the prefill orchestrator, so the
77
+ matching `GLM_NSA, num_heads=64, topk=2176` prefill specialization is also
78
+ required. The patched module is rebuilt for `sm_121a`; editing Python or JIT
79
+ source alone does not override the precompiled AOT `.so` in the base image.
80
+
81
+ The physical sparse-MLA row remains the native GLM_NSA 656-byte layout:
82
+
83
+ ```text
84
+ query = [absorbed NoPE 512 | zero padding 64]
85
+ KV = [FP8 latent 512 | four FP32 scales | 64 BF16 zeros]
86
+ ```
87
+
88
+ The vLLM CLI still requires `--block-size 256` because the GLM index cache must
89
+ be divisible by `index_kpool * 32`. Internally the compressed FlashInfer sparse
90
+ cache uses 64-token physical pages; these are different levels of the cache
91
+ layout and should not be conflated.
92
+
93
+ ## Run with the GB10 image
94
+
95
+ ```bash
96
+ docker run --rm --gpus all --ipc=host -p 8000:8000 \
97
+ ghcr.io/cyijun/glm-5.3-flash-nvfp4-gb10:vllm-glm53-sm121 \
98
+ cyijun2k/glm-5.3-flash-tiny-random-nvfp4 \
99
+ --served-model-name glm53-tiny \
100
+ --max-model-len 512 \
101
+ --max-num-seqs 2 \
102
+ --gpu-memory-utilization 0.10 \
103
+ --block-size 256 \
104
+ --moe-backend marlin \
105
+ --enforce-eager
106
+ ```
107
+
108
+ Optional one-token MTP smoke test:
109
+
110
+ ```text
111
+ --speculative-config '{"method":"mtp","num_speculative_tokens":1}'
112
+ ```
113
+
114
+ ## Validation evidence
115
+
116
+ Validation was performed on an NVIDIA GB10 (SM121) with vLLM
117
+ `0.1.dev20051+g487ecf187`, FlashInfer `0.6.17`, Transformers `5.15.1`, and
118
+ PyTorch `2.13.0+cu130`.
119
+
120
+ | Check | Result |
121
+ | --- | --- |
122
+ | critical configuration fields against pinned source revision | 21/21 match |
123
+ | fixture tensor names with an analogous source tensor | 5342/5342 |
124
+ | NVFP4 weight/scale/global-scale dtypes | `U8` / `F8_E4M3` / `F32` |
125
+ | model load and `/health` | pass |
126
+ | OpenAI-compatible short chat + continuous decode | pass |
127
+ | 491-token prefill + 16-token decode | pass |
128
+ | MTP with one speculative token | pass |
129
+ | public companion GHCR manifest | `sha256:4251b561d111d817765ed4097512ce36811deac071a4a7411d20242df5c74a47` |
130
+
131
+ See `VALIDATION.json` for the exact image digest and machine-readable results.
132
+
133
+ ## Integrity
134
+
135
+ `model.safetensors` is 1,010,842,392 bytes and contains 5,342 tensors.
136
+
137
+ ```text
138
+ sha256 d0f8a670c6d96be8984db205a4bfb32c947f09182d6b327fab8d4f1088b66810
139
+ ```
140
+
141
+ The checkpoint is deterministic with model seed 42 and expert payload seed
142
+ 4242. `BUILD_INFO.json` records the source revision and fixture profile.
VALIDATION.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "validated_at": "2026-08-27",
3
+ "hardware": {
4
+ "gpu": "NVIDIA GB10",
5
+ "compute_capability": "SM121",
6
+ "memory_gib": 121.69
7
+ },
8
+ "base_runtime": {
9
+ "image": "vllm/vllm-openai:glm53-flash-arm64-cu130",
10
+ "digest": "sha256:905c02933be6021301db2dc284e24e3727467aa3a0f63b41d609885778a07bce",
11
+ "image_id": "sha256:d42649063a2b05810bce6e1462918475b4ae6e44ad56033735f7118d5c16f136",
12
+ "vllm": "0.1.dev20051+g487ecf187",
13
+ "flashinfer": "0.6.17",
14
+ "transformers": "5.15.1",
15
+ "torch": "2.13.0+cu130"
16
+ },
17
+ "schema": {
18
+ "critical_config_fields_matched": 21,
19
+ "mock_tensor_count": 5342,
20
+ "analogous_target_tensor_names": 5342,
21
+ "missing_target_tensor_names": 0,
22
+ "nvfp4_weight_dtype": "U8",
23
+ "nvfp4_scale_dtype": "F8_E4M3",
24
+ "nvfp4_global_scale_dtype": "F32"
25
+ },
26
+ "runtime": {
27
+ "adapter_image_runtime_tested_local_id": "sha256:7e79066623ddc0485c71cc01a181637cc287457d86c74676043d93bc478ea491",
28
+ "published_image_local_id": "sha256:0d255dd6c0f4c797214a185706fc57cf982e85952945904414eaa83e15fc1e71",
29
+ "published_image": "ghcr.io/cyijun/glm-5.3-flash-nvfp4-gb10@sha256:4251b561d111d817765ed4097512ce36811deac071a4a7411d20242df5c74a47",
30
+ "published_source_revision": "5bb0a598829839a9e0c420c6b737a742e084948c",
31
+ "published_manifest_visibility": "public",
32
+ "health": "pass",
33
+ "openai_models": "pass",
34
+ "short_chat_decode": "pass",
35
+ "prefill_491_tokens_and_decode_16_tokens": "pass",
36
+ "mtp_one_speculative_token": "pass",
37
+ "note": "Generated text is intentionally random; validation concerns loading, cache layout, CUDA dispatch, prefill, decode, and MTP execution."
38
+ }
39
+ }
chat_template.jinja ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gMASK]<sop>
2
+ {%- set effective_reasoning_effort = reasoning_effort if reasoning_effort is defined and reasoning_effort in ['low', 'high'] else 'max' -%}
3
+ {%- if effective_reasoning_effort is not none -%}<|system|>Reasoning Effort: {{ effective_reasoning_effort | capitalize }}{%- endif -%}
4
+ {%- if tools -%}
5
+ {%- macro tool_to_json(tool) -%}
6
+ {%- set ns_tool = namespace(first=true) -%}
7
+ {{ '{' -}}
8
+ {%- for k, v in tool.items() -%}
9
+ {%- if k != 'defer_loading' and k != 'strict' -%}
10
+ {%- if not ns_tool.first -%}{{- ', ' -}}{%- endif -%}
11
+ {%- set ns_tool.first = false -%}
12
+ "{{ k }}": {{ v | tojson(ensure_ascii=False) }}
13
+ {%- endif -%}
14
+ {%- endfor -%}
15
+ {{- '}' -}}
16
+ {%- endmacro -%}
17
+ {%- macro tool_references_to_response(refs) -%}
18
+ {{- '<tool_response><tools>\n' -}}
19
+ {%- for tr in refs -%}
20
+ {%- for tool in tools -%}
21
+ {%- if 'function' in tool -%}
22
+ {%- set tool = tool['function'] -%}
23
+ {%- endif -%}
24
+ {%- if tool.name == tr.name -%}
25
+ {{- tool_to_json(tool) + '\n' -}}
26
+ {%- endif -%}
27
+ {%- endfor -%}
28
+ {%- endfor -%}
29
+ {{- '</tools></tool_response>' -}}
30
+ {%- endmacro -%}
31
+ <|system|>
32
+ # Tools
33
+
34
+ You may call one or more functions to assist with the user query.
35
+
36
+ You are provided with function signatures within <tools></tools> XML tags:
37
+ <tools>
38
+ {% for tool in tools %}
39
+ {%- if 'function' in tool -%}
40
+ {%- set tool = tool['function'] -%}
41
+ {%- endif -%}
42
+ {% if tool.defer_loading is not defined or not tool.defer_loading %}
43
+ {{ tool_to_json(tool) }}
44
+ {% endif %}
45
+ {% endfor %}
46
+ </tools>
47
+
48
+ For each function call, output the function name and arguments within the following XML format:
49
+ <tool_call>{function-name}<arg_key>{arg-key-1}</arg_key><arg_value>{arg-value-1}</arg_value><arg_key>{arg-key-2}</arg_key><arg_value>{arg-value-2}</arg_value>...</tool_call>{%- endif -%}
50
+ {%- macro visible_text(content) -%}
51
+ {%- if content is string -%}
52
+ {{- content }}
53
+ {%- elif content is iterable and content is not mapping -%}
54
+ {%- for item in content -%}
55
+ {%- if item is mapping and item.type == 'text' -%}
56
+ {{- item.text }}
57
+ {%- elif item is string -%}
58
+ {{- item }}
59
+ {%- elif item is mapping and item.type in ['image', 'image_url', 'video', 'video_url', 'audio', 'audio_url', 'input_audio'] -%}
60
+ {%- set media_type = item.type | replace('_url', '') | replace('input_', '') -%}
61
+ {{- "<reminder>You are unable to process this " ~ media_type ~ " because you don't have multi-modal input ability. Try different methods.</reminder>" }}
62
+ {%- endif -%}
63
+ {%- endfor -%}
64
+ {%- else -%}
65
+ {{- content }}
66
+ {%- endif -%}
67
+ {%- endmacro -%}
68
+ {%- macro tool_response(text) -%}
69
+ {{- '<tool_response>' + text + '</tool_response>' -}}
70
+ {%- endmacro -%}
71
+ {%- macro render_tool_response(m) -%}
72
+ {%- if m.content is string -%}
73
+ {{- tool_response(m.content) -}}
74
+ {%- elif m.content and m.content is not mapping and m.content.0.type == "tool_reference" -%}
75
+ {{- tool_references_to_response(m.content) -}}
76
+ {%- elif is_list_of_outputs(m) -%}
77
+ {%- for tr in m.content -%}
78
+ {%- if tr.output is iterable and tr.output is not string and tr.output is not mapping and tr.output and tr.output.0.type == "tool_reference" -%}
79
+ {{- tool_references_to_response(tr.output) -}}
80
+ {%- else -%}
81
+ {{- tool_response(visible_text(tr.output)) -}}
82
+ {%- endif -%}
83
+ {%- endfor -%}
84
+ {%- else -%}
85
+ {{- tool_response(visible_text(m.content)) -}}
86
+ {%- endif -%}
87
+ {%- endmacro -%}
88
+ {%- macro id_of(obj) -%}
89
+ {%- if obj.tool_call_id -%}
90
+ {{- obj.tool_call_id -}}
91
+ {%- elif obj.id -%}
92
+ {{- obj.id -}}
93
+ {%- endif -%}
94
+ {%- endmacro -%}
95
+ {%- macro is_list_of_outputs(m) -%}
96
+ {%- if m.content and m.content.0.output is defined -%}1{%- endif -%}
97
+ {%- endmacro -%}
98
+ {%- set ns = namespace(last_user_index=-1) -%}
99
+ {%- for m in messages %}
100
+ {%- if m.role == 'user' %}
101
+ {%- set ns.last_user_index = loop.index0 -%}
102
+ {%- endif %}
103
+ {%- endfor %}
104
+ {%- for m in messages -%}
105
+ {%- if m.role == 'user' -%}<|user|>{{ visible_text(m.content) }}
106
+ {%- elif m.role == 'assistant' -%}
107
+ <|assistant|>
108
+ {%- set content = visible_text(m.content) %}
109
+ {%- if m.reasoning_content is string %}
110
+ {%- set reasoning_content = m.reasoning_content %}
111
+ {%- elif '</think>' in content %}
112
+ {%- set reasoning_content = content.split('</think>')[0].split('<think>')[-1] %}
113
+ {%- set content = content.split('</think>')[-1] %}
114
+ {%- endif %}
115
+ {%- if ((clear_thinking is defined and not clear_thinking) or loop.index0 > ns.last_user_index) and reasoning_content is defined -%}
116
+ {{ '<think>' + reasoning_content + '</think>'}}
117
+ {%- else -%}
118
+ {{ '<think></think>' }}
119
+ {%- endif -%}
120
+ {%- if content.strip() -%}
121
+ {{ content.strip() }}
122
+ {%- endif -%}
123
+ {% if m.tool_calls %}
124
+ {% for tc in m.tool_calls %}
125
+ {%- if tc.function %}
126
+ {%- set tc = tc.function %}
127
+ {%- endif %}
128
+ {{- '<tool_call>' + tc.name -}}
129
+ {% set _args = tc.arguments %}{% for k, v in _args.items() %}<arg_key>{{ k }}</arg_key><arg_value>{{ v | tojson(ensure_ascii=False) if v is not string else v }}</arg_value>{% endfor %}</tool_call>{% endfor %}
130
+ {% endif %}
131
+ {%- elif m.role == 'tool' -%}
132
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
133
+ {{- '<|observation|>' -}}
134
+ {%- set block_start = loop.index0 -%}
135
+ {%- set ns_blk = namespace(end=block_start) -%}
136
+ {%- for j in range(block_start, messages|length) -%}
137
+ {%- if messages[j].role == 'tool' -%}
138
+ {%- set ns_blk.end = j -%}
139
+ {%- else -%}
140
+ {%- break -%}
141
+ {%- endif -%}
142
+ {%- endfor -%}
143
+ {%- set ns_a = namespace(tool_calls=none) -%}
144
+ {%- if block_start > 0 and messages[block_start - 1].role == 'assistant' and messages[block_start - 1].tool_calls -%}
145
+ {%- set ns_a.tool_calls = messages[block_start - 1].tool_calls -%}
146
+ {%- endif -%}
147
+ {%- set ns_chk = namespace(can_sort=true) -%}
148
+ {%- if not ns_a.tool_calls -%}
149
+ {%- set ns_chk.can_sort = false -%}
150
+ {%- else -%}
151
+ {%- for k in range(block_start, ns_blk.end + 1) -%}
152
+ {%- set m = messages[k] -%}
153
+ {%- if is_list_of_outputs(m) -%}
154
+ {%- for entry in m.content -%}
155
+ {%- set eid = id_of(entry) -%}
156
+ {%- if not eid -%}
157
+ {%- set ns_chk.can_sort = false -%}
158
+ {%- endif -%}
159
+ {%- endfor -%}
160
+ {%- else -%}
161
+ {%- set tk_id = id_of(m) -%}
162
+ {%- if not tk_id -%}
163
+ {%- set ns_chk.can_sort = false -%}
164
+ {%- endif -%}
165
+ {%- endif -%}
166
+ {%- endfor -%}
167
+ {%- for tc in ns_a.tool_calls -%}
168
+ {%- set tc_id = id_of(tc) -%}
169
+ {%- if not tc_id -%}
170
+ {%- set ns_chk.can_sort = false -%}
171
+ {%- endif -%}
172
+ {%- endfor -%}
173
+ {%- endif -%}
174
+ {%- if ns_chk.can_sort -%}
175
+ {%- for tc in ns_a.tool_calls -%}
176
+ {%- set tc_id = id_of(tc) -%}
177
+ {%- for k in range(block_start, ns_blk.end + 1) -%}
178
+ {%- set m = messages[k] -%}
179
+ {%- if is_list_of_outputs(m) -%}
180
+ {%- for entry in m.content -%}
181
+ {%- set eid = id_of(entry) -%}
182
+ {%- if eid == tc_id -%}
183
+ {%- if entry.output is iterable and entry.output is not string and entry.output is not mapping and entry.output and entry.output.0.type == "tool_reference" -%}
184
+ {{- tool_references_to_response(entry.output) -}}
185
+ {%- else -%}
186
+ {{- tool_response(visible_text(entry.output)) -}}
187
+ {%- endif -%}
188
+ {%- endif -%}
189
+ {%- endfor -%}
190
+ {%- else -%}
191
+ {%- set tk_id = id_of(m) -%}
192
+ {%- if tk_id == tc_id -%}
193
+ {{- render_tool_response(m) -}}
194
+ {%- endif -%}
195
+ {%- endif -%}
196
+ {%- endfor -%}
197
+ {%- endfor -%}
198
+ {%- else -%}
199
+ {%- for k in range(block_start, ns_blk.end + 1) -%}
200
+ {{- render_tool_response(messages[k]) -}}
201
+ {%- endfor -%}
202
+ {%- endif -%}
203
+ {% endif -%}
204
+ {%- elif m.role == 'system' -%}
205
+ <|system|>{{ visible_text(m.content) }}
206
+ {%- endif -%}
207
+ {%- endfor -%}
208
+ {%- if add_generation_prompt -%}
209
+ <|assistant|>{{- '<think>' -}}
210
+ {%- endif -%}
config.json ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Glm5NextForConditionalGeneration"
4
+ ],
5
+ "text_config": {
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "dtype": "bfloat16",
9
+ "eos_token_id": [
10
+ 154820,
11
+ 154827,
12
+ 154829
13
+ ],
14
+ "first_k_dense_replace": 3,
15
+ "hc_eps": 1e-06,
16
+ "hc_mult": 4,
17
+ "hc_sinkhorn_iters": 20,
18
+ "head_dim": 0,
19
+ "hidden_act": "silu",
20
+ "hidden_size": 256,
21
+ "index_head_dim": 128,
22
+ "index_kpool": 4,
23
+ "index_kpool_always_select_tail": true,
24
+ "index_kpool_compress": true,
25
+ "index_n_heads": 32,
26
+ "index_topk": 2048,
27
+ "index_share_for_mtp_iteration": true,
28
+ "indexer_rope_interleave": true,
29
+ "indexer_types": [
30
+ "full",
31
+ "full",
32
+ "full",
33
+ "full"
34
+ ],
35
+ "initializer_range": 0.02,
36
+ "intermediate_size": 12288,
37
+ "kv_lora_rank": 512,
38
+ "layer_types": [
39
+ "linear_attention",
40
+ "linear_attention",
41
+ "linear_attention",
42
+ "deepseek_sparse_attention"
43
+ ],
44
+ "linear_attn_config": {
45
+ "num_heads": 64,
46
+ "gate_lower_bound": -5.0,
47
+ "head_dim": 128,
48
+ "short_conv_kernel_size": 4,
49
+ "kda_layers": [
50
+ 0,
51
+ 1,
52
+ 2
53
+ ],
54
+ "full_attn_layers": [
55
+ 3
56
+ ]
57
+ },
58
+ "max_position_embeddings": 8192,
59
+ "mhc": true,
60
+ "mla_use_nope": true,
61
+ "mlp_layer_types": [
62
+ "dense",
63
+ "dense",
64
+ "dense",
65
+ "sparse"
66
+ ],
67
+ "model_type": "glm5_next_text",
68
+ "moe_intermediate_size": 2048,
69
+ "moe_router_dtype": "float32",
70
+ "n_group": 1,
71
+ "n_routed_experts": 288,
72
+ "n_shared_experts": 1,
73
+ "norm_topk_prob": true,
74
+ "num_attention_heads": 64,
75
+ "num_experts_per_tok": 8,
76
+ "num_hidden_layers": 4,
77
+ "num_key_value_heads": 64,
78
+ "num_nextn_predict_layers": 1,
79
+ "output_router_logits": false,
80
+ "pad_token_id": 154820,
81
+ "q_lora_rank": 1536,
82
+ "qk_head_dim": 256,
83
+ "qk_nope_head_dim": 256,
84
+ "qk_rope_head_dim": 0,
85
+ "rms_norm_eps": 1e-05,
86
+ "routed_scaling_factor": 2.5,
87
+ "router_aux_loss_coef": 0.001,
88
+ "scoring_func": "sigmoid",
89
+ "swiglu_limit": 10.0,
90
+ "tie_word_embeddings": false,
91
+ "topk_group": 1,
92
+ "topk_method": "noaux_tc",
93
+ "use_cache": true,
94
+ "v_head_dim": 256,
95
+ "vocab_size": 154880
96
+ },
97
+ "vision_config": {
98
+ "attention_bias": true,
99
+ "attention_dropout": 0.0,
100
+ "depth": 1,
101
+ "hidden_act": "silu",
102
+ "hidden_size": 128,
103
+ "image_size": 56,
104
+ "in_channels": 3,
105
+ "initializer_range": 0.02,
106
+ "intermediate_size": 256,
107
+ "model_type": "glm5_next_vision",
108
+ "num_heads": 4,
109
+ "out_hidden_size": 256,
110
+ "patch_size": 14,
111
+ "projection_intermediate_size": 512,
112
+ "rms_norm_eps": 1e-05,
113
+ "spatial_merge_size": 2,
114
+ "swiglu_limit": 10.0,
115
+ "temporal_patch_size": 2
116
+ },
117
+ "image_token_id": 154854,
118
+ "video_token_id": 154855,
119
+ "image_start_token_id": 154830,
120
+ "image_end_token_id": 154831,
121
+ "video_start_token_id": 154832,
122
+ "video_end_token_id": 154833,
123
+ "tie_word_embeddings": false,
124
+ "model_type": "glm5_next",
125
+ "transformers_version": "5.16.0",
126
+ "quantization_config": {
127
+ "config_groups": {
128
+ "group_0": {
129
+ "targets": [
130
+ "Linear"
131
+ ],
132
+ "weights": {
133
+ "num_bits": 4,
134
+ "type": "float",
135
+ "group_size": 16,
136
+ "dynamic": false,
137
+ "symmetric": true
138
+ },
139
+ "input_activations": null,
140
+ "output_activations": null
141
+ }
142
+ },
143
+ "quant_algo": "NVFP4",
144
+ "kv_cache_scheme": null,
145
+ "producer": {
146
+ "name": "modelopt",
147
+ "version": "0.45.0"
148
+ },
149
+ "quant_method": "modelopt",
150
+ "ignore": [
151
+ "lm_head",
152
+ "model.language_model.embed_tokens",
153
+ "*.self_attn.in_proj_qkvbfg_a",
154
+ "*.self_attn.q_proj",
155
+ "*.self_attn.k_proj",
156
+ "*.self_attn.v_proj",
157
+ "*.self_attn.b_proj",
158
+ "*.self_attn.f_a_proj",
159
+ "*.self_attn.g_a_proj",
160
+ "*.self_attn.f_b_proj",
161
+ "*.self_attn.g_b_proj",
162
+ "*.self_attn.fused_qkv_a_proj",
163
+ "*.self_attn.q_a_proj",
164
+ "*.self_attn.kv_a_proj_with_mqa",
165
+ "*.self_attn.q_b_proj",
166
+ "*.self_attn.kv_b_proj",
167
+ "*.self_attn.indexer.wk_weights_proj",
168
+ "*.self_attn.indexer.wk",
169
+ "*.self_attn.indexer.weights_proj",
170
+ "*.self_attn.indexer.wq_b",
171
+ "*.self_attn.o_proj",
172
+ "*.mlp.gate",
173
+ "*.mlp.gate_up_proj",
174
+ "*.mlp.down_proj",
175
+ "*.mlp.shared_experts.gate_up_proj",
176
+ "*.mlp.shared_experts.down_proj",
177
+ "*.mlp.shared_experts.gate_proj",
178
+ "*.mlp.shared_experts.up_proj",
179
+ "*.mlp.gate_proj",
180
+ "*.mlp.up_proj",
181
+ "*.eh_proj",
182
+ "model.visual.*"
183
+ ]
184
+ }
185
+ }
generation_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "eos_token_id": [
4
+ 154820,
5
+ 154827,
6
+ 154829
7
+ ],
8
+ "pad_token_id": 154820,
9
+ "temperature": 1.0,
10
+ "top_p": 0.95,
11
+ "transformers_version": "5.16.0"
12
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d0f8a670c6d96be8984db205a4bfb32c947f09182d6b327fab8d4f1088b66810
3
+ size 1010842392
processor_config.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "image_processor": {
3
+ "do_rescale": true,
4
+ "patch_expand_factor": 1,
5
+ "merge_size": 2,
6
+ "image_mean": [
7
+ 0.48145466,
8
+ 0.4578275,
9
+ 0.40821073
10
+ ],
11
+ "image_std": [
12
+ 0.26862954,
13
+ 0.26130258,
14
+ 0.27577711
15
+ ],
16
+ "temporal_patch_size": 2,
17
+ "patch_size": 14,
18
+ "min_image_tokens": 16,
19
+ "max_image_tokens": 8000,
20
+ "image_processor_type": "Glm5NextImageProcessor"
21
+ },
22
+ "video_processor": {
23
+ "do_rescale": true,
24
+ "video_processor_type": "Glm5NextVideoProcessor",
25
+ "patch_expand_factor": 1,
26
+ "merge_size": 2,
27
+ "image_mean": [
28
+ 0.48145466,
29
+ 0.4578275,
30
+ 0.40821073
31
+ ],
32
+ "image_std": [
33
+ 0.26862954,
34
+ 0.26130258,
35
+ 0.27577711
36
+ ],
37
+ "temporal_patch_size": 2,
38
+ "patch_size": 14,
39
+ "min_image_tokens": 16,
40
+ "max_image_tokens": 240000,
41
+ "fps": 2
42
+ },
43
+ "processor_class": "Glm5NextProcessor"
44
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:19e773648cb4e65de8660ea6365e10acca112d42a854923df93db4a6f333a82d
3
+ size 20217442
tokenizer_config.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "clean_up_tokenization_spaces": false,
4
+ "do_lower_case": false,
5
+ "eos_token": "<|endoftext|>",
6
+ "extra_special_tokens": [
7
+ "<|endoftext|>",
8
+ "[MASK]",
9
+ "[gMASK]",
10
+ "[sMASK]",
11
+ "<sop>",
12
+ "<eop>",
13
+ "<|system|>",
14
+ "<|user|>",
15
+ "<|assistant|>",
16
+ "<|observation|>",
17
+ "<|begin_of_image|>",
18
+ "<|end_of_image|>",
19
+ "<|begin_of_video|>",
20
+ "<|end_of_video|>",
21
+ "<|begin_of_audio|>",
22
+ "<|end_of_audio|>",
23
+ "<|begin_of_transcription|>",
24
+ "<|end_of_transcription|>"
25
+ ],
26
+ "is_local": true,
27
+ "model_max_length": 8192,
28
+ "model_specific_special_tokens": {},
29
+ "pad_token": "<|endoftext|>",
30
+ "padding_side": "left",
31
+ "remove_space": false,
32
+ "tokenizer_class": "TokenizersBackend"
33
+ }
vllm_patch/flashinfer-glm53.patch ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --- flashinfer/mla/_sparse_mla_sm120.py
2
+ +++ flashinfer/mla/_sparse_mla_sm120.py
3
+ @@ -112,6 +112,7 @@
4
+ (64, 512),
5
+ (64, 1024),
6
+ (64, 2048),
7
+ + (64, 2176),
8
+ (128, 128),
9
+ (128, 512),
10
+ (128, 1024),
11
+ --- flashinfer/data/csrc/sparse_mla_sm120_decode_dsv3_2.cu
12
+ +++ flashinfer/data/csrc/sparse_mla_sm120_decode_dsv3_2.cu
13
+ @@ -162,6 +164,7 @@
14
+ DSV3_2_DISPATCH(64, 512)
15
+ DSV3_2_DISPATCH(64, 1024)
16
+ DSV3_2_DISPATCH(64, 2048)
17
+ + DSV3_2_DISPATCH(64, 2176)
18
+ DSV3_2_DISPATCH(128, 128)
19
+ DSV3_2_DISPATCH(128, 512)
20
+ DSV3_2_DISPATCH(128, 1024)
21
+ --- flashinfer/data/csrc/sparse_mla_sm120_prefill.cu
22
+ +++ flashinfer/data/csrc/sparse_mla_sm120_prefill.cu
23
+ @@ -217,6 +217,16 @@
24
+ float* out_lse, float sm_scale, int num_tokens, size_t stride_kv_block,
25
+ const int* topk_length_ptr, cudaStream_t stream) {
26
+ static_assert(KVCacheTraits<MT>::D_QK == 576);
27
+ + if (topk == 2176) {
28
+ + if constexpr (MT == ModelType::GLM_NSA) {
29
+ + if (num_heads != 64) return false;
30
+ + launch_prefill_mg<MT, ComputeMode::FP8, 64, 2176, 64>(
31
+ + Q, KV, indices, attn_sink, output, out_lse, sm_scale, num_tokens,
32
+ + stride_kv_block, topk_length_ptr, stream);
33
+ + return true;
34
+ + }
35
+ + return false;
36
+ + }
37
+ if (topk != 2048) return false;
38
+
39
+ // PBS=64 matches the V32 decode (`decode_dsv3_2_kernel.cuh`). NH=8 covers
vllm_patch/sitecustomize.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Runtime compatibility patch for GLM-5.3 NoPE sparse MLA on SM120/SM121.
2
+
3
+ The fp8_ds_mla physical cache layout reserves 64 BF16 dimensions for RoPE.
4
+ GLM-5.3 uses native NoPE (qk_rope_head_dim=0), so vLLM otherwise forwards an
5
+ empty k_pe tensor to concat_and_cache_mla, whose packed-layout kernel requires
6
+ pe_dim=64. Pad only the physical cache write; the model and attention kernel
7
+ continue to use the architecture-correct logical RoPE dimension of zero.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+
14
+ import torch
15
+ import flashinfer.mla._sparse_mla_sm120 as _sparse_mla_sm120
16
+
17
+ from vllm.v1.attention.backend import MLAAttentionImpl
18
+ from vllm.v1.attention.backends.mla.flashinfer_mla_sparse import (
19
+ _get_workspace_buffer,
20
+ )
21
+ from vllm.v1.attention.backends.mla.flashinfer_mla_sparse_sm120 import (
22
+ FlashInferMLASparseSM120Impl,
23
+ )
24
+ from vllm.v1.attention.backends.mla.sparse_utils import (
25
+ triton_convert_req_index_to_global_index,
26
+ )
27
+
28
+
29
+ _original_decode_dsv3_2_dispatchable = (
30
+ _sparse_mla_sm120._decode_dsv3_2_dispatchable
31
+ )
32
+ _debug = os.getenv("GLM53_GB10_PATCH_DEBUG") == "1"
33
+ _debugged_forward = False
34
+
35
+ if (64, 2176) not in _sparse_mla_sm120._DECODE_DSV3_2_DISPATCH:
36
+ raise RuntimeError(
37
+ "This mock requires the GLM-5.3 H=64/top-k=2176 FlashInfer decode "
38
+ "specialization; use the companion GB10 adapter image."
39
+ )
40
+
41
+
42
+ def _glm53_decode_dsv3_2_dispatchable(
43
+ num_tokens: int,
44
+ num_heads: int,
45
+ topk: int,
46
+ d_qk: int,
47
+ page_block_size: int,
48
+ ) -> bool:
49
+ # The CLI block size is 256 for kpool storage alignment; vLLM exposes the
50
+ # compressed sparse-MLA cache to FlashInfer as physical 64-token pages.
51
+ result = _original_decode_dsv3_2_dispatchable(
52
+ num_tokens,
53
+ num_heads,
54
+ topk,
55
+ d_qk,
56
+ page_block_size,
57
+ )
58
+ if _debug:
59
+ print(
60
+ "GLM53_PATCH dispatch "
61
+ f"tokens={num_tokens} heads={num_heads} topk={topk} "
62
+ f"d_qk={d_qk} physical_page={page_block_size} -> {result}",
63
+ flush=True,
64
+ )
65
+ return result
66
+
67
+
68
+ _sparse_mla_sm120._decode_dsv3_2_dispatchable = (
69
+ _glm53_decode_dsv3_2_dispatchable
70
+ )
71
+
72
+
73
+ _original_do_kv_cache_update = MLAAttentionImpl.do_kv_cache_update
74
+
75
+
76
+ def _glm53_nope_do_kv_cache_update(
77
+ self,
78
+ kv_c_normed: torch.Tensor,
79
+ k_pe: torch.Tensor,
80
+ kv_cache: torch.Tensor,
81
+ slot_mapping: torch.Tensor,
82
+ kv_cache_dtype: str,
83
+ k_scale: torch.Tensor,
84
+ ) -> None:
85
+ if kv_cache_dtype == "fp8_ds_mla" and k_pe.shape[-1] == 0:
86
+ k_pe = k_pe.new_zeros((*k_pe.shape[:-1], 64))
87
+ return _original_do_kv_cache_update(
88
+ self,
89
+ kv_c_normed,
90
+ k_pe,
91
+ kv_cache,
92
+ slot_mapping,
93
+ kv_cache_dtype,
94
+ k_scale,
95
+ )
96
+
97
+
98
+ MLAAttentionImpl.do_kv_cache_update = _glm53_nope_do_kv_cache_update
99
+
100
+
101
+ def _glm53_nope_forward_mqa(
102
+ self,
103
+ q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
104
+ kv_c_and_k_pe_cache: torch.Tensor,
105
+ attn_metadata,
106
+ layer,
107
+ ) -> tuple[torch.Tensor, None]:
108
+ """Run logical NoPE through the physical 576-wide GLM_NSA kernel.
109
+
110
+ SM120's GLM_NSA sparse kernel supports the architecture-required top-k
111
+ 2048, but its packed cache ABI is 512 latent FP8 values plus 64 BF16 RoPE
112
+ values. Appending zero RoPE values preserves the exact NoPE dot product.
113
+ """
114
+ global _debugged_forward
115
+
116
+ if isinstance(q, tuple):
117
+ q = torch.cat(q, dim=-1)
118
+
119
+ if self.qk_rope_head_dim != 0:
120
+ raise RuntimeError("GLM-5.3 NoPE patch received a non-NoPE MLA layer")
121
+
122
+ q = torch.nn.functional.pad(q, (0, 64))
123
+ num_actual_toks = q.shape[0]
124
+ assert self.topk_indices_buffer is not None
125
+ topk_indices = self.topk_indices_buffer[:num_actual_toks]
126
+ if attn_metadata.topk_tokens != 2048:
127
+ raise RuntimeError(
128
+ f"expected architecture index_topk=2048, got {attn_metadata.topk_tokens}"
129
+ )
130
+ if topk_indices.shape[1] != 2176:
131
+ raise RuntimeError(
132
+ "expected the GLM kpool/tail/alignment buffer width 2176, got "
133
+ f"{topk_indices.shape[1]}"
134
+ )
135
+
136
+ converted = triton_convert_req_index_to_global_index(
137
+ attn_metadata.req_id_per_token[:num_actual_toks],
138
+ attn_metadata.block_table,
139
+ topk_indices,
140
+ BLOCK_SIZE=attn_metadata.block_size,
141
+ NUM_TOPK_TOKENS=topk_indices.shape[1],
142
+ return_valid_counts=True,
143
+ )
144
+ topk_indices_physical, valid_counts = converted
145
+ empty_rows = valid_counts == 0
146
+ topk_indices_physical[:, 0] = topk_indices_physical[:, 0].masked_fill(
147
+ empty_rows, 0
148
+ )
149
+ active_lengths = valid_counts.clamp(min=1)
150
+ sparse_topk_capacity = topk_indices_physical.shape[1]
151
+ if _debug and not _debugged_forward:
152
+ print(
153
+ "GLM53_PATCH forward "
154
+ f"q={tuple(q.shape)} topk={tuple(topk_indices.shape)} "
155
+ f"physical_topk={tuple(topk_indices_physical.shape)} "
156
+ f"valid_min={int(valid_counts.min())} "
157
+ f"valid_max={int(valid_counts.max())} "
158
+ f"block_size={attn_metadata.block_size} "
159
+ f"cache={tuple(kv_c_and_k_pe_cache.shape)}",
160
+ flush=True,
161
+ )
162
+ _debugged_forward = True
163
+
164
+ output = q.new_empty(
165
+ (num_actual_toks, self.num_heads, self.kv_lora_rank),
166
+ dtype=q.dtype,
167
+ )
168
+ if self._workspace_buffer is None:
169
+ self._workspace_buffer = _get_workspace_buffer(q.device)
170
+
171
+ from vllm.utils.flashinfer import (
172
+ flashinfer_trtllm_batch_decode_with_kv_cache_mla,
173
+ )
174
+
175
+ out = flashinfer_trtllm_batch_decode_with_kv_cache_mla(
176
+ query=q.unsqueeze(1),
177
+ kv_cache=kv_c_and_k_pe_cache.view(torch.uint8).unsqueeze(1),
178
+ workspace_buffer=self._workspace_buffer,
179
+ qk_nope_head_dim=self.qk_nope_head_dim,
180
+ kv_lora_rank=self.kv_lora_rank,
181
+ qk_rope_head_dim=64,
182
+ block_tables=topk_indices_physical.unsqueeze(1),
183
+ seq_lens=active_lengths,
184
+ max_seq_len=sparse_topk_capacity,
185
+ out=output.unsqueeze(1),
186
+ bmm1_scale=self.scale,
187
+ bmm2_scale=1.0,
188
+ sparse_mla_top_k=sparse_topk_capacity,
189
+ kv_scale_format=self.kv_scale_format,
190
+ ).squeeze(1)
191
+ out = out.masked_fill(empty_rows[:, None, None], 0)
192
+ return out, None
193
+
194
+
195
+ FlashInferMLASparseSM120Impl.forward_mqa = _glm53_nope_forward_mqa