|
| 1 | +from typing import Dict, Optional, Tuple |
| 2 | +import onnx |
| 3 | +import onnx.helper as oh |
| 4 | +import torch |
| 5 | +from .torch_helper import onnx_dtype_to_torch_dtype, torch_dtype_to_onnx_dtype |
| 6 | +from ..reference.torch_ops import OpRunKernel, OpRunTensor |
| 7 | + |
| 8 | + |
| 9 | +class LayerNormalizationOrt(OpRunKernel): |
| 10 | + "LayerNormalization with onnxruntime" |
| 11 | + |
| 12 | + @classmethod |
| 13 | + def device_dependent(cls) -> bool: |
| 14 | + "Needs device." |
| 15 | + return False |
| 16 | + |
| 17 | + def __init__( |
| 18 | + self, |
| 19 | + node: onnx.NodeProto, |
| 20 | + version=None, |
| 21 | + device: Optional[torch.device] = None, |
| 22 | + verbose=0, |
| 23 | + ): |
| 24 | + super().__init__(node, version, verbose=verbose) |
| 25 | + self.axis = self.get_attribute_int(node, "axis", -1) |
| 26 | + self.epsilon = self.get_attribute_float(node, "epsilon", 1e-5) |
| 27 | + self.device = device |
| 28 | + self.stash_type = onnx_dtype_to_torch_dtype( |
| 29 | + self.get_attribute_int(node, "stash_type", onnx.TensorProto.FLOAT) # type: ignore[arg-type] |
| 30 | + ) |
| 31 | + self.compute_std = len(node.output) > 1 |
| 32 | + assert not self.compute_std, ( |
| 33 | + f"This kernel implementation only work when only one output " |
| 34 | + f"is required but {node.output} were." |
| 35 | + ) |
| 36 | + self._cache: Dict[Tuple[int, int], onnx.ModelProto] = {} |
| 37 | + self.is_cpu = torch.device("cpu") == self.device |
| 38 | + |
| 39 | + def _make_model(self, itype: int, rank: int) -> onnx.ModelProto: |
| 40 | + shape = [*["d{i}" for i in range(rank - 1)], "last"] |
| 41 | + layer_model = oh.make_model( |
| 42 | + oh.make_graph( |
| 43 | + [ |
| 44 | + oh.make_node( |
| 45 | + "LayerNormalization", |
| 46 | + ["X", "W", "B"], |
| 47 | + ["Z"], |
| 48 | + axis=self.axis, |
| 49 | + epsilon=self.epsilon, |
| 50 | + ) |
| 51 | + ], |
| 52 | + "dummy", |
| 53 | + [ |
| 54 | + oh.make_tensor_value_info("X", itype, shape), |
| 55 | + oh.make_tensor_value_info("W", itype, ["last"]), |
| 56 | + oh.make_tensor_value_info("B", itype, ["last"]), |
| 57 | + ], |
| 58 | + [oh.make_tensor_value_info("Z", itype, shape)], |
| 59 | + ), |
| 60 | + ir_version=9, |
| 61 | + opset_imports=[oh.make_opsetid("", 18)], |
| 62 | + ) |
| 63 | + import onnxruntime |
| 64 | + |
| 65 | + provider = "CPUExecutionProvider" if self.is_cpu else "CUDAExecutionProvider" |
| 66 | + return onnxruntime.InferenceSession( |
| 67 | + layer_model.SerializeToString(), providers=[provider] |
| 68 | + ) |
| 69 | + |
| 70 | + def run(self, x, scale, bias=None): |
| 71 | + itype = torch_dtype_to_onnx_dtype(x.dtype) |
| 72 | + rank = len(x.shape) |
| 73 | + key = itype, rank |
| 74 | + if key not in self._cache: |
| 75 | + self._cache[key] = self._make_model(itype, rank) |
| 76 | + sess = self._cache[key] |
| 77 | + feeds = dict(X=x, W=scale) |
| 78 | + if bias is not None: |
| 79 | + feeds["B"] = bias |
| 80 | + feeds = {k: v.tensor.detach().cpu().numpy() for k, v in feeds.items()} |
| 81 | + got = sess.run(None, feeds)[0] |
| 82 | + return OpRunTensor(torch.from_numpy(got).to(x.dtype).to(x.device)) |
| 83 | + |
| 84 | + |
| 85 | +class MatMulOrt(OpRunKernel): |
| 86 | + "MatMul with onnxruntime" |
| 87 | + |
| 88 | + @classmethod |
| 89 | + def device_dependent(cls) -> bool: |
| 90 | + "Needs device." |
| 91 | + return False |
| 92 | + |
| 93 | + def __init__( |
| 94 | + self, |
| 95 | + node: onnx.NodeProto, |
| 96 | + version=None, |
| 97 | + device: Optional[torch.device] = None, |
| 98 | + verbose=0, |
| 99 | + ): |
| 100 | + super().__init__(node, version, verbose=verbose) |
| 101 | + self.device = device |
| 102 | + self._cache: Dict[Tuple[int, int, int], onnx.ModelProto] = {} |
| 103 | + self.is_cpu = torch.device("cpu") == self.device |
| 104 | + |
| 105 | + def _make_model(self, itype: int, ranka: int, rankb: int) -> onnx.ModelProto: |
| 106 | + shapea = ["a{i}" for i in range(ranka)] |
| 107 | + shapeb = ["b{i}" for i in range(rankb)] |
| 108 | + shapec = ["c{i}" for i in range(max(ranka, rankb))] |
| 109 | + model = oh.make_model( |
| 110 | + oh.make_graph( |
| 111 | + [oh.make_node("MatMul", ["A", "B"], ["C"])], |
| 112 | + "dummy", |
| 113 | + [ |
| 114 | + oh.make_tensor_value_info("A", itype, shapea), |
| 115 | + oh.make_tensor_value_info("B", itype, shapeb), |
| 116 | + ], |
| 117 | + [oh.make_tensor_value_info("C", itype, shapec)], |
| 118 | + ), |
| 119 | + ir_version=9, |
| 120 | + opset_imports=[oh.make_opsetid("", 17)], |
| 121 | + ) |
| 122 | + import onnxruntime |
| 123 | + |
| 124 | + provider = "CPUExecutionProvider" if self.is_cpu else "CUDAExecutionProvider" |
| 125 | + return onnxruntime.InferenceSession(model.SerializeToString(), providers=[provider]) |
| 126 | + |
| 127 | + def run(self, a, b): |
| 128 | + itype = torch_dtype_to_onnx_dtype(a.dtype) |
| 129 | + ranka, rankb = len(a.shape), len(b.shape) |
| 130 | + key = itype, ranka, rankb |
| 131 | + if key not in self._cache: |
| 132 | + self._cache[key] = self._make_model(itype, ranka, rankb) |
| 133 | + sess = self._cache[key] |
| 134 | + feeds = dict(A=a, B=b) |
| 135 | + feeds = {k: v.tensor.detach().cpu().numpy() for k, v in feeds.items()} |
| 136 | + got = sess.run(None, feeds)[0] |
| 137 | + return OpRunTensor(torch.from_numpy(got).to(a.dtype).to(a.device)) |
0 commit comments