Lab 02 — Custom torch.compile Backend
Phase: 04 — torch.compile, FX Graph & Custom Backends | Difficulty: ⭐⭐⭐⭐⭐ | Time: 4–5 hours
Implement a custom backend that classifies ops as NPU-eligible or CPU-fallback and substitutes them in the FX graph.
What you build
- NPU op registry with
@register_npu_opdecorator classify_nodes— analyze FX graph for NPU vs CPU opstransform_graph— replace ATen ops with registered NPU ops via FX node substitutionnpu_backend—torch.compile(model, backend=npu_backend)callableverify_backend_correctness— compare eager vs compiled numerics
Key concepts
| Concept | What to understand |
|---|---|
| Backend callable | (gm: GraphModule, example_inputs) → Callable |
| ATen ops | aten.mm.default, aten.relu.default — canonical op names |
| Node replacement | graph.inserting_after(node) + node.replace_all_uses_with |
| Correctness gate | Max absolute diff < 1e-4 between eager and compiled |
Files
| File | Purpose |
|---|---|
lab.py | Stubs with TODO markers |
solution.py | Complete working implementation |
test_lab.py | pytest suite |
requirements.txt | Dependencies |
Run
pip install -r requirements.txt
python lab.py
pytest test_lab.py -v