File size: 1,711 Bytes
c647930
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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))