Skip to content

Commit dfc387b

Browse files
Arm backend: Added TOSA workflow minimal example (#13727)
Added a python notebook containing a minimalistic example of how to best use the TOSA workflow within the ARM backend. This is intended for validating and experimenting with model lowering to TOSA, and is aimed at contributors and developers, rather than production deployment. Signed-off-by: Michiel Olieslagers <[email protected]>
1 parent 010e68a commit dfc387b

File tree

1 file changed

+281
-0
lines changed

1 file changed

+281
-0
lines changed
Lines changed: 281 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,281 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "code",
5+
"execution_count": null,
6+
"metadata": {},
7+
"outputs": [],
8+
"source": [
9+
"# Copyright 2025 Arm Limited and/or its affiliates.\n",
10+
"#\n",
11+
"# This source code is licensed under the BSD-style license found in the\n",
12+
"# LICENSE file in the root directory of this source tree."
13+
]
14+
},
15+
{
16+
"cell_type": "markdown",
17+
"metadata": {},
18+
"source": [
19+
"# TOSA delegate flow example\n",
20+
"\n",
21+
"This guide walks through the complete process of running a module on Arm TOSA using ExecuTorch, with a focus on TOSA lowering exploration. \n",
22+
"This workflow is intended for validating and experimenting with model lowering to TOSA, and is aimed at contributors and developers, rather than production deployment.\n",
23+
"It’s important to note that the compilation flow and passes applied can vary based on the target, so this flow does not necessarily produce TOSA flatbuffers and PTE files which are optimal (or even compatible) with any one target.\n",
24+
"If something is not working for you, please raise a GitHub issue and tag Arm.\n",
25+
"\n",
26+
"Before you begin:\n",
27+
"1. (In a clean virtual environment with a compatible Python version) Install executorch using `./install_executorch.sh`\n",
28+
"2. Install Arm TOSA dependencies using `examples/arm/setup.sh --disable-ethos-u-deps`\n",
29+
"\n",
30+
"With all commands executed from the base `executorch` folder.\n",
31+
"\n",
32+
"\n",
33+
"\n",
34+
"*Some scripts in this notebook produces long output logs: Configuring the 'Customizing Notebook Layout' settings to enable 'Output:scrolling' and setting 'Output:Text Line Limit' makes this more manageable*"
35+
]
36+
},
37+
{
38+
"cell_type": "markdown",
39+
"metadata": {},
40+
"source": [
41+
"## AOT Flow\n",
42+
"\n",
43+
"The first step is creating the PyTorch module and exporting it. Exporting converts the python code in the module into a graph structure. The result is still runnable python code, which can be displayed by printing the `graph_module` of the exported program. "
44+
]
45+
},
46+
{
47+
"cell_type": "code",
48+
"execution_count": null,
49+
"metadata": {},
50+
"outputs": [],
51+
"source": [
52+
"import torch\n",
53+
"\n",
54+
"print(torch.__version__)\n",
55+
"\n",
56+
"class Add(torch.nn.Module):\n",
57+
" def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:\n",
58+
" return x + y\n",
59+
"\n",
60+
"example_inputs = (torch.ones(1,1,1,1),torch.ones(1,1,1,1))\n",
61+
"\n",
62+
"model = Add()\n",
63+
"model = model.eval()\n",
64+
"exported_program = torch.export.export(model, example_inputs)\n",
65+
"graph_module = exported_program.module()\n",
66+
"\n",
67+
"_ = graph_module.print_readable()"
68+
]
69+
},
70+
{
71+
"cell_type": "markdown",
72+
"metadata": {},
73+
"source": [
74+
"## TOSA backend supports both INT and FP targets.\n",
75+
"\n",
76+
"To lower the graph_module for FP targets using the TOSA backend, we run it through the default FP lowering pipeline.\n",
77+
"\n",
78+
"FP lowering can be customized for different subgraphs; the sequence shown here is the recommended workflow for TOSA. Because we are staying in floating-point precision, no calibration with example inputs is required.\n",
79+
"\n",
80+
"If you print the module again, you will see that nodes are left in FP form (or annotated with any necessary casts) without any quantize/dequantize wrappers."
81+
]
82+
},
83+
{
84+
"cell_type": "code",
85+
"execution_count": null,
86+
"metadata": {},
87+
"outputs": [],
88+
"source": [
89+
"from executorch.backends.arm.arm_backend import (\n",
90+
" ArmCompileSpecBuilder,\n",
91+
")\n",
92+
"from executorch.backends.arm.tosa_specification import TosaSpecification\n",
93+
"from torchao.quantization.pt2e.quantize_pt2e import convert_pt2e, prepare_pt2e\n",
94+
"from pathlib import Path\n",
95+
"\n",
96+
"target = \"TOSA-1.0+FP\"\n",
97+
"base_name = \"tosa_simple_example\"\n",
98+
"cwd_dir = Path.cwd()\n",
99+
"\n",
100+
"# Create a compilation spec describing the target for configuring the quantizer\n",
101+
"# Dump intermediate artifacts (in this case TOSA flat buffers) to specified location\n",
102+
"tosa_spec = TosaSpecification.create_from_string(target)\n",
103+
"spec_builder = (ArmCompileSpecBuilder()\n",
104+
" .tosa_compile_spec(tosa_spec)\n",
105+
" .dump_intermediate_artifacts_to(str(cwd_dir / base_name)))\n",
106+
"compile_spec = spec_builder.build()\n",
107+
"\n",
108+
"_ = graph_module.print_readable()\n",
109+
"\n",
110+
"# Create a new exported program using the quantized_graph_module\n",
111+
"lowered_exported_program = torch.export.export(graph_module, example_inputs)"
112+
]
113+
},
114+
{
115+
"cell_type": "markdown",
116+
"metadata": {},
117+
"source": [
118+
"To lower the graph_module for INT targets using the TOSA backend, we apply the arm_quantizer.\n",
119+
"\n",
120+
"Quantization can be performed in various ways and tailored to different subgraphs; the sequence shown here represents the recommended workflow for TOSA.\n",
121+
"\n",
122+
"This step also requires calibrating the module with representative inputs.\n",
123+
"\n",
124+
"If you print the module again, you’ll see that each node is now wrapped in quantization/dequantization nodes that embed the calculated quantization parameters."
125+
]
126+
},
127+
{
128+
"cell_type": "code",
129+
"execution_count": null,
130+
"metadata": {},
131+
"outputs": [],
132+
"source": [
133+
"from executorch.backends.arm.arm_backend import (\n",
134+
" ArmCompileSpecBuilder,\n",
135+
" get_tosa_spec,\n",
136+
")\n",
137+
"from executorch.backends.arm.quantizer import (\n",
138+
" TOSAQuantizer,\n",
139+
" get_symmetric_quantization_config,\n",
140+
")\n",
141+
"from executorch.backends.arm.tosa_specification import TosaSpecification\n",
142+
"from torchao.quantization.pt2e.quantize_pt2e import convert_pt2e, prepare_pt2e\n",
143+
"from pathlib import Path\n",
144+
"\n",
145+
"target = \"TOSA-1.0+INT\"\n",
146+
"base_name = \"tosa_simple_example\"\n",
147+
"cwd_dir = Path.cwd()\n",
148+
"\n",
149+
"# Create a compilation spec describing the target for configuring the quantizer\n",
150+
"# Dump intermediate artifacts (in this case TOSA flat buffers) to specified location\n",
151+
"tosa_spec = TosaSpecification.create_from_string(target)\n",
152+
"spec_builder = (ArmCompileSpecBuilder()\n",
153+
" .tosa_compile_spec(tosa_spec)\n",
154+
" .dump_intermediate_artifacts_to(str(cwd_dir / base_name)))\n",
155+
"compile_spec = spec_builder.build()\n",
156+
"\n",
157+
"# Create and configure quantizer to use a symmetric quantization config globally on all nodes\n",
158+
"quantizer = TOSAQuantizer(get_tosa_spec(compile_spec))\n",
159+
"operator_config = get_symmetric_quantization_config()\n",
160+
"quantizer.set_global(operator_config)\n",
161+
"\n",
162+
"# Post training quantization\n",
163+
"quantized_graph_module = prepare_pt2e(graph_module, quantizer)\n",
164+
"quantized_graph_module(*example_inputs) # Calibrate the graph module with the example input\n",
165+
"quantized_graph_module = convert_pt2e(quantized_graph_module)\n",
166+
"\n",
167+
"_ = quantized_graph_module.print_readable()\n",
168+
"\n",
169+
"# Create a new exported program using the quantized_graph_module\n",
170+
"lowered_exported_program = torch.export.export(quantized_graph_module, example_inputs)"
171+
]
172+
},
173+
{
174+
"cell_type": "markdown",
175+
"metadata": {},
176+
"source": [
177+
"The lowering in the TOSABackend happens in four steps:\n",
178+
"\n",
179+
"1. **Lowering to core Aten operator set**: Transform module to use a subset of operators applicable to edge devices. \n",
180+
"2. **Partitioning**: Find subgraphs which are supported for running on TOSA\n",
181+
"3. **Lowering to TOSA compatible operator set**: Perform transforms to make the TOSA subgraph(s) compatible with TOSA operator set\n",
182+
"4. **Serialization to TOSA**: Compiles the graph module into a TOSA graph \n",
183+
"Step 4 also prints a Network summary for each processed subgraph.\n",
184+
"\n",
185+
"All of this happens behind the scenes in `to_edge_transform_and_lower`. Printing the graph module shows that what is left in the graph is two quantization nodes for `x` and `y` going into an `executorch_call_delegate` node, followed by a dequantization node."
186+
]
187+
},
188+
{
189+
"cell_type": "code",
190+
"execution_count": null,
191+
"metadata": {},
192+
"outputs": [],
193+
"source": [
194+
"from executorch.backends.arm.tosa_partitioner import TOSAPartitioner\n",
195+
"from executorch.exir import (\n",
196+
" EdgeCompileConfig,\n",
197+
" ExecutorchBackendConfig,\n",
198+
" to_edge_transform_and_lower,\n",
199+
")\n",
200+
"from executorch.extension.export_util.utils import save_pte_program\n",
201+
"\n",
202+
"# Create partitioner from compile spec\n",
203+
"partitioner = TOSAPartitioner(compile_spec)\n",
204+
"\n",
205+
"# Lower the exported program to the TOSA backend\n",
206+
"edge_program_manager = to_edge_transform_and_lower(\n",
207+
" lowered_exported_program,\n",
208+
" partitioner=[partitioner],\n",
209+
" compile_config=EdgeCompileConfig(\n",
210+
" _check_ir_validity=False,\n",
211+
" ),\n",
212+
" )\n",
213+
"\n",
214+
"# Convert edge program to executorch\n",
215+
"executorch_program_manager = edge_program_manager.to_executorch(\n",
216+
" config=ExecutorchBackendConfig(extract_delegate_segments=False)\n",
217+
" )\n",
218+
"\n",
219+
"executorch_program_manager.exported_program().module().print_readable()\n",
220+
"\n",
221+
"# Save pte file\n",
222+
"pte_name = base_name + \".pte\"\n",
223+
"pte_path = cwd_dir / base_name / pte_name\n",
224+
"save_pte_program(executorch_program_manager, str(pte_path))\n",
225+
"assert pte_path.exists(), \"Build failed; no .pte-file found\""
226+
]
227+
},
228+
{
229+
"cell_type": "markdown",
230+
"metadata": {},
231+
"source": [
232+
"## Use TOSA reference model to verify TOSA graph\n",
233+
"\n",
234+
"After the AOT compilation flow is done, the resulting lowered TOSA graph can be verified using the TOSA reference model tool."
235+
]
236+
},
237+
{
238+
"cell_type": "code",
239+
"execution_count": null,
240+
"metadata": {},
241+
"outputs": [],
242+
"source": [
243+
"import subprocess\n",
244+
"import tosa_reference_model as reference_model\n",
245+
"from executorch.backends.arm.test.runner_utils import TosaReferenceModelDispatch\n",
246+
"\n",
247+
"# Run TOSA graph through reference model using sample inputs\n",
248+
"with TosaReferenceModelDispatch():\n",
249+
" executorch_program_manager.exported_program().module()(*example_inputs)"
250+
]
251+
},
252+
{
253+
"cell_type": "code",
254+
"execution_count": null,
255+
"metadata": {},
256+
"outputs": [],
257+
"source": []
258+
}
259+
],
260+
"metadata": {
261+
"kernelspec": {
262+
"display_name": "Python 3 (ipykernel)",
263+
"language": "python",
264+
"name": "python3"
265+
},
266+
"language_info": {
267+
"codemirror_mode": {
268+
"name": "ipython",
269+
"version": 3
270+
},
271+
"file_extension": ".py",
272+
"mimetype": "text/x-python",
273+
"name": "python",
274+
"nbconvert_exporter": "python",
275+
"pygments_lexer": "ipython3",
276+
"version": "3.10.16"
277+
}
278+
},
279+
"nbformat": 4,
280+
"nbformat_minor": 4
281+
}

0 commit comments

Comments
 (0)