diff --git a/python/tvm/relax/frontend/onnx/onnx_frontend.py b/python/tvm/relax/frontend/onnx/onnx_frontend.py index 33a4392d25e0..b698d928e4ab 100644 --- a/python/tvm/relax/frontend/onnx/onnx_frontend.py +++ b/python/tvm/relax/frontend/onnx/onnx_frontend.py @@ -5620,6 +5620,135 @@ def _impl_v1(cls, bb, inputs, attr, params): return relax.Tuple([output, placeholder, placeholder]) +class SimplifiedLayerNormalization(OnnxOpConverter): + """Converts a microsoft contrib SimplifiedLayerNormalization node into a Relax expression.""" + + @classmethod + def _impl_v1(cls, bb, inputs, attr, params): + data = inputs[0] + scale = inputs[1] + bias = inputs[2] if len(inputs) > 2 and inputs[2] is not None else None + axis = attr.get("axis", -1) + epsilon = attr.get("epsilon", 1e-05) + stash_type = attr.get("stash_type", 1) + + if stash_type != 1: + raise ValueError( + f"SimplifiedLayerNormalization currently only supports stash_type=1 (FLOAT), " + f"but got stash_type={stash_type}." + ) + + ndim = _get_known_tensor_rank(data) + if ndim is None: + raise ValueError("SimplifiedLayerNormalization requires a statically known input rank.") + axis = _normalize_constant_axes([axis], ndim, "SimplifiedLayerNormalization")[0] + axes = list(range(axis, ndim)) + + input_dtype = data.ty.dtype.dtype + scale_dtype = scale.ty.dtype.dtype + + # Broadcast scale to the normalized shape if necessary + decompose_scale = True + if isinstance(data.ty.shape, relax.ShapeExpr) and isinstance( + scale.ty.shape, relax.ShapeExpr + ): + normalized_shape = relax.ShapeExpr(data.ty.shape.values[axis:]) + if tvm_ffi.structural_equal(scale.ty.shape, normalized_shape): + decompose_scale = False + elif len(scale.ty.shape) <= len(normalized_shape): + compute_broadcast_shape(scale.ty.shape.values, normalized_shape.values) + scale = relax.op.broadcast_to(scale, normalized_shape) + decompose_scale = False + else: + compute_broadcast_shape(scale.ty.shape.values, data.ty.shape.values) + + # stash_type == 1 computes in float32 + compute_dtype = "float32" + + data_compute = ( + data if input_dtype == compute_dtype else relax.op.astype(data, compute_dtype) + ) + scale_compute = ( + scale if scale_dtype == compute_dtype else relax.op.astype(scale, compute_dtype) + ) + + num_outputs = attr.get("tvm_custom", {}).get("num_outputs", 1) + full_reduce = len(axes) == ndim + use_decomposed = full_reduce or decompose_scale or num_outputs > 1 + + if use_decomposed: + mean_square = relax.op.mean( + relax.op.multiply(data_compute, data_compute), axis=axes, keepdims=True + ) + inv_std = relax.op.rsqrt( + relax.op.add(mean_square, relax.const(epsilon, dtype=compute_dtype)) + ) + # Decompose to avoid the TOPI rms_norm 0-dim indexing bug + output = relax.op.multiply(relax.op.multiply(data_compute, inv_std), scale_compute) + else: + output = relax.op.nn.rms_norm(data_compute, scale_compute, axes, epsilon) + + if bias is not None: + bias_compute = ( + bias + if bias.ty.dtype.dtype == compute_dtype + else relax.op.astype(bias, compute_dtype) + ) + output = relax.op.add(output, bias_compute) + + if compute_dtype != scale_dtype: + output = relax.op.astype(output, scale_dtype) + + if num_outputs == 1: + return output + + return relax.Tuple([output, inv_std]) + + +class SkipSimplifiedLayerNormalization(OnnxOpConverter): + """Converts a microsoft contrib SkipSimplifiedLayerNormalization node into a Relax expression.""" + + @classmethod + def _impl_v1(cls, bb, inputs, attr, params): + data = inputs[0] + skip = inputs[1] + gamma = inputs[2] + bias = inputs[3] if len(inputs) > 3 and inputs[3] is not None else None + + epsilon = attr.get("epsilon", 1e-12) + num_outputs = attr.get("tvm_custom", {}).get("num_outputs", 3) + + input_dtype = data.ty.dtype.dtype + low_precision = input_dtype in ("float16", "bfloat16") + if low_precision: + data = relax.op.astype(data, "float32") + skip = relax.op.astype(skip, "float32") + gamma = relax.op.astype(gamma, "float32") + if bias is not None: + bias = relax.op.astype(bias, "float32") + + data = relax.op.add(data, skip) + if bias is not None: + data = relax.op.add(data, bias) + + output = relax.op.nn.rms_norm(data, gamma, axes=-1, epsilon=epsilon) + + if low_precision: + output = relax.op.astype(output, input_dtype) + if num_outputs > 3: + data = relax.op.astype(data, input_dtype) + + placeholder = relax.const(0, dtype="float32") + + if num_outputs > 3: + # Output 4 - input_skip_bias_sum + return relax.Tuple([output, placeholder, placeholder, data]) + if num_outputs == 1: + return output + + return relax.Tuple([output, placeholder, placeholder]) + + class EmbedLayerNormalization(OnnxOpConverter): """Converts a microsoft contrib EmbedLayerNormalization node into a Relax expression.""" @@ -6898,8 +7027,10 @@ def _get_convert_map(): "BatchNormalization": BatchNormalization, "LayerNormalization": LayerNormalization, "RMSNormalization": RMSNormalization, + "SimplifiedLayerNormalization": SimplifiedLayerNormalization, "GroupNormalization": GroupNormalization, "SkipLayerNormalization": SkipLayerNormalization, + "SkipSimplifiedLayerNormalization": SkipSimplifiedLayerNormalization, "EmbedLayerNormalization": EmbedLayerNormalization, "InstanceNormalization": InstanceNormalization, "MeanVarianceNormalization": MeanVarianceNormalization, diff --git a/tests/python/relax/test_frontend_onnx.py b/tests/python/relax/test_frontend_onnx.py index d9a4037baa87..3d9987eb67bc 100644 --- a/tests/python/relax/test_frontend_onnx.py +++ b/tests/python/relax/test_frontend_onnx.py @@ -6548,6 +6548,234 @@ def test_rms_norm(): check_correctness(model, opset=23, rtol=1e-2, atol=1e-2) +def _make_simplified_layer_norm_expected_ir( + input_shape: list | tuple, + scale_shape: list | tuple, + axis: int = -1, + epsilon: float = 1e-5, + dtype: str = "float32", +): + # Convert string dimensions to shared T.dynamic symbolic variables + var_dict = {} + + def get_dim(d): + if not isinstance(d, str): + return d + if d not in var_dict: + var_dict[d] = T.dynamic(d, "int64") + return var_dict[d] + + input_shape = tuple(get_dim(d) for d in input_shape) + scale_shape = tuple(get_dim(d) for d in scale_shape) + + ndim = len(input_shape) + norm_axis = axis if axis >= 0 else ndim + axis + norm_shape = tuple(input_shape[norm_axis:]) + red_axis = list(range(norm_axis, ndim)) + eps_val = float(np.float32(epsilon)) + + is_broadcast = scale_shape != norm_shape + + if dtype == "float32": + if is_broadcast: + + @I.ir_module + class ExpectedFP32Broadcast: + @R.function + def main( + input: R.Tensor(input_shape, dtype="float32"), + scale: R.Tensor(scale_shape, dtype="float32"), + ) -> R.Tensor(input_shape, dtype="float32"): + R.func_attr({"num_input": 2}) + with R.dataflow(): + lv: R.Tensor(norm_shape, dtype="float32") = R.broadcast_to( + scale, norm_shape + ) + gv: R.Tensor(input_shape, dtype="float32") = R.nn.rms_norm( + input, lv, axes=red_axis, epsilon=eps_val + ) + R.output(gv) + return gv + + return ExpectedFP32Broadcast + + else: + + @I.ir_module + class ExpectedFP32: + @R.function + def main( + input: R.Tensor(input_shape, dtype="float32"), + scale: R.Tensor(scale_shape, dtype="float32"), + ) -> R.Tensor(input_shape, dtype="float32"): + R.func_attr({"num_input": 2}) + with R.dataflow(): + gv: R.Tensor(input_shape, dtype="float32") = R.nn.rms_norm( + input, scale, axes=red_axis, epsilon=eps_val + ) + R.output(gv) + return gv + + return ExpectedFP32 + + @I.ir_module + class ExpectedOtherDtype: + @R.function + def main( + input: R.Tensor(input_shape, dtype=dtype), + scale: R.Tensor(scale_shape, dtype=dtype), + ) -> R.Tensor(input_shape, dtype=dtype): + R.func_attr({"num_input": 2}) + with R.dataflow(): + lv: R.Tensor(input_shape, dtype="float32") = R.astype(input, dtype="float32") + lv1: R.Tensor(scale_shape, dtype="float32") = R.astype(scale, dtype="float32") + lv2: R.Tensor(input_shape, dtype="float32") = R.nn.rms_norm( + lv, lv1, axes=red_axis, epsilon=eps_val + ) + gv: R.Tensor(input_shape, dtype=dtype) = R.astype(lv2, dtype=dtype) + R.output(gv) + return gv + + return ExpectedOtherDtype + + +def test_simplified_layer_norm(): + def verify_simplified_layer_norm( + shape: list, + axis: int = -1, + epsilon: float = 1e-5, + dtype: str = "float32", + scale_shape: list | None = None, + ): + ndim = len(shape) + norm_axis = axis if axis >= 0 else ndim + axis + scale_shape = scale_shape if scale_shape is not None else shape[norm_axis:] + proto_dtype = TensorProto.FLOAT if dtype == "float32" else TensorProto.FLOAT16 + + node = helper.make_node( + "SimplifiedLayerNormalization", + inputs=["input", "scale"], + outputs=["y"], + domain="", + axis=axis, + epsilon=epsilon, + ) + graph = helper.make_graph( + [node], + "simplified_layer_norm_test", + inputs=[ + helper.make_tensor_value_info("input", proto_dtype, list(shape)), + helper.make_tensor_value_info("scale", proto_dtype, list(scale_shape)), + ], + outputs=[helper.make_tensor_value_info("y", proto_dtype, list(shape))], + ) + model = helper.make_model( + graph, + opset_imports=[ + helper.make_opsetid("", 14), + helper.make_opsetid("com.microsoft", 1), + ], + ) + + tvm_model = from_onnx(model, keep_params_in_input=True) + expected = _make_simplified_layer_norm_expected_ir( + shape, scale_shape, axis=axis, epsilon=epsilon, dtype=dtype + ) + tvm_tirx.ir.assert_structural_equal(tvm_model, expected) + + with pytest.raises(ValueError, match="Cannot broadcast symbolic dimension"): + verify_simplified_layer_norm([2, 32], -1, scale_shape=["s"]) + + # Static input test cases + verify_simplified_layer_norm([2, 8, 32], -1, 1e-5, "float32") + verify_simplified_layer_norm([4, 16], 1, 1e-6, "float32") + verify_simplified_layer_norm([1, 3, 224, 224], -1, 1e-7, "float16") + verify_simplified_layer_norm([1, 3, 16, 16, 256], 2, 1e-9, "float32") + verify_simplified_layer_norm([2, 3, 4], 1, scale_shape=[4]) + verify_simplified_layer_norm([2, 32], -1, scale_shape=[1]) + verify_simplified_layer_norm([2, 32], -1, scale_shape=[32]) + # Dynamic input test cases + verify_simplified_layer_norm(["batch", "seq_len", 48], -1, 1e-8, "float32") + verify_simplified_layer_norm(["batch", "dim_1", "dim_2", 512], 1, 1e-6, "float32") + verify_simplified_layer_norm(["n", 8, 32, 1, 1], -1, 1e-12, "float16") + + +def _verify_simplified_layer_norm_execution(shape, axis, in_dtype, scale_dtype, num_outputs=1): + proto_in = TensorProto.FLOAT16 if in_dtype == "float16" else TensorProto.FLOAT + proto_scale = TensorProto.FLOAT16 if scale_dtype == "float16" else TensorProto.FLOAT + + norm_axis = axis if axis >= 0 else len(shape) + axis + scale_shape = shape[norm_axis:] + inv_std_shape = list(shape[:norm_axis]) + [1] * (len(shape) - norm_axis) + + output_names = ["y"] if num_outputs == 1 else ["y", "inv_std_var"] + node = helper.make_node( + "SimplifiedLayerNormalization", + inputs=["x", "scale"], + outputs=output_names, + domain="", + axis=axis, + epsilon=1e-5, + ) + graph_outputs = [helper.make_tensor_value_info("y", proto_scale, shape)] + if num_outputs > 1: + graph_outputs.append( + helper.make_tensor_value_info("inv_std_var", TensorProto.FLOAT, inv_std_shape) + ) + + graph = helper.make_graph( + [node], + "sln_exec_test", + inputs=[ + helper.make_tensor_value_info("x", proto_in, shape), + helper.make_tensor_value_info("scale", proto_scale, scale_shape), + ], + outputs=graph_outputs, + ) + model = helper.make_model( + graph, opset_imports=[helper.make_opsetid("", 14), helper.make_opsetid("com.microsoft", 1)] + ) + + rg = np.random.default_rng(0) + x = rg.standard_normal(shape).astype(in_dtype) + scale = rg.standard_normal(scale_shape).astype(scale_dtype) + + red_axes = tuple(range(norm_axis, len(shape))) + mean_sq = np.mean(x.astype(np.float32) ** 2, axis=red_axes, keepdims=True) + inv_std = 1.0 / np.sqrt(mean_sq + 1e-5) + expected_y = ((x.astype(np.float32) * inv_std) * scale.astype(np.float32)).astype(scale_dtype) + + tvm_out = run_in_tvm(model, inputs={"x": x, "scale": scale}) + + if num_outputs == 1: + assert tvm_out.numpy().dtype == np.dtype(scale_dtype) + tvm_tirx.testing.assert_allclose(tvm_out.numpy(), expected_y, rtol=1e-3, atol=1e-3) + else: + out_y, out_inv_std = tvm_out + assert out_y.numpy().dtype == np.dtype(scale_dtype) + tvm_tirx.testing.assert_allclose(out_y.numpy(), expected_y, rtol=1e-3, atol=1e-3) + + assert out_inv_std.numpy().shape == tuple(inv_std_shape) + assert out_inv_std.numpy().dtype == np.dtype(np.float32) + tvm_tirx.testing.assert_allclose(out_inv_std.numpy(), inv_std, rtol=1e-5, atol=1e-5) + + +@pytest.mark.parametrize("shape, axis", [([2, 8, 32], -1), ([2, 8, 32], 1), ([4, 16], 0)]) +@pytest.mark.parametrize("in_dtype", ["float32", "float16"]) +@pytest.mark.parametrize("scale_dtype", ["float32", "float16"]) +def test_simplified_layer_norm_output_dtype(shape, axis, in_dtype, scale_dtype): + """Verify 1-output SLN: output matches scale dtype, and all-axes decomposition legalizes.""" + _verify_simplified_layer_norm_execution(shape, axis, in_dtype, scale_dtype, num_outputs=1) + + +@pytest.mark.parametrize("shape, axis", [([2, 8, 32], -1), ([2, 8, 32], 1), ([4, 16], 0)]) +@pytest.mark.parametrize("in_dtype", ["float32", "float16"]) +@pytest.mark.parametrize("scale_dtype", ["float32", "float16"]) +def test_simplified_layer_norm_inv_std_output(shape, axis, in_dtype, scale_dtype): + """Verify 2-output SLN: importer accepts 2 outputs, and inv_std_var shape and values match.""" + _verify_simplified_layer_norm_execution(shape, axis, in_dtype, scale_dtype, num_outputs=2) + + def _make_group_norm_expected_ir( input_shape: list[int], scale_shape: list[int], @@ -6890,6 +7118,208 @@ def main( verify_skiplayernormalization(input_array, skip, gamma, beta, bias) +def _make_skip_simplified_layer_norm_expected_ir( + input_shape: list | tuple, + gamma_shape: list | tuple, + has_bias: bool = False, + epsilon: float = 1e-5, + dtype: str = "float32", +): + # Convert string dimensions to shared T.dynamic symbolic variables + var_dict = {} + + def get_dim(d): + if not isinstance(d, str): + return d + if d not in var_dict: + var_dict[d] = T.dynamic(d, "int64") + return var_dict[d] + + input_shape = tuple(get_dim(d) for d in input_shape) + gamma_shape = tuple(get_dim(d) for d in gamma_shape) + eps_val = float(np.float32(epsilon)) + + if not has_bias: + + @I.ir_module + class ExpectedNoBias: + @R.function + def main( + input: R.Tensor(input_shape, dtype=dtype), + skip: R.Tensor(input_shape, dtype=dtype), + gamma: R.Tensor(gamma_shape, dtype=dtype), + ) -> R.Tensor(input_shape, dtype=dtype): + R.func_attr({"num_input": 3}) + with R.dataflow(): + lv: R.Tensor(input_shape, dtype=dtype) = R.add(input, skip) + lv1: R.Tensor(input_shape, dtype=dtype) = R.nn.rms_norm( + lv, gamma, axes=[-1], epsilon=eps_val + ) + gv: R.Tensor(input_shape, dtype=dtype) = lv1 + R.output(gv) + return gv + + return ExpectedNoBias + + @I.ir_module + class ExpectedWithBias: + @R.function + def main( + input: R.Tensor(input_shape, dtype=dtype), + skip: R.Tensor(input_shape, dtype=dtype), + gamma: R.Tensor(gamma_shape, dtype=dtype), + bias: R.Tensor(gamma_shape, dtype=dtype), + ) -> R.Tensor(input_shape, dtype=dtype): + R.func_attr({"num_input": 4}) + with R.dataflow(): + lv: R.Tensor(input_shape, dtype=dtype) = R.add(input, skip) + lv1: R.Tensor(input_shape, dtype=dtype) = R.add(lv, bias) + lv2: R.Tensor(input_shape, dtype=dtype) = R.nn.rms_norm( + lv1, gamma, axes=[-1], epsilon=eps_val + ) + gv: R.Tensor(input_shape, dtype=dtype) = lv2 + R.output(gv) + return gv + + return ExpectedWithBias + + +def test_skipsimplifiedlayernormalization(): + def verify_skipsimplifiedlayernormalization( + shape: list, + has_bias: bool = False, + epsilon: float = 1e-5, + dtype: str = "float32", + ): + hidden_size = shape[-1] + gamma_shape = [hidden_size] + proto_dtype = TensorProto.FLOAT if dtype == "float32" else TensorProto.FLOAT16 + + input_names = ["input", "skip", "gamma"] + inputs = [ + helper.make_tensor_value_info("input", proto_dtype, list(shape)), + helper.make_tensor_value_info("skip", proto_dtype, list(shape)), + helper.make_tensor_value_info("gamma", proto_dtype, list(gamma_shape)), + ] + + if has_bias: + input_names.append("bias") + inputs.append(helper.make_tensor_value_info("bias", proto_dtype, list(gamma_shape))) + + node = helper.make_node( + "SkipSimplifiedLayerNormalization", + inputs=input_names, + outputs=["output", "mean", "inv_std_dev"], + domain="com.microsoft", + epsilon=epsilon, + ) + + graph = helper.make_graph( + [node], + "skip_simplified_layer_norm_test", + inputs=inputs, + outputs=[ + helper.make_tensor_value_info("output", proto_dtype, list(shape)), + ], + ) + model = helper.make_model( + graph, + opset_imports=[ + helper.make_opsetid("", 14), + helper.make_opsetid("com.microsoft", 1), + ], + ) + + tvm_model = from_onnx(model, keep_params_in_input=True) + expected = _make_skip_simplified_layer_norm_expected_ir( + shape, gamma_shape, has_bias=has_bias, epsilon=epsilon, dtype=dtype + ) + tvm_tirx.ir.assert_structural_equal(tvm_model, expected) + + verify_skipsimplifiedlayernormalization(shape=[2, 8, 32, 128], has_bias=False, epsilon=1e-5) + verify_skipsimplifiedlayernormalization(shape=[1, 3, 224], has_bias=True, epsilon=1e-5) + verify_skipsimplifiedlayernormalization(shape=[4, 16, 64], has_bias=True, epsilon=1e-6) + + verify_skipsimplifiedlayernormalization(shape=["batch", "seq_len", 128], has_bias=False) + verify_skipsimplifiedlayernormalization(shape=["batch", "seq_len", 256], has_bias=True) + verify_skipsimplifiedlayernormalization(shape=["batch", "hidden_dim"], has_bias=True) + + +def _verify_skip_simplified_layer_norm_execution(shape, dtype, has_bias, with_residual_output): + proto = TensorProto.FLOAT16 if dtype == "float16" else TensorProto.FLOAT + epsilon = 1e-5 + gamma_shape = [shape[-1]] + + input_names = ["input", "skip", "gamma"] + (["bias"] if has_bias else []) + output_names = ["output", "", "", "input_skip_bias_sum"] if with_residual_output else ["output"] + + node = helper.make_node( + "SkipSimplifiedLayerNormalization", + inputs=input_names, + outputs=output_names, + domain="com.microsoft", + epsilon=epsilon, + ) + + graph_inputs = [ + helper.make_tensor_value_info("input", proto, shape), + helper.make_tensor_value_info("skip", proto, shape), + helper.make_tensor_value_info("gamma", proto, gamma_shape), + ] + if has_bias: + graph_inputs.append(helper.make_tensor_value_info("bias", proto, gamma_shape)) + + graph_outputs = [helper.make_tensor_value_info("output", proto, shape)] + if with_residual_output: + graph_outputs.append(helper.make_tensor_value_info("input_skip_bias_sum", proto, shape)) + + graph = helper.make_graph( + [node], "skip_sln_exec_test", inputs=graph_inputs, outputs=graph_outputs + ) + model = helper.make_model( + graph, opset_imports=[helper.make_opsetid("", 14), helper.make_opsetid("com.microsoft", 1)] + ) + + rg = np.random.default_rng(0) + feeds = { + "input": rg.standard_normal(shape).astype(dtype), + "skip": rg.standard_normal(shape).astype(dtype), + "gamma": rg.standard_normal(gamma_shape).astype(dtype), + } + if has_bias: + feeds["bias"] = rg.standard_normal(gamma_shape).astype(dtype) + + # accumulate in float32, cast back to the input dtype + summed = feeds["input"].astype(np.float32) + feeds["skip"].astype(np.float32) + if has_bias: + summed = summed + feeds["bias"].astype(np.float32) + inv_std = 1.0 / np.sqrt(np.mean(summed**2, axis=-1, keepdims=True) + epsilon) + expected_out = (summed * inv_std * feeds["gamma"].astype(np.float32)).astype(dtype) + expected_sum = summed.astype(dtype) + + rtol, atol = (1e-3, 1e-3) if dtype == "float16" else (1e-5, 1e-5) + tvm_out = run_in_tvm(model, inputs=feeds) + + if with_residual_output: + out, residual = tvm_out + assert residual.numpy().shape == tuple(shape) + assert residual.numpy().dtype == np.dtype(dtype) + tvm_tirx.testing.assert_allclose(residual.numpy(), expected_sum, rtol=rtol, atol=atol) + else: + out = tvm_out + + assert out.numpy().shape == tuple(shape) + assert out.numpy().dtype == np.dtype(dtype) + tvm_tirx.testing.assert_allclose(out.numpy(), expected_out, rtol=rtol, atol=atol) + + +@pytest.mark.parametrize("dtype", ["float32", "float16"]) +@pytest.mark.parametrize("has_bias", [False, True]) +@pytest.mark.parametrize("with_residual_output", [False, True]) +def test_skip_simplified_layer_norm_execution(dtype, has_bias, with_residual_output): + _verify_skip_simplified_layer_norm_execution([2, 8, 32], dtype, has_bias, with_residual_output) + + def test_embedlayernormalization(): def verify_embedlayernormalization( input_ids,