Skip to content

Commit d755944

Browse files
authored
Merge branch 'main' into small_llama
2 parents e97a8f4 + f7ddbde commit d755944

File tree

159 files changed

+4651
-1664
lines changed

Some content is hidden

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

159 files changed

+4651
-1664
lines changed

.ci/scripts/test_huggingface_optimum_model.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -262,14 +262,20 @@ def test_vit(model_id, model_dir, recipe, *, quantize=False, run_only=False):
262262

263263
assert torch.allclose(
264264
eager_output.logits, et_output, atol=1e-02, rtol=1e-02
265-
), "CoreML output does not match eager"
265+
), "Model output does not match eager"
266266

267267

268268
if __name__ == "__main__":
269269
parser = argparse.ArgumentParser()
270270
parser.add_argument("--model", type=str, required=True)
271271
parser.add_argument("--recipe", type=str, required=True)
272272
parser.add_argument("--quantize", action="store_true", help="Enable quantization")
273+
parser.add_argument(
274+
"--model_dir",
275+
type=str,
276+
required=False,
277+
help="When provided, write the pte file to this directory. Otherwise, a temporary directory is created for the test.",
278+
)
273279
args = parser.parse_args()
274280

275281
model_to_model_id_and_test_function = {
@@ -294,11 +300,11 @@ def test_vit(model_id, model_dir, recipe, *, quantize=False, run_only=False):
294300
f"Unknown model name: {args.model}. Available models: {model_to_model_id_and_test_function.keys()}"
295301
)
296302

303+
model_id, test_fn = model_to_model_id_and_test_function[args.model]
297304
with tempfile.TemporaryDirectory() as tmp_dir:
298-
model_id, test_fn = model_to_model_id_and_test_function[args.model]
299305
test_fn(
300306
model_id=model_id,
301-
model_dir=tmp_dir,
307+
model_dir=tmp_dir if args.model_dir is None else args.model_dir,
302308
recipe=args.recipe,
303309
quantize=args.quantize,
304310
)

.ci/scripts/test_model.sh

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,9 @@ 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
204+
EXTRA_FLAGS="--dataset imagenet-mini/val"
202205
elif [[ "${MODEL_NAME}" == "cvt" ]]; then
203206
EXPORT_SCRIPT=cvt
204207
elif [[ "${MODEL_NAME}" == "distilbert" ]]; then
@@ -238,7 +241,7 @@ test_model_with_qnn() {
238241
"cvt"|"dit"|"focalnet"|"mobilevit_v2"|"pvt"|"swin")
239242
SCRIPT_FOLDER=oss_scripts
240243
;;
241-
"albert"|"bert"|"distilbert"|"roberta"|"efficientnet"|"mobilevit_v1")
244+
"albert"|"bert"|"conv_former"|"distilbert"|"roberta"|"efficientnet"|"mobilevit_v1")
242245
pip install evaluate
243246
SCRIPT_FOLDER=oss_scripts
244247
# 16bit models will encounter op validation fail on some operations,

.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
@@ -569,7 +623,7 @@ jobs:
569623
strategy:
570624
matrix:
571625
dtype: [fp32]
572-
model: [dl3, mv3, mv2, ic4, ic3, vit, mb, w2l]
626+
model: [dl3, mv3, mv2, ic4, ic3, vit, mb, w2l, conv_former]
573627
fail-fast: false
574628
with:
575629
runner: linux.2xlarge

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)

backends/apple/coreml/runtime/delegate/coreml_backend_delegate.mm

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -88,17 +88,17 @@
8888
ET_LOG(Error, "%s: DataType=%d is not supported", ETCoreMLStrings.delegateIdentifier.UTF8String, (int)tensor.scalar_type());
8989
return std::nullopt;
9090
}
91-
91+
9292
std::vector<ssize_t> strides(tensor.strides().begin(), tensor.strides().end());
9393
std::vector<size_t> shape(tensor.sizes().begin(), tensor.sizes().end());
94-
94+
9595
// If tensor is rank 0, wrap in rank 1
9696
// See https://github.com/apple/coremltools/blob/8.2/coremltools/converters/mil/frontend/torch/exir_utils.py#L73
9797
if (shape.size() == 0) {
9898
shape.push_back(1);
9999
strides.push_back(1);
100100
}
101-
101+
102102
MultiArray::MemoryLayout layout(dataType.value(), std::move(shape), std::move(strides));
103103
switch (argType) {
104104
case ArgType::Input: {
@@ -281,9 +281,11 @@ ModelLoggingOptions get_logging_options(BackendExecutionContext& context) {
281281
}
282282

283283
namespace {
284-
auto cls = CoreMLBackendDelegate();
285-
Backend backend{ETCoreMLStrings.delegateIdentifier.UTF8String, &cls};
286-
static auto success_with_compiler = register_backend(backend);
284+
#ifndef LAZY_LOAD_IOS_PYTORCH_INITIALIZER
285+
auto cls = CoreMLBackendDelegate();
286+
Backend backend{ETCoreMLStrings.delegateIdentifier.UTF8String, &cls};
287+
static auto success_with_compiler = register_backend(backend);
288+
#endif
287289
}
288290

289291
} // namespace coreml

backends/apple/coreml/test/test_torch_ops.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@
1414

1515
from executorch.backends.apple.coreml.compiler import CoreMLBackend
1616
from executorch.backends.apple.coreml.partition import CoreMLPartitioner
17+
from executorch.exir.backend.utils import format_delegated_graph
18+
19+
from torchao.prototype.quantization.codebook_coreml import CodebookWeightOnlyConfig
1720
from torchao.quantization import IntxWeightOnlyConfig, PerAxis, PerGroup, quantize_
1821

1922

@@ -164,6 +167,61 @@ def test_dequantize_affine_c8w_embedding_b4w_linear(self):
164167
et_prog = delegated_program.to_executorch()
165168
self._compare_outputs(et_prog, model, example_inputs)
166169

170+
def test_dequantize_codebook_linear(self):
171+
model, example_inputs = self._get_test_model()
172+
quantize_(
173+
model,
174+
CodebookWeightOnlyConfig(dtype=torch.uint2, block_size=[-1, 16]),
175+
)
176+
ep = torch.export.export(model, example_inputs)
177+
assert "torch.ops.quant.dequantize_codebook.default" in ep.graph_module.code
178+
delegated_program = executorch.exir.to_edge_transform_and_lower(
179+
ep,
180+
partitioner=[self._coreml_partitioner()],
181+
)
182+
for node in delegated_program.exported_program().graph.nodes:
183+
if node.op == "call_function":
184+
assert node.target.__name__ in [
185+
"executorch_call_delegate",
186+
"getitem",
187+
], f"Got unexpected node target after delegation: {node.target.__name__}"
188+
189+
assert (
190+
"executorch.exir.dialects.edge._ops.quant.dequantize_codebook.default"
191+
in format_delegated_graph(delegated_program.exported_program().graph_module)
192+
)
193+
194+
et_prog = delegated_program.to_executorch()
195+
self._compare_outputs(et_prog, model, example_inputs)
196+
197+
def test_dequantize_codebook_embedding(self):
198+
model, example_inputs = self._get_test_model()
199+
quantize_(
200+
model,
201+
CodebookWeightOnlyConfig(dtype=torch.uint3, block_size=[-1, 16]),
202+
lambda m, fqn: isinstance(m, torch.nn.Embedding),
203+
)
204+
ep = torch.export.export(model, example_inputs)
205+
assert "torch.ops.quant.dequantize_codebook.default" in ep.graph_module.code
206+
delegated_program = executorch.exir.to_edge_transform_and_lower(
207+
ep,
208+
partitioner=[self._coreml_partitioner()],
209+
)
210+
for node in delegated_program.exported_program().graph.nodes:
211+
if node.op == "call_function":
212+
assert node.target.__name__ in [
213+
"executorch_call_delegate",
214+
"getitem",
215+
], f"Got unexpected node target after delegation: {node.target.__name__}"
216+
217+
assert (
218+
"executorch.exir.dialects.edge._ops.quant.dequantize_codebook.default"
219+
in format_delegated_graph(delegated_program.exported_program().graph_module)
220+
)
221+
222+
et_prog = delegated_program.to_executorch()
223+
self._compare_outputs(et_prog, model, example_inputs)
224+
167225

168226
if __name__ == "__main__":
169227
test_runner = TestTorchOps()
@@ -172,3 +230,5 @@ def test_dequantize_affine_c8w_embedding_b4w_linear(self):
172230
test_runner.test_dequantize_affine_c4w_embedding()
173231
test_runner.test_dequantize_affine_c4w_linear()
174232
test_runner.test_dequantize_affine_c8w_embedding_b4w_linear()
233+
test_runner.test_dequantize_codebook_linear()
234+
test_runner.test_dequantize_codebook_embedding()

backends/arm/_passes/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
from .decompose_atanh_pass import DecomposeAtanhPass # noqa
3232
from .decompose_avg_pool2d import DecomposeAvgPool2d # noqa
3333
from .decompose_batch_norm_no_stats import DecomposeBatchNormNoStatsPass # noqa
34+
from .decompose_cosh_pass import DecomposeCoshPass # noqa
3435
from .decompose_cosine_similarity_pass import DecomposeCosineSimilarityPass # noqa
3536
from .decompose_div_pass import DecomposeDivPass # noqa
3637
from .decompose_embedding_pass import DecomposeEmbeddingPass # noqa # noqa

backends/arm/_passes/arm_pass_manager.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
DecomposeAtanPass,
3737
DecomposeAvgPool2d,
3838
DecomposeBatchNormNoStatsPass,
39+
DecomposeCoshPass,
3940
DecomposeCosineSimilarityPass,
4041
DecomposeDivPass,
4142
DecomposeEmbeddingPass,
@@ -167,6 +168,7 @@ def _tosa_FP_pipeline(self, exported_program: ExportedProgram) -> GraphModule:
167168
self.add_pass(DecomposeAcoshPass())
168169
self.add_pass(DecomposeAsinPass())
169170
self.add_pass(DecomposeAsinhPass())
171+
self.add_pass(DecomposeCoshPass())
170172
self.add_pass(DecomposeSqrtPass())
171173
self.add_pass(DecomposeAtanPass())
172174
self.add_pass(DecomposeAtanhPass())

backends/arm/_passes/decompose_avg_pool2d.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,10 @@ def call_operator(self, op, args, kwargs, meta):
4545
x = args[0]
4646
kernel_h, kernel_w = args[1]
4747
kernel_size = kernel_h * kernel_w
48-
stride_h, stride_w = args[2]
48+
if len(args) > 2 and args[2] is not None:
49+
stride_h, stride_w = args[2]
50+
else:
51+
stride_h, stride_w = kernel_h, kernel_w
4952
pad_h, pad_w = new_pad_h, new_pad_w = args[3] if len(args) > 3 else (0, 0)
5053
ceil_mode = args[4] if len(args) > 4 else False
5154
count_include_pad = args[5] if len(args) > 5 else True
@@ -108,7 +111,14 @@ def call_operator(self, op, args, kwargs, meta):
108111
x = super().call_operator(cat_op, (cat_nodes, 2), kwargs, meta)
109112
new_pad_h = 0
110113

111-
avgpool_args = (x, args[1], args[2], [new_pad_h, new_pad_w], ceil_mode, False)
114+
avgpool_args = (
115+
x,
116+
args[1],
117+
[stride_h, stride_w],
118+
[new_pad_h, new_pad_w],
119+
ceil_mode,
120+
False,
121+
)
112122
x = super().call_operator(avgpool_op, avgpool_args, kwargs, meta)
113123

114124
# Multiply by factor (kernel_size / divisor_override) if divisor_override

0 commit comments

Comments
 (0)