Skip to content

Commit 36be399

Browse files
committed
Update on "Save foundation weights separately"
This diff: 1. Introduces SerializationConfig to llm_config. Currently, this allows user to save the foundation weights in a separate file; majorly useful for lora case. 2. Adds a pass to tag foundation (non-lora) weights. This is at the top-level (export_llama_lib). The tags are preserved through run_decomps/other passes, and do not affect functionality. 3. Tags are read when placing constants into the named_data_store. 4. Tagged weights are serialized to a separate file. Notes 1. Adding tags to node.meta['custom']['blah'] means that they will not be discarded by run_decompositions 2. Adding tags to the lifted model (ep.graph_module) requires the EP to check is_param_node for xnnpack constants. Instead, add tags to the unlifted model (ep.module()), so we do not need to go through a re-export to get the EP. 3. Not an issue for this diff as llama doesn't have any higher order ops. Adding tags to models with higher-order ops is problematic due to nested submodules. Differential Revision: [D79181064](https://our.internmc.facebook.com/intern/diff/D79181064/) [ghstack-poisoned]
2 parents e042184 + 9671bd9 commit 36be399

File tree

181 files changed

+5693
-1904
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

181 files changed

+5693
-1904
lines changed

.ci/scripts/test_model.sh

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,8 @@ test_model_with_qnn() {
199199
EXPORT_SCRIPT=albert
200200
elif [[ "${MODEL_NAME}" == "bert" ]]; then
201201
EXPORT_SCRIPT=bert
202+
elif [[ "${MODEL_NAME}" == "conv_former" ]]; then
203+
EXPORT_SCRIPT=conv_former
202204
elif [[ "${MODEL_NAME}" == "cvt" ]]; then
203205
EXPORT_SCRIPT=cvt
204206
elif [[ "${MODEL_NAME}" == "distilbert" ]]; then
@@ -238,7 +240,7 @@ test_model_with_qnn() {
238240
"cvt"|"dit"|"focalnet"|"mobilevit_v2"|"pvt"|"swin")
239241
SCRIPT_FOLDER=oss_scripts
240242
;;
241-
"albert"|"bert"|"distilbert"|"roberta"|"efficientnet"|"mobilevit_v1")
243+
"albert"|"bert"|"conv_former"|"distilbert"|"roberta"|"efficientnet"|"mobilevit_v1")
242244
pip install evaluate
243245
SCRIPT_FOLDER=oss_scripts
244246
# 16bit models will encounter op validation fail on some operations,

.ci/scripts/test_qnn_static_llama.sh

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,12 @@ echo "Creating tokenizer.bin"
3333
$PYTHON_EXECUTABLE -m pytorch_tokenizers.tools.llama2c.convert -t tokenizer.model -o tokenizer.bin
3434

3535
set +e
36-
# Compile only as weight sharing is not applicable on x86
37-
$PYTHON_EXECUTABLE backends/qualcomm/tests/test_qnn_delegate.py -k TestExampleLLMScript.test_llama_stories_110m --model SM8650 --build_folder build-android/ --executorch_root . --artifact_dir . --llama_artifacts . --compile_only
36+
# Compile only as weight sharing is not applicable on x86.
37+
$PYTHON_EXECUTABLE backends/qualcomm/tests/test_qnn_delegate.py -k TestExampleLLMScript.test_llama_stories_110m --model SM8650 --build_folder build-android/ --executorch_root . --artifact_dir ./stories_110m_pte_size --llama_artifacts . --compile_only
3838
exit_code1=$?
3939

4040
# Checks accuracy with weight sharing disabled since x86 does not support weight sharing.
41-
$PYTHON_EXECUTABLE backends/qualcomm/tests/test_qnn_delegate.py -k TestExampleLLMScript.test_llama_stories_110m --model SM8650 --build_folder build-x86/ --executorch_root . --artifact_dir . --llama_artifacts . --enable_x86_64
41+
$PYTHON_EXECUTABLE backends/qualcomm/tests/test_qnn_delegate.py -k TestExampleLLMScript.test_llama_stories_110m --model SM8650 --build_folder build-x86/ --executorch_root . --artifact_dir ./stories_110m_accuracy --llama_artifacts . --enable_x86_64
4242
exit_code2=$?
4343

4444
# Check BC

.github/workflows/trunk.yml

Lines changed: 62 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ jobs:
6060
uses: pytorch/test-infra/.github/workflows/linux_job.yml@main
6161
strategy:
6262
matrix:
63-
model: [add]
63+
model: [add, softmax, mv2]
6464
fail-fast: false
6565
with:
6666
runner: linux.2xlarge
@@ -72,31 +72,85 @@ jobs:
7272
MODEL_NAME=${{ matrix.model }}
7373
CONDA_ENV=$(conda env list --json | jq -r ".envs | .[-1]")
7474
conda activate "${CONDA_ENV}"
75+
if [[ ${{ matrix.model}} == "add" ]]; then
76+
SIM_LIMIT_SEC=60
77+
elif [[ ${{ matrix.model}} == "softmax" ]]; then
78+
SIM_LIMIT_SEC=60
79+
elif [[ ${{ matrix.model}} == "mv2" ]]; then
80+
SIM_LIMIT_SEC=5000
81+
else
82+
echo "Failed unsupported model selection ${{ matrix.model }}"
83+
exit 1
84+
fi
7585
7686
source .ci/scripts/utils.sh
7787
source .ci/scripts/zephyr-utils.sh
7888
mkdir -p zephyr_scratch/
7989
cd zephyr_scratch
8090
export ZEPHYR_PROJ_ROOT=$(realpath $(pwd))
91+
export ARM_FVP_TUTORIALS_ROOT=$ZEPHYR_PROJ_ROOT/zephyr/samples/modules/executorch/arm-fvp-tutorials
8192
93+
# TODO @Bujji: Should see if this can be moved into the docker image itself
8294
download_arm_zephyr_sdk
8395
./zephyr-sdk-0.16.0/setup.sh -c -t arm-zephyr-eabi
84-
8596
cd $ZEPHYR_PROJ_ROOT
8697
setup_zephyr_et_module
8798
99+
# Run setup scripts for Arm FVP and Arm AOT Compilation
88100
cd $ZEPHYR_PROJ_ROOT/modules/lib/executorch
89101
install_executorch "--use-pt-pinned-commit"
90102
.ci/scripts/setup-arm-baremetal-tools.sh --target-toolchain zephyr
91103
source examples/arm/ethos-u-scratch/setup_path.sh
92104
source $ZEPHYR_PROJ_ROOT/zephyr/zephyr-env.sh
93-
cd $ZEPHYR_PROJ_ROOT/zephyr/samples/modules/executorch/arm/hello_world
94-
west build -p always -b mps3/corstone300/fvp
95-
FVP_Corstone_SSE-300_Ethos-U55 -a build/zephyr/zephyr.elf -C mps3_board.visualisation.disable-visualisation=1 -C mps3_board.telnetterminal0.start_telnet=0 -C mps3_board.uart0.out_file='sim.out' -C cpu0.CFGITCMSZ=15 -C cpu0.CFGDTCMSZ=15 --simlimit 120
96105
97-
grep -qF "Output[0][0]: (float) 2.000000" sim.out
106+
# Get the model as PTE
107+
python -m examples.arm.aot_arm_compiler \
108+
--model_name="${MODEL_NAME}" \
109+
--output="${MODEL_NAME}.pte"
110+
111+
# Generate the C-style header
112+
cd $ARM_FVP_TUTORIALS_ROOT
113+
python build_model.py \
114+
--executorch-root $ZEPHYR_PROJ_ROOT/modules/lib/executorch \
115+
--pte-file $ZEPHYR_PROJ_ROOT/modules/lib/executorch/${MODEL_NAME}.pte \
116+
--output-path $ARM_FVP_TUTORIALS_ROOT/models/${MODEL_NAME}/src/
117+
118+
cd $ARM_FVP_TUTORIALS_ROOT/models/${MODEL_NAME}/
119+
120+
# Build the zephyr elf
121+
west build -p always -b mps3/corstone300/fvp -- \
122+
-DET_PTE_FILE_PATH_FOR_SELECTIVE_BUILD=$ZEPHYR_PROJ_ROOT/modules/lib/executorch/${MODEL_NAME}.pte
123+
124+
# Run the simulation
125+
FVP_Corstone_SSE-300_Ethos-U55 -a build/zephyr/zephyr.elf \
126+
-C mps3_board.visualisation.disable-visualisation=1 \
127+
-C mps3_board.telnetterminal0.start_telnet=0 \
128+
-C mps3_board.uart0.out_file='sim.out' \
129+
-C cpu0.CFGITCMSZ=15 \
130+
-C cpu0.CFGDTCMSZ=15 \
131+
--simlimit ${SIM_LIMIT_SEC}
132+
133+
# Disable exit on error
134+
set +e
135+
# Report failure if any of the ouptut verification checks fail
136+
grep -qF "ERROR" sim.out
137+
exit_status=$? #store 0 if found (failure), 1 if not (success)
138+
if [[ "$exit_status" -eq "0" ]]; then
139+
cat sim.out
140+
set -e
141+
exit 1
142+
fi
143+
144+
# Report fail if simulation does not complete successfully
145+
grep -qF "SUCCESS: Program complete, exiting." sim.out
98146
exit_status=$? #store 0 if found (success), 1 if not (failure)
99-
exit $exit_status
147+
if [[ "$exit_status" -eq "1" ]]; then
148+
cat sim.out
149+
set -e
150+
exit 1
151+
fi
152+
# Re-enable exit on error
153+
set -e
100154
101155
test-models-linux-aarch64:
102156
name: test-models-linux-aarch64
@@ -568,7 +622,7 @@ jobs:
568622
strategy:
569623
matrix:
570624
dtype: [fp32]
571-
model: [dl3, mv3, mv2, ic4, ic3, vit, mb, w2l]
625+
model: [dl3, mv3, mv2, ic4, ic3, vit, mb, w2l, conv_former]
572626
fail-fast: false
573627
with:
574628
runner: linux.2xlarge

backends/apple/coreml/TARGETS

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,26 @@ runtime.python_library(
6060
],
6161
)
6262

63+
runtime.python_library(
64+
name = "recipes",
65+
srcs = glob([
66+
"recipes/*.py",
67+
]),
68+
visibility = [
69+
"@EXECUTORCH_CLIENTS",
70+
],
71+
deps = [
72+
"fbsource//third-party/pypi/coremltools:coremltools",
73+
":backend",
74+
"//caffe2:torch",
75+
"//executorch/exir:lib",
76+
"//executorch/exir/backend:compile_spec_schema",
77+
"//executorch/exir/backend:partitioner",
78+
"//executorch/exir/backend:utils",
79+
"//executorch/export:lib",
80+
],
81+
)
82+
6383
runtime.cxx_python_extension(
6484
name = "executorchcoreml",
6585
srcs = [
@@ -103,6 +123,7 @@ runtime.python_test(
103123
"fbsource//third-party/pypi/pytest:pytest",
104124
":partitioner",
105125
":quantizer",
126+
":recipes",
106127
"//caffe2:torch",
107128
"//pytorch/vision:torchvision",
108129
],

backends/apple/coreml/compiler/torch_ops.py

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
# coremltools than is used by ExecuTorch. Each op registered here should have a link to a PR in coremltools that adds
99
# the op to the coremltools library.
1010

11+
import numpy as np
1112
import torch as _torch
1213
from coremltools import _logger
1314
from coremltools.converters.mil.frontend import _utils
@@ -21,7 +22,6 @@
2122
transpose,
2223
unbind,
2324
)
24-
2525
from coremltools.converters.mil.frontend.torch.torch_op_registry import (
2626
register_torch_op,
2727
)
@@ -132,3 +132,43 @@ def dequantize_affine(context, node):
132132
name=node.name,
133133
)
134134
context.add(output, node.name)
135+
136+
137+
@register_torch_op(
138+
torch_alias=["quant::dequantize_codebook", "quant.dequantize_codebook"],
139+
override=False,
140+
)
141+
def dequantize_codebook(context, node):
142+
inputs = _get_inputs(context, node, expected=[4, 5])
143+
codes = inputs[0].val
144+
codebook = inputs[1].val
145+
nbits = inputs[2].val
146+
147+
# information in block_size is redundant with codebook.shape
148+
block_size = inputs[3].val # noqa: F841
149+
150+
assert len(codes.shape) == 2, "Only rank 2 inputs are supported"
151+
152+
# Assert codebook is as expected. codebook.dim() = codes.dim() + 2
153+
assert len(codebook.shape) == 4, "Only rank 4 inputs are supported for codebook"
154+
assert codebook.shape[0] == 1, "Only grouped_channel granularity is supported"
155+
n_luts = codebook.shape[1]
156+
assert (
157+
codes.shape[1] % n_luts == 0
158+
), "codes.shape[1] must be divisible by codebook.shape[1]"
159+
assert codebook.shape[2] == 2**nbits
160+
assert codebook.shape[3] == 1, "Only scalar look up values are supported"
161+
162+
if len(inputs) > 4:
163+
output_dtype = inputs[4].val
164+
out_np_dtype = NUM_TO_NUMPY_DTYPE[output_dtype]
165+
_logger.warning(
166+
f"Core ML ignores output_dtype {out_np_dtype} on torchao.dequantize_affine and instead uses the native precision."
167+
)
168+
169+
output = _utils._construct_constexpr_lut_op(
170+
codes.astype(np.int8),
171+
codebook,
172+
name=node.name,
173+
)
174+
context.add(output, node.name)
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Copyright © 2025 Apple Inc. All rights reserved.
2+
#
3+
# Please refer to the license found in the LICENSE file in the root directory of the source tree.
4+
5+
6+
from executorch.export import recipe_registry
7+
8+
from .coreml_recipe_provider import CoreMLRecipeProvider
9+
from .coreml_recipe_types import CoreMLRecipeType
10+
11+
# Auto-register CoreML backend recipe provider
12+
recipe_registry.register_backend_recipe_provider(CoreMLRecipeProvider())
13+
14+
__all__ = [
15+
"CoreMLRecipeProvider",
16+
"CoreMLRecipeType",
17+
]
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
# Copyright © 2025 Apple Inc. All rights reserved.
2+
#
3+
# Please refer to the license found in the LICENSE file in the root directory of the source tree.
4+
5+
6+
from typing import Any, Optional, Sequence
7+
8+
import coremltools as ct
9+
10+
from executorch.backends.apple.coreml.compiler import CoreMLBackend
11+
from executorch.backends.apple.coreml.partition.coreml_partitioner import (
12+
CoreMLPartitioner,
13+
)
14+
from executorch.backends.apple.coreml.recipes.coreml_recipe_types import (
15+
COREML_BACKEND,
16+
CoreMLRecipeType,
17+
)
18+
19+
from executorch.exir import EdgeCompileConfig
20+
from executorch.export import (
21+
BackendRecipeProvider,
22+
ExportRecipe,
23+
LoweringRecipe,
24+
RecipeType,
25+
)
26+
27+
28+
class CoreMLRecipeProvider(BackendRecipeProvider):
29+
@property
30+
def backend_name(self) -> str:
31+
return COREML_BACKEND
32+
33+
def get_supported_recipes(self) -> Sequence[RecipeType]:
34+
return list(CoreMLRecipeType)
35+
36+
def create_recipe(
37+
self, recipe_type: RecipeType, **kwargs: Any
38+
) -> Optional[ExportRecipe]:
39+
"""Create CoreML recipe with precision and compute unit combinations"""
40+
41+
if recipe_type not in self.get_supported_recipes():
42+
return None
43+
44+
if ct is None:
45+
raise ImportError(
46+
"coremltools is required for CoreML recipes. "
47+
"Install it with: pip install coremltools"
48+
)
49+
50+
# Validate kwargs
51+
self._validate_recipe_kwargs(recipe_type, **kwargs)
52+
53+
# Parse recipe type to get precision and compute unit
54+
precision = None
55+
if recipe_type == CoreMLRecipeType.FP32:
56+
precision = ct.precision.FLOAT32
57+
elif recipe_type == CoreMLRecipeType.FP16:
58+
precision = ct.precision.FLOAT16
59+
60+
if precision is None:
61+
raise ValueError(f"Unknown precision for recipe: {recipe_type.value}")
62+
63+
return self._build_recipe(recipe_type, precision, **kwargs)
64+
65+
def _validate_recipe_kwargs(self, recipe_type: RecipeType, **kwargs: Any) -> None:
66+
if not kwargs:
67+
return
68+
expected_keys = {"minimum_deployment_target", "compute_unit"}
69+
unexpected = set(kwargs.keys()) - expected_keys
70+
if unexpected:
71+
raise ValueError(
72+
f"CoreML Recipes only accept 'minimum_deployment_target' or 'compute_unit' as parameter. "
73+
f"Unexpected parameters: {list(unexpected)}"
74+
)
75+
if "minimum_deployment_target" in kwargs:
76+
minimum_deployment_target = kwargs["minimum_deployment_target"]
77+
if not isinstance(minimum_deployment_target, ct.target):
78+
raise ValueError(
79+
f"Parameter 'minimum_deployment_target' must be an enum of type ct.target, got {type(minimum_deployment_target)}"
80+
)
81+
if "compute_unit" in kwargs:
82+
compute_unit = kwargs["compute_unit"]
83+
if not isinstance(compute_unit, ct.ComputeUnit):
84+
raise ValueError(
85+
f"Parameter 'compute_unit' must be an enum of type ct.ComputeUnit, got {type(compute_unit)}"
86+
)
87+
88+
def _build_recipe(
89+
self,
90+
recipe_type: RecipeType,
91+
precision: ct.precision,
92+
**kwargs: Any,
93+
) -> ExportRecipe:
94+
lowering_recipe = self._get_coreml_lowering_recipe(
95+
compute_precision=precision,
96+
**kwargs,
97+
)
98+
99+
return ExportRecipe(
100+
name=recipe_type.value,
101+
quantization_recipe=None, # TODO - add quantization recipe
102+
lowering_recipe=lowering_recipe,
103+
)
104+
105+
def _get_coreml_lowering_recipe(
106+
self,
107+
compute_precision: ct.precision,
108+
**kwargs: Any,
109+
) -> LoweringRecipe:
110+
compile_specs = CoreMLBackend.generate_compile_specs(
111+
compute_precision=compute_precision,
112+
**kwargs,
113+
)
114+
115+
minimum_deployment_target = kwargs.get("minimum_deployment_target", None)
116+
take_over_mutable_buffer = True
117+
if minimum_deployment_target and minimum_deployment_target < ct.target.iOS18:
118+
take_over_mutable_buffer = False
119+
120+
partitioner = CoreMLPartitioner(
121+
compile_specs=compile_specs,
122+
take_over_mutable_buffer=take_over_mutable_buffer,
123+
)
124+
125+
edge_compile_config = EdgeCompileConfig(
126+
_check_ir_validity=False,
127+
_skip_dim_order=False,
128+
)
129+
130+
return LoweringRecipe(
131+
partitioners=[partitioner], edge_compile_config=edge_compile_config
132+
)

0 commit comments

Comments
 (0)