aidiffuser commited on
Commit
9961374
·
verified ·
1 Parent(s): 68252cf

GLM-5.2-Vision: MoonViT tower + trained projector (MLX repackaging)

Browse files
README.md ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ base_model: zai-org/GLM-5.2
4
+ tags:
5
+ - mlx
6
+ - vision
7
+ - glm
8
+ - moonvit
9
+ - exo
10
+ library_name: mlx
11
+ ---
12
+
13
+ # GLM-5.2-Vision — MoonViT tower + trained projector (MLX)
14
+
15
+ Add **image input to any MLX quant of GLM-5.2** with a ~1 GB sidecar: the frozen
16
+ MoonViT-3d vision tower from Kimi K2.6 plus the trained 49.5M-parameter
17
+ PatchMerger projector from
18
+ [baseten/GLM-5.2-Vision-NVFP4](https://huggingface.co/baseten/GLM-5.2-Vision-NVFP4)
19
+ (Harry Partridge's vision retrofit), repackaged for Apple Silicon / MLX.
20
+ The GLM-5.2 text backbone is untouched — text-only behavior stays byte-identical.
21
+
22
+ ## What's in this repo
23
+
24
+ | File | What it is |
25
+ |---|---|
26
+ | `glm52_vision.safetensors` (+ index) | MoonViT-3d tower (417M, 27 layers, 1152-dim, bf16, `vision_tower.*`) **and** the trained projector (`mm_projector.pre_norm/linear_1/linear_2`, 1152 → 2×2 merge → 4608 → 6144) in one file. Kimi's original 7168-dim projector is removed — the GLM-trained one replaces it. |
27
+ | `config.json` | `vision_config` (+ `text_config.hidden_size: 6144`, `media_placeholder_token_id: 154854`) |
28
+ | `preprocessor_config.json`, `kimi_k25_*.py`, `media_utils.py` | Baseten's reference image processor (NaViT resize, patch 14, 2×2 merge, ≤4096 tokens/image) — the exact preprocessing the projector was trained against |
29
+
30
+ GLM-5.2's stock tokenizer already contains the image tokens
31
+ (`<|begin_of_image|>` 154830, `<|image|>` 154854, `<|end_of_image|>` 154831) —
32
+ no tokenizer changes needed. Each image expands to its media-token count at the
33
+ `<|image|>` position and the projected features are substituted at those
34
+ embedding positions. You need a chat template that renders image content parts
35
+ into the marker triplet (GLM's stock template does not; Baseten ships one in
36
+ their repo).
37
+
38
+ ## Using with [exo](https://github.com/exo-explore/exo)
39
+
40
+ exo's vision stack loads this repo directly as a `weights_repo`/`processor_repo`.
41
+ Model card stanza:
42
+
43
+ ```toml
44
+ [vision]
45
+ image_token_id = 154854
46
+ model_type = "kimi_vl"
47
+ weights_repo = "<this repo id>"
48
+ processor_repo = "<this repo id>"
49
+ ```
50
+
51
+ Point the card's model at a directory containing your GLM-5.2 MLX quant with
52
+ Baseten's `chat_template.jinja` and this repo's `config.json` additions
53
+ (`vision_config` / `text_config` / `media_placeholder_token_id`). Assembly
54
+ scripts (symlink the backbone — no weight duplication):
55
+ [`build_glm52_vision_dir.py`](https://github.com/aidiffuser/exo/blob/update-latest/scripts/build_glm52_vision_dir.py)
56
+ and
57
+ [`build_glm52_vision_tower.py`](https://github.com/aidiffuser/exo/blob/update-latest/scripts/build_glm52_vision_tower.py).
58
+
59
+ Verified live on a 2-Mac-Studio (M3 Ultra) tensor-parallel cluster over RDMA,
60
+ against both `mlx-community/GLM-5.2-DQ4plus-q8` and `mlx-community/GLM-5.2-mxfp4`:
61
+ temp-0 deterministic, no cross-image cache bleed, text-only outputs identical
62
+ to the plain model.
63
+
64
+ ## What to expect (honest notes)
65
+
66
+ - Scene understanding, objects, colors, spatial layout and orientation: **good**.
67
+ Reads real-world photos (e.g. product packaging labels) usefully.
68
+ - Dense/synthetic text OCR and fine-grained counting: **weak** — this is a 50M
69
+ projector retrofit at the source's reported ~Haiku-4.5-level MMMU-Pro (55%),
70
+ not a natively-trained VLM. A Kimi K2.6 A/B on the same pipeline is clearly
71
+ stronger at fine detail.
72
+ - The projector was trained against the bf16/NVFP4 backbone; serving quantized
73
+ backbones (mxfp4 / DQ4) costs some additional vision quality, never text
74
+ quality.
75
+
76
+ ## Provenance & license
77
+
78
+ MIT, following all parents. Full chain: **Z.ai** (GLM-5.2, MIT) →
79
+ **Moonshot AI** (Kimi K2.6 MoonViT tower, Modified MIT) → **Harry Partridge /
80
+ Baseten** (projector training + reference processor,
81
+ [baseten/GLM-5.2-Vision-NVFP4](https://huggingface.co/baseten/GLM-5.2-Vision-NVFP4),
82
+ MIT) → **exolabs** (original K2.6 tower extraction for MLX) → this repackaging
83
+ (tensor remap documented in the build script). None of the upstream teams were
84
+ involved in this packaging.
config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "source": "MoonViT tower from moonshotai/Kimi-K2.6 (via exolabs extract) + trained projector from baseten/GLM-5.2-Vision-NVFP4",
3
+ "component": "vision_tower + mm_projector",
4
+ "model_type": "kimi_k25",
5
+ "vision_config": {
6
+ "patch_size": 14,
7
+ "init_pos_emb_height": 64,
8
+ "init_pos_emb_width": 64,
9
+ "init_pos_emb_time": 4,
10
+ "pos_emb_type": "divided_fixed",
11
+ "num_attention_heads": 16,
12
+ "num_hidden_layers": 27,
13
+ "hidden_size": 1152,
14
+ "intermediate_size": 4304,
15
+ "vt_num_attention_heads": 16,
16
+ "vt_num_hidden_layers": 27,
17
+ "vt_hidden_size": 1152,
18
+ "vt_intermediate_size": 4304,
19
+ "merge_kernel_size": [
20
+ 2,
21
+ 2
22
+ ],
23
+ "video_attn_type": "spatial_temporal",
24
+ "merge_type": "sd2_tpool",
25
+ "mm_projector_type": "patchmerger",
26
+ "mm_hidden_size": 1152,
27
+ "projector_hidden_act": "gelu",
28
+ "projector_ln_eps": 1e-05,
29
+ "text_hidden_size": 6144
30
+ },
31
+ "text_config": {
32
+ "hidden_size": 6144
33
+ },
34
+ "media_placeholder_token_id": 154854,
35
+ "original_dtype": "bfloat16",
36
+ "num_tensors": 335
37
+ }
glm52_vision.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:18e6e27be3c1a46951dd6812c4b29a18469a6ddcf5483790c93a18419e2a6d52
3
+ size 932887076
glm52_vision.safetensors.index.json ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 932887076
4
+ },
5
+ "weight_map": {
6
+ "vision_tower.patch_embed.proj.weight": "glm52_vision.safetensors",
7
+ "vision_tower.patch_embed.proj.bias": "glm52_vision.safetensors",
8
+ "vision_tower.patch_embed.pos_emb.weight": "glm52_vision.safetensors",
9
+ "vision_tower.encoder.final_layernorm.weight": "glm52_vision.safetensors",
10
+ "vision_tower.encoder.blocks.9.wqkv.weight": "glm52_vision.safetensors",
11
+ "vision_tower.encoder.blocks.9.mlp.fc1.weight": "glm52_vision.safetensors",
12
+ "vision_tower.encoder.blocks.9.mlp.fc1.bias": "glm52_vision.safetensors",
13
+ "vision_tower.encoder.blocks.9.mlp.fc0.bias": "glm52_vision.safetensors",
14
+ "vision_tower.encoder.blocks.8.wqkv.bias": "glm52_vision.safetensors",
15
+ "vision_tower.encoder.blocks.8.norm1.weight": "glm52_vision.safetensors",
16
+ "vision_tower.encoder.blocks.8.norm0.bias": "glm52_vision.safetensors",
17
+ "vision_tower.encoder.blocks.8.mlp.fc1.weight": "glm52_vision.safetensors",
18
+ "vision_tower.encoder.blocks.8.mlp.fc1.bias": "glm52_vision.safetensors",
19
+ "vision_tower.encoder.blocks.7.wqkv.weight": "glm52_vision.safetensors",
20
+ "vision_tower.encoder.blocks.7.wo.weight": "glm52_vision.safetensors",
21
+ "vision_tower.encoder.blocks.7.wo.bias": "glm52_vision.safetensors",
22
+ "vision_tower.encoder.blocks.7.norm1.weight": "glm52_vision.safetensors",
23
+ "vision_tower.encoder.blocks.7.norm1.bias": "glm52_vision.safetensors",
24
+ "vision_tower.encoder.blocks.9.wo.bias": "glm52_vision.safetensors",
25
+ "vision_tower.encoder.blocks.7.norm0.weight": "glm52_vision.safetensors",
26
+ "vision_tower.encoder.blocks.7.norm0.bias": "glm52_vision.safetensors",
27
+ "vision_tower.encoder.blocks.7.mlp.fc1.weight": "glm52_vision.safetensors",
28
+ "vision_tower.encoder.blocks.7.mlp.fc1.bias": "glm52_vision.safetensors",
29
+ "vision_tower.encoder.blocks.7.mlp.fc0.bias": "glm52_vision.safetensors",
30
+ "vision_tower.encoder.blocks.6.norm1.weight": "glm52_vision.safetensors",
31
+ "vision_tower.encoder.blocks.5.norm1.bias": "glm52_vision.safetensors",
32
+ "vision_tower.encoder.blocks.5.norm0.bias": "glm52_vision.safetensors",
33
+ "vision_tower.encoder.blocks.5.mlp.fc0.weight": "glm52_vision.safetensors",
34
+ "vision_tower.encoder.blocks.4.wo.weight": "glm52_vision.safetensors",
35
+ "vision_tower.encoder.blocks.4.wo.bias": "glm52_vision.safetensors",
36
+ "vision_tower.encoder.blocks.4.norm0.weight": "glm52_vision.safetensors",
37
+ "vision_tower.encoder.blocks.7.wqkv.bias": "glm52_vision.safetensors",
38
+ "vision_tower.encoder.blocks.4.mlp.fc1.weight": "glm52_vision.safetensors",
39
+ "vision_tower.encoder.blocks.4.mlp.fc1.bias": "glm52_vision.safetensors",
40
+ "vision_tower.encoder.blocks.4.mlp.fc0.weight": "glm52_vision.safetensors",
41
+ "vision_tower.encoder.blocks.3.wqkv.weight": "glm52_vision.safetensors",
42
+ "vision_tower.encoder.blocks.3.wo.weight": "glm52_vision.safetensors",
43
+ "vision_tower.encoder.blocks.6.norm0.bias": "glm52_vision.safetensors",
44
+ "vision_tower.encoder.blocks.3.wo.bias": "glm52_vision.safetensors",
45
+ "vision_tower.encoder.blocks.3.norm1.weight": "glm52_vision.safetensors",
46
+ "vision_tower.encoder.blocks.3.norm1.bias": "glm52_vision.safetensors",
47
+ "vision_tower.encoder.blocks.3.norm0.weight": "glm52_vision.safetensors",
48
+ "vision_tower.encoder.blocks.5.norm1.weight": "glm52_vision.safetensors",
49
+ "vision_tower.encoder.blocks.26.wo.bias": "glm52_vision.safetensors",
50
+ "vision_tower.encoder.blocks.26.norm1.bias": "glm52_vision.safetensors",
51
+ "vision_tower.encoder.blocks.26.norm0.weight": "glm52_vision.safetensors",
52
+ "vision_tower.encoder.blocks.26.norm0.bias": "glm52_vision.safetensors",
53
+ "vision_tower.encoder.blocks.26.mlp.fc1.weight": "glm52_vision.safetensors",
54
+ "vision_tower.encoder.blocks.26.mlp.fc0.weight": "glm52_vision.safetensors",
55
+ "vision_tower.encoder.blocks.25.wqkv.weight": "glm52_vision.safetensors",
56
+ "vision_tower.encoder.blocks.25.wqkv.bias": "glm52_vision.safetensors",
57
+ "vision_tower.encoder.blocks.25.norm1.bias": "glm52_vision.safetensors",
58
+ "vision_tower.encoder.blocks.25.norm0.bias": "glm52_vision.safetensors",
59
+ "vision_tower.encoder.blocks.9.norm1.bias": "glm52_vision.safetensors",
60
+ "vision_tower.encoder.blocks.25.mlp.fc1.weight": "glm52_vision.safetensors",
61
+ "vision_tower.encoder.blocks.6.mlp.fc1.weight": "glm52_vision.safetensors",
62
+ "vision_tower.encoder.blocks.25.mlp.fc0.weight": "glm52_vision.safetensors",
63
+ "vision_tower.encoder.blocks.9.norm1.weight": "glm52_vision.safetensors",
64
+ "vision_tower.encoder.blocks.24.wo.weight": "glm52_vision.safetensors",
65
+ "vision_tower.encoder.blocks.24.norm1.weight": "glm52_vision.safetensors",
66
+ "vision_tower.encoder.blocks.24.norm0.weight": "glm52_vision.safetensors",
67
+ "vision_tower.encoder.blocks.6.norm1.bias": "glm52_vision.safetensors",
68
+ "vision_tower.encoder.blocks.24.mlp.fc1.weight": "glm52_vision.safetensors",
69
+ "vision_tower.encoder.blocks.23.wqkv.weight": "glm52_vision.safetensors",
70
+ "vision_tower.encoder.blocks.23.wqkv.bias": "glm52_vision.safetensors",
71
+ "vision_tower.encoder.blocks.23.wo.weight": "glm52_vision.safetensors",
72
+ "vision_tower.encoder.blocks.23.mlp.fc1.weight": "glm52_vision.safetensors",
73
+ "vision_tower.encoder.blocks.23.mlp.fc1.bias": "glm52_vision.safetensors",
74
+ "vision_tower.encoder.blocks.23.mlp.fc0.weight": "glm52_vision.safetensors",
75
+ "vision_tower.encoder.blocks.17.mlp.fc0.weight": "glm52_vision.safetensors",
76
+ "vision_tower.encoder.blocks.22.wqkv.bias": "glm52_vision.safetensors",
77
+ "vision_tower.encoder.blocks.22.wo.weight": "glm52_vision.safetensors",
78
+ "vision_tower.encoder.blocks.22.mlp.fc1.bias": "glm52_vision.safetensors",
79
+ "vision_tower.encoder.blocks.24.mlp.fc0.bias": "glm52_vision.safetensors",
80
+ "vision_tower.encoder.blocks.21.wqkv.weight": "glm52_vision.safetensors",
81
+ "vision_tower.encoder.blocks.11.mlp.fc0.bias": "glm52_vision.safetensors",
82
+ "vision_tower.encoder.blocks.21.wqkv.bias": "glm52_vision.safetensors",
83
+ "vision_tower.encoder.blocks.21.wo.weight": "glm52_vision.safetensors",
84
+ "vision_tower.encoder.blocks.23.wo.bias": "glm52_vision.safetensors",
85
+ "vision_tower.encoder.blocks.18.mlp.fc0.bias": "glm52_vision.safetensors",
86
+ "vision_tower.encoder.blocks.21.wo.bias": "glm52_vision.safetensors",
87
+ "vision_tower.encoder.blocks.3.wqkv.bias": "glm52_vision.safetensors",
88
+ "vision_tower.encoder.blocks.18.norm0.bias": "glm52_vision.safetensors",
89
+ "vision_tower.encoder.blocks.21.norm0.bias": "glm52_vision.safetensors",
90
+ "vision_tower.encoder.blocks.21.mlp.fc0.weight": "glm52_vision.safetensors",
91
+ "vision_tower.encoder.blocks.2.mlp.fc0.weight": "glm52_vision.safetensors",
92
+ "vision_tower.encoder.blocks.20.wqkv.weight": "glm52_vision.safetensors",
93
+ "vision_tower.encoder.blocks.10.mlp.fc1.weight": "glm52_vision.safetensors",
94
+ "vision_tower.encoder.blocks.13.norm0.weight": "glm52_vision.safetensors",
95
+ "vision_tower.encoder.blocks.20.wo.bias": "glm52_vision.safetensors",
96
+ "vision_tower.encoder.blocks.24.wqkv.bias": "glm52_vision.safetensors",
97
+ "vision_tower.encoder.blocks.20.mlp.fc1.bias": "glm52_vision.safetensors",
98
+ "vision_tower.encoder.blocks.20.mlp.fc0.weight": "glm52_vision.safetensors",
99
+ "vision_tower.encoder.blocks.15.mlp.fc0.weight": "glm52_vision.safetensors",
100
+ "vision_tower.encoder.blocks.20.mlp.fc0.bias": "glm52_vision.safetensors",
101
+ "vision_tower.encoder.blocks.26.wqkv.bias": "glm52_vision.safetensors",
102
+ "vision_tower.encoder.blocks.2.wqkv.weight": "glm52_vision.safetensors",
103
+ "vision_tower.encoder.blocks.3.norm0.bias": "glm52_vision.safetensors",
104
+ "vision_tower.encoder.blocks.2.mlp.fc1.weight": "glm52_vision.safetensors",
105
+ "vision_tower.encoder.blocks.2.wqkv.bias": "glm52_vision.safetensors",
106
+ "vision_tower.encoder.blocks.6.wo.bias": "glm52_vision.safetensors",
107
+ "vision_tower.encoder.blocks.20.norm0.weight": "glm52_vision.safetensors",
108
+ "vision_tower.encoder.blocks.2.wo.weight": "glm52_vision.safetensors",
109
+ "vision_tower.encoder.blocks.5.mlp.fc0.bias": "glm52_vision.safetensors",
110
+ "vision_tower.encoder.blocks.0.norm1.bias": "glm52_vision.safetensors",
111
+ "vision_tower.encoder.blocks.2.wo.bias": "glm52_vision.safetensors",
112
+ "vision_tower.encoder.blocks.22.norm1.weight": "glm52_vision.safetensors",
113
+ "vision_tower.encoder.blocks.8.wqkv.weight": "glm52_vision.safetensors",
114
+ "vision_tower.encoder.blocks.5.wo.weight": "glm52_vision.safetensors",
115
+ "vision_tower.encoder.blocks.2.norm1.bias": "glm52_vision.safetensors",
116
+ "vision_tower.encoder.blocks.7.mlp.fc0.weight": "glm52_vision.safetensors",
117
+ "vision_tower.encoder.blocks.2.norm0.weight": "glm52_vision.safetensors",
118
+ "vision_tower.encoder.blocks.3.mlp.fc0.weight": "glm52_vision.safetensors",
119
+ "vision_tower.encoder.blocks.2.norm0.bias": "glm52_vision.safetensors",
120
+ "vision_tower.encoder.blocks.9.wo.weight": "glm52_vision.safetensors",
121
+ "vision_tower.encoder.blocks.19.norm1.weight": "glm52_vision.safetensors",
122
+ "vision_tower.encoder.blocks.11.mlp.fc1.weight": "glm52_vision.safetensors",
123
+ "vision_tower.encoder.blocks.21.norm0.weight": "glm52_vision.safetensors",
124
+ "vision_tower.encoder.blocks.20.wo.weight": "glm52_vision.safetensors",
125
+ "vision_tower.encoder.blocks.5.mlp.fc1.weight": "glm52_vision.safetensors",
126
+ "vision_tower.encoder.blocks.19.norm1.bias": "glm52_vision.safetensors",
127
+ "vision_tower.encoder.blocks.19.norm0.bias": "glm52_vision.safetensors",
128
+ "vision_tower.encoder.blocks.4.norm1.bias": "glm52_vision.safetensors",
129
+ "vision_tower.encoder.blocks.19.mlp.fc1.weight": "glm52_vision.safetensors",
130
+ "vision_tower.encoder.blocks.18.wqkv.weight": "glm52_vision.safetensors",
131
+ "vision_tower.encoder.blocks.8.mlp.fc0.bias": "glm52_vision.safetensors",
132
+ "vision_tower.encoder.blocks.18.wqkv.bias": "glm52_vision.safetensors",
133
+ "vision_tower.encoder.blocks.8.mlp.fc0.weight": "glm52_vision.safetensors",
134
+ "vision_tower.encoder.blocks.18.wo.bias": "glm52_vision.safetensors",
135
+ "vision_tower.encoder.blocks.18.norm0.weight": "glm52_vision.safetensors",
136
+ "vision_tower.encoder.blocks.0.mlp.fc1.weight": "glm52_vision.safetensors",
137
+ "vision_tower.encoder.blocks.18.mlp.fc1.bias": "glm52_vision.safetensors",
138
+ "vision_tower.encoder.blocks.4.wqkv.weight": "glm52_vision.safetensors",
139
+ "vision_tower.encoder.blocks.11.wqkv.weight": "glm52_vision.safetensors",
140
+ "vision_tower.encoder.blocks.17.wo.weight": "glm52_vision.safetensors",
141
+ "vision_tower.encoder.blocks.17.wo.bias": "glm52_vision.safetensors",
142
+ "vision_tower.encoder.blocks.24.wqkv.weight": "glm52_vision.safetensors",
143
+ "vision_tower.encoder.blocks.15.wqkv.bias": "glm52_vision.safetensors",
144
+ "vision_tower.encoder.blocks.17.norm1.bias": "glm52_vision.safetensors",
145
+ "vision_tower.encoder.blocks.17.norm0.weight": "glm52_vision.safetensors",
146
+ "vision_tower.encoder.blocks.17.norm0.bias": "glm52_vision.safetensors",
147
+ "vision_tower.encoder.blocks.24.norm1.bias": "glm52_vision.safetensors",
148
+ "vision_tower.encoder.blocks.13.mlp.fc1.bias": "glm52_vision.safetensors",
149
+ "vision_tower.encoder.blocks.17.mlp.fc1.bias": "glm52_vision.safetensors",
150
+ "vision_tower.encoder.blocks.26.mlp.fc0.bias": "glm52_vision.safetensors",
151
+ "vision_tower.encoder.blocks.14.norm0.bias": "glm52_vision.safetensors",
152
+ "vision_tower.encoder.blocks.17.mlp.fc0.bias": "glm52_vision.safetensors",
153
+ "vision_tower.encoder.blocks.8.norm0.weight": "glm52_vision.safetensors",
154
+ "vision_tower.encoder.blocks.10.mlp.fc0.weight": "glm52_vision.safetensors",
155
+ "vision_tower.encoder.blocks.16.wqkv.weight": "glm52_vision.safetensors",
156
+ "vision_tower.encoder.blocks.6.norm0.weight": "glm52_vision.safetensors",
157
+ "vision_tower.encoder.blocks.10.mlp.fc1.bias": "glm52_vision.safetensors",
158
+ "vision_tower.encoder.blocks.19.wo.weight": "glm52_vision.safetensors",
159
+ "vision_tower.encoder.blocks.18.wo.weight": "glm52_vision.safetensors",
160
+ "vision_tower.encoder.blocks.17.norm1.weight": "glm52_vision.safetensors",
161
+ "vision_tower.encoder.blocks.16.wo.weight": "glm52_vision.safetensors",
162
+ "vision_tower.encoder.blocks.1.mlp.fc1.bias": "glm52_vision.safetensors",
163
+ "vision_tower.encoder.blocks.14.norm1.bias": "glm52_vision.safetensors",
164
+ "vision_tower.encoder.blocks.20.norm0.bias": "glm52_vision.safetensors",
165
+ "vision_tower.encoder.blocks.0.mlp.fc0.bias": "glm52_vision.safetensors",
166
+ "vision_tower.encoder.blocks.19.mlp.fc1.bias": "glm52_vision.safetensors",
167
+ "vision_tower.encoder.blocks.23.norm0.weight": "glm52_vision.safetensors",
168
+ "vision_tower.encoder.blocks.12.mlp.fc0.bias": "glm52_vision.safetensors",
169
+ "vision_tower.encoder.blocks.16.norm1.weight": "glm52_vision.safetensors",
170
+ "vision_tower.encoder.blocks.6.wqkv.weight": "glm52_vision.safetensors",
171
+ "vision_tower.encoder.blocks.3.mlp.fc1.bias": "glm52_vision.safetensors",
172
+ "vision_tower.encoder.blocks.25.wo.bias": "glm52_vision.safetensors",
173
+ "vision_tower.encoder.blocks.12.norm1.bias": "glm52_vision.safetensors",
174
+ "vision_tower.encoder.blocks.12.norm0.bias": "glm52_vision.safetensors",
175
+ "vision_tower.encoder.blocks.16.norm1.bias": "glm52_vision.safetensors",
176
+ "vision_tower.encoder.blocks.5.mlp.fc1.bias": "glm52_vision.safetensors",
177
+ "vision_tower.encoder.blocks.21.norm1.bias": "glm52_vision.safetensors",
178
+ "vision_tower.encoder.blocks.24.norm0.bias": "glm52_vision.safetensors",
179
+ "vision_tower.encoder.blocks.16.norm0.bias": "glm52_vision.safetensors",
180
+ "vision_tower.encoder.blocks.21.mlp.fc1.weight": "glm52_vision.safetensors",
181
+ "vision_tower.encoder.blocks.6.wqkv.bias": "glm52_vision.safetensors",
182
+ "vision_tower.encoder.blocks.26.wo.weight": "glm52_vision.safetensors",
183
+ "vision_tower.encoder.blocks.16.mlp.fc1.weight": "glm52_vision.safetensors",
184
+ "vision_tower.encoder.blocks.23.norm1.weight": "glm52_vision.safetensors",
185
+ "vision_tower.encoder.blocks.16.mlp.fc1.bias": "glm52_vision.safetensors",
186
+ "vision_tower.encoder.blocks.18.mlp.fc1.weight": "glm52_vision.safetensors",
187
+ "vision_tower.encoder.blocks.16.mlp.fc0.bias": "glm52_vision.safetensors",
188
+ "vision_tower.encoder.blocks.0.mlp.fc0.weight": "glm52_vision.safetensors",
189
+ "vision_tower.encoder.blocks.22.norm0.bias": "glm52_vision.safetensors",
190
+ "vision_tower.encoder.blocks.20.norm1.bias": "glm52_vision.safetensors",
191
+ "vision_tower.encoder.blocks.22.mlp.fc1.weight": "glm52_vision.safetensors",
192
+ "vision_tower.encoder.blocks.19.wqkv.bias": "glm52_vision.safetensors",
193
+ "vision_tower.encoder.blocks.8.norm1.bias": "glm52_vision.safetensors",
194
+ "vision_tower.encoder.blocks.15.wo.weight": "glm52_vision.safetensors",
195
+ "vision_tower.encoder.blocks.15.wo.bias": "glm52_vision.safetensors",
196
+ "vision_tower.encoder.blocks.24.mlp.fc1.bias": "glm52_vision.safetensors",
197
+ "vision_tower.encoder.blocks.15.norm1.weight": "glm52_vision.safetensors",
198
+ "vision_tower.encoder.blocks.25.mlp.fc0.bias": "glm52_vision.safetensors",
199
+ "vision_tower.encoder.blocks.15.mlp.fc1.weight": "glm52_vision.safetensors",
200
+ "vision_tower.encoder.final_layernorm.bias": "glm52_vision.safetensors",
201
+ "vision_tower.encoder.blocks.15.mlp.fc1.bias": "glm52_vision.safetensors",
202
+ "vision_tower.encoder.blocks.15.norm1.bias": "glm52_vision.safetensors",
203
+ "vision_tower.encoder.blocks.18.norm1.weight": "glm52_vision.safetensors",
204
+ "vision_tower.encoder.blocks.15.mlp.fc0.bias": "glm52_vision.safetensors",
205
+ "vision_tower.encoder.blocks.20.wqkv.bias": "glm52_vision.safetensors",
206
+ "vision_tower.encoder.blocks.14.mlp.fc1.bias": "glm52_vision.safetensors",
207
+ "vision_tower.encoder.blocks.13.wqkv.weight": "glm52_vision.safetensors",
208
+ "vision_tower.encoder.blocks.13.wqkv.bias": "glm52_vision.safetensors",
209
+ "vision_tower.encoder.blocks.13.wo.weight": "glm52_vision.safetensors",
210
+ "vision_tower.encoder.blocks.17.mlp.fc1.weight": "glm52_vision.safetensors",
211
+ "vision_tower.encoder.blocks.15.wqkv.weight": "glm52_vision.safetensors",
212
+ "vision_tower.encoder.blocks.14.mlp.fc0.bias": "glm52_vision.safetensors",
213
+ "vision_tower.encoder.blocks.22.wqkv.weight": "glm52_vision.safetensors",
214
+ "vision_tower.encoder.blocks.14.wqkv.bias": "glm52_vision.safetensors",
215
+ "vision_tower.encoder.blocks.25.wo.weight": "glm52_vision.safetensors",
216
+ "vision_tower.encoder.blocks.22.mlp.fc0.weight": "glm52_vision.safetensors",
217
+ "vision_tower.encoder.blocks.13.norm1.weight": "glm52_vision.safetensors",
218
+ "vision_tower.encoder.blocks.22.norm1.bias": "glm52_vision.safetensors",
219
+ "vision_tower.encoder.blocks.5.wo.bias": "glm52_vision.safetensors",
220
+ "vision_tower.encoder.blocks.17.wqkv.weight": "glm52_vision.safetensors",
221
+ "vision_tower.encoder.blocks.12.wo.weight": "glm52_vision.safetensors",
222
+ "vision_tower.encoder.blocks.14.norm0.weight": "glm52_vision.safetensors",
223
+ "vision_tower.encoder.blocks.21.norm1.weight": "glm52_vision.safetensors",
224
+ "vision_tower.encoder.blocks.11.wo.bias": "glm52_vision.safetensors",
225
+ "vision_tower.encoder.blocks.13.mlp.fc0.weight": "glm52_vision.safetensors",
226
+ "vision_tower.encoder.blocks.12.wqkv.weight": "glm52_vision.safetensors",
227
+ "vision_tower.encoder.blocks.17.wqkv.bias": "glm52_vision.safetensors",
228
+ "vision_tower.encoder.blocks.14.wqkv.weight": "glm52_vision.safetensors",
229
+ "vision_tower.encoder.blocks.13.mlp.fc1.weight": "glm52_vision.safetensors",
230
+ "vision_tower.encoder.blocks.9.norm0.weight": "glm52_vision.safetensors",
231
+ "vision_tower.encoder.blocks.4.norm1.weight": "glm52_vision.safetensors",
232
+ "vision_tower.encoder.blocks.12.wqkv.bias": "glm52_vision.safetensors",
233
+ "vision_tower.encoder.blocks.2.norm1.weight": "glm52_vision.safetensors",
234
+ "vision_tower.encoder.blocks.26.wqkv.weight": "glm52_vision.safetensors",
235
+ "vision_tower.encoder.blocks.19.norm0.weight": "glm52_vision.safetensors",
236
+ "vision_tower.encoder.blocks.12.norm1.weight": "glm52_vision.safetensors",
237
+ "vision_tower.encoder.blocks.1.norm0.weight": "glm52_vision.safetensors",
238
+ "vision_tower.encoder.blocks.23.norm0.bias": "glm52_vision.safetensors",
239
+ "vision_tower.encoder.blocks.19.mlp.fc0.weight": "glm52_vision.safetensors",
240
+ "vision_tower.encoder.blocks.14.mlp.fc1.weight": "glm52_vision.safetensors",
241
+ "vision_tower.encoder.blocks.15.norm0.weight": "glm52_vision.safetensors",
242
+ "vision_tower.encoder.blocks.13.norm0.bias": "glm52_vision.safetensors",
243
+ "vision_tower.encoder.blocks.10.wo.weight": "glm52_vision.safetensors",
244
+ "vision_tower.encoder.blocks.22.norm0.weight": "glm52_vision.safetensors",
245
+ "vision_tower.encoder.blocks.12.mlp.fc1.bias": "glm52_vision.safetensors",
246
+ "vision_tower.encoder.blocks.12.mlp.fc0.weight": "glm52_vision.safetensors",
247
+ "vision_tower.encoder.blocks.0.wo.weight": "glm52_vision.safetensors",
248
+ "vision_tower.encoder.blocks.25.mlp.fc1.bias": "glm52_vision.safetensors",
249
+ "vision_tower.encoder.blocks.13.norm1.bias": "glm52_vision.safetensors",
250
+ "vision_tower.encoder.blocks.3.mlp.fc1.weight": "glm52_vision.safetensors",
251
+ "vision_tower.encoder.blocks.20.mlp.fc1.weight": "glm52_vision.safetensors",
252
+ "vision_tower.encoder.blocks.6.mlp.fc0.weight": "glm52_vision.safetensors",
253
+ "vision_tower.encoder.blocks.11.wqkv.bias": "glm52_vision.safetensors",
254
+ "vision_tower.encoder.blocks.11.wo.weight": "glm52_vision.safetensors",
255
+ "vision_tower.encoder.blocks.11.norm0.weight": "glm52_vision.safetensors",
256
+ "vision_tower.encoder.blocks.19.wqkv.weight": "glm52_vision.safetensors",
257
+ "vision_tower.encoder.blocks.5.wqkv.bias": "glm52_vision.safetensors",
258
+ "vision_tower.encoder.blocks.11.mlp.fc0.weight": "glm52_vision.safetensors",
259
+ "vision_tower.encoder.blocks.5.wqkv.weight": "glm52_vision.safetensors",
260
+ "vision_tower.encoder.blocks.23.norm1.bias": "glm52_vision.safetensors",
261
+ "vision_tower.encoder.blocks.0.wo.bias": "glm52_vision.safetensors",
262
+ "vision_tower.encoder.blocks.5.norm0.weight": "glm52_vision.safetensors",
263
+ "vision_tower.encoder.blocks.16.wqkv.bias": "glm52_vision.safetensors",
264
+ "vision_tower.encoder.blocks.15.norm0.bias": "glm52_vision.safetensors",
265
+ "vision_tower.encoder.blocks.4.mlp.fc0.bias": "glm52_vision.safetensors",
266
+ "vision_tower.encoder.blocks.1.wo.bias": "glm52_vision.safetensors",
267
+ "vision_tower.encoder.blocks.9.mlp.fc0.weight": "glm52_vision.safetensors",
268
+ "vision_tower.encoder.blocks.25.norm0.weight": "glm52_vision.safetensors",
269
+ "vision_tower.encoder.blocks.20.norm1.weight": "glm52_vision.safetensors",
270
+ "vision_tower.encoder.blocks.12.wo.bias": "glm52_vision.safetensors",
271
+ "vision_tower.encoder.blocks.26.mlp.fc1.bias": "glm52_vision.safetensors",
272
+ "vision_tower.encoder.blocks.10.wqkv.bias": "glm52_vision.safetensors",
273
+ "vision_tower.encoder.blocks.22.mlp.fc0.bias": "glm52_vision.safetensors",
274
+ "vision_tower.encoder.blocks.10.norm1.weight": "glm52_vision.safetensors",
275
+ "vision_tower.encoder.blocks.14.wo.weight": "glm52_vision.safetensors",
276
+ "vision_tower.encoder.blocks.6.mlp.fc1.bias": "glm52_vision.safetensors",
277
+ "vision_tower.encoder.blocks.10.norm0.weight": "glm52_vision.safetensors",
278
+ "vision_tower.encoder.blocks.4.norm0.bias": "glm52_vision.safetensors",
279
+ "vision_tower.encoder.blocks.2.mlp.fc1.bias": "glm52_vision.safetensors",
280
+ "vision_tower.encoder.blocks.10.norm0.bias": "glm52_vision.safetensors",
281
+ "vision_tower.encoder.blocks.10.mlp.fc0.bias": "glm52_vision.safetensors",
282
+ "vision_tower.encoder.blocks.26.norm1.weight": "glm52_vision.safetensors",
283
+ "vision_tower.encoder.blocks.21.mlp.fc0.bias": "glm52_vision.safetensors",
284
+ "vision_tower.encoder.blocks.16.mlp.fc0.weight": "glm52_vision.safetensors",
285
+ "vision_tower.encoder.blocks.4.wqkv.bias": "glm52_vision.safetensors",
286
+ "vision_tower.encoder.blocks.1.norm1.weight": "glm52_vision.safetensors",
287
+ "vision_tower.encoder.blocks.13.mlp.fc0.bias": "glm52_vision.safetensors",
288
+ "vision_tower.encoder.blocks.8.wo.weight": "glm52_vision.safetensors",
289
+ "vision_tower.encoder.blocks.1.wo.weight": "glm52_vision.safetensors",
290
+ "vision_tower.encoder.blocks.19.wo.bias": "glm52_vision.safetensors",
291
+ "vision_tower.encoder.blocks.9.wqkv.bias": "glm52_vision.safetensors",
292
+ "vision_tower.encoder.blocks.11.norm0.bias": "glm52_vision.safetensors",
293
+ "vision_tower.encoder.blocks.11.norm1.weight": "glm52_vision.safetensors",
294
+ "vision_tower.encoder.blocks.1.norm1.bias": "glm52_vision.safetensors",
295
+ "vision_tower.encoder.blocks.0.wqkv.weight": "glm52_vision.safetensors",
296
+ "vision_tower.encoder.blocks.25.norm1.weight": "glm52_vision.safetensors",
297
+ "vision_tower.encoder.blocks.2.mlp.fc0.bias": "glm52_vision.safetensors",
298
+ "vision_tower.encoder.blocks.16.norm0.weight": "glm52_vision.safetensors",
299
+ "vision_tower.encoder.blocks.3.mlp.fc0.bias": "glm52_vision.safetensors",
300
+ "vision_tower.encoder.blocks.24.wo.bias": "glm52_vision.safetensors",
301
+ "vision_tower.encoder.blocks.11.mlp.fc1.bias": "glm52_vision.safetensors",
302
+ "vision_tower.encoder.blocks.16.wo.bias": "glm52_vision.safetensors",
303
+ "vision_tower.encoder.blocks.1.norm0.bias": "glm52_vision.safetensors",
304
+ "vision_tower.encoder.blocks.1.mlp.fc0.weight": "glm52_vision.safetensors",
305
+ "vision_tower.encoder.blocks.14.norm1.weight": "glm52_vision.safetensors",
306
+ "vision_tower.encoder.blocks.18.norm1.bias": "glm52_vision.safetensors",
307
+ "vision_tower.encoder.blocks.1.mlp.fc1.weight": "glm52_vision.safetensors",
308
+ "vision_tower.encoder.blocks.11.norm1.bias": "glm52_vision.safetensors",
309
+ "vision_tower.encoder.blocks.12.norm0.weight": "glm52_vision.safetensors",
310
+ "vision_tower.encoder.blocks.0.norm1.weight": "glm52_vision.safetensors",
311
+ "vision_tower.encoder.blocks.0.norm0.weight": "glm52_vision.safetensors",
312
+ "vision_tower.encoder.blocks.0.norm0.bias": "glm52_vision.safetensors",
313
+ "vision_tower.encoder.blocks.1.wqkv.bias": "glm52_vision.safetensors",
314
+ "vision_tower.encoder.blocks.6.wo.weight": "glm52_vision.safetensors",
315
+ "vision_tower.encoder.blocks.0.wqkv.bias": "glm52_vision.safetensors",
316
+ "vision_tower.encoder.blocks.8.wo.bias": "glm52_vision.safetensors",
317
+ "vision_tower.encoder.blocks.23.mlp.fc0.bias": "glm52_vision.safetensors",
318
+ "vision_tower.encoder.blocks.18.mlp.fc0.weight": "glm52_vision.safetensors",
319
+ "vision_tower.encoder.blocks.9.norm0.bias": "glm52_vision.safetensors",
320
+ "vision_tower.encoder.blocks.22.wo.bias": "glm52_vision.safetensors",
321
+ "vision_tower.encoder.blocks.10.wo.bias": "glm52_vision.safetensors",
322
+ "vision_tower.encoder.blocks.13.wo.bias": "glm52_vision.safetensors",
323
+ "vision_tower.encoder.blocks.6.mlp.fc0.bias": "glm52_vision.safetensors",
324
+ "vision_tower.encoder.blocks.0.mlp.fc1.bias": "glm52_vision.safetensors",
325
+ "vision_tower.encoder.blocks.12.mlp.fc1.weight": "glm52_vision.safetensors",
326
+ "vision_tower.encoder.blocks.10.wqkv.weight": "glm52_vision.safetensors",
327
+ "vision_tower.encoder.blocks.24.mlp.fc0.weight": "glm52_vision.safetensors",
328
+ "vision_tower.encoder.blocks.21.mlp.fc1.bias": "glm52_vision.safetensors",
329
+ "vision_tower.encoder.blocks.1.wqkv.weight": "glm52_vision.safetensors",
330
+ "vision_tower.encoder.blocks.1.mlp.fc0.bias": "glm52_vision.safetensors",
331
+ "vision_tower.encoder.blocks.14.mlp.fc0.weight": "glm52_vision.safetensors",
332
+ "vision_tower.encoder.blocks.10.norm1.bias": "glm52_vision.safetensors",
333
+ "vision_tower.encoder.blocks.19.mlp.fc0.bias": "glm52_vision.safetensors",
334
+ "vision_tower.encoder.blocks.14.wo.bias": "glm52_vision.safetensors",
335
+ "mm_projector.pre_norm.weight": "glm52_vision.safetensors",
336
+ "mm_projector.linear_2.weight": "glm52_vision.safetensors",
337
+ "mm_projector.pre_norm.bias": "glm52_vision.safetensors",
338
+ "mm_projector.linear_2.bias": "glm52_vision.safetensors",
339
+ "mm_projector.linear_1.weight": "glm52_vision.safetensors",
340
+ "mm_projector.linear_1.bias": "glm52_vision.safetensors"
341
+ }
342
+ }
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)}")
preprocessor_config.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoProcessor": "kimi_k25_processor.KimiK25Processor",
4
+ "AutoImageProcessor": "kimi_k25_vision_processing.KimiK25VisionProcessor"
5
+ },
6
+ "media_proc_cfg": {
7
+ "in_patch_limit": 16384,
8
+ "patch_size": 14,
9
+ "image_mean": [
10
+ 0.5,
11
+ 0.5,
12
+ 0.5
13
+ ],
14
+ "image_std": [
15
+ 0.5,
16
+ 0.5,
17
+ 0.5
18
+ ],
19
+ "merge_kernel_size": 2,
20
+ "fixed_output_tokens": null,
21
+ "patch_limit_on_one_side": 512,
22
+ "in_patch_limit_each_frame": 16384,
23
+ "in_patch_limit_video": null,
24
+ "sample_fps": 2.0,
25
+ "max_num_frames_each_video": null,
26
+ "temporal_merge_kernel_size": 4,
27
+ "timestamp_mode": "hh:mm:ss.fff",
28
+ "config_type": "media_proc.processors.moonvit.MoonViTMediaProcessorConfig"
29
+ }
30
+ }