-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathonnx_visualnode.py
More file actions
1557 lines (1368 loc) · 64.8 KB
/
Copy pathonnx_visualnode.py
File metadata and controls
1557 lines (1368 loc) · 64.8 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
合并了所有模块功能的单文件版本,用于捕获和可视化ONNX模型推理过程中所有节点的中间张量值。
Usage:
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
# ============================================================================
# 模块1: graph_patcher - 图修改工具
# ============================================================================
def patch_model_expose_all_intermediates(model: onnx.ModelProto) -> onnx.ModelProto:
"""
将所有中间张量(value_info)注册为图输出。
这是捕获所有节点激活值的核心技巧。
"""
# 形状推断填充可能缺失的value_info条目
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
# ============================================================================
# 模块2: model_loader - 模型加载器
# ============================================================================
def load_model(model_path: str) -> onnx.ModelProto:
"""加载ONNX模型并尝试形状推断。"""
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
# ============================================================================
# 模块3: runner - 推理执行器
# ============================================================================
class OnnxRunner:
def __init__(self, model_path: str):
model = onnx.load(model_path)
patched_model = patch_model_expose_all_intermediates(model)
# 禁用图优化以防止节点融合
sess_options = ort.SessionOptions()
sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_DISABLE_ALL
# 直接从内存加载修改后的模型 — 无需临时文件
self.session = ort.InferenceSession(
patched_model.SerializeToString(),
sess_options=sess_options,
)
self.model = model
def run_from_npy(self, npy_path: str) -> dict:
"""加载input.npy并返回所有张量(输入 + 每个中间层)。"""
input_data = np.load(npy_path, allow_pickle=True)
# 支持dict-in-npy(多输入)或普通数组(单输入)
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)
# 合并原始输入以便每个节点的输入张量都可访问
all_tensors = {**inputs, **dict(zip(output_names, results))}
return all_tensors
# ============================================================================
# 模块4: node_info - 节点信息提取
# ============================================================================
def get_node_static_info(node: onnx.NodeProto, idx: int) -> dict:
"""返回 {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],
}
# ============================================================================
# 模块5: tensor_viewer - 张量统计
# ============================================================================
def tensor_stats(arr: np.ndarray) -> dict:
"""返回数值张量的min/max/mean/std/abs_mean。"""
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:
"""
返回单个张量的详细描述字典:
{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
# ============================================================================
# 模块6: debugger - 主调试器接口
# ============================================================================
class OnnxDebugger:
def __init__(self, model_path: str):
self.model_path = model_path
self.model = onnx.load(model_path)
self.runner = OnnxRunner(model_path)
# ------------------------------------------------------------------
# 核心方法
# ------------------------------------------------------------------
def run(self, npy_path: str) -> dict:
"""
运行推理并返回每个节点的结构化字典,包含实际张量
值(形状 + 统计信息)用于每个输入和输出。
"""
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: # 跳过空的可选输入
arr = all_tensors.get(name)
desc = describe_tensor(name, arr)
if desc.get("available"):
# 仅保留可序列化的键
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
# ------------------------------------------------------------------
# 便捷辅助方法
# ------------------------------------------------------------------
def inspect_node(self, node_id: str, npy_path: str):
"""漂亮打印单个节点的I/O张量。"""
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}")
# ============================================================================
# 模块7: html_builder - HTML报告生成
# ============================================================================
def _safe_json(obj):
"""序列化为JSON,优雅地转换不可序列化的类型。"""
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):
"""
从debug_result构建图形视图所需的nodes_data和edges
返回: (nodes_data, edges)
"""
nodes_data = []
edges = []
# 建立tensor name到node id的映射
tensor_to_node = {}
# 收集所有输入tensor(模型输入)
all_input_tensors = set()
all_output_tensors = set()
all_intermediate_tensors = set()
# 第一步:收集所有tensor信息
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)
# 从ONNX模型获取真正的输入(排除initializer中的权重参数)
model_inputs = set()
if model is not None:
# 获取所有initializer(权重参数)的名称
initializer_names = {init.name for init in model.graph.initializer}
# 真正的模型输入 = 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:
# 如果没有model对象,使用旧逻辑作为fallback
model_inputs = all_input_tensors - all_intermediate_tensors
# 模型输出 = 所有输出tensor中不被其他节点使用的
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)
# 第二步:创建input节点
input_node_id = 0
input_tensor_to_node = {}
# 从ONNX模型获取输入元数据
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:
# 提取shape和dtype信息
shape = []
dtype_str = "unknown"
if input_info.type.tensor_type:
tt = input_info.type.tensor_type
# 获取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)
# 获取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):
# 优先从ONNX模型元数据获取shape
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: 从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
# 第三步:创建所有算子节点
for idx, (node_id, nd) in enumerate(debug_result.items()):
nid = idx + input_node_id # 偏移input节点数量
# 收集输入输出形状信息
input_shapes = []
for name, tensor_info in nd.get("inputs", {}).items():
# 即使tensor不可用,也尝试获取shape信息
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():
# 即使tensor不可用,也尝试获取shape信息
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", {}),
})
# 记录输出tensor到node的映射
for out_name in nd.get("outputs", {}).keys():
tensor_to_node[out_name] = nid
# 第四步:创建output节点
output_node_start_id = len(nodes_data)
output_tensor_to_node = {}
# 从ONNX模型获取输出元数据
output_metadata = {}
if model is not None:
for output_info in model.graph.output:
# 提取shape和dtype信息
shape = []
dtype_str = "unknown"
if output_info.type.tensor_type:
tt = output_info.type.tensor_type
# 获取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)
# 获取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):
# 优先从ONNX模型元数据获取shape
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: 从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
# 第五步:构建边(基于tensor依赖关系)
seen_edges = set()
# 从input节点到第一个使用它的算子节点
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]
})
# 算子节点之间的边
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]
})
# 从算子节点到output节点
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,
output_path: str,
):
"""
debug_result – OnnxDebugger.run()返回的字典
model_path – .onnx路径(用于显示)
npy_path – 输入.npy路径(用于显示)
output_path – .html文件写入位置
"""
# 加载模型以获取正确的输入信息
model = onnx.load(model_path)
# 为每个节点字典添加id和category以便JS使用
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)
# 准备图形视图数据 (nodes_data 和 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),
"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:"输入",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
const outEntries = Object.entries(nd.outputs||{{}});
if(outEntries.length){{
html += `<div class="card"><div class="card-title"><span class="icon">📤</span>Output Tensors (` + outEntries.length + `)</div>