Upload 2 files
Browse files- 00_setup_cpu.sh +34 -0
- 01_export_quant.py +243 -0
00_setup_cpu.sh
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# 00_setup_cpu.sh — RunPod CPU-Pod (16 vCPU / 64 GB RAM / 100 GB Disk)
|
| 3 |
+
# Alles auf /root (Container Disk), NICHT auf /workspace (Quota-Limit).
|
| 4 |
+
set -e
|
| 5 |
+
|
| 6 |
+
export HF_HOME=/root/hf
|
| 7 |
+
mkdir -p /root/hf /root/train
|
| 8 |
+
|
| 9 |
+
python -m venv /root/venv
|
| 10 |
+
source /root/venv/bin/activate
|
| 11 |
+
pip install -U pip
|
| 12 |
+
|
| 13 |
+
# CPU-Torch (kein CUDA-Wheel — spart ~2.5 GB Download)
|
| 14 |
+
pip install torch --index-url https://download.pytorch.org/whl/cpu
|
| 15 |
+
|
| 16 |
+
# KEIN optimum installieren: zieht transformers<4.58 und bricht Gemma 4.
|
| 17 |
+
pip install "transformers>=5.13" accelerate safetensors sentencepiece pillow
|
| 18 |
+
pip install onnx onnxruntime numpy
|
| 19 |
+
|
| 20 |
+
# Threads auf die 16 Cores setzen
|
| 21 |
+
export OMP_NUM_THREADS=16
|
| 22 |
+
echo 'export OMP_NUM_THREADS=16' >> /root/venv/bin/activate
|
| 23 |
+
echo 'export HF_HOME=/root/hf' >> /root/venv/bin/activate
|
| 24 |
+
|
| 25 |
+
df -h /root
|
| 26 |
+
free -g
|
| 27 |
+
python - <<'PY'
|
| 28 |
+
import torch, transformers, onnx, onnxruntime
|
| 29 |
+
print("torch ", torch.__version__)
|
| 30 |
+
print("transformers ", transformers.__version__)
|
| 31 |
+
print("onnx ", onnx.__version__)
|
| 32 |
+
print("onnxruntime ", onnxruntime.__version__) # <-- diese Zeile brauche ich!
|
| 33 |
+
PY
|
| 34 |
+
echo "--- Setup fertig."
|
01_export_quant.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""
|
| 3 |
+
01_export_quant.py
|
| 4 |
+
Gemma 4 E4B (gfp78/gemma4-bund-merged) -> ONNX-Decoder -> q4f16
|
| 5 |
+
|
| 6 |
+
Phasen:
|
| 7 |
+
A) Modell laden (bf16 -> fp32 auf CPU/GPU)
|
| 8 |
+
B) Cache-Layer + Head-Dims per Trockenlauf ermitteln (NICHT raten)
|
| 9 |
+
C) torch.onnx.export (Legacy-Tracer, dynamo=False)
|
| 10 |
+
D) Konsolidierung zu EINER .onnx_data (finaler Name direkt!)
|
| 11 |
+
E) MatMul4BitsQuantizer -> q4f16
|
| 12 |
+
F) Verifikation + Groessen-Check
|
| 13 |
+
|
| 14 |
+
Laufzeit-Schaetzung: A-D ~40 Min, E ~10-25 Min.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
import gc
|
| 18 |
+
import os
|
| 19 |
+
import shutil
|
| 20 |
+
import sys
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
import onnx
|
| 25 |
+
|
| 26 |
+
os.environ.setdefault("HF_HOME", "/root/hf")
|
| 27 |
+
|
| 28 |
+
MODEL_ID = "gfp78/gemma4-bund-merged"
|
| 29 |
+
OUT = Path("/root/train/gemma4-bund-onnx")
|
| 30 |
+
OUT.mkdir(parents=True, exist_ok=True)
|
| 31 |
+
|
| 32 |
+
FP32_ONNX = OUT / "decoder_model_merged.onnx"
|
| 33 |
+
FP32_DATA = "decoder_model_merged.onnx_data" # relativer Name, PFLICHT
|
| 34 |
+
Q4_ONNX = OUT / "decoder_model_merged_q4f16.onnx"
|
| 35 |
+
Q4_DATA = "decoder_model_merged_q4f16.onnx_data"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def log(msg):
|
| 39 |
+
print(f"\n=== {msg}", flush=True)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# ---------------------------------------------------------------- A) laden
|
| 43 |
+
log("A) Modell laden")
|
| 44 |
+
from transformers import AutoTokenizer, AutoModelForImageTextToText, DynamicCache
|
| 45 |
+
|
| 46 |
+
tok = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 47 |
+
model = AutoModelForImageTextToText.from_pretrained(
|
| 48 |
+
MODEL_ID, dtype=torch.float32, device_map="cpu"
|
| 49 |
+
)
|
| 50 |
+
model.eval()
|
| 51 |
+
|
| 52 |
+
# Sprach-Turm + lm_head separat: language_model liefert nur last_hidden_state,
|
| 53 |
+
# die lm_head-Projektion sitzt eine Ebene hoeher.
|
| 54 |
+
lm = model.model.language_model
|
| 55 |
+
lm_head = model.lm_head if hasattr(model, "lm_head") else model.get_output_embeddings()
|
| 56 |
+
tcfg = lm.config
|
| 57 |
+
HIDDEN = tcfg.hidden_size
|
| 58 |
+
print("hidden_size:", HIDDEN)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# ------------------------------------------- B) Cache-Geometrie ermitteln
|
| 62 |
+
log("B) Trockenlauf: Anzahl Cache-Layer + Head-Dims ermitteln")
|
| 63 |
+
with torch.no_grad():
|
| 64 |
+
probe_ids = torch.tensor([[1, 2, 3, 4]], dtype=torch.long)
|
| 65 |
+
probe_emb = lm.get_input_embeddings()(probe_ids)
|
| 66 |
+
probe = lm(inputs_embeds=probe_emb, use_cache=True, return_dict=True)
|
| 67 |
+
|
| 68 |
+
pkv = probe.past_key_values
|
| 69 |
+
N_CACHE = len(pkv.layers) # transformers 5.13: .layers, nicht .key_cache
|
| 70 |
+
print("n_cache_layers:", N_CACHE) # erwartet: 24 (nicht 42!)
|
| 71 |
+
|
| 72 |
+
# Gemma 4 hat ZWEI Head-Dims: 256 (sliding window) und 512 (full attention).
|
| 73 |
+
# Deshalb pro Layer die echte Form auslesen statt eine globale anzunehmen.
|
| 74 |
+
KV_SHAPES = []
|
| 75 |
+
for i in range(N_CACHE):
|
| 76 |
+
k = pkv.layers[i].keys
|
| 77 |
+
KV_SHAPES.append((int(k.shape[1]), int(k.shape[3]))) # (n_kv_heads, head_dim)
|
| 78 |
+
for i, s in enumerate(KV_SHAPES):
|
| 79 |
+
print(f" layer {i:2d}: n_kv_heads={s[0]}, head_dim={s[1]}")
|
| 80 |
+
|
| 81 |
+
del probe, pkv, probe_emb
|
| 82 |
+
gc.collect()
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
# ------------------------------------------------------------ C) Wrapper
|
| 86 |
+
class DecoderWrapper(torch.nn.Module):
|
| 87 |
+
"""inputs_embeds + attention_mask + position_ids + past -> logits + present"""
|
| 88 |
+
|
| 89 |
+
def __init__(self, lm, lm_head, n_cache):
|
| 90 |
+
super().__init__()
|
| 91 |
+
self.lm = lm
|
| 92 |
+
self.lm_head = lm_head
|
| 93 |
+
self.n_cache = n_cache
|
| 94 |
+
|
| 95 |
+
def forward(self, inputs_embeds, attention_mask, position_ids, *past):
|
| 96 |
+
cache = None
|
| 97 |
+
if len(past) == 2 * self.n_cache and past[0].shape[2] > 0:
|
| 98 |
+
cache = DynamicCache(config=self.lm.config)
|
| 99 |
+
for i in range(self.n_cache):
|
| 100 |
+
cache.update(past[2 * i], past[2 * i + 1], i)
|
| 101 |
+
|
| 102 |
+
out = self.lm(
|
| 103 |
+
inputs_embeds=inputs_embeds,
|
| 104 |
+
attention_mask=attention_mask,
|
| 105 |
+
position_ids=position_ids,
|
| 106 |
+
past_key_values=cache,
|
| 107 |
+
use_cache=True,
|
| 108 |
+
return_dict=True,
|
| 109 |
+
)
|
| 110 |
+
logits = self.lm_head(out.last_hidden_state)
|
| 111 |
+
|
| 112 |
+
present = []
|
| 113 |
+
for i in range(self.n_cache):
|
| 114 |
+
present.append(out.past_key_values.layers[i].keys)
|
| 115 |
+
present.append(out.past_key_values.layers[i].values)
|
| 116 |
+
return (logits, *present)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
wrapper = DecoderWrapper(lm, lm_head, N_CACHE).eval()
|
| 120 |
+
|
| 121 |
+
log("C) Dummy-Inputs bauen (P=1 Vergangenheit, S=1 neues Token)")
|
| 122 |
+
B, S, P = 1, 1, 1
|
| 123 |
+
dummy_embeds = torch.zeros(B, S, HIDDEN, dtype=torch.float32)
|
| 124 |
+
dummy_mask = torch.ones(B, P + S, dtype=torch.long)
|
| 125 |
+
dummy_pos = torch.tensor([[P]], dtype=torch.long)
|
| 126 |
+
|
| 127 |
+
# Pro Layer eigene Dummy-Form — 256 vs. 512 Head-Dim!
|
| 128 |
+
dummy_past = []
|
| 129 |
+
for (n_kv, hd) in KV_SHAPES:
|
| 130 |
+
dummy_past.append(torch.zeros(B, n_kv, P, hd, dtype=torch.float32))
|
| 131 |
+
dummy_past.append(torch.zeros(B, n_kv, P, hd, dtype=torch.float32))
|
| 132 |
+
|
| 133 |
+
input_names = ["inputs_embeds", "attention_mask", "position_ids"]
|
| 134 |
+
output_names = ["logits"]
|
| 135 |
+
dynamic_axes = {
|
| 136 |
+
"inputs_embeds": {0: "batch", 1: "seq"},
|
| 137 |
+
"attention_mask": {0: "batch", 1: "total"},
|
| 138 |
+
"position_ids": {0: "batch", 1: "seq"},
|
| 139 |
+
"logits": {0: "batch", 1: "seq"},
|
| 140 |
+
}
|
| 141 |
+
for i in range(N_CACHE):
|
| 142 |
+
for kv in ("key", "value"):
|
| 143 |
+
pn = f"past_key_values.{i}.{kv}"
|
| 144 |
+
on = f"present.{i}.{kv}"
|
| 145 |
+
input_names.append(pn)
|
| 146 |
+
output_names.append(on)
|
| 147 |
+
dynamic_axes[pn] = {0: "batch", 2: "past_seq"}
|
| 148 |
+
dynamic_axes[on] = {0: "batch", 2: "total_seq"}
|
| 149 |
+
|
| 150 |
+
log("C) torch.onnx.export laeuft (dauert lange, kein Fortschrittsbalken)")
|
| 151 |
+
with torch.no_grad():
|
| 152 |
+
torch.onnx.export(
|
| 153 |
+
wrapper,
|
| 154 |
+
(dummy_embeds, dummy_mask, dummy_pos, *dummy_past),
|
| 155 |
+
str(FP32_ONNX),
|
| 156 |
+
input_names=input_names,
|
| 157 |
+
output_names=output_names,
|
| 158 |
+
dynamic_axes=dynamic_axes,
|
| 159 |
+
opset_version=17,
|
| 160 |
+
do_constant_folding=True,
|
| 161 |
+
dynamo=False, # MUSS letztes Keyword bleiben
|
| 162 |
+
)
|
| 163 |
+
print("Export geschrieben.")
|
| 164 |
+
|
| 165 |
+
del model, lm, lm_head, wrapper, dummy_past
|
| 166 |
+
gc.collect()
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
# --------------------------------------------------- D) Konsolidierung
|
| 170 |
+
log("D) Konsolidierung zu EINER .onnx_data (finaler Name direkt, nie umbenennen!)")
|
| 171 |
+
m = onnx.load(str(FP32_ONNX), load_external_data=True)
|
| 172 |
+
onnx.save_model(
|
| 173 |
+
m,
|
| 174 |
+
str(FP32_ONNX),
|
| 175 |
+
save_as_external_data=True,
|
| 176 |
+
all_tensors_to_one_file=True,
|
| 177 |
+
location=FP32_DATA,
|
| 178 |
+
size_threshold=1024,
|
| 179 |
+
)
|
| 180 |
+
del m
|
| 181 |
+
gc.collect()
|
| 182 |
+
|
| 183 |
+
# Fragment-Dateien aufraeumen (sonst laeuft die Disk voll)
|
| 184 |
+
for f in OUT.iterdir():
|
| 185 |
+
if f.name.startswith("onnx__") or f.name.startswith("_"):
|
| 186 |
+
f.unlink()
|
| 187 |
+
os.system(f"df -h /root; ls -la {OUT}")
|
| 188 |
+
|
| 189 |
+
onnx.checker.check_model(str(FP32_ONNX))
|
| 190 |
+
print("fp32-Graph valide.")
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
# ----------------------------------------------------- E) q4f16-Quantisierung
|
| 194 |
+
log("E) MatMul4BitsQuantizer -> q4f16 (der eine ungetestete Schritt)")
|
| 195 |
+
from onnxruntime.quantization.matmul_4bits_quantizer import (
|
| 196 |
+
MatMul4BitsQuantizer,
|
| 197 |
+
DefaultWeightOnlyQuantConfig,
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
model_fp32 = onnx.load(str(FP32_ONNX), load_external_data=True)
|
| 201 |
+
|
| 202 |
+
cfg = DefaultWeightOnlyQuantConfig(
|
| 203 |
+
block_size=32, # Transformers.js-kompatibel
|
| 204 |
+
is_symmetric=True,
|
| 205 |
+
accuracy_level=4, # int8-Compute
|
| 206 |
+
)
|
| 207 |
+
quant = MatMul4BitsQuantizer(model_fp32, algo_config=cfg)
|
| 208 |
+
quant.process()
|
| 209 |
+
|
| 210 |
+
onnx.save_model(
|
| 211 |
+
quant.model.model,
|
| 212 |
+
str(Q4_ONNX),
|
| 213 |
+
save_as_external_data=True,
|
| 214 |
+
all_tensors_to_one_file=True,
|
| 215 |
+
location=Q4_DATA,
|
| 216 |
+
size_threshold=1024,
|
| 217 |
+
)
|
| 218 |
+
print("q4f16 geschrieben.")
|
| 219 |
+
|
| 220 |
+
del model_fp32, quant
|
| 221 |
+
gc.collect()
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
# --------------------------------------------------------- F) Verifikation
|
| 225 |
+
log("F) Verifikation")
|
| 226 |
+
onnx.checker.check_model(str(Q4_ONNX))
|
| 227 |
+
|
| 228 |
+
size_mb = (OUT / Q4_DATA).stat().st_size / 1e6
|
| 229 |
+
print(f"{Q4_DATA}: {size_mb:.0f} MB")
|
| 230 |
+
if size_mb > 3500:
|
| 231 |
+
print("!! WARNUNG: >3.5 GB — Browser-ArrayBuffer-Limit gefaehrdet.")
|
| 232 |
+
else:
|
| 233 |
+
print("OK: Groesse im browsertauglichen Bereich.")
|
| 234 |
+
|
| 235 |
+
import onnxruntime as ort
|
| 236 |
+
|
| 237 |
+
sess = ort.InferenceSession(str(Q4_ONNX), providers=["CPUExecutionProvider"])
|
| 238 |
+
print("Session laedt. Inputs:", len(sess.get_inputs()), "Outputs:", len(sess.get_outputs()))
|
| 239 |
+
|
| 240 |
+
log("FERTIG. Naechster Schritt: Tokenizer + config.json daneben legen,")
|
| 241 |
+
print("config.json braucht den transformers.js_config-Block mit")
|
| 242 |
+
print(' "use_external_data_format": true')
|
| 243 |
+
print("sonst wird die .onnx_data im Browser nie angefragt.")
|