diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index 843dee2c7..e5ba2bfbf 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -50,13 +50,13 @@ and same device, two transformers: 5.x rewrote the MoE block to remove the graph breaks (12 graphs -> 1), and paid for it in fallbacks. The wrong number came with them. -**WHAT TO DO INSTEAD.** A rewrite in `pytorchsim/frontend/rewrite_fx_graph.py`, -written in aten ops the backend already lowers, so the work stays in the graph. -That file exists for exactly this and says so. Note that casting an operand until -the CPU kernel accepts it is only half the job: the histc decomposition there -still leaves `aten.histc` as an extern call, and its own docstring names the -device-side form it should have been (`(x == bin).sum()` against `arange(bins)` — -one elementwise and one reduce). +**WHAT TO DO INSTEAD.** A rewrite in `pytorchsim/frontend/inductor/post_grad_pass.py`, +the npu's `device_custom_pass`, written in aten ops Inductor lowers as they are +(the pass runs after decomposition), so the work stays in the graph. Casting an +operand until the CPU kernel accepts it is only half the job: histc, for one, is +counted there with aten's own bin rule, so no histc leaves the device. An op +with a Triton kernel of its own (topk, grouped_mm, SDPA) registers it through +torch.library instead, in its own file under `pytorchsim/frontend/dispatcher/`. **IF YOU CANNOT REMOVE ONE,** say so in those words and name it. A fallback left in place is a known hole in what "this model runs" means, and it belongs in the @@ -67,17 +67,17 @@ report next to the number it produced — never folded into a pass. | Path | Purpose | |---|---| | `pytorchsim/config.py` | The central settings reader, shared by every stage | -| `pytorchsim/frontend/` | The graph side, where the framework is met: `rewrite_fx_graph.py` (our FX graph rewrites, so ops with no `npu` kernel stay on the device) and `inductor_patches.py` (decompositions, template and tile choices, the patches that make Inductor's Triton route serve `npu`) | +| `pytorchsim/frontend/` | The graph side, where the framework is met: `post_grad_pass.py` (the npu's post-grad pass, Inductor's `device_custom_pass`: rewrites so ops with no `npu` kernel stay on the device), `triton_ops/` (`topk.py`, `grouped_mm.py`, `attention.py`: ops with a Triton kernel of their own, SDPA's fused ones among them, through torch.library) `choices.py` (NPUChoices, Inductor's `inductor_choices_class`: conv tiles, persistent reductions, splits, recorded picks; the mm/bmm template heuristics; `pinned_blocks`), `selection.py` (how a template's config is picked: TOGSim cycles in timing mode), `triton_gpu.py` (npu as a Triton GPU to Inductor) and `inductor_patches.py` (the lowering patches with no Inductor hook, npu's conv decompositions, and `install()`, which applies everything) | | `pytorchsim/contract.py` | What the stages share, so none of them imports another for it: the axes and programs of a launch, how far a strided layout reaches in storage, and the kernel workdir (the manifest and artifacts the compiler left, and each process's launch directory) | -| `pytorchsim/codegen/` | What runs while Inductor generates code: `inductor_hooks.py` (the scheduling and wrapper classes registered for `npu`; Inductor writes the Triton source, these wrap it), `kernel_metadata.py` (what the compile step needs from an Inductor kernel), `tiling.py` (block sizes, a template's grid, this machine's mm tiles), `verify.py` (the per-kernel CPU cross-check, both the lines put in the wrapper and the check they call) | -| `pytorchsim/driver/` | Building a kernel and having it run: `codecache.py` (the compile entry point, the cache and the identity that admits it, the launcher), `select.py` (a template's config: Inductor's selection timed on TOGSim, and the recorded picks), `autotune.py` (smaller pinned blocks when the compiler says too big), `compiler_input.py` (what the compiler is handed: the rewritten Triton source and the KernelSpec file), `compiler_bridge.py` (PyTorchSim-Triton-Backend in a subprocess, the target description) | +| `pytorchsim/frontend/inductor/codegen/` | What runs while Inductor generates code: `inductor_hooks.py` (the scheduling and wrapper classes registered for `npu`; Inductor writes the Triton source, these wrap it), `kernel_metadata.py` (what the compile step needs from an Inductor kernel), `tiling.py` (block sizes, a template's grid, this machine's mm tiles), `verify.py` (the per-kernel CPU cross-check, both the lines put in the wrapper and the check they call) | +| `pytorchsim/backend/` | Building a kernel and having it run: `codecache.py` (the compile entry point, the cache and the identity that admits it, the launcher), `select.py` (a template's config: Inductor's selection timed on TOGSim, and the recorded picks), `autotune.py` (smaller pinned blocks when the compiler says too big), `compiler_input.py` (what the compiler is handed: the rewritten Triton source and the KernelSpec file), `compiler_bridge.py` (PyTorchSim-Triton-Backend in a subprocess, the target description) | | `pytorchsim/simulator/` | What runs a kernel object: `functional.py` (tensors to disk, Spike, tensors back), `timing.py` (gem5 tile cycles, the cycle and unit tables beside the TOG, TOGSim), `togsim.py` (`TOGSimProcess`, the TOGSim process, and `poisson_request_generator`), `wallclock.py` (where the run's own time went) | | `device/` | C++ PyTorch backend registering the `npu` device. Built as a pip-installed package via `setup.py`. Based on `torch_openreg` (PrivateUse1 example). Produces `_C.cpython-*.so` | | `$TOGSIM_DIR` (not in this repo) | TOGSim, the repository PSAL-POSTECH/TOGSim, as the compiler checkout carries it: `$TORCHSIM_COMPILE_DIR/third_party/TOGSim`. C++ source in `src/` and `include/` (`include/togsim_runtime.h` is the C ABI a TOG is compiled against), the built `build/bin/Simulator`, and `configs/` | | `$TOGSIM_DIR/configs/` | TOGSim machine files (YAML); `config.CONFIG_TOGSIM_CONFIG_DIR`. `TORCHSIM_TARGET` names one (`tpuv6e` by default, i.e. `tpuv6e.yml`) | -| `tests/` | Op- and model-level tests organized under `ops//` (elementwise, reduce, gemm, conv, attention, view, sort, misc, fusion), `models//` (Llama, Mixtral8x7B, DeepSeek, Diffusion, MoE, MLP, MobileNet, Yolov5) plus single-file model tests (test_resnet, test_transformer, test_vit, test_mlp, test_single_perceptron), and `system/` (eager, vectorops, TOGSim session and result, selection). Shared helper: `tests/_pytorchsim_utils.py`. **Which of them pass is `scripts/ci/triton_route_passing.txt`**; the rest are known gaps, swept and reported by `scripts/ci/triton_route_sweep.py --all` | +| `tests/` | Op- and model-level tests organized under `ops//` (elementwise, reduce, gemm, conv, attention, view, sort, misc, fusion), `models//` (Llama, Mixtral8x7B, DeepSeek, Diffusion, MoE, MLP, MobileNet, Yolov5) plus single-file model tests (test_resnet, test_transformer, test_vit, test_mlp, test_single_perceptron), and `system/` (eager, vectorops, TOGSim session and result, selection). Shared helper: `tests/result_check.py` (`check_result`). **Which of them pass is `scripts/ci/triton_route_passing.txt`**; the rest are known gaps, swept and reported by `scripts/ci/triton_route_sweep.py --all` | | `experiments/artifact/` | Paper reproduction scripts (`cycle_validation/run_cycle.sh`, `speedup/run_speedup.sh`) | -| `scripts/` | Dev tools (`util_viewer.py`, `trace_timeline.py`, `op_coverage.py`, `clear_codegen_cache.sh`, `setup_worktree.sh`) and CI helpers (`ci/`). `build_from_source.sh` builds the compiler and its simulators through PTB | +| `scripts/` | Dev tools (`util_viewer.py`, `trace_timeline.py`, `clear_codegen_cache.sh`, `setup_worktree.sh`) and CI helpers (`ci/`). `build_from_source.sh` builds the compiler and its simulators through PTB | | `docker/` | CI's images: `Dockerfile.base` (the compiler's published image at the pin plus the test stack) and `Dockerfile` (this tree on top of it), each with its own `.dockerignore`. The build context is the repository root | | `third_party/` | Version pins, no code: `pytorchsim-triton-backend.json` (the compiler commit, which is also what pins TOGSim) and `github-releases.json` | | `togsim_results/` | TOGSim log + trace dump directory (per-run) | @@ -111,7 +111,7 @@ export TORCHSIM_FUNCTIONAL_MODE=0 # skips Spike; outputs are not computed, so reach is the one that owns it. **To find which op a wrong result first diverges at** (per-kernel CPU cross-check; -sub-option of functional mode, `pytorchsim/codegen/verify.py`). Set `TORCHSIM_FUNCTIONAL_VERIFY_PER_KERNEL=1`, +sub-option of functional mode, `pytorchsim/frontend/inductor/codegen/verify.py`). Set `TORCHSIM_FUNCTIONAL_VERIFY_PER_KERNEL=1`, clear the codegen cache, and re-run: each compiled kernel's output is compared to a CPU golden and the run stops at the first divergent kernel, naming the op and offending indices. @@ -173,7 +173,7 @@ with torch.npu.TOGSimulator(config_path=...): ## Where to look for X -- **Adding a new op:** nothing here, usually — Inductor's own Triton lowerings emit the kernel and PyTorchSim-Triton-Backend lowers it. What lives here is our FX graph rewrites, `rewrite_fx_graph.py`: decompositions and post-grad passes for ops with no `npu` kernel (histc, polar, topk, transformers' grouped_mm, complex arithmetic). GEMM/BMM tile selection: `pytorchsim/codegen/tiling.py` (`gemm_tile_candidates`). Kernel source fixups before the compiler sees them: `pytorchsim/driver/compiler_input.py`. +- **Adding a new op:** nothing here, usually — Inductor's own Triton lowerings emit the kernel and PyTorchSim-Triton-Backend lowers it. What lives here is the npu's post-grad pass, `post_grad_pass.py`, for ops with no `npu` kernel (histc, polar, a row times a matrix, complex arithmetic), and torch.library kernels for ops with a Triton kernel of their own (`triton_ops/topk.py`, `triton_ops/grouped_mm.py`, `triton_ops/attention.py`). GEMM/BMM tile selection: `pytorchsim/frontend/inductor/codegen/tiling.py` (`gemm_tile_candidates`). Kernel source fixups before the compiler sees them: `pytorchsim/backend/compiler_input.py`. - **Adding a PyTorch device op:** `device/csrc/aten/native/*` (Minimal/Extra split mirrors `torch_openreg`). - **TOGSim hardware model changes:** in the TOGSim repository, `src/{Core,Dram,Interconnect,L2Cache,Tile,TileGraph}.cc` + matching `include/*.h`. They reach this repository when the compiler pins that TOGSim commit and this repository pins that compiler commit. - **TOG generation:** the compiler emits the tile-operation-graph (TOG) as C++, compiles it to `tog.so` against TOGSim's `togsim_runtime.h` and records the compute type of each tile (`pytorchsim_triton_compiler/lowering/tog/`; `tog_cpp`, `tog_so` and `tile_types` in `kernel.json`); this repo measures the tiles under gem5 and writes `tog_cycles.tsv` and `tog_units.tsv` beside the TOG (`pytorchsim/simulator/timing.py`); TOGSim replays the TOG into a TileGraph (`tog_to_tilegraph`). diff --git a/device/csrc/aten/native/Extra.cpp b/device/csrc/aten/native/Extra.cpp index b72c7eaed..c6080d6f3 100644 --- a/device/csrc/aten/native/Extra.cpp +++ b/device/csrc/aten/native/Extra.cpp @@ -31,7 +31,7 @@ int64_t _fused_sdp_choice( // The overrideable op carries a call it can state whole: no mask, no dropout, no gradient (its // npu kernel has no backward), H dividing Hq. Whether a fused kernel then takes it is - // pytorchsim/frontend/attention.py's fused_plan alone; what that declines runs SDPA's math. + // pytorchsim/frontend/dispatcher/attention.py's fused_plan alone; what that declines runs SDPA's math. const int64_t Hq = query.size(-3), H = key.size(-3); const bool grad = at::GradMode::is_enabled() && (query.requires_grad() || key.requires_grad() || value.requires_grad()); diff --git a/device/torch_openreg/__init__.py b/device/torch_openreg/__init__.py index 1e407115a..934cd6304 100644 --- a/device/torch_openreg/__init__.py +++ b/device/torch_openreg/__init__.py @@ -18,21 +18,9 @@ sys.path.append(os.environ.get('TORCHSIM_DIR', default='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/workspace/PyTorchSim')) import pytorchsim.config # noqa: F401 -from pytorchsim.frontend import inductor_patches as _inductor_patches -from pytorchsim.frontend import rewrite_fx_graph as _rewrite_fx_graph - -_rewrite_fx_graph.install() -_inductor_patches.install() - -# The `npu` codegen route: Inductor's own Triton codegen, lowered by the -# compiler passes. Registered here because Inductor registers a backend per -# device, once. -from pytorchsim.codegen import TritonNPUScheduling, TritonNPUWrapperCodegen -torch._inductor.codegen.common.register_backend_for_device( - "npu", - TritonNPUScheduling, - TritonNPUWrapperCodegen -) +from pytorchsim import frontend as _frontend + +_frontend.install() torch_openreg.openreg.init() torch_openreg.openreg.register_eager_to_compile( @@ -40,5 +28,5 @@ sys.modules['torch.npu'] = torch_openreg.openreg def _autoload(): - # It is a placeholder function here to be registered as an entry point. + """A placeholder registered as torch's device-backend entry point.""" pass \ No newline at end of file diff --git a/device/torch_openreg/openreg/__init__.py b/device/torch_openreg/openreg/__init__.py index 8d5f7c26f..19bc5f162 100644 --- a/device/torch_openreg/openreg/__init__.py +++ b/device/torch_openreg/openreg/__init__.py @@ -2,12 +2,9 @@ import threading import torch -from torch._dynamo.device_interface import register_interface_for_device import torch_openreg._C # type: ignore[misc] from . import meta # noqa: F401 -from . import extension_device_op_overrides -from .extension_device_interface import ExtensionDeviceInterface _initialized = False _default_streams = {} # Dictionary to store default streams per device @@ -80,7 +77,6 @@ def _lazy_init(): return torch_openreg._C._init() - register_interface_for_device(custom_device(), ExtensionDeviceInterface) _initialized = True # Create default streams for all devices diff --git a/pytorchsim/driver/__init__.py b/pytorchsim/backend/__init__.py similarity index 100% rename from pytorchsim/driver/__init__.py rename to pytorchsim/backend/__init__.py diff --git a/pytorchsim/driver/autotune.py b/pytorchsim/backend/autotune.py similarity index 94% rename from pytorchsim/driver/autotune.py rename to pytorchsim/backend/autotune.py index 0eccc2bfc..6858a0125 100644 --- a/pytorchsim/driver/autotune.py +++ b/pytorchsim/backend/autotune.py @@ -1,14 +1,14 @@ """A kernel the compiler refuses as too big is retried at smaller blocks. A kernel's pinned blocks (its fixed_config) halve when the compiler says they do not fit. A -template's own blocks are its config, which Inductor chose (driver/select.py), and are built as +template's own blocks are its config, which Inductor chose (backend/select.py), and are built as rendered. """ import copy import itertools -from pytorchsim.driver import compiler_bridge +from pytorchsim.backend import compiler_bridge def too_big(exc): diff --git a/pytorchsim/driver/codecache.py b/pytorchsim/backend/codecache.py similarity index 99% rename from pytorchsim/driver/codecache.py rename to pytorchsim/backend/codecache.py index 4c1cea51a..fa603a3af 100644 --- a/pytorchsim/driver/codecache.py +++ b/pytorchsim/backend/codecache.py @@ -19,7 +19,7 @@ from pytorchsim import config from pytorchsim import contract -from pytorchsim.driver import autotune, compiler_bridge, compiler_input +from pytorchsim.backend import autotune, compiler_bridge, compiler_input from pytorchsim.simulator import functional, timing, wallclock logger = config.setup_logger() diff --git a/pytorchsim/driver/compiler_bridge.py b/pytorchsim/backend/compiler_bridge.py similarity index 96% rename from pytorchsim/driver/compiler_bridge.py rename to pytorchsim/backend/compiler_bridge.py index 718118f81..a7f6e8bae 100644 --- a/pytorchsim/driver/compiler_bridge.py +++ b/pytorchsim/backend/compiler_bridge.py @@ -121,11 +121,8 @@ def compiler_env(): def run_pipeline(spec_path, workdir, to_stage="torchsim-compile", tog=False, timeout=1800): - """Drive the compiler's stages over `spec_path`, writing artifacts into `workdir`. - - Stops at `to_stage`, by default `torchsim-compile` -- the ELF: spike and verify - want tensors and a per-kernel reference this route has no graph-level answer for. - """ + """Drive the compiler's stages over `spec_path`, writing artifacts into `workdir`, up to + `to_stage` (by default `torchsim-compile`, the ELF).""" cmd = [config.CONFIG_TORCHSIM_COMPILE_PYTHON, os.path.join(compiler_dir(), "pytorchsim-triton-compiler"), spec_path, "--from", "triton-compile", "--to", to_stage, "--workdir", workdir] + (["--tog"] if tog else []) diff --git a/pytorchsim/driver/compiler_input.py b/pytorchsim/backend/compiler_input.py similarity index 98% rename from pytorchsim/driver/compiler_input.py rename to pytorchsim/backend/compiler_input.py index 6cc3a96a3..fda3cd346 100644 --- a/pytorchsim/driver/compiler_input.py +++ b/pytorchsim/backend/compiler_input.py @@ -8,7 +8,7 @@ from pytorchsim import contract from pytorchsim.contract import SpecIncomplete -from pytorchsim.driver import compiler_bridge +from pytorchsim.backend import compiler_bridge _C_TYPE = {"i32": "int32_t", "i64": "int64_t", "fp32": "float"} @@ -35,7 +35,7 @@ def scalar_args(meta): SPEC_TEMPLATE = '''\ -"""Generated by pytorchsim/driver/compiler_input.py -- do not edit. +"""Generated by pytorchsim/backend/compiler_input.py -- do not edit. Inductor kernel {kernel_name!r}: the compiler takes its @triton.jit function, with the block sizes pinned as constexprs, so the launch shape is static. See compiler_input.py for why. diff --git a/pytorchsim/driver/select.py b/pytorchsim/backend/select.py similarity index 98% rename from pytorchsim/driver/select.py rename to pytorchsim/backend/select.py index d2e4d9091..749eb69b0 100644 --- a/pytorchsim/driver/select.py +++ b/pytorchsim/backend/select.py @@ -17,8 +17,8 @@ import time from pytorchsim import config, contract -from pytorchsim.codegen import kernel_metadata -from pytorchsim.driver import autotune, compiler_bridge, compiler_input +from pytorchsim.frontend.inductor.codegen import kernel_metadata +from pytorchsim.backend import autotune, compiler_bridge, compiler_input from pytorchsim.simulator import timing logger = config.setup_logger() @@ -181,7 +181,7 @@ def record_path(): def identity(): """What a recorded pick was timed with: the compiler this tree pins, the machine and TOGSim's runtime ABI.""" - from pytorchsim.driver import codecache + from pytorchsim.backend import codecache with open(PIN_FILE) as f: pin = json.load(f)["pytorchsim_triton_backend"]["ref"] whole = codecache.identity() diff --git a/pytorchsim/config.py b/pytorchsim/config.py index 611102b5b..f8a1efb82 100644 --- a/pytorchsim/config.py +++ b/pytorchsim/config.py @@ -61,13 +61,13 @@ def __getattr__(name): if name == "CONFIG_TORCHSIM_TARGET": return os.environ.get("TORCHSIM_TARGET") or "tpuv6e" if name == "CONFIG_MACHINE": - from pytorchsim.driver import compiler_bridge + from pytorchsim.backend import compiler_bridge return compiler_bridge.target() if name == "CONFIG_MACHINE_FILE": - from pytorchsim.driver import compiler_bridge + from pytorchsim.backend import compiler_bridge return compiler_bridge.target().file if name == "CONFIG_NUM_CORES": - from pytorchsim.driver import compiler_bridge + from pytorchsim.backend import compiler_bridge with open(compiler_bridge.target().file) as f: return yaml.safe_load(f)["num_cores"] diff --git a/pytorchsim/frontend/__init__.py b/pytorchsim/frontend/__init__.py index e35bfeaf4..3c8c77fe0 100644 --- a/pytorchsim/frontend/__init__.py +++ b/pytorchsim/frontend/__init__.py @@ -1 +1,24 @@ -"""The graph side: FX rewrites and the Inductor patches that make its Triton route serve npu.""" +"""What PyTorchSim plugs into torch.compile, one package per layer it meets: + + dynamo/ npu's DeviceInterface + inductor/ npu as an Inductor backend and the patches to Inductor's passes, choices and codegen + dispatcher/ ops with a Triton kernel of their own, registered at the npu dispatch keys + +What compiles and runs a kernel after Inductor is pytorchsim/backend and pytorchsim/simulator. +""" + + +def install(): + """Plug npu into every layer, once.""" + global _installed + if _installed: + return + from . import dispatcher, dynamo, inductor + + dynamo.install() + inductor.install() + dispatcher.install() + _installed = True + + +_installed = False diff --git a/pytorchsim/frontend/dispatcher/__init__.py b/pytorchsim/frontend/dispatcher/__init__.py new file mode 100644 index 000000000..676dbd02a --- /dev/null +++ b/pytorchsim/frontend/dispatcher/__init__.py @@ -0,0 +1,11 @@ +"""Ops the npu takes as a Triton kernel of our own: each module registers its op's npu kernel through +torch.library and launches the kernel as a triton_op (torchsim::). Rewrites into aten ops are +frontend/post_grad_pass.py instead.""" + + +def install(): + """Register every op's npu kernel, once each.""" + from . import attention, grouped_mm, topk + attention.install() + grouped_mm.install() + topk.install() diff --git a/pytorchsim/frontend/attention.py b/pytorchsim/frontend/dispatcher/attention.py similarity index 99% rename from pytorchsim/frontend/attention.py rename to pytorchsim/frontend/dispatcher/attention.py index f3d92d196..50fff9ccb 100644 --- a/pytorchsim/frontend/attention.py +++ b/pytorchsim/frontend/dispatcher/attention.py @@ -157,7 +157,7 @@ def _decode_tiles(GP, BKV, D, esize): def _fits(tiles): """Whether `tiles` fit one lane's scratchpad budget, and each is a tensor Triton builds.""" - from pytorchsim.codegen import tiling + from pytorchsim.frontend.inductor.codegen import tiling big = tiling.triton_max_numel() return (all(r * c <= big for r, c, _ in tiles) and _lane_bytes(tiles) <= int(config.CONFIG_MACHINE.spad_budget)) @@ -278,7 +278,7 @@ def install(): backend key, where a call made under inference_mode lands. Count each fused kernel launch.""" global _lib if _lib is None: - from pytorchsim.driver import codecache + from pytorchsim.backend import codecache codecache.observe_launches(_prefill_kernel, lambda: _count("prefill")) codecache.observe_launches(_decode_kernel, lambda: _count("decode")) _lib = torch.library.Library("aten", "IMPL") diff --git a/pytorchsim/frontend/grouped_mm.py b/pytorchsim/frontend/dispatcher/grouped_mm.py similarity index 77% rename from pytorchsim/frontend/grouped_mm.py rename to pytorchsim/frontend/dispatcher/grouped_mm.py index fae30a1ed..3b8e06716 100644 --- a/pytorchsim/frontend/grouped_mm.py +++ b/pytorchsim/frontend/dispatcher/grouped_mm.py @@ -1,6 +1,6 @@ -"""aten._grouped_mm on the npu (2-D A grouped by offs, times 3-D B) as one Triton kernel in fused_moe form: a -program is a block of BM rows of one group, its group, first row and row count read from a table the TOG reads as -runtime attributes; a block without rows runs its K loop zero times. Registered through torch.library.""" +"""aten._grouped_mm and transformers' grouped_mm_fallback on the npu (2-D A grouped by offs, times 3-D B) as one +Triton kernel in fused_moe form: a program is a block of BM rows of one group, its group, first row and row count +read from a table the TOG reads as runtime attributes. Both ops register one entry through torch.library.""" import torch import triton @@ -14,7 +14,7 @@ def _tiles(n, k, esize): """(BM, BN, BK): BM the lanes, BN and BK the largest tile the machine's mm rule gives a BM-row block.""" - from pytorchsim.codegen import tiling + from pytorchsim.frontend.inductor.codegen import tiling bm = int(config.CONFIG_MACHINE.vector_lanes) acc = 4 _, tn, tk = tiling.gemm_tile_candidates(bm, n, k, acc + esize, esize)[0] @@ -111,14 +111,22 @@ def _aten_grouped_mm(a, b, offs=None, bias=None, out_dtype=None): return grouped_mm(a, b, offs) -_lib = None +def _transformers_grouped_mm_fallback(input, weight, offs): + """transformers' grouped_mm_fallback, which it calls instead of aten._grouped_mm (under torch.compile when the + weight is not bf16), on aten._grouped_mm's route.""" + return _aten_grouped_mm(input, weight, offs) + + +_libs = [] def install(): - """Register aten._grouped_mm's npu kernel above autograd and functionalization, and at the backend key, - where a call made under inference_mode lands.""" - global _lib - if _lib is None: - _lib = torch.library.Library("aten", "IMPL") - for key in ("AutogradPrivateUse1", "PrivateUse1"): - _lib.impl("_grouped_mm", _aten_grouped_mm, key) + """Register the npu kernel of aten._grouped_mm and of transformers::grouped_mm_fallback above autograd and + functionalization, and at the backend key, where a call made under inference_mode lands.""" + if not _libs: + for ns, op, fn in (("aten", "_grouped_mm", _aten_grouped_mm), + ("transformers", "grouped_mm_fallback", _transformers_grouped_mm_fallback)): + lib = torch.library.Library(ns, "IMPL") + for key in ("AutogradPrivateUse1", "PrivateUse1"): + lib.impl(op, fn, key) + _libs.append(lib) diff --git a/pytorchsim/frontend/topk.py b/pytorchsim/frontend/dispatcher/topk.py similarity index 98% rename from pytorchsim/frontend/topk.py rename to pytorchsim/frontend/dispatcher/topk.py index f4bf9b914..457360489 100644 --- a/pytorchsim/frontend/topk.py +++ b/pytorchsim/frontend/dispatcher/topk.py @@ -73,7 +73,7 @@ def topk_plan(x, k, dim): """(the kernel's blocks, None) when it takes topk of `x` along `dim`, else (None, why). A program takes a row on each lane, those past the last masked, halved while its tiles overrun the scratchpad budget.""" - from pytorchsim.frontend.attention import _fits + from pytorchsim.frontend.dispatcher.attention import _fits if not x.is_floating_point(): return None, f"{x.dtype} is not a floating dtype" if x.dim() == 0 or x.numel() == 0: @@ -175,7 +175,7 @@ def install(): key, where a call made under inference_mode lands. Count each kernel launch.""" global _lib if _lib is None: - from pytorchsim.driver import codecache + from pytorchsim.backend import codecache codecache.observe_launches(_topk_kernel, lambda: _count("kernel")) _lib = torch.library.Library("aten", "IMPL") for key in ("AutogradPrivateUse1", "PrivateUse1"): diff --git a/pytorchsim/frontend/dynamo/__init__.py b/pytorchsim/frontend/dynamo/__init__.py new file mode 100644 index 000000000..c3b4ad089 --- /dev/null +++ b/pytorchsim/frontend/dynamo/__init__.py @@ -0,0 +1,8 @@ +"""What npu plugs into Dynamo: its DeviceInterface (device_interface.py).""" + + +def install(): + """Register npu with Dynamo.""" + from . import device_interface + + device_interface.install() diff --git a/device/torch_openreg/openreg/extension_device_interface.py b/pytorchsim/frontend/dynamo/device_interface.py similarity index 83% rename from device/torch_openreg/openreg/extension_device_interface.py rename to pytorchsim/frontend/dynamo/device_interface.py index 9df2df936..14328aae2 100644 --- a/device/torch_openreg/openreg/extension_device_interface.py +++ b/pytorchsim/frontend/dynamo/device_interface.py @@ -1,7 +1,12 @@ +"""npu's DeviceInterface for Dynamo: the device, stream and properties queries Dynamo and Inductor's +compile workers make, answered for the simulated device.""" + import torch from torch._dynamo.device_interface import DeviceInterface, caching_worker_current_devices, caching_worker_device_properties -class _ExtensionDeviceProperties: # FIXME: Dummy property values +class _ExtensionDeviceProperties: + """Placeholder properties for the simulated device; multi_processor_count is what Inductor reads as + its SM count.""" name: str = "Extension_device" platform_name: str vendor: str @@ -20,7 +25,7 @@ class _ExtensionDeviceProperties: # FIXME: Dummy property values has_subgroup_matrix_multiply_accumulate_tensor_float32: bool has_subgroup_2d_block_io: bool total_memory: int - multi_processor_count: int = 128 # gpu_subslice_count, num_sm + multi_processor_count: int = 128 architecture: int type: str @@ -81,3 +86,10 @@ def is_bf16_supported(including_emulation: bool = False) -> bool: is a silent CPU fallback that simulates nothing. """ return True + + +def install(): + """Register ExtensionDeviceInterface as npu's DeviceInterface.""" + from torch._dynamo.device_interface import register_interface_for_device + + register_interface_for_device("npu", ExtensionDeviceInterface) diff --git a/pytorchsim/frontend/inductor/__init__.py b/pytorchsim/frontend/inductor/__init__.py new file mode 100644 index 000000000..295faf4b1 --- /dev/null +++ b/pytorchsim/frontend/inductor/__init__.py @@ -0,0 +1,41 @@ +"""What npu plugs into Inductor, in the order Inductor meets it: + + registration.py npu as an Inductor backend: GPU_TYPES, Triton present, codegen and op overrides + device_op_overrides.py the device code Inductor writes into an npu wrapper + post_grad_pass.py the FX graph after Inductor's post-grad passes (device_custom_pass) + lowering.py lowering patches with no Inductor hook, npu's conv decompositions + choices.py NPUChoices: conv tiles, pinned blocks, reductions, recorded template picks + selection.py how a template's config is picked (TOGSim cycles in timing mode) + codegen/ the scheduling and wrapper Inductor generates through, kernel metadata, tiling +""" + +from pytorchsim import config + + +def install(): + """Register npu with Inductor and apply every patch here, then Inductor's config.""" + from . import choices, lowering, registration, selection + + registration.install() + choices.install() + lowering.install() + selection.install() + _configure_inductor() + + +def _configure_inductor(): + """mm/conv template autotune on, at compile time off. In timing mode a template with an epilogue + is picked by its fused cycles, Inductor timing the top configs one at a time in this process + (TritonNPUScheduling.benchmark_codegened_module); select records picks, so its cache stays off.""" + from torch._inductor import config as inductor_config + + inductor_config.max_autotune_gemm = True + inductor_config.max_autotune_gemm_backends = "ATEN,TRITON" + inductor_config.max_autotune_conv_backends = "ATEN,TRITON" + inductor_config.triton.autotune_at_compile_time = False + timed = bool(config.pytorchsim_timing_mode) + inductor_config.benchmark_epilogue_fusion = timed + inductor_config.max_epilogue_benchmarked_choices = config.codegen_autotune_template_topk + inductor_config.autotune_local_cache = False + if timed: + inductor_config.compile_threads = 1 diff --git a/pytorchsim/frontend/inductor/choices.py b/pytorchsim/frontend/inductor/choices.py new file mode 100644 index 000000000..cf446f0a4 --- /dev/null +++ b/pytorchsim/frontend/inductor/choices.py @@ -0,0 +1,287 @@ +"""The choices npu makes differently from Inductor's, through Inductor's own hooks: NPUChoices +(config.inductor_choices_class) for conv tiles, persistent reductions, splits and recorded template +picks, and register_template_heuristic for the mm/bmm tiles; pinned_blocks fixes a kernel's blocks. +""" + +import threading + +import torch + +from pytorchsim import config +from pytorchsim.frontend.inductor.codegen import tiling +from pytorchsim.frontend.inductor.registration import lowering_npu + +logger = config.setup_logger() + +conv_groups = threading.local() + +_NPU_CHOICES = None + + +def install(): + """Make NPUChoices Inductor's choices, unless something else already is, and register the + mm/bmm/addmm/baddbmm heuristics.""" + from torch._inductor import config as inductor_config + + if inductor_config.inductor_choices_class is None: + inductor_config.inductor_choices_class = _npu_choices_class() + _register_template_heuristics() + + +def _npu_choices_class(): + """NPUChoices, built once: Inductor's lookup-table choices, with this machine's conv tiles, + reduction policy and recorded template picks.""" + global _NPU_CHOICES + if _NPU_CHOICES is not None: + return _NPU_CHOICES + from torch._inductor.choices import InductorChoices + from torch._inductor.lookup_table import LookupTableChoices + + from pytorchsim.backend import select + + class NPUChoices(LookupTableChoices): + def uuid(self): + """This class's part of Inductor's cache key: the machine and the picks it hands out.""" + return f"pytorchsim-npu-choices-4-{select.graph_digest()}" + + def get_config_heuristics(self, device_type="cuda"): + """npu's conv tiles (_npu_config_heuristic); every other device keeps Inductor's.""" + if device_type == "npu": + return _npu_config_heuristic() + return super().get_config_heuristics(device_type) + + def _get_lookup_table(self): + """This machine's recorded picks; Inductor's own looks only on CUDA.""" + return select.lookup_table() + + @staticmethod + def _get_device_key(device): + if getattr(device, "type", None) == "npu": + return select.device_key() + return LookupTableChoices._get_device_key(device) + + def _create_lookup_choices(self, *args, **kwargs): + """Inductor's choices from the recorded configs, each marked as recorded.""" + ktcs = super()._create_lookup_choices(*args, **kwargs) + for ktc in ktcs: + ktc.annotations[select.SOURCE] = select.RECORDED + return ktcs + + @staticmethod + def should_use_persistent_reduction(features, cooperative_reduction): + """Persistent only when the whole reduction fits this machine's reduction block.""" + base = InductorChoices.should_use_persistent_reduction( + features, cooperative_reduction) + if not base or not lowering_npu(): + return base + try: + extent = int(features.reduction_numel) + except (TypeError, ValueError): + return base + if extent < 1: + return base + persistent = 1 << (extent - 1).bit_length() + try: + numels = {"xnumel": int(features.numel), "r0_numel": extent} + shim = type("K", (), {"inside_reduction": True, "numels": numels})() + pinned = tiling.fixed_config_for(shim, numels, _elem_args(features), + contiguous=_kept_axis_contiguous(features)) + return persistent <= int(pinned["R0_BLOCK"]) + except Exception: # noqa: BLE001 + return persistent <= tiling.reduction_block_for(extent) + + def reduction_split_factor(self, device, reduction_numel_hint, numel_hint, + inner_reduction): + """Split a reduction only when a core would otherwise sit idle, and at most cores ways. + + One core, or a parallel axis that already fills the cores, means no split. + """ + if getattr(device, "type", device) != "npu": + return super().reduction_split_factor( + device, reduction_numel_hint, numel_hint, inner_reduction) + cores = _num_cores() + if cores > 1: + want = super().reduction_split_factor( + device, reduction_numel_hint, numel_hint, inner_reduction) + try: + if int(numel_hint) >= cores: + return 1 + except (TypeError, ValueError): + return 1 + split = min(int(want), cores) + if split > 1: + logger.info( + "[torchsim-compile] splitting a reduction of %s elements %s ways " + "over %s cores (upstream wanted %s)", + reduction_numel_hint, split, cores, want) + return split + return 1 + return 1 + + NPUChoices.__module__ = __name__ + NPUChoices.__qualname__ = "NPUChoices" + globals()["NPUChoices"] = NPUChoices + _NPU_CHOICES = NPUChoices + return NPUChoices + + +def _npu_config_heuristic(): + """npu's conv tile table: BLOCK_N is the lane count, per group (groups_now).""" + from torch._inductor.heuristics.template.triton import ( + BaseConfigHeuristic, ConvConfig) + + lanes = int(config.CONFIG_MACHINE.vector_lanes) + + class NPUConfigHeuristic(BaseConfigHeuristic): + def __init__(self): + super().__init__() + self.conv_configs = [ + ConvConfig(64, lanes, 16, 1, 4), + ConvConfig(32, lanes, 16, 1, 4), + ConvConfig(64, lanes, 32, 1, 4), + ] + + def get_conv_configs(self): + base = super().get_conv_configs() + + def per_group(m, n, k, **kwargs): + groups = groups_now() + return base(m, max(1, n // groups) if groups > 1 else n, k, + **kwargs) + + return per_group + + return NPUConfigHeuristic() + + +def groups_now(): + """The groups of the convolution being lowered right now (1 outside one).""" + return getattr(conv_groups, "value", 1) or 1 + + +def _register_template_heuristics(): + """Register npu's mm/bmm/addmm/baddbmm tile heuristics: this machine's tiles, then the generic set.""" + from torch._inductor.kernel.bmm import bmm_template + from torch._inductor.kernel.mm import mm_template + from torch._inductor.heuristics.template.registry import ( + register_template_heuristic) + from torch._inductor.heuristics.template.triton import ( + BaseConfigHeuristic, MMTemplateConfigMixin) + from torch._inductor.heuristics.template.triton_addmm import AddMMConfigMixin + + @register_template_heuristic(mm_template.uid, "npu") + @register_template_heuristic(bmm_template.uid, "npu") + class NPUMMTemplateConfigHeuristic(MMTemplateConfigMixin, BaseConfigHeuristic): + def _get_config_generator(self): + """Configs for one m, n, k: the first codegen_autotune_template_topk of gemm_tiles, + or the generic set when none of this machine's tiles is a legal block.""" + generic = super()._get_config_generator() + + def configs(m, n, k, **kwargs): + from torch._inductor.virtualized import V + try: + mnk = [int(V.graph.sizevars.optimization_hint(s)) for s in (m, n, k)] + except Exception: + yield from generic(m, n, k, **kwargs) + return + mapped = tiling.gemm_tiles(*mnk, kwargs.get("dtype_size", 4)) + if not mapped: + logger.warning( + "[torchsim-compile] no mapped tile for %sx%sx%s is a legal " + "Triton block; falling back to the generic set", *mnk) + yield from generic(m, n, k, **kwargs) + return + yield from self._finalize_mm_configs( + mapped[:config.codegen_autotune_template_topk]) + + return configs + + @register_template_heuristic(mm_template.uid, "npu", op_name="addmm") + @register_template_heuristic(bmm_template.uid, "npu", op_name="baddbmm") + class NPUAddmmTemplateConfigHeuristic(AddMMConfigMixin, + NPUMMTemplateConfigHeuristic): + pass + + +def pinned_blocks(kernel_tiling, features): + """This machine's blocks for a kernel of `kernel_tiling` as a FixedTritonConfig, or None. + + The numels come from the tiling; the dtype width from the widest tensor a scheduled node makes + or reads; whether the kept axis is the contiguous one from Inductor's hint. + """ + from torch._inductor.codegen.triton import FixedTritonConfig + + numels = {} + for prefix, n in (kernel_tiling or {}).items(): + try: + numels[f"{prefix}numel"] = int(n) + except Exception: + pass + if not numels or features is None: + return None + args = _elem_args(features) + shim = type("K", (), {"inside_reduction": bool(features.is_reduction()), + "numels": numels})() + try: + cfg = tiling.fixed_config_for(shim, numels, args, + contiguous=_kept_axis_contiguous(features)) or {} + except Exception as e: # noqa: BLE001 + logger.info("[torchsim-compile] no fixed_config for this kernel: %s", e) + return None + cfg = {k: int(v) for k, v in cfg.items() if v and k.endswith("BLOCK")} + return FixedTritonConfig(cfg) if cfg else None + + +def _num_cores(): + """This machine's core count, from the TOGSim config.""" + try: + return max(1, int(config.CONFIG_NUM_CORES)) + except Exception: # noqa: BLE001 + return 1 + + +def _kept_axis_contiguous(features): + """'x' when the largest read (in bytes) over every index of a reduction runs unit-stride along a + kept axis, from its MemoryDep strides; else None. Inductor's OUTER hint is not used: it is left + DEFAULT for any kernel of at least num_sm * 64 rows, whatever its strides.""" + from torch._inductor.dependencies import MemoryDep + from torch._inductor.virtualized import V + if not features.is_reduction(): + return None + best = None + for node in features.reduction_nodes(): + kept, reduced = node._sizes + for dep in node.read_writes.reads: + if not isinstance(dep, MemoryDep) or len(dep.var_names) != len(kept) + len(reduced): + continue + strides = V.graph.sizevars.stride_hints(dep.index, dep.var_names) + unit = [i for i, s in enumerate(strides) if s == 1] + if not unit: + continue + size = dep.numbytes_hint() + if best is None or size > best[0]: + best = (size, unit[0] < len(kept)) + return "x" if best and best[1] else None + + +_DT_BITS = {torch.float64: 64, torch.float32: 32, torch.float16: 16, + torch.bfloat16: 16, torch.int64: 64, torch.int32: 32, + torch.int16: 16, torch.int8: 8, torch.uint8: 8, torch.bool: 8} + + +def _elem_args(features): + """The widest tensor a scheduled node makes or reads, as fixed_config_for's args.""" + from torch._inductor.virtualized import V + bits = [] + for nd in features.scheduler_nodes(): + try: + bits.append(_DT_BITS.get(nd.node.get_dtype(), 32)) + except Exception: + pass + for dep in getattr(getattr(nd, "read_writes", None), "reads", ()) or (): + try: + bits.append(_DT_BITS.get(V.graph.get_dtype(dep.name), 32)) + except Exception: + pass + return ([{"dtype": {64: "float64", 32: "float32", 16: "float16", + 8: "int8"}[max(bits)]}] if bits else []) diff --git a/pytorchsim/codegen/__init__.py b/pytorchsim/frontend/inductor/codegen/__init__.py similarity index 60% rename from pytorchsim/codegen/__init__.py rename to pytorchsim/frontend/inductor/codegen/__init__.py index f3afd76e9..b93c32bcc 100644 --- a/pytorchsim/codegen/__init__.py +++ b/pytorchsim/frontend/inductor/codegen/__init__.py @@ -1,11 +1,11 @@ """The `npu` codegen route: Inductor's Triton backend + the compiler's passes. Inductor -> TritonNPUScheduling.define_kernel (inductor_hooks.py) - -> torchsim_compile (driver/codecache.py, driver/compiler_input.py) - -> pytorchsim-triton-compiler, in a subprocess (driver/compiler_bridge.py) + -> torchsim_compile (backend/codecache.py, backend/compiler_input.py) + -> pytorchsim-triton-compiler, in a subprocess (backend/compiler_bridge.py) -> Spike (simulator/functional.py) / TOGSim (simulator/timing.py) Registered for `npu` at device import; see device/torch_openreg. """ -from pytorchsim.codegen.inductor_hooks import TritonNPUScheduling, TritonNPUWrapperCodegen +from pytorchsim.frontend.inductor.codegen.scheduling import TritonNPUScheduling, TritonNPUWrapperCodegen diff --git a/pytorchsim/codegen/kernel_metadata.py b/pytorchsim/frontend/inductor/codegen/kernel_metadata.py similarity index 99% rename from pytorchsim/codegen/kernel_metadata.py rename to pytorchsim/frontend/inductor/codegen/kernel_metadata.py index d1476aa20..853211bab 100644 --- a/pytorchsim/codegen/kernel_metadata.py +++ b/pytorchsim/frontend/inductor/codegen/kernel_metadata.py @@ -7,7 +7,7 @@ from torch._inductor.codegen.common import InplacedBuffer, is_buffer_removed from torch._inductor.virtualized import V -from pytorchsim.codegen import tiling +from pytorchsim.frontend.inductor.codegen import tiling from pytorchsim.contract import storage_span _DTYPE = { diff --git a/pytorchsim/codegen/inductor_hooks.py b/pytorchsim/frontend/inductor/codegen/scheduling.py similarity index 97% rename from pytorchsim/codegen/inductor_hooks.py rename to pytorchsim/frontend/inductor/codegen/scheduling.py index dee83a18d..4875f5832 100644 --- a/pytorchsim/codegen/inductor_hooks.py +++ b/pytorchsim/frontend/inductor/codegen/scheduling.py @@ -17,7 +17,7 @@ from torch._inductor.virtualized import V from pytorchsim import config -from pytorchsim.codegen import kernel_metadata, verify +from pytorchsim.frontend.inductor.codegen import kernel_metadata, verify _logger = config.setup_logger() @@ -32,7 +32,7 @@ def __init__(self, tiling, *args, fixed_config=None, **kwargs): """Pin this machine's blocks here, where every kernel of this class is made: the one Inductor emits and the one its fusion benchmark times are then the same kernel.""" if fixed_config is None: - from pytorchsim.frontend.inductor_patches import pinned_blocks + from pytorchsim.frontend.inductor.choices import pinned_blocks fixed_config = pinned_blocks(tiling, kwargs.get("features")) super().__init__(tiling, *args, fixed_config=fixed_config, **kwargs) @@ -85,7 +85,7 @@ def benchmark_codegened_module(self, mod, n_spills_threshold=8, node_names=None, skip_perf_cache=False): """(TOGSim cycles, path) of a module generate_kernel_code_from_nodes wrote: Inductor compares these with the cycles select.time_choices gave the unfused choices.""" - from pytorchsim.driver import select + from pytorchsim.backend import select got = self._benchmarked.get(mod.__file__) if got is None: @@ -136,7 +136,7 @@ def _tile_source(node_schedule): RECORDED_UNFUSED; a MultiTemplateBuffer is only made for choices timed in cycles.""" from torch._inductor.ir import MultiTemplateBuffer - from pytorchsim.driver import select + from pytorchsim.backend import select nodes = [n for n in node_schedule if hasattr(n, "is_template")] template = next((n for n in nodes if n.is_template()), None) @@ -175,10 +175,10 @@ def write_header(self): self.header.splice( f""" from pytorchsim.config import setup_logger - from pytorchsim.codegen import verify as _fverify - from pytorchsim.driver.codecache import torchsim_compile, torchsim_extern + from pytorchsim.frontend.inductor.codegen import verify as _fverify + from pytorchsim.backend.codecache import torchsim_compile, torchsim_extern - _logger = setup_logger("pytorchsim.codegen.generated_wrapper") + _logger = setup_logger("pytorchsim.frontend.inductor.codegen.generated_wrapper") _logger.info(f'Wrapper Codegen Path = {{__file__}}') """ ) @@ -329,7 +329,7 @@ def user_kernel_meta(kernel, kwargs, triton_meta, grid): written (inout) where torch's mutation analysis says the launch writes it, read (in) elsewhere, every pointer inout when that analysis is not at hand.""" from pytorchsim.contract import storage_span - from pytorchsim.driver.codecache import user_kernel_id + from pytorchsim.backend.codecache import user_kernel_id hint = V.graph.sizevars.optimization_hint signature = {str(k): str(v) for k, v in triton_meta["signature"].items()} diff --git a/pytorchsim/codegen/tiling.py b/pytorchsim/frontend/inductor/codegen/tiling.py similarity index 99% rename from pytorchsim/codegen/tiling.py rename to pytorchsim/frontend/inductor/codegen/tiling.py index 198276a2a..b720e5d83 100644 --- a/pytorchsim/codegen/tiling.py +++ b/pytorchsim/frontend/inductor/codegen/tiling.py @@ -106,7 +106,7 @@ def reduction_block_for(extent, elem_bytes=4, lane_bytes=None): Cover the extent and no more, then shrink to the budget: half of one lane's scratchpad, shared by the tiles a reduction keeps live. Two callers must - agree: this pins the block, inductor_patches asks if persistence matches. + agree: this pins the block, choices.NPUChoices asks if persistence matches. Both see the machine's scratchpad when `lane_bytes` is left to this function; a persistent reduction rendered for a bigger one than the target has is a kernel the compiler refuses as over budget, whatever XBLOCK shrinks to. diff --git a/pytorchsim/codegen/verify.py b/pytorchsim/frontend/inductor/codegen/verify.py similarity index 99% rename from pytorchsim/codegen/verify.py rename to pytorchsim/frontend/inductor/codegen/verify.py index cc2771653..df00b4667 100644 --- a/pytorchsim/codegen/verify.py +++ b/pytorchsim/frontend/inductor/codegen/verify.py @@ -31,7 +31,7 @@ from torch._inductor.codegen import wrapper from torch._inductor.virtualized import V -from pytorchsim.codegen import kernel_metadata +from pytorchsim.frontend.inductor.codegen import kernel_metadata from pytorchsim import config from pytorchsim.config import setup_logger diff --git a/device/torch_openreg/openreg/extension_device_op_overrides.py b/pytorchsim/frontend/inductor/device_op_overrides.py similarity index 60% rename from device/torch_openreg/openreg/extension_device_op_overrides.py rename to pytorchsim/frontend/inductor/device_op_overrides.py index 45b10c9f1..150adfb23 100644 --- a/device/torch_openreg/openreg/extension_device_op_overrides.py +++ b/pytorchsim/frontend/inductor/device_op_overrides.py @@ -1,3 +1,6 @@ +"""The device code Inductor writes into an npu wrapper: no raw stream, no device to set or sync, a +null device guard; cpu keeps its own.""" + from __future__ import annotations from textwrap import dedent @@ -21,8 +24,10 @@ def synchronize(self) -> str: return "pass" def device_guard(self, device_idx: int) -> str: - # The caller writes `with {this}:`, so "pass" is a SyntaxError. + """A null context: the caller writes `with {this}:`, where "pass" would not parse.""" return "torch._ops.contextlib.nullcontext()" -register_device_op_overrides("npu", ExtensionDeviceOpOverrides()) -register_device_op_overrides("cpu", CpuDeviceOpOverrides()) \ No newline at end of file +def install(): + """Register npu's device op overrides, and cpu's own beside them.""" + register_device_op_overrides("npu", ExtensionDeviceOpOverrides()) + register_device_op_overrides("cpu", CpuDeviceOpOverrides()) \ No newline at end of file diff --git a/pytorchsim/frontend/inductor/lowering.py b/pytorchsim/frontend/inductor/lowering.py new file mode 100644 index 000000000..ad531b166 --- /dev/null +++ b/pytorchsim/frontend/inductor/lowering.py @@ -0,0 +1,251 @@ +"""Inductor lowering patches for npu that Inductor has no hook for: a transposed conv lowered as its +direct equivalent, a grouped conv's grid per group, a zero-length GEMM as zeros; and npu's conv +decompositions.""" + +import torch + +from pytorchsim.frontend.inductor.choices import conv_groups +from pytorchsim.frontend.inductor.registration import is_npu, lowering_npu + + +def install(): + """Apply this file's patches.""" + _wrap_convolution_lowering() + _size_grouped_conv_grid_per_group() + _short_circuit_degenerate_gemms() + _decompose_convolution_for_npu() + + +def _wrap_convolution_lowering(): + """Wrap aten.convolution's lowering: record its groups, and lower a transposed one as direct. + + The groups narrow the conv heuristic's BLOCK_N to one group's channels (choices.groups_now). + """ + import functools + import inspect + + from torch._inductor import ir + from torch._inductor import lowering as inductor_lowering + from torch._inductor.kernel import conv as conv_kernel + from torch._inductor.lowering import lowerings as L + from torch._inductor.virtualized import V + + aten = torch.ops.aten + prims = torch.ops.prims + sig = inspect.signature(conv_kernel.convolution) + + def _per_dim(seq, n): + seq = list(seq) + return seq * n if len(seq) == 1 else seq + + def _spread(t, lead, extents, factor): + """Put factor-1 zeros between neighbouring elements of each dim.""" + if all(f == 1 for f in factor): + return t + n = len(extents) + paired = list(lead) + for extent in extents: + paired += [extent, 1] + y = L[aten.view](t, paired) + pad = [] + for i in reversed(range(n)): + pad += [0, factor[i] - 1, 0, 0] + y = L[aten.constant_pad_nd](y, pad, 0.0) + y = L[aten.view](y, list(lead) + + [extents[i] * factor[i] for i in range(n)]) + for i in range(n): + if factor[i] != 1: + y = L[aten.slice](y, len(lead) + i, 0, + extents[i] * factor[i] - (factor[i] - 1)) + return y + + def _rewrite(x, weight, stride, padding, dilation, output_padding, groups): + """Return the (x, weight, *params) of the equivalent direct conv.""" + ints = V.graph.sizevars.guard_int_seq + batch, in_chan, *spatial = ints(x.get_size()) + _, out_per_group, *kernel = ints(weight.get_size()) + n_sp = len(kernel) + out_chan = out_per_group * groups + stride = _per_dim(stride, n_sp) + padding = _per_dim(padding, n_sp) + dilation = _per_dim(dilation, n_sp) + output_padding = _per_dim(output_padding, n_sp) + + y = _spread(x, [batch, in_chan], spatial, stride) + + pad = [] + for i in reversed(range(n_sp)): + lo = dilation[i] * (kernel[i] - 1) - padding[i] + pad += [lo, lo + output_padding[i]] + if any(p != 0 for p in pad): + y = L[aten.constant_pad_nd](y, pad, 0.0) + + w = L[aten.view](weight, [groups, in_chan // groups, + out_chan // groups] + kernel) + w = L[aten.permute](w, [0, 2, 1] + [3 + i for i in range(n_sp)]) + w = L[aten.view](w, [out_chan, in_chan // groups] + kernel) + if any(k != 1 for k in kernel): + w = L[prims.rev.default](w, [2 + i for i in range(n_sp)]) + + w = _spread(w, [out_chan, in_chan // groups], kernel, dilation) + + return y, w, [1] * n_sp, [0] * n_sp, [1] * n_sp, [0] * n_sp + + def lower(inner, a, args, kwargs): + """The lowering itself: a transposed npu conv as its direct equivalent, else inner.""" + if a is None: + return inner(*args, **kwargs) + x, weight = a["x"], a["weight"] + if not a["transposed"] or ir.get_device_type(x) != "npu": + return inner(*args, **kwargs) + + batchless = len(x.get_size()) == len(weight.get_size()) - 1 + if batchless: + x = L[aten.expand](x, [1, *x.get_size()]) + + y, w, stride, padding, dilation, output_padding = _rewrite( + x, weight, a["stride"], a["padding"], a["dilation"], + a["output_padding"], a["groups"]) + out = inner(y, w, a["bias"], stride, padding, dilation, False, + output_padding, a["groups"]) + return L[aten.squeeze](out, dim=0) if batchless else out + + def wrap(inner): + @functools.wraps(inner) + def convolution(*args, **kwargs): + try: + bound = sig.bind(*args, **kwargs) + bound.apply_defaults() + a = bound.arguments + groups = a.get("groups", 1) + except TypeError: + a, groups = None, 1 + prev = getattr(conv_groups, "value", 1) + conv_groups.value = groups if isinstance(groups, int) else 1 + try: + return lower(inner, a, args, kwargs) + finally: + conv_groups.value = prev + + return convolution + + packet = torch.ops.aten.convolution + for key in [packet] + [getattr(packet, o) for o in packet.overloads()]: + inner = inductor_lowering.lowerings.get(key) + if inner is not None: + inductor_lowering.lowerings[key] = wrap(inner) + + +def _size_grouped_conv_grid_per_group(): + """Grid a grouped convolution over one group's channels, not all of them.""" + from torch._inductor.kernel import conv as conv_kernel + from torch._inductor.select_algorithm import SymbolicGridFn + + orig2d = conv_kernel.conv2d_grid + orig3d = conv_kernel.conv3d_grid + + @SymbolicGridFn + def conv2d_grid(n, c, h, w, meta, *, cdiv): + if not lowering_npu(): + return orig2d(n, c, h, w, meta) + groups = meta.get("GROUPS", 1) or 1 + return ( + cdiv(n * h * w, meta["BLOCK_M"]), + cdiv(cdiv(c, groups), meta["BLOCK_N"]), + groups, + ) + + @SymbolicGridFn + def conv3d_grid(n, c, d, h, w, meta, *, cdiv): + if not lowering_npu(): + return orig3d(n, c, d, h, w, meta) + groups = meta.get("GROUPS", 1) or 1 + return ( + cdiv(n * d * h * w, meta["BLOCK_M"]), + cdiv(cdiv(c, groups), meta["BLOCK_N"]), + groups, + ) + + conv_kernel.conv2d_grid = conv2d_grid + conv_kernel.conv3d_grid = conv3d_grid + for tmpl, fn in ((getattr(conv_kernel, "conv2d_template", None), conv2d_grid), + (getattr(conv_kernel, "conv3d_template", None), conv3d_grid)): + if tmpl is not None: + tmpl.grid = fn + + +def _short_circuit_degenerate_gemms(): + """Lower an npu mm/bmm/addmm/baddbmm with a zero-length M or N (or K, unbiased) as zeros.""" + from torch._inductor.kernel.mm_common import mm_args + from torch._inductor.lowering import full, lowerings + from torch._inductor.virtualized import V + + def wrap(op, bias): + def wrapped(*args, _orig=lowerings[op], **kwargs): + try: + m, n, k, layout = mm_args(*args[bias:bias + 2], + layout=kwargs.get("layout"))[:4] + m, n, k = (int(V.graph.sizevars.optimization_hint(s)) for s in (m, n, k)) + except Exception: + return _orig(*args, **kwargs) + if not is_npu(layout): + return _orig(*args, **kwargs) + if m == 0 or n == 0 or (k == 0 and not bias): + return full(layout.size, 0, dtype=layout.dtype, + device=layout.device) + return _orig(*args, **kwargs) + + return wrapped + + aten = torch.ops.aten + for op, bias in ((aten.mm, 0), (aten.bmm, 0), + (aten.addmm, 1), (aten.baddbmm, 1)): + for name in op.overloads(): + o = getattr(op, name) + if o in lowerings: + lowerings[o] = wrap(o, bias) + + +def _decompose_convolution_for_npu(): + """Register npu's aten.convolution decompositions: a Conv1d reaches the 2-D template through + torch's conv1d_to_conv2d, and a depthwise 2-D conv is a stencil on the vector unit. Declines + non-npu inputs, transposed convs and output_padding; anything else keeps the template.""" + from torch._inductor.decomposition import conv1d_to_conv2d, register_decomposition + + aten = torch.ops.aten + + @register_decomposition([aten.convolution]) + def _npu_convolution(input, weight, bias, stride, padding, dilation, + transposed, output_padding, groups): + if input.device.type != "npu" or transposed: + return NotImplemented + if any(p != 0 for p in output_padding): + return NotImplemented + if len(stride) == 1: + return conv1d_to_conv2d(input, weight, bias, stride, padding, dilation, groups) + if len(stride) == 2 and _is_depthwise(input, weight, groups): + return _depthwise_stencil(input, weight, bias, stride, padding, dilation) + return NotImplemented + + +def _is_depthwise(input, weight, groups): + """One channel a group, in and out: the conv is a per-channel stencil, not a matmul.""" + return (groups > 1 and input.shape[1] == groups and weight.shape[0] == groups + and weight.shape[1] == 1) + + +def _depthwise_stencil(x, w, bias, stride, padding, dilation): + """A depthwise 2-D conv as taps: each a strided slice of the padded input times its weight, summed.""" + (sh, sw), (ph, pw), (dh, dw) = stride, padding, dilation + g, _, kh, kw = w.shape + x = torch.ops.aten.constant_pad_nd(x, [pw, pw, ph, ph]) + h_out = (x.shape[2] - dh * (kh - 1) - 1) // sh + 1 + w_out = (x.shape[3] - dw * (kw - 1) - 1) // sw + 1 + out = None + for i in range(kh): + for j in range(kw): + tap = x[:, :, i * dh:i * dh + sh * (h_out - 1) + 1:sh, + j * dw:j * dw + sw * (w_out - 1) + 1:sw] + term = tap * w[:, 0, i, j].reshape(1, g, 1, 1) + out = term if out is None else out + term + return out if bias is None else out + bias.reshape(1, g, 1, 1) diff --git a/pytorchsim/frontend/inductor/post_grad_pass.py b/pytorchsim/frontend/inductor/post_grad_pass.py new file mode 100644 index 000000000..c3d3bcf20 --- /dev/null +++ b/pytorchsim/frontend/inductor/post_grad_pass.py @@ -0,0 +1,292 @@ +"""The npu's post-grad pass: rewrites that keep ops with no npu kernel on the device. + +pytorchsim_post_grad_pass is the device_custom_pass Inductor runs on npu graphs only, after its post-grad +passes: histc, polar, a row times a matrix, complex values as real pairs. Ops with a Triton kernel of +their own (topk, grouped_mm, SDPA) are frontend/triton_ops/. +""" + +import torch +from torch import fx +from torch.fx import traceback as fx_traceback +from torch._inductor.custom_graph_pass import CustomGraphModulePass, get_hash_for_files + +from pytorchsim import config + +aten = torch.ops.aten +prims = torch.ops.prims + +logger = config.setup_logger() + + +class _pytorchsim_post_grad_pass(CustomGraphModulePass): + """The four rewrites in this order on an npu graph (polar before the complex values it makes); its uuid + hashes this file, so an edit here is a new cache key.""" + + def __call__(self, gm: fx.GraphModule) -> None: + graph, fake_mode = gm.graph, _fake_mode(gm.graph) + changed = (rewrite_aten_histc(graph, fake_mode) + + rewrite_aten_polar(graph, fake_mode) + + rewrite_aten_mm_addmm_row(graph, fake_mode) + + rewrite_aten_view_as_complex(graph, fake_mode)) + if changed: + graph.eliminate_dead_code() + gm.recompile() + + def uuid(self): + return get_hash_for_files((__file__,)) + + +pytorchsim_post_grad_pass = _pytorchsim_post_grad_pass() + + +def rewrite_aten_histc(graph, fake_mode) -> int: + """Every aten.histc as a count on the device (_insert_histc); one without a fake value is left to aten, + logged. Returns how many were rewritten.""" + def build(call, node): + x = node.args[0] + if _val(x) is None: + logger.info("[post_grad_pass] histc without a fake value: left to aten") + return None + said = dict(zip(("bins", "min", "max"), node.args[1:]), **node.kwargs) + return _insert_histc(call, x, _val(x), int(said.get("bins", 100)), said.get("min", 0), said.get("max", 0)) + return _replace(graph, fake_mode, graph.find_nodes(op="call_function", target=aten.histc.default), build) + + +def _insert_histc(call, x, xv, bins, lo, hi): + """aten's histc: bin (x - lo) * bins / (hi - lo), integral in int64 and floating in x's dtype, the top + edge in the last bin, outside [lo, hi] dropped; lo == hi takes x's range, widened by 1 if it is one value.""" + integral = not xv.is_floating_point() + flat = call(prims.convert_element_type.default, call(aten.reshape.default, x, [-1]), + torch.int64 if integral else xv.dtype) + if lo == hi and xv.numel(): + lo, hi = call(aten.amin.default, flat, [0]), call(aten.amax.default, flat, [0]) + one = call(aten.eq.Tensor, lo, hi) + lo, hi = (call(aten.where.self, one, call(aten.sub.Tensor, lo, 1), lo), + call(aten.where.self, one, call(aten.add.Tensor, hi, 1), hi)) + width = call(aten.sub.Tensor, hi, lo) + else: + if lo == hi: + lo, hi = lo - 1, hi + 1 + if integral: + lo, hi = int(lo), int(hi) + if hi <= lo: + raise RuntimeError(f"torch.histc: max must be larger than min (min {lo}, max {hi})") + width = hi - lo + scaled = call(aten.mul.Tensor, call(aten.sub.Tensor, flat, lo), bins) + if integral: + pos = call(aten.div.Tensor_mode, scaled, width, rounding_mode="floor") + else: + pos = call(prims.convert_element_type.default, call(aten.div.Tensor, scaled, width), torch.int64) + pos = call(aten.clamp_max.default, pos, bins - 1) + ge, le = ((aten.ge.Tensor, aten.le.Tensor) if isinstance(lo, fx.Node) + else (aten.ge.Scalar, aten.le.Scalar)) + inside = call(aten.logical_and.default, call(ge, flat, lo), call(le, flat, hi)) + seats = call(prims.iota.default, bins, start=0, step=1, dtype=torch.int64, device=xv.device, + requires_grad=False) + hits = call(aten.logical_and.default, + call(aten.eq.Tensor, call(aten.reshape.default, pos, [-1, 1]), + call(aten.reshape.default, seats, [1, -1])), + call(aten.reshape.default, inside, [-1, 1])) + return call(prims.convert_element_type.default, call(aten.sum.dim_IntList, hits, [0]), xv.dtype) + + +def rewrite_aten_polar(graph, fake_mode) -> int: + """polar(abs, angle) as view_as_complex of the pair (abs*cos, abs*sin), built contiguous since + view_as_complex needs a unit last stride; rewrite_aten_view_as_complex then takes it to real pairs.""" + def build(call, node): + r, angle = node.args[:2] + return call(aten.view_as_complex.default, + _join(call, call(aten.mul.Tensor, r, call(aten.cos.default, angle)), + call(aten.mul.Tensor, r, call(aten.sin.default, angle)))) + return _replace(graph, fake_mode, graph.find_nodes(op="call_function", target=aten.polar.default), build) + + +def rewrite_aten_mm_addmm_row(graph, fake_mode) -> int: + """Replace a 1 x K row times a K x N matrix with the row broadcast down the matrix, a + multiply and a sum over K: vector work, where the mm template would run it on the array.""" + def build(call, node): + found = _row_times_matrix(node) + if found is None: + return None + a, b, bias = found + column = call(aten.view.default, a, [int(_val(a).shape[1]), 1]) + out = call(aten.sum.dim_IntList, call(aten.mul.Tensor, column, b), [0], True) + return out if bias is None else call(aten.add.Tensor, out, bias) + return _replace(graph, fake_mode, graph.find_nodes(op="call_function", target=aten.mm.default) + + graph.find_nodes(op="call_function", target=aten.addmm.default), build) + + +def _row_times_matrix(node): + """(a, b, bias) of an mm or a plain addmm of real floating operands whose left one is a row, else None.""" + if node.target is aten.mm.default: + (a, b), bias = node.args, None + elif not node.kwargs: + bias, a, b = node.args + else: + return None + av, bv = _val(a), _val(b) + if av is None or bv is None or av.dim() != 2 or bv.dim() != 2 or av.shape[0] != 1: + return None + if not (av.is_floating_point() and bv.is_floating_point()): + return None + return a, b, bias + + +def rewrite_aten_view_as_complex(graph, fake_mode) -> int: + """Each component of complex values whose ops _REAL_PAIR has a rule for becomes real [..., 2] pairs; any + other component stays as it is, logged with why. Returns the components rewritten.""" + changed = 0 + for component in _complex_components([n for n in graph.nodes if _is_complex(n)]): + why = _why_not_real(component) + if why is not None: + logger.info("[post_grad_pass] %d complex nodes left to aten: %s", len(component), why) + continue + _to_real_pairs(graph, fake_mode, component) + changed += 1 + return changed + + +def _complex_components(nodes): + """The complex nodes grouped by the complex values joining them, each group in graph order.""" + parent = {n: n for n in nodes} + + def root(n): + while parent[n] is not n: + parent[n] = parent[parent[n]] + n = parent[n] + return n + + for n in nodes: + for a in n.all_input_nodes: + if a in parent: + parent[root(a)] = root(n) + groups = {} + for n in nodes: + groups.setdefault(root(n), []).append(n) + return list(groups.values()) + + +def _why_not_real(component): + """Why the component has no real-pair form, or None: a node _REAL_PAIR has no rule for (a placeholder or + attribute among them), or a complex value read by anything but _REAL_PAIR and view_as_real (the output too).""" + for n in component: + if n.target not in _REAL_PAIR: + return f"{n.op} {n.target}" + for user in n.users: + if user.target is not aten.view_as_real.default and user.target not in _REAL_PAIR: + return f"{user.op} {user.name} reads {n.name}'s complex value" + return None + + +def _to_real_pairs(graph, fake_mode, component): + """Rewrite one eligible component: each complex value becomes its [..., 2] pair and every view_as_real of + it reads the pair.""" + pair = {} + for n in component: + pair[n] = _REAL_PAIR[n.target](_inserter(graph, fake_mode, n), n, pair) + + for n in component: + for user in list(n.users): + if user.target is aten.view_as_real.default: + user.replace_all_uses_with(pair[n]) + + +def _pair_of_view(call, n, pair): + """view_as_complex(x): its pair is x.""" + return n.args[0] + + +def _pair_of_unsqueeze(call, n, pair): + """unsqueeze(z, dim): the pair unsqueezed before its last axis.""" + dim = n.args[1] + return call(aten.unsqueeze.default, pair[n.args[0]], dim if dim >= 0 else dim - 1) + + +def _pair_of_mul(call, n, pair): + """z * w as (zr*wr - zi*wi, zr*wi + zi*wr) when w is complex (a value or a Python complex); z * r scales + the pair when r is real.""" + a, b = n.args[0], n.args[1] + cx, other = (a, b) if _is_complex(a) else (b, a) + if not (_is_complex(other) or isinstance(other, complex)): + if isinstance(other, fx.Node): + other = call(aten.unsqueeze.default, other, -1) + return call(aten.mul.Tensor, pair[cx], other) + ar, ai = call(aten.select.int, pair[cx], -1, 0), call(aten.select.int, pair[cx], -1, 1) + if isinstance(other, complex): + br, bi = other.real, other.imag + else: + br, bi = call(aten.select.int, pair[other], -1, 0), call(aten.select.int, pair[other], -1, 1) + re = call(aten.sub.Tensor, call(aten.mul.Tensor, ar, br), call(aten.mul.Tensor, ai, bi)) + im = call(aten.add.Tensor, call(aten.mul.Tensor, ar, bi), call(aten.mul.Tensor, ai, br)) + return _join(call, re, im) + + +_REAL_PAIR = { + aten.view_as_complex.default: _pair_of_view, + aten.unsqueeze.default: _pair_of_unsqueeze, + aten.mul.Tensor: _pair_of_mul, + aten.mul.Scalar: _pair_of_mul, +} + + +def _replace(graph, fake_mode, nodes, build): + """Each node of nodes for which build(call, node) returns a value is replaced by it and erased, call + being _inserter's for that node. Returns how many were replaced.""" + changed = 0 + for node in nodes: + out = build(_inserter(graph, fake_mode, node), node) + if out is not None: + node.replace_all_uses_with(out) + graph.erase_node(node) + changed += 1 + return changed + + +def _inserter(graph, fake_mode, origin): + """call(target, *args, **kwargs): a node just before origin, made through FX's tracer under origin's meta + so FX copies its provenance and records origin in from_node; its fake value is set, as nothing after does.""" + def unwrap(a): + if isinstance(a, (list, tuple)): + return type(a)(unwrap(x) for x in a) + if isinstance(a, dict): + return {k: unwrap(v) for k, v in a.items()} + return _val(a) + + tracer = fx.proxy.GraphAppendingTracer(graph) + + def call(target, *args, **kwargs): + with graph.inserting_before(origin), fx_traceback.preserve_node_meta(), \ + fx_traceback.set_current_meta(origin): + node = tracer.create_node("call_function", target, args, kwargs) + if fake_mode is not None: + with fake_mode: + node.meta["val"] = target(*unwrap(args), **unwrap(kwargs)) + return node + + return call + + +def _join(call, re, im): + """The [..., 2] real pair of re and im.""" + return call(aten.cat.default, [call(aten.unsqueeze.default, re, -1), + call(aten.unsqueeze.default, im, -1)], -1) + + +def _val(node): + """The fake value of a node, or the argument itself when it is not a node.""" + return node.meta.get("val", None) if isinstance(node, fx.Node) else node + + +def _is_complex(node): + """Whether the node holds a complex tensor.""" + v = _val(node) + return isinstance(v, torch.Tensor) and v.is_complex() + + +def _fake_mode(graph): + """The fake mode of the graph's tensors, or None.""" + for n in graph.nodes: + v = _val(n) + if isinstance(v, torch.Tensor) and hasattr(v, "fake_mode"): + return v.fake_mode + return None diff --git a/pytorchsim/frontend/inductor/registration.py b/pytorchsim/frontend/inductor/registration.py new file mode 100644 index 000000000..c0659249b --- /dev/null +++ b/pytorchsim/frontend/inductor/registration.py @@ -0,0 +1,57 @@ +"""npu as an Inductor backend: a Triton GPU (GPU_TYPES, which Inductor has no hook for, so it +patches its module state), its codegen and post-grad pass (register_backend_for_device) and its +device op overrides (device_op_overrides.py). is_npu and lowering_npu are the device tests the other +patches share. +""" + +def install(): + """Make Inductor take npu as a Triton GPU and register npu's codegen, post-grad pass and op overrides.""" + _register_npu_as_gpu() + _register_backend() + _register_device_op_overrides() + + +def _register_backend(): + """npu's codegen route: Inductor's Triton codegen through TritonNPUScheduling and its wrapper, with + pytorchsim_post_grad_pass run on every npu graph.""" + from torch._inductor.codegen.common import register_backend_for_device + + from pytorchsim.frontend.inductor.codegen import TritonNPUScheduling, TritonNPUWrapperCodegen + from pytorchsim.frontend.inductor.post_grad_pass import pytorchsim_post_grad_pass + + register_backend_for_device("npu", TritonNPUScheduling, TritonNPUWrapperCodegen, + device_custom_pass=pytorchsim_post_grad_pass) + + +def _register_device_op_overrides(): + """The device code Inductor writes into an npu wrapper (device_op_overrides.py).""" + from pytorchsim.frontend.inductor import device_op_overrides + + device_op_overrides.install() + + +def _register_npu_as_gpu(): + """Add npu to Inductor's GPU_TYPES, so Triton codegen is chosen for it.""" + import torch._inductor.utils as inductor_utils + + if "npu" not in inductor_utils.GPU_TYPES: + inductor_utils.GPU_TYPES.append("npu") + + +def lowering_npu(): + """Whether the graph being lowered right now targets this device.""" + from torch._inductor.virtualized import V + + try: + return V.graph.get_current_device_or_throw().type == "npu" + except Exception: # noqa: BLE001 + return False + + +def is_npu(obj): + """Whether a device, device string, tensor, layout or node is on this device.""" + dev = getattr(obj, "device", obj) + dev = getattr(dev, "device", dev) + if isinstance(dev, str): + return dev.split(":")[0] == "npu" + return getattr(dev, "type", None) == "npu" diff --git a/pytorchsim/frontend/inductor/selection.py b/pytorchsim/frontend/inductor/selection.py new file mode 100644 index 000000000..eb2893799 --- /dev/null +++ b/pytorchsim/frontend/inductor/selection.py @@ -0,0 +1,82 @@ +"""How a template's config is picked for npu: TOGSim cycles in timing mode (backend/select.py), the +offered order otherwise, a recorded pick when there is one. Inductor's recording hooks +(add_preprocessing_fn, add_feedback_saver) take the last; it has none for timing a choice, so the +rest replaces four AlgorithmSelectorCache methods, each falling back to Inductor's off npu. +""" + +import torch + +from pytorchsim import config +from pytorchsim.frontend.inductor.registration import is_npu + + +def install(): + """Patch algorithm selection for npu choices: cycles from TOGSim in timing mode, the offered + order otherwise; no precompile; allocate-only examples. A recorded pick is the only choice, + and a timed one is recorded.""" + from torch._inductor import config as inductor_config + from torch._inductor import select_algorithm + from torch._inductor.select_algorithm import AlgorithmSelectorCache + + from pytorchsim.backend import select + + orig_benchmark = AlgorithmSelectorCache.__dict__["benchmark_choices"].__func__ + orig_call = AlgorithmSelectorCache.__call__ + orig_precompile = AlgorithmSelectorCache.make_precompile_fn + orig_example = AlgorithmSelectorCache.__dict__["generate_example_value"].__func__ + + def _choices_are_npu(choices): + return any(is_npu(getattr(c, "layout", None)) for c in choices) + + def benchmark_choices(cls, choices, autotune_args, is_collective=False): + if not _choices_are_npu(choices): + return orig_benchmark(cls, choices, autotune_args, is_collective) + timed = bool(config.pytorchsim_timing_mode) + if timed != inductor_config.benchmark_epilogue_fusion: + raise RuntimeError( + "TORCHSIM_TIMING_MODE changed after pytorchsim was installed: Inductor's " + "epilogue-fusion benchmark follows the mode the process started in") + if timed and select.times(choices): + return select.time_choices(choices) + return pick_config(choices) + + def __call__(self, name, choices, *args, **kwargs): + """Inductor's selection; a fusion is benchmarked only for choices timed in cycles.""" + if _choices_are_npu(choices) and not select.times(choices): + kwargs["return_multi_template"] = False + return orig_call(self, name, choices, *args, **kwargs) + + def make_precompile_fn(self, choices, *args, **kwargs): + if not _choices_are_npu(choices): + return orig_precompile(self, choices, *args, **kwargs) + return lambda: None + + def generate_example_value(size, stride, device, dtype, extra_size, + allocation_size=None): + """An unread benchmark operand, allocated rather than sampled.""" + if not is_npu(device): + return orig_example(size, stride, device, dtype, extra_size, + allocation_size) + shape = size if allocation_size is None else allocation_size + needed = extra_size + if all(s > 0 for s in shape): + needed += sum((s - 1) * t for s, t in zip(shape, stride)) + 1 + view = torch.as_strided( + torch.empty(needed, dtype=dtype, device=device), shape, stride) + return view if tuple(shape) == tuple(size) else view.as_strided(size, stride) + + AlgorithmSelectorCache.benchmark_choices = classmethod(benchmark_choices) + AlgorithmSelectorCache.__call__ = __call__ + AlgorithmSelectorCache.make_precompile_fn = make_precompile_fn + AlgorithmSelectorCache.generate_example_value = staticmethod( + generate_example_value) + select_algorithm.add_preprocessing_fn(select.keep_recorded) + select_algorithm.add_feedback_saver(select.record) + + +def pick_config(choices): + """Timings in place of benchmarking: the offered order wins, extern last.""" + from torch._inductor.select_algorithm import ExternKernelCaller + + return {c: (1e3 if isinstance(c, ExternKernelCaller) else 1.0) + i * 1e-3 + for i, c in enumerate(choices)} diff --git a/pytorchsim/frontend/inductor_patches.py b/pytorchsim/frontend/inductor_patches.py deleted file mode 100644 index 871e723b2..000000000 --- a/pytorchsim/frontend/inductor_patches.py +++ /dev/null @@ -1,667 +0,0 @@ -"""Our patches to Inductor so its Triton codegen serves npu. - -npu counts as a Triton GPU, mm/bmm/conv go to the Triton templates with this machine's tiles, -every kernel's blocks are pinned (pinned_blocks), and a template's config is Inductor's own -selection: timed on TOGSim in timing mode, the offered order otherwise, a recorded pick when there -is one (driver/select.py). -""" - -import torch - -from pytorchsim import config -from pytorchsim.codegen import tiling - -logger = config.setup_logger() - -_conv_groups = None - -_NPU_CHOICES = None - -_NPU_CONFIG_HEURISTIC = None - -_installed = False - - -def _register_npu_as_gpu(): - """Add npu to Inductor's GPU_TYPES, so Triton codegen is chosen for it.""" - import torch._inductor.utils as inductor_utils - - if "npu" not in inductor_utils.GPU_TYPES: - inductor_utils.GPU_TYPES.append("npu") - - -def _lowering_npu(): - """Whether the graph being lowered right now targets this device.""" - from torch._inductor.virtualized import V - - try: - return V.graph.get_current_device_or_throw().type == "npu" - except Exception: # noqa: BLE001 - return False - - -def _is_npu(obj): - """Whether a device, device string, tensor, layout or node is on this device.""" - dev = getattr(obj, "device", obj) - dev = getattr(dev, "device", dev) - if isinstance(dev, str): - return dev.split(":")[0] == "npu" - return getattr(dev, "type", None) == "npu" - - -def _register_template_heuristics(): - """Register npu's mm/bmm/addmm/baddbmm tile heuristics: this machine's tiles, then the generic set.""" - from torch._inductor.kernel.bmm import bmm_template - from torch._inductor.kernel.mm import mm_template - from torch._inductor.heuristics.template.registry import ( - register_template_heuristic) - from torch._inductor.heuristics.template.triton import ( - BaseConfigHeuristic, MMTemplateConfigMixin) - from torch._inductor.heuristics.template.triton_addmm import AddMMConfigMixin - - @register_template_heuristic(mm_template.uid, "npu") - @register_template_heuristic(bmm_template.uid, "npu") - class NPUMMTemplateConfigHeuristic(MMTemplateConfigMixin, BaseConfigHeuristic): - def _get_config_generator(self): - """Configs for one m, n, k: the first codegen_autotune_template_topk of gemm_tiles, - or the generic set when none of this machine's tiles is a legal block.""" - generic = super()._get_config_generator() - - def configs(m, n, k, **kwargs): - from torch._inductor.virtualized import V - try: - mnk = [int(V.graph.sizevars.optimization_hint(s)) for s in (m, n, k)] - except Exception: - yield from generic(m, n, k, **kwargs) - return - mapped = tiling.gemm_tiles(*mnk, kwargs.get("dtype_size", 4)) - if not mapped: - logger.warning( - "[torchsim-compile] no mapped tile for %sx%sx%s is a legal " - "Triton block; falling back to the generic set", *mnk) - yield from generic(m, n, k, **kwargs) - return - yield from self._finalize_mm_configs( - mapped[:config.codegen_autotune_template_topk]) - - return configs - - @register_template_heuristic(mm_template.uid, "npu", op_name="addmm") - @register_template_heuristic(bmm_template.uid, "npu", op_name="baddbmm") - class NPUAddmmTemplateConfigHeuristic(AddMMConfigMixin, - NPUMMTemplateConfigHeuristic): - pass - - -def _groups_now(): - """The groups of the convolution being lowered right now (1 outside one).""" - return getattr(_conv_groups, "value", 1) or 1 - - -def _wrap_convolution_lowering(): - """Wrap aten.convolution's lowering: record its groups, and lower a transposed one as direct. - - The groups narrow the conv heuristic's BLOCK_N to one group's channels. - """ - import functools - import inspect - import threading - - from torch._inductor import ir - from torch._inductor import lowering as inductor_lowering - from torch._inductor.kernel import conv as conv_kernel - from torch._inductor.lowering import lowerings as L - from torch._inductor.virtualized import V - - global _conv_groups - _conv_groups = threading.local() - aten = torch.ops.aten - prims = torch.ops.prims - sig = inspect.signature(conv_kernel.convolution) - - def _per_dim(seq, n): - seq = list(seq) - return seq * n if len(seq) == 1 else seq - - def _spread(t, lead, extents, factor): - """Put factor-1 zeros between neighbouring elements of each dim.""" - if all(f == 1 for f in factor): - return t - n = len(extents) - paired = list(lead) - for extent in extents: - paired += [extent, 1] - y = L[aten.view](t, paired) - pad = [] - for i in reversed(range(n)): - pad += [0, factor[i] - 1, 0, 0] - y = L[aten.constant_pad_nd](y, pad, 0.0) - y = L[aten.view](y, list(lead) + - [extents[i] * factor[i] for i in range(n)]) - for i in range(n): - if factor[i] != 1: - y = L[aten.slice](y, len(lead) + i, 0, - extents[i] * factor[i] - (factor[i] - 1)) - return y - - def _rewrite(x, weight, stride, padding, dilation, output_padding, groups): - """Return the (x, weight, *params) of the equivalent direct conv.""" - ints = V.graph.sizevars.guard_int_seq - batch, in_chan, *spatial = ints(x.get_size()) - _, out_per_group, *kernel = ints(weight.get_size()) - n_sp = len(kernel) - out_chan = out_per_group * groups - stride = _per_dim(stride, n_sp) - padding = _per_dim(padding, n_sp) - dilation = _per_dim(dilation, n_sp) - output_padding = _per_dim(output_padding, n_sp) - - y = _spread(x, [batch, in_chan], spatial, stride) - - pad = [] - for i in reversed(range(n_sp)): - lo = dilation[i] * (kernel[i] - 1) - padding[i] - pad += [lo, lo + output_padding[i]] - if any(p != 0 for p in pad): - y = L[aten.constant_pad_nd](y, pad, 0.0) - - w = L[aten.view](weight, [groups, in_chan // groups, - out_chan // groups] + kernel) - w = L[aten.permute](w, [0, 2, 1] + [3 + i for i in range(n_sp)]) - w = L[aten.view](w, [out_chan, in_chan // groups] + kernel) - if any(k != 1 for k in kernel): - w = L[prims.rev.default](w, [2 + i for i in range(n_sp)]) - - w = _spread(w, [out_chan, in_chan // groups], kernel, dilation) - - return y, w, [1] * n_sp, [0] * n_sp, [1] * n_sp, [0] * n_sp - - def lower(inner, a, args, kwargs): - """The lowering itself: a transposed npu conv as its direct equivalent, else inner.""" - if a is None: - return inner(*args, **kwargs) - x, weight = a["x"], a["weight"] - if not a["transposed"] or ir.get_device_type(x) != "npu": - return inner(*args, **kwargs) - - batchless = len(x.get_size()) == len(weight.get_size()) - 1 - if batchless: - x = L[aten.expand](x, [1, *x.get_size()]) - - y, w, stride, padding, dilation, output_padding = _rewrite( - x, weight, a["stride"], a["padding"], a["dilation"], - a["output_padding"], a["groups"]) - out = inner(y, w, a["bias"], stride, padding, dilation, False, - output_padding, a["groups"]) - return L[aten.squeeze](out, dim=0) if batchless else out - - def wrap(inner): - @functools.wraps(inner) - def convolution(*args, **kwargs): - try: - bound = sig.bind(*args, **kwargs) - bound.apply_defaults() - a = bound.arguments - groups = a.get("groups", 1) - except TypeError: - a, groups = None, 1 - prev = getattr(_conv_groups, "value", 1) - _conv_groups.value = groups if isinstance(groups, int) else 1 - try: - return lower(inner, a, args, kwargs) - finally: - _conv_groups.value = prev - - return convolution - - packet = torch.ops.aten.convolution - for key in [packet] + [getattr(packet, o) for o in packet.overloads()]: - inner = inductor_lowering.lowerings.get(key) - if inner is not None: - inductor_lowering.lowerings[key] = wrap(inner) - - -def _npu_config_heuristic(): - """npu's own conv tile table, built once: BLOCK_N is the lane count, per group.""" - global _NPU_CONFIG_HEURISTIC - if _NPU_CONFIG_HEURISTIC is not None: - return _NPU_CONFIG_HEURISTIC() - from torch._inductor.heuristics.template.triton import ( - BaseConfigHeuristic, ConvConfig) - - lanes = int(config.CONFIG_MACHINE.vector_lanes) - - class NPUConfigHeuristic(BaseConfigHeuristic): - def __init__(self): - super().__init__() - self.conv_configs = [ - ConvConfig(64, lanes, 16, 1, 4), - ConvConfig(32, lanes, 16, 1, 4), - ConvConfig(64, lanes, 32, 1, 4), - ] - - def get_conv_configs(self): - base = super().get_conv_configs() - - def per_group(m, n, k, **kwargs): - groups = _groups_now() - return base(m, max(1, n // groups) if groups > 1 else n, k, - **kwargs) - - return per_group - - _NPU_CONFIG_HEURISTIC = NPUConfigHeuristic - return NPUConfigHeuristic() - - -def _size_grouped_conv_grid_per_group(): - """Grid a grouped convolution over one group's channels, not all of them.""" - from torch._inductor.kernel import conv as conv_kernel - from torch._inductor.select_algorithm import SymbolicGridFn - - orig2d = conv_kernel.conv2d_grid - orig3d = conv_kernel.conv3d_grid - - @SymbolicGridFn - def conv2d_grid(n, c, h, w, meta, *, cdiv): - if not _lowering_npu(): - return orig2d(n, c, h, w, meta) - groups = meta.get("GROUPS", 1) or 1 - return ( - cdiv(n * h * w, meta["BLOCK_M"]), - cdiv(cdiv(c, groups), meta["BLOCK_N"]), - groups, - ) - - @SymbolicGridFn - def conv3d_grid(n, c, d, h, w, meta, *, cdiv): - if not _lowering_npu(): - return orig3d(n, c, d, h, w, meta) - groups = meta.get("GROUPS", 1) or 1 - return ( - cdiv(n * d * h * w, meta["BLOCK_M"]), - cdiv(cdiv(c, groups), meta["BLOCK_N"]), - groups, - ) - - conv_kernel.conv2d_grid = conv2d_grid - conv_kernel.conv3d_grid = conv3d_grid - for tmpl, fn in ((getattr(conv_kernel, "conv2d_template", None), conv2d_grid), - (getattr(conv_kernel, "conv3d_template", None), conv3d_grid)): - if tmpl is not None: - tmpl.grid = fn - - -def pick_config(choices): - """Timings in place of benchmarking: the offered order wins, extern last.""" - from torch._inductor.select_algorithm import ExternKernelCaller - - return {c: (1e3 if isinstance(c, ExternKernelCaller) else 1.0) + i * 1e-3 - for i, c in enumerate(choices)} - - -def _short_circuit_degenerate_gemms(): - """Lower an npu mm/bmm/addmm/baddbmm with a zero-length M or N (or K, unbiased) as zeros.""" - from torch._inductor.kernel.mm_common import mm_args - from torch._inductor.lowering import full, lowerings - from torch._inductor.virtualized import V - - def wrap(op, bias): - def wrapped(*args, _orig=lowerings[op], **kwargs): - try: - m, n, k, layout = mm_args(*args[bias:bias + 2], - layout=kwargs.get("layout"))[:4] - m, n, k = (int(V.graph.sizevars.optimization_hint(s)) for s in (m, n, k)) - except Exception: - return _orig(*args, **kwargs) - if not _is_npu(layout): - return _orig(*args, **kwargs) - if m == 0 or n == 0 or (k == 0 and not bias): - return full(layout.size, 0, dtype=layout.dtype, - device=layout.device) - return _orig(*args, **kwargs) - - return wrapped - - aten = torch.ops.aten - for op, bias in ((aten.mm, 0), (aten.bmm, 0), - (aten.addmm, 1), (aten.baddbmm, 1)): - for name in op.overloads(): - o = getattr(op, name) - if o in lowerings: - lowerings[o] = wrap(o, bias) - - -def _num_cores(): - """This machine's core count, from the TOGSim config.""" - try: - return max(1, int(config.CONFIG_NUM_CORES)) - except Exception: # noqa: BLE001 - return 1 - - -def _kept_axis_contiguous(features): - """'x' when the largest read (in bytes) over every index of a reduction runs unit-stride along a - kept axis, from its MemoryDep strides; else None. Inductor's OUTER hint is not used: it is left - DEFAULT for any kernel of at least num_sm * 64 rows, whatever its strides.""" - from torch._inductor.dependencies import MemoryDep - from torch._inductor.virtualized import V - if not features.is_reduction(): - return None - best = None - for node in features.reduction_nodes(): - kept, reduced = node._sizes - for dep in node.read_writes.reads: - if not isinstance(dep, MemoryDep) or len(dep.var_names) != len(kept) + len(reduced): - continue - strides = V.graph.sizevars.stride_hints(dep.index, dep.var_names) - unit = [i for i, s in enumerate(strides) if s == 1] - if not unit: - continue - size = dep.numbytes_hint() - if best is None or size > best[0]: - best = (size, unit[0] < len(kept)) - return "x" if best and best[1] else None - - -_DT_BITS = {torch.float64: 64, torch.float32: 32, torch.float16: 16, - torch.bfloat16: 16, torch.int64: 64, torch.int32: 32, - torch.int16: 16, torch.int8: 8, torch.uint8: 8, torch.bool: 8} - - -def _elem_args(features): - """The widest tensor a scheduled node makes or reads, as fixed_config_for's args.""" - from torch._inductor.virtualized import V - bits = [] - for nd in features.scheduler_nodes(): - try: - bits.append(_DT_BITS.get(nd.node.get_dtype(), 32)) - except Exception: - pass - for dep in getattr(getattr(nd, "read_writes", None), "reads", ()) or (): - try: - bits.append(_DT_BITS.get(V.graph.get_dtype(dep.name), 32)) - except Exception: - pass - return ([{"dtype": {64: "float64", 32: "float32", 16: "float16", - 8: "int8"}[max(bits)]}] if bits else []) - - -def pinned_blocks(kernel_tiling, features): - """This machine's blocks for a kernel of `kernel_tiling` as a FixedTritonConfig, or None. - - The numels come from the tiling; the dtype width from the widest tensor a scheduled node makes - or reads; whether the kept axis is the contiguous one from Inductor's hint. - """ - from torch._inductor.codegen.triton import FixedTritonConfig - - numels = {} - for prefix, n in (kernel_tiling or {}).items(): - try: - numels[f"{prefix}numel"] = int(n) - except Exception: - pass - if not numels or features is None: - return None - args = _elem_args(features) - shim = type("K", (), {"inside_reduction": bool(features.is_reduction()), - "numels": numels})() - try: - cfg = tiling.fixed_config_for(shim, numels, args, - contiguous=_kept_axis_contiguous(features)) or {} - except Exception as e: # noqa: BLE001 - logger.info("[torchsim-compile] no fixed_config for this kernel: %s", e) - return None - cfg = {k: int(v) for k, v in cfg.items() if v and k.endswith("BLOCK")} - return FixedTritonConfig(cfg) if cfg else None - - -def _npu_choices_class(): - """NPUChoices, built once: Inductor's lookup-table choices, with this machine's reduction - policy and its recorded template picks.""" - global _NPU_CHOICES - if _NPU_CHOICES is not None: - return _NPU_CHOICES - from torch._inductor.choices import InductorChoices - from torch._inductor.lookup_table import LookupTableChoices - - from pytorchsim.driver import select - - class NPUChoices(LookupTableChoices): - def uuid(self): - """This class's part of Inductor's cache key: the machine and the picks it hands out.""" - return f"pytorchsim-npu-choices-4-{select.graph_digest()}" - - def _get_lookup_table(self): - """This machine's recorded picks; Inductor's own looks only on CUDA.""" - return select.lookup_table() - - @staticmethod - def _get_device_key(device): - if getattr(device, "type", None) == "npu": - return select.device_key() - return LookupTableChoices._get_device_key(device) - - def _create_lookup_choices(self, *args, **kwargs): - """Inductor's choices from the recorded configs, each marked as recorded.""" - ktcs = super()._create_lookup_choices(*args, **kwargs) - for ktc in ktcs: - ktc.annotations[select.SOURCE] = select.RECORDED - return ktcs - - def get_config_heuristics(self, device_type="cuda"): - """npu's own conv tile table; every other device keeps upstream's.""" - if device_type == "npu": - return _npu_config_heuristic() - return super().get_config_heuristics(device_type) - - @staticmethod - def should_use_persistent_reduction(features, cooperative_reduction): - """Persistent only when the whole reduction fits this machine's reduction block.""" - base = InductorChoices.should_use_persistent_reduction( - features, cooperative_reduction) - if not base or not _lowering_npu(): - return base - try: - extent = int(features.reduction_numel) - except (TypeError, ValueError): - return base - if extent < 1: - return base - persistent = 1 << (extent - 1).bit_length() - try: - numels = {"xnumel": int(features.numel), "r0_numel": extent} - shim = type("K", (), {"inside_reduction": True, "numels": numels})() - pinned = tiling.fixed_config_for(shim, numels, _elem_args(features), - contiguous=_kept_axis_contiguous(features)) - return persistent <= int(pinned["R0_BLOCK"]) - except Exception: # noqa: BLE001 - return persistent <= tiling.reduction_block_for(extent) - - def reduction_split_factor(self, device, reduction_numel_hint, numel_hint, - inner_reduction): - """Split a reduction only when a core would otherwise sit idle, and at most cores ways. - - One core, or a parallel axis that already fills the cores, means no split. - """ - if getattr(device, "type", device) != "npu": - return super().reduction_split_factor( - device, reduction_numel_hint, numel_hint, inner_reduction) - cores = _num_cores() - if cores > 1: - want = super().reduction_split_factor( - device, reduction_numel_hint, numel_hint, inner_reduction) - try: - if int(numel_hint) >= cores: - return 1 - except (TypeError, ValueError): - return 1 - split = min(int(want), cores) - if split > 1: - logger.info( - "[torchsim-compile] splitting a reduction of %s elements %s ways " - "over %s cores (upstream wanted %s)", - reduction_numel_hint, split, cores, want) - return split - return 1 - return 1 - - NPUChoices.__module__ = __name__ - NPUChoices.__qualname__ = "NPUChoices" - globals()["NPUChoices"] = NPUChoices - _NPU_CHOICES = NPUChoices - return NPUChoices - - -def _install_npu_choices(): - """Register the choices this hardware makes differently: persistence, splits.""" - from torch._inductor import config as inductor_config - - if inductor_config.inductor_choices_class is None: - inductor_config.inductor_choices_class = _npu_choices_class() - - -def _is_depthwise(input, weight, groups): - """One channel a group, in and out: the conv is a per-channel stencil, not a matmul.""" - return (groups > 1 and input.shape[1] == groups and weight.shape[0] == groups - and weight.shape[1] == 1) - - -def _depthwise_stencil(x, w, bias, stride, padding, dilation): - """A depthwise 2-D conv as taps: each a strided slice of the padded input times its weight, summed.""" - (sh, sw), (ph, pw), (dh, dw) = stride, padding, dilation - g, _, kh, kw = w.shape - x = torch.ops.aten.constant_pad_nd(x, [pw, pw, ph, ph]) - h_out = (x.shape[2] - dh * (kh - 1) - 1) // sh + 1 - w_out = (x.shape[3] - dw * (kw - 1) - 1) // sw + 1 - out = None - for i in range(kh): - for j in range(kw): - tap = x[:, :, i * dh:i * dh + sh * (h_out - 1) + 1:sh, - j * dw:j * dw + sw * (w_out - 1) + 1:sw] - term = tap * w[:, 0, i, j].reshape(1, g, 1, 1) - out = term if out is None else out + term - return out if bias is None else out + bias.reshape(1, g, 1, 1) - - -def _decompose_convolution_for_npu(): - """Register npu's aten.convolution decompositions: a Conv1d reaches the 2-D template through - torch's conv1d_to_conv2d, and a depthwise 2-D conv is a stencil on the vector unit. Declines - non-npu inputs, transposed convs and output_padding; anything else keeps the template.""" - from torch._inductor.decomposition import conv1d_to_conv2d, register_decomposition - - aten = torch.ops.aten - - @register_decomposition([aten.convolution]) - def _npu_convolution(input, weight, bias, stride, padding, dilation, - transposed, output_padding, groups): - if input.device.type != "npu" or transposed: - return NotImplemented - if any(p != 0 for p in output_padding): - return NotImplemented - if len(stride) == 1: - return conv1d_to_conv2d(input, weight, bias, stride, padding, dilation, groups) - if len(stride) == 2 and _is_depthwise(input, weight, groups): - return _depthwise_stencil(input, weight, bias, stride, padding, dilation) - return NotImplemented - - -def _install_selection(): - """Patch algorithm selection for npu choices: cycles from TOGSim in timing mode, the offered - order otherwise; no precompile; allocate-only examples. A recorded pick is the only choice, - and a timed one is recorded.""" - from torch._inductor import config as inductor_config - from torch._inductor import select_algorithm - from torch._inductor.select_algorithm import AlgorithmSelectorCache - - from pytorchsim.driver import select - - orig_benchmark = AlgorithmSelectorCache.__dict__["benchmark_choices"].__func__ - orig_call = AlgorithmSelectorCache.__call__ - orig_precompile = AlgorithmSelectorCache.make_precompile_fn - orig_example = AlgorithmSelectorCache.__dict__["generate_example_value"].__func__ - - def _choices_are_npu(choices): - return any(_is_npu(getattr(c, "layout", None)) for c in choices) - - def benchmark_choices(cls, choices, autotune_args, is_collective=False): - if not _choices_are_npu(choices): - return orig_benchmark(cls, choices, autotune_args, is_collective) - timed = bool(config.pytorchsim_timing_mode) - if timed != inductor_config.benchmark_epilogue_fusion: - raise RuntimeError( - "TORCHSIM_TIMING_MODE changed after pytorchsim was installed: Inductor's " - "epilogue-fusion benchmark follows the mode the process started in") - if timed and select.times(choices): - return select.time_choices(choices) - return pick_config(choices) - - def __call__(self, name, choices, *args, **kwargs): - """Inductor's selection; a fusion is benchmarked only for choices timed in cycles.""" - if _choices_are_npu(choices) and not select.times(choices): - kwargs["return_multi_template"] = False - return orig_call(self, name, choices, *args, **kwargs) - - def make_precompile_fn(self, choices, *args, **kwargs): - if not _choices_are_npu(choices): - return orig_precompile(self, choices, *args, **kwargs) - return lambda: None - - def generate_example_value(size, stride, device, dtype, extra_size, - allocation_size=None): - """An unread benchmark operand, allocated rather than sampled.""" - if not _is_npu(device): - return orig_example(size, stride, device, dtype, extra_size, - allocation_size) - shape = size if allocation_size is None else allocation_size - needed = extra_size - if all(s > 0 for s in shape): - needed += sum((s - 1) * t for s, t in zip(shape, stride)) + 1 - view = torch.as_strided( - torch.empty(needed, dtype=dtype, device=device), shape, stride) - return view if tuple(shape) == tuple(size) else view.as_strided(size, stride) - - AlgorithmSelectorCache.benchmark_choices = classmethod(benchmark_choices) - AlgorithmSelectorCache.__call__ = __call__ - AlgorithmSelectorCache.make_precompile_fn = make_precompile_fn - AlgorithmSelectorCache.generate_example_value = staticmethod( - generate_example_value) - select_algorithm.add_preprocessing_fn(select.keep_recorded) - select_algorithm.add_feedback_saver(select.record) - - -def install(): - """Apply every patch here once, and turn on Inductor's mm/conv template autotune.""" - global _installed - if _installed: - return - from torch._inductor import config as inductor_config - - _register_npu_as_gpu() - _register_template_heuristics() - _wrap_convolution_lowering() - _size_grouped_conv_grid_per_group() - _short_circuit_degenerate_gemms() - _install_npu_choices() - _decompose_convolution_for_npu() - _install_selection() - from pytorchsim.frontend import attention, grouped_mm, topk - attention.install() - grouped_mm.install() - topk.install() - - inductor_config.max_autotune_gemm = True - inductor_config.max_autotune_gemm_backends = "ATEN,TRITON" - inductor_config.max_autotune_conv_backends = "ATEN,TRITON" - inductor_config.triton.autotune_at_compile_time = False - # In timing mode a template with an epilogue is picked by its fused cycles: Inductor times the - # top configs fused (TritonNPUScheduling.benchmark_codegened_module), one at a time in this - # process. Picks are recorded by select, so Inductor's own autotune cache stays off. - timed = bool(config.pytorchsim_timing_mode) - inductor_config.benchmark_epilogue_fusion = timed - inductor_config.max_epilogue_benchmarked_choices = config.codegen_autotune_template_topk - inductor_config.autotune_local_cache = False - if timed: - inductor_config.compile_threads = 1 - - _installed = True diff --git a/pytorchsim/frontend/rewrite_fx_graph.py b/pytorchsim/frontend/rewrite_fx_graph.py deleted file mode 100644 index 4c5bf1a6c..000000000 --- a/pytorchsim/frontend/rewrite_fx_graph.py +++ /dev/null @@ -1,339 +0,0 @@ -"""Our rewrites of the FX graph, so ops with no npu kernel stay on the device. - -Decompositions (histc, polar) and post-grad passes (grouped_mm, row mm, complex to real -pairs), all chained onto Inductor's one post-grad hook by install(). topk is frontend/topk.py. -""" - -import torch -from torch import fx -from torch._inductor.custom_graph_pass import CustomGraphPass -from torch._inductor.decomposition import register_decomposition - -aten = torch.ops.aten -prims = torch.ops.prims - - -@register_decomposition(aten.histc.default) -def decompose_histc(self, bins: int = 100, min: int = 0, max: int = 0): - """Counts of an integral tensor, on the device when the bins are the values. - - Exact for bins=N, min=0, max=N-1; any other edges keep the CPU hop. - """ - if self.is_floating_point(): - return NotImplemented - if int(min) == 0 and int(max) == int(bins) - 1: - vals = torch.arange(int(bins), device=self.device, dtype=self.dtype) - counts = (self.reshape(-1, 1) == vals.reshape(1, -1)).sum(0) - return counts.to(self.dtype) - counts = torch.histc(self.to(torch.float32), bins, min, max) - return counts.to(self.dtype) - - -@register_decomposition(aten.polar.default) -def decompose_polar(abs, angle): - """`polar` as a view over a real pair, so it never becomes an extern call. - - The pair is made contiguous because view_as_complex needs a unit last stride. - """ - pair = torch.stack((abs * torch.cos(angle), abs * torch.sin(angle)), dim=-1) - return torch.view_as_complex(pair.contiguous()) - - -def is_npu_graph(g) -> bool: - """Whether any tensor in this graph lives on the npu device.""" - graph = getattr(g, "graph", g) - for node in graph.nodes: - val = node.meta.get("val") - for t in (val if isinstance(val, (tuple, list)) else (val,)): - if isinstance(t, torch.Tensor) and t.device.type == "npu": - return True - return False - - -def npu_only(fn): - """The same pass, a no-op on a graph with no npu tensor.""" - def _gated(graph): - if is_npu_graph(graph): - fn(graph) - return _gated - - -def _identity(fn): - """A name for a foreign callable that is the same in every process.""" - uuid = getattr(fn, "uuid", None) - if callable(uuid): - return uuid() - module = getattr(fn, "__module__", "?") - name = getattr(fn, "__qualname__", None) - return f"{module}.{name}" if name else f"{module}." - - -class _Chain(CustomGraphPass): - """Inductor's single post-grad slot, as a chain that knows what is in it.""" - - def __init__(self, foreign): - self._foreign = foreign - self._keys = [] - self._passes = [] - - def add(self, key, fn) -> bool: - """Append fn under key, or report that key is already chained.""" - if key in self._keys: - return False - self._keys.append(key) - self._passes.append(fn) - return True - - def uuid(self): - head = () if self._foreign is None else (_identity(self._foreign),) - return head + tuple(self._keys) - - def __call__(self, graph): - if self._foreign is not None: - self._foreign(graph) - for fn in self._passes: - fn(graph) - - -def install_once(key, fn): - """Chain fn onto Inductor's post-grad hook, at most once per key.""" - from torch._inductor import config - - chain = config.post_grad_custom_post_pass - if not isinstance(chain, _Chain): - chain = _Chain(chain) - config.post_grad_custom_post_pass = chain - return chain.add(key, fn) - - -def _recompile(g): - """Drop what a rewrite left dead and refresh the owning module's code.""" - g.eliminate_dead_code() - if g.owning_module is not None: - g.owning_module.recompile() - - -def _grouped_mm_target(): - """transformers' grouped_mm_fallback overload, or None until transformers is imported.""" - ns = getattr(torch.ops, "transformers", None) - op = getattr(ns, "grouped_mm_fallback", None) if ns is not None else None - return op.default if op is not None else None - - -def _emit_dense_grouped_mm(g, inp, weight, offs, s, e, o, dtype, dev): - """Every expert over the whole input, masked to its own rows and summed. - - Returns the (s, o) result node. - """ - call = g.call_function - i64 = torch.int64 - rows = call(prims.iota.default, (s,), - {"start": 0, "step": 1, "dtype": i64, "device": dev, - "requires_grad": False}) - rows2 = call(aten.view.default, (rows, [s, 1])) - offs64 = call(prims.convert_element_type.default, (offs, i64)) - offs2 = call(aten.view.default, (offs64, [1, e])) - reached = call(aten.ge.Tensor, (rows2, offs2)) - reached64 = call(prims.convert_element_type.default, (reached, i64)) - expert_of = call(aten.sum.dim_IntList, (reached64, [1])) - - out = call(aten.full.default, ([s, o], 0), {"dtype": dtype, "device": dev}) - for i in range(e): - wi = call(aten.clone.default, (call(aten.select.int, (weight, 0, i)),), - {"memory_format": torch.contiguous_format}) - part = call(aten.mm.default, (inp, wi)) - keep = call(aten.eq.Scalar, (expert_of, i)) - keep2 = call(aten.view.default, (keep, [s, 1])) - keepf = call(prims.convert_element_type.default, (keep2, dtype)) - out = call(aten.add.Tensor, (out, call(aten.mul.Tensor, (part, keepf)))) - return out - - -def rewrite_grouped_mm(g) -> None: - """Replace every `transformers.grouped_mm_fallback` call with the dense form.""" - target = _grouped_mm_target() - if target is None: - return - if isinstance(g, fx.GraphModule): - g = g.graph - changed = 0 - for node in list(g.nodes): - if node.op != "call_function" or node.target is not target: - continue - inp, weight, offs = node.args[0], node.args[1], node.args[2] - iv = inp.meta.get("val") if hasattr(inp, "meta") else None - wv = weight.meta.get("val") if hasattr(weight, "meta") else None - if iv is None or wv is None or iv.dim() != 2 or wv.dim() != 3: - continue - s, e, o = int(iv.shape[0]), int(wv.shape[0]), int(wv.shape[2]) - with g.inserting_before(node): - dense = _emit_dense_grouped_mm(g, inp, weight, offs, s, e, o, - iv.dtype, iv.device) - node.replace_all_uses_with(dense) - changed += 1 - if changed: - _recompile(g) - - -def _row_times_matrix(node): - """(a, b, bias) of an mm or a plain addmm whose left operand is one row, else None.""" - if node.op != "call_function": - return None - if node.target is aten.mm.default: - (a, b), bias = node.args, None - elif node.target is aten.addmm.default and not node.kwargs: - bias, a, b = node.args - else: - return None - av, bv = _val(a), _val(b) - if av is None or bv is None or av.dim() != 2 or bv.dim() != 2 or av.shape[0] != 1: - return None - return a, b, bias - - -def rewrite_row_mm(g) -> None: - """Replace a 1 x K row times a K x N matrix with the row broadcast down the matrix, a - multiply and a sum over K: vector work, where the mm template would run it on the array.""" - if isinstance(g, fx.GraphModule): - g = g.graph - changed = 0 - for node in list(g.nodes): - found = _row_times_matrix(node) - if found is None: - continue - a, b, bias = found - k = int(_val(a).shape[1]) - with g.inserting_before(node): - column = g.call_function(aten.view.default, (a, [k, 1])) - scaled = g.call_function(aten.mul.Tensor, (column, b)) - out = g.call_function(aten.sum.dim_IntList, (scaled, [0], True)) - if bias is not None: - out = g.call_function(aten.add.Tensor, (out, bias)) - node.replace_all_uses_with(out) - changed += 1 - if changed: - _recompile(g) - - -_MUL = (aten.mul.Tensor, aten.mul.Scalar) -_SHAPE = (aten.unsqueeze.default,) -_HANDLED = (aten.view_as_complex.default,) + _MUL + _SHAPE - - -def _val(node): - """The fake value of a node, or the argument itself when it is not a node.""" - return node.meta.get("val", None) if isinstance(node, torch.fx.Node) else node - - -def _is_complex(node): - """Whether the node holds a complex tensor.""" - v = _val(node) - return isinstance(v, torch.Tensor) and v.is_complex() - - -def _fake_mode(graph): - """The fake mode of the graph's tensors, or None.""" - for n in graph.nodes: - v = _val(n) - if isinstance(v, torch.Tensor) and hasattr(v, "fake_mode"): - return v.fake_mode - return None - - -class ComplexToRealPairs(CustomGraphPass): - """Complex values become their real [..., 2] pairs, whole component or nothing. - - Handles view_as_complex, mul and unsqueeze; any other complex op leaves the graph as is. - """ - - def uuid(self): - return "pytorchsim-complex-to-real-pairs-3" - - def __call__(self, graph: torch.fx.Graph) -> None: - complex_nodes = [n for n in graph.nodes if _is_complex(n)] - if not complex_nodes: - return - - for n in complex_nodes: - if n.op != "call_function": - return - if n.target not in _HANDLED: - return - for user in n.users: - if user.op == "output": - return - if user.target is aten.view_as_real.default: - continue - if user.target in _HANDLED: - continue - return - - fake_mode = _fake_mode(graph) - - def _unwrap(a): - if isinstance(a, (list, tuple)): - return type(a)(_unwrap(x) for x in a) - return _val(a) - - def call(target, *args): - node = graph.call_function(target, args) - if fake_mode is not None: - with fake_mode: - node.meta["val"] = target(*[_unwrap(a) for a in args]) - return node - - def join(re, im): - return call(aten.cat.default, - [call(aten.unsqueeze.default, re, -1), - call(aten.unsqueeze.default, im, -1)], -1) - - pair = {} - for n in complex_nodes: - with graph.inserting_before(n): - if n.target is aten.view_as_complex.default: - pair[n] = n.args[0] - continue - - if n.target in _SHAPE: - dim = n.args[1] - pair[n] = call(n.target, pair[n.args[0]], - dim if dim >= 0 else dim - 1) - continue - - a, b = n.args[0], n.args[1] - cx, other = (a, b) if _is_complex(a) else (b, a) - if _is_complex(other) or isinstance(other, complex): - pa = pair[cx] - ar = call(aten.select.int, pa, -1, 0) - ai = call(aten.select.int, pa, -1, 1) - if isinstance(other, complex): - br, bi = other.real, other.imag - else: - br = call(aten.select.int, pair[other], -1, 0) - bi = call(aten.select.int, pair[other], -1, 1) - re = call(aten.sub.Tensor, call(aten.mul.Tensor, ar, br), - call(aten.mul.Tensor, ai, bi)) - im = call(aten.add.Tensor, call(aten.mul.Tensor, ar, bi), - call(aten.mul.Tensor, ai, br)) - pair[n] = join(re, im) - else: - if isinstance(other, torch.fx.Node): - other = call(aten.unsqueeze.default, other, -1) - pair[n] = call(aten.mul.Tensor, pair[cx], other) - - for n in complex_nodes: - for user in list(n.users): - if user.target is aten.view_as_real.default: - user.replace_all_uses_with(pair[n]) - - graph.eliminate_dead_code() - - -_COMPLEX_TO_REAL = ComplexToRealPairs() - - -def install(): - """Chain the post-grad passes onto Inductor's hook, each at most once.""" - install_once("pytorchsim-grouped-mm", npu_only(rewrite_grouped_mm)) - install_once("pytorchsim-row-mm", npu_only(rewrite_row_mm)) - install_once(_COMPLEX_TO_REAL.uuid(), npu_only(_COMPLEX_TO_REAL)) diff --git a/pytorchsim/simulator/functional.py b/pytorchsim/simulator/functional.py index 3a1bfa0eb..75af38836 100644 --- a/pytorchsim/simulator/functional.py +++ b/pytorchsim/simulator/functional.py @@ -12,7 +12,7 @@ from pytorchsim import contract from pytorchsim.contract import storage_span -from pytorchsim.driver import compiler_bridge +from pytorchsim.backend import compiler_bridge logger = config.setup_logger() diff --git a/pytorchsim/simulator/timing.py b/pytorchsim/simulator/timing.py index 4f37e2941..c93ba43ab 100644 --- a/pytorchsim/simulator/timing.py +++ b/pytorchsim/simulator/timing.py @@ -14,7 +14,7 @@ from pytorchsim import config from pytorchsim import contract -from pytorchsim.driver import compiler_bridge +from pytorchsim.backend import compiler_bridge from pytorchsim.simulator import wallclock logger = config.setup_logger() diff --git a/scripts/ci/bundle.py b/scripts/ci/bundle.py index 5518d9fd9..6a27affb4 100644 --- a/scripts/ci/bundle.py +++ b/scripts/ci/bundle.py @@ -49,7 +49,7 @@ import torch # noqa: E402 (first: its device autoload installs pytorchsim) from pytorchsim import config, contract # noqa: E402 -from pytorchsim.driver import codecache, compiler_bridge, compiler_input, select # noqa: E402 +from pytorchsim.backend import codecache, compiler_bridge, compiler_input, select # noqa: E402 from pytorchsim.simulator import functional # noqa: E402 #: The head dimension the compiler's attention measurements were taken at. diff --git a/scripts/ci/triton_route_passing.txt b/scripts/ci/triton_route_passing.txt index d83ec26e7..dde0d3d80 100644 --- a/scripts/ci/triton_route_passing.txt +++ b/scripts/ci/triton_route_passing.txt @@ -178,7 +178,7 @@ # alias key covers PrivateUse1, so the CPU fallback never gets # a turn, and a kernel would run the convolution on the host # and simulate nothing. Fixed by not emitting it: -# pytorchsim/frontend/inductor_patches.py rewrites a transposed +# pytorchsim/frontend/inductor/lowering.py rewrites a transposed # convolution as the direct one it is, wrapped around the # convolution lowering. OUT OF THE GATE ON RUNTIME -- 498s # would take the gate to about 1600s against an 1800s budget diff --git a/scripts/op_coverage.py b/scripts/op_coverage.py deleted file mode 100644 index 73c23233d..000000000 --- a/scripts/op_coverage.py +++ /dev/null @@ -1,663 +0,0 @@ -"""Op-coverage diagnostic for new LLM models on PyTorchSim. - -Runs each model in two phases: - Phase 1 (enumerate): custom torch.compile backend captures the FX graph and - lists every aten op that appears, without touching NPU. - Phase 2 (run): torch.compile(model) on npu:0, real forward. On crash, - parses the traceback to identify the failing op. - -Usage: - python scripts/op_coverage.py # all models - python scripts/op_coverage.py --models qwen2 # subset - python scripts/op_coverage.py --enumerate-only # skip NPU compile (fast) -""" - -import argparse -import datetime as _dt -import os -import re -import sys -import traceback -from contextlib import contextmanager - -import torch - -REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) -if REPO_ROOT not in sys.path: - sys.path.insert(0, REPO_ROOT) - - -# --------------------------------------------------------------------------- -# Model registry: each entry returns (model, kwargs_for_forward) on CPU. -# Sizes follow "small but realistic" variants (1-layer) so a forward is cheap -# enough to actually drive through TOGSim. -# --------------------------------------------------------------------------- - -def _causal_mask(batch, seq_len, dtype): - min_v = torch.finfo(dtype).min - m = torch.full((seq_len, seq_len), min_v, dtype=dtype) - if seq_len > 1: - m = torch.triu(m, diagonal=1) - return m[None, None, :, :].expand(batch, 1, -1, -1).contiguous() - - -def build_qwen2(batch=1, seq_len=32, dtype=torch.float32): - from transformers.models.qwen2.configuration_qwen2 import Qwen2Config - from transformers.models.qwen2.modeling_qwen2 import Qwen2Model - cfg = Qwen2Config( - vocab_size=4096, - hidden_size=1536, - num_attention_heads=12, - num_key_value_heads=2, - intermediate_size=8960, - num_hidden_layers=2, - max_position_embeddings=4096, - rms_norm_eps=1e-6, - rope_theta=1000000.0, - torch_dtype=dtype, - use_cache=False, - _attn_implementation="eager", - ) - model = Qwen2Model(cfg).eval().to(dtype=dtype) - input_ids = torch.randint(0, cfg.vocab_size, (batch, seq_len)) - attn_mask = _causal_mask(batch, seq_len, dtype) - return model, {"input_ids": input_ids, "attention_mask": attn_mask} - - -def build_gemma(batch=1, seq_len=32, dtype=torch.float32): - from transformers.models.gemma.configuration_gemma import GemmaConfig - from transformers.models.gemma.modeling_gemma import GemmaModel - cfg = GemmaConfig( - vocab_size=4096, - hidden_size=2048, - num_attention_heads=8, - num_key_value_heads=1, - intermediate_size=16384, - num_hidden_layers=2, - head_dim=256, - max_position_embeddings=4096, - rms_norm_eps=1e-6, - rope_theta=10000.0, - torch_dtype=dtype, - use_cache=False, - _attn_implementation="eager", - ) - model = GemmaModel(cfg).eval().to(dtype=dtype) - input_ids = torch.randint(0, cfg.vocab_size, (batch, seq_len)) - attn_mask = _causal_mask(batch, seq_len, dtype) - return model, {"input_ids": input_ids, "attention_mask": attn_mask} - - -def build_gemma2(batch=1, seq_len=32, dtype=torch.float32): - from transformers.models.gemma2.configuration_gemma2 import Gemma2Config - from transformers.models.gemma2.modeling_gemma2 import Gemma2Model - cfg = Gemma2Config( - vocab_size=4096, - hidden_size=2304, - num_attention_heads=8, - num_key_value_heads=4, - intermediate_size=9216, - num_hidden_layers=2, - head_dim=256, - max_position_embeddings=4096, - rms_norm_eps=1e-6, - rope_theta=10000.0, - torch_dtype=dtype, - use_cache=False, - attn_logit_softcapping=50.0, - final_logit_softcapping=30.0, - sliding_window=16, - _attn_implementation="eager", - ) - model = Gemma2Model(cfg).eval().to(dtype=dtype) - input_ids = torch.randint(0, cfg.vocab_size, (batch, seq_len)) - attn_mask = _causal_mask(batch, seq_len, dtype) - return model, {"input_ids": input_ids, "attention_mask": attn_mask} - - -def build_phi3(batch=1, seq_len=32, dtype=torch.float32): - from transformers.models.phi3.configuration_phi3 import Phi3Config - from transformers.models.phi3.modeling_phi3 import Phi3Model - cfg = Phi3Config( - vocab_size=4096, - pad_token_id=0, - bos_token_id=1, - eos_token_id=2, - hidden_size=3072, - num_attention_heads=32, - num_key_value_heads=32, - intermediate_size=8192, - num_hidden_layers=2, - max_position_embeddings=4096, - rms_norm_eps=1e-5, - rope_theta=10000.0, - torch_dtype=dtype, - use_cache=False, - _attn_implementation="eager", - ) - model = Phi3Model(cfg).eval().to(dtype=dtype) - input_ids = torch.randint(0, cfg.vocab_size, (batch, seq_len)) - attn_mask = _causal_mask(batch, seq_len, dtype) - return model, {"input_ids": input_ids, "attention_mask": attn_mask} - - -def _build_lm(cfg, ModelCls, batch, seq_len, dtype): - """Shared helper: build a causal-LM-style model and matching token+mask inputs.""" - model = ModelCls(cfg).eval().to(dtype=dtype) - input_ids = torch.randint(0, cfg.vocab_size, (batch, seq_len)) - attn_mask = _causal_mask(batch, seq_len, dtype) - return model, {"input_ids": input_ids, "attention_mask": attn_mask} - - -def build_qwen3(batch=1, seq_len=32, dtype=torch.float32): - from transformers.models.qwen3.configuration_qwen3 import Qwen3Config - from transformers.models.qwen3.modeling_qwen3 import Qwen3Model - cfg = Qwen3Config( - vocab_size=4096, hidden_size=1024, num_attention_heads=8, num_key_value_heads=4, - intermediate_size=3072, num_hidden_layers=2, max_position_embeddings=4096, - rms_norm_eps=1e-6, rope_theta=1000000.0, torch_dtype=dtype, use_cache=False, - _attn_implementation="eager", - ) - return _build_lm(cfg, Qwen3Model, batch, seq_len, dtype) - - -def build_qwen3_moe(batch=1, seq_len=32, dtype=torch.float32): - from transformers.models.qwen3_moe.configuration_qwen3_moe import Qwen3MoeConfig - from transformers.models.qwen3_moe.modeling_qwen3_moe import Qwen3MoeModel - cfg = Qwen3MoeConfig( - vocab_size=4096, hidden_size=1024, num_attention_heads=8, num_key_value_heads=4, - intermediate_size=3072, moe_intermediate_size=768, num_experts=4, num_experts_per_tok=2, - decoder_sparse_step=1, num_hidden_layers=2, max_position_embeddings=4096, - rms_norm_eps=1e-6, rope_theta=1000000.0, torch_dtype=dtype, use_cache=False, - _attn_implementation="eager", - ) - return _build_lm(cfg, Qwen3MoeModel, batch, seq_len, dtype) - - -def build_gemma3(batch=1, seq_len=32, dtype=torch.float32): - from transformers.models.gemma3.configuration_gemma3 import Gemma3TextConfig - from transformers.models.gemma3.modeling_gemma3 import Gemma3TextModel - cfg = Gemma3TextConfig( - vocab_size=4096, hidden_size=2048, num_attention_heads=8, num_key_value_heads=4, - intermediate_size=8192, head_dim=256, num_hidden_layers=2, - sliding_window=16, sliding_window_pattern=2, - max_position_embeddings=4096, rms_norm_eps=1e-6, rope_theta=10000.0, - torch_dtype=dtype, use_cache=False, _attn_implementation="eager", - ) - return _build_lm(cfg, Gemma3TextModel, batch, seq_len, dtype) - - -def _build_vlm(cfg, ModelCls, batch, seq_len, dtype, image_token_index, - n_image_tokens, image_size): - """Shared helper for a vision-language model: tokens WITH image placeholders, - plus the pixel_values those placeholders stand for. - - The text builders above make `input_ids` only, which is why every - multimodal entry in this file used to scan its text branch alone. A VLM - refuses a forward unless the count of image-placeholder tokens in - `input_ids` matches what the vision tower will produce, so the caller passes - that count rather than guessing: it is patches for PaliGemma and - `mm_tokens_per_image` for Gemma 3, which are not the same number in general. - Tokens start at 10 so a random one cannot collide with the placeholder. - """ - model = ModelCls(cfg).eval().to(dtype=dtype) - vocab = cfg.text_config.vocab_size - input_ids = torch.randint(10, vocab, (batch, seq_len)) - input_ids[:, :n_image_tokens] = image_token_index - pixel_values = torch.randn(batch, 3, image_size, image_size, dtype=dtype) - return model, {"input_ids": input_ids, "pixel_values": pixel_values} - - -def build_gemma3_mm(batch=1, seq_len=32, dtype=torch.float32): - # Gemma 3's multimodal half: a SigLIP tower in front of the text tower that - # `gemma3` already scans. What is new here is the tower and the projector, - # not the decoder. - from transformers import Gemma3Config, Gemma3ForConditionalGeneration - text = dict(vocab_size=512, hidden_size=128, intermediate_size=256, - num_hidden_layers=2, num_attention_heads=2, num_key_value_heads=1, - head_dim=64, sliding_window=8, sliding_window_pattern=2, - rope_theta=1000000.0, rope_local_base_freq=10000.0, - use_cache=False, cache_implementation=None) - vision = dict(hidden_size=64, intermediate_size=128, num_hidden_layers=2, - num_attention_heads=2, image_size=32, patch_size=16) - cfg = Gemma3Config(text_config=text, vision_config=vision, - mm_tokens_per_image=4, image_token_index=7, - torch_dtype=dtype) - cfg._attn_implementation = "eager" - return _build_vlm(cfg, Gemma3ForConditionalGeneration, batch, seq_len, dtype, - image_token_index=7, n_image_tokens=4, image_size=32) - - -def build_paligemma(batch=1, seq_len=32, dtype=torch.float32): - # PaliGemma is a SigLIP tower in front of a GEMMA 1 text tower, so against - # gemma3_mm it isolates the tower from the Gemma 3 decoder's own novelties. - from transformers import PaliGemmaConfig, PaliGemmaForConditionalGeneration - text = dict(vocab_size=512, hidden_size=128, intermediate_size=256, - num_hidden_layers=2, num_attention_heads=2, num_key_value_heads=1, - head_dim=64, use_cache=False) - vision = dict(hidden_size=64, intermediate_size=128, num_hidden_layers=2, - num_attention_heads=2, image_size=32, patch_size=16) - cfg = PaliGemmaConfig(text_config=text, vision_config=vision, - image_token_index=7, projection_dim=128, - torch_dtype=dtype) - cfg._attn_implementation = "eager" - # PaliGemma emits one token per patch, unpooled: (32 // 16) ** 2 == 4. - return _build_vlm(cfg, PaliGemmaForConditionalGeneration, batch, seq_len, dtype, - image_token_index=7, n_image_tokens=4, image_size=32) - - -# ShieldGemma 2 is deliberately absent. It is ShieldGemma2ForImageClassification -# wrapping Gemma 3 with a classification head -- a checkpoint and a head, not an -# architecture -- so its op set is gemma3_mm's and scanning it would add a row -# that repeats one already here. - - -def build_recurrent_gemma(batch=1, seq_len=32, dtype=torch.float32): - # RecurrentGemma is a Gemma checkpoint family but NOT a Gemma block: it is - # Griffin, a linear recurrence interleaved with local attention. Scanned - # here rather than tested because the recurrence is what would be new, and - # an op scan says whether it is reachable before a bring-up pays for it. - # block_types is given both kinds so the scan sees the recurrent block and - # the attention block, which is the whole point of the model. - from transformers.models.recurrent_gemma.configuration_recurrent_gemma import RecurrentGemmaConfig - from transformers.models.recurrent_gemma.modeling_recurrent_gemma import RecurrentGemmaModel - cfg = RecurrentGemmaConfig( - vocab_size=4096, hidden_size=1024, num_attention_heads=8, num_key_value_heads=1, - intermediate_size=3072, head_dim=128, num_hidden_layers=2, - block_types=("recurrent", "attention"), - attention_window_size=16, - max_position_embeddings=4096, rms_norm_eps=1e-6, - torch_dtype=dtype, use_cache=False, _attn_implementation="eager", - ) - return _build_lm(cfg, RecurrentGemmaModel, batch, seq_len, dtype) - - -def build_deepseek_v3(batch=1, seq_len=32, dtype=torch.float32): - from transformers.models.deepseek_v3.configuration_deepseek_v3 import DeepseekV3Config - from transformers.models.deepseek_v3.modeling_deepseek_v3 import DeepseekV3Model - cfg = DeepseekV3Config( - vocab_size=4096, hidden_size=1024, num_attention_heads=16, num_key_value_heads=16, - intermediate_size=4096, moe_intermediate_size=512, - n_routed_experts=8, num_experts_per_tok=2, n_shared_experts=1, - n_group=2, topk_group=1, - q_lora_rank=512, kv_lora_rank=128, qk_rope_head_dim=32, qk_nope_head_dim=32, v_head_dim=64, - num_hidden_layers=2, first_k_dense_replace=1, - max_position_embeddings=4096, rms_norm_eps=1e-6, rope_theta=10000.0, - torch_dtype=dtype, use_cache=False, _attn_implementation="eager", - ) - return _build_lm(cfg, DeepseekV3Model, batch, seq_len, dtype) - - -def build_llama4(batch=1, seq_len=32, dtype=torch.float32): - from transformers.models.llama4.configuration_llama4 import Llama4TextConfig - from transformers.models.llama4.modeling_llama4 import Llama4TextModel - cfg = Llama4TextConfig( - vocab_size=4096, hidden_size=1024, num_attention_heads=8, num_key_value_heads=4, - intermediate_size=3072, intermediate_size_mlp=3072, - num_local_experts=4, num_experts_per_tok=1, num_hidden_layers=2, interleave_moe_layer_step=2, - max_position_embeddings=4096, rms_norm_eps=1e-6, rope_theta=10000.0, - torch_dtype=dtype, use_cache=False, _attn_implementation="eager", - ) - return _build_lm(cfg, Llama4TextModel, batch, seq_len, dtype) - - -def build_glm4(batch=1, seq_len=32, dtype=torch.float32): - from transformers.models.glm4.configuration_glm4 import Glm4Config - from transformers.models.glm4.modeling_glm4 import Glm4Model - cfg = Glm4Config( - vocab_size=4096, pad_token_id=0, bos_token_id=1, eos_token_id=2, - hidden_size=1536, num_attention_heads=12, num_key_value_heads=2, - intermediate_size=4096, num_hidden_layers=2, max_position_embeddings=4096, - rms_norm_eps=1e-5, rope_theta=10000.0, torch_dtype=dtype, use_cache=False, - _attn_implementation="eager", - ) - return _build_lm(cfg, Glm4Model, batch, seq_len, dtype) - - -def build_olmo2(batch=1, seq_len=32, dtype=torch.float32): - from transformers.models.olmo2.configuration_olmo2 import Olmo2Config - from transformers.models.olmo2.modeling_olmo2 import Olmo2Model - cfg = Olmo2Config( - vocab_size=4096, hidden_size=2048, num_attention_heads=16, num_key_value_heads=16, - intermediate_size=8192, num_hidden_layers=2, max_position_embeddings=4096, - rms_norm_eps=1e-6, rope_theta=10000.0, torch_dtype=dtype, use_cache=False, - _attn_implementation="eager", - ) - return _build_lm(cfg, Olmo2Model, batch, seq_len, dtype) - - -def build_granite(batch=1, seq_len=32, dtype=torch.float32): - from transformers.models.granite.configuration_granite import GraniteConfig - from transformers.models.granite.modeling_granite import GraniteModel - cfg = GraniteConfig( - vocab_size=4096, hidden_size=2048, num_attention_heads=16, num_key_value_heads=8, - intermediate_size=8192, num_hidden_layers=2, max_position_embeddings=4096, - rms_norm_eps=1e-5, rope_theta=10000.0, torch_dtype=dtype, use_cache=False, - _attn_implementation="eager", - ) - return _build_lm(cfg, GraniteModel, batch, seq_len, dtype) - - -def build_phimoe(batch=1, seq_len=32, dtype=torch.float32): - from transformers.models.phimoe.configuration_phimoe import PhimoeConfig - from transformers.models.phimoe.modeling_phimoe import PhimoeModel - cfg = PhimoeConfig( - vocab_size=4096, hidden_size=1024, num_attention_heads=8, num_key_value_heads=4, - intermediate_size=3072, num_local_experts=4, num_experts_per_tok=2, - num_hidden_layers=2, max_position_embeddings=4096, - rms_norm_eps=1e-5, rope_theta=10000.0, torch_dtype=dtype, use_cache=False, - _attn_implementation="eager", - ) - return _build_lm(cfg, PhimoeModel, batch, seq_len, dtype) - - -def build_mamba2(batch=1, seq_len=32, dtype=torch.float32): - # State-space model: no attention, no RoPE -- completely different op profile. - # Invariant: num_heads * head_dim == intermediate_size == expand * hidden_size - # (modeling_mamba2.py:171 + the view(B, num_heads*head_dim) at line 365). - from transformers.models.mamba2.configuration_mamba2 import Mamba2Config - from transformers.models.mamba2.modeling_mamba2 import Mamba2Model - cfg = Mamba2Config( - vocab_size=4096, hidden_size=512, - num_heads=16, head_dim=64, - state_size=16, chunk_size=16, - expand=2, n_groups=1, - num_hidden_layers=2, torch_dtype=dtype, use_cache=False, - ) - model = Mamba2Model(cfg).eval().to(dtype=dtype) - input_ids = torch.randint(0, cfg.vocab_size, (batch, seq_len)) - # Mamba has no attention mask; pass none. - return model, {"input_ids": input_ids} - - -def build_mllama(batch=1, seq_len=32, dtype=torch.float32): - # Llama 3.2 Vision -- text branch only (text-only call path). - # MllamaRotaryEmbedding requires config.rope_scaling["rope_type"]; pass default. - from transformers.models.mllama.configuration_mllama import MllamaTextConfig - from transformers.models.mllama.modeling_mllama import MllamaTextModel - cfg = MllamaTextConfig( - vocab_size=4096, pad_token_id=0, bos_token_id=1, eos_token_id=2, - hidden_size=1024, num_attention_heads=8, num_key_value_heads=4, - intermediate_size=3072, num_hidden_layers=2, - cross_attention_layers=[], - max_position_embeddings=4096, rms_norm_eps=1e-5, rope_theta=10000.0, - rope_scaling={"rope_type": "default"}, - torch_dtype=dtype, use_cache=False, _attn_implementation="eager", - ) - return _build_lm(cfg, MllamaTextModel, batch, seq_len, dtype) - - -BUILDERS = { - "qwen2": build_qwen2, - "gemma": build_gemma, - "gemma2": build_gemma2, - "phi3": build_phi3, - # Models newly available with transformers 4.51.3 - "qwen3": build_qwen3, - "qwen3_moe": build_qwen3_moe, - "gemma3": build_gemma3, - "gemma3_mm": build_gemma3_mm, - "paligemma": build_paligemma, - "recurrent_gemma": build_recurrent_gemma, - "deepseek_v3": build_deepseek_v3, - "llama4": build_llama4, - "glm4": build_glm4, - "olmo2": build_olmo2, - "granite": build_granite, - "phimoe": build_phimoe, - "mamba2": build_mamba2, - "mllama": build_mllama, -} - - -# --------------------------------------------------------------------------- -# Phase 1: enumerate aten ops by intercepting the FX graph from torch.compile. -# --------------------------------------------------------------------------- - -def _node_op_name(target): - # OpOverload / OpOverloadPacket: has a .name() method returning "aten::mm.default" etc. - if hasattr(target, "name") and callable(target.name): - try: - return target.name() - except Exception: - pass - if hasattr(target, "_schema"): - try: - return str(target._schema.name) + ( - "." + target._schema.overload_name if target._schema.overload_name else "" - ) - except Exception: - pass - # torch.* python builtins: use their __module__/__qualname__ - mod = getattr(target, "__module__", "") - qn = getattr(target, "__qualname__", None) or getattr(target, "__name__", "") - if mod and qn: - return f"{mod}.{qn}" - return str(target) - - -@torch.no_grad() -def enumerate_ops(model, inputs): - """Capture the post-AOTAutograd aten graph(s) via aot_module_simplified. - - This is the same level of IR TOGSim/Inductor consumes, so the op set - matches what the NPU backend actually has to lower. - """ - from functorch.compile import aot_module_simplified - - seen = set() - graph_sizes = [] - - def fw_compiler(gm, example_inputs): - graph_sizes.append(sum(1 for _ in gm.graph.nodes)) - for node in gm.graph.nodes: - if node.op == "call_function": - seen.add(_node_op_name(node.target)) - return gm.forward - - def dynamo_backend(gm, example_inputs): - return aot_module_simplified(gm, example_inputs, fw_compiler=fw_compiler) - - torch._dynamo.reset() - compiled = torch.compile(model, backend=dynamo_backend, dynamic=False) - compiled(**inputs) - return sorted(seen), graph_sizes - - -# --------------------------------------------------------------------------- -# Phase 2: real NPU compile + run. Capture and parse failure tracebacks. -# --------------------------------------------------------------------------- - -ATEN_RE = re.compile(r"aten[.:][a-zA-Z_][a-zA-Z0-9_.]*") -NOTIMPL_RE = re.compile(r"NotImplementedError[: ]+(.*)") - - -EXTERN_RE = re.compile(r"(extern_kernels\.[a-zA-Z_][a-zA-Z0-9_]*)") - - -def _extern_hint(tb_text): - """Name the extern kernel a traceback died in, when no aten op appears. - - Inductor does not lower every op; some it hands to an ATen extern kernel, - and on npu:0 an unregistered one raises `_overrideable not - implemented` with no aten token anywhere in the traceback. - """ - m = EXTERN_RE.search(tb_text) - return m.group(1) if m else None - - -def _last_exception_line(tb_text): - """Last resort: the traceback's final line, which is the exception itself. - - Not every stop is an op. RecurrentGemma's is a stage of the the compiler pipeline - refusing a command ("args must not exceed 2048 bytes") -- no aten token, no - extern kernel, no NotImplementedError -- and a summary that shrugs at that - is a summary you have to go around. - """ - lines = [l.strip() for l in tb_text.strip().splitlines() if l.strip()] - return lines[-1][:70] if lines else None - - -def parse_failure(tb_text): - aten_hits = [] - for m in ATEN_RE.finditer(tb_text): - op = m.group(0).replace("aten:", "aten.").lstrip(".") - if op not in aten_hits: - aten_hits.append(op) - msg = "" - nm = NOTIMPL_RE.search(tb_text) - if nm: - msg = nm.group(1).strip().splitlines()[0] - return aten_hits, msg - - -@torch.no_grad() -def run_on_npu(model, inputs): - device = torch.device("npu:0") - model = model.to(device) - inputs = {k: v.to(device) for k, v in inputs.items()} - torch._dynamo.reset() - compiled = torch.compile(model, dynamic=False) - out = compiled(**inputs) - # touch the output to force completion - if hasattr(out, "last_hidden_state"): - out.last_hidden_state.cpu() - elif isinstance(out, torch.Tensor): - out.cpu() - return "OK", None, None - - -# --------------------------------------------------------------------------- -# Driver -# --------------------------------------------------------------------------- - -def run_model(name, args, out_dir): - builder = BUILDERS[name] - log_path = os.path.join(out_dir, f"{name}.log") - with open(log_path, "w") as fh: - def w(s=""): - print(s) - fh.write(s + "\n") - - w(f"=== {name} ===") - w(f"batch={args.batch} seq_len={args.seq_len} dtype={args.dtype}") - - try: - model, inputs = builder(args.batch, args.seq_len, _DTYPE_MAP[args.dtype]) - except Exception as e: - w(f"[BUILD FAIL] {type(e).__name__}: {e}") - return {"name": name, "status": "BUILD_FAIL", "ops": [], "fail_op": str(e)} - - # Phase 1 - w("\n[Phase 1] FX op enumeration (eager backend, no NPU)") - try: - ops, graph_sizes = enumerate_ops(model, inputs) - w(f" graphs: {len(graph_sizes)} total_nodes_per_graph: {graph_sizes}") - w(f" unique aten ops: {len(ops)}") - for op in ops: - w(f" {op}") - except Exception: - tb = traceback.format_exc() - w("[Phase 1 FAIL]\n" + tb) - ops = [] - - if args.enumerate_only: - return {"name": name, "status": "ENUM_ONLY", "ops": ops, "fail_op": None} - - # Phase 2 - w("\n[Phase 2] torch.compile on npu:0 + forward") - try: - status, fail_op, msg = run_on_npu(model, inputs) - w(f" status: {status}") - return {"name": name, "status": status, "ops": ops, "fail_op": None} - except Exception: - tb = traceback.format_exc() - hits, msg = parse_failure(tb) - w(" status: FAIL") - if msg: - w(f" NotImplemented message: {msg}") - if hits: - w(f" aten ops in traceback (first = most likely culprit):") - for h in hits[:10]: - w(f" {h}") - w("\n----- traceback -----\n" + tb) - # Fall back to the NotImplemented message when the traceback names - # no aten op. That is not a rare corner: a failure inside an EXTERN - # kernel has no aten token at all. RecurrentGemma stops at - # extern_kernels.convolution -> convolution_overrideable, and the - # summary said "?" while the one useful sentence sat in the log, - # which is a summary that sends you to read the log it exists to - # replace. - return { - "name": name, - "status": "FAIL", - "ops": ops, - "fail_op": hits[0] if hits else ( - _extern_hint(tb) or (msg[:60] if msg else None) - or _last_exception_line(tb) or "?"), - "msg": msg, - } - - -_DTYPE_MAP = {"float32": torch.float32, "float16": torch.float16, "bfloat16": torch.bfloat16} - - -def main(): - p = argparse.ArgumentParser() - p.add_argument("--models", nargs="+", default=list(BUILDERS.keys()), - choices=list(BUILDERS.keys())) - p.add_argument("--batch", type=int, default=1) - p.add_argument("--seq-len", type=int, default=32) - p.add_argument("--dtype", default="float32", choices=list(_DTYPE_MAP.keys())) - p.add_argument("--enumerate-only", action="store_true", - help="Skip NPU compile; just list aten ops per model (fast).") - p.add_argument("--out-dir", default=None) - args = p.parse_args() - - ts = _dt.datetime.now().strftime("%Y%m%d_%H%M%S") - out_dir = args.out_dir or os.path.join( - os.environ.get("TORCHSIM_LOG_PATH", os.path.join(REPO_ROOT, "togsim_results")), - "op_coverage", ts, - ) - os.makedirs(out_dir, exist_ok=True) - print(f"Output dir: {out_dir}") - - results = [] - for name in args.models: - try: - results.append(run_model(name, args, out_dir)) - except KeyboardInterrupt: - print(f"[interrupt] aborted during {name}") - break - except Exception: - traceback.print_exc() - results.append({"name": name, "status": "DRIVER_ERR", "ops": [], "fail_op": None}) - - # Summary - summary_path = os.path.join(out_dir, "summary.txt") - with open(summary_path, "w") as fh: - def w(s=""): - print(s) - fh.write(s + "\n") - w("\n========== SUMMARY ==========") - w(f"{'model':10s} {'ops':>5s} {'status':10s} first_fail") - for r in results: - w(f"{r['name']:10s} {len(r['ops']):>5d} {r['status']:10s} {r.get('fail_op') or '-'}") - # Union & overlap across models - all_ops = set() - for r in results: - all_ops.update(r["ops"]) - w(f"\nUnion of aten ops across all models: {len(all_ops)}") - w("Per-model op set diff (ops unique to this model):") - for r in results: - others = set().union(*(set(r2["ops"]) for r2 in results if r2 is not r)) - unique = sorted(set(r["ops"]) - others) - w(f" {r['name']}: {len(unique)} unique") - for op in unique: - w(f" {op}") - - print(f"\nWrote: {summary_path}") - - -if __name__ == "__main__": - main() diff --git a/scripts/selection_merge.py b/scripts/selection_merge.py index e6eb07a5d..079191412 100644 --- a/scripts/selection_merge.py +++ b/scripts/selection_merge.py @@ -12,7 +12,7 @@ import torch # noqa: E402,F401 (first: its device autoload installs pytorchsim, which imports select) -from pytorchsim.driver import select # noqa: E402 +from pytorchsim.backend import select # noqa: E402 def main(paths): diff --git a/tests/models/BERT/test_bert.py b/tests/models/BERT/test_bert.py index 03ac485b6..f6bcd0c45 100644 --- a/tests/models/BERT/test_bert.py +++ b/tests/models/BERT/test_bert.py @@ -23,7 +23,7 @@ import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result # Presets shrink the model, not the shapes' character: the head dim, the 4x @@ -134,7 +134,7 @@ def run_bert( attention_mask=attention_mask.to(device), token_type_ids=token_type_ids.to(device))) - test_result(f"BERT {part} ({preset})", npu_out, cpu_out, rtol=rtol, atol=atol) + check_result(f"BERT {part} ({preset})", npu_out, cpu_out, rtol=rtol, atol=atol) print("Max diff > ", torch.max(torch.abs(npu_out.cpu() - cpu_out))) print("BERT Simulation Done") diff --git a/tests/models/DeepSeek/test_deepseek_v3_base.py b/tests/models/DeepSeek/test_deepseek_v3_base.py index 375c83cf6..479b41bc1 100644 --- a/tests/models/DeepSeek/test_deepseek_v3_base.py +++ b/tests/models/DeepSeek/test_deepseek_v3_base.py @@ -5,7 +5,7 @@ from pathlib import Path import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result # DeepSeek-V3's remote modeling file (trust_remote_code) imports flash_attn, and # transformers' check_imports statically requires it to be installed even though @@ -53,7 +53,7 @@ def exec_module(self, module): # RecursionError: maximum recursion depth exceeded # # DeepSeek-V2's complex RoPE closed that loop. It no longer does: - # rewrite_fx_graph.py rewrites the complex multiply into real + # frontend/post_grad_pass.py rewrites the complex multiply into real # arithmetic, Inductor generates a kernel, and no fallback is emitted. # Measured both ways, and pinned by # tests/ops/misc/test_eager_to_compile_recursion.py. @@ -244,7 +244,7 @@ def cat_default_fn(a, b): _assert_simulation_happened(before, "cat.default") cpu_out = torch.cat([x.cpu(), y.cpu()], dim=0) - test_result("cat.default", out, cpu_out, rtol=1e-4, atol=1e-4) + check_result("cat.default", out, cpu_out, rtol=1e-4, atol=1e-4) def test_cat_out(device): @@ -261,7 +261,7 @@ def cat_out_fn(a, b, out): _assert_simulation_happened(before, "cat.out") cpu_out = torch.cat([x.cpu(), y.cpu()], dim=0) - test_result("cat.out", out, cpu_out, rtol=1e-4, atol=1e-4) + check_result("cat.out", out, cpu_out, rtol=1e-4, atol=1e-4) @torch.no_grad() @@ -354,7 +354,7 @@ def run_deepseek_v3_base( npu_out = _extract_logits(model_npu(input_ids)) # Campare results - test_result( + check_result( "DeepSeek V3 Base", npu_out, cpu_out, diff --git a/tests/models/Diffusion/test_diffusion.py b/tests/models/Diffusion/test_diffusion.py index 7ad5a7590..0d78c8d4f 100644 --- a/tests/models/Diffusion/test_diffusion.py +++ b/tests/models/Diffusion/test_diffusion.py @@ -10,7 +10,7 @@ from diffusers.models.resnet import ResnetBlock2D from diffusers.models.embeddings import Timesteps sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result @torch.no_grad() def test_unet_conditional( @@ -88,7 +88,7 @@ def test_unet_conditional( else: out_cpu = unet_cpu(latents.cpu(), timestep, encoder_hidden_states=enc_states_cpu).sample - test_result(f"UNet({model_id}) forward", out_dev, out_cpu, rtol=rtol, atol=atol) + check_result(f"UNet({model_id}) forward", out_dev, out_cpu, rtol=rtol, atol=atol) print("Max diff >", torch.max(torch.abs(out_dev.cpu() - out_cpu)).item()) print("UNet Simulation Done") @@ -143,7 +143,7 @@ def test_unet_mid_block2d_cross_attn( encoder_hidden_states=encoder_hidden_states_dev, ) - test_result("UNetMidBlock2DCrossAttn", dev_out, cpu_out, rtol=rtol, atol=atol) + check_result("UNetMidBlock2DCrossAttn", dev_out, cpu_out, rtol=rtol, atol=atol) print("Max diff >", torch.max(torch.abs(dev_out.cpu() - cpu_out)).item()) print("UNetMidBlock2DCrossAttn simulation done.") @@ -210,7 +210,7 @@ def test_cross_attn_up_block2d( encoder_hidden_states=encoder_hidden_states_dev, ) - test_result("CrossAttnUpBlock2D", dev_out, cpu_out, rtol=rtol, atol=atol) + check_result("CrossAttnUpBlock2D", dev_out, cpu_out, rtol=rtol, atol=atol) print("Max diff >", torch.max(torch.abs(dev_out.cpu() - cpu_out)).item()) print("CrossAttnUpBlock2D simulation done.") @@ -278,7 +278,7 @@ def test_unet2d_condition_model( ).sample for idx, (cpu, dev) in enumerate(zip(y_cpu, y_dev)): - test_result(f"[{idx}] UNet2DConditionModel", dev.cpu(), cpu, rtol=rtol, atol=atol) + check_result(f"[{idx}] UNet2DConditionModel", dev.cpu(), cpu, rtol=rtol, atol=atol) max_diff = torch.max(torch.abs(dev.detach().cpu() - cpu)).item() print("Max diff >", max_diff) print("UNet2DConditionModel simulation done.") @@ -343,7 +343,7 @@ def test_cross_attn_down_block2d( ) # 7. Compare the results - test_result("CrossAttnDownBlock2D", dev_out, cpu_out, rtol=rtol, atol=atol) + check_result("CrossAttnDownBlock2D", dev_out, cpu_out, rtol=rtol, atol=atol) print("Max diff >", torch.max(torch.abs(dev_out.cpu() - cpu_out)).item()) print("CrossAttnDownBlock2D simulation done.") @@ -402,7 +402,7 @@ def test_resnetblock2d( y_dev = dev_blk(x_dev, temb=temb_dev) try: - test_result("ResnetBlock2D(down=True)", y_dev, y_cpu, rtol=rtol, atol=atol) + check_result("ResnetBlock2D(down=True)", y_dev, y_cpu, rtol=rtol, atol=atol) except NameError: # fallback: PyTorch의 기본 엄밀 비교 torch.testing.assert_close(y_dev.cpu(), y_cpu, rtol=rtol, atol=atol) @@ -467,7 +467,7 @@ def test_groupnorm( dev_out = device_norm(input_dev) # 7. Compare the results - test_result("GroupNorm", dev_out, cpu_out, rtol=rtol, atol=atol) + check_result("GroupNorm", dev_out, cpu_out, rtol=rtol, atol=atol) print("Max diff >", torch.max(torch.abs(dev_out.cpu() - cpu_out)).item()) print("GroupNorm simulation done.") @@ -523,7 +523,7 @@ def test_upsample2d( with torch.no_grad(): y_dev = dev_block(x_dev) - test_result("Upsample2D", y_dev, y_cpu, rtol=rtol, atol=atol) + check_result("Upsample2D", y_dev, y_cpu, rtol=rtol, atol=atol) print("Max diff >", torch.max(torch.abs(y_dev.cpu() - y_cpu)).item()) print("Upsample2D simulation done.") @@ -570,9 +570,9 @@ def create_embeddings_compiled(timesteps, embedding_dim, scale=1.0, flip_sin_to_ emb_flip_dev = create_embeddings_compiled(timesteps_dev, embedding_dim, flip_sin_to_cos=True) # Verify flip case - test_result("Embedding (flip_sin_to_cos=True)", emb_flip_dev[0], emb_flip_cpu[0], rtol=rtol, atol=atol) + check_result("Embedding (flip_sin_to_cos=True)", emb_flip_dev[0], emb_flip_cpu[0], rtol=rtol, atol=atol) print("Max diff (flip) >", torch.max(torch.abs(emb_flip_dev[0].cpu() - emb_flip_cpu[0])).item()) - test_result("Embedding (flip_sin_to_cos=True)", emb_flip_dev[1], emb_flip_cpu[1], rtol=rtol, atol=atol) + check_result("Embedding (flip_sin_to_cos=True)", emb_flip_dev[1], emb_flip_cpu[1], rtol=rtol, atol=atol) print("Max diff (flip) >", torch.max(torch.abs(emb_flip_dev[1].cpu() - emb_flip_cpu[1])).item()) @@ -606,7 +606,7 @@ def test_timesteps( with torch.no_grad(): dev_out = dev_timesteps(timesteps_dev) - test_result("Timesteps", dev_out, cpu_out, rtol=rtol, atol=atol) + check_result("Timesteps", dev_out, cpu_out, rtol=rtol, atol=atol) print("Max diff >", torch.max(torch.abs(dev_out.cpu() - cpu_out)).item()) print("Timesteps simulation done.") diff --git a/tests/models/GPT2/test_gpt2.py b/tests/models/GPT2/test_gpt2.py index 4c8515f55..5c7a01ed5 100644 --- a/tests/models/GPT2/test_gpt2.py +++ b/tests/models/GPT2/test_gpt2.py @@ -39,7 +39,7 @@ import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result # Presets shrink the model, not the shapes' character: the head dim, the 4x MLP @@ -131,7 +131,7 @@ def run_gpt2( model_npu = torch.compile(model_npu, dynamic=False) npu_out = _logits(model_npu(input_ids.to(device))) - test_result(f"GPT-2 {part} ({preset})", npu_out, cpu_out, rtol=rtol, atol=atol) + check_result(f"GPT-2 {part} ({preset})", npu_out, cpu_out, rtol=rtol, atol=atol) print("Max diff > ", torch.max(torch.abs(npu_out.cpu() - cpu_out))) print("GPT-2 Simulation Done") diff --git a/tests/models/Gemma/test_gemma.py b/tests/models/Gemma/test_gemma.py index ebb18e69d..1fc0b8ed3 100644 --- a/tests/models/Gemma/test_gemma.py +++ b/tests/models/Gemma/test_gemma.py @@ -165,7 +165,7 @@ import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result # Presets shrink cost, not character. Width carries head_dim, the GQA repeat @@ -960,7 +960,7 @@ def run_gemma( model_npu = torch.compile(model_npu, dynamic=False) npu_out = _out(model_npu(**{k: v.to(device) for k, v in cpu_inputs.items()})) - test_result(f"Gemma {part} ({preset})", npu_out, cpu_out, rtol=rtol, atol=atol) + check_result(f"Gemma {part} ({preset})", npu_out, cpu_out, rtol=rtol, atol=atol) print("Max diff > ", torch.max(torch.abs(npu_out.cpu() - cpu_out))) print("Gemma Simulation Done") diff --git a/tests/models/Kimi/test_kimi.py b/tests/models/Kimi/test_kimi.py index b46324f7e..bb2ec7ec3 100644 --- a/tests/models/Kimi/test_kimi.py +++ b/tests/models/Kimi/test_kimi.py @@ -88,7 +88,7 @@ import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result #: Rung -> (model id, kind, remote). Release order; climb it in this order. @@ -482,7 +482,7 @@ def run_rung(rung, device, preset="tiny", dtype="float32", batch=None, # pass/fail, this says how much room is left, and it is the number the # ladder note below is written from. print(f" max abs diff: {(npu_out.cpu() - cpu_out).abs().max().item():.6g}") - test_result(f"Kimi {rung} ({preset})", npu_out, cpu_out, rtol=rtol, atol=atol) + check_result(f"Kimi {rung} ({preset})", npu_out, cpu_out, rtol=rtol, atol=atol) if __name__ == "__main__": diff --git a/tests/models/Llama/test_llama.py b/tests/models/Llama/test_llama.py index 3900b1cf6..64849ba67 100644 --- a/tests/models/Llama/test_llama.py +++ b/tests/models/Llama/test_llama.py @@ -6,7 +6,7 @@ from transformers.models.llama.configuration_llama import LlamaConfig from transformers.models.llama.modeling_llama import LlamaForCausalLM, LlamaDecoderLayer, LlamaRMSNorm, LlamaRotaryEmbedding, LlamaModel sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result @torch.no_grad() def run_rmsnorm_test( @@ -41,7 +41,7 @@ def run_rmsnorm_test( out_cpu = cpu_norm(hidden_states) out_dev = compiled_norm(hs_dev) - test_result("LlamaRMSNorm forward", out_dev, out_cpu, rtol=rtol, atol=atol) + check_result("LlamaRMSNorm forward", out_dev, out_cpu, rtol=rtol, atol=atol) print("Max diff >", (out_dev.detach().cpu() - out_cpu.detach().cpu()).abs().max().item()) @@ -116,8 +116,8 @@ def run_rotary_embedding_test( print(f"Output dtype check - CPU: {cos_cpu.dtype}, Device: {cos_dev.dtype}") - test_result("LlamaRotaryEmbedding (Cos)", cos_dev, cos_cpu, rtol=rtol, atol=atol) - test_result("LlamaRotaryEmbedding (Sin)", sin_dev, sin_cpu, rtol=rtol, atol=atol) + check_result("LlamaRotaryEmbedding (Cos)", cos_dev, cos_cpu, rtol=rtol, atol=atol) + check_result("LlamaRotaryEmbedding (Sin)", sin_dev, sin_cpu, rtol=rtol, atol=atol) diff_cos = (cos_dev.detach().cpu() - cos_cpu.detach().cpu()).abs().max().item() diff_sin = (sin_dev.detach().cpu() - sin_cpu.detach().cpu()).abs().max().item() @@ -213,7 +213,7 @@ def run_decoder_layer_test( if isinstance(out_dev, tuple): out_dev = out_dev[0] - test_result("LlamaDecoderLayer forward", out_dev, out_cpu, rtol=rtol, atol=atol) + check_result("LlamaDecoderLayer forward", out_dev, out_cpu, rtol=rtol, atol=atol) print("Max diff >", (out_dev.detach().cpu() - out_cpu.detach().cpu()).abs().max().item()) @torch.no_grad() @@ -289,7 +289,7 @@ def run_custom_llama_test( logits_cpu = cpu_model(input_ids=input_ids_cpu, attention_mask=attn_mask_cpu)#.logits logits_dev = compiled(input_ids=input_ids_dev, attention_mask=attn_mask_dev)#.logits - test_result("Custom Llama forward(logits)", logits_dev, logits_cpu, rtol=rtol, atol=atol) + check_result("Custom Llama forward(logits)", logits_dev, logits_cpu, rtol=rtol, atol=atol) print("Max diff >", (logits_dev.detach().cpu() - logits_cpu.detach().cpu()).abs().max().item()) @torch.no_grad() @@ -346,7 +346,7 @@ def run_llama_model_test( last_hidden_state_cpu = out_cpu.last_hidden_state last_hidden_state_dev = out_dev.last_hidden_state - test_result("LlamaModel (last_hidden_state)", last_hidden_state_dev, last_hidden_state_cpu, rtol=rtol, atol=atol) + check_result("LlamaModel (last_hidden_state)", last_hidden_state_dev, last_hidden_state_cpu, rtol=rtol, atol=atol) diff = (last_hidden_state_dev.detach().cpu() - last_hidden_state_cpu.detach().cpu()).abs().max().item() print(f"Max diff > {diff}") diff --git a/tests/models/Llama/test_llama3.py b/tests/models/Llama/test_llama3.py index d278226a5..34b6f5100 100644 --- a/tests/models/Llama/test_llama3.py +++ b/tests/models/Llama/test_llama3.py @@ -6,7 +6,7 @@ from transformers.models.llama.configuration_llama import LlamaConfig from transformers.models.llama.modeling_llama import LlamaDecoderLayer, LlamaModel sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result # Llama 3 is the Llama architecture with three things changed, and each one lands # on a different part of this backend: @@ -103,7 +103,7 @@ def run_decoder_layer_test(device, batch=1, seq_len=32, dtype="float32", position_ids=position_ids_dev, position_embeddings=pos_emb_dev)[0] - test_result("Llama3 DecoderLayer forward", out_dev, out_cpu, rtol=rtol, atol=atol) + check_result("Llama3 DecoderLayer forward", out_dev, out_cpu, rtol=rtol, atol=atol) diff = (out_dev.detach().cpu() - out_cpu.detach().cpu()).abs().max().item() print(f"Max diff > {diff}") @@ -144,7 +144,7 @@ def run_model_test(device, batch=1, seq_len=32, dtype="float32", out_cpu = cpu_model(input_ids=input_ids_cpu, attention_mask=attn_mask_cpu) out_dev = compiled_model(input_ids=input_ids_dev, attention_mask=attn_mask_dev) - test_result("Llama3 Model (last_hidden_state)", out_dev.last_hidden_state, + check_result("Llama3 Model (last_hidden_state)", out_dev.last_hidden_state, out_cpu.last_hidden_state, rtol=rtol, atol=atol) diff = (out_dev.last_hidden_state.detach().cpu() - out_cpu.last_hidden_state.detach().cpu()).abs().max().item() diff --git a/tests/models/Llama/test_llama3x.py b/tests/models/Llama/test_llama3x.py index 642a4687b..16a972d24 100644 --- a/tests/models/Llama/test_llama3x.py +++ b/tests/models/Llama/test_llama3x.py @@ -60,7 +60,7 @@ import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result # Presets shrink the model, not the shapes' character. Width is the axis that @@ -246,7 +246,7 @@ def run_llama3x( npu_out = _out(model_npu(input_ids=input_ids.to(device), attention_mask=attn_mask.to(device))) - test_result(f"Llama 3.x {part} ({preset})", npu_out, cpu_out, rtol=rtol, atol=atol) + check_result(f"Llama 3.x {part} ({preset})", npu_out, cpu_out, rtol=rtol, atol=atol) print("Max diff > ", torch.max(torch.abs(npu_out.cpu() - cpu_out))) print("Llama 3.x Simulation Done") diff --git a/tests/models/Llama/test_llama4.py b/tests/models/Llama/test_llama4.py index f058dfea4..11775f666 100644 --- a/tests/models/Llama/test_llama4.py +++ b/tests/models/Llama/test_llama4.py @@ -39,7 +39,7 @@ Fifteen ops run eager: 11 `fill_` and 4 `topk`. The complex arithmetic used to be the bulk of that list -- 7 `view_as_complex`, 7 `mul.out`, 6 `view_as_real`, -twenty calls leaving the simulator -- and `rewrite_fx_graph` (84ad277) +twenty calls leaving the simulator -- and the npu post-grad pass (84ad277) now keeps all of it in the graph. That pass was written and measured against DeepSeek-V2's rope, and it covers this one unchanged: Llama 4's complex path uses no op outside the set it already knew. The kernel count went 30 -> 31 as @@ -114,7 +114,7 @@ import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result # Experts scaled down, everything that decides the SHAPE of the routing kept. @@ -229,7 +229,7 @@ def run_llama4(device, preset="small", batch=1, seq_len=None, dtype="float32", model_npu = torch.compile(model_npu, dynamic=False) npu_out = model_npu(input_ids=input_ids.to(device)).last_hidden_state - test_result(f"Llama 4 text ({preset})", npu_out, cpu_out, rtol=rtol, atol=atol) + check_result(f"Llama 4 text ({preset})", npu_out, cpu_out, rtol=rtol, atol=atol) print("Max diff > ", torch.max(torch.abs(npu_out.cpu() - cpu_out))) print("Llama 4 Simulation Done") @@ -327,7 +327,7 @@ def run_llama4_vision(device, preset="tiny", batch=1, dtype="float32", model_npu = torch.compile(model_npu, dynamic=False) npu_out = model_npu(px.to(device)).last_hidden_state - test_result(f"Llama 4 vision ({preset})", npu_out, cpu_out, rtol=rtol, atol=atol) + check_result(f"Llama 4 vision ({preset})", npu_out, cpu_out, rtol=rtol, atol=atol) print("Max diff > ", torch.max(torch.abs(npu_out.cpu() - cpu_out))) print("Llama 4 Vision Simulation Done") diff --git a/tests/models/Llama/test_mllama.py b/tests/models/Llama/test_mllama.py index 5e6a372ad..da1751937 100644 --- a/tests/models/Llama/test_mllama.py +++ b/tests/models/Llama/test_mllama.py @@ -26,10 +26,6 @@ test_clip.py already gate ViT-shaped attention at 768, so what is unproven is the tile structure and the global split, both of which survive scaling. -scripts/op_coverage.py's build_mllama does NOT cover any of this -- it passes -cross_attention_layers=[] and builds the text branch alone, which is a Llama -with a different class name. Its "26 ops, OK" says nothing about this file. - source /workspace/torchsim-env.sh python tests/models/Llama/test_mllama.py --part vision python tests/models/Llama/test_mllama.py --part text @@ -70,7 +66,7 @@ import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result # The vision tower. image_size / patch_size gives 16 patches a tile against the @@ -168,7 +164,7 @@ def run_vision(device, batch=1, dtype="float32", compile_model=True, aspect_ratio_ids=aspect_ratio_ids.to(device), aspect_ratio_mask=aspect_ratio_mask.to(device)).last_hidden_state - test_result("Mllama vision tower", npu_out, cpu_out, rtol=rtol, atol=atol) + check_result("Mllama vision tower", npu_out, cpu_out, rtol=rtol, atol=atol) print("Max diff > ", torch.max(torch.abs(npu_out.cpu() - cpu_out))) @@ -191,9 +187,6 @@ def run_text(device, batch=1, seq_len=32, dtype="float32", compile_model=True, print("layers:", [k.replace("Mllama", "").replace("DecoderLayer", "") for k in kinds]) print("text params:", sum(p.numel() for p in model_cpu.parameters())) - # The trap op_coverage.py fell into: with cross_attention_layers=[] this is - # a Llama wearing a different class name, and every check below still - # passes. Refuse to report a result unless a cross layer is really there. n_cross = sum(isinstance(l, MllamaCrossAttentionDecoderLayer) for l in model_cpu.layers) assert n_cross > 0, "no cross-attention layer was built -- this is not testing Mllama" print(f"cross-attention layers built: {n_cross}") @@ -227,7 +220,7 @@ def call(m, dev): model_npu = torch.compile(model_npu, dynamic=False) npu_out = call(model_npu, device) - test_result("Mllama text tower (cross-attention)", npu_out, cpu_out, + check_result("Mllama text tower (cross-attention)", npu_out, cpu_out, rtol=rtol, atol=atol) print("Max diff > ", torch.max(torch.abs(npu_out.cpu() - cpu_out))) diff --git a/tests/models/MLP/test_mlp.py b/tests/models/MLP/test_mlp.py index ac3d03e02..929f2acd4 100644 --- a/tests/models/MLP/test_mlp.py +++ b/tests/models/MLP/test_mlp.py @@ -20,7 +20,7 @@ from torch._inductor import config sys.path.insert(0, os.path.join(os.environ.get('TORCHSIM_DIR', default='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/workspace/PyTorchSim'), 'tests')) -from _pytorchsim_utils import test_result +from result_check import check_result class MLP(nn.Module): def __init__(self, input_size, output_size, hidden_size): @@ -57,7 +57,7 @@ def test_mlp(device): y1 = model_device(x1) y2 = model_cpu(x2) - test_result("MLP", y1, y2) + check_result("MLP", y1, y2) def test_train_mlp(device): torch.manual_seed(0) @@ -93,13 +93,13 @@ def test_train_mlp(device): print("Forward") y1_hat = model_device(x1) y2_hat = model_cpu(x2) - test_result("MLP Forward", y1_hat, y2_hat) + check_result("MLP Forward", y1_hat, y2_hat) """ Loss """ print("Loss") loss1 = criterion(y1_hat, y1) loss2 = criterion(y2_hat, y2) - test_result("Loss", loss1, loss2) + check_result("Loss", loss1, loss2) """ Backward """ opt_zero_grad() @@ -115,11 +115,11 @@ def test_train_mlp(device): # Check weights and gradients # for p1, p2 in zip(model_device.parameters(), model_cpu.parameters()): - # test_result("Gradient", p1.grad, p2.grad) - # test_result("FC1 Gradient", model_device.fc1.weight.grad, model_cpu.fc1.weight.grad) - # test_result("FC1 Bias Gradient", model_device.fc1.bias.grad, model_cpu.fc1.bias.grad) - # test_result("FC2 Gradient", model_device.fc2.weight.grad, model_cpu.fc2.weight.grad) - # test_result("FC2 Bias Gradient", model_device.fc2.bias.grad, model_cpu.fc2.bias.grad) + # check_result("Gradient", p1.grad, p2.grad) + # check_result("FC1 Gradient", model_device.fc1.weight.grad, model_cpu.fc1.weight.grad) + # check_result("FC1 Bias Gradient", model_device.fc1.bias.grad, model_cpu.fc1.bias.grad) + # check_result("FC2 Gradient", model_device.fc2.weight.grad, model_cpu.fc2.weight.grad) + # check_result("FC2 Bias Gradient", model_device.fc2.bias.grad, model_cpu.fc2.bias.grad) print("Finished") def train_mlp_mnist(device): diff --git a/tests/models/Mixtral8x7B/test_mistral.py b/tests/models/Mixtral8x7B/test_mistral.py index c993c2ec6..ac48be602 100644 --- a/tests/models/Mixtral8x7B/test_mistral.py +++ b/tests/models/Mixtral8x7B/test_mistral.py @@ -4,7 +4,7 @@ import torch from model import Transformer, TransformerBlock, ModelArgs, Attention, FeedForward, KVCache, RMSNorm, precompute_freqs_cis, sample sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_decode(device, prompt_length, nr_tokens): # Setup model & model args @@ -59,7 +59,7 @@ def test_decode(device, prompt_length, nr_tokens): T = 1 # Check output token - test_result("Mistral", res, cpu_res) + check_result("Mistral", res, cpu_res) def test_attention(device): args = ModelArgs() @@ -86,7 +86,7 @@ def test_attention(device): opt_fn = torch.compile(dynamic=False)(model) res = opt_fn(prompt, None, mask, input_pos) cpu_res = cpu_model(cpu_prompt, None, cpu_mask, cpu_input_pos) - test_result("Attention", res, cpu_res) + check_result("Attention", res, cpu_res) def test_ffn(device): args = ModelArgs() @@ -107,7 +107,7 @@ def test_ffn(device): opt_fn = torch.compile(dynamic=False)(model) res = opt_fn(prompt) cpu_res = cpu_model(cpu_prompt) - test_result("FFN", res, cpu_res) + check_result("FFN", res, cpu_res) def test_concat(device, size1=(1, 8, 32, 64), size2=(1, 8, 1, 64), dim=2): def concat_tensors(a, b): @@ -124,7 +124,7 @@ def concat_tensors(a, b): res = opt_fn(x, y) out = concat_tensors(cpu_x, cpu_y) - test_result("ConcatTensors", res, out) + check_result("ConcatTensors", res, out) def test_rmsnorm(device, seq=32): dim = 512 @@ -143,7 +143,7 @@ def test_rmsnorm(device, seq=32): res = opt_fn(x) cpu_res = cpu_model(cpu_x) - test_result("RMSNorm", res, cpu_res) + check_result("RMSNorm", res, cpu_res) if __name__ == "__main__": device = torch.device("npu:0") diff --git a/tests/models/MoE/test_moe.py b/tests/models/MoE/test_moe.py index 6df068034..3576ef59e 100644 --- a/tests/models/MoE/test_moe.py +++ b/tests/models/MoE/test_moe.py @@ -15,7 +15,7 @@ from torch._inductor import config sys.path.insert(0, os.path.join(os.environ.get('TORCHSIM_DIR', default='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/workspace/PyTorchSim'), 'tests')) -from _pytorchsim_utils import test_result +from result_check import check_result # FIXME. This is a Dynamo bug. Solution to avoid is_forward conflict during backward def patch_metrics_context_update(): @@ -424,8 +424,8 @@ def test_moe(device): model_cpu.train() # model_cpu.eval() cpu_hat, cpu_aux_loss = model_cpu(x2) - test_result("MoE Forward", y_hat, cpu_hat) - test_result("MoE Aux Loss", aux_loss, cpu_aux_loss) + check_result("MoE Forward", y_hat, cpu_hat) + check_result("MoE Aux Loss", aux_loss, cpu_aux_loss) print("MoE Forward Done!") # Backward @@ -461,11 +461,11 @@ def test_moe(device): print("MoE Weight Bias Grad") for i in range(num_experts): print(f"\nExpert {i}") - test_result(f"FC1 Grad", model.experts[i].fc1.weight.grad, model_cpu.experts[i].fc1.weight.grad) - test_result(f"FC1 Bias", model.experts[i].fc1.bias.grad, model_cpu.experts[i].fc1.bias.grad) + check_result(f"FC1 Grad", model.experts[i].fc1.weight.grad, model_cpu.experts[i].fc1.weight.grad) + check_result(f"FC1 Bias", model.experts[i].fc1.bias.grad, model_cpu.experts[i].fc1.bias.grad) print("\n") - test_result(f"FC2 Grad", model.experts[i].fc2.weight.grad, model_cpu.experts[i].fc2.weight.grad) - test_result(f"FC2 Bias", model.experts[i].fc2.bias.grad, model_cpu.experts[i].fc2.bias.grad) + check_result(f"FC2 Grad", model.experts[i].fc2.weight.grad, model_cpu.experts[i].fc2.weight.grad) + check_result(f"FC2 Bias", model.experts[i].fc2.bias.grad, model_cpu.experts[i].fc2.bias.grad) print("\n") def train_moe(device): @@ -519,8 +519,8 @@ def weight_update(a, b, lr): model_cpu.train() # model_cpu.eval() cpu_hat, cpu_aux_loss = model_cpu(x2) - test_result("MoE Forward", y_hat, cpu_hat) - test_result("MoE Aux Loss", aux_loss, cpu_aux_loss) + check_result("MoE Forward", y_hat, cpu_hat) + check_result("MoE Aux Loss", aux_loss, cpu_aux_loss) print("MoE Forward Done!") for i, out in enumerate(y_hat): @@ -541,18 +541,18 @@ def weight_update(a, b, lr): total_cpu_loss.backward() print("MoE Backward Done!") - test_result("MoE Forward", y_hat, cpu_hat) - test_result("MoE Aux Loss", aux_loss, cpu_aux_loss) - test_result("Loss", total_loss, total_cpu_loss) + check_result("MoE Forward", y_hat, cpu_hat) + check_result("MoE Aux Loss", aux_loss, cpu_aux_loss) + check_result("Loss", total_loss, total_cpu_loss) print("MoE Weight Bias Grad") for i in range(num_experts): print(f"\nExpert {i}") - test_result(f"FC1 Grad", model.experts[i].fc1.weight.grad, model_cpu.experts[i].fc1.weight.grad) - test_result(f"FC1 Bias", model.experts[i].fc1.bias.grad, model_cpu.experts[i].fc1.bias.grad) + check_result(f"FC1 Grad", model.experts[i].fc1.weight.grad, model_cpu.experts[i].fc1.weight.grad) + check_result(f"FC1 Bias", model.experts[i].fc1.bias.grad, model_cpu.experts[i].fc1.bias.grad) print("\n") - test_result(f"FC2 Grad", model.experts[i].fc2.weight.grad, model_cpu.experts[i].fc2.weight.grad) - test_result(f"FC2 Bias", model.experts[i].fc2.bias.grad, model_cpu.experts[i].fc2.bias.grad) + check_result(f"FC2 Grad", model.experts[i].fc2.weight.grad, model_cpu.experts[i].fc2.weight.grad) + check_result(f"FC2 Bias", model.experts[i].fc2.bias.grad, model_cpu.experts[i].fc2.bias.grad) print("\n") import matplotlib.pyplot as plt diff --git a/tests/models/MobileNet/test_mobilenet.py b/tests/models/MobileNet/test_mobilenet.py index 0b6ec0ed1..c78b810b6 100644 --- a/tests/models/MobileNet/test_mobilenet.py +++ b/tests/models/MobileNet/test_mobilenet.py @@ -8,7 +8,7 @@ import torch.utils.cpp_extension from torchvision.models import mobilenet_v2 sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result @@ -42,9 +42,9 @@ def run_mobilenet(batch): if isinstance(y_cpu, (list, tuple)): for i, (out_npu, out_cpu) in enumerate(zip(y_npu, y_cpu)): - test_result(f"MobileNet Output {i}", out_npu, out_cpu) + check_result(f"MobileNet Output {i}", out_npu, out_cpu) else: - test_result("MobileNet Output", y_npu, y_cpu) + check_result("MobileNet Output", y_npu, y_cpu) print("MobileNet Simulation Done") @@ -65,7 +65,7 @@ def test_inverted_residual_module(device, batch=1, inp=32, oup=32, stride=1, exp compiled_model_npu = torch.compile(dynamic=False)(model_npu) y_npu = compiled_model_npu(x_npu) - test_result("InvertedResidual Module", y_npu, y_cpu) + check_result("InvertedResidual Module", y_npu, y_cpu) print("InvertedResidual Module Test Done") diff --git a/tests/models/Qwen/test_qwen.py b/tests/models/Qwen/test_qwen.py index 18bd5b0fa..4cd52b71d 100644 --- a/tests/models/Qwen/test_qwen.py +++ b/tests/models/Qwen/test_qwen.py @@ -100,7 +100,7 @@ WHAT THIS FOUND: one defect, in this repo rather than in Qwen. Qwen3's q_norm fuses with rope into a PERSISTENT reduction over head_dim, and 27 live scratchpad tiles put it 1625120 bytes/lane over a 131072 budget. The scratchpad -retry in `pytorchsim/driver/codecache.py` answered that by halving R0_BLOCK, which +retry in `pytorchsim/backend/codecache.py` answered that by halving R0_BLOCK, which a persistent reduction writes into its own body and never reads from the launch -- so 128, 8 and 1 all measured the identical overflow and the kernel was refused. `_shrink_tile` now moves only a block the kernel actually takes as an @@ -116,7 +116,7 @@ import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result # Presets shrink cost, not character. Width carries head_dim, the GQA repeat @@ -417,7 +417,7 @@ def run_qwen( npu_out = _out(model_npu(input_ids=input_ids.to(device), attention_mask=attn_mask.to(device))) - test_result(f"Qwen {part} ({preset})", npu_out, cpu_out, rtol=rtol, atol=atol) + check_result(f"Qwen {part} ({preset})", npu_out, cpu_out, rtol=rtol, atol=atol) print("Max diff > ", torch.max(torch.abs(npu_out.cpu() - cpu_out))) print("Qwen Simulation Done") diff --git a/tests/models/Qwen/test_qwen_next.py b/tests/models/Qwen/test_qwen_next.py index f8c6ab9a7..479ace833 100644 --- a/tests/models/Qwen/test_qwen_next.py +++ b/tests/models/Qwen/test_qwen_next.py @@ -54,7 +54,7 @@ qwen3_asr 1.19e-06 216s 32 mel x 100 frames, 13 tokens The two audio figures are max abs diff read off the same shapes at the same - seed before this ran as a test; `test_result` itself reports only the + seed before this ran as a test; `check_result` itself reports only the verdict, and what it reported was Passed at rtol 1e-2 / atol 1e-4. THE AUDIO PATH IS NOT GATED YET, and the reason is a pin rather than a result. @@ -78,7 +78,7 @@ import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result FAMILIES = ("qwen3_vl", "qwen3_vl_moe", "qwen3_5", "qwen3_5_moe", "qwen3_next", "qwen2_audio", "qwen3_asr") @@ -199,7 +199,7 @@ def first(out): with torch.no_grad(): npu_out = first(runner(**kw_npu)).cpu() - test_result(f"Qwen {family}", npu_out, cpu_out, rtol=rtol, atol=atol) + check_result(f"Qwen {family}", npu_out, cpu_out, rtol=rtol, atol=atol) def run_audio(family, rtol=1e-2, atol=1e-4, compile_it=True): @@ -278,7 +278,7 @@ def first(out): with torch.no_grad(): npu_out = first(runner(**kw_npu)).cpu() - test_result(f"Qwen {family} audio", npu_out, cpu_out, rtol=rtol, atol=atol) + check_result(f"Qwen {family} audio", npu_out, cpu_out, rtol=rtol, atol=atol) if __name__ == "__main__": diff --git a/tests/models/Qwen/test_qwen_vl.py b/tests/models/Qwen/test_qwen_vl.py index 34005ca66..2dd24efea 100644 --- a/tests/models/Qwen/test_qwen_vl.py +++ b/tests/models/Qwen/test_qwen_vl.py @@ -95,7 +95,7 @@ import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result # Depth is one layer on BOTH sides, for the reason the text presets give: the @@ -323,7 +323,7 @@ def run_qwen_vl(device, version="2", preset="2b", dtype="float32", npu_kwargs = {k: (v.to(device) if torch.is_tensor(v) else v) for k, v in kwargs.items()} npu_out = _logits(model_npu(**npu_kwargs)) - test_result(f"Qwen{'2' if version == '2' else '2.5'}-VL ({preset})", + check_result(f"Qwen{'2' if version == '2' else '2.5'}-VL ({preset})", npu_out, cpu_out, rtol=rtol, atol=atol) print("Max diff > ", torch.max(torch.abs(npu_out.cpu() - cpu_out))) print("Qwen-VL Simulation Done") diff --git a/tests/models/Yolo/test_yolo.py b/tests/models/Yolo/test_yolo.py index 1cb301739..7dcff331e 100644 --- a/tests/models/Yolo/test_yolo.py +++ b/tests/models/Yolo/test_yolo.py @@ -154,7 +154,7 @@ a kernel would run the convolution on the HOST and simulate nothing. The fix is to stop emitting it: a transposed convolution IS a direct one over an input with stride-1 zeros inserted, and that rewrite lives in - ``pytorchsim/frontend/inductor_patches.py``, wrapped around the convolution + ``pytorchsim/frontend/inductor/lowering.py``, wrapped around the convolution LOWERING. Verified against aten over the product of stride, padding, output_padding, dilation, groups and kernel size before it was wired in, then through the route on twelve shapes. It costs stride^2 times the @@ -271,7 +271,7 @@ import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result # One preset per parser version directory under ultralytics/cfg/models. The @@ -505,7 +505,7 @@ def run_yolo(device, version="v8", batch=1, imgsz=None, compile_model=True, rtol # element is already within 1e-2 of zero -- so each output gets # atol = tol * max|ref| instead, floored so an all-zero tensor still has a # threshold. That is one criterion, applied at nine different scales. - # The whole table is printed BEFORE any assertion. test_result exits on + # The whole table is printed BEFORE any assertion. check_result exits on # the first mismatch, and a failure that reports one output while hiding # the other eight says nothing about where the divergence starts. worst = worst_rel = 0.0 @@ -523,7 +523,7 @@ def run_yolo(device, version="v8", batch=1, imgsz=None, compile_model=True, rtol print(f"Max diff > {worst}") print(f"Max rel > {worst_rel}") for i, a, b, scaled_atol in rows: - test_result(f"YOLO {version} output[{i}] {tuple(b.shape)}", a, b, + check_result(f"YOLO {version} output[{i}] {tuple(b.shape)}", a, b, rtol=rtol, atol=scaled_atol) print("Yolo Simulation Done") diff --git a/tests/models/Yolov5/test_yolov5.py b/tests/models/Yolov5/test_yolov5.py index da6202146..84e3925d7 100644 --- a/tests/models/Yolov5/test_yolov5.py +++ b/tests/models/Yolov5/test_yolov5.py @@ -14,7 +14,7 @@ import sys import shutil sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def run_yolo(batch): import copy @@ -54,9 +54,9 @@ def run_yolo(batch): # YOLOv5 output is typically a list or tensor, handle both cases if isinstance(y_cpu, (list, tuple)): for i, (out_npu, out_cpu) in enumerate(zip(y_npu, y_cpu)): - test_result(f"YOLOv5 Output {i}", out_npu, out_cpu) + check_result(f"YOLOv5 Output {i}", out_npu, out_cpu) else: - test_result("YOLOv5 Output", y_npu, y_cpu) + check_result("YOLOv5 Output", y_npu, y_cpu) print("Yolo Simulation Done") @@ -100,9 +100,9 @@ def test_c3_module(device, batch=1, c1=64, c2=128, n=1, h=64, w=64): # Compare results if isinstance(y_cpu, (list, tuple)): for i, (out_npu, out_cpu) in enumerate(zip(y_npu, y_cpu)): - test_result(f"C3 Output {i}", out_npu, out_cpu) + check_result(f"C3 Output {i}", out_npu, out_cpu) else: - test_result("C3 Output", y_npu, y_cpu) + check_result("C3 Output", y_npu, y_cpu) print("C3 Module Test Done") @@ -143,7 +143,7 @@ def test_bottleneck_module(device, batch=1, c1=64, c2=64, shortcut=True, g=1, e= y_npu = compiled_model_npu(x_npu) # Compare results - test_result("Bottleneck Module", y_npu, y_cpu) + check_result("Bottleneck Module", y_npu, y_cpu) print("Bottleneck Module Test Done") @@ -184,7 +184,7 @@ def test_conv_module(device, batch=1, c1=32, c2=64, k=3, s=1, p=None, g=1, d=1, y_npu = compiled_model_npu(x_npu) # Compare results - test_result("Conv Module", y_npu, y_cpu) + check_result("Conv Module", y_npu, y_cpu) print("Conv Module Test Done") @@ -221,7 +221,7 @@ def concat_fn(x1, x2, x3): y_npu = compiled_concat(x1_npu, x2_npu, x3_npu) # Compare results - test_result("Concat 4D", y_npu, y_cpu) + check_result("Concat 4D", y_npu, y_cpu) print(f"Output shape: {y_npu.shape}") print("Concat 4D Test Done") diff --git a/tests/models/test_clip.py b/tests/models/test_clip.py index 35566aa1d..55876931e 100644 --- a/tests/models/test_clip.py +++ b/tests/models/test_clip.py @@ -6,7 +6,7 @@ from transformers import CLIPVisionConfig, CLIPVisionModel sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def _init_weights(m): @@ -50,7 +50,7 @@ def test_clip(device, batch=2, image_size=224, patch_size=32, num_layers=2): opt_model = torch.compile(dynamic=False)(model) out_device = opt_model(pixel_values=x.to(device)).last_hidden_state - test_result(f"CLIP vision (batch={batch})", out_device, out_cpu) + check_result(f"CLIP vision (batch={batch})", out_device, out_cpu) print("Max diff >", torch.max(torch.abs(out_device.cpu() - out_cpu))) print("CLIP Simulation Done") diff --git a/tests/models/test_convnextv2.py b/tests/models/test_convnextv2.py index bfde58f4d..b1e8ee5e9 100644 --- a/tests/models/test_convnextv2.py +++ b/tests/models/test_convnextv2.py @@ -6,7 +6,7 @@ from transformers import ConvNextV2Config, ConvNextV2Model sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def _init_weights(m): @@ -48,7 +48,7 @@ def test_convnextv2(device, batch=2, image_size=64, patch_size=4): opt_model = torch.compile(dynamic=False)(model) out_device = opt_model(pixel_values=x.to(device)).last_hidden_state - test_result(f"ConvNeXt V2 (batch={batch})", out_device, out_cpu) + check_result(f"ConvNeXt V2 (batch={batch})", out_device, out_cpu) print("Max diff >", torch.max(torch.abs(out_device.cpu() - out_cpu))) print("ConvNeXt V2 Simulation Done") diff --git a/tests/models/test_mlp.py b/tests/models/test_mlp.py index cb27fe76c..a1c32d056 100644 --- a/tests/models/test_mlp.py +++ b/tests/models/test_mlp.py @@ -3,7 +3,7 @@ import copy import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result class MLP(torch.nn.Module): def __init__(self, input_size=28*28, hidden_size=64, output_size=8): @@ -44,12 +44,12 @@ def test_mlp(device, batch_size=64, input_size=64, hidden_size=32, output_size=8 cpu_loss = loss_fn(cpu_y, y2) loss.backward() cpu_loss.backward() - test_result("MLP Forward", y, cpu_y) - test_result("Loss", loss, cpu_loss) - test_result("MLP Weight1 Backward", model.linear1.weight.grad, cpu_model.linear1.weight.grad) - test_result("MLP Bias1 Backward", model.linear1.bias.grad, cpu_model.linear1.bias.grad) - test_result("MLP Weight2 Backward", model.linear2.weight.grad, cpu_model.linear2.weight.grad) - test_result("MLP Bias2 Backward", model.linear2.bias.grad, cpu_model.linear2.bias.grad) + check_result("MLP Forward", y, cpu_y) + check_result("Loss", loss, cpu_loss) + check_result("MLP Weight1 Backward", model.linear1.weight.grad, cpu_model.linear1.weight.grad) + check_result("MLP Bias1 Backward", model.linear1.bias.grad, cpu_model.linear1.bias.grad) + check_result("MLP Weight2 Backward", model.linear2.weight.grad, cpu_model.linear2.weight.grad) + check_result("MLP Bias2 Backward", model.linear2.bias.grad, cpu_model.linear2.bias.grad) def test_mlp_inf(device, batch_size=64, input_size=64, hidden_size=32, output_size=8, sparsity=0.0): torch.manual_seed(0) @@ -65,7 +65,7 @@ def test_mlp_inf(device, batch_size=64, input_size=64, hidden_size=32, output_si cpu_model = copy.deepcopy(model).to("cpu") cpu_model.requires_grad = False cpu_y = cpu_model(x2) - test_result("MLP Forward", y, cpu_y) + check_result("MLP Forward", y, cpu_y) def test_optimizer(device): torch.manual_seed(0) @@ -89,7 +89,7 @@ def test_optimizer(device): cpu_loss.backward() opt_step() cpu_optimizer.step() - test_result("Optimizer", model.linear1.weight, cpu_model.linear1.weight) + check_result("Optimizer", model.linear1.weight, cpu_model.linear1.weight) if __name__ == "__main__": device = torch.device("npu:0") diff --git a/tests/models/test_resnet.py b/tests/models/test_resnet.py index f9f13bd48..3a4ec1218 100644 --- a/tests/models/test_resnet.py +++ b/tests/models/test_resnet.py @@ -6,7 +6,7 @@ import os import sys sys.path.insert(0, os.path.join(os.environ.get('TORCHSIM_DIR', default='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/workspace/PyTorchSim'), 'tests')) -from _pytorchsim_utils import test_result +from result_check import check_result def test_resnet(device, batch=1, model_type='resnet18'): from torchvision.models import resnet @@ -26,7 +26,7 @@ def test_resnet(device, batch=1, model_type='resnet18'): res = opt_fn(x1) cpu_model = model.cpu().to(memory_format=torch.channels_last) cpu_res = cpu_model(x2) - test_result(f"{model_type} inference", res, cpu_res) + check_result(f"{model_type} inference", res, cpu_res) print("Max diff > ", torch.max(torch.abs(res.cpu() - cpu_res))) print(f"{model_type} Simulation Done") diff --git a/tests/models/test_single_perceptron.py b/tests/models/test_single_perceptron.py index 3b2621321..65ea35b0e 100644 --- a/tests/models/test_single_perceptron.py +++ b/tests/models/test_single_perceptron.py @@ -3,7 +3,7 @@ import copy import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_single_perceptron(device): def perceptron(a, b, c): @@ -41,10 +41,10 @@ def weight_update(a, b, lr): cpu_y = perceptron(x2, w2, b2) cpu_loss = loss_fn(cpu_y, y2) cpu_loss.backward() - test_result("Perceptron", y, cpu_y) - test_result("Loss", loss, cpu_loss) - test_result("Weight Update", w1.grad, w2.grad) - test_result("Bias Update", b1.grad, b2.grad) + check_result("Perceptron", y, cpu_y) + check_result("Loss", loss, cpu_loss) + check_result("Weight Update", w1.grad, w2.grad) + check_result("Bias Update", b1.grad, b2.grad) # for i in range(50): # y = opt_mlp(w1, x1, b1) # loss = opt_loss(y, y1) diff --git a/tests/models/test_swinv2.py b/tests/models/test_swinv2.py index dd63fc9a9..d41f7a664 100644 --- a/tests/models/test_swinv2.py +++ b/tests/models/test_swinv2.py @@ -6,7 +6,7 @@ from transformers import Swinv2Config, Swinv2Model sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def _init_weights(m): @@ -74,7 +74,7 @@ def test_swinv2(device, batch=2, image_size=64, window_size=8): out_cpu = model.cpu()(pixel_values=x.cpu()).last_hidden_state - test_result(f"SwinV2 shifted-window (batch={batch})", out_device, out_cpu) + check_result(f"SwinV2 shifted-window (batch={batch})", out_device, out_cpu) print("Max diff >", torch.max(torch.abs(out_device.cpu() - out_cpu))) print("SwinV2 Simulation Done") diff --git a/tests/models/test_transformer.py b/tests/models/test_transformer.py index 2eaa9fd0a..fd5e1fbe5 100644 --- a/tests/models/test_transformer.py +++ b/tests/models/test_transformer.py @@ -4,7 +4,7 @@ import copy import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def clones(module, N): "Produce N identical layers." @@ -68,7 +68,7 @@ def test_EncoderBlock(device, head=12, embed_dim=768, input_seq=512): opt_fn = torch.compile(dynamic=False)(encoder_block) res = opt_fn(query) - test_result("Encoder Block Forwrad", res, cpu_res) + check_result("Encoder Block Forwrad", res, cpu_res) def test_Attention(device, head=16, seq=512, d_k=64): def attention(query, key, value): @@ -87,7 +87,7 @@ def attention(query, key, value): res = opt_fn(query, key, value) cpu_res = attention(query.cpu(), key.cpu(), value.cpu()) - test_result("Attention Forward", res, cpu_res) + check_result("Attention Forward", res, cpu_res) def test_MHA(device, num_heads=12, embed_dim=768, input_seq=512): MHA = my_MultiheadAttention(num_heads, embed_dim) @@ -99,7 +99,7 @@ def test_MHA(device, num_heads=12, embed_dim=768, input_seq=512): opt_fn = torch.compile(dynamic=False)(MHA) res = opt_fn(query, query, query) - test_result("MHA Forward", res, cpu_res) + check_result("MHA Forward", res, cpu_res) if __name__ == "__main__": device = torch.device("npu:0") diff --git a/tests/models/test_vit.py b/tests/models/test_vit.py index 9fa8a2f0f..3fb31be93 100644 --- a/tests/models/test_vit.py +++ b/tests/models/test_vit.py @@ -7,7 +7,7 @@ import os import sys sys.path.insert(0, os.path.join(os.environ.get('TORCHSIM_DIR', default='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/workspace/PyTorchSim'), 'tests')) -from _pytorchsim_utils import test_result +from result_check import check_result def init_vit_weights(m): if isinstance(m, torch.nn.Linear): @@ -64,7 +64,7 @@ def test_vit(device, batch=1, shape=(3, 224, 224), num_layers=1, num_heads=12, h cpu_model = model.cpu() out_cpu = cpu_model(x_cpu) - test_result("VisionTransformer inference", out_device, out_cpu) + check_result("VisionTransformer inference", out_device, out_cpu) print("Max diff > ", torch.max(torch.abs(out_device.cpu() - out_cpu))) print("VisionTransformer Simulation Done") @@ -94,7 +94,7 @@ def test_multihead_attention(device, batch=1, seq_len=32, hidden_dim=768, num_he with torch.no_grad(): out_cpu, _ = mha_cpu(q2, k2, v2) - test_result("MultiheadAttention", out_device, out_cpu) + check_result("MultiheadAttention", out_device, out_cpu) print("Max diff > ", torch.max(torch.abs(out_device.cpu() - out_cpu))) print("MultiheadAttention Simulation Done") @@ -120,7 +120,7 @@ def test_encoder_block(device, batch=1, seq_len=16, hidden_dim=768, num_heads=12 cpu_block = block.cpu() out_cpu = cpu_block(x_cpu) - test_result("EncoderBlock", out_device, out_cpu) + check_result("EncoderBlock", out_device, out_cpu) print("Max diff >", torch.max(torch.abs(out_device.cpu() - out_cpu))) print("EncoderBlock Simulation Done") @@ -172,7 +172,7 @@ def test_encoder_block_with_class_token( wrapper_cpu = wrapper.cpu() out_cpu = wrapper_cpu(input_tensor.cpu()) - test_result("EncoderBlock with class token", out_device, out_cpu) + check_result("EncoderBlock with class token", out_device, out_cpu) print("Max diff >", torch.max(torch.abs(out_device.cpu() - out_cpu))) print("EncoderBlock with class token Simulation Done") diff --git a/tests/ops/attention/test_fused_sdpa.py b/tests/ops/attention/test_fused_sdpa.py index 54420e925..beab56312 100644 --- a/tests/ops/attention/test_fused_sdpa.py +++ b/tests/ops/attention/test_fused_sdpa.py @@ -65,7 +65,7 @@ def _err(out, ref): def _routed(): - from pytorchsim.frontend import attention + from pytorchsim.frontend.dispatcher import attention return getattr(attention, "ROUTED", None) @@ -146,7 +146,7 @@ def run_spad(name): since one query block's scratch is live at a time; doubling its D halves the block as the scratchpad bound binds, until one row per lane overruns it and fused_plan declines.""" from pytorchsim import config - from pytorchsim.frontend import attention + from pytorchsim.frontend.dispatcher import attention _, B, Hq, H, _, S0, D0, causal = CASES["prefill_causal_gqa"] def plan(S, D): diff --git a/tests/ops/attention/test_gqa.py b/tests/ops/attention/test_gqa.py index 038861c80..7b6dc2e7e 100644 --- a/tests/ops/attention/test_gqa.py +++ b/tests/ops/attention/test_gqa.py @@ -6,7 +6,7 @@ import torch._dynamo import argparse sys.path.insert(0, os.path.join(os.environ.get('TORCHSIM_DIR', default='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/workspace/PyTorchSim'), 'tests')) -from _pytorchsim_utils import test_result +from result_check import check_result @@ -167,7 +167,7 @@ def test_gqa_attention(device, batch=1, seq_len=32, embed_dim=768, num_heads=12, with torch.no_grad(): out_cpu = gqa_cpu(q2, k2, v2) - test_result("GQA Attention", out_device, out_cpu) + check_result("GQA Attention", out_device, out_cpu) print("Max diff > ", torch.max(torch.abs(out_device.cpu() - out_cpu))) print("GQA Attention Simulation Done") @@ -265,11 +265,11 @@ def scaled_dot_product_attention(query, key, value, attn_mask=None, dropout_p=0. is_causal=False, scale=None, enable_gqa=True) # Compare results - test_result("repeat_interleave in scaled_dot_product_attention", output_device[0], output_cpu[0]) + check_result("repeat_interleave in scaled_dot_product_attention", output_device[0], output_cpu[0]) print("Max diff > ", torch.max(torch.abs(output_device[0].cpu() - output_cpu[0]))) - test_result("repeat_interleave in scaled_dot_product_attention", output_device[1], output_cpu[1]) + check_result("repeat_interleave in scaled_dot_product_attention", output_device[1], output_cpu[1]) print("Max diff > ", torch.max(torch.abs(output_device[1].cpu() - output_cpu[1]))) - test_result("repeat_interleave in scaled_dot_product_attention", output_device[2], output_cpu[2]) + check_result("repeat_interleave in scaled_dot_product_attention", output_device[2], output_cpu[2]) print("Max diff > ", torch.max(torch.abs(output_device[2].cpu() - output_cpu[2]))) print("repeat_interleave compilation test Done") diff --git a/tests/ops/attention/test_gqa_decode.py b/tests/ops/attention/test_gqa_decode.py index 8f7bf50c8..fc4a6252d 100644 --- a/tests/ops/attention/test_gqa_decode.py +++ b/tests/ops/attention/test_gqa_decode.py @@ -6,7 +6,7 @@ import math import argparse sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result device = torch.device("npu:0") # ───────────────────────────────────────────────────────────────────────────── # Optimized: Flash-Decode style — tile S upfront, batch in B dimension @@ -199,7 +199,7 @@ def test_gqa_decode_optimized(model, device, seq_len: int = 10240, tile_size: in print(f" npu out max = {out_dev.cpu().abs().max().item():.6f}") print(f" cpu out max = {out_cpu.abs().max().item():.6f}") print(f" library out max = {out_library.abs().max().item():.6f}") - test_result("GQADecodeOptimized", out_dev, out_cpu, rtol=0, atol=0.05) + check_result("GQADecodeOptimized", out_dev, out_cpu, rtol=0, atol=0.05) diff --git a/tests/ops/conv/test_cnn.py b/tests/ops/conv/test_cnn.py index dcb4e14c8..38d894389 100644 --- a/tests/ops/conv/test_cnn.py +++ b/tests/ops/conv/test_cnn.py @@ -2,7 +2,7 @@ import sys import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result class CNN(torch.nn.Module): def __init__(self): @@ -32,7 +32,7 @@ def test_CNN(device): y = opt_fn(x1) cpu_model = model.to("cpu") cpu_y = cpu_model(x2) - test_result("CNN Forward", y, cpu_y, rtol=2e-1, atol=2e-1) + check_result("CNN Forward", y, cpu_y, rtol=2e-1, atol=2e-1) print("Max diff > ", torch.max(torch.abs(y.cpu() - cpu_y))) if __name__ == "__main__": diff --git a/tests/ops/conv/test_conv2d.py b/tests/ops/conv/test_conv2d.py index d4cfeff14..a077788b0 100644 --- a/tests/ops/conv/test_conv2d.py +++ b/tests/ops/conv/test_conv2d.py @@ -3,7 +3,7 @@ import torch import torch._dynamo sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_conv2d(device, batch_size=1, in_channels=8, out_channels=16, input_size=64, kernel_size=3, stride=1, padding=0): def custom_conv2d(a, b, bias): @@ -20,7 +20,7 @@ def custom_conv2d(a, b, bias): opt_fn = torch.compile(dynamic=False)(custom_conv2d) res = opt_fn(conv_input, conv_kernel, conv_bias) out = custom_conv2d(conv_input.cpu(), conv_kernel.cpu(), conv_bias.cpu()) - test_result("Conv2d Forward", res, out, rtol=1e-3, atol=1e-3) + check_result("Conv2d Forward", res, out, rtol=1e-3, atol=1e-3) print("Max diff > ", torch.max(torch.abs(res.cpu() - out))) if __name__ == "__main__": diff --git a/tests/ops/conv/test_conv_view_input.py b/tests/ops/conv/test_conv_view_input.py index f3d9740bb..1a4798c37 100644 --- a/tests/ops/conv/test_conv_view_input.py +++ b/tests/ops/conv/test_conv_view_input.py @@ -3,7 +3,7 @@ import torch import torch._dynamo sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_conv_view_input(device, batch_size=1, channels=32, height=8, width=8, out_channels=16, kernel_size=2): """Conv whose input is a free view (ReinterpretView) over a lower-rank buffer. @@ -25,7 +25,7 @@ def conv_on_view(a, b, bias): out = conv_on_view(conv_input, conv_kernel, conv_bias) opt_fn = torch.compile(dynamic=False)(conv_on_view) res = opt_fn(conv_input.to(device=device), conv_kernel.to(device=device), conv_bias.to(device=device)) - test_result("Conv2d view input", res, out, rtol=1e-3, atol=1e-3) + check_result("Conv2d view input", res, out, rtol=1e-3, atol=1e-3) print("Max diff > ", torch.max(torch.abs(res.cpu() - out))) if __name__ == "__main__": diff --git a/tests/ops/conv/test_group_conv.py b/tests/ops/conv/test_group_conv.py index 57dd10bad..b41d4ce57 100644 --- a/tests/ops/conv/test_group_conv.py +++ b/tests/ops/conv/test_group_conv.py @@ -4,7 +4,7 @@ import torch._dynamo from pytorchsim.simulator.togsim import TOGSimProcess sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_group_convolution( device, @@ -52,7 +52,7 @@ def custom_group_conv(a, weight, bias): res = opt_fn(x1, w1, b1) y = custom_group_conv(x2, w2, b2) label = f"Group Conv Forward (groups={groups}, stride={stride}, pad={padding})" - test_result(label, res, y, rtol=1e-3, atol=1e-3) + check_result(label, res, y, rtol=1e-3, atol=1e-3) print("Max diff > ", torch.max(torch.abs(res.cpu() - y))) diff --git a/tests/ops/conv/test_pool.py b/tests/ops/conv/test_pool.py index 91d8fce19..c33f032b2 100644 --- a/tests/ops/conv/test_pool.py +++ b/tests/ops/conv/test_pool.py @@ -2,7 +2,7 @@ import sys import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_maxpool(device, b=1, c=64, h=112, w=112): torch.manual_seed(0) @@ -15,7 +15,7 @@ def test_maxpool(device, b=1, c=64, h=112, w=112): res = opt_fn(x1) model.to("cpu") out = model(x2) - test_result("Maxpool Forward", res, out) # TODO: MaxPool Functionality is not working + check_result("Maxpool Forward", res, out) # TODO: MaxPool Functionality is not working def test_avgpool(device, b=1, c=64, h=112, w=112): def avgpool(a): @@ -27,7 +27,7 @@ def avgpool(a): opt_fn = torch.compile(dynamic=False)(avgpool) res = opt_fn(x1) out = avgpool(x2) - test_result("Avgpool Forward", res, out) + check_result("Avgpool Forward", res, out) if __name__ == "__main__": device = torch.device("npu:0") diff --git a/tests/ops/elementwise/test_activation.py b/tests/ops/elementwise/test_activation.py index f1c5de963..e494bdacf 100644 --- a/tests/ops/elementwise/test_activation.py +++ b/tests/ops/elementwise/test_activation.py @@ -5,7 +5,7 @@ import torch.utils.cpp_extension import torch.nn.functional as F sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_ReLU(device, size=(128, 128)): torch.manual_seed(0) @@ -16,7 +16,7 @@ def test_ReLU(device, size=(128, 128)): opt_fn = torch.compile(dynamic=False)(ReLU) y = opt_fn(x1) cpu_y = ReLU(x2) - test_result("ReLU", y, cpu_y) + check_result("ReLU", y, cpu_y) def test_GeLU(device, size=(128, 128), approximate='none'): torch.manual_seed(0) @@ -27,7 +27,7 @@ def test_GeLU(device, size=(128, 128), approximate='none'): opt_fn = torch.compile(dynamic=False)(GeLU) y = opt_fn(x1) cpu_y = GeLU(x2) - test_result("GeLU", y, cpu_y) + check_result("GeLU", y, cpu_y) def test_sigmoid(device, size=(128, 128)): torch.manual_seed(0) @@ -38,7 +38,7 @@ def test_sigmoid(device, size=(128, 128)): opt_fn = torch.compile(dynamic=False)(Sigmoid) y = opt_fn(x1) cpu_y = Sigmoid(x2) - test_result("Sigmoid", y, cpu_y) + check_result("Sigmoid", y, cpu_y) def test_SiLU(device, size=(128, 128)): torch.manual_seed(0) @@ -49,7 +49,7 @@ def test_SiLU(device, size=(128, 128)): opt_fn = torch.compile(dynamic=False)(SiLU) y = opt_fn(x1) cpu_y = SiLU(x2) - test_result("SiLU", y, cpu_y) + check_result("SiLU", y, cpu_y) class SwiGLU(torch.nn.Module): def forward(self, x): @@ -65,7 +65,7 @@ def test_SwiGLU(device, size=(128, 128)): opt_fn = torch.compile(dynamic=False)(SwiGLU_fn) y = opt_fn(x1) cpu_y = SwiGLU_fn(x2) - test_result("SwiGLU", y, cpu_y) + check_result("SwiGLU", y, cpu_y) if __name__ == "__main__": import argparse diff --git a/tests/ops/elementwise/test_add.py b/tests/ops/elementwise/test_add.py index b3c94653f..24e6a9392 100644 --- a/tests/ops/elementwise/test_add.py +++ b/tests/ops/elementwise/test_add.py @@ -4,7 +4,7 @@ import torch._dynamo import torch.utils.cpp_extension sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_vectoradd(device, size=(128, 128)): def vectoradd(a, b): @@ -14,7 +14,7 @@ def vectoradd(a, b): opt_fn = torch.compile(dynamic=False)(vectoradd) res = opt_fn(x, y) out = vectoradd(x.cpu(), y.cpu()) - test_result("VectorAdd", res, out) + check_result("VectorAdd", res, out) def test_vector_scalar_add(device, size=(128, 128)): def vectoradd(a, b): @@ -24,7 +24,7 @@ def vectoradd(a, b): opt_fn = torch.compile(dynamic=False)(vectoradd) res = opt_fn(x, y) out = vectoradd(x.cpu(), y.cpu()) - test_result("VectorScalarAdd", res, out) + check_result("VectorScalarAdd", res, out) def test_vector_tensor_add(device, size=(128, 128)): def vectoradd(a, b): @@ -34,7 +34,7 @@ def vectoradd(a, b): opt_fn = torch.compile(dynamic=False)(vectoradd) res = opt_fn(x, y) out = vectoradd(x.cpu(), y.cpu()) - test_result("VectorTensorAdd", res, out) + check_result("VectorTensorAdd", res, out) if __name__ == "__main__": import argparse diff --git a/tests/ops/elementwise/test_exponent.py b/tests/ops/elementwise/test_exponent.py index 5bc578419..94e243c0c 100644 --- a/tests/ops/elementwise/test_exponent.py +++ b/tests/ops/elementwise/test_exponent.py @@ -2,7 +2,7 @@ import sys import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_exponent(device, size=(128, 128)): def exponent(a): @@ -11,7 +11,7 @@ def exponent(a): opt_fn = torch.compile(dynamic=False)(exponent) res = opt_fn(x) out = exponent(x.cpu()) - test_result("exponent", res, out) + check_result("exponent", res, out) if __name__ == "__main__": device = torch.device("npu:0") diff --git a/tests/ops/elementwise/test_transcendental.py b/tests/ops/elementwise/test_transcendental.py index c3a2ee0f1..fa7843918 100644 --- a/tests/ops/elementwise/test_transcendental.py +++ b/tests/ops/elementwise/test_transcendental.py @@ -4,7 +4,7 @@ import torch._dynamo import torch.utils.cpp_extension sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_tanh(device, size=(128, 128)): def tanh(a): @@ -13,7 +13,7 @@ def tanh(a): opt_fn = torch.compile(dynamic=False)(tanh) res = opt_fn(x) out = tanh(x.cpu()) - test_result("Tanh", res, out) + check_result("Tanh", res, out) def test_exp(device, size=(128, 128)): def exp(a): @@ -22,7 +22,7 @@ def exp(a): opt_fn = torch.compile(dynamic=False)(exp) res = opt_fn(x) out = exp(x.cpu()) - test_result("Exp", res, out) + check_result("Exp", res, out) def test_erf(device, size=(128, 128)): def erf(a): @@ -31,7 +31,7 @@ def erf(a): opt_fn = torch.compile(dynamic=False)(erf) res = opt_fn(x) out = erf(x.cpu()) - test_result("Erf", res, out) + check_result("Erf", res, out) def test_sin(device, size=(128, 128)): def sin(a): @@ -40,7 +40,7 @@ def sin(a): opt_fn = torch.compile(dynamic=False)(sin) res = opt_fn(x) out = sin(x.cpu()) - test_result("Sin", res, out) + check_result("Sin", res, out) def test_cos(device, size=(128, 128)): def cos(a): @@ -49,7 +49,7 @@ def cos(a): opt_fn = torch.compile(dynamic=False)(cos) res = opt_fn(x) out = cos(x.cpu()) - test_result("Cos", res, out) + check_result("Cos", res, out) if __name__ == "__main__": import argparse diff --git a/tests/ops/fusion/test_addmm_residual.py b/tests/ops/fusion/test_addmm_residual.py index e2fd97f1c..913479f7c 100644 --- a/tests/ops/fusion/test_addmm_residual.py +++ b/tests/ops/fusion/test_addmm_residual.py @@ -2,7 +2,7 @@ import sys import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_addmm_residual(device, input_size=128, hidden_size=128, output_size=128): def addmm_residual(a, b, c, d): @@ -23,7 +23,7 @@ def addmm_residual(a, b, c, d): opt_fn = torch.compile(dynamic=False)(addmm_residual) res = opt_fn(b1, x1, w1, r1) y = addmm_residual(b2, x2, w2, r2) - test_result("Addmm + Residual Fusion Forward", res, y) + check_result("Addmm + Residual Fusion Forward", res, y) if __name__ == "__main__": device = torch.device("npu:0") diff --git a/tests/ops/fusion/test_attention_fusion.py b/tests/ops/fusion/test_attention_fusion.py index 3edb589ba..92ee29ddc 100644 --- a/tests/ops/fusion/test_attention_fusion.py +++ b/tests/ops/fusion/test_attention_fusion.py @@ -3,7 +3,7 @@ import copy import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def clones(module, N): "Produce N identical layers." @@ -54,7 +54,7 @@ def test_MHA(device, num_heads=12, embed_dim=768, input_seq=512): opt_fn = torch.compile(dynamic=False)(MHA) res = opt_fn(query, key, value) - test_result("MHA Forward", res, cpu_res) + check_result("MHA Forward", res, cpu_res) if __name__ == "__main__": device = torch.device("npu:0") diff --git a/tests/ops/fusion/test_bmm_reduction.py b/tests/ops/fusion/test_bmm_reduction.py index a9e027259..75fe61ad6 100644 --- a/tests/ops/fusion/test_bmm_reduction.py +++ b/tests/ops/fusion/test_bmm_reduction.py @@ -2,7 +2,7 @@ import sys import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_bmm_reduce(device, batch=12, size=512): def bmm(a, b): @@ -21,8 +21,8 @@ def bmm(a, b): opt_fn = torch.compile(dynamic=False)(bmm) res = opt_fn(x1, w1) y = bmm(x2, w2) - test_result("BMM Reduction Fusion activation", res[0], y[0]) - test_result("BMM Reduction Fusion reduction", res[1], y[1]) + check_result("BMM Reduction Fusion activation", res[0], y[0]) + check_result("BMM Reduction Fusion reduction", res[1], y[1]) if __name__ == "__main__": device = torch.device("npu:0") diff --git a/tests/ops/fusion/test_conv_fusion.py b/tests/ops/fusion/test_conv_fusion.py index eb168086c..de6f0a226 100644 --- a/tests/ops/fusion/test_conv_fusion.py +++ b/tests/ops/fusion/test_conv_fusion.py @@ -2,7 +2,7 @@ import sys import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result # exit(1) @@ -24,7 +24,7 @@ def custom_conv2d(a, b, bias, c): opt_fn = torch.compile(dynamic=False)(custom_conv2d) res = opt_fn(conv_input, conv_kernel, conv_bias, add_tensor) out = custom_conv2d(conv_input.cpu(), conv_kernel.cpu(), conv_bias.cpu(), add_tensor.cpu()) - test_result("Conv2d Residual Fusion Forward", res, out, rtol=1e-3, atol=1e-3) + check_result("Conv2d Residual Fusion Forward", res, out, rtol=1e-3, atol=1e-3) print("Max diff > ", torch.max(torch.abs(res.cpu() - out))) @@ -43,7 +43,7 @@ def custom_conv2d(a, b, bias, c): opt_fn = torch.compile(dynamic=False)(custom_conv2d) res = opt_fn(conv_input, conv_kernel, conv_bias, 2) out = custom_conv2d(conv_input.cpu(), conv_kernel.cpu(), conv_bias.cpu(), 2) - test_result("Conv2d + Scalar Fusion Forward", res, out, rtol=1e-3, atol=1e-3) + check_result("Conv2d + Scalar Fusion Forward", res, out, rtol=1e-3, atol=1e-3) print("Max diff > ", torch.max(torch.abs(res.cpu() - out))) def test_conv_relu(device, batch_size=1, in_channels=8, out_channels=16, input_size=64, kernel_size=3, stride=1, padding=0): @@ -61,7 +61,7 @@ def custom_conv2d(a, b, bias): opt_fn = torch.compile(dynamic=False)(custom_conv2d) res = opt_fn(conv_input, conv_kernel, conv_bias) out = custom_conv2d(conv_input.cpu(), conv_kernel.cpu(), conv_bias.cpu()) - test_result("Conv2d + ReLU Fusion Forward", res, out, rtol=1e-3, atol=1e-3) + check_result("Conv2d + ReLU Fusion Forward", res, out, rtol=1e-3, atol=1e-3) print("Max diff > ", torch.max(torch.abs(res.cpu() - out))) def test_conv_bn_relu(device, batch_size=1, in_channels=8, out_channels=16, input_size=64, kernel_size=3, stride=1, padding=0): @@ -85,7 +85,7 @@ def custom_conv_bn_relu(a, b, bias, c, d, e, f): with torch.no_grad(): res = opt_fn(conv_input, conv_kernel, conv_bias, bn_mean, bn_var, bn_weight, bn_bias) out = custom_conv_bn_relu(conv_input.cpu(), conv_kernel.cpu(), conv_bias.cpu(), bn_mean.cpu(), bn_var.cpu(), bn_weight.cpu(), bn_bias.cpu()) - test_result("Conv2d + BN + ReLU Fusion Forward", res, out, rtol=1e-3, atol=1e-3) + check_result("Conv2d + BN + ReLU Fusion Forward", res, out, rtol=1e-3, atol=1e-3) print("Max diff > ", torch.max(torch.abs(res.cpu() - out))) if __name__ == "__main__": diff --git a/tests/ops/fusion/test_matmul_activation.py b/tests/ops/fusion/test_matmul_activation.py index 60261ab9d..41d217024 100644 --- a/tests/ops/fusion/test_matmul_activation.py +++ b/tests/ops/fusion/test_matmul_activation.py @@ -3,7 +3,7 @@ import copy import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result class Matmul_ActivationFn(torch.nn.Module): def __init__(self, input_size, output_size, activation_fn): @@ -51,7 +51,7 @@ def test_matmul_activation(device, batch_size=16, input_size=32, output_size=8, cpu_model = copy.deepcopy(model).to("cpu") cpu_y = cpu_model(x2) if device: - test_result(f"Matmul_ActivationFn {activation_fn}", y, cpu_y) + check_result(f"Matmul_ActivationFn {activation_fn}", y, cpu_y) else: print("CPU output > ", cpu_y) diff --git a/tests/ops/fusion/test_matmul_reduction.py b/tests/ops/fusion/test_matmul_reduction.py index 3fbbec190..12e4cc6ed 100644 --- a/tests/ops/fusion/test_matmul_reduction.py +++ b/tests/ops/fusion/test_matmul_reduction.py @@ -4,7 +4,7 @@ import torch._dynamo import torch.utils.cpp_extension sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_matmul_reduce(device, M=512, N=512, K=512): def matmul_fused(a, b): @@ -22,8 +22,8 @@ def matmul_fused(a, b): opt_fn = torch.compile(dynamic=False)(matmul_fused) res = opt_fn(x1, w1) y = [t.float() for t in matmul_fused(x2, w2)] - test_result("Matmul Reduction Fusion activation", res[0], y[0]) - test_result("Matmul Reduction Fusion reduction", res[1], y[1]) + check_result("Matmul Reduction Fusion activation", res[0], y[0]) + check_result("Matmul Reduction Fusion reduction", res[1], y[1]) def test_matmul_reduce_last_dim(device, M=256, N=96, K=96): """Reducing the matmul output's contiguous (last) axis cannot be expressed in the GEMM's @@ -38,7 +38,7 @@ def matmul_fused(a, b): opt_fn = torch.compile(dynamic=False)(matmul_fused) res = opt_fn(input.to(device=device), weight.to(device=device)) y = matmul_fused(input.to("cpu", torch.float64), weight.to("cpu", torch.float64)).float() - test_result("Matmul reduce over contiguous axis", res, y) + check_result("Matmul reduce over contiguous axis", res, y) def test_matmul_var_mean(device, size=512): def matmul_fused(a, b, c): @@ -59,9 +59,9 @@ def matmul_fused(a, b, c): opt_fn = torch.compile(dynamic=False)(matmul_fused) res = opt_fn(x1, w1, c) y = [t.float() for t in matmul_fused(x2, w2, c)] - test_result("Matmul var_mean Fusion activation", res[0], y[0]) - test_result("Matmul var_mean Fusion reduction", res[1], y[1]) - test_result("Matmul var_mean Fusion reduction", res[2], y[2]) + check_result("Matmul var_mean Fusion activation", res[0], y[0]) + check_result("Matmul var_mean Fusion reduction", res[1], y[1]) + check_result("Matmul var_mean Fusion reduction", res[2], y[2]) def test_matmul_add_var_mean(device, M=768, N=512, K=3072): def matmul_fused(a, b, c, d): @@ -84,9 +84,9 @@ def matmul_fused(a, b, c, d): opt_fn = torch.compile(dynamic=False)(matmul_fused) res = opt_fn(x1, w1, b1, r1) y = [t.float() for t in matmul_fused(x2, w2, b2, r2)] - test_result("Matmul+residual+var_mean Fusion activation", res[0], y[0]) - test_result("Matmul+residual+var_mean Fusion reduction", res[1], y[1]) - test_result("Matmul+residual+var_mean Fusion reduction", res[2], y[2]) + check_result("Matmul+residual+var_mean Fusion activation", res[0], y[0]) + check_result("Matmul+residual+var_mean Fusion reduction", res[1], y[1]) + check_result("Matmul+residual+var_mean Fusion reduction", res[2], y[2]) if __name__ == "__main__": device = torch.device("npu:0") diff --git a/tests/ops/fusion/test_matmul_scalar.py b/tests/ops/fusion/test_matmul_scalar.py index 19a55518f..045c6a65c 100644 --- a/tests/ops/fusion/test_matmul_scalar.py +++ b/tests/ops/fusion/test_matmul_scalar.py @@ -4,7 +4,7 @@ import torch._dynamo import torch.utils.cpp_extension sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_matmul_scalar(device): def matmul_fused(a, b, c): @@ -21,7 +21,7 @@ def matmul_fused(a, b, c): opt_fn = torch.compile(dynamic=False)(matmul_fused) res = opt_fn(x1, w1, c) y = matmul_fused(x2, w2, c) - test_result("Matmul Scalar Fusion Forward", res, y) + check_result("Matmul Scalar Fusion Forward", res, y) if __name__ == "__main__": device = torch.device("npu:0") diff --git a/tests/ops/fusion/test_matmul_vector.py b/tests/ops/fusion/test_matmul_vector.py index c7e55272e..502f59dc9 100644 --- a/tests/ops/fusion/test_matmul_vector.py +++ b/tests/ops/fusion/test_matmul_vector.py @@ -2,7 +2,7 @@ import sys import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_matmul_vector(device, size=[56, 78, 239], dim=0): def matmul_fused(a, b, c, d): @@ -25,7 +25,7 @@ def matmul_fused(a, b, c, d): opt_fn = torch.compile(dynamic=False)(matmul_fused) res = opt_fn(x1, w1, a1, b1) y = matmul_fused(x2, w2, a2, b2) - test_result("Matmul Vector Fusion Forward", res, y) + check_result("Matmul Vector Fusion Forward", res, y) if __name__ == "__main__": device = torch.device("npu:0") diff --git a/tests/ops/fusion/test_prologue_fusion.py b/tests/ops/fusion/test_prologue_fusion.py index 05d89a398..bdaae407f 100644 --- a/tests/ops/fusion/test_prologue_fusion.py +++ b/tests/ops/fusion/test_prologue_fusion.py @@ -2,7 +2,7 @@ import sys import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_elem_broadcast_fusion(device): def matmul_fused(a, b, c): @@ -20,7 +20,7 @@ def matmul_fused(a, b, c): opt_fn = torch.compile(dynamic=False)(matmul_fused) res = opt_fn(x1, w1, c1) y = matmul_fused(x2, w2, c2) - test_result("Matmul Scalar Fusion Forward", res, y) + check_result("Matmul Scalar Fusion Forward", res, y) def test_elem_fusion(device): def matmul_fused(a, b, c): @@ -38,7 +38,7 @@ def matmul_fused(a, b, c): opt_fn = torch.compile(dynamic=False)(matmul_fused) res = opt_fn(x1, w1, c1) y = matmul_fused(x2, w2, c2) - test_result("Matmul Element-wise Fusion Forward", res, y) + check_result("Matmul Element-wise Fusion Forward", res, y) def test_elem_bmm_weight_fusion(device, batch_size=1, m=512, n=512, k=64): def bmm(a, b, c, d): @@ -53,7 +53,7 @@ def bmm(a, b, c, d): res = opt_fn(a, b, c, d) out = bmm(a.cpu(), b.cpu(), c.cpu(), d.cpu()) print(torch.max(torch.abs(res.cpu() - out))) - test_result("BMM Element-wise Fusion Forward", res, out) + check_result("BMM Element-wise Fusion Forward", res, out) def test_elem_bmm_input_fusion(device, batch_size=1, m=512, n=512, k=64): def bmm(a, b, c, d): @@ -68,7 +68,7 @@ def bmm(a, b, c, d): res = opt_fn(a, b, c, d) out = bmm(a.cpu(), b.cpu(), c.cpu(), d.cpu()) print(torch.max(torch.abs(res.cpu() - out))) - test_result("BMM Element-wise Fusion Forward", res, out) + check_result("BMM Element-wise Fusion Forward", res, out) if __name__ == "__main__": device = torch.device("npu:0") diff --git a/tests/ops/fusion/test_transformer_fusion.py b/tests/ops/fusion/test_transformer_fusion.py index b6eb274f9..4e461e234 100644 --- a/tests/ops/fusion/test_transformer_fusion.py +++ b/tests/ops/fusion/test_transformer_fusion.py @@ -4,7 +4,7 @@ import copy import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def clones(module, N): "Produce N identical layers." @@ -128,7 +128,7 @@ def test_EncoderBlock(device, head=12, embed_dim=768, input_seq=512): opt_fn = torch.compile(dynamic=False)(encoder_block) res = opt_fn(query) - test_result("Encoder Block Forwrad", res, cpu_res) + check_result("Encoder Block Forwrad", res, cpu_res) def test_Attention(device, head=16, seq=512, d_k=64): def attention(query, key, value): @@ -147,7 +147,7 @@ def attention(query, key, value): res = opt_fn(query, key, value) cpu_res = attention(query.cpu(), key.cpu(), value.cpu()) - test_result("Attention Forward", res, cpu_res) + check_result("Attention Forward", res, cpu_res) def test_MHA(device, num_heads=12, embed_dim=768, input_seq=512): MHA = my_MultiheadAttention(num_heads, embed_dim) @@ -159,7 +159,7 @@ def test_MHA(device, num_heads=12, embed_dim=768, input_seq=512): opt_fn = torch.compile(dynamic=False)(MHA) res = opt_fn(query, query, query) - test_result("MHA Forward", res, cpu_res) + check_result("MHA Forward", res, cpu_res) def test_EncoderBlock_validation(head=12, embed_dim=768, input_seq=512): bert_origin = EncoderBlock_origin(embed_dim, head) @@ -183,7 +183,7 @@ def test_EncoderBlock_validation(head=12, embed_dim=768, input_seq=512): origin_res = bert_origin(origin_query) res = bert(query) - test_result("Encoder Block Validation", res, origin_res) + check_result("Encoder Block Validation", res, origin_res) if __name__ == "__main__": device = torch.device("npu:0") diff --git a/tests/ops/gemm/test_bmm.py b/tests/ops/gemm/test_bmm.py index 5f0ae9c9e..13afba9c7 100644 --- a/tests/ops/gemm/test_bmm.py +++ b/tests/ops/gemm/test_bmm.py @@ -2,7 +2,7 @@ import sys import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_BMM(device, batch_size=1, m=32, n=16, k=64): def bmm(a, b): @@ -13,7 +13,7 @@ def bmm(a, b): opt_fn = torch.compile(dynamic=False)(bmm) res = opt_fn(a, b) out = bmm(a.cpu(), b.cpu()) - test_result("BMM Forward", res, out) + check_result("BMM Forward", res, out) def test_addBMM(device, batch_size=1, m=32, n=16, k=64, bias_rank=1):#TODO: Fusion should be implemented for this test def bmm(a, b, bias): @@ -26,7 +26,7 @@ def bmm(a, b, bias): opt_fn = torch.compile(dynamic=False)(bmm) res = opt_fn(a, b, bias) out = bmm(a.cpu(), b.cpu(), bias.cpu()) - test_result("BMM Forward", res, out) + check_result("BMM Forward", res, out) if __name__ == "__main__": device = torch.device("npu:0") diff --git a/tests/ops/gemm/test_grouped_mm.py b/tests/ops/gemm/test_grouped_mm.py index b3339ed65..8e63babd3 100644 --- a/tests/ops/gemm/test_grouped_mm.py +++ b/tests/ops/gemm/test_grouped_mm.py @@ -5,9 +5,11 @@ few_rows fewer rows than groups: every block holds rows, the grid stops at the row count eager outside torch.compile the call runs group by group (no Triton launch outside a compiled graph) grad inputs that require grad run group by group, and their gradients match the CPU's + fallback transformers' grouped_mm_fallback (its call when the weight is not bf16) takes the same kernel Usage: test_grouped_mm.py [case ...] (all cases when none is named) """ +import importlib import sys import torch @@ -40,16 +42,21 @@ def _err(out, ref): return ((out.float().cpu() - ref).abs().max() / ref.abs().max()).item() -def _run_compiled(sizes, k, n): +def _fallback(a, b, offs): + return torch.ops.transformers.grouped_mm_fallback(a, b, offs=offs) + + +def _run_compiled(sizes, k, n, fn=_gmm, dtype=torch.bfloat16): """(relative error, grouped-kernel launches, calls left to aten) of one compiled call.""" - from pytorchsim.driver import codecache - from pytorchsim.frontend import grouped_mm + from pytorchsim.backend import codecache + from pytorchsim.frontend.dispatcher import grouped_mm launches, externs = [], [] codecache.observe_launches(grouped_mm._grouped_mm_kernel, lambda: launches.append(1)) codecache.observe_every_extern(externs.append) a, b, offs = _inputs(sizes, k, n) + a, b = a.to(dtype), b.to(dtype) torch._dynamo.reset() - out = torch.compile(_gmm, dynamic=False)(a.to(device), b.to(device), offs.to(device)) + out = torch.compile(fn, dynamic=False)(a.to(device), b.to(device), offs.to(device)) return _err(out, _reference(a, b, offs)), len(launches), externs @@ -80,7 +87,14 @@ def case_grad(): return ea < TOL and eb < TOL, f"grad err a {ea:.3g}, b {eb:.3g}" -CASES = {"routed": case_routed, "few_rows": case_few_rows, "eager": case_eager, "grad": case_grad} +def case_fallback(): + importlib.import_module("transformers.integrations.moe") + err, launched, externs = _run_compiled([0, 130, 7, 0, 64, 1, 0, 30], 256, 256, _fallback, torch.float32) + return err < TOL and launched == 1 and not externs, f"err {err:.3g}, launches {launched}, externs {externs}" + + +CASES = {"routed": case_routed, "few_rows": case_few_rows, "eager": case_eager, "grad": case_grad, + "fallback": case_fallback} if __name__ == "__main__": diff --git a/tests/ops/gemm/test_matmul.py b/tests/ops/gemm/test_matmul.py index 756b99a20..2c7df35ad 100644 --- a/tests/ops/gemm/test_matmul.py +++ b/tests/ops/gemm/test_matmul.py @@ -2,7 +2,7 @@ import sys import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_matmul(device, input_size=128, hidden_size=128, output_size=128): def custom_matmul(a, b): @@ -17,7 +17,7 @@ def custom_matmul(a, b): opt_fn = torch.compile(dynamic=False)(custom_matmul) res = opt_fn(x1, w1) y = custom_matmul(x2, w2) - test_result("Matmul Forward", res, y) + check_result("Matmul Forward", res, y) def test_addmm(device, input_size=128, hidden_size=128, output_size=128, bias_rank=1): def custom_matmul(bias, a, b): @@ -35,7 +35,7 @@ def custom_matmul(bias, a, b): opt_fn = torch.compile(dynamic=False)(custom_matmul) res = opt_fn(b1, x1, w1) y = custom_matmul(b2, x2, w2) - test_result("Addmm Forward", res, y) + check_result("Addmm Forward", res, y) def test_addmm2(device, input_size=128, hidden_size=128, output_size=128): def custom_matmul(bias, a, b): @@ -53,7 +53,7 @@ def custom_matmul(bias, a, b): opt_fn = torch.compile(dynamic=False)(custom_matmul) res = opt_fn(b1, x1, w1) y = custom_matmul(b2, x2, w2) - test_result("Addmm2 Forward", res, y) + check_result("Addmm2 Forward", res, y) def test_linear(device, input_size=128, hidden_size=128, output_size=128): def custom_linear(a, b, bias): @@ -74,7 +74,7 @@ def custom_linear(a, b, bias): opt_fn = torch.compile(dynamic=False)(custom_linear) res = opt_fn(x1, w1, b1) y = custom_linear(x2, w2, b2) - test_result("Linear Forward", res, y) + check_result("Linear Forward", res, y) if __name__ == "__main__": device = torch.device("npu:0") diff --git a/tests/ops/gemm/test_row_matmul.py b/tests/ops/gemm/test_row_matmul.py index de84afb0a..414ba7d67 100644 --- a/tests/ops/gemm/test_row_matmul.py +++ b/tests/ops/gemm/test_row_matmul.py @@ -2,7 +2,7 @@ import sys import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_row_matmul(device, hidden_size=256, output_size=384): @@ -14,7 +14,7 @@ def row_matmul(a, b): weight = torch.randn(hidden_size, output_size) opt_fn = torch.compile(dynamic=False)(row_matmul) res = opt_fn(row.to(device=device), weight.to(device=device)) - test_result("Row Matmul Forward", res, row_matmul(row, weight)) + check_result("Row Matmul Forward", res, row_matmul(row, weight)) def test_row_addmm(device, hidden_size=256, output_size=384): @@ -27,7 +27,7 @@ def row_addmm(bias, a, b): bias = torch.randn(output_size) opt_fn = torch.compile(dynamic=False)(row_addmm) res = opt_fn(bias.to(device=device), row.to(device=device), weight.to(device=device)) - test_result("Row Addmm Forward", res, row_addmm(bias, row, weight)) + check_result("Row Addmm Forward", res, row_addmm(bias, row, weight)) def test_row_matmul_bf16(device, hidden_size=256, output_size=384): @@ -41,7 +41,7 @@ def row_matmul(a, b): opt_fn = torch.compile(dynamic=False)(row_matmul) res = opt_fn(row.to(device=device), weight.to(device=device)) want = row_matmul(row.float(), weight.float()).to(torch.bfloat16) - test_result("Row Matmul bf16 Forward", res.float(), want.float(), rtol=2e-2, atol=2e-2) + check_result("Row Matmul bf16 Forward", res.float(), want.float(), rtol=2e-2, atol=2e-2) if __name__ == "__main__": diff --git a/tests/ops/misc/test_complex_to_real.py b/tests/ops/misc/test_complex_to_real.py index e5da2c1bb..92e943b23 100644 --- a/tests/ops/misc/test_complex_to_real.py +++ b/tests/ops/misc/test_complex_to_real.py @@ -5,9 +5,9 @@ from torch.fx.experimental.proxy_tensor import make_fx from torch._inductor.decomposition import select_decomp_table sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result -from pytorchsim.frontend.rewrite_fx_graph import ComplexToRealPairs +from pytorchsim.frontend.inductor.post_grad_pass import pytorchsim_post_grad_pass aten = torch.ops.aten @@ -23,15 +23,20 @@ def _rope(x, a): def _trace(fn, *args): - # WITH INDUCTOR'S DECOMPOSITION TABLE, because that is the graph the pass - # actually runs on. A bare make_fx keeps aten.polar.default, which this - # backend decomposes one stage earlier (pytorchsim/frontend/rewrite_fx_graph.py) and - # which the pass therefore does not handle -- tracing without the table - # measures a graph the pipeline never produces. + """The graph Inductor hands its post-grad passes: make_fx with Inductor's decomposition table, which + keeps aten.polar, so the device pass rewrites it before the complex values.""" return make_fx(fn, decomposition_table=select_decomp_table(), tracing_mode="fake")(*args) +def _unlowered(gm): + """The ops of gm Inductor has no lowering for; the device pass runs after decomposition, so any it + inserts must lower as they are.""" + from torch._inductor.lowering import lowerings + return sorted({str(m.target) for m in gm.graph.nodes if callable(m.target) + and m.target not in lowerings and m.target.overloadpacket not in lowerings}) + + def _complex_nodes(graph): out = [] for n in graph.nodes: @@ -52,13 +57,13 @@ def test_pass_leaves_no_complex(): before = _complex_nodes(gm.graph) assert before, "the traced graph should have complex nodes to rewrite" - ComplexToRealPairs()(gm.graph) + pytorchsim_post_grad_pass(gm) gm.recompile() after = _complex_nodes(gm.graph) assert not after, f"complex nodes survived the pass: {[str(n.target) for n in after]}" - test_result("complex-to-real (rewritten graph)", gm(x, a), _rope(x, a)) + check_result("complex-to-real (rewritten graph)", gm(x, a), _rope(x, a)) def test_rope_on_device(device): @@ -69,7 +74,7 @@ def test_rope_on_device(device): x, a = torch.randn(1, 32, 64), torch.randn(1, 32, 32) cpu_out = _rope(x, a) npu_out = torch.compile(_rope, dynamic=False)(x.to(device=device), a.to(device=device)) - test_result("complex-to-real (RoPE on device)", npu_out, cpu_out) + check_result("complex-to-real (RoPE on device)", npu_out, cpu_out) def test_complex_scalar_multiply(): @@ -82,11 +87,54 @@ def f(x): x = torch.randn(1, 32, 64) gm = _trace(f, x) - ComplexToRealPairs()(gm.graph) + pytorchsim_post_grad_pass(gm) gm.recompile() after = _complex_nodes(gm.graph) assert not after, f"complex nodes survived the pass: {[str(n.target) for n in after]}" - test_result("complex-to-real (complex scalar)", gm(x), f(x)) + assert not _unlowered(gm), f"no Inductor lowering for {_unlowered(gm)}" + check_result("complex-to-real (complex scalar)", gm(x), f(x)) + + +def test_components_are_judged_apart(): + """A component the pass cannot say in real arithmetic leaves a separate one it can rewritten; every node it + makes keeps the stack trace of the node it replaces, and its from_node names that node.""" + def f(x, y): + a = torch.view_as_real(torch.view_as_complex(x) * (0.6 - 0.8j)) + b = torch.view_as_real(torch.exp(torch.view_as_complex(y))) + return a, b + + x, y = torch.randn(4, 8, 2), torch.randn(4, 8, 2) + gm = _trace(f, x, y) + for n in gm.graph.nodes: + n.meta["stack_trace"] = f"user.py:{n.name}" + n.meta["from_node"] = [n.name] + before = {n.name for n in gm.graph.nodes} + pytorchsim_post_grad_pass(gm) + for n in gm.graph.nodes: + if n.name in before: + continue + src = n.meta.get("from_node", []) + last = src[-1] if src else None + assert getattr(last, "name", None) in before, f"{n.name}: from_node {src}" + left = sorted(str(n.target) for n in _complex_nodes(gm.graph)) + assert left == ["aten.exp.default", "aten.view_as_complex.default"], f"complex nodes left: {left}" + bare = [n.name for n in gm.graph.nodes if callable(n.target) and "stack_trace" not in n.meta] + assert not bare, f"nodes without provenance: {bare}" + out = gm(x, y) + check_result("complex-to-real (components apart)", out[0], f(x, y)[0]) + + +def test_row_mm_stays_real(): + """The GEMV rewrite takes real floating operands only: a complex 1 x K mm stays one mm.""" + def f(a, b): + return torch.view_as_real(torch.view_as_complex(a) @ torch.view_as_complex(b)) + + a, b = torch.randn(1, 8, 2), torch.randn(8, 4, 2) + gm = _trace(f, a, b) + pytorchsim_post_grad_pass(gm) + mms = [n for n in gm.graph.nodes if n.target is aten.mm.default] + assert len(mms) == 1, f"complex mm rewritten: {[str(n.target) for n in gm.graph.nodes]}" + check_result("complex 1 x K mm", gm(a, b), f(a, b)) def test_unhandled_op_is_left_alone(): @@ -100,7 +148,7 @@ def f(x): x = torch.randn(1, 32, 64) gm = _trace(f, x) before = [str(n.target) for n in _complex_nodes(gm.graph)] - ComplexToRealPairs()(gm.graph) + pytorchsim_post_grad_pass(gm) after = [str(n.target) for n in _complex_nodes(gm.graph)] assert before == after, f"an ineligible component was rewritten: {before} -> {after}" print("unhandled complex op left alone:", after) @@ -110,5 +158,7 @@ def f(x): device = torch.device("npu:0") test_pass_leaves_no_complex() test_complex_scalar_multiply() + test_components_are_judged_apart() + test_row_mm_stays_real() test_unhandled_op_is_left_alone() test_rope_on_device(device) diff --git a/tests/ops/misc/test_eager_to_compile_recursion.py b/tests/ops/misc/test_eager_to_compile_recursion.py index b27f13eb4..4b10b0d40 100644 --- a/tests/ops/misc/test_eager_to_compile_recursion.py +++ b/tests/ops/misc/test_eager_to_compile_recursion.py @@ -3,7 +3,7 @@ import torch import torch._dynamo sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result # REGISTERED ON PURPOSE, and this file exists because of what that used to do. # @@ -20,7 +20,7 @@ # RecursionError: maximum recursion depth exceeded # # DeepSeek-V2's RoPE closed that loop, because it multiplies complex tensors. -# It does not close any more: rewrite_fx_graph.py rewrites the complex +# It does not close any more: frontend/post_grad_pass.py rewrites the complex # multiply into real arithmetic, so Inductor generates a kernel and no fallback # is emitted. This test is that sentence, executable -- it recurses on a tree # without that pass and passes with it. @@ -49,7 +49,7 @@ def test_registered_mul_out_does_not_recurse(device): "aten::mul.out recursed through its own eager_to_compile wrapper -- " "the complex multiply became a fallback again") - test_result("eager_to_compile mul.out + complex", npu_out, cpu_out) + check_result("eager_to_compile mul.out + complex", npu_out, cpu_out) if __name__ == "__main__": diff --git a/tests/ops/misc/test_expert_mask.py b/tests/ops/misc/test_expert_mask.py index 9da3b9ac9..21f7a11c9 100644 --- a/tests/ops/misc/test_expert_mask.py +++ b/tests/ops/misc/test_expert_mask.py @@ -4,7 +4,7 @@ import torch._dynamo import torch.utils.cpp_extension sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result @@ -27,7 +27,7 @@ def expert_mask(expert_idx, scores): opt_fn = torch.compile(dynamic=False)(expert_mask) npu_out = opt_fn(expert_idx.to(device=device), scores.to(device=device)) - test_result("ExpertMask (i64 == arange)", npu_out, cpu_out) + check_result("ExpertMask (i64 == arange)", npu_out, cpu_out) if __name__ == "__main__": diff --git a/tests/ops/misc/test_histc.py b/tests/ops/misc/test_histc.py index 440d9b4e4..296332d7e 100644 --- a/tests/ops/misc/test_histc.py +++ b/tests/ops/misc/test_histc.py @@ -2,8 +2,14 @@ import sys import torch import torch._dynamo +from torch import fx +from torch._subclasses.fake_tensor import FakeTensorMode sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result + +from pytorchsim.frontend.inductor.post_grad_pass import pytorchsim_post_grad_pass + +aten = torch.ops.aten def _histc(x, bins, lo, hi): @@ -22,8 +28,7 @@ def test_histc_integral(device, n=64, bins=8): # and "mps", integral otherwise -- so `npu` gets the branch written for # CUDA and the fallback then lands on the very kernel the first branch # exists to avoid. That is what stopped DeepSeek-V3 under transformers - # 5.15.0, and pytorchsim/frontend/rewrite_fx_graph.py is the answer: - # counting is dtype-blind, so it casts in and back out. + # 5.15.0; post_grad_pass.rewrite_aten_histc counts it on the device. # # Both integral widths are here because they take different paths back: # the counts return in the INPUT's dtype, which is the contract the CUDA @@ -39,13 +44,11 @@ def test_histc_integral(device, n=64, bins=8): assert npu_out.dtype == dtype, ( f"histc should return the input's dtype: {npu_out.dtype} != {dtype}") - test_result(f"histc {dtype}", npu_out, cpu_out) + check_result(f"histc {dtype}", npu_out, cpu_out) def test_histc_float_unchanged(device, n=64, bins=8): - # The floating case must keep going to ATen -- the decomposition returns - # NotImplemented there, which is also what stops it recursing on the cast - # it just made. + """A floating histc is counted on the device too, and comes back in its own dtype.""" g = torch.Generator().manual_seed(1) cpu_x = torch.rand(n, generator=g) * (bins - 1) cpu_out = torch.histc(cpu_x, bins=bins, min=0, max=bins - 1) @@ -54,10 +57,68 @@ def test_histc_float_unchanged(device, n=64, bins=8): npu_out = opt_fn(cpu_x.to(device=device), bins, 0, bins - 1) assert npu_out.dtype == torch.float32, npu_out.dtype - test_result("histc float32", npu_out, cpu_out) + check_result("histc float32", npu_out, cpu_out) + + +def _unlowered(gm): + """The ops of gm Inductor has no lowering for; the device pass runs after decomposition, so any it + inserts must lower as they are.""" + from torch._inductor.lowering import lowerings + return sorted({str(m.target) for m in gm.graph.nodes if callable(m.target) + and m.target not in lowerings and m.target.overloadpacket not in lowerings}) + + +def _histc_graph(x, bins, lo, hi): + """A graph of one aten.histc of x as the post-grad passes see it; built by hand, since make_fx cannot + trace an integral histc on the CPU.""" + mode = FakeTensorMode() + g = fx.Graph() + p = g.placeholder("x") + p.meta["val"] = mode.from_tensor(x) + h = g.call_function(aten.histc.default, (p, bins, lo, hi)) + with mode: + h.meta["val"] = torch.empty(bins, dtype=x.dtype) + g.output(h) + return fx.GraphModule(torch.nn.Module(), g) + + +def test_pass_counts_on_the_device(n=64): + """The device pass alone leaves no aten.histc and counts what aten counts: bins that are the values, + wider edges, int8 past 127 bins, floats with values on and past the edges, and min == max.""" + g = torch.Generator().manual_seed(2) + ints = torch.randint(-4, 20, (n,), generator=g) + floats = torch.cat([torch.rand(n, generator=g) * 3 - 1, torch.tensor([0., 0.5, 1., 1.0000001, float("nan")])]) + cases = ( + ("values", ints.clamp(0, 7).to(torch.int32), 8, 0, 7), + ("wide edges", ints.to(torch.int32), 8, 0, 15), + ("int8 past 127 bins", torch.tensor([0, 1, 127, -100, -100, -100], dtype=torch.int8), 200, 0, 199), + ("float", floats, 4, 0, 1), + ("float min == max", floats.nan_to_num(0.0), 5, 0, 0), + ("int64 min == max", ints, 6, 0, 0), + ("one value", torch.full((7,), 3, dtype=torch.int64), 4, 0, 0), + ) + for name, x, bins, lo, hi in cases: + gm = _histc_graph(x, bins, lo, hi) + pytorchsim_post_grad_pass(gm) + left = [m for m in gm.graph.nodes if m.target is aten.histc.default] + assert not left, f"{name}: {len(left)} aten.histc left" + assert not _unlowered(gm), f"{name}: no Inductor lowering for {_unlowered(gm)}" + ref = torch.histc(x.double() if not x.is_floating_point() else x, bins, lo, hi).to(x.dtype) + out = gm(x) + assert torch.equal(out, ref), f"{name}: {out.tolist()} != {ref.tolist()}" + print(f"histc pass {name}: {out.tolist()}") + for name, x, lo, hi in (("int edges that truncate to one", ints.to(torch.int32), 0.2, 0.8), + ("float max below min", floats, 1.0, 0.0)): + try: + pytorchsim_post_grad_pass(_histc_graph(x, 4, lo, hi)) + except RuntimeError as e: + assert "max must be larger than min" in str(e), f"{name}: {e}" + else: + raise AssertionError(f"{name}: [{lo}, {hi}] was not refused") if __name__ == "__main__": device = torch.device("npu:0") + test_pass_counts_on_the_device() test_histc_integral(device) test_histc_float_unchanged(device) diff --git a/tests/ops/misc/test_indirect_access.py b/tests/ops/misc/test_indirect_access.py index 057dcf485..fa4c51100 100644 --- a/tests/ops/misc/test_indirect_access.py +++ b/tests/ops/misc/test_indirect_access.py @@ -3,7 +3,7 @@ import torch import copy sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_indirect_vectoradd(device, size=(128, 128)): def vectoradd(a, idx, b): @@ -14,7 +14,7 @@ def vectoradd(a, idx, b): opt_fn = torch.compile(dynamic=False)(vectoradd) res = opt_fn(x, idx, y) out = vectoradd(x.cpu(), idx.cpu(), y.cpu()) - test_result("Indirect VectorAdd", res, out) + check_result("Indirect VectorAdd", res, out) def test_embedding(device, vocab_size, dim): emb = torch.nn.Embedding(vocab_size, dim) @@ -28,7 +28,7 @@ def test_embedding(device, vocab_size, dim): opt_emb = torch.compile(dynamic=False)(emb) res = opt_emb(prompt) cpu_res = cpu_emb(cpu_prompt) - test_result("Embedding", res, cpu_res) + check_result("Embedding", res, cpu_res) def test_multidim_indirect(device, size=(64, 64), n=256): torch.manual_seed(0) @@ -40,7 +40,7 @@ def gather2d(x, ix, iy): opt_fn = torch.compile(dynamic=False)(gather2d) res = opt_fn(x, ix, iy) out = gather2d(x.cpu(), ix.cpu(), iy.cpu()) - test_result("Multi-dim Indirect (x[ix,iy])", res, out) + check_result("Multi-dim Indirect (x[ix,iy])", res, out) def test_multidim_indirect_index_reuse(device, size=(64, 64), n=256): torch.manual_seed(0) @@ -53,7 +53,7 @@ def gather_reuse(x, ix, iy): opt_fn = torch.compile(dynamic=False)(gather_reuse) res = opt_fn(x, ix, iy) out = gather_reuse(x.cpu(), ix.cpu(), iy.cpu()) - test_result("Multi-dim Indirect index reuse (x[ix,iy]+ix)", res, out) + check_result("Multi-dim Indirect index reuse (x[ix,iy]+ix)", res, out) def test_scatter_full(device, size=(128, 128)): def vectoradd(a, idx, b): @@ -66,7 +66,7 @@ def vectoradd(a, idx, b): opt_fn = torch.compile(dynamic=False)(vectoradd) res = opt_fn(x, idx, y) out = vectoradd(x_cpu, idx.cpu(), y.cpu()) - test_result("Indirect VectorAdd", res, out) + check_result("Indirect VectorAdd", res, out) if __name__ == "__main__": device = torch.device("npu:0") diff --git a/tests/ops/misc/test_inplace_partial_write.py b/tests/ops/misc/test_inplace_partial_write.py index 07cfb66fd..6e281de57 100644 --- a/tests/ops/misc/test_inplace_partial_write.py +++ b/tests/ops/misc/test_inplace_partial_write.py @@ -20,7 +20,7 @@ inductor_meta: mutated_arg_names: ['out_ptr0'] The second kernel MUTATES buf0. `mutated_arg_names` is where Inductor says so, -and `pytorchsim/codegen/kernel_metadata.py` deliberately does not read it -- it decides +and `pytorchsim/frontend/inductor/codegen/kernel_metadata.py` deliberately does not read it -- it decides each argument's role from the stores Inductor renders instead, because the table overstates (an `in_out_ptr0` whose store Inductor removed is still listed, and believing it produced divergence reports about values nothing materialised). @@ -56,7 +56,7 @@ import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result T, E = 4, 4 #: NOT ZERO ON PURPOSE -- see the module docstring. Zero makes the defect pass. @@ -77,7 +77,7 @@ def f(vals, idx): cpu_out = f(vals, idx) npu_out = torch.compile(dynamic=False)(f)(vals.to(device), idx.to(device)) - test_result("scatter_ keeps the untouched elements", npu_out, cpu_out) + check_result("scatter_ keeps the untouched elements", npu_out, cpu_out) def test_index_put_keeps_the_base(device): @@ -91,7 +91,7 @@ def f(vals, idx): cpu_out = f(vals, idx) npu_out = torch.compile(dynamic=False)(f)(vals.to(device), idx.to(device)) - test_result("index_put_ keeps the untouched elements", npu_out, cpu_out) + check_result("index_put_ keeps the untouched elements", npu_out, cpu_out) def test_index_copy_keeps_the_base(device): @@ -104,7 +104,7 @@ def f(vals): cpu_out = f(vals) npu_out = torch.compile(dynamic=False)(f)(vals.to(device)) - test_result("index_copy_ keeps the untouched elements", npu_out, cpu_out) + check_result("index_copy_ keeps the untouched elements", npu_out, cpu_out) def test_masked_fill_is_the_boundary(device): @@ -123,7 +123,7 @@ def f(vals, idx): cpu_out = f(vals, idx) npu_out = torch.compile(dynamic=False)(f)(vals.to(device), idx.to(device)) - test_result("masked_fill_ writes every element", npu_out, cpu_out) + check_result("masked_fill_ writes every element", npu_out, cpu_out) if __name__ == "__main__": diff --git a/tests/ops/misc/test_masked_nondividing.py b/tests/ops/misc/test_masked_nondividing.py index 20d12c8a1..7c6f205ef 100644 --- a/tests/ops/misc/test_masked_nondividing.py +++ b/tests/ops/misc/test_masked_nondividing.py @@ -13,7 +13,7 @@ import torch.nn.functional as F sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_pad_2d(device, size=(5, 10), pad=(2, 3, 1, 1)): @@ -23,7 +23,7 @@ def fn(x): return F.pad(x, pad) x = torch.randn(size).to(device=device) res = torch.compile(dynamic=False)(fn)(x) - test_result(f"Pad2D {size} {pad}", res, fn(x.cpu())) + check_result(f"Pad2D {size} {pad}", res, fn(x.cpu())) def test_sum_over_broadcast(device, size=(5, 13)): @@ -35,7 +35,7 @@ def fn(a, b): a = torch.randn(size).to(device=device) b = torch.randn(size[0], 1).to(device=device) res = torch.compile(dynamic=False)(fn)(a, b) - test_result(f"SumOverBroadcast {size}", res, fn(a.cpu(), b.cpu())) + check_result(f"SumOverBroadcast {size}", res, fn(a.cpu(), b.cpu())) def test_softmax_nondividing(device, size=(4, 10)): @@ -44,7 +44,7 @@ def fn(a): return F.softmax(a, dim=1) a = torch.randn(size).to(device=device) res = torch.compile(dynamic=False)(fn)(a) - test_result(f"Softmax {size}", res, fn(a.cpu())) + check_result(f"Softmax {size}", res, fn(a.cpu())) def test_elementwise_nondividing(device, size=(7, 13)): @@ -53,7 +53,7 @@ def fn(a, b): a = torch.randn(size).to(device=device) b = torch.randn(size).to(device=device) res = torch.compile(dynamic=False)(fn)(a, b) - test_result(f"Elementwise {size}", res, fn(a.cpu(), b.cpu())) + check_result(f"Elementwise {size}", res, fn(a.cpu(), b.cpu())) def test_gather_nondividing(device, rows=13, cols=10, n=17): @@ -63,7 +63,7 @@ def fn(x, idx): x = torch.randn(rows, cols).to(device=device) idx = torch.randint(0, rows, [n]).to(device=device) res = torch.compile(dynamic=False)(fn)(x, idx) - test_result(f"Gather [{rows},{cols}]->{n}", res, fn(x.cpu(), idx.cpu())) + check_result(f"Gather [{rows},{cols}]->{n}", res, fn(x.cpu(), idx.cpu())) if __name__ == "__main__": diff --git a/tests/ops/misc/test_polar.py b/tests/ops/misc/test_polar.py index ec75a07e9..44efcf348 100644 --- a/tests/ops/misc/test_polar.py +++ b/tests/ops/misc/test_polar.py @@ -2,8 +2,12 @@ import sys import torch import torch._dynamo +from torch.fx.experimental.proxy_tensor import make_fx +from torch._inductor.decomposition import select_decomp_table sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result + +from pytorchsim.frontend.inductor.post_grad_pass import pytorchsim_post_grad_pass def _rope_like(a): @@ -26,32 +30,53 @@ def test_polar_on_transposed(device, n=32): # 'torch.ops.aten.polar.default') # AssertionError: expected size 32==32, stride 32==1 at dim=1 # - # pytorchsim/frontend/rewrite_fx_graph.py takes the extern call out - # instead of arguing about the layout: the pair is built with ops this - # backend compiles and view_as_complex names it, which Inductor already - # treats as a view over real data. + # post_grad_pass.rewrite_aten_polar takes the extern call out instead + # of arguing about the layout: the pair is built contiguous with ops this + # backend compiles, and the complex rewrite takes it to real pairs. x = torch.randn(1, n, n) cpu_out = _rope_like(x) opt_fn = torch.compile(dynamic=False)(_rope_like) npu_out = opt_fn(x.to(device=device)) - test_result("polar on a transposed view", npu_out, cpu_out) + check_result("polar on a transposed view", npu_out, cpu_out) def test_polar_contiguous(device, n=32): - # The ordinary case, which passed before the decomposition too: it is here - # so a future rewrite that only handles the transposed shape is caught. + """The ordinary case, so a rewrite that only handles the transposed shape is caught.""" def f(a): return torch.view_as_real(torch.polar(torch.ones_like(a), a)) x = torch.randn(1, n, n) cpu_out = f(x) npu_out = torch.compile(dynamic=False)(f)(x.to(device=device)) - test_result("polar on a contiguous tile", npu_out, cpu_out) + check_result("polar on a contiguous tile", npu_out, cpu_out) + + +def _unlowered(gm): + """The ops of gm Inductor has no lowering for; the device pass runs after decomposition, so any it + inserts must lower as they are.""" + from torch._inductor.lowering import lowerings + return sorted({str(m.target) for m in gm.graph.nodes if callable(m.target) + and m.target not in lowerings and m.target.overloadpacket not in lowerings}) + + +def test_pass_leaves_no_polar(n=32): + """The device pass alone, on a traced polar of a transposed view: no aten.polar and no complex value + is left, and the real pairs are polar's.""" + x = torch.randn(1, n, n) + gm = make_fx(_rope_like, decomposition_table=select_decomp_table(), tracing_mode="fake")(x) + pytorchsim_post_grad_pass(gm) + left = [str(m.target) for m in gm.graph.nodes + if m.target is torch.ops.aten.polar.default + or (isinstance(m.meta.get("val"), torch.Tensor) and m.meta["val"].is_complex())] + assert not left, f"left after the pass: {left}" + assert not _unlowered(gm), f"no Inductor lowering for {_unlowered(gm)}" + check_result("polar pass", gm(x), _rope_like(x)) if __name__ == "__main__": device = torch.device("npu:0") + test_pass_leaves_no_polar() test_polar_on_transposed(device) test_polar_contiguous(device) diff --git a/tests/ops/misc/test_user_triton_kernel.py b/tests/ops/misc/test_user_triton_kernel.py index 8ba19c88a..1eb677cd5 100644 --- a/tests/ops/misc/test_user_triton_kernel.py +++ b/tests/ops/misc/test_user_triton_kernel.py @@ -22,7 +22,7 @@ sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result @triton.jit @@ -74,7 +74,7 @@ def wrap(x: torch.Tensor) -> torch.Tensor: def _check_roles(kernel, want): - from pytorchsim.codegen import kernel_metadata + from pytorchsim.frontend.inductor.codegen import kernel_metadata got = {n: r for n, r in kernel_metadata.ROLES_BY_KERNEL.items() if n.startswith(kernel)} if not got or any(r != want for r in got.values()): print(f"|UserTritonKernel roles of {kernel} Test Failed| got {got}, want {want}") @@ -88,19 +88,19 @@ def test_user_triton_kernel(device): y = torch.randn(512) f = torch.compile(lambda x, y: (scale(x, 2.0, 256), scale(y, 3.0, 128)), dynamic=False) ox, oy = f(x.to(device), y.to(device)) - test_result("UserTritonKernel stored through a helper", ox, x * 2.0) - test_result("UserTritonKernel relaunched with other constexprs", oy, y * 3.0) + check_result("UserTritonKernel stored through a helper", ox, x * 2.0) + check_result("UserTritonKernel relaunched with other constexprs", oy, y * 3.0) _check_roles("_scale_kernel", ["in", "inout"]) a, b = torch.randn(512), torch.randn(1024) g = torch.compile(lambda a, b: (add_one(a), add_one(b)), dynamic=False) oa, ob = g(a.to(device), b.to(device)) - test_result("UserTritonKernel relaunched with other extents", oa, a + 1.0) - test_result("UserTritonKernel relaunched with other extents (second)", ob, b + 1.0) + check_result("UserTritonKernel relaunched with other extents", oa, a + 1.0) + check_result("UserTritonKernel relaunched with other extents (second)", ob, b + 1.0) w = torch.randn(128) ow = torch.compile(wrap, dynamic=False)(w.to(device)) - test_result("UserTritonKernel source reaches the compiler as written", ow, + check_result("UserTritonKernel source reaches the compiler as written", ow, w[torch.arange(256) % 128] * 64) diff --git a/tests/ops/misc/test_widen_dtype.py b/tests/ops/misc/test_widen_dtype.py index 9bc110995..5ba0cd5fe 100644 --- a/tests/ops/misc/test_widen_dtype.py +++ b/tests/ops/misc/test_widen_dtype.py @@ -2,7 +2,7 @@ import sys import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def _widen(device, name, src_dtype, dst_dtype, lo, hi): @@ -14,7 +14,7 @@ def _widen(device, name, src_dtype, dst_dtype, lo, hi): fn = lambda a: a.to(dst_dtype) res = torch.compile(dynamic=False)(fn)(a.to(device=device)) out = fn(a) - test_result(name, res, out) + check_result(name, res, out) def test_widen(device): diff --git a/tests/ops/reduce/test_batchnorm.py b/tests/ops/reduce/test_batchnorm.py index 1c34942d4..7d09293d0 100644 --- a/tests/ops/reduce/test_batchnorm.py +++ b/tests/ops/reduce/test_batchnorm.py @@ -2,7 +2,7 @@ import sys import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_BatchNorm(device, size=(1, 16, 64, 64)): torch.manual_seed(0) @@ -17,7 +17,7 @@ def test_BatchNorm(device, size=(1, 16, 64, 64)): y = opt_fn(x1) cpu_model = model.to("cpu") cpu_y = cpu_model(x2) - test_result("BatchNorm Forward", y, cpu_y) + check_result("BatchNorm Forward", y, cpu_y) if __name__ == "__main__": device = torch.device("npu:0") diff --git a/tests/ops/reduce/test_layernorm.py b/tests/ops/reduce/test_layernorm.py index 553ce7e34..ac6c4d4a1 100644 --- a/tests/ops/reduce/test_layernorm.py +++ b/tests/ops/reduce/test_layernorm.py @@ -4,7 +4,7 @@ import torch._dynamo import torch.utils.cpp_extension sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_LayerNorm(device, size=(64, 64)): torch.manual_seed(0) @@ -17,7 +17,7 @@ def test_LayerNorm(device, size=(64, 64)): y = opt_fn(x1) cpu_model = model.to("cpu") cpu_y = cpu_model(x2) - test_result("LayerNorm Forward", y, cpu_y) + check_result("LayerNorm Forward", y, cpu_y) if __name__ == "__main__": import argparse diff --git a/tests/ops/reduce/test_reduce.py b/tests/ops/reduce/test_reduce.py index c829261bd..8ac9b8b50 100644 --- a/tests/ops/reduce/test_reduce.py +++ b/tests/ops/reduce/test_reduce.py @@ -4,7 +4,7 @@ import torch._dynamo import torch.utils.cpp_extension sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_reduce_sum(device, size, dim, keepdim=False): def reduce_sum(a, b, dim, keepdim): @@ -14,7 +14,7 @@ def reduce_sum(a, b, dim, keepdim): opt_fn = torch.compile(dynamic=False)(reduce_sum) res = opt_fn(x, y, dim, keepdim) out = reduce_sum(x.cpu(), y.cpu(), dim, keepdim) - test_result("ReduceSum", res, out) + check_result("ReduceSum", res, out) def test_reduce_sum2(device, size, dim=-1, keepdim=False): def reduce_sum(a, dim, keepdim): @@ -23,7 +23,7 @@ def reduce_sum(a, dim, keepdim): opt_fn = torch.compile(dynamic=False)(reduce_sum) res = opt_fn(x, dim, keepdim) out = reduce_sum(x.cpu(), dim, keepdim) - test_result("ReduceMax", res, out) + check_result("ReduceMax", res, out) def test_reduce_gather_bias(device, NW=4, H=3, Q=32, K=32, T=64): """A reduction fused with an INDIRECT gather bias, as in SwinV2 cosine-window @@ -41,7 +41,7 @@ def fn(score, idx, table): table = torch.randn(T, H).to(device=device) res = torch.compile(dynamic=False)(fn)(score, idx, table) out = fn(score.cpu(), idx.cpu(), table.cpu()) - test_result("ReduceGatherBias", res, out) + check_result("ReduceGatherBias", res, out) if __name__ == "__main__": import argparse diff --git a/tests/ops/reduce/test_softmax.py b/tests/ops/reduce/test_softmax.py index 2e5e64221..ca230bb8e 100644 --- a/tests/ops/reduce/test_softmax.py +++ b/tests/ops/reduce/test_softmax.py @@ -4,7 +4,7 @@ import torch._dynamo import torch.utils.cpp_extension sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_softmax(device, size=(128, 128), dim=1): torch.manual_seed(0) @@ -26,14 +26,14 @@ def test_softmax(device, size=(128, 128), dim=1): #max = opt_fn1(x1) #cpu_max = softmax1(x2) - #test_result("Softmax Max", max, cpu_max) + #check_result("Softmax Max", max, cpu_max) #sum = opt_fn2(x1, max) #cpu_sum = softmax2(x2, cpu_max) - #test_result("Softmax Sum", sum, cpu_sum) + #check_result("Softmax Sum", sum, cpu_sum) #y = opt_fn3(x1, max, sum) #cpu_y = softmax3(x2, cpu_max, cpu_sum) - #test_result("Softmax", y, cpu_y) + #check_result("Softmax", y, cpu_y) class SoftmaxModule(torch.nn.Module): def __init__(self, dim): @@ -47,7 +47,7 @@ def forward(self, x): opt_fn = torch.compile(dynamic=False)(softmax_module) y = opt_fn(x1) cpu_y = torch.nn.functional.softmax(x2, dim=dim) - test_result("Softmax", y, cpu_y) + check_result("Softmax", y, cpu_y) if __name__ == "__main__": import argparse diff --git a/tests/ops/sort/test_sort.py b/tests/ops/sort/test_sort.py index d9b510873..b8c14549a 100644 --- a/tests/ops/sort/test_sort.py +++ b/tests/ops/sort/test_sort.py @@ -3,7 +3,7 @@ import argparse import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_equal(name, out, cpu_out): @@ -33,13 +33,13 @@ def sort_test(x): ref_values, ref_indices = torch.sort(x, stable=stable, dim=dim, descending=descending) prefix = "Sort.stable" if stable else "Sort.unstable" - test_result(f"{prefix}/values size={size}, dim={dim}, desc={descending}", out_values, ref_values) + check_result(f"{prefix}/values size={size}, dim={dim}, desc={descending}", out_values, ref_values) if stable: - test_result(f"{prefix}/indices size={size}, dim={dim}, desc={descending}", out_indices, ref_indices) + check_result(f"{prefix}/indices size={size}, dim={dim}, desc={descending}", out_indices, ref_indices) else: # Unstable sort does not guarantee tie ordering; validate index-value consistency instead. gathered = torch.gather(x, dim, out_indices.cpu()) - test_result(f"{prefix}/indices_gather size={size}, dim={dim}, desc={descending}", gathered, out_values.cpu()) + check_result(f"{prefix}/indices_gather size={size}, dim={dim}, desc={descending}", gathered, out_values.cpu()) def test_sort_stable_suite(device): @@ -83,7 +83,7 @@ def sort_test(inp): ref_values, ref_indices = torch.sort( x, dim=case["dim"], descending=case["descending"], stable=True ) - test_result(f"Sort.dup/stable_values {case}", out_values, ref_values) + check_result(f"Sort.dup/stable_values {case}", out_values, ref_values) test_equal(f"Sort.dup/stable_indices {case}", out_indices, ref_indices) def sort_test_unstable(inp): @@ -91,9 +91,9 @@ def sort_test_unstable(inp): out_values_u, out_indices_u = torch.compile(dynamic=False)(sort_test_unstable)(x.to(device=device)) ref_values_u, _ = torch.sort(x, dim=case["dim"], descending=case["descending"], stable=False) - test_result(f"Sort.dup/unstable_values {case}", out_values_u, ref_values_u) + check_result(f"Sort.dup/unstable_values {case}", out_values_u, ref_values_u) gathered_u = torch.gather(x, case["dim"], out_indices_u.cpu()) - test_result(f"Sort.dup/unstable_gather {case}", gathered_u, out_values_u.cpu()) + check_result(f"Sort.dup/unstable_gather {case}", gathered_u, out_values_u.cpu()) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run sort tests") diff --git a/tests/ops/sort/test_topk.py b/tests/ops/sort/test_topk.py index ba75b7bfb..aa07268e9 100644 --- a/tests/ops/sort/test_topk.py +++ b/tests/ops/sort/test_topk.py @@ -49,7 +49,7 @@ def _ref(x, k, dim, largest): def _routed(): - from pytorchsim.frontend import topk + from pytorchsim.frontend.dispatcher import topk return topk.ROUTED diff --git a/tests/ops/view/test_transpose2D.py b/tests/ops/view/test_transpose2D.py index dd83e9ed3..6afbef55a 100644 --- a/tests/ops/view/test_transpose2D.py +++ b/tests/ops/view/test_transpose2D.py @@ -2,7 +2,7 @@ import sys import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_Transpose2D(device, size=(16, 32)): def transpose(a): @@ -13,7 +13,7 @@ def transpose(a): opt_fn = torch.compile(dynamic=False)(transpose) res = opt_fn(x) out = transpose(x.cpu()) - test_result("Transpose Forward", res, out) + check_result("Transpose Forward", res, out) def test_Transpose2D_2(device, size=(16, 32)): def transpose(a, b): @@ -26,7 +26,7 @@ def transpose(a, b): opt_fn = torch.compile(dynamic=False)(transpose) res = opt_fn(x, y) out = transpose(x.cpu(), y.cpu()) - test_result("Transpose2 Forward", res, out) + check_result("Transpose2 Forward", res, out) if __name__ == "__main__": device = torch.device("npu:0") diff --git a/tests/ops/view/test_transpose3D.py b/tests/ops/view/test_transpose3D.py index f121c7135..e0d00a2ba 100644 --- a/tests/ops/view/test_transpose3D.py +++ b/tests/ops/view/test_transpose3D.py @@ -2,7 +2,7 @@ import sys import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_Transpose3D_1(device, size=(4, 16, 32)): def transpose(a, b): @@ -15,7 +15,7 @@ def transpose(a, b): opt_fn = torch.compile(dynamic=False)(transpose) res = opt_fn(x, y) out = transpose(x.cpu(), y.cpu()) - test_result("Transpose 3D Forward", res, out) + check_result("Transpose 3D Forward", res, out) def test_Transpose3D_2(device, size=(4, 16, 32)): def transpose(a, b): @@ -28,7 +28,7 @@ def transpose(a, b): opt_fn = torch.compile(dynamic=False)(transpose) res = opt_fn(x, y) out = transpose(x.cpu(), y.cpu()) - test_result("Transpose 3D Forward", res, out) + check_result("Transpose 3D Forward", res, out) def test_Transpose3D_3(device, size=(4, 16, 32)): def transpose(a, b): @@ -41,7 +41,7 @@ def transpose(a, b): opt_fn = torch.compile(dynamic=False)(transpose) res = opt_fn(x, y) out = transpose(x.cpu(), y.cpu()) - test_result("Transpose 3D Forward", res, out) + check_result("Transpose 3D Forward", res, out) if __name__ == "__main__": device = torch.device("npu:0") diff --git a/tests/ops/view/test_view3D_2D.py b/tests/ops/view/test_view3D_2D.py index b6e5ffffa..c2cfbc51d 100644 --- a/tests/ops/view/test_view3D_2D.py +++ b/tests/ops/view/test_view3D_2D.py @@ -2,7 +2,7 @@ import sys import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result def test_view3D_2D(device, size=(16, 8, 16), t_x=0, t_y=1): def view3D_2D(a): @@ -13,7 +13,7 @@ def view3D_2D(a): opt_fn = torch.compile(dynamic=False)(view3D_2D) res = opt_fn(input) out = view3D_2D(cpu_input) - test_result("view 3D->2D", res, out) + check_result("view 3D->2D", res, out) def test_view2D_3D(device, size=(512, 768), h=12, d_k=64): def view2D_3D(a): @@ -24,7 +24,7 @@ def view2D_3D(a): opt_fn = torch.compile(dynamic=False)(view2D_3D) res = opt_fn(input) out = view2D_3D(cpu_input) - test_result("view 2D->3D", res, out) + check_result("view 2D->3D", res, out) if __name__ == "__main__": device = torch.device("npu:0") diff --git a/tests/_pytorchsim_utils.py b/tests/result_check.py similarity index 81% rename from tests/_pytorchsim_utils.py rename to tests/result_check.py index 923f4bb72..b1770a6ad 100644 --- a/tests/_pytorchsim_utils.py +++ b/tests/result_check.py @@ -1,4 +1,5 @@ -"""Shared helpers for PyTorchSim test files. +"""The result check PyTorchSim test files share: check_result compares an npu result to its CPU +reference and prints the line the CI sweep reads. Module name is unique (not ``tests._utils``) because ``ultralytics`` ships a top-level ``tests`` package in site-packages that would shadow it. @@ -8,7 +9,7 @@ import os, sys sys.path.insert(0, os.path.join( os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) - from _pytorchsim_utils import test_result + from result_check import check_result """ import sys @@ -16,7 +17,7 @@ import torch -def test_result(name, out, expected, rtol=1e-4, atol=1e-4): +def check_result(name, out, expected, rtol=1e-4, atol=1e-4): """Compare ``out`` to ``expected``; exit 1 on mismatch.""" out_cpu = out.cpu() if hasattr(out, "cpu") else out expected_cpu = expected.cpu() if hasattr(expected, "cpu") else expected diff --git a/tests/system/test_artifact_scripts.py b/tests/system/test_artifact_scripts.py index 86e57ebed..6c08534db 100644 --- a/tests/system/test_artifact_scripts.py +++ b/tests/system/test_artifact_scripts.py @@ -9,7 +9,7 @@ REPO = os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim") CYCLE = os.path.join(REPO, "experiments/artifact/cycle_validation/run_cycle.sh") ILS = "experiments/artifact/speedup/scripts/run_speed_ils_matmul.sh" -RESOLVE = ("import torch; from pytorchsim.driver import compiler_bridge; " +RESOLVE = ("import torch; from pytorchsim.backend import compiler_bridge; " "print(compiler_bridge.target().file)") diff --git a/tests/system/test_attribute_sources.py b/tests/system/test_attribute_sources.py index 0a8c030d2..5f5f03639 100644 --- a/tests/system/test_attribute_sources.py +++ b/tests/system/test_attribute_sources.py @@ -13,7 +13,7 @@ import torch # noqa: E402 the npu backend loads pytorchsim whole, before its parts are imported from pytorchsim import contract # noqa: E402 -from pytorchsim.driver import compiler_input # noqa: E402 +from pytorchsim.backend import compiler_input # noqa: E402 META = {"kernel_name": "k", "signature": {"ids_ptr": "*i32", "x_ptr": "*bf16", "o_ptr": "*bf16", "B": "constexpr"}, "constants": {"B": 4}, "numels": {}, "template_grid": [1, 1, 1], "user_defined": True, diff --git a/tests/system/test_cache_identity.py b/tests/system/test_cache_identity.py index e00879063..5b9aa4b38 100644 --- a/tests/system/test_cache_identity.py +++ b/tests/system/test_cache_identity.py @@ -11,7 +11,7 @@ import torch # noqa: F401,E402 the npu backend loads pytorchsim whole, before its parts are imported from pytorchsim import config # noqa: E402 -from pytorchsim.driver import codecache, compiler_bridge # noqa: E402 +from pytorchsim.backend import codecache, compiler_bridge # noqa: E402 def _ask_compiler(expr): diff --git a/tests/system/test_compiler_failure.py b/tests/system/test_compiler_failure.py index 0fe5bb0c3..61e3ba49e 100644 --- a/tests/system/test_compiler_failure.py +++ b/tests/system/test_compiler_failure.py @@ -8,7 +8,7 @@ sys.path.insert(0, os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim")) import torch # noqa: F401 the npu backend loads pytorchsim whole, before its parts are imported -from pytorchsim.driver import autotune, compiler_bridge +from pytorchsim.backend import autotune, compiler_bridge def _failed(spec_path): diff --git a/tests/system/test_eager.py b/tests/system/test_eager.py index 3a0bb1ba3..274f22fbe 100644 --- a/tests/system/test_eager.py +++ b/tests/system/test_eager.py @@ -4,7 +4,7 @@ import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result torch.npu.register_eager_to_compile(["aten::mul.Tensor", "aten::add.Tensor"]) @@ -16,4 +16,4 @@ y = y_cpu.to(device) z = x * y z = x + z - test_result("Eager mul + add", z, x_cpu + x_cpu * y_cpu) + check_result("Eager mul + add", z, x_cpu + x_cpu * y_cpu) diff --git a/tests/system/test_patch_scope.py b/tests/system/test_patch_scope.py index ff205efc7..0871fe12c 100644 --- a/tests/system/test_patch_scope.py +++ b/tests/system/test_patch_scope.py @@ -6,7 +6,7 @@ import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result from torch._dynamo.testing import rand_strided from torch._dynamo.utils import preserve_rng_state @@ -23,7 +23,7 @@ def test_reduction_split_is_upstream_off_device(): device, r, n, True) for r, n in shapes] upstream = [InductorChoices().reduction_split_factor( device, r, n, True) for r, n in shapes] - test_result("ReductionSplitOffDevice", torch.tensor(ours), + check_result("ReductionSplitOffDevice", torch.tensor(ours), torch.tensor(upstream)) @@ -34,7 +34,7 @@ def test_benchmark_operand_is_upstream_off_device(): with preserve_rng_state(): upstream = rand_strided((64,), (1,), device="cpu", dtype=torch.float32, extra_size=0) - test_result("BenchmarkOperandOffDevice", ours, upstream) + check_result("BenchmarkOperandOffDevice", ours, upstream) def test_device_predicate_reads_every_spelling(): @@ -43,12 +43,12 @@ def test_device_predicate_reads_every_spelling(): A predicate that answers only torch.device sends the string form to upstream, whose operand is sampled -- one silent CPU fallback per call. """ - from pytorchsim.frontend.inductor_patches import _is_npu + from pytorchsim.frontend.inductor.registration import is_npu spellings = ("npu", "npu:0", torch.device("npu"), torch.device("npu:0"), "cpu", "cuda", torch.device("cpu"), None) - got = torch.tensor([_is_npu(d) for d in spellings]) - test_result("DevicePredicateSpellings", got, + got = torch.tensor([is_npu(d) for d in spellings]) + check_result("DevicePredicateSpellings", got, torch.tensor([True, True, True, True, False, False, False, False])) @@ -63,7 +63,7 @@ def test_conv_grid_is_upstream_off_device(): meta = {"BLOCK_M": 64, "BLOCK_N": 128, "GROUPS": 4} got = torch.tensor(list(conv_kernel.conv2d_grid(2, 256, 8, 8, meta)) + list(conv_kernel.conv3d_grid(2, 256, 4, 8, 8, meta))) - test_result("ConvGridOffDevice", got, torch.tensor([2, 2, 4, 8, 2, 4])) + check_result("ConvGridOffDevice", got, torch.tensor([2, 2, 4, 8, 2, 4])) def test_this_device_still_gets_its_own_answers(): @@ -73,7 +73,7 @@ def test_this_device_still_gets_its_own_answers(): operand = AlgorithmSelectorCache.generate_example_value( (64,), (1,), "npu", torch.float32, 0) got = torch.tensor([split, operand.numel(), operand.device.type == "npu"]) - test_result("OnDeviceAnswersKept", got, torch.tensor([1, 64, True])) + check_result("OnDeviceAnswersKept", got, torch.tensor([1, 64, True])) def test_triton_presence_is_upstream(): @@ -89,7 +89,7 @@ def test_triton_presence_is_upstream(): got = torch.tensor([triton_utils.has_triton(), hasattr(triton_utils.has_triton, "cache_info"), triton_utils.triton_hash_with_backend() == want]) - test_result("TritonPresenceUpstream", got, torch.tensor([True, True, True])) + check_result("TritonPresenceUpstream", got, torch.tensor([True, True, True])) def test_conv_heuristics_are_upstream_outside_npu_choices(): @@ -106,7 +106,7 @@ def block_n(heuristic): upstream = block_n(BaseConfigHeuristic()) got = [block_n(InductorChoices().get_config_heuristics("npu")) == upstream, block_n(config.inductor_choices_class().get_config_heuristics("npu")) == [lanes]] - test_result("ConvHeuristicsScoped", torch.tensor(got), torch.tensor([True, True])) + check_result("ConvHeuristicsScoped", torch.tensor(got), torch.tensor([True, True])) _SDP_PROBE = """ @@ -132,7 +132,7 @@ def test_sdpa_flags_are_upstream(): b = torch.backends.cuda ours = [b.flash_sdp_enabled(), b.mem_efficient_sdp_enabled(), b.math_sdp_enabled(), torch._C._get_overrideable_sdp_enabled(), torch._fused_sdp_choice(q, q, q)] - test_result("SdpaFlagsUpstream", torch.tensor([int(x) for x in ours]), + check_result("SdpaFlagsUpstream", torch.tensor([int(x) for x in ours]), torch.tensor([int(x) for x in upstream])) diff --git a/tests/system/test_reduction_tiling.py b/tests/system/test_reduction_tiling.py index 592d959ba..3fa807534 100644 --- a/tests/system/test_reduction_tiling.py +++ b/tests/system/test_reduction_tiling.py @@ -7,9 +7,9 @@ import torch sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="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/workspace/PyTorchSim"), "tests")) -from _pytorchsim_utils import test_result +from result_check import check_result -from pytorchsim.codegen import tiling +from pytorchsim.frontend.inductor.codegen import tiling LANES, LANE_BYTES = 128, 1 << 20 @@ -25,7 +25,7 @@ def test_gemv_blocks_follow_the_contiguous_kept_axis(): (3072, 8192): (1024, 2048), (5120, 8192): (1024, 2048), (768, 768): (256, 1024), (384, 384): (128, 512), (1000, 4096): (1024, 2048)} got = {k: _blocks(*k) for k in want} - test_result("GemvBlocks", torch.tensor(list(got.values())), torch.tensor(list(want.values()))) + check_result("GemvBlocks", torch.tensor(list(got.values())), torch.tensor(list(want.values()))) def test_lane_cover_and_budget_are_never_crossed(): @@ -37,7 +37,7 @@ def test_lane_cover_and_budget_are_never_crossed(): xb, rb = _blocks(x, r) if xb < min(LANES, 1 << (x - 1).bit_length()) or xb * rb > LANES * per_lane: bad.append((x, r, xb, rb)) - test_result("BlocksWithinBudget", torch.tensor(len(bad)), torch.tensor(0)) + check_result("BlocksWithinBudget", torch.tensor(len(bad)), torch.tensor(0)) def test_kept_axis_is_the_unit_stride_axis_of_the_largest_read(): @@ -47,7 +47,7 @@ def test_kept_axis_is_the_unit_stride_axis_of_the_largest_read(): from torch._inductor.dependencies import MemoryDep from torch._inductor.sizevars import SizeVarAllocator from torch._inductor.virtualized import V - from pytorchsim.frontend.inductor_patches import _kept_axis_contiguous + from pytorchsim.frontend.inductor.choices import _kept_axis_contiguous c0, c1 = sympy.symbols("c0 c1", integer=True, nonnegative=True) graph = type("G", (), {"sizevars": SizeVarAllocator(), "get_dtype": lambda self, n: torch.bfloat16})() @@ -61,7 +61,7 @@ def feats(n, reads, red=True): with V.set_graph_handler(graph): got = [_kept_axis_contiguous(feats(4096, gemv(4096))), _kept_axis_contiguous(feats(24576, gemv(24576))), _kept_axis_contiguous(feats(8192, rows)), _kept_axis_contiguous(feats(4096, gemv(4096), red=False))] - test_result("KeptAxisFromStrides", torch.tensor([g == "x" for g in got]), + check_result("KeptAxisFromStrides", torch.tensor([g == "x" for g in got]), torch.tensor([True, True, False, False])) @@ -74,7 +74,7 @@ def test_row_reduction_rows_fill_the_tile_budget(): (128, 4096): (128, 4096), (1, 4096): (1, 4096)} got = {k: tuple(tiling.fixed_config_for(kernel, {"xnumel": k[0], "r0_numel": k[1]}, args)[b] for b in ("XBLOCK", "R0_BLOCK")) for k in cases} - test_result("RowReductionRows", torch.tensor(list(got.values())), torch.tensor(list(cases.values()))) + check_result("RowReductionRows", torch.tensor(list(got.values())), torch.tensor(list(cases.values()))) def test_other_reductions_keep_todays_blocks(): @@ -84,7 +84,7 @@ def test_other_reductions_keep_todays_blocks(): args = [{"dtype": "float32"}] base = tiling.fixed_config_for(kernel, numels, args) same = [tiling.fixed_config_for(kernel, numels, args, contiguous=c) == base for c in (None, "r")] - test_result("RowReductionUnchanged", torch.tensor(same), torch.tensor([True, True])) + check_result("RowReductionUnchanged", torch.tensor(same), torch.tensor([True, True])) def test_few_rows_budget_the_reduced_axis_over_every_lane(): @@ -101,7 +101,7 @@ def test_few_rows_budget_the_reduced_axis_over_every_lane(): ({"xnumel": 4096, "r0_numel": 1024}, tiling.fixed_config_for(kernel, {"xnumel": 4096, "r0_numel": 1024}, args)["R0_BLOCK"])] got = [tiling.fixed_config_for(kernel, n, args)["R0_BLOCK"] for n, _ in cases] - test_result("FewRowsLaneBlocks", torch.tensor(got), torch.tensor([w for _, w in cases])) + check_result("FewRowsLaneBlocks", torch.tensor(got), torch.tensor([w for _, w in cases])) if __name__ == "__main__": diff --git a/tests/system/test_select.py b/tests/system/test_select.py index 54df84ff1..ae180367f 100644 --- a/tests/system/test_select.py +++ b/tests/system/test_select.py @@ -15,7 +15,7 @@ import torch # noqa: E402 the npu backend loads pytorchsim whole, before its parts are imported from torch._inductor.select_algorithm import TritonTemplateCaller # noqa: E402 -from pytorchsim.driver import select # noqa: E402 +from pytorchsim.backend import select # noqa: E402 SHAPE = (128, 256, 256) @@ -24,8 +24,8 @@ CHILD = r""" import json, os, sys import torch -from pytorchsim.codegen.inductor_hooks import TritonNPUScheduling -from pytorchsim.driver import select +from pytorchsim.frontend.inductor.codegen.scheduling import TritonNPUScheduling +from pytorchsim.backend import select select.RECORD_DIR = os.environ["SELECT_RECORD_DIR"] timed = {"choices": [], "modules": []} @@ -94,7 +94,7 @@ def _picks(dump): def _merge(root, dump): """scripts/selection_merge.py over a timed run's picks, into the record under `root`.""" script = os.path.join(TORCHSIM_DIR, "scripts", "selection_merge.py") - code = (f"import runpy, sys, torch; from pytorchsim.driver import select; " + code = (f"import runpy, sys, torch; from pytorchsim.backend import select; " f"select.RECORD_DIR = {os.path.join(root, 'record')!r}; " f"sys.argv = [{script!r}, {os.path.join(dump, select.RECORD_LOG)!r}]; " f"runpy.run_path({script!r}, run_name='__main__')") diff --git a/tests/system/test_tuned_blocks_on_hit.py b/tests/system/test_tuned_blocks_on_hit.py index a5d9036b0..3f966d071 100644 --- a/tests/system/test_tuned_blocks_on_hit.py +++ b/tests/system/test_tuned_blocks_on_hit.py @@ -11,7 +11,7 @@ import torch # noqa: F401,E402 the npu backend loads pytorchsim whole, before its parts are imported from pytorchsim import contract # noqa: E402 -from pytorchsim.driver import codecache # noqa: E402 +from pytorchsim.backend import codecache # noqa: E402 from pytorchsim.simulator import timing # noqa: E402 SRC = "def kernel(): pass\n"