Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions backends/vulkan/custom_ops_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI review] A1 (Medium): The linear dtype fix is untested.

On main, calling linear_q4gsw / linear_dq8ca_q4gsw with an fp16 activation, eagerly or on retrace, raises expected m1 and m2 to have the same dtype, but got: c10::Half != float. This line fixes that, but reverting it leaves every test green. The only new test covers the embedding.

Proposed fix: add a small test that calls torch.ops.et_vk.linear_q4gsw (and linear_dq8ca_q4gsw) with an fp16 input, using both fp16 and fp32 scales. Assert that out.dtype == torch.float16 and that the output is allclose to the fp32 computation. Alternatively, extend test_fuse_q4gsw_linear_keeps_preceding_reshape with an .half() model and check ep.module()(x).dtype.

)

out = torch.nn.functional.linear(x, weights, bias)
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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)


Expand Down
38 changes: 34 additions & 4 deletions backends/vulkan/patterns/quantized_embedding.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI review] A2 (Low): Extra cast dispatch where the shader could write the model dtype directly.

For this PR's target case (fp16 model, fp32 scales), this adds a separate _to_dim_order_copy plus an fp32 [*, S, D] intermediate: one extra dispatch per forward, and 2× embedding activation memory during prefill. The runtime already decouples the two dtypes: add_embedding_q4gsw_node picks _float_scales from the scales dtype and the shader's dtype suffix from out.

Proposed fix: add ScalarType? dtype=None to the embedding_q4gsw schema. The impl returns .to(dtype or weight_scales.dtype), the pattern passes out_val.dtype, and C++ reads the dtype from out, which already selects the shader. That removes the cast node and this branch. If you'd rather not change the schema, note in this docstring that the cast is a known cost.

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
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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)
88 changes: 88 additions & 0 deletions backends/vulkan/test/test_vulkan_passes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down