File size: 9,151 Bytes
c065523
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
#!/usr/bin/env python3
"""
Build a tiny slice of openbmb/MiniCPM-OCR-Jev (openbmb-minicpm-ocr-jev decision model) for testing. Output is gibberish, only the shapes and code paths are real.

Adapted from the slice-model skill of llama.cpp (skills/slice-model): tensors are fetched with HTTP range requests and config.json is
patched to match, then convert_hf_to_gguf.py does the conversion. The stock script only drops layers, which cannot go below the
248320 x 2048 token embedding, so this one also narrows the hidden sizes of the trunk, of the vision encoder and of the score head.

The config.json of the upstream repo declares Qwen3_5ForConditionalGeneration, the slice declares MiniCPMOCRForSequenceClassification
so that convert_hf_to_gguf.py picks the sequence classifier (the upstream repo has no LICENSE file, it is Apache-2.0 per its model card).

usage: slice_minicpm_ocr_jev.py <output dir>
"""
import json, re, struct, sys
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

import requests
import torch
from huggingface_hub import hf_hub_url
from safetensors.torch import save_file

REPO = 'openbmb/MiniCPM-OCR-Jev'
AUX = ['tokenizer.json', 'tokenizer_config.json', 'chat_template.jinja', 'processor_config.json', 'preprocessor_config.json', 'generation_config.json']

# text: hidden, ffn, attention heads, kv heads (head_dim stays 256), linear attention key / value heads (head dims stay 128)
E, FF, H, KV, LK, LV = 32, 128, 2, 1, 2, 2   # upstream has as many key heads as value heads
HD, LKD, LVD = 256, 128, 128
TEXT_LAYERS = [0, 1, 2, 3]           # 3 linear attention + 1 full attention
# vision: hidden, ffn, heads (head_dim stays 64)
V, VFF, VH = 128, 256, 2
VISION_LAYERS = [0, 1]
MERGE = 4                            # 2 x 2 patches are merged

DTYPES = {'BF16': torch.bfloat16, 'F32': torch.float32, 'F16': torch.float16}


def read_header(url):
    def rng(a, b):
        r = requests.get(url, headers={'Range': f'bytes={a}-{b}'}, timeout=120)
        r.raise_for_status()
        return r.content
    n = struct.unpack('<Q', rng(0, 7))[0]
    h = json.loads(rng(8, 8 + n - 1))
    h.pop('__metadata__', None)
    return h, 8 + n


def fetch(url, meta, base):
    a, b = meta['data_offsets']
    if a == b:
        return torch.zeros(meta['shape'], dtype=DTYPES[meta['dtype']])
    r = requests.get(url, headers={'Range': f'bytes={base + a}-{base + b - 1}'}, timeout=600)
    r.raise_for_status()
    assert len(r.content) == b - a
    return torch.frombuffer(bytearray(r.content), dtype=DTYPES[meta['dtype']]).reshape(meta['shape'])


def renumber(name, prefix, keep):
    m = re.match(re.escape(prefix) + r'\.(\d+)\.(.*)', name)
    if not m:
        return name
    i = int(m[1])
    return f'{prefix}.{keep.index(i)}.{m[2]}' if i in keep else None


def rename_main(n):
    for prefix, keep in (('model.language_model.layers', TEXT_LAYERS), ('model.visual.blocks', VISION_LAYERS)):
        if n.startswith(prefix + '.'):
            return renumber(n, prefix, keep)
    if n.startswith('mtp.'):
        return None
    return n


def linear_qkv_rows(t, nk, nv):
    """in_proj_qkv / conv1d: q (nk * dk), k (nk * dk), v (nv * dv) stacked on dim 0, v heads grouped by key head."""
    q, k, v = torch.split(t, [nk * LKD, nk * LKD, nv * LVD], dim=0)
    return torch.cat([q[:LK * LKD], k[:LK * LKD], v[:LV * LVD]], dim=0)


def narrow_text_layer(key, t, nk, nv):
    if key.endswith(('input_layernorm.weight', 'post_attention_layernorm.weight')):
        return t[:E]
    if key.endswith(('mlp.gate_proj.weight', 'mlp.up_proj.weight')):
        return t[:FF, :E]
    if key.endswith('mlp.down_proj.weight'):
        return t[:E, :FF]
    # full attention, q_proj has the output gate: [n_head, 2 * head_dim] per head
    if key.endswith('self_attn.q_proj.weight'):
        return t[:H * 2 * HD, :E]
    if key.endswith(('self_attn.k_proj.weight', 'self_attn.v_proj.weight')):
        return t[:KV * HD, :E]
    if key.endswith('self_attn.o_proj.weight'):
        return t[:E, :H * HD]
    if key.endswith(('self_attn.q_norm.weight', 'self_attn.k_norm.weight', 'linear_attn.norm.weight')):
        return t
    # linear attention (gated delta net)
    if key.endswith('linear_attn.in_proj_qkv.weight'):
        return linear_qkv_rows(t, nk, nv)[:, :E]
    if key.endswith('linear_attn.conv1d.weight'):
        return linear_qkv_rows(t, nk, nv)
    if key.endswith('linear_attn.in_proj_z.weight'):
        return t[:LV * LVD, :E]
    if key.endswith(('linear_attn.in_proj_a.weight', 'linear_attn.in_proj_b.weight')):
        return t[:LV, :E]
    if key.endswith(('linear_attn.A_log', 'linear_attn.dt_bias')):
        return t[:LV]
    if key.endswith('linear_attn.out_proj.weight'):
        return t[:E, :LV * LVD]
    raise SystemExit(f'unhandled tensor {key}')


def narrow_vision_block(key, t, vo):
    if key.endswith('attn.qkv.weight'):
        return t.reshape(3, vo, vo)[:, :V, :V].reshape(3 * V, V)
    if key.endswith('attn.qkv.bias'):
        return t.reshape(3, vo)[:, :V].reshape(-1)
    if key.endswith('attn.proj.weight'):
        return t[:V, :V]
    if key.endswith('mlp.linear_fc1.weight'):
        return t[:VFF, :V]
    if key.endswith('mlp.linear_fc1.bias'):
        return t[:VFF]
    if key.endswith('mlp.linear_fc2.weight'):
        return t[:V, :VFF]
    if key.endswith(('attn.proj.bias', 'mlp.linear_fc2.bias', 'norm1.weight', 'norm1.bias', 'norm2.weight', 'norm2.bias')):
        return t[:V]
    raise SystemExit(f'unhandled tensor {key}')


def make_narrow(text_cfg, vision_cfg):
    nk, nv = text_cfg['linear_num_key_heads'], text_cfg['linear_num_value_heads']
    vo = vision_cfg['hidden_size']

    def narrow(name, t):
        if name.startswith('model.language_model.layers.'):
            return narrow_text_layer(name, t, nk, nv)
        if name.startswith('model.visual.blocks.'):
            return narrow_vision_block(name, t, vo)
        table = {
            'model.language_model.embed_tokens.weight': lambda: t[:, :E],
            'score.weight': lambda: t[:, :E],  # [inconsistent, consistent] x hidden
            'model.language_model.norm.weight': lambda: t[:E],
            'model.visual.patch_embed.proj.weight': lambda: t[:V],
            'model.visual.patch_embed.proj.bias': lambda: t[:V],
            'model.visual.pos_embed.weight': lambda: t[:, :V],
            'model.visual.merger.norm.weight': lambda: t[:V],
            'model.visual.merger.norm.bias': lambda: t[:V],
            # the input of linear_fc1 is MERGE patches of the vision hidden size, its output has the same size
            'model.visual.merger.linear_fc1.weight': lambda: t[:MERGE * V].reshape(MERGE * V, MERGE, vo)[:, :, :V].reshape(MERGE * V, MERGE * V),
            'model.visual.merger.linear_fc1.bias': lambda: t[:MERGE * V],
            'model.visual.merger.linear_fc2.weight': lambda: t[:E, :MERGE * V],
            'model.visual.merger.linear_fc2.bias': lambda: t[:E],
        }
        if name in table:
            return table[name]()
        raise SystemExit(f'unhandled tensor {name}')
    return narrow


def slice_files(filenames, out_path, rename, transform):
    jobs = []
    n_total = 0
    for filename in filenames:
        url = hf_hub_url(REPO, filename)
        header, base = read_header(url)
        n_total += len(header)
        jobs += [(url, base, n, m, rename(n)) for n, m in header.items()]
    jobs = [j for j in jobs if j[4] is not None]

    def one(job):
        url, base, src, meta, dst = job
        return dst, transform(src, fetch(url, meta, base)).contiguous().clone()

    with ThreadPoolExecutor(8) as ex:
        tensors = dict(ex.map(one, jobs))
    out_path.parent.mkdir(parents=True, exist_ok=True)
    save_file(tensors, out_path, metadata={'format': 'pt'})
    print(f'{filenames}: {len(tensors)}/{n_total} tensors, {out_path.stat().st_size / 1e6:.1f} MB')


def get_json(f):
    r = requests.get(hf_hub_url(REPO, f), timeout=120)
    r.raise_for_status()
    return r.json()


def main():
    out = Path(sys.argv[1])
    out.mkdir(parents=True, exist_ok=True)
    cfg = get_json('config.json')
    slice_files(['model.safetensors'], out / 'model.safetensors', rename_main, make_narrow(cfg['text_config'], cfg['vision_config']))

    for f in AUX:
        r = requests.get(hf_hub_url(REPO, f), timeout=120)
        r.raise_for_status()
        (out / f).write_bytes(r.content)

    cfg['architectures'] = ['MiniCPMOCRForSequenceClassification']
    cfg['hidden_size'] = E
    t = cfg['text_config']
    t.update(hidden_size=E, intermediate_size=FF, num_attention_heads=H, num_key_value_heads=KV,
             linear_num_key_heads=LK, linear_num_value_heads=LV,
             num_hidden_layers=len(TEXT_LAYERS), layer_types=[t['layer_types'][i] for i in TEXT_LAYERS])
    v = cfg['vision_config']
    v.update(depth=len(VISION_LAYERS), hidden_size=V, intermediate_size=VFF, num_heads=VH, out_hidden_size=E,
             deepstack_visual_indexes=[i for i in v['deepstack_visual_indexes'] if i in VISION_LAYERS])
    (out / 'config.json').write_text(json.dumps(cfg, indent=2) + '\n')


main()