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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""
|
| 3 |
+
02_export_quant_b.py — WEG B
|
| 4 |
+
Gemma 4 E4B (gfp78/gemma4-bund-merged) -> EIN ONNX-Decoder -> q4f16
|
| 5 |
+
|
| 6 |
+
Unterschied zu 01: Der Wrapper nimmt input_ids statt inputs_embeds.
|
| 7 |
+
Der Decoder erzeugt Embeddings UND Per-Layer-Embeddings (PLE) intern selbst.
|
| 8 |
+
Kein separates embed_tokens.onnx, kein Reverse-Lookup.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import gc
|
| 12 |
+
import os
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import onnx
|
| 17 |
+
|
| 18 |
+
os.environ.setdefault("HF_HOME", "/root/hf")
|
| 19 |
+
|
| 20 |
+
MODEL_ID = "gfp78/gemma4-bund-merged"
|
| 21 |
+
OUT = Path("/root/train/gemma4-bund-onnx")
|
| 22 |
+
OUT.mkdir(parents=True, exist_ok=True)
|
| 23 |
+
|
| 24 |
+
FP32_ONNX = OUT / "decoder_model_merged.onnx"
|
| 25 |
+
FP32_DATA = "decoder_model_merged.onnx_data"
|
| 26 |
+
Q4_ONNX = OUT / "decoder_model_merged_q4f16.onnx"
|
| 27 |
+
Q4_DATA = "decoder_model_merged_q4f16.onnx_data"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def log(m):
|
| 31 |
+
print(f"\n=== {m}", flush=True)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# ------------------------------------------------------------------ A) laden
|
| 35 |
+
log("A) Modell laden")
|
| 36 |
+
from transformers import AutoTokenizer, AutoModelForImageTextToText, DynamicCache
|
| 37 |
+
|
| 38 |
+
tok = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 39 |
+
model = AutoModelForImageTextToText.from_pretrained(
|
| 40 |
+
MODEL_ID, dtype=torch.float32, device_map="cpu"
|
| 41 |
+
)
|
| 42 |
+
model.eval()
|
| 43 |
+
|
| 44 |
+
lm = model.model.language_model
|
| 45 |
+
lm_head = model.lm_head if hasattr(model, "lm_head") else model.get_output_embeddings()
|
| 46 |
+
print("hidden_size:", lm.config.hidden_size)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# ------------------------------------------------- B) Cache-Geometrie messen
|
| 50 |
+
log("B) Trockenlauf: Cache-Layer + Head-Dims")
|
| 51 |
+
with torch.no_grad():
|
| 52 |
+
probe = lm(input_ids=torch.tensor([[1, 2, 3, 4]]), use_cache=True, return_dict=True)
|
| 53 |
+
|
| 54 |
+
pkv = probe.past_key_values
|
| 55 |
+
N_CACHE = len(pkv.layers)
|
| 56 |
+
print("n_cache_layers:", N_CACHE, " (erwartet: 24)")
|
| 57 |
+
|
| 58 |
+
KV_SHAPES = []
|
| 59 |
+
for i in range(N_CACHE):
|
| 60 |
+
k = pkv.layers[i].keys
|
| 61 |
+
KV_SHAPES.append((int(k.shape[1]), int(k.shape[3])))
|
| 62 |
+
print(f" layer {i:2d}: n_kv_heads={k.shape[1]}, head_dim={k.shape[3]}")
|
| 63 |
+
|
| 64 |
+
del probe, pkv
|
| 65 |
+
gc.collect()
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# ---------------------------------------------------------------- C) Wrapper
|
| 69 |
+
class DecoderWrapper(torch.nn.Module):
|
| 70 |
+
"""input_ids + attention_mask + position_ids + past -> logits + present"""
|
| 71 |
+
|
| 72 |
+
def __init__(self, lm, lm_head, n_cache):
|
| 73 |
+
super().__init__()
|
| 74 |
+
self.lm = lm
|
| 75 |
+
self.lm_head = lm_head
|
| 76 |
+
self.n_cache = n_cache
|
| 77 |
+
|
| 78 |
+
def forward(self, input_ids, attention_mask, position_ids, *past):
|
| 79 |
+
cache = None
|
| 80 |
+
if len(past) == 2 * self.n_cache and past[0].shape[2] > 0:
|
| 81 |
+
cache = DynamicCache(config=self.lm.config)
|
| 82 |
+
for i in range(self.n_cache):
|
| 83 |
+
cache.update(past[2 * i], past[2 * i + 1], i)
|
| 84 |
+
|
| 85 |
+
out = self.lm(
|
| 86 |
+
input_ids=input_ids, # <-- Weg B: ids, nicht embeds
|
| 87 |
+
attention_mask=attention_mask,
|
| 88 |
+
position_ids=position_ids,
|
| 89 |
+
past_key_values=cache,
|
| 90 |
+
use_cache=True,
|
| 91 |
+
return_dict=True,
|
| 92 |
+
)
|
| 93 |
+
logits = self.lm_head(out.last_hidden_state)
|
| 94 |
+
|
| 95 |
+
present = []
|
| 96 |
+
for i in range(self.n_cache):
|
| 97 |
+
present.append(out.past_key_values.layers[i].keys)
|
| 98 |
+
present.append(out.past_key_values.layers[i].values)
|
| 99 |
+
return (logits, *present)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
wrapper = DecoderWrapper(lm, lm_head, N_CACHE).eval()
|
| 103 |
+
|
| 104 |
+
log("C) Dummy-Inputs (echte Token-ID, keine Nullen)")
|
| 105 |
+
B, S, P = 1, 1, 1
|
| 106 |
+
dummy_ids = torch.tensor([[42]], dtype=torch.long)
|
| 107 |
+
dummy_mask = torch.ones(B, P + S, dtype=torch.long)
|
| 108 |
+
dummy_pos = torch.tensor([[P]], dtype=torch.long)
|
| 109 |
+
|
| 110 |
+
dummy_past = []
|
| 111 |
+
for (n_kv, hd) in KV_SHAPES:
|
| 112 |
+
dummy_past.append(torch.zeros(B, n_kv, P, hd, dtype=torch.float32))
|
| 113 |
+
dummy_past.append(torch.zeros(B, n_kv, P, hd, dtype=torch.float32))
|
| 114 |
+
|
| 115 |
+
input_names = ["input_ids", "attention_mask", "position_ids"]
|
| 116 |
+
output_names = ["logits"]
|
| 117 |
+
dynamic_axes = {
|
| 118 |
+
"input_ids": {0: "batch", 1: "seq"},
|
| 119 |
+
"attention_mask": {0: "batch", 1: "total"},
|
| 120 |
+
"position_ids": {0: "batch", 1: "seq"},
|
| 121 |
+
"logits": {0: "batch", 1: "seq"},
|
| 122 |
+
}
|
| 123 |
+
for i in range(N_CACHE):
|
| 124 |
+
for kv in ("key", "value"):
|
| 125 |
+
pn, on = f"past_key_values.{i}.{kv}", f"present.{i}.{kv}"
|
| 126 |
+
input_names.append(pn)
|
| 127 |
+
output_names.append(on)
|
| 128 |
+
dynamic_axes[pn] = {0: "batch", 2: "past_seq"}
|
| 129 |
+
dynamic_axes[on] = {0: "batch", 2: "total_seq"}
|
| 130 |
+
|
| 131 |
+
log("C) torch.onnx.export laeuft — LANGE STILLE IST NORMAL")
|
| 132 |
+
with torch.no_grad():
|
| 133 |
+
torch.onnx.export(
|
| 134 |
+
wrapper,
|
| 135 |
+
(dummy_ids, dummy_mask, dummy_pos, *dummy_past),
|
| 136 |
+
str(FP32_ONNX),
|
| 137 |
+
input_names=input_names,
|
| 138 |
+
output_names=output_names,
|
| 139 |
+
dynamic_axes=dynamic_axes,
|
| 140 |
+
opset_version=17,
|
| 141 |
+
do_constant_folding=True,
|
| 142 |
+
dynamo=False,
|
| 143 |
+
)
|
| 144 |
+
print("Export geschrieben.")
|
| 145 |
+
|
| 146 |
+
del model, lm, lm_head, wrapper, dummy_past
|
| 147 |
+
gc.collect()
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
# --------------------------------------------------------- D) Konsolidierung
|
| 151 |
+
log("D) Konsolidierung (finaler Name direkt, NIE danach umbenennen)")
|
| 152 |
+
m = onnx.load(str(FP32_ONNX), load_external_data=True)
|
| 153 |
+
onnx.save_model(m, str(FP32_ONNX), save_as_external_data=True,
|
| 154 |
+
all_tensors_to_one_file=True, location=FP32_DATA, size_threshold=1024)
|
| 155 |
+
del m
|
| 156 |
+
gc.collect()
|
| 157 |
+
|
| 158 |
+
for f in OUT.iterdir():
|
| 159 |
+
if f.name.startswith("onnx__") or f.name.startswith("_"):
|
| 160 |
+
f.unlink()
|
| 161 |
+
os.system(f"df -h /root; free -g; ls -la {OUT}")
|
| 162 |
+
|
| 163 |
+
onnx.checker.check_model(str(FP32_ONNX))
|
| 164 |
+
print("fp32-Graph valide.")
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
# ------------------------------------------------------------ E) q4f16
|
| 168 |
+
log("E) q4f16-Quantisierung")
|
| 169 |
+
try:
|
| 170 |
+
from onnxruntime.quantization.matmul_nbits_quantizer import (
|
| 171 |
+
MatMulNBitsQuantizer as Q, DefaultWeightOnlyQuantConfig)
|
| 172 |
+
except ImportError:
|
| 173 |
+
from onnxruntime.quantization.matmul_4bits_quantizer import (
|
| 174 |
+
MatMul4BitsQuantizer as Q, DefaultWeightOnlyQuantConfig)
|
| 175 |
+
|
| 176 |
+
model_fp32 = onnx.load(str(FP32_ONNX), load_external_data=True)
|
| 177 |
+
cfg = DefaultWeightOnlyQuantConfig(block_size=32, is_symmetric=True, accuracy_level=4)
|
| 178 |
+
quant = Q(model_fp32, algo_config=cfg)
|
| 179 |
+
quant.process()
|
| 180 |
+
|
| 181 |
+
qm = quant.model.model if hasattr(quant.model, "model") else quant.model
|
| 182 |
+
onnx.save_model(qm, str(Q4_ONNX), save_as_external_data=True,
|
| 183 |
+
all_tensors_to_one_file=True, location=Q4_DATA, size_threshold=1024)
|
| 184 |
+
print("q4f16 geschrieben.")
|
| 185 |
+
|
| 186 |
+
del model_fp32, quant, qm
|
| 187 |
+
gc.collect()
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
# ------------------------------------------------------- F) Verifikation
|
| 191 |
+
log("F) Verifikation")
|
| 192 |
+
onnx.checker.check_model(str(Q4_ONNX))
|
| 193 |
+
size_mb = (OUT / Q4_DATA).stat().st_size / 1e6
|
| 194 |
+
print(f"{Q4_DATA}: {size_mb:.0f} MB")
|
| 195 |
+
print("!! >3500 MB = Browser-Limit gefaehrdet" if size_mb > 3500 else "OK: browsertauglich")
|
| 196 |
+
|
| 197 |
+
import onnxruntime as ort
|
| 198 |
+
sess = ort.InferenceSession(str(Q4_ONNX), providers=["CPUExecutionProvider"])
|
| 199 |
+
print("Session OK. Inputs:", len(sess.get_inputs()), "Outputs:", len(sess.get_outputs()))
|
| 200 |
+
|
| 201 |
+
tok.save_pretrained(str(OUT.parent / "gemma4-bund-final"))
|
| 202 |
+
log("FERTIG — jetzt SOFORT auf HF pushen, /root ist fluechtig!")
|