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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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
#!/usr/bin/env python
"""
09_export_bisect.py — Export MIT Qualitaetsmessung nach jeder Stufe.

Unterschied zu 07_export_v3.py:
  * Zwischenstufen werden NICHT geloescht -> Neustart ab beliebiger Stufe moeglich
  * nach JEDER Stufe ein echter Qualitaetstest (Teacher-Forcing-Perplexitaet)
  * am Ende eine Tabelle, die zeigt, WELCHE Stufe das Modell zerstoert
  * Quantisierung asymmetrisch + lm_head ausgenommen (Verdacht aus Code-Review)

Gemessene Stufen:
  S1  fp32                     (roher torch.onnx.export)
  S2  fp16                     (convert_float_to_float16 + fix_edges)
  S3  fp16 + RMSNorm-fp32-Wrap
  S4  q4f16                    (Endprodukt)

Interpretation der Perplexitaet (ppl):
  S1 ist die Referenz. Ein Anstieg um Faktor <1.5 ist unkritisch.
  Die erste Stufe mit ppl > 3x S1 (oder NaN) ist der Schuldige.

Start:
  cd /root/train && nohup python 09_export_bisect.py > bisect.log 2>&1 &
  tail -f bisect.log
"""
import gc, os, json, shutil
from pathlib import Path
import numpy as np
import torch, onnx
from onnx import TensorProto, helper

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

MODEL_ID = "/root/gemma4-bund-merged"
STOCK    = "onnx-community/gemma-4-E4B-it-ONNX"
OUT      = Path("/root/train/gemma4-bund-bisect")
ONNX_DIR = OUT / "onnx"
ONNX_DIR.mkdir(parents=True, exist_ok=True)

S1    = ONNX_DIR / "s1_fp32.onnx";        S1_D = "s1_fp32.onnx_data"
S2    = ONNX_DIR / "s2_fp16.onnx";        S2_D = "s2_fp16.onnx_data"
S3    = ONNX_DIR / "s3_fp16_rms.onnx";    S3_D = "s3_fp16_rms.onnx_data"
S4    = ONNX_DIR / "decoder_model_merged_q4f16.onnx"
S4_D  = "decoder_model_merged_q4f16.onnx_data"

PROBE = OUT / "probe.npz"
RESULTS = []

# Testfall: Frage mit eindeutiger, kurzer Antwort. Teacher-Forcing misst,
# wie ueberrascht das Modell von der KORREKTEN Antwort ist.
TEST_Q = "Wie lange dauert die Probezeit bei einer Anstellung beim Bund?"
TEST_A = "Die Probezeit dauert in der Regel drei Monate."


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


def fix_edges(m):
    n = 0
    for nd in m.graph.node:
        if nd.op_type == "Cast":
            for a in nd.attribute:
                if a.name == "to" and a.i == TensorProto.FLOAT:
                    a.i = TensorProto.FLOAT16
                    n += 1
    return n


def wrap_rmsnorm_fp32(m):
    g = m.graph; new = []; nw = 0
    for node in list(g.node):
        if node.op_type == "ReduceMean":
            rin = node.input[0]; pre = rin + "_to32"
            new.append(helper.make_node("Cast", [rin], [pre],
                                        to=TensorProto.FLOAT,
                                        name=node.name + "/CastIn32"))
            node.input[0] = pre
            outp = node.output[0]; post = outp + "_f32"
            node.output[0] = post
            new.append(node)
            new.append(helper.make_node("Cast", [post], [outp],
                                        to=TensorProto.FLOAT16,
                                        name=node.name + "/CastOut16"))
            nw += 1
        else:
            new.append(node)
    del g.node[:]; g.node.extend(new)
    return nw


# ---------------------------------------------------------------- Messung
def measure(path, label, fp16_io):
    """Teacher-Forcing-Perplexitaet der Referenzantwort. Kleiner = besser."""
    import onnxruntime as ort
    d = np.load(PROBE)
    emb = d["emb"]; ple = d["ple"]; tgt = d["tgt"]; a_start = int(d["a_start"])
    n_cache = int(d["n_cache"]); kv = d["kv_shapes"]

    dt = np.float16 if fp16_io else np.float32
    seq = emb.shape[1]
    feed = {
        "inputs_embeds":    emb.astype(dt),
        "per_layer_inputs": ple.astype(dt),
        "attention_mask":   np.ones((1, seq), dtype=np.int64),
        "position_ids":     np.arange(seq, dtype=np.int64)[None, :],
    }
    for i in range(n_cache):
        n_kv, hd = int(kv[i][0]), int(kv[i][1])
        z = np.zeros((1, n_kv, 0, hd), dtype=dt)
        feed[f"past_key_values.{i}.key"] = z
        feed[f"past_key_values.{i}.value"] = z

    try:
        so = ort.SessionOptions(); so.intra_op_num_threads = 8
        sess = ort.InferenceSession(str(path), sess_options=so,
                                    providers=["CPUExecutionProvider"])
        logits = sess.run(["logits"], feed)[0].astype(np.float64)
        del sess
    except Exception as e:
        msg = str(e).split(chr(10))[0][:140]
        print(f"    !! LAEDT/LAEUFT NICHT: {msg}", flush=True)
        RESULTS.append((label, "FEHLER", "-", msg[:60]))
        return

    if not np.isfinite(logits).all():
        print("    !! logits enthalten NaN/Inf", flush=True)
        RESULTS.append((label, "NaN/Inf", "-", "numerischer Ueberlauf"))
        return

    # Perplexitaet nur ueber die Antwort-Tokens
    lp = logits[0] - logits[0].max(axis=-1, keepdims=True)
    lp = lp - np.log(np.exp(lp).sum(axis=-1, keepdims=True))
    nll, cnt = 0.0, 0
    for p in range(a_start - 1, len(tgt) - 1):
        nll -= lp[p, int(tgt[p + 1])]; cnt += 1
    ppl = float(np.exp(nll / max(cnt, 1)))

    # Erstes Antwort-Token: was sagt das Modell wirklich?
    top = int(np.argmax(logits[0, a_start - 1]))
    exp = int(tgt[a_start])
    hit = "JA" if top == exp else "nein"

    print(f"    ppl={ppl:.3f}   erstes Antwort-Token korrekt: {hit}", flush=True)
    RESULTS.append((label, f"{ppl:.3f}", hit, ""))
    gc.collect()


def table():
    log("BISEKTIONS-ERGEBNIS")
    print(f"{'Stufe':<22}{'ppl':>12}{'1.Token':>10}  Hinweis")
    print("-" * 72)
    for r in RESULTS:
        print(f"{r[0]:<22}{r[1]:>12}{r[2]:>10}  {r[3]}")
    print("-" * 72)
    print("Die erste Stufe mit ppl > 3x der Stufe S1 (oder FEHLER/NaN)")
    print("ist die Ursache. Bleibt ppl ueberall niedrig, liegt der Fehler")
    print("NICHT im Export, sondern im Embed-Pfad oder im Browser-Prompt.",
          flush=True)


# ================================================================ A) laden
log("A) Modell laden (fp32) + Probe-Tensoren erzeugen")
from transformers import AutoTokenizer, AutoModelForImageTextToText, DynamicCache

tok = AutoTokenizer.from_pretrained(MODEL_ID)
model = AutoModelForImageTextToText.from_pretrained(
    MODEL_ID, dtype=torch.float32, device_map="cpu").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, flush=True)

# Chat-Template anwenden — exakt wie im Training
p_txt = tok.apply_chat_template([{"role": "user", "content": TEST_Q}],
                                tokenize=False, add_generation_prompt=True)
p_ids = tok(p_txt, add_special_tokens=False)["input_ids"]
a_ids = tok(TEST_A, add_special_tokens=False)["input_ids"]
full = p_ids + a_ids
a_start = len(p_ids)
print("Prompt-Tokens:", len(p_ids), "| Antwort-Tokens:", len(a_ids), flush=True)
print("Template-Auszug:", repr(p_txt[:120]), flush=True)

log("B) Trockenlauf (Geometrie)")
with torch.no_grad():
    t_ids = torch.tensor([full], dtype=torch.long)
    t_emb = lm.get_input_embeddings()(t_ids)
    t_ple = lm.get_per_layer_inputs(t_ids, t_emb)
    print("per_layer_inputs Shape:", tuple(t_ple.shape), flush=True)
    probe = lm(inputs_embeds=t_emb[:, :4], per_layer_inputs=t_ple[:, :4],
               use_cache=True, return_dict=True)
pkv = probe.past_key_values
N_CACHE = len(pkv.layers)
KV_SHAPES = [(int(pkv.layers[i].keys.shape[1]), int(pkv.layers[i].keys.shape[3]))
             for i in range(N_CACHE)]
print("n_cache_layers:", N_CACHE, "| head_dims:",
      sorted({s[1] for s in KV_SHAPES}), flush=True)

np.savez(PROBE,
         emb=t_emb.numpy().astype(np.float32),
         ple=t_ple.numpy().astype(np.float32),
         tgt=np.array(full, dtype=np.int64),
         a_start=np.array(a_start),
         n_cache=np.array(N_CACHE),
         kv_shapes=np.array(KV_SHAPES, dtype=np.int64))
print("Probe gespeichert:", PROBE, flush=True)
del probe, pkv, t_emb, t_ple, t_ids
gc.collect()


# ================================================================ C) Export
class DecoderWrapper(torch.nn.Module):
    def __init__(s, lm, lm_head, n):
        super().__init__(); s.lm, s.lm_head, s.n = lm, lm_head, n

    def forward(s, inputs_embeds, per_layer_inputs, attention_mask, position_ids, *past):
        cache = None
        if len(past) == 2 * s.n and past[0].shape[2] > 0:
            cache = DynamicCache(config=s.lm.config)
            for i in range(s.n):
                cache.update(past[2 * i], past[2 * i + 1], i)
        out = s.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 = s.lm_head(out.last_hidden_state)
        present = []
        for i in range(s.n):
            present += [out.past_key_values.layers[i].keys,
                        out.past_key_values.layers[i].values]
        return (logits, *present)


if not S1.exists():
    log("C) ONNX-Export fp32 (LANGE STILLE IST NORMAL, 20-40 min)")
    wrapper = DecoderWrapper(lm, lm_head, N_CACHE).eval()
    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(1, 2, dtype=torch.long)
    d_pos = torch.tensor([[1]], dtype=torch.long)
    d_past = []
    for (n_kv, hd) in KV_SHAPES:
        d_past += [torch.zeros(1, n_kv, 1, hd), torch.zeros(1, n_kv, 1, 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 kvn in ("key", "value"):
            pn, on = f"past_key_values.{i}.{kvn}", f"present.{i}.{kvn}"
            input_names.append(pn); output_names.append(on)
            dyn[pn] = {0: "batch", 2: "past_seq"}
            dyn[on] = {0: "batch", 2: "total_seq"}

    with torch.no_grad():
        torch.onnx.export(wrapper, (d_emb, d_ple, d_mask, d_pos, *d_past), str(S1),
                          input_names=input_names, output_names=output_names,
                          dynamic_axes=dyn, opset_version=17,
                          do_constant_folding=True, dynamo=False)
    print("Export geschrieben.", flush=True)
    del wrapper, d_past, d_emb, d_ple
    del model, lm, lm_head
    gc.collect()

    log("C.1) Konsolidierung fp32")
    m = onnx.load(str(S1), load_external_data=True)
    onnx.save_model(m, str(S1), save_as_external_data=True,
                    all_tensors_to_one_file=True, location=S1_D, size_threshold=1024)
    del m; gc.collect()
    for f in ONNX_DIR.iterdir():
        if f.name.startswith(("onnx__", "lm.", "_")):
            f.unlink()
else:
    print("S1 existiert bereits — Export uebersprungen.", flush=True)
    del model, lm, lm_head
    gc.collect()

log("MESSUNG S1 (fp32) — das ist die Referenz")
measure(S1, "S1 fp32", fp16_io=False)


# ============================================================ D) fp16
if not S2.exists():
    log("D) fp16-Konvertierung + fix_edges")
    from onnxconverter_common import float16
    m32 = onnx.load(str(S1), load_external_data=True)
    m16 = float16.convert_float_to_float16(m32, keep_io_types=False,
                                           disable_shape_infer=True, op_block_list=[])
    ne = fix_edges(m16)
    print(f"fix_edges Casts: {ne}", flush=True)
    onnx.save_model(m16, str(S2), save_as_external_data=True,
                    all_tensors_to_one_file=True, location=S2_D, size_threshold=1024)
    del m32, m16; gc.collect()
else:
    print("S2 existiert bereits.", flush=True)

log("MESSUNG S2 (fp16, ohne RMSNorm-Wrap)")
measure(S2, "S2 fp16", fp16_io=True)


# ============================================================ E) RMSNorm
if not S3.exists():
    log("E) RMSNorm-fp32-Wrap")
    m = onnx.load(str(S2), load_external_data=True)
    nw = wrap_rmsnorm_fp32(m)
    print(f"ReduceMean gewrappt: {nw}", flush=True)
    onnx.save_model(m, str(S3), save_as_external_data=True,
                    all_tensors_to_one_file=True, location=S3_D, size_threshold=1024)
    del m; gc.collect()
else:
    print("S3 existiert bereits.", flush=True)

log("MESSUNG S3 (fp16 + RMSNorm-fp32)")
measure(S3, "S3 fp16+RMSwrap", fp16_io=True)


# ============================================================ F) q4f16
if not S4.exists():
    log("F) q4f16 — asymmetrisch, lm_head ausgenommen")
    from onnxruntime.quantization.matmul_nbits_quantizer import (
        MatMulNBitsQuantizer as Q, DefaultWeightOnlyQuantConfig)
    mf = onnx.load(str(S3), load_external_data=True)

    # lm_head finden: die MatMul mit der groessten Gewichtsmatrix.
    dims = {i.name: list(i.dims) for i in mf.graph.initializer}
    big, bigsz = None, 0
    for nd in mf.graph.node:
        if nd.op_type in ("MatMul", "Gemm"):
            for inp in nd.input:
                d = dims.get(inp)
                if d and len(d) == 2:
                    sz = d[0] * d[1]
                    if sz > bigsz:
                        bigsz, big = sz, nd.name
    excl = [big] if big else []
    print(f"lm_head-Kandidat ausgenommen: {big} ({bigsz/1e6:.0f}M Params)", flush=True)

    quant = Q(mf, algo_config=DefaultWeightOnlyQuantConfig(
                  block_size=32, is_symmetric=False, accuracy_level=4),
              nodes_to_exclude=excl)
    quant.process()
    qm = quant.model.model if hasattr(quant.model, "model") else quant.model
    onnx.save_model(qm, str(S4), save_as_external_data=True,
                    all_tensors_to_one_file=True, location=S4_D, size_threshold=1024)
    del mf, quant, qm; gc.collect()
else:
    print("S4 existiert bereits.", flush=True)

log("MESSUNG S4 (q4f16 — Endprodukt)")
measure(S4, "S4 q4f16", fp16_io=True)


# ============================================================ G) Beiwerk
log("G) Stock-Embed + Cast auf fp16 + config/tokenizer")
from huggingface_hub import hf_hub_download

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, flush=True)

ep = ONNX_DIR / "embed_tokens_q4f16.onnx"
em = onnx.load(str(ep), load_external_data=False)
tg = [o.name for o in em.graph.output if o.type.tensor_type.elem_type == TensorProto.FLOAT]
pr = {o: (nd, i) for nd in em.graph.node for i, o in enumerate(nd.output) if o in tg}
for name in tg:
    nd, idx = pr[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(ep))
print("Embed-Outputs auf fp16 gecastet:", tg, flush=True)

tok.save_pretrained(str(OUT))
from transformers import AutoConfig
AutoConfig.from_pretrained(MODEL_ID).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,
                                 "embed_tokens_q4f16.onnx": True},
    "kv_cache_dtype": "float16"}
json.dump(cfg, open(cp, "w"), indent=2)

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 eingebettet.", flush=True)

gc_cfg = OUT / "generation_config.json"
if not gc_cfg.exists():
    json.dump({"eos_token_id": [1, 106, 50], "bos_token_id": 2,
               "pad_token_id": 0}, open(gc_cfg, "w"), indent=2)
    print("generation_config.json angelegt.", flush=True)

table()
log("FERTIG. Zwischenstufen bleiben liegen. /root ist fluechtig — JETZT sichern!")