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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""
|
| 3 |
+
09_export_bisect.py — Export MIT Qualitaetsmessung nach jeder Stufe.
|
| 4 |
+
|
| 5 |
+
Unterschied zu 07_export_v3.py:
|
| 6 |
+
* Zwischenstufen werden NICHT geloescht -> Neustart ab beliebiger Stufe moeglich
|
| 7 |
+
* nach JEDER Stufe ein echter Qualitaetstest (Teacher-Forcing-Perplexitaet)
|
| 8 |
+
* am Ende eine Tabelle, die zeigt, WELCHE Stufe das Modell zerstoert
|
| 9 |
+
* Quantisierung asymmetrisch + lm_head ausgenommen (Verdacht aus Code-Review)
|
| 10 |
+
|
| 11 |
+
Gemessene Stufen:
|
| 12 |
+
S1 fp32 (roher torch.onnx.export)
|
| 13 |
+
S2 fp16 (convert_float_to_float16 + fix_edges)
|
| 14 |
+
S3 fp16 + RMSNorm-fp32-Wrap
|
| 15 |
+
S4 q4f16 (Endprodukt)
|
| 16 |
+
|
| 17 |
+
Interpretation der Perplexitaet (ppl):
|
| 18 |
+
S1 ist die Referenz. Ein Anstieg um Faktor <1.5 ist unkritisch.
|
| 19 |
+
Die erste Stufe mit ppl > 3x S1 (oder NaN) ist der Schuldige.
|
| 20 |
+
|
| 21 |
+
Start:
|
| 22 |
+
cd /root/train && nohup python 09_export_bisect.py > bisect.log 2>&1 &
|
| 23 |
+
tail -f bisect.log
|
| 24 |
+
"""
|
| 25 |
+
import gc, os, json, shutil
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
import numpy as np
|
| 28 |
+
import torch, onnx
|
| 29 |
+
from onnx import TensorProto, helper
|
| 30 |
+
|
| 31 |
+
os.environ.setdefault("HF_HOME", "/root/hf-cache")
|
| 32 |
+
|
| 33 |
+
MODEL_ID = "/root/gemma4-bund-merged"
|
| 34 |
+
STOCK = "onnx-community/gemma-4-E4B-it-ONNX"
|
| 35 |
+
OUT = Path("/root/train/gemma4-bund-bisect")
|
| 36 |
+
ONNX_DIR = OUT / "onnx"
|
| 37 |
+
ONNX_DIR.mkdir(parents=True, exist_ok=True)
|
| 38 |
+
|
| 39 |
+
S1 = ONNX_DIR / "s1_fp32.onnx"; S1_D = "s1_fp32.onnx_data"
|
| 40 |
+
S2 = ONNX_DIR / "s2_fp16.onnx"; S2_D = "s2_fp16.onnx_data"
|
| 41 |
+
S3 = ONNX_DIR / "s3_fp16_rms.onnx"; S3_D = "s3_fp16_rms.onnx_data"
|
| 42 |
+
S4 = ONNX_DIR / "decoder_model_merged_q4f16.onnx"
|
| 43 |
+
S4_D = "decoder_model_merged_q4f16.onnx_data"
|
| 44 |
+
|
| 45 |
+
PROBE = OUT / "probe.npz"
|
| 46 |
+
RESULTS = []
|
| 47 |
+
|
| 48 |
+
# Testfall: Frage mit eindeutiger, kurzer Antwort. Teacher-Forcing misst,
|
| 49 |
+
# wie ueberrascht das Modell von der KORREKTEN Antwort ist.
|
| 50 |
+
TEST_Q = "Wie lange dauert die Probezeit bei einer Anstellung beim Bund?"
|
| 51 |
+
TEST_A = "Die Probezeit dauert in der Regel drei Monate."
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def log(m):
|
| 55 |
+
print(f"\n=== {m}", flush=True)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def fix_edges(m):
|
| 59 |
+
n = 0
|
| 60 |
+
for nd in m.graph.node:
|
| 61 |
+
if nd.op_type == "Cast":
|
| 62 |
+
for a in nd.attribute:
|
| 63 |
+
if a.name == "to" and a.i == TensorProto.FLOAT:
|
| 64 |
+
a.i = TensorProto.FLOAT16
|
| 65 |
+
n += 1
|
| 66 |
+
return n
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def wrap_rmsnorm_fp32(m):
|
| 70 |
+
g = m.graph; new = []; nw = 0
|
| 71 |
+
for node in list(g.node):
|
| 72 |
+
if node.op_type == "ReduceMean":
|
| 73 |
+
rin = node.input[0]; pre = rin + "_to32"
|
| 74 |
+
new.append(helper.make_node("Cast", [rin], [pre],
|
| 75 |
+
to=TensorProto.FLOAT,
|
| 76 |
+
name=node.name + "/CastIn32"))
|
| 77 |
+
node.input[0] = pre
|
| 78 |
+
outp = node.output[0]; post = outp + "_f32"
|
| 79 |
+
node.output[0] = post
|
| 80 |
+
new.append(node)
|
| 81 |
+
new.append(helper.make_node("Cast", [post], [outp],
|
| 82 |
+
to=TensorProto.FLOAT16,
|
| 83 |
+
name=node.name + "/CastOut16"))
|
| 84 |
+
nw += 1
|
| 85 |
+
else:
|
| 86 |
+
new.append(node)
|
| 87 |
+
del g.node[:]; g.node.extend(new)
|
| 88 |
+
return nw
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# ---------------------------------------------------------------- Messung
|
| 92 |
+
def measure(path, label, fp16_io):
|
| 93 |
+
"""Teacher-Forcing-Perplexitaet der Referenzantwort. Kleiner = besser."""
|
| 94 |
+
import onnxruntime as ort
|
| 95 |
+
d = np.load(PROBE)
|
| 96 |
+
emb = d["emb"]; ple = d["ple"]; tgt = d["tgt"]; a_start = int(d["a_start"])
|
| 97 |
+
n_cache = int(d["n_cache"]); kv = d["kv_shapes"]
|
| 98 |
+
|
| 99 |
+
dt = np.float16 if fp16_io else np.float32
|
| 100 |
+
seq = emb.shape[1]
|
| 101 |
+
feed = {
|
| 102 |
+
"inputs_embeds": emb.astype(dt),
|
| 103 |
+
"per_layer_inputs": ple.astype(dt),
|
| 104 |
+
"attention_mask": np.ones((1, seq), dtype=np.int64),
|
| 105 |
+
"position_ids": np.arange(seq, dtype=np.int64)[None, :],
|
| 106 |
+
}
|
| 107 |
+
for i in range(n_cache):
|
| 108 |
+
n_kv, hd = int(kv[i][0]), int(kv[i][1])
|
| 109 |
+
z = np.zeros((1, n_kv, 0, hd), dtype=dt)
|
| 110 |
+
feed[f"past_key_values.{i}.key"] = z
|
| 111 |
+
feed[f"past_key_values.{i}.value"] = z
|
| 112 |
+
|
| 113 |
+
try:
|
| 114 |
+
so = ort.SessionOptions(); so.intra_op_num_threads = 8
|
| 115 |
+
sess = ort.InferenceSession(str(path), sess_options=so,
|
| 116 |
+
providers=["CPUExecutionProvider"])
|
| 117 |
+
logits = sess.run(["logits"], feed)[0].astype(np.float64)
|
| 118 |
+
del sess
|
| 119 |
+
except Exception as e:
|
| 120 |
+
msg = str(e).split(chr(10))[0][:140]
|
| 121 |
+
print(f" !! LAEDT/LAEUFT NICHT: {msg}", flush=True)
|
| 122 |
+
RESULTS.append((label, "FEHLER", "-", msg[:60]))
|
| 123 |
+
return
|
| 124 |
+
|
| 125 |
+
if not np.isfinite(logits).all():
|
| 126 |
+
print(" !! logits enthalten NaN/Inf", flush=True)
|
| 127 |
+
RESULTS.append((label, "NaN/Inf", "-", "numerischer Ueberlauf"))
|
| 128 |
+
return
|
| 129 |
+
|
| 130 |
+
# Perplexitaet nur ueber die Antwort-Tokens
|
| 131 |
+
lp = logits[0] - logits[0].max(axis=-1, keepdims=True)
|
| 132 |
+
lp = lp - np.log(np.exp(lp).sum(axis=-1, keepdims=True))
|
| 133 |
+
nll, cnt = 0.0, 0
|
| 134 |
+
for p in range(a_start - 1, len(tgt) - 1):
|
| 135 |
+
nll -= lp[p, int(tgt[p + 1])]; cnt += 1
|
| 136 |
+
ppl = float(np.exp(nll / max(cnt, 1)))
|
| 137 |
+
|
| 138 |
+
# Erstes Antwort-Token: was sagt das Modell wirklich?
|
| 139 |
+
top = int(np.argmax(logits[0, a_start - 1]))
|
| 140 |
+
exp = int(tgt[a_start])
|
| 141 |
+
hit = "JA" if top == exp else "nein"
|
| 142 |
+
|
| 143 |
+
print(f" ppl={ppl:.3f} erstes Antwort-Token korrekt: {hit}", flush=True)
|
| 144 |
+
RESULTS.append((label, f"{ppl:.3f}", hit, ""))
|
| 145 |
+
gc.collect()
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def table():
|
| 149 |
+
log("BISEKTIONS-ERGEBNIS")
|
| 150 |
+
print(f"{'Stufe':<22}{'ppl':>12}{'1.Token':>10} Hinweis")
|
| 151 |
+
print("-" * 72)
|
| 152 |
+
for r in RESULTS:
|
| 153 |
+
print(f"{r[0]:<22}{r[1]:>12}{r[2]:>10} {r[3]}")
|
| 154 |
+
print("-" * 72)
|
| 155 |
+
print("Die erste Stufe mit ppl > 3x der Stufe S1 (oder FEHLER/NaN)")
|
| 156 |
+
print("ist die Ursache. Bleibt ppl ueberall niedrig, liegt der Fehler")
|
| 157 |
+
print("NICHT im Export, sondern im Embed-Pfad oder im Browser-Prompt.",
|
| 158 |
+
flush=True)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
# ================================================================ A) laden
|
| 162 |
+
log("A) Modell laden (fp32) + Probe-Tensoren erzeugen")
|
| 163 |
+
from transformers import AutoTokenizer, AutoModelForImageTextToText, DynamicCache
|
| 164 |
+
|
| 165 |
+
tok = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 166 |
+
model = AutoModelForImageTextToText.from_pretrained(
|
| 167 |
+
MODEL_ID, dtype=torch.float32, device_map="cpu").eval()
|
| 168 |
+
lm = model.model.language_model
|
| 169 |
+
lm_head = model.lm_head if hasattr(model, "lm_head") else model.get_output_embeddings()
|
| 170 |
+
print("hidden_size:", lm.config.hidden_size, flush=True)
|
| 171 |
+
|
| 172 |
+
# Chat-Template anwenden — exakt wie im Training
|
| 173 |
+
p_txt = tok.apply_chat_template([{"role": "user", "content": TEST_Q}],
|
| 174 |
+
tokenize=False, add_generation_prompt=True)
|
| 175 |
+
p_ids = tok(p_txt, add_special_tokens=False)["input_ids"]
|
| 176 |
+
a_ids = tok(TEST_A, add_special_tokens=False)["input_ids"]
|
| 177 |
+
full = p_ids + a_ids
|
| 178 |
+
a_start = len(p_ids)
|
| 179 |
+
print("Prompt-Tokens:", len(p_ids), "| Antwort-Tokens:", len(a_ids), flush=True)
|
| 180 |
+
print("Template-Auszug:", repr(p_txt[:120]), flush=True)
|
| 181 |
+
|
| 182 |
+
log("B) Trockenlauf (Geometrie)")
|
| 183 |
+
with torch.no_grad():
|
| 184 |
+
t_ids = torch.tensor([full], dtype=torch.long)
|
| 185 |
+
t_emb = lm.get_input_embeddings()(t_ids)
|
| 186 |
+
t_ple = lm.get_per_layer_inputs(t_ids, t_emb)
|
| 187 |
+
print("per_layer_inputs Shape:", tuple(t_ple.shape), flush=True)
|
| 188 |
+
probe = lm(inputs_embeds=t_emb[:, :4], per_layer_inputs=t_ple[:, :4],
|
| 189 |
+
use_cache=True, return_dict=True)
|
| 190 |
+
pkv = probe.past_key_values
|
| 191 |
+
N_CACHE = len(pkv.layers)
|
| 192 |
+
KV_SHAPES = [(int(pkv.layers[i].keys.shape[1]), int(pkv.layers[i].keys.shape[3]))
|
| 193 |
+
for i in range(N_CACHE)]
|
| 194 |
+
print("n_cache_layers:", N_CACHE, "| head_dims:",
|
| 195 |
+
sorted({s[1] for s in KV_SHAPES}), flush=True)
|
| 196 |
+
|
| 197 |
+
np.savez(PROBE,
|
| 198 |
+
emb=t_emb.numpy().astype(np.float32),
|
| 199 |
+
ple=t_ple.numpy().astype(np.float32),
|
| 200 |
+
tgt=np.array(full, dtype=np.int64),
|
| 201 |
+
a_start=np.array(a_start),
|
| 202 |
+
n_cache=np.array(N_CACHE),
|
| 203 |
+
kv_shapes=np.array(KV_SHAPES, dtype=np.int64))
|
| 204 |
+
print("Probe gespeichert:", PROBE, flush=True)
|
| 205 |
+
del probe, pkv, t_emb, t_ple, t_ids
|
| 206 |
+
gc.collect()
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
# ================================================================ C) Export
|
| 210 |
+
class DecoderWrapper(torch.nn.Module):
|
| 211 |
+
def __init__(s, lm, lm_head, n):
|
| 212 |
+
super().__init__(); s.lm, s.lm_head, s.n = lm, lm_head, n
|
| 213 |
+
|
| 214 |
+
def forward(s, inputs_embeds, per_layer_inputs, attention_mask, position_ids, *past):
|
| 215 |
+
cache = None
|
| 216 |
+
if len(past) == 2 * s.n and past[0].shape[2] > 0:
|
| 217 |
+
cache = DynamicCache(config=s.lm.config)
|
| 218 |
+
for i in range(s.n):
|
| 219 |
+
cache.update(past[2 * i], past[2 * i + 1], i)
|
| 220 |
+
out = s.lm(inputs_embeds=inputs_embeds, per_layer_inputs=per_layer_inputs,
|
| 221 |
+
attention_mask=attention_mask, position_ids=position_ids,
|
| 222 |
+
past_key_values=cache, use_cache=True, return_dict=True)
|
| 223 |
+
logits = s.lm_head(out.last_hidden_state)
|
| 224 |
+
present = []
|
| 225 |
+
for i in range(s.n):
|
| 226 |
+
present += [out.past_key_values.layers[i].keys,
|
| 227 |
+
out.past_key_values.layers[i].values]
|
| 228 |
+
return (logits, *present)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
if not S1.exists():
|
| 232 |
+
log("C) ONNX-Export fp32 (LANGE STILLE IST NORMAL, 20-40 min)")
|
| 233 |
+
wrapper = DecoderWrapper(lm, lm_head, N_CACHE).eval()
|
| 234 |
+
with torch.no_grad():
|
| 235 |
+
d_ids = torch.tensor([[42]], dtype=torch.long)
|
| 236 |
+
d_emb = lm.get_input_embeddings()(d_ids).detach()
|
| 237 |
+
d_ple = lm.get_per_layer_inputs(d_ids, d_emb).detach()
|
| 238 |
+
d_mask = torch.ones(1, 2, dtype=torch.long)
|
| 239 |
+
d_pos = torch.tensor([[1]], dtype=torch.long)
|
| 240 |
+
d_past = []
|
| 241 |
+
for (n_kv, hd) in KV_SHAPES:
|
| 242 |
+
d_past += [torch.zeros(1, n_kv, 1, hd), torch.zeros(1, n_kv, 1, hd)]
|
| 243 |
+
|
| 244 |
+
input_names = ["inputs_embeds", "per_layer_inputs", "attention_mask", "position_ids"]
|
| 245 |
+
output_names = ["logits"]
|
| 246 |
+
dyn = {"inputs_embeds": {0: "batch", 1: "seq"},
|
| 247 |
+
"per_layer_inputs": {0: "batch", 1: "seq"},
|
| 248 |
+
"attention_mask": {0: "batch", 1: "total"},
|
| 249 |
+
"position_ids": {0: "batch", 1: "seq"},
|
| 250 |
+
"logits": {0: "batch", 1: "seq"}}
|
| 251 |
+
for i in range(N_CACHE):
|
| 252 |
+
for kvn in ("key", "value"):
|
| 253 |
+
pn, on = f"past_key_values.{i}.{kvn}", f"present.{i}.{kvn}"
|
| 254 |
+
input_names.append(pn); output_names.append(on)
|
| 255 |
+
dyn[pn] = {0: "batch", 2: "past_seq"}
|
| 256 |
+
dyn[on] = {0: "batch", 2: "total_seq"}
|
| 257 |
+
|
| 258 |
+
with torch.no_grad():
|
| 259 |
+
torch.onnx.export(wrapper, (d_emb, d_ple, d_mask, d_pos, *d_past), str(S1),
|
| 260 |
+
input_names=input_names, output_names=output_names,
|
| 261 |
+
dynamic_axes=dyn, opset_version=17,
|
| 262 |
+
do_constant_folding=True, dynamo=False)
|
| 263 |
+
print("Export geschrieben.", flush=True)
|
| 264 |
+
del wrapper, d_past, d_emb, d_ple
|
| 265 |
+
del model, lm, lm_head
|
| 266 |
+
gc.collect()
|
| 267 |
+
|
| 268 |
+
log("C.1) Konsolidierung fp32")
|
| 269 |
+
m = onnx.load(str(S1), load_external_data=True)
|
| 270 |
+
onnx.save_model(m, str(S1), save_as_external_data=True,
|
| 271 |
+
all_tensors_to_one_file=True, location=S1_D, size_threshold=1024)
|
| 272 |
+
del m; gc.collect()
|
| 273 |
+
for f in ONNX_DIR.iterdir():
|
| 274 |
+
if f.name.startswith(("onnx__", "lm.", "_")):
|
| 275 |
+
f.unlink()
|
| 276 |
+
else:
|
| 277 |
+
print("S1 existiert bereits — Export uebersprungen.", flush=True)
|
| 278 |
+
del model, lm, lm_head
|
| 279 |
+
gc.collect()
|
| 280 |
+
|
| 281 |
+
log("MESSUNG S1 (fp32) — das ist die Referenz")
|
| 282 |
+
measure(S1, "S1 fp32", fp16_io=False)
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
# ============================================================ D) fp16
|
| 286 |
+
if not S2.exists():
|
| 287 |
+
log("D) fp16-Konvertierung + fix_edges")
|
| 288 |
+
from onnxconverter_common import float16
|
| 289 |
+
m32 = onnx.load(str(S1), load_external_data=True)
|
| 290 |
+
m16 = float16.convert_float_to_float16(m32, keep_io_types=False,
|
| 291 |
+
disable_shape_infer=True, op_block_list=[])
|
| 292 |
+
ne = fix_edges(m16)
|
| 293 |
+
print(f"fix_edges Casts: {ne}", flush=True)
|
| 294 |
+
onnx.save_model(m16, str(S2), save_as_external_data=True,
|
| 295 |
+
all_tensors_to_one_file=True, location=S2_D, size_threshold=1024)
|
| 296 |
+
del m32, m16; gc.collect()
|
| 297 |
+
else:
|
| 298 |
+
print("S2 existiert bereits.", flush=True)
|
| 299 |
+
|
| 300 |
+
log("MESSUNG S2 (fp16, ohne RMSNorm-Wrap)")
|
| 301 |
+
measure(S2, "S2 fp16", fp16_io=True)
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
# ============================================================ E) RMSNorm
|
| 305 |
+
if not S3.exists():
|
| 306 |
+
log("E) RMSNorm-fp32-Wrap")
|
| 307 |
+
m = onnx.load(str(S2), load_external_data=True)
|
| 308 |
+
nw = wrap_rmsnorm_fp32(m)
|
| 309 |
+
print(f"ReduceMean gewrappt: {nw}", flush=True)
|
| 310 |
+
onnx.save_model(m, str(S3), save_as_external_data=True,
|
| 311 |
+
all_tensors_to_one_file=True, location=S3_D, size_threshold=1024)
|
| 312 |
+
del m; gc.collect()
|
| 313 |
+
else:
|
| 314 |
+
print("S3 existiert bereits.", flush=True)
|
| 315 |
+
|
| 316 |
+
log("MESSUNG S3 (fp16 + RMSNorm-fp32)")
|
| 317 |
+
measure(S3, "S3 fp16+RMSwrap", fp16_io=True)
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
# ============================================================ F) q4f16
|
| 321 |
+
if not S4.exists():
|
| 322 |
+
log("F) q4f16 — asymmetrisch, lm_head ausgenommen")
|
| 323 |
+
from onnxruntime.quantization.matmul_nbits_quantizer import (
|
| 324 |
+
MatMulNBitsQuantizer as Q, DefaultWeightOnlyQuantConfig)
|
| 325 |
+
mf = onnx.load(str(S3), load_external_data=True)
|
| 326 |
+
|
| 327 |
+
# lm_head finden: die MatMul mit der groessten Gewichtsmatrix.
|
| 328 |
+
dims = {i.name: list(i.dims) for i in mf.graph.initializer}
|
| 329 |
+
big, bigsz = None, 0
|
| 330 |
+
for nd in mf.graph.node:
|
| 331 |
+
if nd.op_type in ("MatMul", "Gemm"):
|
| 332 |
+
for inp in nd.input:
|
| 333 |
+
d = dims.get(inp)
|
| 334 |
+
if d and len(d) == 2:
|
| 335 |
+
sz = d[0] * d[1]
|
| 336 |
+
if sz > bigsz:
|
| 337 |
+
bigsz, big = sz, nd.name
|
| 338 |
+
excl = [big] if big else []
|
| 339 |
+
print(f"lm_head-Kandidat ausgenommen: {big} ({bigsz/1e6:.0f}M Params)", flush=True)
|
| 340 |
+
|
| 341 |
+
quant = Q(mf, algo_config=DefaultWeightOnlyQuantConfig(
|
| 342 |
+
block_size=32, is_symmetric=False, accuracy_level=4),
|
| 343 |
+
nodes_to_exclude=excl)
|
| 344 |
+
quant.process()
|
| 345 |
+
qm = quant.model.model if hasattr(quant.model, "model") else quant.model
|
| 346 |
+
onnx.save_model(qm, str(S4), save_as_external_data=True,
|
| 347 |
+
all_tensors_to_one_file=True, location=S4_D, size_threshold=1024)
|
| 348 |
+
del mf, quant, qm; gc.collect()
|
| 349 |
+
else:
|
| 350 |
+
print("S4 existiert bereits.", flush=True)
|
| 351 |
+
|
| 352 |
+
log("MESSUNG S4 (q4f16 — Endprodukt)")
|
| 353 |
+
measure(S4, "S4 q4f16", fp16_io=True)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
# ============================================================ G) Beiwerk
|
| 357 |
+
log("G) Stock-Embed + Cast auf fp16 + config/tokenizer")
|
| 358 |
+
from huggingface_hub import hf_hub_download
|
| 359 |
+
|
| 360 |
+
for fn in ("onnx/embed_tokens_q4f16.onnx", "onnx/embed_tokens_q4f16.onnx_data"):
|
| 361 |
+
p = hf_hub_download(STOCK, fn, local_dir="/root/stock-embed")
|
| 362 |
+
shutil.copy(p, ONNX_DIR / Path(fn).name)
|
| 363 |
+
print("geholt:", fn, flush=True)
|
| 364 |
+
|
| 365 |
+
ep = ONNX_DIR / "embed_tokens_q4f16.onnx"
|
| 366 |
+
em = onnx.load(str(ep), load_external_data=False)
|
| 367 |
+
tg = [o.name for o in em.graph.output if o.type.tensor_type.elem_type == TensorProto.FLOAT]
|
| 368 |
+
pr = {o: (nd, i) for nd in em.graph.node for i, o in enumerate(nd.output) if o in tg}
|
| 369 |
+
for name in tg:
|
| 370 |
+
nd, idx = pr[name]; pre = name + "_fp32"; nd.output[idx] = pre
|
| 371 |
+
em.graph.node.append(helper.make_node("Cast", [pre], [name],
|
| 372 |
+
to=TensorProto.FLOAT16,
|
| 373 |
+
name=name + "/CastToFp16"))
|
| 374 |
+
for o in em.graph.output:
|
| 375 |
+
if o.name == name:
|
| 376 |
+
o.type.tensor_type.elem_type = TensorProto.FLOAT16
|
| 377 |
+
onnx.save(em, str(ep))
|
| 378 |
+
print("Embed-Outputs auf fp16 gecastet:", tg, flush=True)
|
| 379 |
+
|
| 380 |
+
tok.save_pretrained(str(OUT))
|
| 381 |
+
from transformers import AutoConfig
|
| 382 |
+
AutoConfig.from_pretrained(MODEL_ID).save_pretrained(str(OUT))
|
| 383 |
+
cp = OUT / "config.json"; cfg = json.load(open(cp))
|
| 384 |
+
cfg["transformers.js_config"] = {
|
| 385 |
+
"dtype": "q4f16",
|
| 386 |
+
"use_external_data_format": {"decoder_model_merged_q4f16.onnx": 2,
|
| 387 |
+
"embed_tokens_q4f16.onnx": True},
|
| 388 |
+
"kv_cache_dtype": "float16"}
|
| 389 |
+
json.dump(cfg, open(cp, "w"), indent=2)
|
| 390 |
+
|
| 391 |
+
tcp = OUT / "tokenizer_config.json"; jinja = OUT / "chat_template.jinja"
|
| 392 |
+
if jinja.exists():
|
| 393 |
+
tc = json.load(open(tcp))
|
| 394 |
+
tc["chat_template"] = jinja.read_text(encoding="utf-8")
|
| 395 |
+
json.dump(tc, open(tcp, "w"), ensure_ascii=False, indent=2)
|
| 396 |
+
print("chat_template eingebettet.", flush=True)
|
| 397 |
+
|
| 398 |
+
gc_cfg = OUT / "generation_config.json"
|
| 399 |
+
if not gc_cfg.exists():
|
| 400 |
+
json.dump({"eos_token_id": [1, 106, 50], "bos_token_id": 2,
|
| 401 |
+
"pad_token_id": 0}, open(gc_cfg, "w"), indent=2)
|
| 402 |
+
print("generation_config.json angelegt.", flush=True)
|
| 403 |
+
|
| 404 |
+
table()
|
| 405 |
+
log("FERTIG. Zwischenstufen bleiben liegen. /root ist fluechtig — JETZT sichern!")
|