| |
| """ |
| 03_export_quant_c.py — WEG C (Decoder-only, ohne Embedding-Gewichte) |
| |
| Der Decoder bekommt inputs_embeds UND per_layer_inputs (4D) von aussen. |
| Damit landen die 14 GB Gather-Gewichte (embed_tokens + embed_tokens_per_layer) |
| NICHT im Graphen -> fp32 ~10 GB -> q4f16 ~2 GB. |
| |
| Das Embed-Modell wird NICHT exportiert: das Stock-embed_tokens_q4f16.onnx von |
| onnx-community/gemma-4-E4B-it-ONNX ist bitidentisch (LoRA hat nur |
| q/k/v/o/gate/up/down_proj beruehrt) und wird einfach danebengelegt. |
| |
| Start IMMER mit nohup: |
| nohup python 03_export_quant_c.py > export_c.log 2>&1 & |
| """ |
|
|
| import gc |
| import os |
| from pathlib import Path |
|
|
| import torch |
| import onnx |
|
|
| os.environ.setdefault("HF_HOME", "/root/hf") |
|
|
| MODEL_ID = "/root/gemma4-bund-merged" |
| STOCK = "onnx-community/gemma-4-E4B-it-ONNX" |
| OUT = Path("/root/train/gemma4-bund-final") |
| ONNX_DIR = OUT / "onnx" |
| ONNX_DIR.mkdir(parents=True, exist_ok=True) |
|
|
| FP32 = ONNX_DIR / "decoder_model_merged.onnx" |
| FP32_DATA = "decoder_model_merged.onnx_data" |
| Q4 = ONNX_DIR / "decoder_model_merged_q4f16.onnx" |
| Q4_DATA = "decoder_model_merged_q4f16.onnx_data" |
| FP16 = ONNX_DIR / "decoder_model_merged_fp16.onnx" |
| FP16_DATA = "decoder_model_merged_fp16.onnx_data" |
|
|
|
|
| def log(m): |
| print(f"\n=== {m}", flush=True) |
|
|
|
|
| |
| log("A) Modell laden") |
| from transformers import AutoTokenizer, AutoModelForImageTextToText, DynamicCache |
|
|
| tok = AutoTokenizer.from_pretrained(MODEL_ID) |
| model = AutoModelForImageTextToText.from_pretrained( |
| MODEL_ID, dtype=torch.float32, device_map="cpu") |
| model.eval() |
|
|
| lm = model.model.language_model |
| lm_head = model.lm_head if hasattr(model, "lm_head") else model.get_output_embeddings() |
| HIDDEN = lm.config.hidden_size |
| print("hidden_size:", HIDDEN) |
|
|
|
|
| |
| log("B) Trockenlauf") |
| with torch.no_grad(): |
| ids = torch.tensor([[1, 2, 3, 4]]) |
| emb = lm.get_input_embeddings()(ids) |
| ple = lm.get_per_layer_inputs(ids, emb) |
| print("per_layer_inputs Shape:", tuple(ple.shape), "(erwartet: 1,4,42,256)") |
| probe = lm(inputs_embeds=emb, per_layer_inputs=ple, use_cache=True, return_dict=True) |
|
|
| PLE_SHAPE = tuple(ple.shape[2:]) |
| pkv = probe.past_key_values |
| N_CACHE = len(pkv.layers) |
| print("n_cache_layers:", N_CACHE, "(erwartet: 24)") |
|
|
| KV_SHAPES = [] |
| for i in range(N_CACHE): |
| k = pkv.layers[i].keys |
| KV_SHAPES.append((int(k.shape[1]), int(k.shape[3]))) |
| print("head_dims:", sorted({s[1] for s in KV_SHAPES}), "(erwartet: [256, 512])") |
|
|
| del probe, pkv, emb, ple, ids |
| gc.collect() |
|
|
|
|
| |
| class DecoderWrapper(torch.nn.Module): |
| def __init__(self, lm, lm_head, n_cache): |
| super().__init__() |
| self.lm, self.lm_head, self.n_cache = lm, lm_head, n_cache |
|
|
| def forward(self, inputs_embeds, per_layer_inputs, |
| attention_mask, position_ids, *past): |
| cache = None |
| if len(past) == 2 * self.n_cache and past[0].shape[2] > 0: |
| cache = DynamicCache(config=self.lm.config) |
| for i in range(self.n_cache): |
| cache.update(past[2 * i], past[2 * i + 1], i) |
|
|
| out = self.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 = self.lm_head(out.last_hidden_state) |
| present = [] |
| for i in range(self.n_cache): |
| present.append(out.past_key_values.layers[i].keys) |
| present.append(out.past_key_values.layers[i].values) |
| return (logits, *present) |
|
|
|
|
| wrapper = DecoderWrapper(lm, lm_head, N_CACHE).eval() |
|
|
| log("C) Dummy-Inputs") |
| B, S, P = 1, 1, 1 |
| |
| 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(B, P + S, dtype=torch.long) |
| d_pos = torch.tensor([[P]], dtype=torch.long) |
| d_past = [] |
| for (n_kv, hd) in KV_SHAPES: |
| d_past += [torch.zeros(B, n_kv, P, hd), torch.zeros(B, n_kv, P, 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 kv in ("key", "value"): |
| pn, on = f"past_key_values.{i}.{kv}", f"present.{i}.{kv}" |
| input_names.append(pn) |
| output_names.append(on) |
| dyn[pn] = {0: "batch", 2: "past_seq"} |
| dyn[on] = {0: "batch", 2: "total_seq"} |
|
|
| log("C) torch.onnx.export — LANGE STILLE IST NORMAL (30-60 Min)") |
| with torch.no_grad(): |
| torch.onnx.export( |
| wrapper, (d_emb, d_ple, d_mask, d_pos, *d_past), str(FP32), |
| input_names=input_names, output_names=output_names, dynamic_axes=dyn, |
| opset_version=17, do_constant_folding=True, dynamo=False, |
| ) |
| print("Export geschrieben.") |
|
|
| del model, lm, lm_head, wrapper, d_past, d_emb, d_ple |
| gc.collect() |
|
|
|
|
| |
| log("D) Konsolidierung") |
| os.system(f"du -sh {ONNX_DIR}; df -h /root") |
| m = onnx.load(str(FP32), load_external_data=True) |
| onnx.save_model(m, str(FP32), save_as_external_data=True, |
| all_tensors_to_one_file=True, location=FP32_DATA, |
| size_threshold=1024) |
| del m |
| gc.collect() |
|
|
| for f in ONNX_DIR.iterdir(): |
| if f.name.startswith("onnx__") or f.name.startswith("lm.") or f.name.startswith("_"): |
| f.unlink() |
| os.system(f"df -h /root; ls -la {ONNX_DIR}") |
| try: |
| onnx.checker.check_model(str(FP32)) |
| print("fp32 valide.") |
| except Exception as e: |
| print("checker uebersprungen (>2GB-Falle):", type(e).__name__) |
|
|
|
|
| |
| |
| log("D.5) fp32 -> fp16") |
| from onnxconverter_common import float16 |
| m32 = onnx.load(str(FP32), load_external_data=True) |
| m16 = float16.convert_float_to_float16( |
| m32, keep_io_types=False, disable_shape_infer=True) |
| onnx.save_model(m16, str(FP16), save_as_external_data=True, |
| all_tensors_to_one_file=True, location=FP16_DATA, |
| size_threshold=1024) |
| del m32, m16 |
| gc.collect() |
| FP32.unlink(missing_ok=True) |
| (ONNX_DIR / FP32_DATA).unlink(missing_ok=True) |
| print("fp16 geschrieben.") |
|
|
|
|
| log("E) q4f16") |
| try: |
| from onnxruntime.quantization.matmul_nbits_quantizer import ( |
| MatMulNBitsQuantizer as Q, DefaultWeightOnlyQuantConfig) |
| except ImportError: |
| from onnxruntime.quantization.matmul_4bits_quantizer import ( |
| MatMul4BitsQuantizer as Q, DefaultWeightOnlyQuantConfig) |
|
|
| mf = onnx.load(str(FP16), load_external_data=True) |
| quant = Q(mf, algo_config=DefaultWeightOnlyQuantConfig( |
| block_size=32, is_symmetric=True, accuracy_level=4)) |
| quant.process() |
| qm = quant.model.model if hasattr(quant.model, "model") else quant.model |
| onnx.save_model(qm, str(Q4), save_as_external_data=True, |
| all_tensors_to_one_file=True, location=Q4_DATA, size_threshold=1024) |
| del mf, quant, qm |
| gc.collect() |
|
|
| |
| FP16.unlink(missing_ok=True) |
| (ONNX_DIR / FP16_DATA).unlink(missing_ok=True) |
|
|
|
|
| |
| log("F) Stock-Embed holen + Tokenizer/Config schreiben") |
| from huggingface_hub import hf_hub_download |
| import shutil, json |
|
|
| for fn in ("onnx/embed_tokens_q4f16.onnx", "onnx/embed_tokens_q4f16.onnx_data"): |
| try: |
| p = hf_hub_download(STOCK, fn) |
| shutil.copy(p, ONNX_DIR / Path(fn).name) |
| print("geholt:", fn) |
| except Exception as e: |
| print("nicht vorhanden (evtl. ok):", fn, e) |
|
|
| tok.save_pretrained(str(OUT)) |
| from transformers import AutoConfig |
| c = AutoConfig.from_pretrained(MODEL_ID) |
| c.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": True, |
| "embed_tokens_q4f16.onnx": True, |
| }, |
| "kv_cache_dtype": "float16", |
| } |
| json.dump(cfg, open(cp, "w"), indent=2) |
| print("transformers.js_config geschrieben.") |
|
|
|
|
| |
| log("G) Verifikation") |
| try: |
| onnx.checker.check_model(str(Q4)) |
| except Exception as e: |
| print("checker uebersprungen:", type(e).__name__) |
| size = (ONNX_DIR / Q4_DATA).stat().st_size / 1e6 |
| print(f"decoder q4f16 data: {size:.0f} MB") |
| print("!! >3500 MB = Browser-Limit" if size > 3500 else "OK: browsertauglich") |
|
|
| import onnxruntime as ort |
| s = ort.InferenceSession(str(Q4), providers=["CPUExecutionProvider"]) |
| print("Inputs:", [i.name for i in s.get_inputs()][:4], "... total", len(s.get_inputs())) |
| os.system(f"du -sh {OUT}; ls -la {ONNX_DIR}") |
|
|
| log("FERTIG. JETZT SOFORT auf HF pushen — /root ist fluechtig!") |
| print(f" hf upload gfp78/gemma4-bund-onnx {OUT} . --repo-type model") |
|
|