From ea3ff03881a682a94b01e26508a93c3f1067b7b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Fri, 27 Nov 2026 13:32:56 +0100 Subject: [PATCH 1/2] Vulkan: keep q4gsw embedding and linear in the model dtype embedding_q4gsw and linear_q4gsw always produced fp32, and the fused embedding took the scales' dtype, so fp32 scales on an fp16 model made the retraced graph fp32 and failed SDPA's dtype checks. Cast back to the replaced op's dtype. --- backends/vulkan/custom_ops_lib.py | 13 +++++- .../vulkan/patterns/quantized_embedding.py | 36 +++++++++++++-- backends/vulkan/test/test_vulkan_passes.py | 45 +++++++++++++++++++ 3 files changed, 88 insertions(+), 6 deletions(-) diff --git a/backends/vulkan/custom_ops_lib.py b/backends/vulkan/custom_ops_lib.py index 31e9872b060..01c8334f250 100644 --- a/backends/vulkan/custom_ops_lib.py +++ b/backends/vulkan/custom_ops_lib.py @@ -317,7 +317,14 @@ def linear_q4gsw( weight_zeros = torch.zeros_like(weight_scales, dtype=torch.int32) weights = torch.ops.torchao.dequantize_affine( - weights, [1, group_size], weight_scales, weight_zeros, torch.int8, -8, 7 + weights, + [1, group_size], + weight_scales, + weight_zeros, + torch.int8, + -8, + 7, + output_dtype=x.dtype, ) out = torch.nn.functional.linear(x, weights, bias) @@ -1187,7 +1194,9 @@ def embedding_q4gsw_impl( unpacked_groups = unpacked.reshape(weight.shape[0], num_groups, group_size) dequantized = unpacked_groups.float() * scales.float() - dequantized = dequantized.reshape(weight.shape[0], -1) + # Output in the scales' dtype, like the fused embedding: always returning + # fp32 makes any retrace re-infer fp32 downstream of an fp16 model. + dequantized = dequantized.reshape(weight.shape[0], -1).to(weight_scales.dtype) return torch.nn.functional.embedding(indices, dequantized) diff --git a/backends/vulkan/patterns/quantized_embedding.py b/backends/vulkan/patterns/quantized_embedding.py index dbd0d6fbf98..77393df9f68 100644 --- a/backends/vulkan/patterns/quantized_embedding.py +++ b/backends/vulkan/patterns/quantized_embedding.py @@ -21,6 +21,36 @@ from executorch.exir.dialects._ops import ops as exir_ops +def _replace_anchor_with_embedding( + graph_module: torch.fx.GraphModule, + match: PatternMatch, + embedding_q4gsw_node: torch.fx.Node, +) -> None: + """ + et_vk.embedding_q4gsw outputs the dtype of its scales. When the replaced + op produced another dtype (e.g. fp32 scales feeding an fp16 model), cast + back to it explicitly, so that the graph's dtypes survive a retrace. + """ + out_val = match.anchor_node.meta["val"] + scales_val = match.scales_node.meta.get("val") + emb_dtype = scales_val.dtype if scales_val is not None else out_val.dtype + embedding_q4gsw_node.meta["val"] = out_val.to(emb_dtype) + result = embedding_q4gsw_node + if emb_dtype != out_val.dtype: + with graph_module.graph.inserting_after(embedding_q4gsw_node): + result = graph_module.graph.create_node( + "call_function", + exir_ops.edge.dim_order_ops._to_dim_order_copy.default, + args=(embedding_q4gsw_node,), + kwargs={ + "dtype": out_val.dtype, + "dim_order": list(range(out_val.dim())), + }, + ) + result.meta["val"] = out_val + match.anchor_node.replace_all_uses_with(result) + + embedding_4bit_target = exir_ops.edge.quantized_decomposed.embedding_4bit.dtype embedding_target = exir_ops.edge.aten.embedding.default torchao_dequantize_affine_target = exir_ops.edge.torchao.dequantize_affine.default @@ -154,8 +184,7 @@ def replace_quantized_embedding_patterns( ), ) - embedding_q4gsw_node.meta["val"] = match.anchor_node.meta["val"] - match.anchor_node.replace_all_uses_with(embedding_q4gsw_node) + _replace_anchor_with_embedding(graph_module, match, embedding_q4gsw_node) class TorchAOQuantizedEmbeddingMatch(PatternMatch): @@ -338,5 +367,4 @@ def replace_torchao_quantized_embedding_patterns( ), ) - embedding_q4gsw_node.meta["val"] = match.anchor_node.meta["val"] - match.anchor_node.replace_all_uses_with(embedding_q4gsw_node) + _replace_anchor_with_embedding(graph_module, match, embedding_q4gsw_node) diff --git a/backends/vulkan/test/test_vulkan_passes.py b/backends/vulkan/test/test_vulkan_passes.py index 36e06c89ceb..5a4ab93dfce 100644 --- a/backends/vulkan/test/test_vulkan_passes.py +++ b/backends/vulkan/test/test_vulkan_passes.py @@ -845,6 +845,51 @@ def forward(self, indices): self.assertEqual(fused_node.args[2], embed_dim) self.assertEqual(tuple(fused_node.args[1].meta["val"].shape), (vocab_size,)) + def test_fuse_quantized_embedding_keeps_output_dtype(self): + import executorch.backends.vulkan.custom_ops_lib # noqa: F401 + + vocab_size = 64 + embed_dim = 128 + + class Fp16QuantizedEmbedding(torch.nn.Module): + def __init__(self): + super().__init__() + self.register_buffer( + "weight", + torch.zeros((vocab_size, embed_dim // 2), dtype=torch.uint8), + ) + self.register_buffer( + "scales", torch.ones(vocab_size, dtype=torch.float32) + ) + + def forward(self, indices): + return torch.ops.quantized_decomposed.embedding_4bit.dtype( + self.weight, + self.scales, + None, + -8, + 7, + indices, + dtype=torch.float16, + ) + + sample_inputs = (torch.tensor([[0, 1, 2]], dtype=torch.long),) + program = torch.export.export( + Fp16QuantizedEmbedding(), sample_inputs, strict=True + ) + edge_program = to_edge( + program, + compile_config=EdgeCompileConfig(_check_ir_validity=False), + ) + ep = edge_program._edge_programs["forward"] + fuse_pass = FusePatternsPass() + fuse_pass._exported_program = ep + + fuse_pass.call(ep.graph_module) + + self.assertEqual(op_node_count(ep.graph_module, "embedding_q4gsw.default"), 1) + self.assertEqual(ep.module()(*sample_inputs).dtype, torch.float16) + def test_conv1d_as_conv2d_rewrites_eligible_conv(self): # Output equality cannot show this: an unrewritten conv1d computes the # same numbers. What distinguishes the two is the rank the convolution From 68284249525c253710efc409d223bca40af2b727 Mon Sep 17 00:00:00 2001 From: Mateusz Sluszniak Date: Thu, 3 Dec 2026 10:13:25 +0100 Subject: [PATCH 2/2] Vulkan: test fp16 activations through the quantized linear reference ops Cover linear_q4gsw and linear_dq8ca_q4gsw with fp16 and fp32 scales, and give linear_q8ta_q8csw and the q4gsw bias the same activation-dtype cast. --- backends/vulkan/custom_ops_lib.py | 9 ++-- .../vulkan/patterns/quantized_embedding.py | 2 + backends/vulkan/test/test_vulkan_passes.py | 43 +++++++++++++++++++ 3 files changed, 50 insertions(+), 4 deletions(-) diff --git a/backends/vulkan/custom_ops_lib.py b/backends/vulkan/custom_ops_lib.py index 01c8334f250..6d9476a6a4b 100644 --- a/backends/vulkan/custom_ops_lib.py +++ b/backends/vulkan/custom_ops_lib.py @@ -313,7 +313,7 @@ def linear_q4gsw( out_channels = weights.shape[0] weight_scales = weight_scales.transpose(0, 1)[:out_channels] if bias is not None: - bias = bias[:out_channels] + bias = bias[:out_channels].to(x.dtype) weight_zeros = torch.zeros_like(weight_scales, dtype=torch.int32) weights = torch.ops.torchao.dequantize_affine( @@ -459,12 +459,13 @@ def linear_q8ta_q8csw( -127, 127, torch.int8, + out_dtype=x.dtype, ) # Perform linear operation out = torch.nn.functional.linear(x, weights) if bias is not None: - out = out + bias + out = out + bias.to(x.dtype) return out @@ -1194,8 +1195,8 @@ def embedding_q4gsw_impl( unpacked_groups = unpacked.reshape(weight.shape[0], num_groups, group_size) dequantized = unpacked_groups.float() * scales.float() - # Output in the scales' dtype, like the fused embedding: always returning - # fp32 makes any retrace re-infer fp32 downstream of an fp16 model. + # Output in the scales' dtype; the fusion pattern casts to the model dtype + # when they differ. dequantized = dequantized.reshape(weight.shape[0], -1).to(weight_scales.dtype) return torch.nn.functional.embedding(indices, dequantized) diff --git a/backends/vulkan/patterns/quantized_embedding.py b/backends/vulkan/patterns/quantized_embedding.py index 77393df9f68..5a7b245fa5e 100644 --- a/backends/vulkan/patterns/quantized_embedding.py +++ b/backends/vulkan/patterns/quantized_embedding.py @@ -30,6 +30,8 @@ def _replace_anchor_with_embedding( et_vk.embedding_q4gsw outputs the dtype of its scales. When the replaced op produced another dtype (e.g. fp32 scales feeding an fp16 model), cast back to it explicitly, so that the graph's dtypes survive a retrace. + The cast is a known cost: one extra dispatch and an intermediate in the + scales' dtype. """ out_val = match.anchor_node.meta["val"] scales_val = match.scales_node.meta.get("val") diff --git a/backends/vulkan/test/test_vulkan_passes.py b/backends/vulkan/test/test_vulkan_passes.py index 5a4ab93dfce..3416213f210 100644 --- a/backends/vulkan/test/test_vulkan_passes.py +++ b/backends/vulkan/test/test_vulkan_passes.py @@ -890,6 +890,49 @@ def forward(self, indices): self.assertEqual(op_node_count(ep.graph_module, "embedding_q4gsw.default"), 1) self.assertEqual(ep.module()(*sample_inputs).dtype, torch.float16) + def test_quantized_linear_ops_keep_fp16_activation_dtype(self): + import executorch.backends.vulkan.custom_ops_lib # noqa: F401 + + torch.manual_seed(0) + out_channels, in_channels, group_size = 8, 64, 32 + packed = torch.randint( + 0, 256, (out_channels, in_channels // 2), dtype=torch.uint8 + ) + q4_scales = torch.rand(in_channels // group_size, out_channels) * 0.1 + 0.01 + q8_weights = torch.randint( + -127, 128, (out_channels, in_channels), dtype=torch.int8 + ) + q8_scales = torch.rand(out_channels) * 0.01 + 0.001 + bias = torch.randn(out_channels) + x = torch.randn(3, in_channels) + zero = torch.zeros(1) + + def calls(x, scales_dtype): + q4 = q4_scales.to(scales_dtype) + q8 = q8_scales.to(scales_dtype) + b = bias.to(scales_dtype) + return { + "linear_q4gsw": lambda: torch.ops.et_vk.linear_q4gsw( + x, packed, q4, group_size, b + ), + "linear_dq8ca_q4gsw": lambda: torch.ops.et_vk.linear_dq8ca_q4gsw( + x, zero, zero, packed, zero, q4, group_size, b + ), + "linear_q8ta_q8csw": lambda: torch.ops.et_vk.linear_q8ta_q8csw( + x, 1.0, 0, q8_weights, zero, q8, b + ), + } + + refs = {name: call() for name, call in calls(x, torch.float32).items()} + for scales_dtype in (torch.float16, torch.float32): + for name, call in calls(x.half(), scales_dtype).items(): + with self.subTest(op=name, scales_dtype=scales_dtype): + out = call() + self.assertEqual(out.dtype, torch.float16) + self.assertTrue( + torch.allclose(out.float(), refs[name], atol=1e-2, rtol=1e-2) + ) + def test_conv1d_as_conv2d_rewrites_eligible_conv(self): # Output equality cannot show this: an unrewritten conv1d computes the # same numbers. What distinguishes the two is the rank the convolution