File size: 7,851 Bytes
70509c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
#!/usr/bin/env python
"""
01_export_quant.py
Gemma 4 E4B (gfp78/gemma4-bund-merged)  ->  ONNX-Decoder  ->  q4f16

Phasen:
  A) Modell laden (bf16 -> fp32 auf CPU/GPU)
  B) Cache-Layer + Head-Dims per Trockenlauf ermitteln (NICHT raten)
  C) torch.onnx.export (Legacy-Tracer, dynamo=False)
  D) Konsolidierung zu EINER .onnx_data (finaler Name direkt!)
  E) MatMul4BitsQuantizer -> q4f16
  F) Verifikation + Groessen-Check

Laufzeit-Schaetzung: A-D ~40 Min, E ~10-25 Min.
"""

import gc
import os
import shutil
import sys
from pathlib import Path

import torch
import onnx

os.environ.setdefault("HF_HOME", "/root/hf")

MODEL_ID = "gfp78/gemma4-bund-merged"
OUT = Path("/root/train/gemma4-bund-onnx")
OUT.mkdir(parents=True, exist_ok=True)

FP32_ONNX = OUT / "decoder_model_merged.onnx"
FP32_DATA = "decoder_model_merged.onnx_data"      # relativer Name, PFLICHT
Q4_ONNX = OUT / "decoder_model_merged_q4f16.onnx"
Q4_DATA = "decoder_model_merged_q4f16.onnx_data"


def log(msg):
    print(f"\n=== {msg}", flush=True)


# ---------------------------------------------------------------- A) laden
log("A) Modell laden")
from transformers import AutoTokenizer, AutoModelForImageTextToText, DynamicCache

tok = AutoTokenizer.from_pretrained(MODEL_ID)
model = AutoModelForImageTextToText.from_pretrained(
    MODEL_ID, dtype=torch.float32, device_map="cpu"
)
model.eval()

# Sprach-Turm + lm_head separat: language_model liefert nur last_hidden_state,
# die lm_head-Projektion sitzt eine Ebene hoeher.
lm = model.model.language_model
lm_head = model.lm_head if hasattr(model, "lm_head") else model.get_output_embeddings()
tcfg = lm.config
HIDDEN = tcfg.hidden_size
print("hidden_size:", HIDDEN)


# ------------------------------------------- B) Cache-Geometrie ermitteln
log("B) Trockenlauf: Anzahl Cache-Layer + Head-Dims ermitteln")
with torch.no_grad():
    probe_ids = torch.tensor([[1, 2, 3, 4]], dtype=torch.long)
    probe_emb = lm.get_input_embeddings()(probe_ids)
    probe = lm(inputs_embeds=probe_emb, use_cache=True, return_dict=True)

pkv = probe.past_key_values
N_CACHE = len(pkv.layers)          # transformers 5.13: .layers, nicht .key_cache
print("n_cache_layers:", N_CACHE)  # erwartet: 24 (nicht 42!)

# Gemma 4 hat ZWEI Head-Dims: 256 (sliding window) und 512 (full attention).
# Deshalb pro Layer die echte Form auslesen statt eine globale anzunehmen.
KV_SHAPES = []
for i in range(N_CACHE):
    k = pkv.layers[i].keys
    KV_SHAPES.append((int(k.shape[1]), int(k.shape[3])))  # (n_kv_heads, head_dim)
for i, s in enumerate(KV_SHAPES):
    print(f"  layer {i:2d}: n_kv_heads={s[0]}, head_dim={s[1]}")

del probe, pkv, probe_emb
gc.collect()


# ------------------------------------------------------------ C) Wrapper
class DecoderWrapper(torch.nn.Module):
    """inputs_embeds + attention_mask + position_ids + past -> logits + present"""

    def __init__(self, lm, lm_head, n_cache):
        super().__init__()
        self.lm = lm
        self.lm_head = lm_head
        self.n_cache = n_cache

    def forward(self, inputs_embeds, attention_mask, position_ids, *past):
        cache = None
        if len(past) == 2 * self.n_cache and past[0].shape[2] > 0:
            cache = DynamicCache(config=self.lm.config)
            for i in range(self.n_cache):
                cache.update(past[2 * i], past[2 * i + 1], i)

        out = self.lm(
            inputs_embeds=inputs_embeds,
            attention_mask=attention_mask,
            position_ids=position_ids,
            past_key_values=cache,
            use_cache=True,
            return_dict=True,
        )
        logits = self.lm_head(out.last_hidden_state)

        present = []
        for i in range(self.n_cache):
            present.append(out.past_key_values.layers[i].keys)
            present.append(out.past_key_values.layers[i].values)
        return (logits, *present)


wrapper = DecoderWrapper(lm, lm_head, N_CACHE).eval()

log("C) Dummy-Inputs bauen (P=1 Vergangenheit, S=1 neues Token)")
B, S, P = 1, 1, 1
dummy_embeds = torch.zeros(B, S, HIDDEN, dtype=torch.float32)
dummy_mask = torch.ones(B, P + S, dtype=torch.long)
dummy_pos = torch.tensor([[P]], dtype=torch.long)

# Pro Layer eigene Dummy-Form — 256 vs. 512 Head-Dim!
dummy_past = []
for (n_kv, hd) in KV_SHAPES:
    dummy_past.append(torch.zeros(B, n_kv, P, hd, dtype=torch.float32))
    dummy_past.append(torch.zeros(B, n_kv, P, hd, dtype=torch.float32))

input_names = ["inputs_embeds", "attention_mask", "position_ids"]
output_names = ["logits"]
dynamic_axes = {
    "inputs_embeds": {0: "batch", 1: "seq"},
    "attention_mask": {0: "batch", 1: "total"},
    "position_ids": {0: "batch", 1: "seq"},
    "logits": {0: "batch", 1: "seq"},
}
for i in range(N_CACHE):
    for kv in ("key", "value"):
        pn = f"past_key_values.{i}.{kv}"
        on = f"present.{i}.{kv}"
        input_names.append(pn)
        output_names.append(on)
        dynamic_axes[pn] = {0: "batch", 2: "past_seq"}
        dynamic_axes[on] = {0: "batch", 2: "total_seq"}

log("C) torch.onnx.export laeuft (dauert lange, kein Fortschrittsbalken)")
with torch.no_grad():
    torch.onnx.export(
        wrapper,
        (dummy_embeds, dummy_mask, dummy_pos, *dummy_past),
        str(FP32_ONNX),
        input_names=input_names,
        output_names=output_names,
        dynamic_axes=dynamic_axes,
        opset_version=17,
        do_constant_folding=True,
        dynamo=False,          # MUSS letztes Keyword bleiben
    )
print("Export geschrieben.")

del model, lm, lm_head, wrapper, dummy_past
gc.collect()


# --------------------------------------------------- D) Konsolidierung
log("D) Konsolidierung zu EINER .onnx_data (finaler Name direkt, nie umbenennen!)")
m = onnx.load(str(FP32_ONNX), load_external_data=True)
onnx.save_model(
    m,
    str(FP32_ONNX),
    save_as_external_data=True,
    all_tensors_to_one_file=True,
    location=FP32_DATA,
    size_threshold=1024,
)
del m
gc.collect()

# Fragment-Dateien aufraeumen (sonst laeuft die Disk voll)
for f in OUT.iterdir():
    if f.name.startswith("onnx__") or f.name.startswith("_"):
        f.unlink()
os.system(f"df -h /root; ls -la {OUT}")

onnx.checker.check_model(str(FP32_ONNX))
print("fp32-Graph valide.")


# ----------------------------------------------------- E) q4f16-Quantisierung
log("E) MatMul4BitsQuantizer -> q4f16 (der eine ungetestete Schritt)")
from onnxruntime.quantization.matmul_4bits_quantizer import (
    MatMul4BitsQuantizer,
    DefaultWeightOnlyQuantConfig,
)

model_fp32 = onnx.load(str(FP32_ONNX), load_external_data=True)

cfg = DefaultWeightOnlyQuantConfig(
    block_size=32,          # Transformers.js-kompatibel
    is_symmetric=True,
    accuracy_level=4,       # int8-Compute
)
quant = MatMul4BitsQuantizer(model_fp32, algo_config=cfg)
quant.process()

onnx.save_model(
    quant.model.model,
    str(Q4_ONNX),
    save_as_external_data=True,
    all_tensors_to_one_file=True,
    location=Q4_DATA,
    size_threshold=1024,
)
print("q4f16 geschrieben.")

del model_fp32, quant
gc.collect()


# --------------------------------------------------------- F) Verifikation
log("F) Verifikation")
onnx.checker.check_model(str(Q4_ONNX))

size_mb = (OUT / Q4_DATA).stat().st_size / 1e6
print(f"{Q4_DATA}: {size_mb:.0f} MB")
if size_mb > 3500:
    print("!! WARNUNG: >3.5 GB — Browser-ArrayBuffer-Limit gefaehrdet.")
else:
    print("OK: Groesse im browsertauglichen Bereich.")

import onnxruntime as ort

sess = ort.InferenceSession(str(Q4_ONNX), providers=["CPUExecutionProvider"])
print("Session laedt. Inputs:", len(sess.get_inputs()), "Outputs:", len(sess.get_outputs()))

log("FERTIG. Naechster Schritt: Tokenizer + config.json daneben legen,")
print("config.json braucht den transformers.js_config-Block mit")
print('  "use_external_data_format": true')
print("sonst wird die .onnx_data im Browser nie angefragt.")