Skip to content

Commit df11e99

Browse files
authored
Adds variable to track random operators (#286)
* Adds variable to track random operators * doc * fox onnx_type_name * fix unittest * better coverahe * fix
1 parent aec66ed commit df11e99

19 files changed

+142
-20
lines changed

CHANGELOGS.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ Change Logs
44
0.8.1
55
+++++
66

7+
* :pr:`286`: adds variable to track random nodes in models
8+
79
0.8.0
810
+++++
911

_unittests/ut_export/test_shape_helper.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,10 +106,15 @@ def test_all_dynamic_shape_all_transformers_cache(self):
106106
]
107107
with torch_export_patches(patch_transformers=True):
108108
for cache, exds in caches:
109-
with self.subTest(cache_name=cache.__class__.__name__):
109+
with self.subTest(cache_name=cache.__class__.__name__, patch=True):
110110
ds = all_dynamic_shapes_from_inputs(cache)
111111
self.assertEqual(exds, ds)
112112

113+
for cache, exds in caches:
114+
with self.subTest(cache_name=cache.__class__.__name__, patch=False):
115+
ds = all_dynamic_shapes_from_inputs(cache)
116+
self.assertEqual(exds, ds)
117+
113118
@requires_transformers("4.52")
114119
@requires_torch("2.7.99")
115120
def test_all_dynamic_shapes_from_inputs(self):

_unittests/ut_helpers/test_args_helper.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
import unittest
22
from onnx_diagnostic.ext_test_case import ExtTestCase
3-
from onnx_diagnostic.helpers.args_helper import get_parsed_args
3+
from onnx_diagnostic.helpers.args_helper import get_parsed_args, check_cuda_availability
44

55

66
class TestHelpers(ExtTestCase):
7+
def test_check_cuda_availability(self):
8+
check_cuda_availability()
9+
710
def test_args(self):
811
try:
912
args = get_parsed_args(

_unittests/ut_helpers/test_bench_run.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,15 @@
99
get_machine,
1010
make_configs,
1111
run_benchmark,
12+
_clean_string,
1213
)
1314
from onnx_diagnostic.helpers.cache_helper import make_dynamic_cache, CacheKeyValue
1415

1516

1617
class TestBenchRun(ExtTestCase):
18+
def test__clean_string(self):
19+
self.assertEqual("r", _clean_string("r"))
20+
1721
def test_reg(self):
1822
text = ":m,6;"
1923
m = _extract_metrics(text)

_unittests/ut_helpers/test_graph_helper.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ def test_computation_order(self):
3333
proto.graph.node, [i.name for i in [*proto.graph.input, *proto.graph.initializer]]
3434
)
3535
self.assertEqual([1, 2, 3], order)
36+
gr = GraphRendering(proto)
37+
self.assertEqual(repr(gr), "GraphRendering(<ModelProto>)")
3638

3739
def test_graph_positions1(self):
3840
proto = oh.make_model(

_unittests/ut_helpers/test_helper.py

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -62,19 +62,21 @@ def test_string_type(self):
6262
s = string_type(obj)
6363
self.assertEqual(s, "dict(a:A7r1,b:#1[float],c:(int,))")
6464

65+
@hide_stdout()
6566
def test_string_dict(self):
6667
a = np.array([1], dtype=np.float32)
6768
obj = {"a": a, "b": {"r": 5.6}, "c": {1}}
68-
s = string_type(obj)
69+
s = string_type(obj, verbose=10)
6970
self.assertEqual(s, "dict(a:A1r1,b:dict(r:float),c:{int})")
7071

72+
@hide_stdout()
7173
def test_string_type_array(self):
7274
a = np.array([1], dtype=np.float32)
7375
t = torch.tensor([1])
7476
obj = {"a": a, "b": t}
75-
s = string_type(obj, with_shape=False)
77+
s = string_type(obj, with_shape=False, verbose=10)
7678
self.assertEqual(s, "dict(a:A1r1,b:T7r1)")
77-
s = string_type(obj, with_shape=True)
79+
s = string_type(obj, with_shape=True, verbose=10)
7880
self.assertEqual(s, "dict(a:A1s1,b:T7s1)")
7981

8082
def test_string_sig_f(self):
@@ -92,6 +94,17 @@ def __init__(self, a, b=3, c=4, e=5):
9294
ssig = string_sig(A(1, c=8))
9395
self.assertEqual(ssig, "A(a=1, c=8)")
9496

97+
def test_ort_value(self):
98+
import onnxruntime as onnxrt
99+
100+
numpy_arr_input = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], dtype=np.float32)
101+
ortvalue = onnxrt.OrtValue.ortvalue_from_numpy(numpy_arr_input)
102+
self.assertEqual("OV1r2", string_type(ortvalue))
103+
self.assertEqual("OV1s3x2", string_type(ortvalue, with_shape=True))
104+
self.assertEqual(
105+
"OV(NO-NUMPY:FIXIT)", string_type(ortvalue, with_shape=True, with_min_max=True)
106+
)
107+
95108
def test_pretty_onnx(self):
96109
proto = oh.make_model(
97110
oh.make_graph(
@@ -122,7 +135,8 @@ def test_print_pretty_onnx(self):
122135
[
123136
oh.make_node("Sigmoid", ["Y"], ["sy"]),
124137
oh.make_node("Mul", ["Y", "sy"], ["ysy"]),
125-
oh.make_node("Mul", ["X", "ysy"], ["final"]),
138+
oh.make_node("Cast", ["ysy"], ["ysyy"], to=1),
139+
oh.make_node("Mul", ["X", "ysyy"], ["final"]),
126140
],
127141
"-nd-",
128142
[

_unittests/ut_helpers/test_log_helper.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,7 @@ def test_cube_logs_excel(self):
183183
["version.*", "model.*"],
184184
["time_latency", "time_baseline"],
185185
key_agg=["model_name"],
186+
plots=True,
186187
),
187188
},
188189
verbose=1,
@@ -268,7 +269,7 @@ def test_cube_logs_performance_cube_time(self):
268269
cube = CubeLogsPerformance(dfs, keep_last_date=True)
269270
cube.load()
270271
ct = cube.clone()
271-
self.assertEqual((52, 116), ct.shape)
272+
self.assertEqual((52, 117), ct.shape)
272273

273274
def test_duplicate(self):
274275
df = pandas.DataFrame(
@@ -523,6 +524,14 @@ def test_cube_sbs_no_time(self):
523524
self.assertEqual(sbs_agg.shape, (2, 11))
524525
self.assertEqual(sbs_agg.index.names, ["date", "METRICS"])
525526
self.assertEqual(sorted(sbs_agg.columns.names), ["CONF", "exporter"])
527+
output = self.get_dump_file("test_cube_sbs_no_time.xlsx")
528+
cube.to_excel(
529+
output,
530+
views=["time_p"],
531+
time_mask=True,
532+
verbose=0,
533+
sbs=dict(CFA=dict(exporter="E1", opt="O"), CFB=dict(exporter="E2", opt="O")),
534+
)
526535

527536
def test_cube_sbs_with_time(self):
528537
df = pandas.DataFrame(

_unittests/ut_helpers/test_memory_peak.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,22 @@
99
ignore_warnings,
1010
requires_cuda,
1111
)
12-
from onnx_diagnostic.helpers.memory_peak import get_memory_rss, start_spying_on
12+
from onnx_diagnostic.helpers.memory_peak import get_memory_rss, start_spying_on, Monitor
1313

1414

1515
class TestMemoryPeak(ExtTestCase):
16+
def test_basic(self):
17+
m = Monitor()
18+
self.assertEqual(
19+
repr(m),
20+
"Monitor(begin=0, end=0, peak=0, average=0, n=0, d_end=0, d_peak=0, d_avg=0)",
21+
)
22+
m.update(1)
23+
self.assertEqual(
24+
repr(m),
25+
"Monitor(begin=1, end=1, peak=1, average=1, n=1, d_end=0, d_peak=0, d_avg=0.0)",
26+
)
27+
1628
@skipif_ci_apple("stuck")
1729
def test_memory(self):
1830
mem = get_memory_rss(os.getpid())

_unittests/ut_helpers/test_mini_onnx_builder.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,27 @@
11
import unittest
22
import numpy as np
3+
import onnx
34
import torch
45
from onnx_diagnostic.ext_test_case import ExtTestCase
56
from onnx_diagnostic.reference import ExtendedReferenceEvaluator
67
from onnx_diagnostic.helpers.mini_onnx_builder import (
78
create_onnx_model_from_input_tensors,
89
create_input_tensors_from_onnx_model,
10+
proto_from_array,
911
MiniOnnxBuilder,
1012
)
1113
from onnx_diagnostic.helpers.cache_helper import make_dynamic_cache, CacheKeyValue
1214
from onnx_diagnostic.helpers import string_type
1315

1416

1517
class TestMiniOnnxBuilder(ExtTestCase):
18+
def test_proto_from_array(self):
19+
self.assertRaise(lambda: proto_from_array(None), TypeError)
20+
t = torch.tensor([[0, 2.0], [3, 0]]).to_sparse()
21+
self.assertRaise(lambda: proto_from_array(t), NotImplementedError)
22+
tp = proto_from_array(torch.tensor([[0, 2.0], [3, 0]]).to(torch.bfloat16))
23+
self.assertEqual(tp.data_type, onnx.TensorProto.BFLOAT16)
24+
1625
def test_mini_onnx_builder_sequence_onnx(self):
1726
builder = MiniOnnxBuilder()
1827
builder.append_output_sequence("name", [np.array([6, 7])])
@@ -31,6 +40,25 @@ def test_mini_onnx_builder_sequence_ort(self):
3140
got = ref.run(None, {})
3241
self.assertEqualAny([np.array([6, 7])], got[0])
3342

43+
def test_mini_onnx_builder_sequence_ort_randomize(self):
44+
from onnxruntime import InferenceSession
45+
46+
builder = MiniOnnxBuilder()
47+
builder.append_output_initializer(
48+
"name1", np.array([6, 7], dtype=np.float32), randomize=True
49+
)
50+
builder.append_output_initializer(
51+
"name2", np.array([-6, 7], dtype=np.float32), randomize=True
52+
)
53+
onx = builder.to_onnx()
54+
ref = InferenceSession(onx.SerializeToString(), providers=["CPUExecutionProvider"])
55+
got = ref.run(None, {})
56+
self.assertEqual((2,), got[0].shape)
57+
self.assertEqual(np.float32, got[0].dtype)
58+
self.assertGreaterOrEqual(got[0].min(), 0)
59+
self.assertEqual((2,), got[1].shape)
60+
self.assertEqual(np.float32, got[1].dtype)
61+
3462
def test_mini_onnx_builder(self):
3563
data = [
3664
(

_unittests/ut_helpers/test_onnx_helper.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
tensor_statistics,
1919
enumerate_results,
2020
shadowing_names,
21+
onnx_dtype_name,
2122
)
2223

2324

@@ -295,6 +296,7 @@ def test_enumerate_results(self):
295296
self.assertEqual(2, len(list(enumerate_results(model, "X", verbose=2))))
296297
self.assertEqual(2, len(list(enumerate_results(model, "Z", verbose=2))))
297298

299+
@hide_stdout()
298300
def test_enumerate_results_loop(self):
299301
x = np.array([1, 2, 3, 4, 5]).astype(np.float32)
300302

@@ -467,6 +469,13 @@ def _mkv_(name):
467469
shadowing_names(model),
468470
)
469471

472+
def test_onnx_dtype_name(self):
473+
for k in dir(TensorProto):
474+
if k.upper() == k and k not in {"DESCRIPTOR", "EXTERNAL"}:
475+
self.assertEqual(k, onnx_dtype_name(getattr(TensorProto, k)))
476+
self.assertRaise(lambda: onnx_dtype_name(1000), ValueError)
477+
self.assertEqual(onnx_dtype_name(1000, exc=False), "UNEXPECTED")
478+
470479

471480
if __name__ == "__main__":
472481
unittest.main(verbosity=2)

0 commit comments

Comments
 (0)