File size: 11,545 Bytes
59be759
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""
07_export_quant_c_v2.py — WEG C, KORRIGIERTE fp16-Konvertierung.

Unterschied zu 03_export_quant_c.py:
  - D.5 haelt RMSNorm/Softcap in fp32 (Default-op_block_list) statt alles fp16 zu
    erzwingen. Dafuer wird VOR der Konvertierung dateibasierte Shape-Inference
    gefahren (infer_shapes_path, vertraegt >2GB), damit convert_float_to_float16
    die Cast-Bruecken an den fp32/fp16-Grenzen korrekt setzt.
  - KEIN fix_fp16_edges mehr (wir WOLLEN die fp32-Inseln — sie verhindern den
    fp16-Ueberlauf in der RMSNorm-Reduktion auf echten WebGPU-Kerneln).

Grund: op_block_list=[] erzwang fp16 ueberall -> ReduceMean-Summe (mean(x^2) ueber
2560 Dims, x~50 nach Gemma-Normalizer) sprengt fp16-Max (65504) auf WebGPU -> NaN.
ORT-CPU rechnet intern fp32 und verzeiht das (deshalb war der CPU-Test kohaerent).

Start IMMER mit nohup:
  nohup python 07_export_quant_c_v2.py > export_v2.log 2>&1 &
"""
import gc, os
from pathlib import Path
import torch, onnx

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

MODEL_ID = "/root/gemma4-bund-merged"          # LOKAL (kein Re-Download)
STOCK    = "onnx-community/gemma-4-E4B-it-ONNX"
OUT      = Path("/root/train/gemma4-bund-final-v2")
ONNX_DIR = OUT / "onnx"; ONNX_DIR.mkdir(parents=True, exist_ok=True)

FP32      = ONNX_DIR / "decoder_model_merged.onnx"
FP32_DATA = "decoder_model_merged.onnx_data"
FP32_SI   = ONNX_DIR / "decoder_model_merged_si.onnx"        # shape-inferred
FP32_SI_DATA = "decoder_model_merged_si.onnx_data"
FP16      = ONNX_DIR / "decoder_model_merged_fp16.onnx"
FP16_DATA = "decoder_model_merged_fp16.onnx_data"
Q4        = ONNX_DIR / "decoder_model_merged_q4f16.onnx"
Q4_DATA   = "decoder_model_merged_q4f16.onnx_data"

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

# ------------------------------------------------------------------ A) laden
log("A) Modell laden (fp32)")
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()
lm = model.model.language_model
lm_head = model.lm_head if hasattr(model, "lm_head") else model.get_output_embeddings()
print("hidden_size:", lm.config.hidden_size)

# ------------------------------------------------- B) Cache-Geometrie messen
log("B) Trockenlauf")
with torch.no_grad():
    ids = torch.tensor([[1, 2, 3, 4]])
    emb = lm.get_input_embeddings()(ids)
    ple = lm.get_per_layer_inputs(ids, emb)
    print("per_layer_inputs Shape:", tuple(ple.shape), "(erwartet: 1,4,42,256)")
    probe = lm(inputs_embeds=emb, per_layer_inputs=ple, use_cache=True, return_dict=True)
pkv = probe.past_key_values
N_CACHE = len(pkv.layers)
print("n_cache_layers:", N_CACHE, "(erwartet: 24)")
KV_SHAPES = [(int(pkv.layers[i].keys.shape[1]), int(pkv.layers[i].keys.shape[3])) for i in range(N_CACHE)]
print("head_dims:", sorted({s[1] for s in KV_SHAPES}), "(erwartet: [256, 512])")
del probe, pkv, emb, ple, ids; gc.collect()

# ---------------------------------------------------------------- C) Wrapper
class DecoderWrapper(torch.nn.Module):
    def __init__(self, lm, lm_head, n_cache):
        super().__init__(); self.lm, self.lm_head, self.n_cache = lm, lm_head, n_cache
    def forward(self, inputs_embeds, per_layer_inputs, 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, per_layer_inputs=per_layer_inputs,
                      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")
B, S, P = 1, 1, 1
with torch.no_grad():
    d_ids = torch.tensor([[42]], dtype=torch.long)
    d_emb = lm.get_input_embeddings()(d_ids).detach()
    d_ple = lm.get_per_layer_inputs(d_ids, d_emb).detach()
d_mask = torch.ones(B, P + S, dtype=torch.long)
d_pos = torch.tensor([[P]], dtype=torch.long)
d_past = []
for (n_kv, hd) in KV_SHAPES:
    d_past += [torch.zeros(B, n_kv, P, hd), torch.zeros(B, n_kv, P, hd)]

input_names = ["inputs_embeds", "per_layer_inputs", "attention_mask", "position_ids"]
output_names = ["logits"]
dyn = {"inputs_embeds":{0:"batch",1:"seq"}, "per_layer_inputs":{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, on = f"past_key_values.{i}.{kv}", f"present.{i}.{kv}"
        input_names.append(pn); output_names.append(on)
        dyn[pn] = {0:"batch",2:"past_seq"}; dyn[on] = {0:"batch",2:"total_seq"}

log("C) torch.onnx.export — LANGE STILLE IST NORMAL")
with torch.no_grad():
    torch.onnx.export(wrapper, (d_emb, d_ple, d_mask, d_pos, *d_past), str(FP32),
        input_names=input_names, output_names=output_names, dynamic_axes=dyn,
        opset_version=17, do_constant_folding=True, dynamo=False)
print("Export geschrieben.")
del model, lm, lm_head, wrapper, d_past, d_emb, d_ple; gc.collect()

# --------------------------------------------------------- D) Konsolidierung
log("D) Konsolidierung")
m = onnx.load(str(FP32), load_external_data=True)
onnx.save_model(m, str(FP32), save_as_external_data=True, all_tensors_to_one_file=True,
                location=FP32_DATA, size_threshold=1024)
del m; gc.collect()
for f in ONNX_DIR.iterdir():
    if f.name.startswith("onnx__") or f.name.startswith("lm.") or f.name.startswith("_"):
        f.unlink()
try:
    onnx.checker.check_model(str(FP32)); print("fp32 valide.")
except Exception as e:
    print("checker uebersprungen (>2GB):", type(e).__name__)

# ---------------------------- D.5) KORRIGIERT: Shape-Inference + fp16, RMSNorm bleibt fp32
log("D.5) Shape-Inference (dateibasiert, >2GB-tauglich)")
from onnx import shape_inference
shape_inference.infer_shapes_path(str(FP32), str(FP32_SI))
print("shape-inferred geschrieben.")
FP32.unlink(missing_ok=True); (ONNX_DIR / FP32_DATA).unlink(missing_ok=True)

log("D.5) fp32 -> fp16 (Default-op_block_list: RMSNorm/Softcap bleiben fp32)")
from onnxconverter_common import float16
m32 = onnx.load(str(FP32_SI), load_external_data=True)
# KEIN op_block_list=[] -> Default-Liste haelt numerisch heikle Ops in fp32.
# disable_shape_infer=True ist ok, weil FP32_SI bereits value_info traegt.
m16 = float16.convert_float_to_float16(m32, keep_io_types=False, disable_shape_infer=True)
onnx.save_model(m16, str(FP16), save_as_external_data=True, all_tensors_to_one_file=True,
                location=FP16_DATA, size_threshold=1024)
del m32, m16; gc.collect()
FP32_SI.unlink(missing_ok=True); (ONNX_DIR / FP32_SI_DATA).unlink(missing_ok=True)
print("fp16 geschrieben (mit fp32-Inseln).")

# Verifikation: laedt + RMSNorm-Reduktion fp32?
import onnxruntime as ort
try:
    so = ort.SessionOptions(); so.intra_op_num_threads = 4
    ort.InferenceSession(str(FP16), sess_options=so, providers=["CPUExecutionProvider"])
    print("fp16 LAEDT in ORT.")
except Exception as e:
    print("!! fp16 LAEDT NICHT:", str(e).split(chr(10))[0][:120])
rm_fp32 = 0
mm = onnx.load(str(FP16), load_external_data=False)
vi = {v.name: v.type.tensor_type.elem_type for v in mm.graph.value_info}
for n in mm.graph.node:
    if n.op_type == "ReduceMean" and vi.get(n.output[0]) == 1:
        rm_fp32 += 1
print(f"ReduceMean in fp32: {rm_fp32} (erwartet >0)")
del mm; gc.collect()

# ------------------------------------------------------------------ E) q4f16
log("E) q4f16")
from onnxruntime.quantization.matmul_nbits_quantizer import (
    MatMulNBitsQuantizer as Q, DefaultWeightOnlyQuantConfig)
mf = onnx.load(str(FP16), load_external_data=True)
quant = Q(mf, algo_config=DefaultWeightOnlyQuantConfig(block_size=32, is_symmetric=True, accuracy_level=4))
quant.process()
qm = quant.model.model if hasattr(quant.model, "model") else quant.model
onnx.save_model(qm, str(Q4), save_as_external_data=True, all_tensors_to_one_file=True,
                location=Q4_DATA, size_threshold=1024)
del mf, quant, qm; gc.collect()
FP16.unlink(missing_ok=True); (ONNX_DIR / FP16_DATA).unlink(missing_ok=True)

# Verifikation nach Quantisierung
try:
    so = ort.SessionOptions(); so.intra_op_num_threads = 4
    s = ort.InferenceSession(str(Q4), sess_options=so, providers=["CPUExecutionProvider"])
    print("q4f16 LAEDT, Inputs total", len(s.get_inputs()))
except Exception as e:
    print("!! q4f16 LAEDT NICHT:", str(e).split(chr(10))[0][:120])

# ---------------------------------------------------- F) Stock-Embed + Config
log("F) Stock-Embed holen, Embed-Output auf fp16 casten, Config/Tokenizer schreiben")
from huggingface_hub import hf_hub_download
import shutil, json
from onnx import helper, TensorProto
for fn in ("onnx/embed_tokens_q4f16.onnx", "onnx/embed_tokens_q4f16.onnx_data"):
    p = hf_hub_download(STOCK, fn, local_dir="/root/stock-embed")
    shutil.copy(p, ONNX_DIR / Path(fn).name); print("geholt:", fn)

# Embed-Outputs fp32 -> fp16 casten (sonst dtype-Mismatch zum fp16-Decoder)
emb_path = ONNX_DIR / "embed_tokens_q4f16.onnx"
em = onnx.load(str(emb_path), load_external_data=False)
tgts = [o.name for o in em.graph.output if o.type.tensor_type.elem_type == TensorProto.FLOAT]
prod = {out: (nd, i) for nd in em.graph.node for i, out in enumerate(nd.output) if out in tgts}
for name in tgts:
    nd, idx = prod[name]; pre = name + "_fp32"; nd.output[idx] = pre
    em.graph.node.append(helper.make_node("Cast", [pre], [name], to=TensorProto.FLOAT16, name=name+"/CastToFp16"))
    for o in em.graph.output:
        if o.name == name: o.type.tensor_type.elem_type = TensorProto.FLOAT16
onnx.save(em, str(emb_path))
print("Embed-Outputs auf fp16 gecastet:", tgts)

tok.save_pretrained(str(OUT))
from transformers import AutoConfig
c = AutoConfig.from_pretrained(MODEL_ID); c.save_pretrained(str(OUT))
cp = OUT / "config.json"; cfg = json.load(open(cp))
cfg["transformers.js_config"] = {
    "dtype": "q4f16",
    "use_external_data_format": {
        "decoder_model_merged_q4f16.onnx": 2,   # 2 Chunks: .onnx_data + .onnx_data_1
        "embed_tokens_q4f16.onnx": True,
    },
    "kv_cache_dtype": "float16",
}
json.dump(cfg, open(cp, "w"), indent=2)

# chat_template ins tokenizer_config.json einbetten (Transformers.js liest es nur von dort)
tcp = OUT / "tokenizer_config.json"
jinja = OUT / "chat_template.jinja"
if jinja.exists():
    tc = json.load(open(tcp)); tc["chat_template"] = jinja.read_text(encoding="utf-8")
    json.dump(tc, open(tcp, "w"), ensure_ascii=False, indent=2)
    print("chat_template in tokenizer_config.json eingebettet.")

log("FERTIG bis E/F. NAECHSTE SCHRITTE:")
print("  1) Reshard:  python 04_reshard.py   (REPO/BASE ggf. anpassen, Quelle = dieser Q4)")
print("  2) Upload nach gfp78/gemma4-bund-onnx-v2 (oder v1 ueberschreiben)")
print("  3) Bundesrechner: 3 Decoder-Dateien + embed + config + tokenizer_config ziehen, Browser-Test")
print("  !! JETZT SOFORT die q4f16-Dateien sichern — /root ist fluechtig.")