Skip to content

Add palletization/codebook support to CoreML backend #13051

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Aug 6, 2025
Merged
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
42 changes: 41 additions & 1 deletion backends/apple/coreml/compiler/torch_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
# coremltools than is used by ExecuTorch. Each op registered here should have a link to a PR in coremltools that adds
# the op to the coremltools library.

import numpy as np
Copy link
Contributor

Choose a reason for hiding this comment

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

Any constraint on numpy version?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think most versions would work. I only use it for np.int8

import torch as _torch
from coremltools import _logger
from coremltools.converters.mil.frontend import _utils
Expand All @@ -21,7 +22,6 @@
transpose,
unbind,
)

from coremltools.converters.mil.frontend.torch.torch_op_registry import (
register_torch_op,
)
Expand Down Expand Up @@ -132,3 +132,43 @@ def dequantize_affine(context, node):
name=node.name,
)
context.add(output, node.name)


@register_torch_op(
torch_alias=["quant::dequantize_codebook", "quant.dequantize_codebook"],
override=False,
)
def dequantize_codebook(context, node):
Copy link
Collaborator

Choose a reason for hiding this comment

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

qq: seems that "codebook" corresponds to our look up table (lut)?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes, codebook is the same as the LUT and codes are the same as the indices.

Copy link
Contributor

Choose a reason for hiding this comment

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

We don't have quantize variant because the weights are always folded?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'm enabling weight-only right now, so there is no quantize variant

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'm enabling weight-only right now, so there is no quantize variant

inputs = _get_inputs(context, node, expected=[4, 5])
codes = inputs[0].val
codebook = inputs[1].val
nbits = inputs[2].val

# information in block_size is redundant with codebook.shape
block_size = inputs[3].val # noqa: F841
Copy link
Contributor Author

Choose a reason for hiding this comment

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

@YifanShenSZ is there any restriction on the block size here needed?

Copy link
Collaborator

Choose a reason for hiding this comment

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

I'm not aware of, and I don't see any from our constexpr_lut_to_dense op doc


assert len(codes.shape) == 2, "Only rank 2 inputs are supported"

# Assert codebook is as expected. codebook.dim() = codes.dim() + 2
assert len(codebook.shape) == 4, "Only rank 4 inputs are supported for codebook"
assert codebook.shape[0] == 1, "Only grouped_channel granularity is supported"
n_luts = codebook.shape[1]
assert (
codes.shape[1] % n_luts == 0
), "codes.shape[1] must be divisible by codebook.shape[1]"
assert codebook.shape[2] == 2**nbits
assert codebook.shape[3] == 1, "Only scalar look up values are supported"

if len(inputs) > 4:
output_dtype = inputs[4].val
out_np_dtype = NUM_TO_NUMPY_DTYPE[output_dtype]
_logger.warning(
f"Core ML ignores output_dtype {out_np_dtype} on torchao.dequantize_affine and instead uses the native precision."
)

output = _utils._construct_constexpr_lut_op(
Copy link
Contributor

Choose a reason for hiding this comment

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

i dont follow the constexpr thing for this though? what does that mean?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This translates the dequantize_codebook op to one of the following CoreML ops:

These ops get fused with the following linear op at runtime.

codes.astype(np.int8),
codebook,
name=node.name,
)
context.add(output, node.name)
60 changes: 60 additions & 0 deletions backends/apple/coreml/test/test_torch_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@

from executorch.backends.apple.coreml.compiler import CoreMLBackend
from executorch.backends.apple.coreml.partition import CoreMLPartitioner
from executorch.exir.backend.utils import format_delegated_graph

from torchao.prototype.quantization.codebook_coreml import CodebookWeightOnlyConfig
from torchao.quantization import IntxWeightOnlyConfig, PerAxis, PerGroup, quantize_


Expand Down Expand Up @@ -164,6 +167,61 @@ def test_dequantize_affine_c8w_embedding_b4w_linear(self):
et_prog = delegated_program.to_executorch()
self._compare_outputs(et_prog, model, example_inputs)

def test_dequantize_codebook_linear(self):
model, example_inputs = self._get_test_model()
quantize_(
model,
CodebookWeightOnlyConfig(dtype=torch.uint2, block_size=[-1, 16]),
)
ep = torch.export.export(model, example_inputs)
assert "torch.ops.quant.dequantize_codebook.default" in ep.graph_module.code
delegated_program = executorch.exir.to_edge_transform_and_lower(
ep,
partitioner=[self._coreml_partitioner()],
)
for node in delegated_program.exported_program().graph.nodes:
if node.op == "call_function":
assert node.target.__name__ in [
"executorch_call_delegate",
"getitem",
], f"Got unexpected node target after delegation: {node.target.__name__}"

assert (
"executorch.exir.dialects.edge._ops.quant.dequantize_codebook.default"
in format_delegated_graph(delegated_program.exported_program().graph_module)
)

et_prog = delegated_program.to_executorch()
self._compare_outputs(et_prog, model, example_inputs)

def test_dequantize_codebook_embedding(self):
model, example_inputs = self._get_test_model()
quantize_(
model,
CodebookWeightOnlyConfig(dtype=torch.uint3, block_size=[-1, 16]),
Copy link
Contributor

Choose a reason for hiding this comment

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

So does coremltools recognize _construct_constexpr_lut_op followed by embedding lookup as special pattern for quantized embedding that gets optimized? Same for say LUT quantized linear?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

From @cymbalrush, during on-device compilation CoreML fuses dequant ops with linear ops into one kernel.

lambda m, fqn: isinstance(m, torch.nn.Embedding),
)
ep = torch.export.export(model, example_inputs)
assert "torch.ops.quant.dequantize_codebook.default" in ep.graph_module.code
delegated_program = executorch.exir.to_edge_transform_and_lower(
ep,
partitioner=[self._coreml_partitioner()],
)
for node in delegated_program.exported_program().graph.nodes:
if node.op == "call_function":
assert node.target.__name__ in [
"executorch_call_delegate",
"getitem",
], f"Got unexpected node target after delegation: {node.target.__name__}"

assert (
"executorch.exir.dialects.edge._ops.quant.dequantize_codebook.default"
in format_delegated_graph(delegated_program.exported_program().graph_module)
)

et_prog = delegated_program.to_executorch()
self._compare_outputs(et_prog, model, example_inputs)


if __name__ == "__main__":
test_runner = TestTorchOps()
Expand All @@ -172,3 +230,5 @@ def test_dequantize_affine_c8w_embedding_b4w_linear(self):
test_runner.test_dequantize_affine_c4w_embedding()
test_runner.test_dequantize_affine_c4w_linear()
test_runner.test_dequantize_affine_c8w_embedding_b4w_linear()
test_runner.test_dequantize_codebook_linear()
test_runner.test_dequantize_codebook_embedding()
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ dependencies=[
"typing-extensions>=4.10.0",
# Keep this version in sync with: ./backends/apple/coreml/scripts/install_requirements.sh
"coremltools==8.3; platform_system == 'Darwin' or platform_system == 'Linux'",
# scikit-learn is used to support palettization in the coreml backend
"scikit-learn==1.7.1",
"hydra-core>=1.3.0",
"omegaconf>=2.3.0",
]
Expand Down
2 changes: 1 addition & 1 deletion third-party/ao
Submodule ao updated 125 files
Loading