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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""
|
| 3 |
+
07_export_quant_c_v2.py — WEG C, KORRIGIERTE fp16-Konvertierung.
|
| 4 |
+
|
| 5 |
+
Unterschied zu 03_export_quant_c.py:
|
| 6 |
+
- D.5 haelt RMSNorm/Softcap in fp32 (Default-op_block_list) statt alles fp16 zu
|
| 7 |
+
erzwingen. Dafuer wird VOR der Konvertierung dateibasierte Shape-Inference
|
| 8 |
+
gefahren (infer_shapes_path, vertraegt >2GB), damit convert_float_to_float16
|
| 9 |
+
die Cast-Bruecken an den fp32/fp16-Grenzen korrekt setzt.
|
| 10 |
+
- KEIN fix_fp16_edges mehr (wir WOLLEN die fp32-Inseln — sie verhindern den
|
| 11 |
+
fp16-Ueberlauf in der RMSNorm-Reduktion auf echten WebGPU-Kerneln).
|
| 12 |
+
|
| 13 |
+
Grund: op_block_list=[] erzwang fp16 ueberall -> ReduceMean-Summe (mean(x^2) ueber
|
| 14 |
+
2560 Dims, x~50 nach Gemma-Normalizer) sprengt fp16-Max (65504) auf WebGPU -> NaN.
|
| 15 |
+
ORT-CPU rechnet intern fp32 und verzeiht das (deshalb war der CPU-Test kohaerent).
|
| 16 |
+
|
| 17 |
+
Start IMMER mit nohup:
|
| 18 |
+
nohup python 07_export_quant_c_v2.py > export_v2.log 2>&1 &
|
| 19 |
+
"""
|
| 20 |
+
import gc, os
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
import torch, onnx
|
| 23 |
+
|
| 24 |
+
os.environ.setdefault("HF_HOME", "/root/hf-cache")
|
| 25 |
+
|
| 26 |
+
MODEL_ID = "/root/gemma4-bund-merged" # LOKAL (kein Re-Download)
|
| 27 |
+
STOCK = "onnx-community/gemma-4-E4B-it-ONNX"
|
| 28 |
+
OUT = Path("/root/train/gemma4-bund-final-v2")
|
| 29 |
+
ONNX_DIR = OUT / "onnx"; ONNX_DIR.mkdir(parents=True, exist_ok=True)
|
| 30 |
+
|
| 31 |
+
FP32 = ONNX_DIR / "decoder_model_merged.onnx"
|
| 32 |
+
FP32_DATA = "decoder_model_merged.onnx_data"
|
| 33 |
+
FP32_SI = ONNX_DIR / "decoder_model_merged_si.onnx" # shape-inferred
|
| 34 |
+
FP32_SI_DATA = "decoder_model_merged_si.onnx_data"
|
| 35 |
+
FP16 = ONNX_DIR / "decoder_model_merged_fp16.onnx"
|
| 36 |
+
FP16_DATA = "decoder_model_merged_fp16.onnx_data"
|
| 37 |
+
Q4 = ONNX_DIR / "decoder_model_merged_q4f16.onnx"
|
| 38 |
+
Q4_DATA = "decoder_model_merged_q4f16.onnx_data"
|
| 39 |
+
|
| 40 |
+
def log(m): print(f"\n=== {m}", flush=True)
|
| 41 |
+
|
| 42 |
+
# ------------------------------------------------------------------ A) laden
|
| 43 |
+
log("A) Modell laden (fp32)")
|
| 44 |
+
from transformers import AutoTokenizer, AutoModelForImageTextToText, DynamicCache
|
| 45 |
+
tok = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 46 |
+
model = AutoModelForImageTextToText.from_pretrained(MODEL_ID, dtype=torch.float32, device_map="cpu")
|
| 47 |
+
model.eval()
|
| 48 |
+
lm = model.model.language_model
|
| 49 |
+
lm_head = model.lm_head if hasattr(model, "lm_head") else model.get_output_embeddings()
|
| 50 |
+
print("hidden_size:", lm.config.hidden_size)
|
| 51 |
+
|
| 52 |
+
# ------------------------------------------------- B) Cache-Geometrie messen
|
| 53 |
+
log("B) Trockenlauf")
|
| 54 |
+
with torch.no_grad():
|
| 55 |
+
ids = torch.tensor([[1, 2, 3, 4]])
|
| 56 |
+
emb = lm.get_input_embeddings()(ids)
|
| 57 |
+
ple = lm.get_per_layer_inputs(ids, emb)
|
| 58 |
+
print("per_layer_inputs Shape:", tuple(ple.shape), "(erwartet: 1,4,42,256)")
|
| 59 |
+
probe = lm(inputs_embeds=emb, per_layer_inputs=ple, use_cache=True, return_dict=True)
|
| 60 |
+
pkv = probe.past_key_values
|
| 61 |
+
N_CACHE = len(pkv.layers)
|
| 62 |
+
print("n_cache_layers:", N_CACHE, "(erwartet: 24)")
|
| 63 |
+
KV_SHAPES = [(int(pkv.layers[i].keys.shape[1]), int(pkv.layers[i].keys.shape[3])) for i in range(N_CACHE)]
|
| 64 |
+
print("head_dims:", sorted({s[1] for s in KV_SHAPES}), "(erwartet: [256, 512])")
|
| 65 |
+
del probe, pkv, emb, ple, ids; gc.collect()
|
| 66 |
+
|
| 67 |
+
# ---------------------------------------------------------------- C) Wrapper
|
| 68 |
+
class DecoderWrapper(torch.nn.Module):
|
| 69 |
+
def __init__(self, lm, lm_head, n_cache):
|
| 70 |
+
super().__init__(); self.lm, self.lm_head, self.n_cache = lm, lm_head, n_cache
|
| 71 |
+
def forward(self, inputs_embeds, per_layer_inputs, attention_mask, position_ids, *past):
|
| 72 |
+
cache = None
|
| 73 |
+
if len(past) == 2 * self.n_cache and past[0].shape[2] > 0:
|
| 74 |
+
cache = DynamicCache(config=self.lm.config)
|
| 75 |
+
for i in range(self.n_cache):
|
| 76 |
+
cache.update(past[2*i], past[2*i+1], i)
|
| 77 |
+
out = self.lm(inputs_embeds=inputs_embeds, per_layer_inputs=per_layer_inputs,
|
| 78 |
+
attention_mask=attention_mask, position_ids=position_ids,
|
| 79 |
+
past_key_values=cache, use_cache=True, return_dict=True)
|
| 80 |
+
logits = self.lm_head(out.last_hidden_state)
|
| 81 |
+
present = []
|
| 82 |
+
for i in range(self.n_cache):
|
| 83 |
+
present.append(out.past_key_values.layers[i].keys)
|
| 84 |
+
present.append(out.past_key_values.layers[i].values)
|
| 85 |
+
return (logits, *present)
|
| 86 |
+
|
| 87 |
+
wrapper = DecoderWrapper(lm, lm_head, N_CACHE).eval()
|
| 88 |
+
log("C) Dummy-Inputs")
|
| 89 |
+
B, S, P = 1, 1, 1
|
| 90 |
+
with torch.no_grad():
|
| 91 |
+
d_ids = torch.tensor([[42]], dtype=torch.long)
|
| 92 |
+
d_emb = lm.get_input_embeddings()(d_ids).detach()
|
| 93 |
+
d_ple = lm.get_per_layer_inputs(d_ids, d_emb).detach()
|
| 94 |
+
d_mask = torch.ones(B, P + S, dtype=torch.long)
|
| 95 |
+
d_pos = torch.tensor([[P]], dtype=torch.long)
|
| 96 |
+
d_past = []
|
| 97 |
+
for (n_kv, hd) in KV_SHAPES:
|
| 98 |
+
d_past += [torch.zeros(B, n_kv, P, hd), torch.zeros(B, n_kv, P, hd)]
|
| 99 |
+
|
| 100 |
+
input_names = ["inputs_embeds", "per_layer_inputs", "attention_mask", "position_ids"]
|
| 101 |
+
output_names = ["logits"]
|
| 102 |
+
dyn = {"inputs_embeds":{0:"batch",1:"seq"}, "per_layer_inputs":{0:"batch",1:"seq"},
|
| 103 |
+
"attention_mask":{0:"batch",1:"total"}, "position_ids":{0:"batch",1:"seq"},
|
| 104 |
+
"logits":{0:"batch",1:"seq"}}
|
| 105 |
+
for i in range(N_CACHE):
|
| 106 |
+
for kv in ("key","value"):
|
| 107 |
+
pn, on = f"past_key_values.{i}.{kv}", f"present.{i}.{kv}"
|
| 108 |
+
input_names.append(pn); output_names.append(on)
|
| 109 |
+
dyn[pn] = {0:"batch",2:"past_seq"}; dyn[on] = {0:"batch",2:"total_seq"}
|
| 110 |
+
|
| 111 |
+
log("C) torch.onnx.export — LANGE STILLE IST NORMAL")
|
| 112 |
+
with torch.no_grad():
|
| 113 |
+
torch.onnx.export(wrapper, (d_emb, d_ple, d_mask, d_pos, *d_past), str(FP32),
|
| 114 |
+
input_names=input_names, output_names=output_names, dynamic_axes=dyn,
|
| 115 |
+
opset_version=17, do_constant_folding=True, dynamo=False)
|
| 116 |
+
print("Export geschrieben.")
|
| 117 |
+
del model, lm, lm_head, wrapper, d_past, d_emb, d_ple; gc.collect()
|
| 118 |
+
|
| 119 |
+
# --------------------------------------------------------- D) Konsolidierung
|
| 120 |
+
log("D) Konsolidierung")
|
| 121 |
+
m = onnx.load(str(FP32), load_external_data=True)
|
| 122 |
+
onnx.save_model(m, str(FP32), save_as_external_data=True, all_tensors_to_one_file=True,
|
| 123 |
+
location=FP32_DATA, size_threshold=1024)
|
| 124 |
+
del m; gc.collect()
|
| 125 |
+
for f in ONNX_DIR.iterdir():
|
| 126 |
+
if f.name.startswith("onnx__") or f.name.startswith("lm.") or f.name.startswith("_"):
|
| 127 |
+
f.unlink()
|
| 128 |
+
try:
|
| 129 |
+
onnx.checker.check_model(str(FP32)); print("fp32 valide.")
|
| 130 |
+
except Exception as e:
|
| 131 |
+
print("checker uebersprungen (>2GB):", type(e).__name__)
|
| 132 |
+
|
| 133 |
+
# ---------------------------- D.5) KORRIGIERT: Shape-Inference + fp16, RMSNorm bleibt fp32
|
| 134 |
+
log("D.5) Shape-Inference (dateibasiert, >2GB-tauglich)")
|
| 135 |
+
from onnx import shape_inference
|
| 136 |
+
shape_inference.infer_shapes_path(str(FP32), str(FP32_SI))
|
| 137 |
+
print("shape-inferred geschrieben.")
|
| 138 |
+
FP32.unlink(missing_ok=True); (ONNX_DIR / FP32_DATA).unlink(missing_ok=True)
|
| 139 |
+
|
| 140 |
+
log("D.5) fp32 -> fp16 (Default-op_block_list: RMSNorm/Softcap bleiben fp32)")
|
| 141 |
+
from onnxconverter_common import float16
|
| 142 |
+
m32 = onnx.load(str(FP32_SI), load_external_data=True)
|
| 143 |
+
# KEIN op_block_list=[] -> Default-Liste haelt numerisch heikle Ops in fp32.
|
| 144 |
+
# disable_shape_infer=True ist ok, weil FP32_SI bereits value_info traegt.
|
| 145 |
+
m16 = float16.convert_float_to_float16(m32, keep_io_types=False, disable_shape_infer=True)
|
| 146 |
+
onnx.save_model(m16, str(FP16), save_as_external_data=True, all_tensors_to_one_file=True,
|
| 147 |
+
location=FP16_DATA, size_threshold=1024)
|
| 148 |
+
del m32, m16; gc.collect()
|
| 149 |
+
FP32_SI.unlink(missing_ok=True); (ONNX_DIR / FP32_SI_DATA).unlink(missing_ok=True)
|
| 150 |
+
print("fp16 geschrieben (mit fp32-Inseln).")
|
| 151 |
+
|
| 152 |
+
# Verifikation: laedt + RMSNorm-Reduktion fp32?
|
| 153 |
+
import onnxruntime as ort
|
| 154 |
+
try:
|
| 155 |
+
so = ort.SessionOptions(); so.intra_op_num_threads = 4
|
| 156 |
+
ort.InferenceSession(str(FP16), sess_options=so, providers=["CPUExecutionProvider"])
|
| 157 |
+
print("fp16 LAEDT in ORT.")
|
| 158 |
+
except Exception as e:
|
| 159 |
+
print("!! fp16 LAEDT NICHT:", str(e).split(chr(10))[0][:120])
|
| 160 |
+
rm_fp32 = 0
|
| 161 |
+
mm = onnx.load(str(FP16), load_external_data=False)
|
| 162 |
+
vi = {v.name: v.type.tensor_type.elem_type for v in mm.graph.value_info}
|
| 163 |
+
for n in mm.graph.node:
|
| 164 |
+
if n.op_type == "ReduceMean" and vi.get(n.output[0]) == 1:
|
| 165 |
+
rm_fp32 += 1
|
| 166 |
+
print(f"ReduceMean in fp32: {rm_fp32} (erwartet >0)")
|
| 167 |
+
del mm; gc.collect()
|
| 168 |
+
|
| 169 |
+
# ------------------------------------------------------------------ E) q4f16
|
| 170 |
+
log("E) q4f16")
|
| 171 |
+
from onnxruntime.quantization.matmul_nbits_quantizer import (
|
| 172 |
+
MatMulNBitsQuantizer as Q, DefaultWeightOnlyQuantConfig)
|
| 173 |
+
mf = onnx.load(str(FP16), load_external_data=True)
|
| 174 |
+
quant = Q(mf, algo_config=DefaultWeightOnlyQuantConfig(block_size=32, is_symmetric=True, accuracy_level=4))
|
| 175 |
+
quant.process()
|
| 176 |
+
qm = quant.model.model if hasattr(quant.model, "model") else quant.model
|
| 177 |
+
onnx.save_model(qm, str(Q4), save_as_external_data=True, all_tensors_to_one_file=True,
|
| 178 |
+
location=Q4_DATA, size_threshold=1024)
|
| 179 |
+
del mf, quant, qm; gc.collect()
|
| 180 |
+
FP16.unlink(missing_ok=True); (ONNX_DIR / FP16_DATA).unlink(missing_ok=True)
|
| 181 |
+
|
| 182 |
+
# Verifikation nach Quantisierung
|
| 183 |
+
try:
|
| 184 |
+
so = ort.SessionOptions(); so.intra_op_num_threads = 4
|
| 185 |
+
s = ort.InferenceSession(str(Q4), sess_options=so, providers=["CPUExecutionProvider"])
|
| 186 |
+
print("q4f16 LAEDT, Inputs total", len(s.get_inputs()))
|
| 187 |
+
except Exception as e:
|
| 188 |
+
print("!! q4f16 LAEDT NICHT:", str(e).split(chr(10))[0][:120])
|
| 189 |
+
|
| 190 |
+
# ---------------------------------------------------- F) Stock-Embed + Config
|
| 191 |
+
log("F) Stock-Embed holen, Embed-Output auf fp16 casten, Config/Tokenizer schreiben")
|
| 192 |
+
from huggingface_hub import hf_hub_download
|
| 193 |
+
import shutil, json
|
| 194 |
+
from onnx import helper, TensorProto
|
| 195 |
+
for fn in ("onnx/embed_tokens_q4f16.onnx", "onnx/embed_tokens_q4f16.onnx_data"):
|
| 196 |
+
p = hf_hub_download(STOCK, fn, local_dir="/root/stock-embed")
|
| 197 |
+
shutil.copy(p, ONNX_DIR / Path(fn).name); print("geholt:", fn)
|
| 198 |
+
|
| 199 |
+
# Embed-Outputs fp32 -> fp16 casten (sonst dtype-Mismatch zum fp16-Decoder)
|
| 200 |
+
emb_path = ONNX_DIR / "embed_tokens_q4f16.onnx"
|
| 201 |
+
em = onnx.load(str(emb_path), load_external_data=False)
|
| 202 |
+
tgts = [o.name for o in em.graph.output if o.type.tensor_type.elem_type == TensorProto.FLOAT]
|
| 203 |
+
prod = {out: (nd, i) for nd in em.graph.node for i, out in enumerate(nd.output) if out in tgts}
|
| 204 |
+
for name in tgts:
|
| 205 |
+
nd, idx = prod[name]; pre = name + "_fp32"; nd.output[idx] = pre
|
| 206 |
+
em.graph.node.append(helper.make_node("Cast", [pre], [name], to=TensorProto.FLOAT16, name=name+"/CastToFp16"))
|
| 207 |
+
for o in em.graph.output:
|
| 208 |
+
if o.name == name: o.type.tensor_type.elem_type = TensorProto.FLOAT16
|
| 209 |
+
onnx.save(em, str(emb_path))
|
| 210 |
+
print("Embed-Outputs auf fp16 gecastet:", tgts)
|
| 211 |
+
|
| 212 |
+
tok.save_pretrained(str(OUT))
|
| 213 |
+
from transformers import AutoConfig
|
| 214 |
+
c = AutoConfig.from_pretrained(MODEL_ID); c.save_pretrained(str(OUT))
|
| 215 |
+
cp = OUT / "config.json"; cfg = json.load(open(cp))
|
| 216 |
+
cfg["transformers.js_config"] = {
|
| 217 |
+
"dtype": "q4f16",
|
| 218 |
+
"use_external_data_format": {
|
| 219 |
+
"decoder_model_merged_q4f16.onnx": 2, # 2 Chunks: .onnx_data + .onnx_data_1
|
| 220 |
+
"embed_tokens_q4f16.onnx": True,
|
| 221 |
+
},
|
| 222 |
+
"kv_cache_dtype": "float16",
|
| 223 |
+
}
|
| 224 |
+
json.dump(cfg, open(cp, "w"), indent=2)
|
| 225 |
+
|
| 226 |
+
# chat_template ins tokenizer_config.json einbetten (Transformers.js liest es nur von dort)
|
| 227 |
+
tcp = OUT / "tokenizer_config.json"
|
| 228 |
+
jinja = OUT / "chat_template.jinja"
|
| 229 |
+
if jinja.exists():
|
| 230 |
+
tc = json.load(open(tcp)); tc["chat_template"] = jinja.read_text(encoding="utf-8")
|
| 231 |
+
json.dump(tc, open(tcp, "w"), ensure_ascii=False, indent=2)
|
| 232 |
+
print("chat_template in tokenizer_config.json eingebettet.")
|
| 233 |
+
|
| 234 |
+
log("FERTIG bis E/F. NAECHSTE SCHRITTE:")
|
| 235 |
+
print(" 1) Reshard: python 04_reshard.py (REPO/BASE ggf. anpassen, Quelle = dieser Q4)")
|
| 236 |
+
print(" 2) Upload nach gfp78/gemma4-bund-onnx-v2 (oder v1 ueberschreiben)")
|
| 237 |
+
print(" 3) Bundesrechner: 3 Decoder-Dateien + embed + config + tokenizer_config ziehen, Browser-Test")
|
| 238 |
+
print(" !! JETZT SOFORT die q4f16-Dateien sichern — /root ist fluechtig.")
|