|
| 1 | +""" |
| 2 | +LayerNormalization implementation cannot be exchanged |
| 3 | +===================================================== |
| 4 | +
|
| 5 | +This example applies what was illustrated |
| 6 | +:ref:`l-plot-parallelized-reduction`, reduction operations |
| 7 | +are sensitive to parallelization. |
| 8 | +
|
| 9 | +We consider a small model including a layer normalization |
| 10 | +followed by a matrix multiplication and we show that replacing |
| 11 | +a kernel by another one may significantly impact the output. |
| 12 | +
|
| 13 | +The model |
| 14 | ++++++++++ |
| 15 | +""" |
| 16 | + |
| 17 | +import itertools |
| 18 | +import pandas |
| 19 | +import onnx |
| 20 | +import onnx.helper as oh |
| 21 | +import onnxruntime |
| 22 | +import torch |
| 23 | +from onnx_array_api.plotting.graphviz_helper import plot_dot |
| 24 | +from onnx_diagnostic.ext_test_case import unit_test_going |
| 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 |
| 29 | +from onnx_diagnostic.reference import TorchOnnxEvaluator |
| 30 | + |
| 31 | +TFLOAT = onnx.TensorProto.FLOAT |
| 32 | +TFLOAT16 = onnx.TensorProto.FLOAT16 |
| 33 | + |
| 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() |
| 59 | +plot_dot(model) |
| 60 | + |
| 61 | +# %% |
| 62 | +# Let's compare two runtimes |
| 63 | +# ++++++++++++++++++++++++++ |
| 64 | +# |
| 65 | +# That will be :epkg:`onnxruntime` and |
| 66 | +# :class:`onnx_diagnostic.reference.TorchOnnxEvaluator`. |
| 67 | + |
| 68 | +last_dim = 64 if unit_test_going() else 1152 |
| 69 | + |
| 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()} |
| 83 | + if provider == "CUDA": |
| 84 | + if not torch.cuda.is_available(): |
| 85 | + return None, None |
| 86 | + tch_feeds = {k: v.to("cuda") for k, v in feeds.items()} |
| 87 | + ort_feeds = np_feeds |
| 88 | + else: |
| 89 | + tch_feeds = feeds.copy() |
| 90 | + tch_feeds["X"] = tch_feeds["X"][:2] # too long otherwise |
| 91 | + ort_feeds = np_feeds.copy() |
| 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) |
| 111 | + print() |
| 112 | + print(f"-- running on {provider} with {onnx_dtype_name(itype)}") |
| 113 | + print("-- running with torch") |
| 114 | + torch_sess = TorchOnnxEvaluator(model, providers=[f"{provider}ExecutionProvider"]) |
| 115 | + expected = torch_sess.run(None, tch_feeds) |
| 116 | + baseline[itype, provider, "torch"] = expected |
| 117 | + print(f"-- torch: {string_type(expected, **kws)}") |
| 118 | + |
| 119 | + print("-- running with ort") |
| 120 | + ort_sess = onnxruntime.InferenceSession( |
| 121 | + model.SerializeToString(), providers=[f"{provider}ExecutionProvider"] |
| 122 | + ) |
| 123 | + got = ort_sess.run(None, ort_feeds) |
| 124 | + baseline[itype, provider, "ort"] = got |
| 125 | + print(f"-- ort: {string_type(got, **kws)}") |
| 126 | + diff = max_diff(expected, got, hist=True) |
| 127 | + print(f"-- diff {string_diff(diff)}") |
| 128 | + |
| 129 | + # memorize the data |
| 130 | + diff["dtype"] = onnx_dtype_name(itype) |
| 131 | + diff["provider"] = provider |
| 132 | + diff.update(diff["rep"]) |
| 133 | + del diff["rep"] |
| 134 | + del diff["dnan"] |
| 135 | + del diff[">100.0"] |
| 136 | + del diff[">10.0"] |
| 137 | + data.append(diff) |
| 138 | + |
| 139 | +# %% |
| 140 | +df = pandas.DataFrame(data).set_index(["provider", "dtype"]) |
| 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