diff --git a/backends/vulkan/custom_ops_lib.py b/backends/vulkan/custom_ops_lib.py index 31e9872b060..6d9476a6a4b 100644 --- a/backends/vulkan/custom_ops_lib.py +++ b/backends/vulkan/custom_ops_lib.py @@ -313,11 +313,18 @@ 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( - 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) @@ -452,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 @@ -1187,7 +1195,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; 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 dbd0d6fbf98..5a7b245fa5e 100644 --- a/backends/vulkan/patterns/quantized_embedding.py +++ b/backends/vulkan/patterns/quantized_embedding.py @@ -21,6 +21,38 @@ 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. + 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") + 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 +186,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 +369,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..3416213f210 100644 --- a/backends/vulkan/test/test_vulkan_passes.py +++ b/backends/vulkan/test/test_vulkan_passes.py @@ -845,6 +845,94 @@ 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_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