Merged
[bugfix][v2.9.0-26.1.0] 修复DVM SiLU BF16精度不一致 #45808
[bugfix][v2.9.0-26.1.0] 修复DVM SiLU BF16精度不一致 #45808
Merged
SorryNaCNAdd on Sep 4
Total: 2 files changed+62-33
@@ -90,6 +90,27 @@ class TestDvmByMlir(TestCase):
90 else:90 else:
91 os.environ["TORCHINDUCTOR_NPU_BACKEND"] = original_backend91 os.environ["TORCHINDUCTOR_NPU_BACKEND"] = original_backend
92 92 
93+ def test_silu_bf16_matches_aclnn_bitwise(self):
94+ def model(grad, x):
95+ return (
96+ torch.ops.aten.silu.default(x),
97+ torch.ops.aten.silu_backward.default(grad, x),
98+ )
99+ 
100+ numel = 257 * 263
101+ x = torch.linspace(-20.0, 20.0, numel, dtype=torch.float32)
102+ grad = torch.linspace(-2.0, 2.0, numel, dtype=torch.float32).cos()
103+ x = x.to(torch.bfloat16).reshape(257, 263).npu()
104+ grad = grad.to(torch.bfloat16).reshape(257, 263).npu()
105+ 
106+ with torch.no_grad():
107+ expect = model(grad, x)
108+ result, codes = self._run_and_get_code_with_dvm(model, grad, x)
109+ 
110+ self.assertTrue(torch.equal(expect[0], result[0]))
111+ self.assertTrue(torch.equal(expect[1], result[1]))
112+ self.assertIn("@dvm.kernel", "\n".join(codes))
113+ 
93 @parametrize("dtype", [torch.float16, torch.float32, torch.bfloat16])114 @parametrize("dtype", [torch.float16, torch.float32, torch.bfloat16])
94 @parametrize("is_dynamic", [True, False])115 @parametrize("is_dynamic", [True, False])
95 def test_basic_partitioning(self, dtype, is_dynamic):116 def test_basic_partitioning(self, dtype, is_dynamic):
@@ -3,6 +3,7 @@ import math
3import torch3import torch
4from torch._decomp import remove_decompositions4from torch._decomp import remove_decompositions
5from torch._inductor import decomposition as inductor_decomp5from torch._inductor import decomposition as inductor_decomp
6+from torch._inductor.decomposition import pw_cast_for_opmath
6 7 
7 8 
8aten = torch.ops.aten9aten = torch.ops.aten
@@ -35,6 +36,8 @@ decomps_to_exclude_npu = [
35 aten.nll_loss_forward,36 aten.nll_loss_forward,
36 aten.reflection_pad2d,37 aten.reflection_pad2d,
37 aten.reflection_pad2d_backward,38 aten.reflection_pad2d_backward,
39+ aten.silu.default,
40+ aten.silu_backward.default,
38 aten.slice.Tensor,41 aten.slice.Tensor,
39 aten.triu,42 aten.triu,
40 aten.upsample_bilinear2d,43 aten.upsample_bilinear2d,
@@ -49,38 +52,33 @@ decomps_to_exclude_npu = [
49 torch.ops.npu.npu_rotary_mul_backward,52 torch.ops.npu.npu_rotary_mul_backward,
50]53]
51 54 
55+cia_decomps_to_exclude_npu = [
56+ aten.silu_backward.default,
57+]
58+ 
52FP32_MIN_V2 = -8.859FP32_MIN_V2 = -8.8
53FP32_MAX_V2 = 8.860FP32_MAX_V2 = 8.8
54DOUBLE_X = 2.061DOUBLE_X = 2.0
55 62 
56 63 
64+@pw_cast_for_opmath
57def tanh(a):65def tanh(a):
58 """66 """
59 y = (exp(2x) - 1) / (exp(2x) + 1)67 y = (exp(2x) - 1) / (exp(2x) + 1)
60 with x clipped to [-8.8, 8.8] in float32 before multiply-by-2.68 with x clipped to [-8.8, 8.8] in float32 before multiply-by-2.
61 """69 """
62- orig_dtype = a.dtype
63- if orig_dtype != torch.float32:
64- a = a.to(torch.float32)
65 x = torch.clamp(a, min=FP32_MIN_V2, max=FP32_MAX_V2)70 x = torch.clamp(a, min=FP32_MIN_V2, max=FP32_MAX_V2)
66 x2 = x * DOUBLE_X71 x2 = x * DOUBLE_X
67 e2x = torch.exp(x2)72 e2x = torch.exp(x2)
68- out = (e2x - 1.0) / (e2x + 1.0)73+ return (e2x - 1.0) / (e2x + 1.0)
69- 
70- if orig_dtype != torch.float32:
71- out = out.to(orig_dtype)
72- return out
73 74 
74 75 
76+@pw_cast_for_opmath
75def gelu(a: torch.Tensor, approximate: str = "none"):77def gelu(a: torch.Tensor, approximate: str = "none"):
76 """78 """
77 y = -sqrt(8/pi) * (x + 0.044715 * x^3)79 y = -sqrt(8/pi) * (x + 0.044715 * x^3)
78 out = x / (1 + exp(y))80 out = x / (1 + exp(y))
79 """81 """
80- orig_dtype = a.dtype
81- if orig_dtype != torch.float32:
82- a = a.to(torch.float32)
83- 
84 M_SQRT2 = math.sqrt(2)82 M_SQRT2 = math.sqrt(2)
85 M_2_SQRTPI = 2.0 / math.sqrt(math.pi)83 M_2_SQRTPI = 2.0 / math.sqrt(math.pi)
86 kBeta = M_SQRT2 * M_2_SQRTPI84 kBeta = M_SQRT2 * M_2_SQRTPI
@@ -89,18 +87,11 @@ def gelu(a: torch.Tensor, approximate: str = "none"):
89 a_cube = a * a * a87 a_cube = a * a * a
90 inner = a + kKappa * a_cube88 inner = a + kKappa * a_cube
91 y = -kBeta * inner89 y = -kBeta * inner
92- out = a / (1.0 + torch.exp(y))90+ return a / (1.0 + torch.exp(y))
93- 
94- if orig_dtype != torch.float32:
95- out = out.to(orig_dtype)
96- return out
97 91 
98 92 
93+@pw_cast_for_opmath
99def gelu_backward(grad, self, approximate: str = "none"):94def gelu_backward(grad, self, approximate: str = "none"):
100- orig_dtype = grad.dtype
101- if orig_dtype != torch.float32:
102- grad = grad.to(torch.float32)
103- self = self.to(torch.float32)
104 M_SQRT2 = math.sqrt(2)95 M_SQRT2 = math.sqrt(2)
105 M_2_SQRTPI = 2.0 / math.sqrt(math.pi)96 M_2_SQRTPI = 2.0 / math.sqrt(math.pi)
106 kBeta = M_SQRT2 * M_2_SQRTPI * 0.597 kBeta = M_SQRT2 * M_2_SQRTPI * 0.5
@@ -118,21 +109,35 @@ def gelu_backward(grad, self, approximate: str = "none"):
118 tanh_derivative = (tanh_inner * tanh_inner) * -1.0 + 1.0109 tanh_derivative = (tanh_inner * tanh_inner) * -1.0 + 1.0
119 inner_derivative = kBeta * (1.0 + 3.0 * kKappa * x_sq)110 inner_derivative = kBeta * (1.0 + 3.0 * kKappa * x_sq)
120 right_derivative = left * tanh_derivative * inner_derivative111 right_derivative = left * tanh_derivative * inner_derivative
121- out = grad * (left_derivative + right_derivative)112+ return grad * (left_derivative + right_derivative)
122- 
123- if orig_dtype != torch.float32:
124- out = out.to(orig_dtype)
125- return out
126 113 
127 114 
115+@pw_cast_for_opmath
128def sigmoid(a: torch.Tensor) -> torch.Tensor:116def sigmoid(a: torch.Tensor) -> torch.Tensor:
129- orig_dtype = a.dtype117+ return aten.reciprocal(1.0 + torch.exp(torch.neg(a)))
130- if orig_dtype != torch.float32:118+ 
131- a = a.to(torch.float32)119+ 
132- out = 1 / (1.0 + torch.exp(torch.neg(a)))120+@pw_cast_for_opmath
133- if orig_dtype != torch.float32:121+def silu(a: torch.Tensor) -> torch.Tensor:
134- out = out.to(orig_dtype)122+ return a / (1.0 + torch.exp(torch.neg(a)))
135- return out123+ 
124+ 
125+@pw_cast_for_opmath
126+def silu_backward(grad: torch.Tensor, self: torch.Tensor) -> torch.Tensor:
127+ sigmoid = aten.reciprocal(1.0 + torch.exp(torch.neg(self)))
128+ return grad * (sigmoid * (1.0 + (1.0 - sigmoid) * self))
129+ 
130+ 
131+def _disable_cia_decompositions():
132+ """Keep FunctionalTensorMode from expanding ops before DVM decompositions."""
133+ dispatch_key = torch._C.DispatchKey.CompositeImplicitAutograd
134+ 
135+ def preserve_for_explicit_decomposition(*_args, **_kwargs):
136+ return NotImplemented
137+ 
138+ for op in cia_decomps_to_exclude_npu:
139+ op.py_kernels.pop(dispatch_key, None)
140+ op.py_impl(dispatch_key)(preserve_for_explicit_decomposition)
136 141 
137 142 
138_dvm_inductor_decomp_patched = False143_dvm_inductor_decomp_patched = False
@@ -167,8 +172,11 @@ def patch_decomp():
167 global _dvm_inductor_decomp_patched172 global _dvm_inductor_decomp_patched
168 if _dvm_inductor_decomp_patched:173 if _dvm_inductor_decomp_patched:
169 return174 return
175+ _disable_cia_decompositions()
170 remove_decompositions(inductor_decomp.decompositions, decomps_to_exclude_npu)176 remove_decompositions(inductor_decomp.decompositions, decomps_to_exclude_npu)
171 _register_inductor_decomposition_safe([aten.sigmoid.default], sigmoid)177 _register_inductor_decomposition_safe([aten.sigmoid.default], sigmoid)
178+ _register_inductor_decomposition_safe([aten.silu.default], silu)
179+ _register_inductor_decomposition_safe([aten.silu_backward.default], silu_backward)
172 _register_inductor_decomposition_safe([aten.gelu_backward.default], gelu_backward)180 _register_inductor_decomposition_safe([aten.gelu_backward.default], gelu_backward)
173 _register_inductor_decomposition_safe([aten.gelu.default], gelu)181 _register_inductor_decomposition_safe([aten.gelu.default], gelu)
174 _register_inductor_decomposition_safe([aten.tanh.default], tanh)182 _register_inductor_decomposition_safe([aten.tanh.default], tanh)