-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathonnx_visualizer.py
More file actions
1763 lines (1548 loc) Β· 73.2 KB
/
Copy pathonnx_visualizer.py
File metadata and controls
1763 lines (1548 loc) Β· 73.2 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
onnx_visualnode.py - ONNX Debugger Single File Version
A single-file version that combines all module functionalities for capturing and visualizing
intermediate tensor values of all nodes during ONNX model inference.
Usage:
python onnx_visualnode.py resnet18.onnx
python onnx_visualnode.py resnet18.onnx --output debug_report.html
python onnx_visualnode.py resnet18.onnx input.npy
python onnx_visualnode.py resnet18.onnx input.npy --output debug_report.html
python onnx_visualnode.py resnet18.onnx input.npy --inspect Conv_0
"""
import sys
import os
import argparse
import json
import numpy as np
import onnx
import onnxruntime as ort
from datetime import datetime
# ============================================================================
# Module 1: graph_patcher - Graph Modification Tools
# ============================================================================
def patch_model_expose_all_intermediates(model: onnx.ModelProto) -> onnx.ModelProto:
"""
Register all intermediate tensors (value_info) as graph outputs.
This is the core technique for capturing all node activation values.
"""
# Shape inference fills potentially missing value_info entries
try:
model = onnx.shape_inference.infer_shapes(model)
except Exception:
pass
existing_outputs = {o.name for o in model.graph.output}
for value_info in model.graph.value_info:
if value_info.name not in existing_outputs:
model.graph.output.append(value_info)
return model
# ============================================================================
# Module 2: model_loader - Model Loader
# ============================================================================
def load_model(model_path: str) -> onnx.ModelProto:
"""Load ONNX model and attempt shape inference."""
model = onnx.load(model_path)
try:
model = onnx.shape_inference.infer_shapes(model)
except Exception as e:
print(f"[model_loader] shape inference warning: {e}")
return model
# ============================================================================
# Module 3: runner - Inference Runner
# ============================================================================
class OnnxRunner:
def __init__(self, model_path: str):
model = onnx.load(model_path)
patched_model = patch_model_expose_all_intermediates(model)
# Disable graph optimization to prevent node fusion
sess_options = ort.SessionOptions()
sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_DISABLE_ALL
# Load modified model directly from memory - no temporary file needed
self.session = ort.InferenceSession(
patched_model.SerializeToString(),
sess_options=sess_options,
)
self.model = model
def run_from_npy(self, npy_path: str) -> dict:
"""Load input.npy and return all tensors (input + each intermediate layer)."""
input_data = np.load(npy_path, allow_pickle=True)
# Support dict-in-npy (multi-input) or plain array (single input)
if input_data.dtype == object:
inputs = input_data.item() # {name: array}
else:
input_name = self.session.get_inputs()[0].name
inputs = {input_name: input_data}
output_names = [o.name for o in self.session.get_outputs()]
results = self.session.run(output_names, inputs)
# Merge original inputs so each node's input tensors are accessible
all_tensors = {**inputs, **dict(zip(output_names, results))}
return all_tensors
# ============================================================================
# Module 4: node_info - Node Information Extraction
# ============================================================================
def get_node_static_info(node: onnx.NodeProto, idx: int) -> dict:
"""Return {node_id, op_type, attrs, input_names, output_names}."""
node_id = node.name if node.name else f"{node.op_type}_{idx}"
attrs = {}
for attr in node.attribute:
if attr.type == onnx.AttributeProto.INT:
attrs[attr.name] = attr.i
elif attr.type == onnx.AttributeProto.FLOAT:
attrs[attr.name] = round(attr.f, 7)
elif attr.type == onnx.AttributeProto.STRING:
attrs[attr.name] = attr.s.decode("utf-8", errors="replace")
elif attr.type == onnx.AttributeProto.INTS:
attrs[attr.name] = list(attr.ints)
elif attr.type == onnx.AttributeProto.FLOATS:
attrs[attr.name] = [round(f, 7) for f in attr.floats]
elif attr.type == onnx.AttributeProto.GRAPH:
attrs[attr.name] = "<subgraph>"
return {
"node_id": node_id,
"op_type": node.op_type,
"attrs": attrs,
"input_names": [n for n in node.input],
"output_names": [n for n in node.output],
}
# ============================================================================
# Module 5: tensor_viewer - Tensor Statistics
# ============================================================================
def tensor_stats(arr: np.ndarray) -> dict:
"""Return min/max/mean/std/abs_mean for numeric tensor."""
if arr is None:
return {}
try:
flat = arr.astype(np.float64).ravel()
return {
"min": float(flat.min()),
"max": float(flat.max()),
"mean": float(flat.mean()),
"std": float(flat.std()),
"abs_mean": float(np.abs(flat).mean()),
}
except Exception:
return {}
def describe_tensor(name: str, arr: np.ndarray) -> dict:
"""
Return detailed description dictionary for a single tensor:
{shape, dtype, stats, has_nan, has_inf}
"""
if arr is None:
return {"name": name, "available": False}
info = {
"name": name,
"available": True,
"shape": list(arr.shape),
"dtype": str(arr.dtype),
"stats": tensor_stats(arr),
}
try:
info["has_nan"] = bool(np.isnan(arr).any())
info["has_inf"] = bool(np.isinf(arr).any())
except Exception:
info["has_nan"] = False
info["has_inf"] = False
return info
# ============================================================================
# Module 6: debugger - Main Debugger Interface
# ============================================================================
class OnnxDebugger:
def __init__(self, model_path: str):
self.model_path = model_path
self.model = onnx.load(model_path)
self.runner = OnnxRunner(model_path)
# ------------------------------------------------------------------
# Core Methods
# ------------------------------------------------------------------
def run(self, npy_path: str) -> dict:
"""
Run inference and return structured dictionary for each node,
containing actual tensor values (shape + statistics) for each input and output.
"""
all_tensors = self.runner.run_from_npy(npy_path) # {name: np.ndarray}
result = {}
for idx, node in enumerate(self.model.graph.node):
info = get_node_static_info(node, idx)
node_id = info["node_id"]
inputs_data = {}
for name in info["input_names"]:
if name: # Skip empty optional inputs
arr = all_tensors.get(name)
desc = describe_tensor(name, arr)
if desc.get("available"):
# Only keep serializable keys
inputs_data[name] = {
"shape": desc["shape"],
"dtype": desc["dtype"],
"stats": desc["stats"],
}
else:
inputs_data[name] = {"available": False}
outputs_data = {}
for name in info["output_names"]:
if name:
arr = all_tensors.get(name)
desc = describe_tensor(name, arr)
if desc.get("available"):
outputs_data[name] = {
"shape": desc["shape"],
"dtype": desc["dtype"],
"stats": desc["stats"],
}
else:
outputs_data[name] = {"available": False}
result[node_id] = {
"op_type": info["op_type"],
"attrs": info["attrs"],
"inputs": inputs_data,
"outputs": outputs_data,
}
return result
# ------------------------------------------------------------------
# Convenience Helper Methods
# ------------------------------------------------------------------
def inspect_node(self, node_id: str, npy_path: str):
"""Pretty print I/O tensors for a single node."""
all_results = self.run(npy_path)
if node_id not in all_results:
print(f"[ERR] Node '{node_id}' not found. Available: {list(all_results.keys())[:5]} ...")
return
nd = all_results[node_id]
print(f"\n=== Node: {node_id} ({nd['op_type']}) ===")
for name, t in nd["inputs"].items():
if t.get("available") is False:
print(f" INPUT [{name}]: <not captured>")
else:
s = t["stats"]
print(f" INPUT [{name}]: shape={t['shape']}, dtype={t['dtype']}, "
f"min={s['min']:.4f}, max={s['max']:.4f}, mean={s['mean']:.4f}")
for name, t in nd["outputs"].items():
if t.get("available") is False:
print(f" OUTPUT [{name}]: <not captured>")
else:
s = t["stats"]
print(f" OUTPUT [{name}]: shape={t['shape']}, dtype={t['dtype']}, "
f"min={s['min']:.4f}, max={s['max']:.4f}, mean={s['mean']:.4f}")
# ============================================================================
# Module 7: html_builder - HTML Report Generation
# ============================================================================
def _safe_json(obj):
"""Serialize to JSON, gracefully converting non-serializable types."""
return json.dumps(obj, ensure_ascii=False, default=str, separators=(",", ":"))
OP_CATEGORY = {
"Conv": "conv", "ConvTranspose": "conv",
"Gemm": "gemm", "MatMul": "gemm",
"Relu": "act", "Sigmoid": "act", "Tanh": "act", "LeakyRelu": "act",
"Elu": "act", "Selu": "act", "Softmax": "act", "Gelu": "act", "PRelu": "act",
"MaxPool": "pool", "AveragePool": "pool", "GlobalAveragePool": "pool",
"GlobalMaxPool": "pool",
"BatchNormalization": "norm", "LayerNormalization": "norm",
"InstanceNormalization": "norm",
"Add": "eltwise", "Sub": "eltwise", "Mul": "eltwise", "Div": "eltwise",
"Sum": "eltwise", "Max": "eltwise", "Min": "eltwise", "Pow": "eltwise",
"Reshape": "shape", "Flatten": "shape", "Squeeze": "shape",
"Unsqueeze": "shape", "Transpose": "shape", "Concat": "shape",
"Slice": "shape", "Gather": "shape", "Expand": "shape", "Pad": "shape",
"Resize": "upsample", "Upsample": "upsample",
"LSTM": "rnn", "GRU": "rnn", "RNN": "rnn",
"Dropout": "other", "Identity": "other", "Constant": "other",
"Shape": "other", "Cast": "other", "Clip": "other",
"ReduceMean": "reduce", "ReduceSum": "reduce", "ReduceMax": "reduce",
"ReduceMin": "reduce", "ReduceL2": "reduce",
"Attention": "attention", "MultiHeadAttention": "attention",
}
def _cat(op_type):
return OP_CATEGORY.get(op_type, "other")
def _build_graph_data(debug_result: dict, model: onnx.ModelProto = None):
"""
Build nodes_data and edges required for graph view from debug_result
Returns: (nodes_data, edges)
"""
nodes_data = []
edges = []
# Build mapping from tensor name to node id
tensor_to_node = {}
# Collect all input tensors (model inputs)
all_input_tensors = set()
all_output_tensors = set()
all_intermediate_tensors = set()
# Step 1: Collect all tensor information
for idx, (node_id, nd) in enumerate(debug_result.items()):
for inp_name in nd.get("inputs", {}).keys():
if inp_name:
all_input_tensors.add(inp_name)
for out_name in nd.get("outputs", {}).keys():
if out_name:
all_output_tensors.add(out_name)
all_intermediate_tensors.add(out_name)
# Get real inputs from ONNX model (exclude weight parameters in initializer)
model_inputs = set()
if model is not None:
# Get all initializer (weight parameter) names
initializer_names = {init.name for init in model.graph.initializer}
# Real model inputs = graph.input - initializer
for input_info in model.graph.input:
if input_info.name not in initializer_names:
model_inputs.add(input_info.name)
else:
# If no model object, use old logic as fallback
model_inputs = all_input_tensors - all_intermediate_tensors
# Model outputs = all output tensors not used by other nodes
model_outputs = set()
for out_name in all_output_tensors:
is_used = False
for node_id, nd in debug_result.items():
if out_name in nd.get("inputs", {}).keys():
is_used = True
break
if not is_used:
model_outputs.add(out_name)
# Step 2: Create input nodes
input_node_id = 0
input_tensor_to_node = {}
# Get input metadata from ONNX model
input_metadata = {}
if model is not None:
initializer_names = {init.name for init in model.graph.initializer}
for input_info in model.graph.input:
if input_info.name not in initializer_names:
# Extract shape and dtype information
shape = []
dtype_str = "unknown"
if input_info.type.tensor_type:
tt = input_info.type.tensor_type
# Get shape
for dim in tt.shape.dim:
if dim.dim_value:
shape.append(dim.dim_value)
elif dim.dim_param:
shape.append(dim.dim_param)
else:
shape.append(-1)
# Get dtype
if tt.elem_type:
from onnx import TensorProto
dtype_map = {
TensorProto.FLOAT: "float32",
TensorProto.DOUBLE: "float64",
TensorProto.INT32: "int32",
TensorProto.INT64: "int64",
TensorProto.UINT8: "uint8",
TensorProto.INT8: "int8",
TensorProto.UINT16: "uint16",
TensorProto.INT16: "int16",
TensorProto.BOOL: "bool",
}
dtype_str = dtype_map.get(tt.elem_type, f"type_{tt.elem_type}")
input_metadata[input_info.name] = {"shape": shape, "dtype": dtype_str}
for tensor_name in sorted(model_inputs):
# Prefer getting shape from ONNX model metadata
shape_str = "?"
attrs = {}
if tensor_name in input_metadata:
meta = input_metadata[tensor_name]
shape = meta.get("shape", [])
if shape:
shape_str = "[" + ", ".join(str(d) for d in shape) + "]"
attrs["dtype"] = meta.get("dtype", "unknown")
attrs["shape"] = shape_str
else:
# fallback: get from debug_result
for node_id, nd in debug_result.items():
if tensor_name in nd.get("inputs", {}):
tensor_info = nd["inputs"][tensor_name]
shape = tensor_info.get("shape", [])
if shape:
shape_str = "[" + ", ".join(str(d) for d in shape) + "]"
if tensor_info.get("dtype"):
attrs["dtype"] = tensor_info["dtype"]
attrs["shape"] = shape_str
break
nodes_data.append({
"id": input_node_id,
"name": tensor_name[:40],
"op": "Input",
"category": "input",
"inputs": [],
"outputs": [tensor_name],
"input_shapes": [],
"output_shapes": [{"name": tensor_name[:40], "shape": shape_str}],
"attrs": attrs,
})
input_tensor_to_node[tensor_name] = input_node_id
input_node_id += 1
# Step 3: Create all operator nodes
for idx, (node_id, nd) in enumerate(debug_result.items()):
nid = idx + input_node_id # Offset by number of input nodes
# Collect input and output shape information
input_shapes = []
for name, tensor_info in nd.get("inputs", {}).items():
# Even if tensor is unavailable, try to get shape information
shape = tensor_info.get("shape", [])
if shape:
shape_str = "[" + ", ".join(str(d) for d in shape) + "]"
else:
shape_str = "?"
input_shapes.append({"name": name[:40], "shape": shape_str})
output_shapes = []
for name, tensor_info in nd.get("outputs", {}).items():
# Even if tensor is unavailable, try to get shape information
shape = tensor_info.get("shape", [])
if shape:
shape_str = "[" + ", ".join(str(d) for d in shape) + "]"
else:
shape_str = "?"
output_shapes.append({"name": name[:40], "shape": shape_str})
nodes_data.append({
"id": nid,
"name": node_id,
"op": nd["op_type"],
"category": _cat(nd["op_type"]),
"inputs": list(nd.get("inputs", {}).keys()),
"outputs": list(nd.get("outputs", {}).keys()),
"input_shapes": input_shapes,
"output_shapes": output_shapes,
"attrs": nd.get("attrs", {}),
})
# Record output tensor to node mapping
for out_name in nd.get("outputs", {}).keys():
tensor_to_node[out_name] = nid
# Step 4: Create output nodes
output_node_start_id = len(nodes_data)
output_tensor_to_node = {}
# Get output metadata from ONNX model
output_metadata = {}
if model is not None:
for output_info in model.graph.output:
# Extract shape and dtype information
shape = []
dtype_str = "unknown"
if output_info.type.tensor_type:
tt = output_info.type.tensor_type
# Get shape
for dim in tt.shape.dim:
if dim.dim_value:
shape.append(dim.dim_value)
elif dim.dim_param:
shape.append(dim.dim_param)
else:
shape.append(-1)
# Get dtype
if tt.elem_type:
from onnx import TensorProto
dtype_map = {
TensorProto.FLOAT: "float32",
TensorProto.DOUBLE: "float64",
TensorProto.INT32: "int32",
TensorProto.INT64: "int64",
TensorProto.UINT8: "uint8",
TensorProto.INT8: "int8",
TensorProto.UINT16: "uint16",
TensorProto.INT16: "int16",
TensorProto.BOOL: "bool",
}
dtype_str = dtype_map.get(tt.elem_type, f"type_{tt.elem_type}")
output_metadata[output_info.name] = {"shape": shape, "dtype": dtype_str}
for tensor_name in sorted(model_outputs):
# Prefer getting shape from ONNX model metadata
shape_str = "?"
attrs = {}
if tensor_name in output_metadata:
meta = output_metadata[tensor_name]
shape = meta.get("shape", [])
if shape:
shape_str = "[" + ", ".join(str(d) for d in shape) + "]"
attrs["dtype"] = meta.get("dtype", "unknown")
attrs["shape"] = shape_str
else:
# fallback: get from debug_result
for node_id, nd in debug_result.items():
if tensor_name in nd.get("outputs", {}):
tensor_info = nd["outputs"][tensor_name]
shape = tensor_info.get("shape", [])
if shape:
shape_str = "[" + ", ".join(str(d) for d in shape) + "]"
if tensor_info.get("dtype"):
attrs["dtype"] = tensor_info["dtype"]
attrs["shape"] = shape_str
break
output_node_id = output_node_start_id + len(output_tensor_to_node)
nodes_data.append({
"id": output_node_id,
"name": tensor_name[:40],
"op": "Output",
"category": "output",
"inputs": [tensor_name],
"outputs": [],
"input_shapes": [{"name": tensor_name[:40], "shape": shape_str}],
"output_shapes": [],
"attrs": attrs,
})
output_tensor_to_node[tensor_name] = output_node_id
# Step 5: Build edges (based on tensor dependencies)
seen_edges = set()
# From input nodes to first operator node using them
for tensor_name, src_id in input_tensor_to_node.items():
for idx, (node_id, nd) in enumerate(debug_result.items()):
if tensor_name in nd.get("inputs", {}).keys():
dst_id = idx + input_node_id
edge_key = (src_id, dst_id, tensor_name)
if edge_key not in seen_edges:
seen_edges.add(edge_key)
edges.append({
"src": src_id,
"dst": dst_id,
"tensor": tensor_name[:40]
})
# Edges between operator nodes
for idx, (node_id, nd) in enumerate(debug_result.items()):
dst_id = idx + input_node_id
for inp_name in nd.get("inputs", {}).keys():
if inp_name in tensor_to_node:
src_id = tensor_to_node[inp_name]
edge_key = (src_id, dst_id, inp_name)
if edge_key not in seen_edges and src_id != dst_id:
seen_edges.add(edge_key)
edges.append({
"src": src_id,
"dst": dst_id,
"tensor": inp_name[:40]
})
# From operator nodes to output nodes
for tensor_name, dst_id in output_tensor_to_node.items():
if tensor_name in tensor_to_node:
src_id = tensor_to_node[tensor_name]
edge_key = (src_id, dst_id, tensor_name)
if edge_key not in seen_edges:
seen_edges.add(edge_key)
edges.append({
"src": src_id,
"dst": dst_id,
"tensor": tensor_name[:40]
})
return nodes_data, edges
def build_html(
debug_result: dict,
model_path: str,
npy_path: str = None,
output_path: str = None,
):
"""
debug_result β Dictionary returned by OnnxDebugger.run()
model_path β .onnx path (for display)
npy_path β Input .npy path (for display, optional)
output_path β .html file write location
"""
# Load model to get correct input information
model = onnx.load(model_path)
# Add id and category to each node dictionary for JS use
nodes_list = []
for node_id, nd in debug_result.items():
entry = {
"node_id": node_id,
"op_type": nd["op_type"],
"category": _cat(nd["op_type"]),
"attrs": nd.get("attrs", {}),
"inputs": nd.get("inputs", {}),
"outputs": nd.get("outputs", {}),
}
nodes_list.append(entry)
# Prepare graph view data (nodes_data and edges)
nodes_data, edges = _build_graph_data(debug_result, model)
data_json = _safe_json({
"model": os.path.basename(model_path),
"npy": os.path.basename(npy_path) if npy_path else "No input file",
"time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"nodes": nodes_list,
"graph_nodes": nodes_data,
"graph_edges": edges,
})
html = _render_html(data_json, os.path.basename(model_path))
with open(output_path, "w", encoding="utf-8") as f:
f.write(html)
print(f"[OK] Report written -> {output_path}")
# βββ HTMLζ¨‘ζΏ βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _render_html(data_json: str, model_name: str) -> str: # noqa: C901
return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>ONNX Debugger - {model_name}</title>
<style>
:root{{
--bg:#0d1117;--panel:#161b22;--panel2:#1f2937;--border:#2d3748;
--accent:#3b82f6;--accent2:#8b5cf6;--text:#e2e8f0;--text2:#94a3b8;
--success:#22c55e;--warn:#f59e0b;--danger:#ef4444;--info:#06b6d4;
--c-conv:#3b82f6;--c-gemm:#8b5cf6;--c-act:#22c55e;--c-pool:#06b6d4;
--c-norm:#f59e0b;--c-eltwise:#ec4899;--c-shape:#a78bfa;
--c-upsample:#10b981;--c-rnn:#f97316;--c-reduce:#84cc16;
--c-attention:#e11d48;--c-other:#6b7280;
}}
*{{box-sizing:border-box;margin:0;padding:0}}
body{{background:var(--bg);color:var(--text);font-family:'Segoe UI',system-ui,sans-serif;
height:100vh;display:flex;flex-direction:column;overflow:hidden}}
a{{color:var(--accent);text-decoration:none}}
/* ββ header ββ */
header{{background:var(--panel);border-bottom:1px solid var(--border);
padding:10px 20px;display:flex;align-items:center;gap:14px;flex-shrink:0}}
.logo{{font-size:19px;font-weight:700;background:linear-gradient(135deg,var(--accent),var(--accent2));
-webkit-background-clip:text;-webkit-text-fill-color:transparent;white-space:nowrap}}
.hinfo{{font-size:12px;color:var(--text2);flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}}
.hchip{{background:var(--panel2);border:1px solid var(--border);border-radius:6px;
padding:3px 10px;font-size:12px;white-space:nowrap}}
.hchip span{{color:var(--accent);font-weight:700}}
.tabs{{display:flex;gap:3px}}
.tab{{padding:5px 14px;border-radius:6px;cursor:pointer;font-size:13px;color:var(--text2);
border:1px solid transparent;transition:all .15s}}
.tab.active{{background:var(--accent);color:#fff;border-color:var(--accent)}}
.tab:hover:not(.active){{background:var(--panel2);color:var(--text)}}
/* ββ layout ββ */
.main{{display:flex;flex:1;overflow:hidden}}
/* ββ node list (left) ββ */
#list-panel{{width:300px;background:var(--panel);border-right:1px solid var(--border);
display:flex;flex-direction:column;flex-shrink:0}}
#search-wrap{{padding:10px;border-bottom:1px solid var(--border)}}
#node-search{{width:100%;background:var(--panel2);border:1px solid var(--border);
border-radius:8px;color:var(--text);padding:6px 12px;font-size:13px;outline:none}}
#node-search:focus{{border-color:var(--accent)}}
#node-list{{flex:1;overflow-y:auto;padding:6px}}
#node-list::-webkit-scrollbar{{width:4px}}
#node-list::-webkit-scrollbar-thumb{{background:var(--border);border-radius:2px}}
.node-item{{padding:7px 10px;border-radius:8px;cursor:pointer;margin-bottom:3px;
display:flex;align-items:center;gap:8px;transition:background .12s}}
.node-item:hover{{background:var(--panel2)}}
.node-item.active{{background:var(--panel2);border:1px solid var(--accent)}}
.op-dot{{width:9px;height:9px;border-radius:3px;flex-shrink:0}}
.node-item-info{{min-width:0}}
.ni-op{{font-size:12px;font-weight:700;color:var(--text)}}
.ni-id{{font-size:10px;color:var(--text2);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}}
/* ββ detail panel (right) ββ */
#detail-panel{{flex:1;overflow-y:auto;padding:16px;background:var(--bg)}}
#detail-panel::-webkit-scrollbar{{width:6px}}
#detail-panel::-webkit-scrollbar-thumb{{background:var(--border);border-radius:3px}}
.no-sel{{color:var(--text2);text-align:center;padding:60px 20px;font-size:14px}}
/* card */
.card{{background:var(--panel);border:1px solid var(--border);border-radius:12px;
padding:16px;margin-bottom:14px}}
.card-title{{font-size:12px;font-weight:700;color:var(--text2);text-transform:uppercase;
letter-spacing:1px;margin-bottom:12px;display:flex;align-items:center;gap:6px}}
.card-title .icon{{font-size:14px}}
.op-badge{{display:inline-block;border-radius:8px;padding:4px 14px;font-size:15px;
font-weight:700;margin-bottom:10px}}
.info-row{{display:flex;gap:8px;margin-bottom:6px;font-size:12px}}
.ik{{color:var(--text2);width:90px;flex-shrink:0}}
.iv{{color:var(--text);word-break:break-all;flex:1}}
/* tensor grid */
.tensors-grid{{display:grid;grid-template-columns:1fr 1fr;gap:10px}}
@media(max-width:900px){{.tensors-grid{{grid-template-columns:1fr}}}}
.tensor-card{{background:var(--panel2);border-radius:8px;padding:10px 12px;border:1px solid var(--border)}}
.tensor-name{{font-size:11px;font-weight:700;color:var(--accent);margin-bottom:6px;
word-break:break-all}}
.tensor-meta{{font-size:11px;color:var(--text2);margin-bottom:6px}}
.stat-grid{{display:grid;grid-template-columns:1fr 1fr;gap:3px 10px}}
.stat-row{{display:flex;justify-content:space-between;font-size:11px}}
.sk{{color:var(--text2)}}
.sv{{color:var(--text);font-weight:600}}
.sv.danger{{color:var(--danger)}}
.sv.warn{{color:var(--warn)}}
.badge-nan{{background:var(--danger);color:#fff;font-size:9px;border-radius:4px;
padding:1px 5px;margin-left:4px}}
.badge-inf{{background:var(--warn);color:#000;font-size:9px;border-radius:4px;
padding:1px 5px;margin-left:4px}}
/* attr table */
.attr-table{{width:100%;border-collapse:collapse;font-size:12px}}
.attr-table td{{padding:4px 8px;border-bottom:1px solid rgba(45,55,72,.5)}}
.attr-table td:first-child{{color:var(--warn);width:120px;vertical-align:top}}
/* ββ stats tab ββ */
#stats-panel{{display:none;flex:1;overflow-y:auto;padding:20px;background:var(--bg)}}
#stats-panel.active{{display:block}}
.scard-grid{{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px;margin-bottom:20px}}
.scard{{background:var(--panel);border:1px solid var(--border);border-radius:12px;padding:16px}}
.scard-label{{font-size:12px;color:var(--text2);margin-bottom:8px}}
.scard-val{{font-size:26px;font-weight:700;background:linear-gradient(135deg,var(--accent),var(--accent2));
-webkit-background-clip:text;-webkit-text-fill-color:transparent}}
.scard-sub{{font-size:11px;color:var(--text2);margin-top:4px}}
.op-table{{width:100%;border-collapse:collapse;font-size:13px}}
.op-table th{{text-align:left;padding:8px 12px;font-size:11px;color:var(--text2);
text-transform:uppercase;letter-spacing:.5px;border-bottom:1px solid var(--border)}}
.op-table td{{padding:7px 12px;border-bottom:1px solid rgba(45,55,72,.4)}}
.op-table tr:hover td{{background:var(--panel)}}
.bar-bg{{background:var(--panel2);border-radius:4px;height:5px;min-width:80px}}
.bar-fill{{height:5px;border-radius:4px}}
/* ββ graph tab ββ */
#graph-panel{{display:none;flex:1;overflow:hidden;position:relative;background:var(--bg)}}
#graph-panel.active{{display:flex}}
#canvas-wrap{{flex:1;position:relative;overflow:hidden;cursor:grab}}
#canvas-wrap.grabbing{{cursor:grabbing}}
svg#graph-svg{{width:100%;height:100%}}
.node-group{{cursor:pointer;transition:filter .15s}}
.node-group:hover{{filter:brightness(1.3)}}
.node-rect{{rx:8;ry:8;stroke-width:1.5}}
.node-op{{font-size:12px;font-weight:700;fill:#fff;text-anchor:middle;dominant-baseline:central;pointer-events:none}}
.node-name{{font-size:9px;fill:rgba(255,255,255,0.6);text-anchor:middle;pointer-events:none}}
.edge-path{{fill:none;stroke:#3a3f5c;stroke-width:1.2;marker-end:url(#arrow);opacity:0.6}}
.edge-path.highlighted{{stroke:var(--accent);opacity:1;stroke-width:2}}
.node-rect.selected{{stroke:#fff;stroke-width:3;filter:drop-shadow(0 0 8px var(--accent))}}
.graph-controls{{position:absolute;bottom:16px;left:16px;display:flex;flex-direction:column;gap:6px}}
.ctrl-btn{{background:var(--panel);border:1px solid var(--border);border-radius:6px;color:var(--text);
width:32px;height:32px;cursor:pointer;font-size:16px;display:flex;align-items:center;
justify-content:center;transition:background .2s}}
.ctrl-btn:hover{{background:var(--panel2)}}
.graph-search{{position:absolute;top:12px;left:12px}}
#graph-search{{background:var(--panel);border:1px solid var(--border);border-radius:8px;color:var(--text);
padding:6px 12px;font-size:13px;width:220px;outline:none}}
#graph-search:focus{{border-color:var(--accent)}}
.graph-legend{{position:absolute;top:12px;right:12px;background:rgba(22,27,34,0.92);
border:1px solid var(--border);border-radius:8px;padding:10px 12px;font-size:11px;
display:flex;flex-direction:column;gap:4px}}
.legend-item{{display:flex;align-items:center;gap:6px}}
.legend-dot{{width:10px;height:10px;border-radius:3px;flex-shrink:0}}
#graph-detail-panel{{width:320px;background:var(--panel);border-left:1px solid var(--border);
display:none;flex-direction:column;flex-shrink:0;overflow:hidden;position:absolute;right:0;top:0;bottom:0;z-index:10}}
#graph-detail-panel.visible{{display:flex}}
.panel-header{{padding:12px 16px;border-bottom:1px solid var(--border);font-size:13px;
font-weight:600;color:var(--text2);display:flex;align-items:center;justify-content:space-between}}
.panel-content{{flex:1;overflow-y:auto;padding:12px}}
.panel-content::-webkit-scrollbar{{width:4px}}
.panel-content::-webkit-scrollbar-thumb{{background:var(--border);border-radius:2px}}
.section-title{{font-size:11px;font-weight:700;color:var(--accent);text-transform:uppercase;
letter-spacing:1px;margin:12px 0 6px}}
.tensor-item{{background:var(--panel2);border-radius:6px;padding:6px 10px;margin-bottom:4px;font-size:11px}}
.attr-item{{display:flex;gap:6px;font-size:11px;margin-bottom:4px}}
.attr-key{{color:var(--warn);min-width:80px;flex-shrink:0}}
.attr-val{{color:var(--text);word-break:break-all}}
</style>
</head>
<body>
<header>
<div class="logo">π ONNX Debugger</div>
<div class="hinfo" id="h-model"></div>
<div class="hchip">Nodes <span id="h-nodes">β</span></div>
<div class="hchip">Time <span id="h-time">β</span></div>
<div class="tabs">
<div class="tab active" id="tab-debug" onclick="switchTab('debug')">Debug View</div>
<div class="tab" id="tab-graph" onclick="switchTab('graph')">Graph View</div>
<div class="tab" id="tab-stats" onclick="switchTab('stats')">Statistics</div>
</div>
</header>
<div class="main">
<!-- left: node list (for debug view) -->
<div id="list-panel">
<div id="search-wrap">
<input id="node-search" type="text" placeholder="π Filter nodesβ¦">
</div>
<div id="node-list"></div>
</div>
<!-- right: detail + stats + graph -->
<div style="flex:1;display:flex;flex-direction:column;overflow:hidden">
<div id="detail-panel">
<div class="no-sel">β Select a node to inspect its tensors</div>
</div>
<div id="stats-panel"></div>
<div id="graph-panel">
<div id="canvas-wrap">
<svg id="graph-svg">
<defs>
<marker id="arrow" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto">
<path d="M0,0 L0,6 L8,3 z" fill="#3a3f5c"/>
</marker>
<marker id="arrow-hl" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto">
<path d="M0,0 L0,6 L8,3 z" fill="var(--accent)"/>
</marker>
</defs>
<g id="graph-root"></g>
</svg>
</div>
<div class="graph-search">
<input id="graph-search" type="text" placeholder="π Search nodes...">
</div>
<div class="graph-controls">
<button class="ctrl-btn" title="Zoom In" onclick="zoomBy(1.25)">+</button>
<button class="ctrl-btn" title="Zoom Out" onclick="zoomBy(0.8)">β</button>
<button class="ctrl-btn" title="Fit View" onclick="fitView()" style="font-size:13px">βΆ</button>
<button class="ctrl-btn" title="Toggle Panel" onclick="toggleGraphPanel()" style="font-size:13px">β°</button>
</div>
<div class="graph-legend" id="legend-panel"></div>
<div id="graph-detail-panel" class="hidden">
<div class="panel-header">
<span>Node Details</span>
<span style="font-size:10px;cursor:pointer;color:var(--text2)" onclick="toggleGraphPanel()">β</span>
</div>
<div class="panel-content" id="graph-node-detail">
<div class="no-sel">Click a node to view details</div>
</div>
</div>
</div>
</div>
</div>
<script>
const RAW = {data_json};
const nodes = RAW.nodes;
const graphNodes = RAW.graph_nodes || [];
const graphEdges = RAW.graph_edges || [];
// ββ colour map ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const CAT_COLOR = {{
conv:"#3b82f6",gemm:"#8b5cf6",act:"#22c55e",pool:"#06b6d4",
norm:"#f59e0b",eltwise:"#ec4899",shape:"#a78bfa",upsample:"#10b981",
rnn:"#f97316",reduce:"#84cc16",attention:"#e11d48",other:"#6b7280"
}};
const CAT_LABEL = {{
conv:"Conv",gemm:"FC/MatMul",act:"Activation",pool:"Pooling",
norm:"Normalization",eltwise:"Element-wise",shape:"Shape Ops",
upsample:"Upsample",rnn:"RNN",reduce:"Reduce",attention:"Attention",
input:"Input",output:"Output",other:"Other"
}};
function catColor(c){{ return CAT_COLOR[c]||"#6b7280"; }}
// ββ header info βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
document.getElementById("h-model").textContent = RAW.model + " Β· " + RAW.npy;
document.getElementById("h-nodes").textContent = nodes.length;
document.getElementById("h-time").textContent = RAW.time;
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// DEBUG VIEW
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// ββ build node list βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function buildList(filter){{
const container = document.getElementById("node-list");
container.innerHTML = "";
const q = (filter||"").toLowerCase();
nodes.forEach((nd,i) => {{
if(q && !nd.op_type.toLowerCase().includes(q) && !nd.node_id.toLowerCase().includes(q)) return;
const div = document.createElement("div");
div.className = "node-item" + (i===activeIdx?" active":"");
div.dataset.idx = i;
const color = catColor(nd.category);
div.innerHTML = `
<div class="op-dot" style="background:${{color}}"></div>
<div class="node-item-info" style="min-width:0">
<div class="ni-op" style="color:${{color}}">${{nd.op_type}}</div>
<div class="ni-id" title="${{nd.node_id}}">${{nd.node_id}}</div>
</div>`;
div.addEventListener("click", () => selectNode(i));
container.appendChild(div);
}});
}}
document.getElementById("node-search").addEventListener("input", function(){{
buildList(this.value);
}});
// ββ select node βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
let activeIdx = -1;
function selectNode(idx){{
activeIdx = idx;
buildList(document.getElementById("node-search").value);
renderDetail(nodes[idx]);
}}
// ββ format helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function fmt4(v){{
if(v===undefined||v===null) return "β";
return (typeof v==="number") ? v.toPrecision(6) : String(v);
}}
function tensorCard(name, t){{
if(!t || t.available===false) return `
<div class="tensor-card">
<div class="tensor-name">${{name}}</div>
<div class="tensor-meta" style="color:var(--danger)">Not captured</div>
</div>`;
const nanBadge = t.has_nan ? `<span class="badge-nan">NaN</span>`:"";
const infBadge = t.has_inf ? `<span class="badge-inf">Inf</span>`:"";
const s = t.stats||{{}};
return `
<div class="tensor-card">
<div class="tensor-name">${{name}}${{nanBadge}}${{infBadge}}</div>
<div class="tensor-meta">shape: [${{(t.shape||[]).join(", ")}}] Β· dtype: ${{t.dtype||"?"}}</div>
<div class="stat-grid">
<div class="stat-row"><span class="sk">min</span><span class="sv">${{fmt4(s.min)}}</span></div>
<div class="stat-row"><span class="sk">max</span><span class="sv">${{fmt4(s.max)}}</span></div>
<div class="stat-row"><span class="sk">mean</span><span class="sv">${{fmt4(s.mean)}}</span></div>
<div class="stat-row"><span class="sk">std</span><span class="sv">${{fmt4(s.std)}}</span></div>
<div class="stat-row"><span class="sk">abs_mean</span><span class="sv">${{fmt4(s.abs_mean)}}</span></div>
</div>
</div>`;
}}
function renderDetail(nd){{
const color = catColor(nd.category);
let html = `
<div class="card">
<div class="op-badge" style="background:${{color}}22;border:1px solid ${{color}};color:${{color}}">${{nd.op_type}}</div>
<div class="info-row"><div class="ik">Node ID</div><div class="iv">${{nd.node_id}}</div></div>
<div class="info-row"><div class="ik">Category</div><div class="iv">${{CAT_LABEL[nd.category]||nd.category}}</div></div>
</div>`;
// Attributes
const attrEntries = Object.entries(nd.attrs||{{}});
if(attrEntries.length){{
html += `<div class="card"><div class="card-title"><span class="icon">βοΈ</span>Attributes</div>
<table class="attr-table">`;
attrEntries.forEach(([k,v])=>{{
html += `<tr><td>${{k}}</td><td>${{JSON.stringify(v)}}</td></tr>`;
}});
html += `</table></div>`;
}}
// Inputs
const inEntries = Object.entries(nd.inputs||{{}});
if(inEntries.length){{
html += `<div class="card"><div class="card-title"><span class="icon">π₯</span>Input Tensors (` + inEntries.length + `)</div>
<div class="tensors-grid">`;
inEntries.forEach(([name,t])=>{{ html += tensorCard(name,t); }});
html += `</div></div>`;
}}
// Outputs