gfp78 commited on
Commit
cdda461
·
verified ·
1 Parent(s): 01bbfd0

Upload 03_export_quant_c.py

Browse files
Files changed (1) hide show
  1. 03_export_quant_c.py +245 -0
03_export_quant_c.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """
3
+ 03_export_quant_c.py — WEG C (Decoder-only, ohne Embedding-Gewichte)
4
+
5
+ Der Decoder bekommt inputs_embeds UND per_layer_inputs (4D) von aussen.
6
+ Damit landen die 14 GB Gather-Gewichte (embed_tokens + embed_tokens_per_layer)
7
+ NICHT im Graphen -> fp32 ~10 GB -> q4f16 ~2 GB.
8
+
9
+ Das Embed-Modell wird NICHT exportiert: das Stock-embed_tokens_q4f16.onnx von
10
+ onnx-community/gemma-4-E4B-it-ONNX ist bitidentisch (LoRA hat nur
11
+ q/k/v/o/gate/up/down_proj beruehrt) und wird einfach danebengelegt.
12
+
13
+ Start IMMER mit nohup:
14
+ nohup python 03_export_quant_c.py > export_c.log 2>&1 &
15
+ """
16
+
17
+ import gc
18
+ import os
19
+ from pathlib import Path
20
+
21
+ import torch
22
+ import onnx
23
+
24
+ os.environ.setdefault("HF_HOME", "/root/hf")
25
+
26
+ MODEL_ID = "gfp78/gemma4-bund-merged"
27
+ STOCK = "onnx-community/gemma-4-E4B-it-ONNX"
28
+ OUT = Path("/root/train/gemma4-bund-final")
29
+ ONNX_DIR = OUT / "onnx"
30
+ ONNX_DIR.mkdir(parents=True, exist_ok=True)
31
+
32
+ FP32 = ONNX_DIR / "decoder_model_merged.onnx"
33
+ FP32_DATA = "decoder_model_merged.onnx_data"
34
+ Q4 = ONNX_DIR / "decoder_model_merged_q4f16.onnx"
35
+ Q4_DATA = "decoder_model_merged_q4f16.onnx_data"
36
+
37
+
38
+ def log(m):
39
+ print(f"\n=== {m}", 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
+ model.eval()
50
+
51
+ lm = model.model.language_model
52
+ lm_head = model.lm_head if hasattr(model, "lm_head") else model.get_output_embeddings()
53
+ HIDDEN = lm.config.hidden_size
54
+ print("hidden_size:", HIDDEN)
55
+
56
+
57
+ # ------------------------------------------------- B) Cache-Geometrie messen
58
+ log("B) Trockenlauf")
59
+ with torch.no_grad():
60
+ ids = torch.tensor([[1, 2, 3, 4]])
61
+ emb = lm.get_input_embeddings()(ids)
62
+ ple = lm.get_per_layer_inputs(ids, emb)
63
+ print("per_layer_inputs Shape:", tuple(ple.shape), "(erwartet: 1,4,42,256)")
64
+ probe = lm(inputs_embeds=emb, per_layer_inputs=ple, use_cache=True, return_dict=True)
65
+
66
+ PLE_SHAPE = tuple(ple.shape[2:]) # (42, 256)
67
+ pkv = probe.past_key_values
68
+ N_CACHE = len(pkv.layers)
69
+ print("n_cache_layers:", N_CACHE, "(erwartet: 24)")
70
+
71
+ KV_SHAPES = []
72
+ for i in range(N_CACHE):
73
+ k = pkv.layers[i].keys
74
+ KV_SHAPES.append((int(k.shape[1]), int(k.shape[3])))
75
+ print("head_dims:", sorted({s[1] for s in KV_SHAPES}), "(erwartet: [256, 512])")
76
+
77
+ del probe, pkv, emb, ple, ids
78
+ gc.collect()
79
+
80
+
81
+ # ---------------------------------------------------------------- C) Wrapper
82
+ class DecoderWrapper(torch.nn.Module):
83
+ def __init__(self, lm, lm_head, n_cache):
84
+ super().__init__()
85
+ self.lm, self.lm_head, self.n_cache = lm, lm_head, n_cache
86
+
87
+ def forward(self, inputs_embeds, per_layer_inputs,
88
+ attention_mask, position_ids, *past):
89
+ cache = None
90
+ if len(past) == 2 * self.n_cache and past[0].shape[2] > 0:
91
+ cache = DynamicCache(config=self.lm.config)
92
+ for i in range(self.n_cache):
93
+ cache.update(past[2 * i], past[2 * i + 1], i)
94
+
95
+ out = self.lm(
96
+ inputs_embeds=inputs_embeds,
97
+ per_layer_inputs=per_layer_inputs,
98
+ attention_mask=attention_mask,
99
+ position_ids=position_ids,
100
+ past_key_values=cache,
101
+ use_cache=True,
102
+ return_dict=True,
103
+ )
104
+ logits = self.lm_head(out.last_hidden_state)
105
+ present = []
106
+ for i in range(self.n_cache):
107
+ present.append(out.past_key_values.layers[i].keys)
108
+ present.append(out.past_key_values.layers[i].values)
109
+ return (logits, *present)
110
+
111
+
112
+ wrapper = DecoderWrapper(lm, lm_head, N_CACHE).eval()
113
+
114
+ log("C) Dummy-Inputs")
115
+ B, S, P = 1, 1, 1
116
+ # ECHTE Embeddings (keine Nullen) — Gemma 4 prueft die Konsistenz
117
+ with torch.no_grad():
118
+ d_ids = torch.tensor([[42]], dtype=torch.long)
119
+ d_emb = lm.get_input_embeddings()(d_ids).detach()
120
+ d_ple = lm.get_per_layer_inputs(d_ids, d_emb).detach()
121
+
122
+ d_mask = torch.ones(B, P + S, dtype=torch.long)
123
+ d_pos = torch.tensor([[P]], dtype=torch.long)
124
+ d_past = []
125
+ for (n_kv, hd) in KV_SHAPES:
126
+ d_past += [torch.zeros(B, n_kv, P, hd), torch.zeros(B, n_kv, P, hd)]
127
+
128
+ input_names = ["inputs_embeds", "per_layer_inputs", "attention_mask", "position_ids"]
129
+ output_names = ["logits"]
130
+ dyn = {
131
+ "inputs_embeds": {0: "batch", 1: "seq"},
132
+ "per_layer_inputs": {0: "batch", 1: "seq"},
133
+ "attention_mask": {0: "batch", 1: "total"},
134
+ "position_ids": {0: "batch", 1: "seq"},
135
+ "logits": {0: "batch", 1: "seq"},
136
+ }
137
+ for i in range(N_CACHE):
138
+ for kv in ("key", "value"):
139
+ pn, on = f"past_key_values.{i}.{kv}", f"present.{i}.{kv}"
140
+ input_names.append(pn)
141
+ output_names.append(on)
142
+ dyn[pn] = {0: "batch", 2: "past_seq"}
143
+ dyn[on] = {0: "batch", 2: "total_seq"}
144
+
145
+ log("C) torch.onnx.export — LANGE STILLE IST NORMAL (30-60 Min)")
146
+ with torch.no_grad():
147
+ torch.onnx.export(
148
+ wrapper, (d_emb, d_ple, d_mask, d_pos, *d_past), str(FP32),
149
+ input_names=input_names, output_names=output_names, dynamic_axes=dyn,
150
+ opset_version=17, do_constant_folding=True, dynamo=False,
151
+ )
152
+ print("Export geschrieben.")
153
+
154
+ del model, lm, lm_head, wrapper, d_past, d_emb, d_ple
155
+ gc.collect()
156
+
157
+
158
+ # --------------------------------------------------------- D) Konsolidierung
159
+ log("D) Konsolidierung")
160
+ os.system(f"du -sh {ONNX_DIR}; df -h /root")
161
+ m = onnx.load(str(FP32), load_external_data=True)
162
+ onnx.save_model(m, str(FP32), save_as_external_data=True,
163
+ all_tensors_to_one_file=True, location=FP32_DATA,
164
+ size_threshold=1024)
165
+ del m
166
+ gc.collect()
167
+
168
+ for f in ONNX_DIR.iterdir():
169
+ if f.name.startswith("onnx__") or f.name.startswith("lm.") or f.name.startswith("_"):
170
+ f.unlink()
171
+ os.system(f"df -h /root; ls -la {ONNX_DIR}")
172
+ onnx.checker.check_model(str(FP32))
173
+ print("fp32 valide.")
174
+
175
+
176
+ # ------------------------------------------------------------------ E) q4f16
177
+ log("E) q4f16")
178
+ try:
179
+ from onnxruntime.quantization.matmul_nbits_quantizer import (
180
+ MatMulNBitsQuantizer as Q, DefaultWeightOnlyQuantConfig)
181
+ except ImportError:
182
+ from onnxruntime.quantization.matmul_4bits_quantizer import (
183
+ MatMul4BitsQuantizer as Q, DefaultWeightOnlyQuantConfig)
184
+
185
+ mf = onnx.load(str(FP32), load_external_data=True)
186
+ quant = Q(mf, algo_config=DefaultWeightOnlyQuantConfig(
187
+ block_size=32, is_symmetric=True, accuracy_level=4))
188
+ quant.process()
189
+ qm = quant.model.model if hasattr(quant.model, "model") else quant.model
190
+ onnx.save_model(qm, str(Q4), save_as_external_data=True,
191
+ all_tensors_to_one_file=True, location=Q4_DATA, size_threshold=1024)
192
+ del mf, quant, qm
193
+ gc.collect()
194
+
195
+ # fp32 wegwerfen — sonst laeuft die Disk beim Upload voll
196
+ FP32.unlink(missing_ok=True)
197
+ (ONNX_DIR / FP32_DATA).unlink(missing_ok=True)
198
+
199
+
200
+ # ---------------------------------------------------- F) Stock-Embed + Config
201
+ log("F) Stock-Embed holen + Tokenizer/Config schreiben")
202
+ from huggingface_hub import hf_hub_download
203
+ import shutil, json
204
+
205
+ for fn in ("onnx/embed_tokens_q4f16.onnx", "onnx/embed_tokens_q4f16.onnx_data"):
206
+ try:
207
+ p = hf_hub_download(STOCK, fn)
208
+ shutil.copy(p, ONNX_DIR / Path(fn).name)
209
+ print("geholt:", fn)
210
+ except Exception as e:
211
+ print("nicht vorhanden (evtl. ok):", fn, e)
212
+
213
+ tok.save_pretrained(str(OUT))
214
+ from transformers import AutoConfig
215
+ c = AutoConfig.from_pretrained(MODEL_ID)
216
+ c.save_pretrained(str(OUT))
217
+
218
+ cp = OUT / "config.json"
219
+ cfg = json.load(open(cp))
220
+ cfg["transformers.js_config"] = {
221
+ "dtype": "q4f16",
222
+ "use_external_data_format": {
223
+ "decoder_model_merged_q4f16.onnx": True,
224
+ "embed_tokens_q4f16.onnx": True,
225
+ },
226
+ "kv_cache_dtype": "float16",
227
+ }
228
+ json.dump(cfg, open(cp, "w"), indent=2)
229
+ print("transformers.js_config geschrieben.")
230
+
231
+
232
+ # ------------------------------------------------------------ G) Verifikation
233
+ log("G) Verifikation")
234
+ onnx.checker.check_model(str(Q4))
235
+ size = (ONNX_DIR / Q4_DATA).stat().st_size / 1e6
236
+ print(f"decoder q4f16 data: {size:.0f} MB")
237
+ print("!! >3500 MB = Browser-Limit" if size > 3500 else "OK: browsertauglich")
238
+
239
+ import onnxruntime as ort
240
+ s = ort.InferenceSession(str(Q4), providers=["CPUExecutionProvider"])
241
+ print("Inputs:", [i.name for i in s.get_inputs()][:4], "... total", len(s.get_inputs()))
242
+ os.system(f"du -sh {OUT}; ls -la {ONNX_DIR}")
243
+
244
+ log("FERTIG. JETZT SOFORT auf HF pushen — /root ist fluechtig!")
245
+ print(f" hf upload gfp78/gemma4-bund-onnx {OUT} . --repo-type model")