ceyxprime commited on
Commit
3f1985b
Β·
verified Β·
1 Parent(s): eb9afd8

Upload det02_make_det_dynamic.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. det02_make_det_dynamic.py +87 -0
det02_make_det_dynamic.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ det02 β€” ONNX graph surgery to patch det_500m.onnx for dynamic batch.
4
+
5
+ Patches 3 things in the graph metadata:
6
+ 1. Input dim[0]: 1 β†’ symbolic 'batch'
7
+ 2. Reshape shape constants starting with 1: that 1 β†’ 0 (copy batch dim from input)
8
+ 3. Output dim[0]: 1 β†’ symbolic 'batch'
9
+
10
+ Saves the result, then prints declared output shapes and actual runtime shapes for N=1 and N=2.
11
+ """
12
+ import argparse
13
+ import numpy as np
14
+ import onnx
15
+ from onnx import numpy_helper
16
+ import onnxruntime as ort
17
+
18
+ parser = argparse.ArgumentParser()
19
+ parser.add_argument('--model', required=True, help='Path to det_500m.onnx')
20
+ parser.add_argument('--out', required=True, help='Output path for patched model')
21
+ args = parser.parse_args()
22
+
23
+ model = onnx.load(args.model)
24
+
25
+ # ── 1. Patch input batch dim ──────────────────────────────────────────────────
26
+ for inp in model.graph.input:
27
+ d0 = inp.type.tensor_type.shape.dim[0]
28
+ d0.ClearField('dim_value')
29
+ d0.dim_param = 'batch'
30
+ print(f" Input '{inp.name}': batch dim β†’ dynamic")
31
+
32
+ # ── 2. Patch Reshape shape initializers that start with 1 ────────────────────
33
+ reshape_shape_names = set()
34
+ for node in model.graph.node:
35
+ if node.op_type == 'Reshape':
36
+ reshape_shape_names.add(node.input[1])
37
+
38
+ patched = 0
39
+ for init in list(model.graph.initializer):
40
+ if init.name not in reshape_shape_names:
41
+ continue
42
+ arr = numpy_helper.to_array(init).copy()
43
+ if arr.ndim == 1 and arr[0] == 1:
44
+ print(f" Reshape initializer '{init.name}': {arr} β†’ ", end='')
45
+ arr[0] = 0
46
+ print(arr)
47
+ new_t = numpy_helper.from_array(arr, init.name)
48
+ model.graph.initializer.remove(init)
49
+ model.graph.initializer.append(new_t)
50
+ patched += 1
51
+
52
+ print(f' Patched {patched} Reshape shape constant(s)')
53
+
54
+ # ── 3. Patch output batch dims ────────────────────────────────────────────────
55
+ for out in model.graph.output:
56
+ d0 = out.type.tensor_type.shape.dim[0]
57
+ d0.ClearField('dim_value')
58
+ d0.dim_param = 'batch'
59
+ print(f" Output '{out.name}': batch dim β†’ dynamic")
60
+
61
+ # ── Save ──────────────────────────────────────────────────────────────────────
62
+ onnx.checker.check_model(model)
63
+ onnx.save(model, args.out)
64
+ print(f'\nSaved: {args.out}')
65
+
66
+ # ── Declared output shapes (from patched graph) ───────────────────────────────
67
+ print('\nDeclared output shapes after surgery:')
68
+ for out in model.graph.output:
69
+ shape = [d.dim_param if d.HasField('dim_param') else d.dim_value
70
+ for d in out.type.tensor_type.shape.dim]
71
+ print(f' {out.name}: {shape}')
72
+
73
+ # ── Actual output shapes (from runtime with N=1 and N=2) ─────────────────────
74
+ print('\nActual output shapes at runtime:')
75
+ session = ort.InferenceSession(args.out, providers=['CPUExecutionProvider'])
76
+ inp0 = session.get_inputs()[0]
77
+ out_names = [o.name for o in session.get_outputs()]
78
+
79
+ for N in (1, 2):
80
+ dummy = np.random.randint(0, 255, (N, 3, 640, 640)).astype(np.float32)
81
+ try:
82
+ outs = session.run(out_names, {inp0.name: dummy})
83
+ print(f' N={N}:')
84
+ for name, o in zip(out_names, outs):
85
+ print(f' {name}: {list(o.shape)}')
86
+ except Exception as e:
87
+ print(f' N={N}: FAILED β€” {e}')