gfp78 commited on
Commit
910b0d4
·
verified ·
1 Parent(s): 59be759

Upload 07_export_v3.py

Browse files
Files changed (1) hide show
  1. 07_export_v3.py +166 -0
07_export_v3.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """
3
+ 07_export_v3.py — WEG C, ROBUSTE fp16-Konvertierung gegen WebGPU-Ueberlauf.
4
+
5
+ D.5-Strategie (statt op_block_list, das an Lib-Bugs/Grenzen scheitert):
6
+ 1. convert_float_to_float16(op_block_list=[]) -> alles fp16 (wie v1, laedt-faehig-Basis)
7
+ 2. fix_edges() -> Cast to=FLOAT -> FLOAT16 (macht es ladefaehig, wie v1)
8
+ 3. wrap_rmsnorm_fp32() -> jede ReduceMean-Reduktion in fp32 (verhindert
9
+ fp16-Ueberlauf der Summe-der-Quadrate auf echten WebGPU-Kerneln)
10
+ Alle drei Schritte in der Sandbox verifiziert (laedt + ReduceMean fp32).
11
+
12
+ Start: nohup python 07_export_v3.py > export_v3.log 2>&1 &
13
+ """
14
+ import gc, os
15
+ from pathlib import Path
16
+ import torch, onnx
17
+ from onnx import TensorProto, helper
18
+
19
+ os.environ.setdefault("HF_HOME", "/root/hf-cache")
20
+ MODEL_ID = "/root/gemma4-bund-merged"
21
+ STOCK = "onnx-community/gemma-4-E4B-it-ONNX"
22
+ OUT = Path("/root/train/gemma4-bund-final-v3"); ONNX_DIR = OUT/"onnx"; ONNX_DIR.mkdir(parents=True, exist_ok=True)
23
+ FP32=ONNX_DIR/"decoder_model_merged.onnx"; FP32_DATA="decoder_model_merged.onnx_data"
24
+ FP16=ONNX_DIR/"decoder_model_merged_fp16.onnx"; FP16_DATA="decoder_model_merged_fp16.onnx_data"
25
+ Q4=ONNX_DIR/"decoder_model_merged_q4f16.onnx"; Q4_DATA="decoder_model_merged_q4f16.onnx_data"
26
+
27
+ def log(m): print(f"\n=== {m}", flush=True)
28
+
29
+ def fix_edges(m):
30
+ n=0
31
+ for nd in m.graph.node:
32
+ if nd.op_type=="Cast":
33
+ for a in nd.attribute:
34
+ if a.name=="to" and a.i==TensorProto.FLOAT: a.i=TensorProto.FLOAT16; n+=1
35
+ return n
36
+
37
+ def wrap_rmsnorm_fp32(m):
38
+ g=m.graph; new=[]; nw=0
39
+ for node in list(g.node):
40
+ if node.op_type=="ReduceMean":
41
+ rin=node.input[0]; pre=rin+"_to32"
42
+ new.append(helper.make_node("Cast",[rin],[pre],to=TensorProto.FLOAT,name=node.name+"/CastIn32"))
43
+ node.input[0]=pre
44
+ outp=node.output[0]; post=outp+"_f32"; node.output[0]=post
45
+ new.append(node)
46
+ new.append(helper.make_node("Cast",[post],[outp],to=TensorProto.FLOAT16,name=node.name+"/CastOut16"))
47
+ nw+=1
48
+ else:
49
+ new.append(node)
50
+ del g.node[:]; g.node.extend(new); return nw
51
+
52
+ # A) laden
53
+ log("A) Modell laden (fp32)")
54
+ from transformers import AutoTokenizer, AutoModelForImageTextToText, DynamicCache
55
+ tok=AutoTokenizer.from_pretrained(MODEL_ID)
56
+ model=AutoModelForImageTextToText.from_pretrained(MODEL_ID,dtype=torch.float32,device_map="cpu").eval()
57
+ lm=model.model.language_model
58
+ lm_head=model.lm_head if hasattr(model,"lm_head") else model.get_output_embeddings()
59
+ print("hidden_size:",lm.config.hidden_size)
60
+
61
+ # B) Geometrie
62
+ log("B) Trockenlauf")
63
+ with torch.no_grad():
64
+ ids=torch.tensor([[1,2,3,4]]); emb=lm.get_input_embeddings()(ids); ple=lm.get_per_layer_inputs(ids,emb)
65
+ print("per_layer_inputs Shape:",tuple(ple.shape))
66
+ probe=lm(inputs_embeds=emb,per_layer_inputs=ple,use_cache=True,return_dict=True)
67
+ pkv=probe.past_key_values; N_CACHE=len(pkv.layers); print("n_cache_layers:",N_CACHE)
68
+ KV_SHAPES=[(int(pkv.layers[i].keys.shape[1]),int(pkv.layers[i].keys.shape[3])) for i in range(N_CACHE)]
69
+ print("head_dims:",sorted({s[1] for s in KV_SHAPES}))
70
+ del probe,pkv,emb,ple,ids; gc.collect()
71
+
72
+ # C) Wrapper + Export
73
+ class DecoderWrapper(torch.nn.Module):
74
+ def __init__(s,lm,lm_head,n): super().__init__(); s.lm,s.lm_head,s.n=lm,lm_head,n
75
+ def forward(s,inputs_embeds,per_layer_inputs,attention_mask,position_ids,*past):
76
+ cache=None
77
+ if len(past)==2*s.n and past[0].shape[2]>0:
78
+ cache=DynamicCache(config=s.lm.config)
79
+ for i in range(s.n): cache.update(past[2*i],past[2*i+1],i)
80
+ out=s.lm(inputs_embeds=inputs_embeds,per_layer_inputs=per_layer_inputs,attention_mask=attention_mask,
81
+ position_ids=position_ids,past_key_values=cache,use_cache=True,return_dict=True)
82
+ logits=s.lm_head(out.last_hidden_state); present=[]
83
+ for i in range(s.n): present+= [out.past_key_values.layers[i].keys,out.past_key_values.layers[i].values]
84
+ return (logits,*present)
85
+ wrapper=DecoderWrapper(lm,lm_head,N_CACHE).eval()
86
+ log("C) Dummy + Export (LANGE STILLE NORMAL)")
87
+ with torch.no_grad():
88
+ d_ids=torch.tensor([[42]],dtype=torch.long); d_emb=lm.get_input_embeddings()(d_ids).detach()
89
+ d_ple=lm.get_per_layer_inputs(d_ids,d_emb).detach()
90
+ d_mask=torch.ones(1,2,dtype=torch.long); d_pos=torch.tensor([[1]],dtype=torch.long); d_past=[]
91
+ for (n_kv,hd) in KV_SHAPES: d_past+=[torch.zeros(1,n_kv,1,hd),torch.zeros(1,n_kv,1,hd)]
92
+ input_names=["inputs_embeds","per_layer_inputs","attention_mask","position_ids"]; output_names=["logits"]
93
+ 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"}}
94
+ for i in range(N_CACHE):
95
+ for kv in ("key","value"):
96
+ pn,on=f"past_key_values.{i}.{kv}",f"present.{i}.{kv}"; input_names.append(pn); output_names.append(on)
97
+ dyn[pn]={0:"batch",2:"past_seq"}; dyn[on]={0:"batch",2:"total_seq"}
98
+ with torch.no_grad():
99
+ torch.onnx.export(wrapper,(d_emb,d_ple,d_mask,d_pos,*d_past),str(FP32),input_names=input_names,
100
+ output_names=output_names,dynamic_axes=dyn,opset_version=17,do_constant_folding=True,dynamo=False)
101
+ print("Export geschrieben.")
102
+ del model,lm,lm_head,wrapper,d_past,d_emb,d_ple; gc.collect()
103
+
104
+ # D) Konsolidierung
105
+ log("D) Konsolidierung")
106
+ m=onnx.load(str(FP32),load_external_data=True)
107
+ onnx.save_model(m,str(FP32),save_as_external_data=True,all_tensors_to_one_file=True,location=FP32_DATA,size_threshold=1024)
108
+ del m; gc.collect()
109
+ for f in ONNX_DIR.iterdir():
110
+ if f.name.startswith("onnx__") or f.name.startswith("lm.") or f.name.startswith("_"): f.unlink()
111
+
112
+ # D.5) fp16 + fix_edges + ReduceMean-fp32-Wrap
113
+ log("D.5) convert(op_block_list=[]) -> fix_edges -> wrap_rmsnorm_fp32")
114
+ from onnxconverter_common import float16
115
+ m32=onnx.load(str(FP32),load_external_data=True)
116
+ m16=float16.convert_float_to_float16(m32,keep_io_types=False,disable_shape_infer=True,op_block_list=[])
117
+ ne=fix_edges(m16); nw=wrap_rmsnorm_fp32(m16)
118
+ print(f"fix_edges Casts: {ne} | ReduceMean gewrappt (fp32): {nw}")
119
+ onnx.save_model(m16,str(FP16),save_as_external_data=True,all_tensors_to_one_file=True,location=FP16_DATA,size_threshold=1024)
120
+ del m32,m16; gc.collect()
121
+ FP32.unlink(missing_ok=True); (ONNX_DIR/FP32_DATA).unlink(missing_ok=True)
122
+ import onnxruntime as ort
123
+ try:
124
+ so=ort.SessionOptions(); so.intra_op_num_threads=4
125
+ ort.InferenceSession(str(FP16),sess_options=so,providers=["CPUExecutionProvider"]); print("fp16 LAEDT in ORT.")
126
+ except Exception as e: print("!! fp16 LAEDT NICHT:",str(e).split(chr(10))[0][:120])
127
+
128
+ # E) q4f16
129
+ log("E) q4f16")
130
+ from onnxruntime.quantization.matmul_nbits_quantizer import MatMulNBitsQuantizer as Q, DefaultWeightOnlyQuantConfig
131
+ mf=onnx.load(str(FP16),load_external_data=True)
132
+ quant=Q(mf,algo_config=DefaultWeightOnlyQuantConfig(block_size=32,is_symmetric=True,accuracy_level=4)); quant.process()
133
+ qm=quant.model.model if hasattr(quant.model,"model") else quant.model
134
+ onnx.save_model(qm,str(Q4),save_as_external_data=True,all_tensors_to_one_file=True,location=Q4_DATA,size_threshold=1024)
135
+ del mf,quant,qm; gc.collect()
136
+ FP16.unlink(missing_ok=True); (ONNX_DIR/FP16_DATA).unlink(missing_ok=True)
137
+ try:
138
+ so=ort.SessionOptions(); so.intra_op_num_threads=4
139
+ s=ort.InferenceSession(str(Q4),sess_options=so,providers=["CPUExecutionProvider"]); print("q4f16 LAEDT, Inputs total",len(s.get_inputs()))
140
+ except Exception as e: print("!! q4f16 LAEDT NICHT:",str(e).split(chr(10))[0][:120])
141
+
142
+ # F) Embed-Cast + config + template
143
+ log("F) Stock-Embed + fp16-Cast + config/tokenizer")
144
+ from huggingface_hub import hf_hub_download
145
+ import shutil, json
146
+ for fn in ("onnx/embed_tokens_q4f16.onnx","onnx/embed_tokens_q4f16.onnx_data"):
147
+ p=hf_hub_download(STOCK,fn,local_dir="/root/stock-embed"); shutil.copy(p,ONNX_DIR/Path(fn).name); print("geholt:",fn)
148
+ ep=ONNX_DIR/"embed_tokens_q4f16.onnx"; em=onnx.load(str(ep),load_external_data=False)
149
+ tg=[o.name for o in em.graph.output if o.type.tensor_type.elem_type==TensorProto.FLOAT]
150
+ pr={o:(nd,i) for nd in em.graph.node for i,o in enumerate(nd.output) if o in tg}
151
+ for name in tg:
152
+ nd,idx=pr[name]; pre=name+"_fp32"; nd.output[idx]=pre
153
+ em.graph.node.append(helper.make_node("Cast",[pre],[name],to=TensorProto.FLOAT16,name=name+"/CastToFp16"))
154
+ for o in em.graph.output:
155
+ if o.name==name: o.type.tensor_type.elem_type=TensorProto.FLOAT16
156
+ onnx.save(em,str(ep)); print("Embed-Outputs fp16:",tg)
157
+ tok.save_pretrained(str(OUT))
158
+ from transformers import AutoConfig
159
+ AutoConfig.from_pretrained(MODEL_ID).save_pretrained(str(OUT))
160
+ cp=OUT/"config.json"; cfg=json.load(open(cp))
161
+ cfg["transformers.js_config"]={"dtype":"q4f16","use_external_data_format":{"decoder_model_merged_q4f16.onnx":2,"embed_tokens_q4f16.onnx":True},"kv_cache_dtype":"float16"}
162
+ json.dump(cfg,open(cp,"w"),indent=2)
163
+ tcp=OUT/"tokenizer_config.json"; jinja=OUT/"chat_template.jinja"
164
+ if jinja.exists():
165
+ tc=json.load(open(tcp)); tc["chat_template"]=jinja.read_text(encoding="utf-8"); json.dump(tc,open(tcp,"w"),ensure_ascii=False,indent=2); print("chat_template eingebettet.")
166
+ log("FERTIG bis F. Naechste Schritte: Reshard -> Upload -> Bundesrechner. JETZT sichern, /root ist fluechtig!")