|
14 | 14 | +++++++++ |
15 | 15 | """ |
16 | 16 |
|
| 17 | +import itertools |
17 | 18 | import pandas |
18 | 19 | import onnx |
19 | 20 | import onnx.helper as oh |
20 | 21 | import onnxruntime |
21 | 22 | import torch |
22 | 23 | from onnx_array_api.plotting.graphviz_helper import plot_dot |
| 24 | +from onnx_diagnostic.ext_test_case import unit_test_going |
23 | 25 | from onnx_diagnostic.helpers import max_diff, string_diff, string_type |
| 26 | +from onnx_diagnostic.helpers.onnx_helper import onnx_dtype_name, onnx_dtype_to_np_dtype |
| 27 | +from onnx_diagnostic.helpers.torch_helper import onnx_dtype_to_torch_dtype |
| 28 | +from onnx_diagnostic.helpers.doc_helper import LayerNormalizationOrt, MatMulOrt |
24 | 29 | from onnx_diagnostic.reference import TorchOnnxEvaluator |
25 | 30 |
|
| 31 | +TFLOAT = onnx.TensorProto.FLOAT |
26 | 32 | TFLOAT16 = onnx.TensorProto.FLOAT16 |
27 | 33 |
|
28 | | -model = oh.make_model( |
29 | | - oh.make_graph( |
30 | | - [ |
31 | | - oh.make_node("LayerNormalization", ["X", "scale", "bias"], ["norm"], axis=-1), |
32 | | - oh.make_node("MatMul", ["norm", "weights"], ["mm"]), |
33 | | - oh.make_node("Add", ["mm", "bias2"], ["Z"]), |
34 | | - ], |
35 | | - "layer_norm_matmul_add", |
36 | | - [ |
37 | | - oh.make_tensor_value_info("X", TFLOAT16, ["a", "b", "c"]), |
38 | | - oh.make_tensor_value_info("scale", TFLOAT16, ["c"]), |
39 | | - oh.make_tensor_value_info("bias", TFLOAT16, ["c"]), |
40 | | - oh.make_tensor_value_info("weights", TFLOAT16, ["c", "c"]), |
41 | | - oh.make_tensor_value_info("bias2", TFLOAT16, ["c"]), |
42 | | - ], |
43 | | - [oh.make_tensor_value_info("Z", TFLOAT16, ["a", "b", "c"])], |
44 | | - ), |
45 | | - ir_version=9, |
46 | | - opset_imports=[oh.make_opsetid("", 18)], |
47 | | -) |
48 | 34 |
|
| 35 | +def get_model(itype: int = TFLOAT16): |
| 36 | + return oh.make_model( |
| 37 | + oh.make_graph( |
| 38 | + [ |
| 39 | + oh.make_node("LayerNormalization", ["X", "scale", "bias"], ["norm"], axis=-1), |
| 40 | + oh.make_node("MatMul", ["norm", "weights"], ["mm"]), |
| 41 | + oh.make_node("Add", ["mm", "bias2"], ["Z"]), |
| 42 | + ], |
| 43 | + "layer_norm_matmul_add", |
| 44 | + [ |
| 45 | + oh.make_tensor_value_info("X", itype, ["a", "b", "c"]), |
| 46 | + oh.make_tensor_value_info("scale", itype, ["c"]), |
| 47 | + oh.make_tensor_value_info("bias", itype, ["c"]), |
| 48 | + oh.make_tensor_value_info("weights", itype, ["c", "c"]), |
| 49 | + oh.make_tensor_value_info("bias2", itype, ["c"]), |
| 50 | + ], |
| 51 | + [oh.make_tensor_value_info("Z", itype, ["a", "b", "c"])], |
| 52 | + ), |
| 53 | + ir_version=9, |
| 54 | + opset_imports=[oh.make_opsetid("", 18)], |
| 55 | + ) |
| 56 | + |
| 57 | + |
| 58 | +model = get_model() |
49 | 59 | plot_dot(model) |
50 | 60 |
|
51 | 61 | # %% |
|
55 | 65 | # That will be :epkg:`onnxruntime` and |
56 | 66 | # :class:`onnx_diagnostic.reference.TorchOnnxEvaluator`. |
57 | 67 |
|
58 | | -feeds = { |
59 | | - "X": (torch.rand((32, 1024, 1152), dtype=torch.float16) - 0.5) * 120, |
60 | | - "scale": torch.rand((1152,), dtype=torch.float16), |
61 | | - "bias": torch.rand((1152,), dtype=torch.float16), |
62 | | - "weights": torch.rand((1152, 1152), dtype=torch.float16), |
63 | | - "bias2": torch.rand((1152,), dtype=torch.float16), |
64 | | -} |
65 | | -np_feeds = {k: v.detach().numpy() for k, v in feeds.items()} |
66 | | -kws = dict(with_shape=True, with_min_max=True, with_device=True) |
67 | | -data = [] |
| 68 | +last_dim = 64 if unit_test_going() else 1152 |
68 | 69 |
|
69 | | -for provider in ["CPU", "CUDA"]: |
| 70 | + |
| 71 | +def make_feeds(last_dim: int): |
| 72 | + return { |
| 73 | + "X": (torch.rand((32, 1024, last_dim), dtype=torch.float16) - 0.5) * 120, |
| 74 | + "scale": torch.rand((last_dim,), dtype=torch.float16), |
| 75 | + "bias": torch.rand((last_dim,), dtype=torch.float16), |
| 76 | + "weights": torch.rand((last_dim, last_dim), dtype=torch.float16), |
| 77 | + "bias2": torch.rand((last_dim,), dtype=torch.float16), |
| 78 | + } |
| 79 | + |
| 80 | + |
| 81 | +def cast_feeds(itype, provider, feeds): |
| 82 | + np_feeds = {k: v.detach().numpy() for k, v in feeds.items()} |
70 | 83 | if provider == "CUDA": |
71 | 84 | if not torch.cuda.is_available(): |
72 | | - continue |
| 85 | + return None, None |
73 | 86 | tch_feeds = {k: v.to("cuda") for k, v in feeds.items()} |
74 | 87 | ort_feeds = np_feeds |
75 | 88 | else: |
76 | 89 | tch_feeds = feeds.copy() |
77 | 90 | tch_feeds["X"] = tch_feeds["X"][:2] # too long otherwise |
78 | 91 | ort_feeds = np_feeds.copy() |
79 | 92 | ort_feeds["X"] = ort_feeds["X"][:2] |
| 93 | + tch_feeds = {k: v.to(ttype) for k, v in tch_feeds.items()} |
| 94 | + ort_feeds = {k: v.astype(np_dtype) for k, v in ort_feeds.items()} |
| 95 | + return tch_feeds, ort_feeds |
| 96 | + |
| 97 | + |
| 98 | +feeds = make_feeds(last_dim) |
| 99 | +kws = dict(with_shape=True, with_min_max=True, with_device=True) |
| 100 | +data = [] |
| 101 | +baseline = {} |
| 102 | + |
| 103 | +for provider, itype in itertools.product(["CPU", "CUDA"], [TFLOAT, TFLOAT16]): |
| 104 | + ttype = onnx_dtype_to_torch_dtype(itype) |
| 105 | + np_dtype = onnx_dtype_to_np_dtype(itype) |
| 106 | + tch_feeds, ort_feeds = cast_feeds(itype, provider, feeds) |
| 107 | + if tch_feeds is None: |
| 108 | + continue |
| 109 | + |
| 110 | + model = get_model(itype) |
80 | 111 | print() |
81 | | - print(f"-- running on {provider}") |
| 112 | + print(f"-- running on {provider} with {onnx_dtype_name(itype)}") |
82 | 113 | print("-- running with torch") |
83 | 114 | torch_sess = TorchOnnxEvaluator(model, providers=[f"{provider}ExecutionProvider"]) |
84 | 115 | expected = torch_sess.run(None, tch_feeds) |
| 116 | + baseline[itype, provider, "torch"] = expected |
85 | 117 | print(f"-- torch: {string_type(expected, **kws)}") |
86 | 118 |
|
87 | 119 | print("-- running with ort") |
88 | 120 | ort_sess = onnxruntime.InferenceSession( |
89 | 121 | model.SerializeToString(), providers=[f"{provider}ExecutionProvider"] |
90 | 122 | ) |
91 | 123 | got = ort_sess.run(None, ort_feeds) |
| 124 | + baseline[itype, provider, "ort"] = got |
92 | 125 | print(f"-- ort: {string_type(got, **kws)}") |
93 | 126 | diff = max_diff(expected, got, hist=True) |
94 | 127 | print(f"-- diff {string_diff(diff)}") |
95 | 128 |
|
96 | 129 | # memorize the data |
| 130 | + diff["dtype"] = onnx_dtype_name(itype) |
97 | 131 | diff["provider"] = provider |
98 | 132 | diff.update(diff["rep"]) |
99 | 133 | del diff["rep"] |
| 134 | + del diff["dnan"] |
| 135 | + del diff[">100.0"] |
| 136 | + del diff[">10.0"] |
100 | 137 | data.append(diff) |
101 | 138 |
|
102 | 139 | # %% |
103 | | -df = pandas.DataFrame(data).set_index("provider") |
| 140 | +df = pandas.DataFrame(data).set_index(["provider", "dtype"]) |
104 | 141 | print(df) |
| 142 | + |
| 143 | +# %% |
| 144 | +# Visually. |
| 145 | + |
| 146 | +df["abs"].plot(title="Discrepancies ORT / torch for LayerNorm(X) @ W + B") |
| 147 | + |
| 148 | +# %% |
| 149 | +# The discrepancies are significant on CUDA, higher for float16. |
| 150 | +# Let's see which operator is responsible for them, |
| 151 | +# *LayerNormalization* or *MatMul*. |
| 152 | + |
| 153 | +# %% |
| 154 | +# The discrepancies come from? |
| 155 | +# ++++++++++++++++++++++++++++ |
| 156 | +# |
| 157 | +# We mix torch and onnxruntime to execute the kernels. |
| 158 | + |
| 159 | +data = [] |
| 160 | + |
| 161 | +for mod, provider, itype in itertools.product( |
| 162 | + ["ORT-TORCH", "TORCH-ORT"], ["CPU", "CUDA"], [TFLOAT, TFLOAT16] |
| 163 | +): |
| 164 | + ttype = onnx_dtype_to_torch_dtype(itype) |
| 165 | + np_dtype = onnx_dtype_to_np_dtype(itype) |
| 166 | + tch_feeds, _ = cast_feeds(itype, provider, feeds) |
| 167 | + if tch_feeds is None: |
| 168 | + continue |
| 169 | + |
| 170 | + custom_kernels = ( |
| 171 | + {("", "LayerNormalization"): LayerNormalizationOrt} |
| 172 | + if mod == "ORT-TORCH" |
| 173 | + else {("", "MatMul"): MatMulOrt} |
| 174 | + ) |
| 175 | + |
| 176 | + model = get_model(itype) |
| 177 | + print() |
| 178 | + print(f"-- {mod} running on {provider} with {onnx_dtype_name(itype)}") |
| 179 | + sess = TorchOnnxEvaluator( |
| 180 | + model, |
| 181 | + custom_kernels=custom_kernels, |
| 182 | + providers=[f"{provider}ExecutionProvider"], |
| 183 | + ) |
| 184 | + got = sess.run(None, tch_feeds) |
| 185 | + print(f"-- {mod}: {string_type(got, **kws)}") |
| 186 | + |
| 187 | + difft = max_diff(baseline[itype, provider, "torch"], got) |
| 188 | + print(f"-- diff with torch {string_diff(difft)}") |
| 189 | + diffo = max_diff(baseline[itype, provider, "ort"], got) |
| 190 | + print(f"-- diff with ort {string_diff(diffo)}") |
| 191 | + |
| 192 | + data.append( |
| 193 | + dict( |
| 194 | + model=mod, |
| 195 | + dtype=onnx_dtype_name(itype), |
| 196 | + provider=provider, |
| 197 | + diff_ort=diffo["abs"], |
| 198 | + diff_torch=difft["abs"], |
| 199 | + ) |
| 200 | + ) |
| 201 | + |
| 202 | +# %% |
| 203 | +df = pandas.DataFrame(data).set_index(["model", "provider", "dtype"]) |
| 204 | +df = df.sort_index() |
| 205 | +print(df) |
| 206 | + |
| 207 | +# %% |
| 208 | +# Visually. |
| 209 | + |
| 210 | +df[["diff_ort", "diff_torch"]].plot(title="ORT/Torch or Torch/ORT for LayerNorm(X) @ W + B") |
0 commit comments