fsdwfv harrypart commited on
Commit
3afa9e2
·
0 Parent(s):

Duplicate from baseten/GLM-5.2-Vision-NVFP4

Browse files

Co-authored-by: Harry Partridge <harrypart@users.noreply.huggingface.co>

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +37 -0
  2. README.md +178 -0
  3. chat_template.jinja +121 -0
  4. config.json +729 -0
  5. configuration_glm5v.py +171 -0
  6. generation_config.json +13 -0
  7. kimi_k25_processor.py +208 -0
  8. kimi_k25_vision_processing.py +251 -0
  9. media_utils.py +368 -0
  10. mm_projector.safetensors +3 -0
  11. model-00001-of-00047.safetensors +3 -0
  12. model-00002-of-00047.safetensors +3 -0
  13. model-00003-of-00047.safetensors +3 -0
  14. model-00004-of-00047.safetensors +3 -0
  15. model-00005-of-00047.safetensors +3 -0
  16. model-00006-of-00047.safetensors +3 -0
  17. model-00007-of-00047.safetensors +3 -0
  18. model-00008-of-00047.safetensors +3 -0
  19. model-00009-of-00047.safetensors +3 -0
  20. model-00010-of-00047.safetensors +3 -0
  21. model-00011-of-00047.safetensors +3 -0
  22. model-00012-of-00047.safetensors +3 -0
  23. model-00013-of-00047.safetensors +3 -0
  24. model-00014-of-00047.safetensors +3 -0
  25. model-00015-of-00047.safetensors +3 -0
  26. model-00016-of-00047.safetensors +3 -0
  27. model-00017-of-00047.safetensors +3 -0
  28. model-00018-of-00047.safetensors +3 -0
  29. model-00019-of-00047.safetensors +3 -0
  30. model-00020-of-00047.safetensors +3 -0
  31. model-00021-of-00047.safetensors +3 -0
  32. model-00022-of-00047.safetensors +3 -0
  33. model-00023-of-00047.safetensors +3 -0
  34. model-00024-of-00047.safetensors +3 -0
  35. model-00025-of-00047.safetensors +3 -0
  36. model-00026-of-00047.safetensors +3 -0
  37. model-00027-of-00047.safetensors +3 -0
  38. model-00028-of-00047.safetensors +3 -0
  39. model-00029-of-00047.safetensors +3 -0
  40. model-00030-of-00047.safetensors +3 -0
  41. model-00031-of-00047.safetensors +3 -0
  42. model-00032-of-00047.safetensors +3 -0
  43. model-00033-of-00047.safetensors +3 -0
  44. model-00034-of-00047.safetensors +3 -0
  45. model-00035-of-00047.safetensors +3 -0
  46. model-00036-of-00047.safetensors +3 -0
  47. model-00037-of-00047.safetensors +3 -0
  48. model-00038-of-00047.safetensors +3 -0
  49. model-00039-of-00047.safetensors +3 -0
  50. model-00040-of-00047.safetensors +3 -0
.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
README.md ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ library_name: sglang
4
+ pipeline_tag: image-text-to-text
5
+ tags:
6
+ - multimodal
7
+ - vision-language
8
+ - glm
9
+ - sglang
10
+ base_model:
11
+ - zai-org/GLM-5.2
12
+ ---
13
+
14
+ # GLM-5.2-Vision (NVFP4)
15
+
16
+ **GLM-5.2 with sight.** A vision-language model that bolts the MoonViT vision encoder from
17
+ [Kimi-K2.6](https://huggingface.co/moonshotai/Kimi-K2.6) onto
18
+ [GLM-5.2](https://huggingface.co/zai-org/GLM-5.2) through a trained PatchMerger projector.
19
+
20
+ GLM-5.2 is a strong open reasoning model with no vision input. This checkpoint adds it,
21
+ without touching a single GLM weight: the text backbone and the vision tower are both frozen
22
+ and byte-identical to their upstream releases. The only newly-trained parameters are the
23
+ **49.5M-parameter projector** that maps MoonViT's 1152-dim patch embeddings into GLM's 6144-dim
24
+ token space.
25
+
26
+ | Component | Detail |
27
+ |---|---|
28
+ | Text backbone | GLM-5.2 (744B total / A40B active, MoE + MLA + DSA sparse attention) — **frozen** |
29
+ | Vision tower | MoonViT-3d from Kimi-K2.6, 27 layers, 1152-dim — **frozen** |
30
+ | Projector | PatchMerger MLP (`pre_norm → linear_1 → GELU → linear_2`), 1152→4608→6144 — **trained** |
31
+ | Text weights | NVFP4, from [`nvidia/GLM-5.2-NVFP4`](https://huggingface.co/nvidia/GLM-5.2-NVFP4) |
32
+ | Size | ~466 GB |
33
+ | Hardware | 8×B200, or 4×B200 at 256k context — **Blackwell only** |
34
+ | Image tokens | up to 4096 per image (16384 MoonViT patches, 2×2 merge) |
35
+ | Max context | 1048576 (1M tokens) |
36
+
37
+ ## Quickstart
38
+
39
+ SGLang needs a small out-of-tree plugin because `Glm5vForConditionalGeneration` is not yet an
40
+ upstream architecture. It ships inside this repo, so there is nothing else to clone:
41
+
42
+ ```bash
43
+ uvx --from huggingface-hub hf download baseten/GLM-5.2-Vision-NVFP4 \
44
+ --include 'plugins/*' --local-dir ./glm5v
45
+ uv pip install ./glm5v/plugins
46
+ ```
47
+
48
+ ### SGLang
49
+
50
+ ```bash
51
+ export SGLANG_EXTERNAL_MODEL_PACKAGE=sglang_glm5v
52
+ export SGLANG_EXTERNAL_MM_PROCESSOR_PACKAGE=sglang_glm5v
53
+ export SGLANG_EXTERNAL_MM_MODEL_ARCH=Glm5vForConditionalGeneration
54
+ python -m sglang_glm5v.patch
55
+ ```
56
+
57
+ #### 8×B200 — full 1M context
58
+
59
+ ```bash
60
+ python -m sglang.launch_server \
61
+ --model-path baseten/GLM-5.2-Vision-NVFP4 --trust-remote-code \
62
+ --tp-size 8 \
63
+ --quantization modelopt_fp4 \
64
+ --disable-shared-experts-fusion --disable-flashinfer-autotune \
65
+ --attention-backend dsa --mm-attention-backend sdpa \
66
+ --kv-cache-dtype fp8_e4m3 --page-size 64 \
67
+ --mem-fraction-static 0.85 \
68
+ --context-length 1048576 \
69
+ --reasoning-parser glm45 --tool-call-parser glm47 \
70
+ --served-model-name glm-5.2-vision \
71
+ --port 30000
72
+ ```
73
+
74
+ #### 4×B200 — 256k context
75
+
76
+ Same command with `--tp-size 4`, a higher memory fraction, and a smaller context:
77
+
78
+ ```bash
79
+ python -m sglang.launch_server \
80
+ --model-path baseten/GLM-5.2-Vision-NVFP4 --trust-remote-code \
81
+ --tp-size 4 \
82
+ --quantization modelopt_fp4 \
83
+ --disable-shared-experts-fusion --disable-flashinfer-autotune \
84
+ --attention-backend dsa --mm-attention-backend sdpa \
85
+ --kv-cache-dtype fp8_e4m3 --page-size 64 \
86
+ --mem-fraction-static 0.90 \
87
+ --context-length 262144 \
88
+ --reasoning-parser glm45 --tool-call-parser glm47 \
89
+ --served-model-name glm-5.2-vision \
90
+ --port 30000
91
+ ```
92
+
93
+ ### Query it
94
+
95
+ Standard OpenAI multimodal messages deliver the image as `image_url`:
96
+
97
+ ```python
98
+ from openai import OpenAI
99
+
100
+ client = OpenAI(base_url="http://localhost:30000/v1", api_key="none")
101
+ r = client.chat.completions.create(
102
+ model="glm-5.2-vision",
103
+ messages=[{"role": "user", "content": [
104
+ {"type": "image_url", "image_url": {"url": "https://ultralytics.com/images/bus.jpg"}},
105
+ {"type": "text", "text": "Describe this image in detail."},
106
+ ]}],
107
+ temperature=1.0, top_p=0.95, max_tokens=512,
108
+ )
109
+ print(r.choices[0].message.content)
110
+ ```
111
+
112
+ GLM-5.2 is a reasoning model: with `--reasoning-parser glm45`, the chain of thought arrives in
113
+ `message.reasoning_content` and the answer in `message.content`.
114
+
115
+ ## Deploy on Baseten
116
+
117
+ The repository includes ready-to-push [Truss](https://truss.baseten.co) configs. The only
118
+ credential you need is an API key for your own Baseten account; no Hugging Face token or
119
+ pre-created Baseten secret is required.
120
+
121
+ 1. Install [`uv`](https://docs.astral.sh/uv/getting-started/installation/) and create a Baseten API key.
122
+ 2. Export the key, download the small Truss directory, and deploy one of the two configurations:
123
+
124
+ ```bash
125
+ export BASETEN_API_KEY="your-baseten-api-key"
126
+ uvx truss login --api-key "$BASETEN_API_KEY" --remote baseten --non-interactive
127
+
128
+ uvx --from huggingface-hub hf download baseten/GLM-5.2-Vision-NVFP4 \
129
+ --include 'truss/*' --local-dir ./glm5v
130
+ cd glm5v/truss
131
+
132
+ # Recommended starting point: 4×B200 and 256k context.
133
+ uvx truss push --remote baseten --config config_nvfp4_4gpu.yaml --wait --output json
134
+
135
+ # Or use 8×B200 for the full 1M-token context.
136
+ # uvx truss push --remote baseten --config config_nvfp4.yaml --wait --output json
137
+ ```
138
+
139
+ The command creates a new model and published deployment in your Baseten account and prints
140
+ JSON containing `model_id`, `model_version_id`, `predict_url`, and `logs_url`. It does not
141
+ promote the deployment to production.
142
+
143
+ Set `PREDICT_URL` to the returned `predict_url`, then query the model:
144
+
145
+ ```bash
146
+ export PREDICT_URL="https://model-...api.baseten.co/deployment/.../predict"
147
+
148
+ curl -fsS "$PREDICT_URL" \
149
+ -H "Authorization: Api-Key $BASETEN_API_KEY" \
150
+ -H "Content-Type: application/json" \
151
+ -d '{
152
+ "model": "glm-5.2-vision",
153
+ "messages": [{
154
+ "role": "user",
155
+ "content": [
156
+ {"type": "image_url", "image_url": {"url": "https://ultralytics.com/images/bus.jpg"}},
157
+ {"type": "text", "text": "Describe this image in detail."}
158
+ ]
159
+ }],
160
+ "max_tokens": 512,
161
+ "temperature": 1.0,
162
+ "top_p": 0.95
163
+ }'
164
+ ```
165
+
166
+ The first deployment downloads about 466 GB of weights and initializes SGLang, so startup can
167
+ take several minutes.
168
+
169
+ ## License
170
+
171
+ MIT, following both parents: GLM-5.2 (MIT) and Kimi-K2.6 (Modified MIT). The projector weights
172
+ are released under MIT. Redistributed upstream weights remain under their original terms.
173
+
174
+ ## Acknowledgements
175
+
176
+ Built on [Z.ai](https://huggingface.co/zai-org)'s GLM-5.2 and
177
+ [Moonshot AI](https://huggingface.co/moonshotai)'s Kimi-K2.6. Neither team was involved in this
178
+ work; please do not direct issues with this checkpoint to them.
chat_template.jinja ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gMASK]<sop>
2
+ {%- set effective_reasoning_effort = 'high' if reasoning_effort is defined and reasoning_effort == 'high' else 'max' -%}
3
+ {%- if (enable_thinking is not defined or enable_thinking) and 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
+ <|system|>
18
+ # Tools
19
+
20
+ You may call one or more functions to assist with the user query.
21
+
22
+ You are provided with function signatures within <tools></tools> XML tags:
23
+ <tools>
24
+ {% for tool in tools %}
25
+ {%- if 'function' in tool -%}
26
+ {%- set tool = tool['function'] -%}
27
+ {%- endif -%}
28
+ {% if tool.defer_loading is not defined or not tool.defer_loading %}
29
+ {{ tool_to_json(tool) }}
30
+ {% endif %}
31
+ {% endfor %}
32
+ </tools>
33
+
34
+ For each function call, output the function name and arguments within the following XML format:
35
+ <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 -%}
36
+ {%- macro visible_text(content) -%}
37
+ {%- if content is string -%}
38
+ {{- content }}
39
+ {%- elif content is iterable and content is not mapping -%}
40
+ {%- for item in content -%}
41
+ {%- if item is mapping and item.type == 'text' -%}
42
+ {{- item.text }}
43
+ {%- elif item is string -%}
44
+ {{- item }}
45
+ {%- elif item is mapping and item.type in ['image', 'image_url'] -%}
46
+ {{- '<|begin_of_image|><|image|><|end_of_image|>' }}
47
+ {%- elif item is mapping and item.type in ['video', 'video_url', 'audio', 'audio_url', 'input_audio'] -%}
48
+ {%- set media_type = item.type | replace('_url', '') | replace('input_', '') -%}
49
+ {{- "<reminder>You are unable to process this " ~ media_type ~ " because you don't have multi-modal input ability. Try different methods.</reminder>" }}
50
+ {%- endif -%}
51
+ {%- endfor -%}
52
+ {%- else -%}
53
+ {{- content }}
54
+ {%- endif -%}
55
+ {%- endmacro -%}
56
+ {%- set ns = namespace(last_user_index=-1) -%}
57
+ {%- for m in messages %}
58
+ {%- if m.role == 'user' %}
59
+ {%- set ns.last_user_index = loop.index0 -%}
60
+ {%- endif %}
61
+ {%- endfor %}
62
+ {%- for m in messages -%}
63
+ {%- if m.role == 'user' -%}<|user|>{{ visible_text(m.content) }}
64
+ {%- elif m.role == 'assistant' -%}
65
+ <|assistant|>
66
+ {%- set content = visible_text(m.content) %}
67
+ {%- if m.reasoning_content is string %}
68
+ {%- set reasoning_content = m.reasoning_content %}
69
+ {%- elif '</think>' in content %}
70
+ {%- set reasoning_content = content.split('</think>')[0].split('<think>')[-1] %}
71
+ {%- set content = content.split('</think>')[-1] %}
72
+ {%- endif %}
73
+ {%- if ((clear_thinking is defined and not clear_thinking) or loop.index0 > ns.last_user_index) and reasoning_content is defined -%}
74
+ {{ '<think>' + reasoning_content + '</think>'}}
75
+ {%- else -%}
76
+ {{ '<think></think>' }}
77
+ {%- endif -%}
78
+ {%- if content.strip() -%}
79
+ {{ content.strip() }}
80
+ {%- endif -%}
81
+ {% if m.tool_calls %}
82
+ {% for tc in m.tool_calls %}
83
+ {%- if tc.function %}
84
+ {%- set tc = tc.function %}
85
+ {%- endif %}
86
+ {{- '<tool_call>' + tc.name -}}
87
+ {% 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 %}
88
+ {% endif %}
89
+ {%- elif m.role == 'tool' -%}
90
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
91
+ {{- '<|observation|>' -}}
92
+ {%- endif %}
93
+ {%- if m.content is string -%}
94
+ {{- '<tool_response>' + m.content + '</tool_response>' -}}
95
+ {%- elif m.content is iterable and m.content is not mapping and m.content and m.content.0.type == "tool_reference" -%}
96
+ {{- '<tool_response><tools>\n' -}}
97
+ {% for tr in m.content %}
98
+ {%- for tool in tools -%}
99
+ {%- if 'function' in tool -%}
100
+ {%- set tool = tool['function'] -%}
101
+ {%- endif -%}
102
+ {%- if tool.name == tr.name -%}
103
+ {{- tool_to_json(tool) + '\n' -}}
104
+ {%- endif -%}
105
+ {%- endfor -%}
106
+ {%- endfor -%}
107
+ {{- '</tools></tool_response>' -}}
108
+ {%- elif m.content is iterable and m.content is not mapping and m.content and m.content.0 is mapping and m.content.0.output is defined -%}
109
+ {%- for tr in m.content -%}
110
+ {{- '<tool_response>' + tr.output + '</tool_response>' -}}
111
+ {%- endfor -%}
112
+ {%- else -%}
113
+ {{- '<tool_response>' + visible_text(m.content) + '</tool_response>' -}}
114
+ {% endif -%}
115
+ {%- elif m.role == 'system' -%}
116
+ <|system|>{{ visible_text(m.content) }}
117
+ {%- endif -%}
118
+ {%- endfor -%}
119
+ {%- if add_generation_prompt -%}
120
+ <|assistant|>{{- '<think></think>' if (enable_thinking is defined and not enable_thinking) else '<think>' -}}
121
+ {%- endif -%}
config.json ADDED
@@ -0,0 +1,729 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Glm5vForConditionalGeneration"
4
+ ],
5
+ "model_type": "glm5v",
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_glm5v.Glm5vConfig"
8
+ },
9
+ "text_config": {
10
+ "architectures": [
11
+ "GlmMoeDsaForCausalLM"
12
+ ],
13
+ "attention_bias": false,
14
+ "attention_dropout": 0.0,
15
+ "bos_token_id": 0,
16
+ "dtype": "bfloat16",
17
+ "eos_token_id": [
18
+ 154820,
19
+ 154827,
20
+ 154829
21
+ ],
22
+ "ep_size": 1,
23
+ "first_k_dense_replace": 3,
24
+ "head_dim": 192,
25
+ "hidden_act": "silu",
26
+ "hidden_size": 6144,
27
+ "index_head_dim": 128,
28
+ "index_n_heads": 32,
29
+ "index_share_for_mtp_iteration": true,
30
+ "index_skip_topk_offset": 3,
31
+ "index_topk": 2048,
32
+ "index_topk_freq": 4,
33
+ "index_topk_pattern": null,
34
+ "indexer_rope_interleave": true,
35
+ "indexer_types": [
36
+ "full",
37
+ "full",
38
+ "full",
39
+ "shared",
40
+ "shared",
41
+ "shared",
42
+ "full",
43
+ "shared",
44
+ "shared",
45
+ "shared",
46
+ "full",
47
+ "shared",
48
+ "shared",
49
+ "shared",
50
+ "full",
51
+ "shared",
52
+ "shared",
53
+ "shared",
54
+ "full",
55
+ "shared",
56
+ "shared",
57
+ "shared",
58
+ "full",
59
+ "shared",
60
+ "shared",
61
+ "shared",
62
+ "full",
63
+ "shared",
64
+ "shared",
65
+ "shared",
66
+ "full",
67
+ "shared",
68
+ "shared",
69
+ "shared",
70
+ "full",
71
+ "shared",
72
+ "shared",
73
+ "shared",
74
+ "full",
75
+ "shared",
76
+ "shared",
77
+ "shared",
78
+ "full",
79
+ "shared",
80
+ "shared",
81
+ "shared",
82
+ "full",
83
+ "shared",
84
+ "shared",
85
+ "shared",
86
+ "full",
87
+ "shared",
88
+ "shared",
89
+ "shared",
90
+ "full",
91
+ "shared",
92
+ "shared",
93
+ "shared",
94
+ "full",
95
+ "shared",
96
+ "shared",
97
+ "shared",
98
+ "full",
99
+ "shared",
100
+ "shared",
101
+ "shared",
102
+ "full",
103
+ "shared",
104
+ "shared",
105
+ "shared",
106
+ "full",
107
+ "shared",
108
+ "shared",
109
+ "shared",
110
+ "full",
111
+ "shared",
112
+ "shared",
113
+ "shared"
114
+ ],
115
+ "initializer_range": 0.02,
116
+ "intermediate_size": 12288,
117
+ "kv_lora_rank": 512,
118
+ "layer_types": [
119
+ "deepseek_sparse_attention",
120
+ "deepseek_sparse_attention",
121
+ "deepseek_sparse_attention",
122
+ "deepseek_sparse_attention",
123
+ "deepseek_sparse_attention",
124
+ "deepseek_sparse_attention",
125
+ "deepseek_sparse_attention",
126
+ "deepseek_sparse_attention",
127
+ "deepseek_sparse_attention",
128
+ "deepseek_sparse_attention",
129
+ "deepseek_sparse_attention",
130
+ "deepseek_sparse_attention",
131
+ "deepseek_sparse_attention",
132
+ "deepseek_sparse_attention",
133
+ "deepseek_sparse_attention",
134
+ "deepseek_sparse_attention",
135
+ "deepseek_sparse_attention",
136
+ "deepseek_sparse_attention",
137
+ "deepseek_sparse_attention",
138
+ "deepseek_sparse_attention",
139
+ "deepseek_sparse_attention",
140
+ "deepseek_sparse_attention",
141
+ "deepseek_sparse_attention",
142
+ "deepseek_sparse_attention",
143
+ "deepseek_sparse_attention",
144
+ "deepseek_sparse_attention",
145
+ "deepseek_sparse_attention",
146
+ "deepseek_sparse_attention",
147
+ "deepseek_sparse_attention",
148
+ "deepseek_sparse_attention",
149
+ "deepseek_sparse_attention",
150
+ "deepseek_sparse_attention",
151
+ "deepseek_sparse_attention",
152
+ "deepseek_sparse_attention",
153
+ "deepseek_sparse_attention",
154
+ "deepseek_sparse_attention",
155
+ "deepseek_sparse_attention",
156
+ "deepseek_sparse_attention",
157
+ "deepseek_sparse_attention",
158
+ "deepseek_sparse_attention",
159
+ "deepseek_sparse_attention",
160
+ "deepseek_sparse_attention",
161
+ "deepseek_sparse_attention",
162
+ "deepseek_sparse_attention",
163
+ "deepseek_sparse_attention",
164
+ "deepseek_sparse_attention",
165
+ "deepseek_sparse_attention",
166
+ "deepseek_sparse_attention",
167
+ "deepseek_sparse_attention",
168
+ "deepseek_sparse_attention",
169
+ "deepseek_sparse_attention",
170
+ "deepseek_sparse_attention",
171
+ "deepseek_sparse_attention",
172
+ "deepseek_sparse_attention",
173
+ "deepseek_sparse_attention",
174
+ "deepseek_sparse_attention",
175
+ "deepseek_sparse_attention",
176
+ "deepseek_sparse_attention",
177
+ "deepseek_sparse_attention",
178
+ "deepseek_sparse_attention",
179
+ "deepseek_sparse_attention",
180
+ "deepseek_sparse_attention",
181
+ "deepseek_sparse_attention",
182
+ "deepseek_sparse_attention",
183
+ "deepseek_sparse_attention",
184
+ "deepseek_sparse_attention",
185
+ "deepseek_sparse_attention",
186
+ "deepseek_sparse_attention",
187
+ "deepseek_sparse_attention",
188
+ "deepseek_sparse_attention",
189
+ "deepseek_sparse_attention",
190
+ "deepseek_sparse_attention",
191
+ "deepseek_sparse_attention",
192
+ "deepseek_sparse_attention",
193
+ "deepseek_sparse_attention",
194
+ "deepseek_sparse_attention",
195
+ "deepseek_sparse_attention",
196
+ "deepseek_sparse_attention"
197
+ ],
198
+ "max_position_embeddings": 1048576,
199
+ "mlp_bias": false,
200
+ "mlp_layer_types": [
201
+ "dense",
202
+ "dense",
203
+ "dense",
204
+ "sparse",
205
+ "sparse",
206
+ "sparse",
207
+ "sparse",
208
+ "sparse",
209
+ "sparse",
210
+ "sparse",
211
+ "sparse",
212
+ "sparse",
213
+ "sparse",
214
+ "sparse",
215
+ "sparse",
216
+ "sparse",
217
+ "sparse",
218
+ "sparse",
219
+ "sparse",
220
+ "sparse",
221
+ "sparse",
222
+ "sparse",
223
+ "sparse",
224
+ "sparse",
225
+ "sparse",
226
+ "sparse",
227
+ "sparse",
228
+ "sparse",
229
+ "sparse",
230
+ "sparse",
231
+ "sparse",
232
+ "sparse",
233
+ "sparse",
234
+ "sparse",
235
+ "sparse",
236
+ "sparse",
237
+ "sparse",
238
+ "sparse",
239
+ "sparse",
240
+ "sparse",
241
+ "sparse",
242
+ "sparse",
243
+ "sparse",
244
+ "sparse",
245
+ "sparse",
246
+ "sparse",
247
+ "sparse",
248
+ "sparse",
249
+ "sparse",
250
+ "sparse",
251
+ "sparse",
252
+ "sparse",
253
+ "sparse",
254
+ "sparse",
255
+ "sparse",
256
+ "sparse",
257
+ "sparse",
258
+ "sparse",
259
+ "sparse",
260
+ "sparse",
261
+ "sparse",
262
+ "sparse",
263
+ "sparse",
264
+ "sparse",
265
+ "sparse",
266
+ "sparse",
267
+ "sparse",
268
+ "sparse",
269
+ "sparse",
270
+ "sparse",
271
+ "sparse",
272
+ "sparse",
273
+ "sparse",
274
+ "sparse",
275
+ "sparse",
276
+ "sparse",
277
+ "sparse",
278
+ "sparse"
279
+ ],
280
+ "model_type": "glm_moe_dsa",
281
+ "moe_intermediate_size": 2048,
282
+ "moe_layer_freq": 1,
283
+ "n_group": 1,
284
+ "n_routed_experts": 256,
285
+ "n_shared_experts": 1,
286
+ "norm_topk_prob": true,
287
+ "num_attention_heads": 64,
288
+ "num_experts": 256,
289
+ "num_experts_per_tok": 8,
290
+ "num_hidden_layers": 78,
291
+ "num_key_value_heads": 64,
292
+ "num_nextn_predict_layers": 1,
293
+ "pad_token_id": 154820,
294
+ "pretraining_tp": 1,
295
+ "q_lora_rank": 2048,
296
+ "qk_head_dim": 256,
297
+ "qk_nope_head_dim": 192,
298
+ "qk_rope_head_dim": 64,
299
+ "rms_norm_eps": 1e-05,
300
+ "rope_interleave": true,
301
+ "rope_parameters": {
302
+ "rope_theta": 8000000,
303
+ "rope_type": "default"
304
+ },
305
+ "routed_scaling_factor": 2.5,
306
+ "scoring_func": "sigmoid",
307
+ "tie_word_embeddings": false,
308
+ "topk_group": 1,
309
+ "topk_method": "noaux_tc",
310
+ "transformers_version": "5.11.0",
311
+ "use_cache": true,
312
+ "v_head_dim": 256,
313
+ "vocab_size": 154880,
314
+ "quantization_config": {
315
+ "config_groups": {
316
+ "group_0": {
317
+ "input_activations": {
318
+ "dynamic": false,
319
+ "num_bits": 4,
320
+ "type": "float",
321
+ "group_size": 16
322
+ },
323
+ "weights": {
324
+ "dynamic": false,
325
+ "num_bits": 4,
326
+ "type": "float",
327
+ "group_size": 16
328
+ },
329
+ "targets": [
330
+ "Linear"
331
+ ]
332
+ }
333
+ },
334
+ "ignore": [
335
+ "lm_head",
336
+ "model.embed_tokens",
337
+ "model.layers.0*",
338
+ "model.layers.1.*",
339
+ "model.layers.10.mlp.shared_experts*",
340
+ "model.layers.10.self_attn*",
341
+ "model.layers.11.mlp.shared_experts*",
342
+ "model.layers.11.self_attn*",
343
+ "model.layers.12.mlp.shared_experts*",
344
+ "model.layers.12.self_attn*",
345
+ "model.layers.13.mlp.shared_experts*",
346
+ "model.layers.13.self_attn*",
347
+ "model.layers.14.mlp.shared_experts*",
348
+ "model.layers.14.self_attn*",
349
+ "model.layers.15.mlp.shared_experts*",
350
+ "model.layers.15.self_attn*",
351
+ "model.layers.16.mlp.shared_experts*",
352
+ "model.layers.16.self_attn*",
353
+ "model.layers.17.mlp.shared_experts*",
354
+ "model.layers.17.self_attn*",
355
+ "model.layers.18.mlp.shared_experts*",
356
+ "model.layers.18.self_attn*",
357
+ "model.layers.19.mlp.shared_experts*",
358
+ "model.layers.19.self_attn*",
359
+ "model.layers.2.*",
360
+ "model.layers.20.mlp.shared_experts*",
361
+ "model.layers.20.self_attn*",
362
+ "model.layers.21.mlp.shared_experts*",
363
+ "model.layers.21.self_attn*",
364
+ "model.layers.22.mlp.shared_experts*",
365
+ "model.layers.22.self_attn*",
366
+ "model.layers.23.mlp.shared_experts*",
367
+ "model.layers.23.self_attn*",
368
+ "model.layers.24.mlp.shared_experts*",
369
+ "model.layers.24.self_attn*",
370
+ "model.layers.25.mlp.shared_experts*",
371
+ "model.layers.25.self_attn*",
372
+ "model.layers.26.mlp.shared_experts*",
373
+ "model.layers.26.self_attn*",
374
+ "model.layers.27.mlp.shared_experts*",
375
+ "model.layers.27.self_attn*",
376
+ "model.layers.28.mlp.shared_experts*",
377
+ "model.layers.28.self_attn*",
378
+ "model.layers.29.mlp.shared_experts*",
379
+ "model.layers.29.self_attn*",
380
+ "model.layers.3.mlp.shared_experts*",
381
+ "model.layers.3.self_attn*",
382
+ "model.layers.30.mlp.shared_experts*",
383
+ "model.layers.30.self_attn*",
384
+ "model.layers.31.mlp.shared_experts*",
385
+ "model.layers.31.self_attn*",
386
+ "model.layers.32.mlp.shared_experts*",
387
+ "model.layers.32.self_attn*",
388
+ "model.layers.33.mlp.shared_experts*",
389
+ "model.layers.33.self_attn*",
390
+ "model.layers.34.mlp.shared_experts*",
391
+ "model.layers.34.self_attn*",
392
+ "model.layers.35.mlp.shared_experts*",
393
+ "model.layers.35.self_attn*",
394
+ "model.layers.36.mlp.shared_experts*",
395
+ "model.layers.36.self_attn*",
396
+ "model.layers.37.mlp.shared_experts*",
397
+ "model.layers.37.self_attn*",
398
+ "model.layers.38.mlp.shared_experts*",
399
+ "model.layers.38.self_attn*",
400
+ "model.layers.39.mlp.shared_experts*",
401
+ "model.layers.39.self_attn*",
402
+ "model.layers.4.mlp.shared_experts*",
403
+ "model.layers.4.self_attn*",
404
+ "model.layers.40.mlp.shared_experts*",
405
+ "model.layers.40.self_attn*",
406
+ "model.layers.41.mlp.shared_experts*",
407
+ "model.layers.41.self_attn*",
408
+ "model.layers.42.mlp.shared_experts*",
409
+ "model.layers.42.self_attn*",
410
+ "model.layers.43.mlp.shared_experts*",
411
+ "model.layers.43.self_attn*",
412
+ "model.layers.44.mlp.shared_experts*",
413
+ "model.layers.44.self_attn*",
414
+ "model.layers.45.mlp.shared_experts*",
415
+ "model.layers.45.self_attn*",
416
+ "model.layers.46.mlp.shared_experts*",
417
+ "model.layers.46.self_attn*",
418
+ "model.layers.47.mlp.shared_experts*",
419
+ "model.layers.47.self_attn*",
420
+ "model.layers.48.mlp.shared_experts*",
421
+ "model.layers.48.self_attn*",
422
+ "model.layers.49.mlp.shared_experts*",
423
+ "model.layers.49.self_attn*",
424
+ "model.layers.5.mlp.shared_experts*",
425
+ "model.layers.5.self_attn*",
426
+ "model.layers.50.mlp.shared_experts*",
427
+ "model.layers.50.self_attn*",
428
+ "model.layers.51.mlp.shared_experts*",
429
+ "model.layers.51.self_attn*",
430
+ "model.layers.52.mlp.shared_experts*",
431
+ "model.layers.52.self_attn*",
432
+ "model.layers.53.mlp.shared_experts*",
433
+ "model.layers.53.self_attn*",
434
+ "model.layers.54.mlp.shared_experts*",
435
+ "model.layers.54.self_attn*",
436
+ "model.layers.55.mlp.shared_experts*",
437
+ "model.layers.55.self_attn*",
438
+ "model.layers.56.mlp.shared_experts*",
439
+ "model.layers.56.self_attn*",
440
+ "model.layers.57.mlp.shared_experts*",
441
+ "model.layers.57.self_attn*",
442
+ "model.layers.58.mlp.shared_experts*",
443
+ "model.layers.58.self_attn*",
444
+ "model.layers.59.mlp.shared_experts*",
445
+ "model.layers.59.self_attn*",
446
+ "model.layers.6.mlp.shared_experts*",
447
+ "model.layers.6.self_attn*",
448
+ "model.layers.60.mlp.shared_experts*",
449
+ "model.layers.60.self_attn*",
450
+ "model.layers.61.mlp.shared_experts*",
451
+ "model.layers.61.self_attn*",
452
+ "model.layers.62.mlp.shared_experts*",
453
+ "model.layers.62.self_attn*",
454
+ "model.layers.63.mlp.shared_experts*",
455
+ "model.layers.63.self_attn*",
456
+ "model.layers.64.mlp.shared_experts*",
457
+ "model.layers.64.self_attn*",
458
+ "model.layers.65.mlp.shared_experts*",
459
+ "model.layers.65.self_attn*",
460
+ "model.layers.66.mlp.shared_experts*",
461
+ "model.layers.66.self_attn*",
462
+ "model.layers.67.mlp.shared_experts*",
463
+ "model.layers.67.self_attn*",
464
+ "model.layers.68.mlp.shared_experts*",
465
+ "model.layers.68.self_attn*",
466
+ "model.layers.69.mlp.shared_experts*",
467
+ "model.layers.69.self_attn*",
468
+ "model.layers.7.mlp.shared_experts*",
469
+ "model.layers.7.self_attn*",
470
+ "model.layers.70.mlp.shared_experts*",
471
+ "model.layers.70.self_attn*",
472
+ "model.layers.71.mlp.shared_experts*",
473
+ "model.layers.71.self_attn*",
474
+ "model.layers.72.mlp.shared_experts*",
475
+ "model.layers.72.self_attn*",
476
+ "model.layers.73.mlp.shared_experts*",
477
+ "model.layers.73.self_attn*",
478
+ "model.layers.74.mlp.shared_experts*",
479
+ "model.layers.74.self_attn*",
480
+ "model.layers.75.mlp.shared_experts*",
481
+ "model.layers.75.self_attn*",
482
+ "model.layers.76.mlp.shared_experts*",
483
+ "model.layers.76.self_attn*",
484
+ "model.layers.77.mlp.shared_experts*",
485
+ "model.layers.77.self_attn*",
486
+ "model.layers.8.mlp.shared_experts*",
487
+ "model.layers.8.self_attn*",
488
+ "model.layers.9.mlp.shared_experts*",
489
+ "model.layers.9.self_attn*",
490
+ "model.layers.78*"
491
+ ],
492
+ "quant_algo": "NVFP4",
493
+ "kv_cache_scheme": {
494
+ "dynamic": false,
495
+ "num_bits": 8,
496
+ "type": "float"
497
+ },
498
+ "producer": {
499
+ "name": "modelopt",
500
+ "version": "0.46.0.dev65+g977d34dc3"
501
+ },
502
+ "quant_method": "modelopt"
503
+ }
504
+ },
505
+ "vision_config": {
506
+ "patch_size": 14,
507
+ "init_pos_emb_height": 64,
508
+ "init_pos_emb_width": 64,
509
+ "init_pos_emb_time": 4,
510
+ "pos_emb_type": "divided_fixed",
511
+ "num_attention_heads": 16,
512
+ "num_hidden_layers": 27,
513
+ "hidden_size": 1152,
514
+ "intermediate_size": 4304,
515
+ "vt_num_attention_heads": 16,
516
+ "vt_num_hidden_layers": 27,
517
+ "vt_hidden_size": 1152,
518
+ "vt_intermediate_size": 4304,
519
+ "merge_kernel_size": [
520
+ 2,
521
+ 2
522
+ ],
523
+ "video_attn_type": "spatial_temporal",
524
+ "merge_type": "sd2_tpool",
525
+ "mm_projector_type": "patchmerger",
526
+ "mm_hidden_size": 1152,
527
+ "projector_hidden_act": "gelu",
528
+ "projector_ln_eps": 1e-05,
529
+ "text_hidden_size": 6144
530
+ },
531
+ "ignore_index": -100,
532
+ "media_placeholder_token_id": 154854,
533
+ "pad_token_id": 154820,
534
+ "use_unified_vision_chunk": true,
535
+ "video_placeholder": "<|glm5v_video_placeholder|>",
536
+ "encoder_only": false,
537
+ "language_only": false,
538
+ "tie_word_embeddings": false,
539
+ "quantization_config": {
540
+ "config_groups": {
541
+ "group_0": {
542
+ "input_activations": {
543
+ "dynamic": false,
544
+ "num_bits": 4,
545
+ "type": "float",
546
+ "group_size": 16
547
+ },
548
+ "weights": {
549
+ "dynamic": false,
550
+ "num_bits": 4,
551
+ "type": "float",
552
+ "group_size": 16
553
+ },
554
+ "targets": [
555
+ "Linear"
556
+ ]
557
+ }
558
+ },
559
+ "ignore": [
560
+ "lm_head",
561
+ "model.embed_tokens",
562
+ "model.layers.0*",
563
+ "model.layers.1.*",
564
+ "model.layers.10.mlp.shared_experts*",
565
+ "model.layers.10.self_attn*",
566
+ "model.layers.11.mlp.shared_experts*",
567
+ "model.layers.11.self_attn*",
568
+ "model.layers.12.mlp.shared_experts*",
569
+ "model.layers.12.self_attn*",
570
+ "model.layers.13.mlp.shared_experts*",
571
+ "model.layers.13.self_attn*",
572
+ "model.layers.14.mlp.shared_experts*",
573
+ "model.layers.14.self_attn*",
574
+ "model.layers.15.mlp.shared_experts*",
575
+ "model.layers.15.self_attn*",
576
+ "model.layers.16.mlp.shared_experts*",
577
+ "model.layers.16.self_attn*",
578
+ "model.layers.17.mlp.shared_experts*",
579
+ "model.layers.17.self_attn*",
580
+ "model.layers.18.mlp.shared_experts*",
581
+ "model.layers.18.self_attn*",
582
+ "model.layers.19.mlp.shared_experts*",
583
+ "model.layers.19.self_attn*",
584
+ "model.layers.2.*",
585
+ "model.layers.20.mlp.shared_experts*",
586
+ "model.layers.20.self_attn*",
587
+ "model.layers.21.mlp.shared_experts*",
588
+ "model.layers.21.self_attn*",
589
+ "model.layers.22.mlp.shared_experts*",
590
+ "model.layers.22.self_attn*",
591
+ "model.layers.23.mlp.shared_experts*",
592
+ "model.layers.23.self_attn*",
593
+ "model.layers.24.mlp.shared_experts*",
594
+ "model.layers.24.self_attn*",
595
+ "model.layers.25.mlp.shared_experts*",
596
+ "model.layers.25.self_attn*",
597
+ "model.layers.26.mlp.shared_experts*",
598
+ "model.layers.26.self_attn*",
599
+ "model.layers.27.mlp.shared_experts*",
600
+ "model.layers.27.self_attn*",
601
+ "model.layers.28.mlp.shared_experts*",
602
+ "model.layers.28.self_attn*",
603
+ "model.layers.29.mlp.shared_experts*",
604
+ "model.layers.29.self_attn*",
605
+ "model.layers.3.mlp.shared_experts*",
606
+ "model.layers.3.self_attn*",
607
+ "model.layers.30.mlp.shared_experts*",
608
+ "model.layers.30.self_attn*",
609
+ "model.layers.31.mlp.shared_experts*",
610
+ "model.layers.31.self_attn*",
611
+ "model.layers.32.mlp.shared_experts*",
612
+ "model.layers.32.self_attn*",
613
+ "model.layers.33.mlp.shared_experts*",
614
+ "model.layers.33.self_attn*",
615
+ "model.layers.34.mlp.shared_experts*",
616
+ "model.layers.34.self_attn*",
617
+ "model.layers.35.mlp.shared_experts*",
618
+ "model.layers.35.self_attn*",
619
+ "model.layers.36.mlp.shared_experts*",
620
+ "model.layers.36.self_attn*",
621
+ "model.layers.37.mlp.shared_experts*",
622
+ "model.layers.37.self_attn*",
623
+ "model.layers.38.mlp.shared_experts*",
624
+ "model.layers.38.self_attn*",
625
+ "model.layers.39.mlp.shared_experts*",
626
+ "model.layers.39.self_attn*",
627
+ "model.layers.4.mlp.shared_experts*",
628
+ "model.layers.4.self_attn*",
629
+ "model.layers.40.mlp.shared_experts*",
630
+ "model.layers.40.self_attn*",
631
+ "model.layers.41.mlp.shared_experts*",
632
+ "model.layers.41.self_attn*",
633
+ "model.layers.42.mlp.shared_experts*",
634
+ "model.layers.42.self_attn*",
635
+ "model.layers.43.mlp.shared_experts*",
636
+ "model.layers.43.self_attn*",
637
+ "model.layers.44.mlp.shared_experts*",
638
+ "model.layers.44.self_attn*",
639
+ "model.layers.45.mlp.shared_experts*",
640
+ "model.layers.45.self_attn*",
641
+ "model.layers.46.mlp.shared_experts*",
642
+ "model.layers.46.self_attn*",
643
+ "model.layers.47.mlp.shared_experts*",
644
+ "model.layers.47.self_attn*",
645
+ "model.layers.48.mlp.shared_experts*",
646
+ "model.layers.48.self_attn*",
647
+ "model.layers.49.mlp.shared_experts*",
648
+ "model.layers.49.self_attn*",
649
+ "model.layers.5.mlp.shared_experts*",
650
+ "model.layers.5.self_attn*",
651
+ "model.layers.50.mlp.shared_experts*",
652
+ "model.layers.50.self_attn*",
653
+ "model.layers.51.mlp.shared_experts*",
654
+ "model.layers.51.self_attn*",
655
+ "model.layers.52.mlp.shared_experts*",
656
+ "model.layers.52.self_attn*",
657
+ "model.layers.53.mlp.shared_experts*",
658
+ "model.layers.53.self_attn*",
659
+ "model.layers.54.mlp.shared_experts*",
660
+ "model.layers.54.self_attn*",
661
+ "model.layers.55.mlp.shared_experts*",
662
+ "model.layers.55.self_attn*",
663
+ "model.layers.56.mlp.shared_experts*",
664
+ "model.layers.56.self_attn*",
665
+ "model.layers.57.mlp.shared_experts*",
666
+ "model.layers.57.self_attn*",
667
+ "model.layers.58.mlp.shared_experts*",
668
+ "model.layers.58.self_attn*",
669
+ "model.layers.59.mlp.shared_experts*",
670
+ "model.layers.59.self_attn*",
671
+ "model.layers.6.mlp.shared_experts*",
672
+ "model.layers.6.self_attn*",
673
+ "model.layers.60.mlp.shared_experts*",
674
+ "model.layers.60.self_attn*",
675
+ "model.layers.61.mlp.shared_experts*",
676
+ "model.layers.61.self_attn*",
677
+ "model.layers.62.mlp.shared_experts*",
678
+ "model.layers.62.self_attn*",
679
+ "model.layers.63.mlp.shared_experts*",
680
+ "model.layers.63.self_attn*",
681
+ "model.layers.64.mlp.shared_experts*",
682
+ "model.layers.64.self_attn*",
683
+ "model.layers.65.mlp.shared_experts*",
684
+ "model.layers.65.self_attn*",
685
+ "model.layers.66.mlp.shared_experts*",
686
+ "model.layers.66.self_attn*",
687
+ "model.layers.67.mlp.shared_experts*",
688
+ "model.layers.67.self_attn*",
689
+ "model.layers.68.mlp.shared_experts*",
690
+ "model.layers.68.self_attn*",
691
+ "model.layers.69.mlp.shared_experts*",
692
+ "model.layers.69.self_attn*",
693
+ "model.layers.7.mlp.shared_experts*",
694
+ "model.layers.7.self_attn*",
695
+ "model.layers.70.mlp.shared_experts*",
696
+ "model.layers.70.self_attn*",
697
+ "model.layers.71.mlp.shared_experts*",
698
+ "model.layers.71.self_attn*",
699
+ "model.layers.72.mlp.shared_experts*",
700
+ "model.layers.72.self_attn*",
701
+ "model.layers.73.mlp.shared_experts*",
702
+ "model.layers.73.self_attn*",
703
+ "model.layers.74.mlp.shared_experts*",
704
+ "model.layers.74.self_attn*",
705
+ "model.layers.75.mlp.shared_experts*",
706
+ "model.layers.75.self_attn*",
707
+ "model.layers.76.mlp.shared_experts*",
708
+ "model.layers.76.self_attn*",
709
+ "model.layers.77.mlp.shared_experts*",
710
+ "model.layers.77.self_attn*",
711
+ "model.layers.8.mlp.shared_experts*",
712
+ "model.layers.8.self_attn*",
713
+ "model.layers.9.mlp.shared_experts*",
714
+ "model.layers.9.self_attn*",
715
+ "model.layers.78*"
716
+ ],
717
+ "quant_algo": "NVFP4",
718
+ "kv_cache_scheme": {
719
+ "dynamic": false,
720
+ "num_bits": 8,
721
+ "type": "float"
722
+ },
723
+ "producer": {
724
+ "name": "modelopt",
725
+ "version": "0.46.0.dev65+g977d34dc3"
726
+ },
727
+ "quant_method": "modelopt"
728
+ }
729
+ }
configuration_glm5v.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Glm5vConfig — remote-code config carried inside the assembled GLM5V SGLang
3
+ checkpoint (referenced by config.json ``auto_map``; loaded with
4
+ ``--trust-remote-code``, which the checkpoint already requires for the Kimi
5
+ image-processor remote code).
6
+
7
+ Self-contained: depends only on ``transformers``. Mirrors SGLang's in-tree
8
+ ``KimiK25Config`` structure (``vision_config`` + ``text_config`` + media
9
+ placeholder fields) with GLM-5.2 as the text model:
10
+
11
+ * ``text_config`` -> ``GlmMoeDsaConfig`` (transformers-native ``glm_moe_dsa``).
12
+ * ``vision_config``-> MoonViT fields; ``text_hidden_size`` (projector output
13
+ dim) retargeted to GLM hidden 6144.
14
+ * ``media_placeholder_token_id`` -> GLM ``<|image|>`` = 154854.
15
+ """
16
+
17
+ from transformers import AutoConfig
18
+ from transformers.configuration_utils import PretrainedConfig
19
+
20
+
21
+ class Glm5vVisionConfig(PretrainedConfig):
22
+ """MoonViT vision tower + PatchMerger projector config.
23
+
24
+ Field names/defaults mirror SGLang's ``KimiK25VisionConfig`` (declared
25
+ names like ``hidden_size``) while the official Kimi checkpoint's ``vt_*``
26
+ names arrive via **kwargs and are stored as attributes — SGLang's model
27
+ code reads both families (tower: ``hidden_size``; projector:
28
+ ``vt_hidden_size``/``text_hidden_size``).
29
+ """
30
+
31
+ model_type = "glm5v_vision"
32
+
33
+ def __init__(
34
+ self,
35
+ # Vision tower
36
+ patch_size: int = 14,
37
+ init_pos_emb_height: int = 64,
38
+ init_pos_emb_width: int = 64,
39
+ init_pos_emb_time: int = 4,
40
+ pos_emb_type: str = "divided_fixed",
41
+ num_attention_heads: int = 16,
42
+ num_hidden_layers: int = 27,
43
+ hidden_size: int = 1152,
44
+ intermediate_size: int = 4304,
45
+ merge_kernel_size=(2, 2),
46
+ video_attn_type: str = "spatial_temporal",
47
+ merge_type: str = "sd2_tpool",
48
+ # MM projector
49
+ mm_projector_type: str = "patchmerger",
50
+ mm_hidden_size: int | None = None,
51
+ vt_hidden_size: int | None = None, # SGLang kimi_k25 projector reads this (== vision-tower hidden)
52
+ projector_hidden_act: str = "gelu",
53
+ projector_ln_eps: float = 1e-5,
54
+ text_hidden_size: int = 6144, # GLM-5.2 hidden (Kimi default is 7168)
55
+ **kwargs,
56
+ ):
57
+ super().__init__(**kwargs)
58
+ self.patch_size = patch_size
59
+ self.init_pos_emb_height = init_pos_emb_height
60
+ self.init_pos_emb_width = init_pos_emb_width
61
+ self.init_pos_emb_time = init_pos_emb_time
62
+ self.pos_emb_type = pos_emb_type
63
+ self.num_attention_heads = num_attention_heads
64
+ self.num_hidden_layers = num_hidden_layers
65
+ self.hidden_size = hidden_size
66
+ self.intermediate_size = intermediate_size
67
+ self.merge_kernel_size = merge_kernel_size
68
+ self.video_attn_type = video_attn_type
69
+ self.merge_type = merge_type
70
+ self.mm_projector_type = mm_projector_type
71
+ self.mm_hidden_size = mm_hidden_size if mm_hidden_size is not None else hidden_size
72
+ self.vt_hidden_size = vt_hidden_size if vt_hidden_size is not None else hidden_size
73
+ self.projector_hidden_act = projector_hidden_act
74
+ self.projector_ln_eps = projector_ln_eps
75
+ self.text_hidden_size = text_hidden_size
76
+
77
+ def __getattr__(self, name):
78
+ # SGLang's kimi_k25 reads vt_-prefixed vision fields (vt_hidden_size, vt_intermediate_size, ...)
79
+ # that our config declares without the prefix; alias any missing vt_* to the base attribute.
80
+ # Reads __dict__ directly (no recursion) and raises normally if the base isn't set.
81
+ if name.startswith("vt_"):
82
+ d = object.__getattribute__(self, "__dict__")
83
+ base = name[3:]
84
+ if base in d:
85
+ return d[base]
86
+ raise AttributeError(name)
87
+
88
+
89
+ class Glm5vConfig(PretrainedConfig):
90
+ """glm5v top-level config: MoonViT ``vision_config`` + GLM-5.2 ``text_config``."""
91
+
92
+ model_type = "glm5v"
93
+
94
+ def __init__(
95
+ self,
96
+ text_config=None,
97
+ vision_config=None,
98
+ ignore_index: int = -100,
99
+ media_placeholder_token_id: int = 154854, # GLM <|image|>
100
+ pad_token_id: int = 154820,
101
+ use_unified_vision_chunk: bool = True,
102
+ video_placeholder: str = "<|glm5v_video_placeholder|>",
103
+ encoder_only: bool = False,
104
+ language_only: bool = False,
105
+ **kwargs,
106
+ ):
107
+ # Vision config (MoonViT).
108
+ if vision_config is None:
109
+ self.vision_config = Glm5vVisionConfig()
110
+ elif isinstance(vision_config, dict):
111
+ self.vision_config = Glm5vVisionConfig(**vision_config)
112
+ else:
113
+ self.vision_config = vision_config
114
+
115
+ # Text config (GLM-5.2 / glm_moe_dsa), built via AutoConfig so the
116
+ # transformers-native GlmMoeDsaConfig class is used.
117
+ raw_text = dict(text_config) if isinstance(text_config, dict) else None
118
+ if text_config is None:
119
+ self.text_config = AutoConfig.for_model("glm_moe_dsa")
120
+ elif isinstance(text_config, dict):
121
+ tc = dict(text_config)
122
+ tc.setdefault("model_type", "glm_moe_dsa")
123
+ # Newer transformers (in the SGLang serving image) validates `layer_types`
124
+ # via a StrictDataclass and rejects the legacy DSA value
125
+ # "deepseek_sparse_attention". The DSA attention path is selected from
126
+ # model_type + the DSA config fields (index_topk etc.), NOT from layer_types,
127
+ # so drop it to pass validation without changing behavior.
128
+ tc.pop("layer_types", None)
129
+ self.text_config = AutoConfig.for_model(**tc)
130
+ else:
131
+ self.text_config = text_config
132
+
133
+ # transformers 5.8.x GlmMoeDsaConfig drops/clobbers raw DSA fields the
134
+ # sparse-attention path needs. SGLang applies this same restore for
135
+ # bare GlmMoeDsaForCausalLM checkpoints (see its HfModelConfigParser;
136
+ # fixed upstream by transformers PR #46338, gone once >= 5.10); our
137
+ # top-level arch is Glm5v so we replicate it here.
138
+ if raw_text is not None:
139
+ for key in ("qk_rope_head_dim", "index_topk_freq"):
140
+ if key in raw_text:
141
+ setattr(self.text_config, key, raw_text[key])
142
+ if hasattr(self.text_config, "qk_nope_head_dim") and hasattr(
143
+ self.text_config, "qk_rope_head_dim"
144
+ ):
145
+ self.text_config.qk_head_dim = (
146
+ self.text_config.qk_nope_head_dim
147
+ + self.text_config.qk_rope_head_dim
148
+ )
149
+
150
+ self.ignore_index = ignore_index
151
+ self.media_placeholder_token_id = media_placeholder_token_id
152
+ self.use_unified_vision_chunk = use_unified_vision_chunk
153
+ self.video_placeholder = video_placeholder
154
+ self.encoder_only = encoder_only
155
+ self.language_only = language_only
156
+
157
+ # Propagate quantization config from the text model (Kimi pattern):
158
+ # only the GLM text Linears are FP8; vision/projector stay bf16 by
159
+ # construction in the model code.
160
+ if getattr(self.text_config, "quantization_config", None) is not None:
161
+ self.quantization_config = self.text_config.quantization_config
162
+
163
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
164
+
165
+ @property
166
+ def hidden_size(self) -> int:
167
+ return self.text_config.hidden_size
168
+
169
+ @property
170
+ def vocab_size(self) -> int:
171
+ return self.text_config.vocab_size
generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 154820,
6
+ 154827,
7
+ 154829
8
+ ],
9
+ "pad_token_id": 154820,
10
+ "temperature": 1.0,
11
+ "top_p": 0.95,
12
+ "transformers_version": "5.11.0"
13
+ }
kimi_k25_processor.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.feature_extraction_utils import BatchFeature
2
+ from transformers.processing_utils import ProcessorMixin
3
+ from transformers.utils import logging
4
+
5
+ logger = logging.get_logger(__name__)
6
+
7
+
8
+ class KimiK25Processor(ProcessorMixin):
9
+ r"""
10
+ Constructs a KimiK25 processor which wraps a KimiK25 image processor and a tokenizer into a single processor.
11
+
12
+ [`KimiK25Processor`] offers all the functionalities of [`KimiK25ImageProcessor`] and [`TikTokenTokenizer`]. See the
13
+ [`~KimiK25Processor.__call__`] and [`~KimiK25Processor.decode`] for more information.
14
+
15
+ Args:
16
+ image_processor ([`KimiK25ImageProcessor`], *optional*):
17
+ The image processor is a required input.
18
+ tokenizer ([`TikTokenTokenizer`], *optional*):
19
+ The tokenizer is a required input.
20
+ chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
21
+ in a chat into a tokenizable string.
22
+ """
23
+
24
+ attributes = ["image_processor", "tokenizer"]
25
+ valid_kwargs = ["chat_template"]
26
+ image_processor_class = "AutoImageProcessor"
27
+ tokenizer_class = "AutoTokenizer"
28
+
29
+ def __init__(
30
+ self,
31
+ image_processor=None,
32
+ tokenizer=None,
33
+ chat_template=None,
34
+ **kwargs,
35
+ ):
36
+ super().__init__(image_processor,
37
+ tokenizer,
38
+ chat_template=chat_template)
39
+ self.media_processor = image_processor
40
+ # A special temporal placeholder to be replaced by actual video placeholders
41
+ self.video_placeholder = "<|kimi_k25_video_placeholder|>"
42
+
43
+ def update_raw_text(self, text: str, video_prompts: list[str]) -> str:
44
+ # replace video prompt in text with video chunk prompts
45
+ video_count = text.count(self.video_placeholder)
46
+ if video_count == 0:
47
+ return text
48
+ assert video_count == len(video_prompts)
49
+ text_parts = text.split(self.video_placeholder)
50
+ assert len(text_parts) == len(video_prompts) + 1
51
+ text = "".join([
52
+ text_parts[i] + video_prompts[i] for i in range(len(video_prompts))
53
+ ])
54
+ text += text_parts[-1]
55
+ return text
56
+
57
+ def preprocess_medias(self, medias: list[dict]) -> list[dict]:
58
+ updated_medias = []
59
+ video_prompts = []
60
+ for media in medias:
61
+ if media['type'] == 'image':
62
+ updated_medias.append(media)
63
+ elif media['type'] == 'video':
64
+ video_chunks = self.media_processor.split_video_chunks(
65
+ media['video'])
66
+ updated_medias.extend(video_chunks)
67
+ video_prompts.append("".join(
68
+ [vc['prompt'] for vc in video_chunks]))
69
+ else:
70
+ raise ValueError(f"unsupported media type: {media['type']}")
71
+ return updated_medias, video_prompts
72
+
73
+ # glm5v: the image placeholder expanded per patch (GLM <|image|> = 154854).
74
+ # The chat template wraps it as <|begin_of_image|><|image|><|end_of_image|>.
75
+ GLM5V_IMAGE_TOKEN = "<|image|>"
76
+
77
+ def __call__(self,
78
+ messages: list[dict] = None,
79
+ medias: list[dict] = None,
80
+ text: str = None,
81
+ images: list = None,
82
+ return_tensors: str = "pt",
83
+ **kwargs) -> BatchFeature:
84
+ """
85
+ Process multimodal inputs for Kimi-K2.5 model.
86
+
87
+ This processor accepts ordered messages and extracts both media and text in a single pass.
88
+ text will be automatically updated if video input detected in messages
89
+
90
+ Args:
91
+ messages: List of message dicts with 'role' and 'content' fields.
92
+ If provided, medias and text will be extracted automatically.
93
+ medias: Pre-extracted list of media dicts. If None, extracted from messages.
94
+ text: Pre-formatted text string. If None, generated via apply_chat_template.
95
+ images: Standard HF VLM API (``processor(text=..., images=[...])``), as
96
+ called by generic drivers (e.g. slime's rollout prompt prep).
97
+ Converted to ``medias`` and each ``<|image|>`` placeholder in
98
+ ``text`` is expanded to that image's per-patch token count, so
99
+ the returned ``input_ids`` align with ``pixel_values`` (same
100
+ semantics as Qwen-family processors and the SGLang serving-layer
101
+ wrapper).
102
+ return_tensors: Format of returned tensors ('pt', 'np', 'tf'). Default: 'pt'.
103
+ **kwargs: Additional arguments passed to tokenizer.apply_chat_template.
104
+
105
+ Returns:
106
+ BatchFeature with fields: input_ids, attention_mask, pixel_values, grid_thws.
107
+ """
108
+ if images is not None and medias is None and text is not None:
109
+ # Standard HF call: expand placeholders, run the media preprocess, and
110
+ # return with STANDARD-HF dtypes: input_ids/attention_mask as python
111
+ # lists (callers like slime's rollout do `sample.tokens += tokens`),
112
+ # media tensors as `return_tensors` (default pt) for the train side.
113
+ if not isinstance(images, (list, tuple)):
114
+ images = [images]
115
+ medias = [{"type": "image", "image": img} for img in images]
116
+ parts = text.split(self.GLM5V_IMAGE_TOKEN)
117
+ if len(parts) - 1 != len(images):
118
+ raise ValueError(
119
+ f"got {len(images)} images but {len(parts) - 1} "
120
+ f"{self.GLM5V_IMAGE_TOKEN!r} placeholders in text")
121
+ expanded = [parts[0]]
122
+ for media, part in zip(medias, parts[1:]):
123
+ num_tokens = self.media_processor.media_tokens_calculator(media)
124
+ expanded.append(self.GLM5V_IMAGE_TOKEN * num_tokens + part)
125
+ text = "".join(expanded)
126
+
127
+ updated_medias, video_prompts = self.preprocess_medias(medias)
128
+ preprocessed = self.media_processor.preprocess(
129
+ updated_medias, return_tensors=return_tensors)
130
+ text = self.update_raw_text(text, video_prompts)
131
+ text_inputs = self.tokenizer([text]) # no return_tensors -> lists
132
+ data = {**text_inputs, **preprocessed.data}
133
+ # Qwen-convention key: downstream training forwards take
134
+ # `image_grid_thw` (same rename the SGLang wrapper applies).
135
+ if "grid_thws" in data:
136
+ data["image_grid_thw"] = data.pop("grid_thws")
137
+ return BatchFeature(data=data)
138
+
139
+ if messages is None and (medias is None or text is None):
140
+ raise ValueError(
141
+ "Provide either 'messages' or both 'medias' and 'text'")
142
+
143
+ if medias is not None and text is not None:
144
+ updated_medias, video_prompts = self.preprocess_medias(medias)
145
+ preprocessed = self.media_processor.preprocess(
146
+ updated_medias, return_tensors=return_tensors)
147
+ text = self.update_raw_text(text, video_prompts)
148
+ text_inputs = self.tokenizer(text, return_tensors=return_tensors)
149
+ return BatchFeature(data={**text_inputs, **preprocessed.data})
150
+
151
+ if medias is None:
152
+ medias = self._extract_medias_from_messages(messages)
153
+ updated_medias, video_prompts = self.preprocess_medias(medias)
154
+ preprocessed = self.media_processor.preprocess(
155
+ updated_medias, return_tensors=return_tensors)
156
+
157
+ # Generate text if not provided
158
+ if text is None:
159
+ text = self.tokenizer.apply_chat_template(messages, **kwargs)
160
+
161
+ text = self.update_raw_text(text, video_prompts)
162
+
163
+ text_inputs = self.tokenizer(text, return_tensors=return_tensors)
164
+ return BatchFeature(data={**text_inputs, **preprocessed.data})
165
+
166
+ @staticmethod
167
+ def _extract_medias_from_messages(messages: list[dict]) -> list[dict]:
168
+ """
169
+ Extract media items from messages in a single pass.
170
+
171
+ This is an optimized version that processes messages only once.
172
+ Kept as internal method since external callers should use __call__.
173
+ """
174
+ medias = []
175
+ for msg in messages:
176
+ if msg['role'] != 'user' or not msg.get('content'):
177
+ continue
178
+
179
+ for content_part in msg['content']:
180
+ if not isinstance(content_part, dict):
181
+ continue
182
+
183
+ content_type = content_part.get('type')
184
+ if content_type in ['video_url', 'video']:
185
+ medias.append({
186
+ 'type': 'video',
187
+ 'video': content_part['video_url']['url'],
188
+ 'first_frame_timestamp': 0.0
189
+ })
190
+ elif content_type in ['image_url', 'image']:
191
+ medias.append({
192
+ 'type': 'image',
193
+ 'image': content_part['image_url'],
194
+ })
195
+ return medias
196
+
197
+ def apply_chat_template(self, messages, **kwargs):
198
+ return self.tokenizer.apply_chat_template(messages, **kwargs)
199
+
200
+ def batch_decode(self, *args, **kwargs):
201
+ return self.tokenizer.batch_decode(*args, **kwargs)
202
+
203
+ def decode(self, *args, **kwargs):
204
+ return self.tokenizer.decode(*args, **kwargs)
205
+
206
+ @property
207
+ def model_input_names(self):
208
+ return ['input_ids', 'attention_mask', 'pixel_values', 'grid_thws']
kimi_k25_vision_processing.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Image processor class for Kimi-K2.5.
2
+ """
3
+
4
+ import json
5
+ from typing import Any, Dict, Optional, Union
6
+
7
+ import numpy as np
8
+ import torch
9
+ from PIL import Image
10
+ from transformers.image_processing_utils import (BaseImageProcessor,
11
+ BatchFeature)
12
+ from transformers.utils import TensorType
13
+
14
+ from .media_utils import (MediaInput, VideoChunkInput, _to_tensor,
15
+ ensure_media_type, get_video_meta, image_to_np,
16
+ navit_patchify, navit_resize_image,
17
+ navit_resize_video, normalize,
18
+ real_sample_fps_and_max_num_frames, timestamp_as_str)
19
+
20
+ try:
21
+ from mecord import VideoReader
22
+ except ImportError:
23
+ VideoReader = None
24
+
25
+
26
+ def resampling(video_bytes: bytes,
27
+ sample_indices: list[int],
28
+ key_indices=None,
29
+ frame_time_info=None,
30
+ num_threads=4) -> str:
31
+ video = VideoReader(video_bytes,
32
+ num_threads=num_threads,
33
+ frame_time_info=frame_time_info,
34
+ key_indices=key_indices)
35
+ # extract target frames
36
+ frames = video[sample_indices]
37
+ frames = [Image.fromarray(frame) for frame in frames]
38
+ return frames
39
+
40
+
41
+ class KimiK25VisionProcessor(BaseImageProcessor):
42
+ model_type = "kimi_k25"
43
+
44
+ def __init__(
45
+ self,
46
+ media_proc_cfg: dict,
47
+ **kwargs,
48
+ ):
49
+ super().__init__(**kwargs)
50
+ self.media_proc_cfg = media_proc_cfg
51
+ self.num_frames_per_chunk = media_proc_cfg[
52
+ 'temporal_merge_kernel_size']
53
+
54
+ def media_tokens_calculator(self, media: MediaInput):
55
+ media = ensure_media_type(media)
56
+ ret = self.get_resize_config(media)
57
+ return ret['num_tokens']
58
+
59
+ @classmethod
60
+ def make_chunk_prompt(cls, timestamp_text: str) -> str:
61
+ return f"{timestamp_text}<|media_begin|>video<|media_content|><|media_pad|><|media_end|>"
62
+
63
+ def split_video_chunks(self,
64
+ video_url: str | bytes) -> list[list[Image.Image]]:
65
+ # video_url should be base64 str or bytes
66
+ video_spec = get_video_meta(video_url)
67
+ sample_fps = min(self.media_proc_cfg['sample_fps'], video_spec.fps)
68
+ sampled_nframes = max(
69
+ round(video_spec.num_frames * sample_fps / video_spec.fps), 1)
70
+ frame_inds = np.linspace(0, video_spec.num_frames - 1,
71
+ sampled_nframes).round().astype(int)
72
+ frame_inds = frame_inds.tolist()
73
+ sampled_frame_ids = []
74
+ temporal_merge_kernel_size = self.media_proc_cfg[
75
+ "temporal_merge_kernel_size"]
76
+ num_chunks = 0
77
+ chunk_timestamp = []
78
+ for i in range(0, len(frame_inds), temporal_merge_kernel_size):
79
+ sampled_frame_ids.extend(frame_inds[i:i +
80
+ temporal_merge_kernel_size])
81
+ start_time = frame_inds[i] / float(video_spec.fps)
82
+ timestamp_text = timestamp_as_str(
83
+ start_time, self.media_proc_cfg["timestamp_mode"])
84
+ chunk_timestamp.append(timestamp_text)
85
+ num_chunks += 1
86
+
87
+ sampled_frames = resampling(video_url, sampled_frame_ids)
88
+ chunks = []
89
+ for chunk_id in range(num_chunks):
90
+ chunk = sampled_frames[chunk_id *
91
+ temporal_merge_kernel_size:(chunk_id + 1) *
92
+ temporal_merge_kernel_size]
93
+ chunks.append(
94
+ VideoChunkInput(type="video_chunk",
95
+ video_chunk=chunk,
96
+ prompt=self.make_chunk_prompt(
97
+ chunk_timestamp[chunk_id])))
98
+ return chunks
99
+
100
+ def get_resize_config(self, media_input: MediaInput) -> dict:
101
+ if media_input['type'] == 'image':
102
+ w, h = media_input['image'].size
103
+ ret = navit_resize_image(
104
+ w, h, self.media_proc_cfg['patch_size'],
105
+ self.media_proc_cfg['merge_kernel_size'],
106
+ self.media_proc_cfg['in_patch_limit'],
107
+ self.media_proc_cfg['patch_limit_on_one_side'],
108
+ self.media_proc_cfg['fixed_output_tokens'])
109
+ return ret
110
+ elif media_input['type'] == 'video_chunk':
111
+ frame = media_input['video_chunk'][0]
112
+ width, height = frame.size
113
+ num_frames = len(media_input["video_chunk"])
114
+ fps = 1.0
115
+
116
+ sample_fps, max_num_frames_each_video = real_sample_fps_and_max_num_frames(
117
+ media_input["type"],
118
+ self.media_proc_cfg['sample_fps'],
119
+ self.media_proc_cfg['max_num_frames_each_video'],
120
+ )
121
+
122
+ in_patch_limit_each_frame = self.media_proc_cfg[
123
+ 'in_patch_limit_each_frame']
124
+ if in_patch_limit_each_frame is None:
125
+ in_patch_limit_each_frame = self.media_proc_cfg[
126
+ 'in_patch_limit']
127
+
128
+ ret = navit_resize_video(
129
+ width,
130
+ height,
131
+ num_frames,
132
+ fps,
133
+ sample_fps,
134
+ self.media_proc_cfg['patch_size'],
135
+ self.media_proc_cfg['merge_kernel_size'],
136
+ in_patch_limit_each_frame,
137
+ self.media_proc_cfg['patch_limit_on_one_side'],
138
+ self.media_proc_cfg['in_patch_limit_video'],
139
+ max_num_frames_each_video,
140
+ self.media_proc_cfg['fixed_output_tokens'],
141
+ )
142
+ return ret
143
+ else:
144
+ raise ValueError("Unsupported type: {}".format(
145
+ media_input['type']))
146
+
147
+ def resize_image(self, image: Image.Image, new_width: int, new_height: int,
148
+ pad_width: int, pad_height: int) -> np.ndarray:
149
+ image_np = image_to_np(image, (new_width, new_height), "resize")
150
+ image_np = np.pad(
151
+ image_np,
152
+ ((0, pad_height), (0, pad_width), (0, 0)),
153
+ mode="constant",
154
+ constant_values=0,
155
+ )
156
+ return image_np
157
+
158
+ def preprocess(
159
+ self,
160
+ medias: list[MediaInput],
161
+ return_tensors: Optional[Union[str, TensorType]] = None,
162
+ ) -> BatchFeature:
163
+ """
164
+ Preprocess a atom vision input (images/video_chunk) into model-ready tensors.
165
+
166
+ Args:
167
+ medias: List of MediaInput.
168
+ return_tensors: Desired output format ('pt', 'np', 'tf', or None).
169
+
170
+ Returns:
171
+ BatchFeature containing 'pixel_values' and 'grid_thws' tensors.
172
+ """
173
+ if not isinstance(medias, list):
174
+ medias = [medias]
175
+ if medias:
176
+ pixel_values = []
177
+ for item in medias:
178
+ item = ensure_media_type(item)
179
+ resize_config = self.get_resize_config(item)
180
+ new_width, new_height, pad_width, pad_height = resize_config[
181
+ 'new_width'], resize_config['new_height'], resize_config[
182
+ 'pad_width'], resize_config['pad_height']
183
+ if item['type'] == 'image':
184
+ image = item['image']
185
+ image_np = self.resize_image(image, new_width, new_height,
186
+ pad_width, pad_height)
187
+ pixel_values.append(np.expand_dims(image_np, axis=0))
188
+ elif item['type'] == 'video_chunk':
189
+ pixels = []
190
+ for frame in item['video_chunk']:
191
+ frame_np = self.resize_image(frame, new_width,
192
+ new_height, pad_width,
193
+ pad_height)
194
+ pixels.append(frame_np)
195
+ pixel_values.append(np.stack(pixels, axis=0))
196
+ else:
197
+ raise ValueError("Unsupported type: {}".format(
198
+ item['type']))
199
+ normalized_pixel_values = []
200
+ image_std_inv = 1.0 / np.array(self.media_proc_cfg['image_std'])
201
+ image_mean = np.array(self.media_proc_cfg['image_mean'])
202
+ for pixels in pixel_values:
203
+ pixels = normalize(pixels, image_mean, image_std_inv)
204
+ pixels_and_thw = navit_patchify(
205
+ pixels,
206
+ self.media_proc_cfg['patch_size'],
207
+ )
208
+ normalized_pixel_values.append(pixels_and_thw)
209
+
210
+ pixel_values = torch.cat([
211
+ _to_tensor(pixel_value['pixel_values'])
212
+ for pixel_value in normalized_pixel_values
213
+ ])
214
+ grid_thws = torch.cat([
215
+ _to_tensor(pixel_value['grid_thw'],
216
+ dtype=torch.int64).unsqueeze(0)
217
+ for pixel_value in normalized_pixel_values
218
+ ])
219
+
220
+ data = {
221
+ 'pixel_values': pixel_values,
222
+ 'grid_thws': grid_thws,
223
+ }
224
+
225
+ else:
226
+ data = {}
227
+
228
+ return BatchFeature(data=data, tensor_type=return_tensors)
229
+
230
+ def __repr__(self):
231
+ return f"KimiK25VisionProcessor(media_proc_cfg={self.media_proc_cfg})"
232
+
233
+ def to_dict(self) -> Dict[str, Any]:
234
+ output = super().to_dict()
235
+ output["media_proc_cfg"] = self.media_proc_cfg
236
+ if "media_processor" in output:
237
+ del output["media_processor"]
238
+ return output
239
+
240
+ @classmethod
241
+ def from_dict(cls, config_dict: Dict[str, Any], **kwargs):
242
+ config = config_dict.copy()
243
+ media_proc_cfg = config.pop("media_proc_cfg", {})
244
+ return cls(media_proc_cfg=media_proc_cfg, **config, **kwargs)
245
+
246
+ def to_json_string(self):
247
+ dictionary = self.to_dict()
248
+ for key, value in dictionary.items():
249
+ if hasattr(value, 'tolist'):
250
+ dictionary[key] = value.tolist()
251
+ return json.dumps(dictionary, indent=2, sort_keys=True) + "\n"
media_utils.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import io
3
+ import math
4
+ import os
5
+ from datetime import datetime, timezone
6
+ from typing import List, Literal, Optional, TypedDict
7
+
8
+ import numpy as np
9
+ from PIL import Image
10
+ from pydantic import BaseModel, Field
11
+
12
+ try:
13
+ from mecord import VideoReader
14
+ except ImportError:
15
+ VideoReader = None
16
+
17
+
18
+ class VideoSpec(BaseModel):
19
+ media_type: str = Literal['video']
20
+ height: int = Field(..., gt=0, description="video frame height")
21
+ width: int = Field(..., gt=0, description="video frame width")
22
+ num_frames: int = Field(..., gt=0, description="num frames")
23
+ fps: float = Field(..., gt=0, description="average fps")
24
+
25
+ # optional, help to accelerate video reading
26
+ key_indices: list[int] = Field(None, description="key indices")
27
+ frame_time_info: dict = Field(None, description="frame time info")
28
+
29
+
30
+ class ImageInput(TypedDict):
31
+ type: Literal['image']
32
+ image: Image.Image
33
+
34
+
35
+ class VideoChunkInput(TypedDict):
36
+ type: Literal['video_chunk']
37
+ video_chunk: List[Image.Image]
38
+ prompt: Optional[str] = None
39
+
40
+
41
+ MediaInput = ImageInput | VideoChunkInput
42
+
43
+
44
+ def get_video_meta(video_src: bytes | str | os.PathLike,
45
+ accurate: bool = True) -> dict:
46
+ """Get the dimensions of a video."""
47
+ if isinstance(video_src, os.PathLike):
48
+ video_src = str(video_src)
49
+ # if b64 string, decode to bytes
50
+ if isinstance(video_src,
51
+ str) and video_src.startswith('data:video/mp4;base64,'):
52
+ video_src = base64.b64decode(video_src.split(',')[1])
53
+ video = VideoReader(video_src, auto_init=accurate, num_threads=1)
54
+ assert video.num_frames > 0, "Invalid video format."
55
+ assert video.original_width > 0 and video.original_height > 0, (
56
+ "Invalid video format.")
57
+ assert video.avg_fps > 0, "Invalid video format."
58
+ return VideoSpec(media_type='video',
59
+ height=video.original_height,
60
+ width=video.original_width,
61
+ num_frames=video.num_frames,
62
+ fps=video.avg_fps,
63
+ key_indices=video.key_indices,
64
+ frame_time_info=video.frame_time_info)
65
+
66
+
67
+ def timestamp_as_str(timestamp: float,
68
+ timestamp_mode: str = "hh:mm:ss.fff") -> str:
69
+ """Convert a timestamp to a string in the format of HH:MM:SS.mmm."""
70
+ if timestamp_mode == "hh:mm:ss.fff":
71
+ return (datetime.fromtimestamp(timestamp,
72
+ tz=timezone.utc).strftime("%H:%M:%S") +
73
+ f".{int((timestamp % 1) * 1000):03d}")
74
+ elif timestamp_mode == "mm:ss.fff":
75
+ return (datetime.fromtimestamp(timestamp,
76
+ tz=timezone.utc).strftime("%M:%S") +
77
+ f".{int((timestamp % 1) * 1000):03d}")
78
+ elif timestamp_mode == "mm:ss":
79
+ return datetime.fromtimestamp(timestamp,
80
+ tz=timezone.utc).strftime("%M:%S")
81
+ else:
82
+ raise ValueError(f"Invalid timestamp mode: {timestamp_mode}")
83
+
84
+
85
+ def navit_resize_image(
86
+ width: int,
87
+ height: int,
88
+ patch_size: int,
89
+ merge_kernel_size: int,
90
+ in_patch_limit: int,
91
+ patch_limit_on_one_side: int,
92
+ fixed_output_tokens: int | None,
93
+ ):
94
+ # Apply the patch limits.
95
+ s1 = math.sqrt(
96
+ in_patch_limit /
97
+ (max(1.0, width // patch_size) * max(1.0, height // patch_size)))
98
+ s2 = patch_limit_on_one_side * patch_size / width
99
+ s3 = patch_limit_on_one_side * patch_size / height
100
+ scale = min(1.0, s1, s2, s3)
101
+ new_w, new_h = max(1, int(width * scale)), max(1, int(height * scale))
102
+ new_w = min(new_w, patch_limit_on_one_side * patch_size)
103
+ new_h = min(new_h, patch_limit_on_one_side * patch_size)
104
+
105
+ # Calculate the padding to make the height and width divisible by the merge kernel size and patch size.
106
+ factor = merge_kernel_size * patch_size
107
+
108
+ pad_height = (factor - new_h % factor) % factor
109
+ pad_width = (factor - new_w % factor) % factor
110
+
111
+ if fixed_output_tokens is not None:
112
+ num_tokens = fixed_output_tokens
113
+ else:
114
+ # Calculate new dimensions after padding and patching
115
+ token_height = (new_h + pad_height) // factor
116
+ token_width = (new_w + pad_width) // factor
117
+
118
+ assert token_height * merge_kernel_size <= patch_limit_on_one_side, (
119
+ f"token_height {token_height} * merge_kernel_size {merge_kernel_size} > patch_limit_on_one_side {patch_limit_on_one_side}"
120
+ )
121
+ assert token_width * merge_kernel_size <= patch_limit_on_one_side, (
122
+ f"token_width {token_width} * merge_kernel_size {merge_kernel_size} > patch_limit_on_one_side {patch_limit_on_one_side}"
123
+ )
124
+
125
+ num_tokens = token_height * token_width
126
+ return {
127
+ "num_tokens": num_tokens,
128
+ "new_width": new_w,
129
+ "new_height": new_h,
130
+ "pad_width": pad_width,
131
+ "pad_height": pad_height,
132
+ "sampled_nframes": 1,
133
+ }
134
+
135
+
136
+ def navit_resize_video(
137
+ width: int,
138
+ height: int,
139
+ nframes: int,
140
+ avg_fps: float,
141
+ sample_fps: float,
142
+ patch_size: int,
143
+ merge_kernel_size: int,
144
+ in_patch_limit_each_frame: int,
145
+ patch_limit_on_one_side: int,
146
+ in_patch_limit_total: int | None,
147
+ max_num_frames_each_video: int | None,
148
+ fixed_output_tokens_each_frame: int | None,
149
+ ):
150
+ sample_fps = min(sample_fps, avg_fps)
151
+ # Calculate the number of frames to sample based on target FPS
152
+ sampled_nframes = max(round(nframes * sample_fps / avg_fps), 1)
153
+ if max_num_frames_each_video is not None:
154
+ sampled_nframes = min(sampled_nframes, max_num_frames_each_video)
155
+
156
+ if in_patch_limit_total is not None:
157
+ in_patch_limit_each_frame = min(
158
+ round(in_patch_limit_total / sampled_nframes),
159
+ in_patch_limit_each_frame)
160
+
161
+ ret = navit_resize_image(
162
+ width,
163
+ height,
164
+ patch_size,
165
+ merge_kernel_size,
166
+ in_patch_limit_each_frame,
167
+ patch_limit_on_one_side,
168
+ fixed_output_tokens_each_frame,
169
+ )
170
+ ret["sampled_nframes"] = sampled_nframes
171
+ return ret
172
+
173
+
174
+ def real_sample_fps_and_max_num_frames(
175
+ type_name: Literal["video", "video_chunk"],
176
+ sample_fps: float,
177
+ max_num_frames_each_video: int | None,
178
+ ) -> tuple[int, int | None]:
179
+ if type_name == "video":
180
+ return sample_fps, max_num_frames_each_video
181
+ elif type_name == "video_chunk":
182
+ max_num_frames_each_video = None
183
+ sample_fps = math.inf
184
+ return sample_fps, max_num_frames_each_video
185
+ else:
186
+ return math.inf, None
187
+
188
+
189
+ def _to_pil(data: str | bytes):
190
+ if isinstance(data, Image.Image):
191
+
192
+ return data.convert("RGB")
193
+ elif isinstance(data, str):
194
+ if data.startswith("data:"):
195
+ raw_base64 = data.split(",")[1]
196
+ return Image.open(io.BytesIO(
197
+ base64.b64decode(raw_base64))).convert("RGB")
198
+ else:
199
+ return Image.open(data).convert("RGB")
200
+ elif isinstance(data, bytes):
201
+ return Image.open(io.BytesIO(data)).convert("RGB")
202
+ else:
203
+ raise ValueError(f"Unsupported data type: {type(data)}")
204
+
205
+
206
+ def ensure_media_type(media: MediaInput) -> MediaInput:
207
+ if media['type'] == 'image':
208
+ media['image'] = _to_pil(media['image'])
209
+ return media
210
+ elif media['type'] == 'video_chunk':
211
+ media['video_chunk'] = [
212
+ _to_pil(frame) for frame in media['video_chunk']
213
+ ]
214
+ return media
215
+ else:
216
+ raise ValueError(f"Unsupported media type: {media['type']}")
217
+
218
+
219
+ def image_to_np(
220
+ image: Image.Image,
221
+ resize_to: tuple[int, int] | None = None,
222
+ mode: str = "resize",
223
+ raise_error_for_ill_resize: bool = True,
224
+ ) -> np.ndarray:
225
+ """Convert an image to a numpy array.
226
+
227
+ Args:
228
+ content: The image to convert.
229
+ resize_to: The size to resize the image to.
230
+ mode: The mode to resize the image to.
231
+ raise_error_for_ill_resize: Whether to raise an error for ill-sized resize.
232
+
233
+ Returns:
234
+ A numpy array.
235
+ """
236
+ assert isinstance(image, Image.Image), "image must be a PIL Image"
237
+ if resize_to is not None:
238
+ if mode == "resize":
239
+ image = image.resize(resize_to, resample=Image.Resampling.BICUBIC)
240
+
241
+ elif mode == "rescale_and_pad_to_center":
242
+ scale = min(resize_to[0] / image.width,
243
+ resize_to[1] / image.height, 1.0)
244
+ new_width = round(image.width * scale)
245
+ new_height = round(image.height * scale)
246
+ if new_width == 0 or new_height == 0:
247
+ if raise_error_for_ill_resize:
248
+ raise ValueError(
249
+ f"Invalid resize to: {resize_to}, from image size: {image.size}"
250
+ )
251
+ else:
252
+ return np.zeros((resize_to[1], resize_to[0], 3),
253
+ dtype=np.uint8)
254
+
255
+ image = image.resize((new_width, new_height),
256
+ resample=Image.Resampling.BICUBIC)
257
+ padding_left = (resize_to[0] - new_width) // 2
258
+ padding_right = resize_to[0] - new_width - padding_left
259
+ padding_top = (resize_to[1] - new_height) // 2
260
+ padding_bottom = resize_to[1] - new_height - padding_top
261
+ image = np.asarray(image)
262
+ image = np.pad(
263
+ image,
264
+ ((padding_top, padding_bottom), (padding_left, padding_right),
265
+ (0, 0)),
266
+ mode="constant",
267
+ constant_values=0,
268
+ )
269
+ assert image.shape == (resize_to[1], resize_to[0], 3)
270
+
271
+ elif mode == "rescale_and_pad_to_rightbottom":
272
+ scale = min(resize_to[0] / image.width,
273
+ resize_to[1] / image.height, 1.0)
274
+ new_width = round(image.width * scale)
275
+ new_height = round(image.height * scale)
276
+ if new_width == 0 or new_height == 0:
277
+ if raise_error_for_ill_resize:
278
+ raise ValueError(
279
+ f"Invalid resize to: {resize_to}, from image size: {image.size}"
280
+ )
281
+ else:
282
+ return np.zeros((resize_to[1], resize_to[0], 3),
283
+ dtype=np.uint8)
284
+
285
+ image = image.resize((new_width, new_height),
286
+ resample=Image.Resampling.BICUBIC)
287
+ padding_right = resize_to[0] - new_width
288
+ padding_bottom = resize_to[1] - new_height
289
+ image = np.asarray(image)
290
+ image = np.pad(
291
+ image,
292
+ ((0, padding_bottom), (0, padding_right), (0, 0)),
293
+ mode="constant",
294
+ constant_values=0,
295
+ )
296
+ assert image.shape == (resize_to[1], resize_to[0], 3)
297
+
298
+ else:
299
+ raise ValueError(f"Invalid mode: {mode}")
300
+
301
+ if isinstance(image, Image.Image):
302
+ return np.asarray(image)
303
+ else:
304
+ return image
305
+
306
+
307
+ def navit_patchify(pixel_values: np.ndarray,
308
+ patch_size: int) -> dict[str, np.ndarray]:
309
+ """Reshape the pixel values to a navit shape.
310
+
311
+ Args:
312
+ pixel_values: np.ndarray, shape (t, h, w, c)
313
+ patch_size: int
314
+
315
+ Returns:
316
+ dict[str, np.ndarray]
317
+ - patches: np.ndarray, shape (t * h//patch_size * w//patch_size, c, patch_size, patch_size)
318
+ - grid_thw: np.ndarray, (t, h//patch_size, w//patch_size)
319
+ """
320
+ T, H, W, C = pixel_values.shape
321
+ assert C == 3, "pixel_values must have 3 channels"
322
+
323
+ patches = pixel_values.reshape(T, H // patch_size, patch_size,
324
+ W // patch_size, patch_size, C)
325
+ # (T, H//patch_size, W//patch_size, C, patch_size, patch_size)
326
+ patches = patches.transpose(0, 1, 3, 5, 2, 4)
327
+ patches = patches.reshape(-1, C, patch_size, patch_size)
328
+ grid_thw = np.array([T, H // patch_size, W // patch_size])
329
+ return {"pixel_values": patches, "grid_thw": grid_thw}
330
+
331
+
332
+ def normalize(x: np.ndarray,
333
+ mean,
334
+ std_inv,
335
+ pixels_dtype: np.dtype = np.float32) -> np.ndarray:
336
+ """Normalize the image.
337
+
338
+ Args:
339
+ x: The image to normalize. The shape is (..., 3). The dtype is uint8. The range is [0, 255].
340
+ mean: The mean of the image.
341
+ std_inv: The inverse of the std of the image.
342
+ pixels_dtype: The dtype of the image.
343
+ Returns:
344
+ The normalized image. The shape is (..., 3). The dtype is determined by the pixels_dtype.
345
+ """
346
+ x = (x / 255.0).astype(pixels_dtype)
347
+ x -= mean
348
+ x *= std_inv
349
+ return x
350
+
351
+
352
+ def _to_tensor(data, **kwargs):
353
+ import torch
354
+
355
+ if isinstance(data, np.ndarray):
356
+ return torch.from_numpy(data).to(**kwargs)
357
+ elif isinstance(data, torch.Tensor):
358
+ return data.to(**kwargs)
359
+ elif isinstance(data, list):
360
+ return [_to_tensor(item, **kwargs) for item in data]
361
+ elif isinstance(data, tuple):
362
+ return tuple(_to_tensor(item, **kwargs) for item in data)
363
+ elif isinstance(data, dict):
364
+ return {k: _to_tensor(v, **kwargs) for k, v in data.items()}
365
+ elif data is None:
366
+ return None
367
+ else:
368
+ raise ValueError(f"Unsupported data type: {type(data)}")
mm_projector.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e7c6ce8c27424f292e708e7bbb48ade57ea9f1aaddd28bd6a1020a860d9db80c
3
+ size 99117136
model-00001-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7355ca8065dac64f806bb8f51921e9c86f428542815e4cbfbe67c207a9e0ff4d
3
+ size 9996935800
model-00002-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5a93bf6840c92c2b921a696b3268c3583f417ce4b85fdf912a3b164679d1df9b
3
+ size 9998076664
model-00003-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:240485288e04efae1c4dcda20eb13a4376efc5f69c0ea1b8c5e3d5d771707ea1
3
+ size 9995585544
model-00004-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:790fe046fb8b18f1c1bc829c32ae88b02aba7203a8fbdb1acf864b37dc838fae
3
+ size 9998076664
model-00005-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9c6a3381b16ff8f37bed8e6e020b338b569f1c927b9a3fa8c025c5c75c77ca79
3
+ size 9997417192
model-00006-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:902e254158f0fac8bb531ff85728de4c1580272464a3418d1e452d67ab9ee4d0
3
+ size 9998081432
model-00007-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:40299690b69637fc15fddf048b47ef0bc82a3c6d9685f0fd048a9823b426cdae
3
+ size 9995590872
model-00008-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:139f1c107077c04c2646d60d16f2c723d8be1876efa8e271eb135f4e564fdb31
3
+ size 9999911744
model-00009-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e1db5be0dac72aaaa446e1fa2437420cf9e47efe3c36c59c5471200be1dd4d23
3
+ size 9998081760
model-00010-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:617a2ca6fd37281f636ed819eab39dd8f2ebb21bc8bbf599f229537bdadb2024
3
+ size 9995590752
model-00011-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5099883c548f807bc1f2cde6188425ac6f40a9c3c244a4e18bfc008e572e7361
3
+ size 9998081968
model-00012-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:df6a0c6ab9fa7be42f0db0872880f1b5636e910b4f73aac5570c42354f05804c
3
+ size 9997420424
model-00013-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2bfd1392eda129e70128ef242284219e5acd07f3b77eeea9f7a6e6b48c3020b9
3
+ size 9998081432
model-00014-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6320d889ab91a2ba274bba38b8ea19b7540b20a6b484ec522ca8bd96ea5333ca
3
+ size 9995590992
model-00015-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:499d121db3e7e08e403a1665071bf55f710d88916de32519359691a571bcbb09
3
+ size 9999911624
model-00016-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b0bfeb109e4a1ca9327430de28f11e858d239505a4d68cc05f93440818c3352b
3
+ size 9998081640
model-00017-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ca88817f6f027fec523052c67e08de81a3751b3b44b45026a29321f32ba61b4b
3
+ size 9995590752
model-00018-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4d32422c750fe5520879ce63b037d2c7061abd0975c56011f757eea603bfbf4b
3
+ size 9959557432
model-00019-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:74ecfce9cddd66f2f6ef551c6f485c1eb2ce5f9f63a9953773c2ab50ce2eff68
3
+ size 10000552960
model-00020-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:23a23304160cf55ca305e920af3f47aabbfacb6a7eb3c2d6624e3cd45af79656
3
+ size 9998081424
model-00021-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:db14cdfbe3e53abbd291c230c148d9c21fd9834f1a6e6bdde8d860936a91c382
3
+ size 9995591144
model-00022-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bf5f1c293e95bc3f37f9da5b2c464d765b9150006695ef4b76d973c2fdc1ef75
3
+ size 9999911480
model-00023-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2fb70768ccd149d6df403ff319b831d3578c6c7ea7040bd6350d36201e2325ae
3
+ size 9998081504
model-00024-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ccf3b2e4ca1e8badbb7e0e3b5e7ed2f23a11a996ee35496f60748649ca45577e
3
+ size 9995590752
model-00025-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:67f233905c40eaa27e1d9174cefd28403ea55dd195f3f97dfa52b55eb480572c
3
+ size 9999911904
model-00026-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:daf23e3ccbf4b5324bcc77a208b4f91f1ab4965a24df62524e26e19a2fef2585
3
+ size 9995591304
model-00027-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1b4c7404684d1f71e6341660ce60b87184e9295c042c68816f70cf21e0d5d378
3
+ size 9998081416
model-00028-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a895f3e5a8150c74996caf4fe7c8b7f11f4ae99f838bcc3207af1a9f87010199
3
+ size 9995591208
model-00029-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5601bf446f5f778b3c2a26d023c78d21c0ed3200c1f2c1a13b082a94143937f5
3
+ size 9999911360
model-00030-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:355b7b4665a899fad5b5b42903c8ff8f58cee469883a7638e651f8ab14a92487
3
+ size 9998081432
model-00031-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7bc1ca71bffdd1a1eee33e43a328d525e23cf39db1b4812fdf55dd3cd90731a4
3
+ size 9995590840
model-00032-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d11bd3fe6f4c772a754ab4b19eca4e05c231c610d2f565aae9f1865723cfef10
3
+ size 9999911784
model-00033-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e39c9ff0d42c6052c538aaee35579a703993862601a340d0c4066ef0d2806bbd
3
+ size 9995591128
model-00034-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a81b529612c93893cf55dfb9c1f1a9a0ebdcca494f62d66181d9c6577a8ed434
3
+ size 9998081416
model-00035-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:70d19f0b6180627f5da59d38ca2d944b3937b77ba0302a5d60db7bfa7a69093c
3
+ size 9995591272
model-00036-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cab4d531d01434f35ec2809ad408519f52b733dd46f30adc43f3aaef6ce95933
3
+ size 9999911176
model-00037-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dc213d3550fc4e8482f88e08c791b4ba74fa8bb85ec2c6d7fc15661dac954055
3
+ size 9998081432
model-00038-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:50c4a5522bd9e4a34977f52fe55018812f483a2afc8c7a32c92cc94e268b474a
3
+ size 9995590960
model-00039-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ca17fd22173184cc0dd50977538725c11f2e6a44d65a48865dc8ea975cfffa67
3
+ size 9999911664
model-00040-of-00047.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:103a33ce23be80b19b18c51eecb1cf15cd49584e22b9138b1d358e8720b2abf3
3
+ size 9995591008