|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +from typing import Optional |
| 8 | + |
| 9 | +import executorch.backends.vulkan.utils as utils |
| 10 | +import torch |
| 11 | +from executorch.backends.transforms.utils import get_param_tensor |
| 12 | +from executorch.backends.vulkan.patterns.pattern_registry import ( |
| 13 | + PatternMatch, |
| 14 | + register_pattern_detector, |
| 15 | + register_pattern_replacement, |
| 16 | +) |
| 17 | +from executorch.exir import ExportedProgram |
| 18 | +from executorch.exir.dialects._ops import ops as exir_ops |
| 19 | + |
| 20 | + |
| 21 | +class QuantizedEmbeddingMatch(PatternMatch): |
| 22 | + def __init__(self, node: torch.fx.Node) -> None: |
| 23 | + self.anchor_node = node |
| 24 | + self.match_found = False |
| 25 | + self.all_nodes = [node] |
| 26 | + |
| 27 | + # quantized_decomposed.embedding_4bit.dtype args: |
| 28 | + # (weight, weight_scales, weight_zero_points, quant_min, quant_max, |
| 29 | + # indices, *, dtype) |
| 30 | + self.weight_node = node.args[0] |
| 31 | + self.scales_node = node.args[1] |
| 32 | + self.indices_node = node.args[5] |
| 33 | + |
| 34 | + # Validate quantization parameters match our shader's assumptions. |
| 35 | + # The shader hardcodes the 4-bit signed offset (subtract 8), which |
| 36 | + # corresponds to quant_min=-8, quant_max=7, zero_points=0. |
| 37 | + quant_min = node.args[3] |
| 38 | + quant_max = node.args[4] |
| 39 | + if quant_min != -8 or quant_max != 7: |
| 40 | + self.match_found = False |
| 41 | + return |
| 42 | + |
| 43 | + # weight_zero_points (args[2]) should be None or all-zeros |
| 44 | + weight_zp_node = node.args[2] |
| 45 | + if weight_zp_node is not None: |
| 46 | + # If it's a constant tensor, verify it's all zeros |
| 47 | + if ( |
| 48 | + isinstance(weight_zp_node, torch.fx.Node) |
| 49 | + and "val" in weight_zp_node.meta |
| 50 | + ): |
| 51 | + zp_val = weight_zp_node.meta["val"] |
| 52 | + if isinstance(zp_val, torch.Tensor) and not torch.all(zp_val == 0): |
| 53 | + self.match_found = False |
| 54 | + return |
| 55 | + |
| 56 | + # Trace weight to its placeholder |
| 57 | + const_node, arg_chain = utils.trace_args_until_placeholder(self.weight_node) |
| 58 | + if const_node is not None: |
| 59 | + self.weight_node = const_node |
| 60 | + self.all_nodes.extend(arg_chain) |
| 61 | + |
| 62 | + # Trace scales to their placeholder |
| 63 | + scales_node, arg_chain = utils.trace_args_until_placeholder(self.scales_node) |
| 64 | + if scales_node is not None: |
| 65 | + self.scales_node = scales_node |
| 66 | + self.all_nodes.extend(arg_chain) |
| 67 | + |
| 68 | + self.match_found = True |
| 69 | + |
| 70 | + |
| 71 | +embedding_4bit_target = exir_ops.edge.quantized_decomposed.embedding_4bit.dtype |
| 72 | + |
| 73 | + |
| 74 | +def _detect_tied_linear_weight( |
| 75 | + ep: ExportedProgram, |
| 76 | + weight_node: torch.fx.Node, |
| 77 | + weight_tensor: torch.Tensor, |
| 78 | +) -> bool: |
| 79 | + """Check if this embedding weight is tied to a linear weight. |
| 80 | +
|
| 81 | + The embedding weight is packed uint8 [vocab_size, embed_dim/2]. The linear |
| 82 | + output weight may be stored as unpacked int8 [vocab_size, embed_dim]. If we |
| 83 | + find a placeholder whose int8 values match our unpacked embedding values, |
| 84 | + the weights are tied and we should use the linear packing to enable dedup. |
| 85 | + """ |
| 86 | + vocab_size = weight_tensor.shape[0] |
| 87 | + embed_dim = weight_tensor.shape[1] * 2 |
| 88 | + |
| 89 | + # Unpack embedding weight using embedding convention (high nibble first) |
| 90 | + emb_high = (weight_tensor >> 4).to(torch.int8) - 8 |
| 91 | + emb_low = (weight_tensor & 0xF).to(torch.int8) - 8 |
| 92 | + emb_unpacked = torch.stack([emb_high, emb_low], dim=-1).reshape( |
| 93 | + vocab_size, embed_dim |
| 94 | + ) |
| 95 | + |
| 96 | + for node in ep.graph_module.graph.nodes: |
| 97 | + if node.op != "placeholder" or node == weight_node: |
| 98 | + continue |
| 99 | + |
| 100 | + try: |
| 101 | + candidate = get_param_tensor(ep, node) |
| 102 | + except RuntimeError: |
| 103 | + continue |
| 104 | + if candidate is None: |
| 105 | + continue |
| 106 | + if candidate.shape != (vocab_size, embed_dim) or candidate.dtype != torch.int8: |
| 107 | + continue |
| 108 | + |
| 109 | + if torch.equal(emb_unpacked, candidate): |
| 110 | + return True |
| 111 | + |
| 112 | + return False |
| 113 | + |
| 114 | + |
| 115 | +@register_pattern_detector("quantized_embedding") |
| 116 | +def find_quantized_embedding_patterns( |
| 117 | + node: torch.fx.Node, |
| 118 | +) -> Optional[QuantizedEmbeddingMatch]: |
| 119 | + if node.target != embedding_4bit_target: |
| 120 | + return None |
| 121 | + |
| 122 | + matched_pattern = QuantizedEmbeddingMatch(node) |
| 123 | + if matched_pattern.match_found: |
| 124 | + return matched_pattern |
| 125 | + return None |
| 126 | + |
| 127 | + |
| 128 | +@register_pattern_replacement("quantized_embedding") |
| 129 | +def replace_quantized_embedding_patterns( |
| 130 | + ep: ExportedProgram, |
| 131 | + graph_module: torch.fx.GraphModule, |
| 132 | + match: QuantizedEmbeddingMatch, |
| 133 | +): |
| 134 | + weight_tensor = get_param_tensor(ep, match.weight_node) |
| 135 | + assert weight_tensor is not None |
| 136 | + |
| 137 | + scales_tensor = get_param_tensor(ep, match.scales_node) |
| 138 | + assert scales_tensor is not None |
| 139 | + |
| 140 | + is_linear_weight = _detect_tied_linear_weight(ep, match.weight_node, weight_tensor) |
| 141 | + |
| 142 | + if is_linear_weight: |
| 143 | + # Repack using linear convention (low nibble = even, high nibble = odd) |
| 144 | + vocab_size = weight_tensor.shape[0] |
| 145 | + high = (weight_tensor >> 4).to(torch.int8) - 8 |
| 146 | + low = (weight_tensor & 0xF).to(torch.int8) - 8 |
| 147 | + unpacked = torch.stack([high, low], dim=-1).reshape(vocab_size, -1) |
| 148 | + repacked = unpacked.to(torch.uint8) + 8 |
| 149 | + weight_tensor = repacked[:, 1::2] << 4 | repacked[:, ::2] |
| 150 | + # Update the state dict with repacked tensor |
| 151 | + original_weight = get_param_tensor(ep, match.weight_node) |
| 152 | + if original_weight is not None: |
| 153 | + for key, value in ep.state_dict.items(): |
| 154 | + if value.data_ptr() == original_weight.data_ptr(): |
| 155 | + ep.state_dict[key] = weight_tensor |
| 156 | + break |
| 157 | + |
| 158 | + # Compute group_size from weight and scales shapes |
| 159 | + embed_dim = weight_tensor.shape[1] * 2 # packed, 2 values per byte |
| 160 | + groups_per_row = scales_tensor.shape[1] if scales_tensor.ndim > 1 else 1 |
| 161 | + group_size = embed_dim // groups_per_row |
| 162 | + |
| 163 | + with graph_module.graph.inserting_before(match.anchor_node): |
| 164 | + embedding_q4gsw_node = graph_module.graph.create_node( |
| 165 | + "call_function", |
| 166 | + exir_ops.edge.et_vk.embedding_q4gsw.default, |
| 167 | + args=( |
| 168 | + match.weight_node, |
| 169 | + match.scales_node, |
| 170 | + group_size, |
| 171 | + match.indices_node, |
| 172 | + is_linear_weight, |
| 173 | + ), |
| 174 | + ) |
| 175 | + |
| 176 | + embedding_q4gsw_node.meta["val"] = match.anchor_node.meta["val"] |
| 177 | + match.anchor_node.replace_all_uses_with(embedding_q4gsw_node) |
0 commit comments