Download convert/fold_casts.py from WeReCooking/AvatarForcing-ONNX-WebGPU: direct link, hf CLI and curl.
- Browser
- Download file 1.71 kB
-
https://huggingface.co/WeReCooking/AvatarForcing-ONNX-WebGPU/resolve/main/convert/fold_casts.py
- Command line
-
hf download hf://WeReCooking/AvatarForcing-ONNX-WebGPU/convert/fold_casts.py
-
curl -L -o fold_casts.py https://huggingface.co/WeReCooking/AvatarForcing-ONNX-WebGPU/resolve/main/convert/fold_casts.py
1.71 kB
| import sys, onnx, numpy as np | |
| from onnx import numpy_helper, TensorProto, helper | |
| def fold(path): | |
| m = onnx.load(path); g = m.graph | |
| inits = {i.name: i for i in g.initializer} | |
| types = {} | |
| for i in g.initializer: types[i.name] = i.data_type | |
| for v in list(g.input) + list(g.value_info): types[v.name] = v.type.tensor_type.elem_type | |
| removed = 0; keep = []; rename = {} | |
| for n in g.node: | |
| for k, x in enumerate(n.input): | |
| if x in rename: n.input[k] = rename[x] | |
| if n.op_type == "Cast": | |
| to = [a.i for a in n.attribute if a.name == "to"][0]; src = n.input[0] | |
| if src in inits: # Cast of a constant: fold into a new constant | |
| arr = numpy_helper.to_array(inits[src]); dt = helper.tensor_dtype_to_np_dtype(to) | |
| t = numpy_helper.from_array(arr.astype(dt), n.output[0]); g.initializer.append(t); inits[n.output[0]] = t; types[n.output[0]] = to; removed += 1; continue | |
| if types.get(src) == to: # same-type Cast: bypass | |
| rename[n.output[0]] = src; removed += 1; continue | |
| keep.append(n) | |
| del g.node[:]; g.node.extend(keep) | |
| for o in g.output: | |
| if o.name in rename: raise SystemExit("graph output renamed; unsupported") | |
| used = {x for n in g.node for x in n.input}; used |= {o.name for o in g.output} | |
| keep_i = [i for i in g.initializer if i.name in used]; pruned = len(g.initializer) - len(keep_i); del g.initializer[:]; g.initializer.extend(keep_i) | |
| onnx.save(m, path); return f'{removed} (pruned {pruned} unused constants)' | |
| for p in sys.argv[1:]: print(p, "folded/removed", fold(p)) | |