diff --git a/.github/workflows/pytorchsim_test.yml b/.github/workflows/pytorchsim_test.yml index 345c716e..0c6b8f93 100644 --- a/.github/workflows/pytorchsim_test.yml +++ b/.github/workflows/pytorchsim_test.yml @@ -18,8 +18,10 @@ on: # Runner policy: the CPU-only CI image is small enough to pull on GitHub-hosted # runners, so op and model tests run on ubuntu-latest. The memory/time-intensive -# jobs stay on self-hosted: test_deepseek (largest model), test_diffusion (UNet2D -# simulation OOMs the hosted runner), and test_accuracy (accuracy + speedup). +# jobs stay on self-hosted: test_deepseek (largest model), test_swinv2 (SwinV2 +# shifted-window backbone), test_clip (CLIP vision backbone), test_convnextv2 +# (ConvNeXt V2 backbone), test_diffusion (UNet2D simulation OOMs the hosted +# runner), and test_accuracy (accuracy + speedup). jobs: test_add: name: Run test_add.py @@ -57,6 +59,24 @@ jobs: -e TOGSIM_CONFIG="${{ inputs.togsim_config }}" \ ${{ inputs.image_name }} python3 PyTorchSim/tests/ops/elementwise/test_transcendental.py + test_pointwise: + name: Run test_pointwise.py + runs-on: ubuntu-latest + steps: + - name: Log in to GitHub Container Registry + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Run test_pointwise.py + run: | + echo "Running test_pointwise.py" + docker run --rm \ + -e TOGSIM_CONFIG="${{ inputs.togsim_config }}" \ + ${{ inputs.image_name }} python3 PyTorchSim/tests/ops/elementwise/test_pointwise.py + test_activation: name: Run test_activation.py runs-on: ubuntu-latest @@ -633,6 +653,24 @@ jobs: -e TOGSIM_CONFIG="${{ inputs.togsim_config }}" \ ${{ inputs.image_name }} python3 PyTorchSim/tests/ops/misc/test_indirect_access.py + test_masked_nondividing: + name: Run test_masked_nondividing + runs-on: ubuntu-latest + steps: + - name: Log in to GitHub Container Registry + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Run test_masked_nondividing.py + run: | + echo "Running test_masked_nondividing.py" + docker run --rm \ + -e TOGSIM_CONFIG="${{ inputs.togsim_config }}" \ + ${{ inputs.image_name }} python3 PyTorchSim/tests/ops/misc/test_masked_nondividing.py + test_scheduler: name: Run test_scheduler runs-on: ubuntu-latest @@ -707,6 +745,66 @@ jobs: -e TOGSIM_CONFIG="${{ inputs.togsim_config }}" \ ${{ inputs.image_name }} python3 PyTorchSim/tests/models/DeepSeek/test_deepseek_v3_base.py + test_swinv2: + name: Run test_swinv2.py + # SwinV2 backbone (shifted-window attention) is heavy; keep it on a + # self-hosted runner like the other model tests. + runs-on: self-hosted + steps: + - name: Log in to GitHub Container Registry + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Run test_swinv2.py + run: | + echo "Running test_swinv2.py" + docker run --rm \ + -e TOGSIM_CONFIG="${{ inputs.togsim_config }}" \ + ${{ inputs.image_name }} python3 PyTorchSim/tests/models/test_swinv2.py + + test_clip: + name: Run test_clip.py + # CLIP vision backbone; keep it on a self-hosted runner like the other + # model tests (the 32x32 patch conv expands to many tiles at small arrays). + runs-on: self-hosted + steps: + - name: Log in to GitHub Container Registry + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Run test_clip.py + run: | + echo "Running test_clip.py" + docker run --rm \ + -e TOGSIM_CONFIG="${{ inputs.togsim_config }}" \ + ${{ inputs.image_name }} python3 PyTorchSim/tests/models/test_clip.py + + test_convnextv2: + name: Run test_convnextv2.py + # ConvNeXt V2 backbone; keep it on a self-hosted runner like the other model + # tests (the depthwise 7x7 conv lowers to one gather kernel per tap). + runs-on: self-hosted + steps: + - name: Log in to GitHub Container Registry + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Run test_convnextv2.py + run: | + echo "Running test_convnextv2.py" + docker run --rm \ + -e TOGSIM_CONFIG="${{ inputs.togsim_config }}" \ + ${{ inputs.image_name }} python3 PyTorchSim/tests/models/test_convnextv2.py + test_eager: name: Run test_eager.py runs-on: ubuntu-latest diff --git a/AsmParser/tog_generator.py b/AsmParser/tog_generator.py index a12460e3..0de76246 100644 --- a/AsmParser/tog_generator.py +++ b/AsmParser/tog_generator.py @@ -1,3 +1,9 @@ +# DEPRECATED (timing path): legacy ONNX Tile-Operation-Graph producer. Builds +# the TOG and serializes it to ONNX for the C++ TileGraphParser. Superseded by +# the C++ trace pipeline (PyTorchSimFrontend/mlir/passes/build_skeleton.py + +# lower_to_emitc.py + cycle_table.py -> a compiled trace .so). Kept live so the +# current pipeline does not break; to be retired once the trace pipeline (P3+) +# stabilizes. See docs/design/togsim_cpp_trace.md. import os import sys import importlib.util diff --git a/CLAUDE.md b/CLAUDE.md index 12d48082..5975ee60 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -21,7 +21,7 @@ The pipeline runs in that order on every `torch.compile` invocation; you'll see | `Simulator/simulator.py` | Python drivers: `FunctionalSimulator` (Spike), `CycleSimulator` (Gem5), `TOGSimulator` (the cycle-accurate one + multi-tenant context manager) | | `Scheduler/scheduler.py` | Poisson arrival generator + scheduling utilities for multi-tenant runs | | `TOGSim/` | C++ TOGSim source. `src/Simulator.cc`, `Core.cc`, `Dram.cc`, `Interconnect.cc`, `L2Cache.cc`, `Tile.cc`, `TileGraph.cc` are the core models. Externals: ramulator2, booksim, stonneCore, onnx, protobuf, spdlog, yaml-cpp | -| `AsmParser/` | `tog_generator.py`, `onnx_utility.py` — TOG generation from ONNX/ASM | +| `AsmParser/` | `tog_generator.py`, `onnx_utility.py` — legacy ONNX TOG generation; now used only by the STONNE sparse path (the main path emits a C++ `trace.so` instead) | | `configs/` | TOGSim hardware configs (YAML). The default is `systolic_ws_128x128_c1_simple_noc_tpuv3.yml`. Naming pattern: `systolic_ws__c__.yml` | | `tests/` | Op- and model-level tests organized under `ops//` (elementwise, reduce, gemm, conv, attention, view, sort, sparsity, 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/` (scheduler, eager, hetro, stonne, vectorops). Shared helper: `tests/_utils.py` | | `experiments/artifact/` | Paper reproduction scripts (`cycle_validation/run_cycle.sh`, `speedup/run_speedup.sh`) | @@ -58,6 +58,12 @@ export TORCHSIM_DUMP_MLIR_IR=1 export TORCHSIM_DUMP_LLVM_IR=1 ``` +**To find which op a wrong result first diverges at** (per-kernel CPU cross-check; +sub-option of functional mode). Set `pytorchsim_functional_verify_per_kernel: 1` +in the config YAML, 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. See `docs/per-kernel-functional-verify.md`. + ## Key environment variables Read in `PyTorchSimFrontend/extension_config.py`: @@ -85,11 +91,13 @@ Note: `TOGSIM_CONFIG` is **overwritten** while inside a `with TOGSimulator(confi Located under `configs/*.yml`: - `num_cores`, `core_freq_mhz`, `num_systolic_array_per_core` +- `sa_weight_buffer_depth` (per-SA resident weight slots; **must be > 0** — the simulator errors on 0. Raise it to effectively disable the preload run-ahead throttle. Defaults to 2 if the key is absent.) - `vpu_num_lanes`, `vpu_spad_size_kb_per_lane`, `vpu_vector_length_bits` - `dram_type` (`ramulator2` | `simple`), `dram_channels`, `dram_freq_mhz`, `ramulator_config_path` - `icnt_type` (`simple` | `booksim`), `icnt_latency_cycles`, `icnt_freq_mhz`, `icnt_config_path` - `l2d_type` (e.g., `datacache`), `l2d_config` (AccelSim-format cache config string) - `pytorchsim_functional_mode` (Spike on/off), `pytorchsim_timing_mode` +- `pytorchsim_functional_verify_per_kernel` (debug: per-kernel CPU cross-check; see `docs/per-kernel-functional-verify.md`) - `codegen_mapping_strategy`: `heuristic` | `autotune` | `external-then-heuristic` | `external-then-autotune` - `codegen_external_mapping_file` (key `"M_N_K"` → `{TILE_M, TILE_K, TILE_N}` JSON) - `codegen_compiler_optimization`: `"all"` | `"none"` | a list from `{fusion, reduction_epilogue, reduction_reduction, prologue, single_batch_conv, multi_tile_conv, subtile}` @@ -122,7 +130,7 @@ Conan deps for TOGSim: `boost/1.79.0`, `robin-hood-hashing/3.11.5`, `spdlog/1.11 - **Adding a new op (Inductor lowering):** `PyTorchSimFrontend/mlir/mlir_ops.py`, `mlir_lowering.py`, plus a new `mlir__template.py` if it needs its own MLIR template. Decomposition rules: `mlir_decomposition.py`. Scheduling: `mlir_scheduling.py`. Autotune: `mlir_autotune.py`. - **Adding a PyTorch device op:** `PyTorchSimDevice/csrc/aten/native/*` (Minimal/Extra split mirrors `torch_openreg`). - **TOGSim hardware model changes:** `TOGSim/src/{Core,Dram,Interconnect,L2Cache,Tile,TileGraph}.cc` + matching `include/*.h`. -- **TOG generation:** `AsmParser/tog_generator.py` builds the raw graph and serializes it via `AsmParser/onnx_utility.py` to **ONNX, which is the on-disk TOG format** consumed by TOGSim. +- **TOG generation:** the main path compiles each kernel to a C++ **`trace.so`** (`mlir/passes/build_skeleton.py` + `lower_to_emitc.py`) plus a `trace_cycles.tsv` cycle table, which TOGSim turns into a TileGraph via `trace_to_tilegraph`. `AsmParser/tog_generator.py` + `onnx_utility.py` (the legacy ONNX TOG) remain only for the **STONNE sparse path** (`extension_op.py`). - **Eager fallback registration:** `torch.npu.register_eager_to_compile([...])` — see `tests/system/test_eager.py`. - **Per-run results:** `togsim_results/>.log` (stats) and `.trace` (instruction trace). The path is also printed at the end of every run. - **Wrapper codegen path:** printed as `Wrapper Codegen Path = /tmp/torchinductor_//...py` — useful for inspecting generated kernel code and tensor names for `SRAM_BUFFER_PLAN_PATH`. diff --git a/PyTorchSimFrontend/extension_codecache.py b/PyTorchSimFrontend/extension_codecache.py index 492133a3..a9cd8ff3 100644 --- a/PyTorchSimFrontend/extension_codecache.py +++ b/PyTorchSimFrontend/extension_codecache.py @@ -5,9 +5,8 @@ import torch from PyTorchSimFrontend import extension_config -from torch._inductor.codecache import get_hash, write +from torch._inductor.codecache import get_hash, write, write_atomic from torch._inductor.async_compile import AsyncCompile -from AsmParser.tog_generator import tog_generator from PyTorchSimFrontend.mlir.mlir_caller_codegen import MLIRKernelCallerCodeGen from Simulator.simulator import FunctionalSimulator, CycleSimulator, TOGSimulator @@ -23,6 +22,13 @@ def get_write_path(src_code): return os.path.join(extension_config.get_dump_path(), hash_prefix(get_hash(src_code.strip()))) +_HEADER_BY_HASH = {} +def store_header(src_code, spike_header, gem5_header): + _HEADER_BY_HASH[get_hash(src_code.strip())] = (spike_header, gem5_header) +def get_header(src_code): + return _HEADER_BY_HASH.get(get_hash(src_code.strip())) + + def get_lock_path(write_path): """Return lock file path for the given write_path (per-source_code lock).""" return os.path.join(write_path, ".compile.lock") @@ -45,7 +51,7 @@ def mlir_compile_command(filename, vectorlane_size, vlen=256): return [re.sub(r"[ \n]+", " ", f""" {extension_config.CONFIG_TORCHSIM_LLVM_PATH}/mlir-opt \ - -test-loop-padding \ + -test-loop-padding --allow-unregistered-dialect \ {'--mlir-print-ir-after-all' if extension_config.CONFIG_TORCHSIM_DUMP_MLIR_IR else ''} \ {filename}.mlir -o {filename}_padded.mlir """, @@ -74,13 +80,13 @@ def mlir_compile_command(filename, vectorlane_size, vlen=256): """, ).strip()] -def mlir_gem5_compile_command(filename, sample_filename, tog_file, vectorlane_size, vlen=256): +def mlir_gem5_compile_command(filename, sample_filename, vectorlane_size, vlen=256): # See mlir_compile_command: -dma-fine-grained and -test-pytorchsim-to-vcix are # Python passes run in-process; mlir-opt runs only loop-padding here. return [re.sub(r"[ \n]+", " ", f""" {extension_config.CONFIG_TORCHSIM_LLVM_PATH}/mlir-opt \ - -test-loop-padding='timing_mode=1' \ + -test-loop-padding='timing_mode=1' --allow-unregistered-dialect \ {'--mlir-print-ir-after-all' if extension_config.CONFIG_TORCHSIM_DUMP_MLIR_IR else ''} \ {filename}.mlir -o {sample_filename}_padded.mlir """, @@ -128,32 +134,48 @@ def load(cls, source_code, vlen = kwargs['vlen'] vlenb = vlen // 8 write_path = get_write_path(source_code) - key, input_path = write(source_code, "mlir", specified_dir=write_path) - # Run the Python out-of-line MLIR passes (MLIR bindings) on the kernel - # .mlir in place, before mlir-opt. Currently lowers torchsim.vlane_idx - # (replaces the old C++ -global-idx pass); add more in passes/__init__.py. + os.makedirs(write_path, exist_ok=True) + global_var_header = kwargs.get("global_var_header") + if global_var_header is not None: + write_atomic(os.path.join(write_path, "global_var.h"), global_var_header) + gem5_global_var_header = kwargs.get("gem5_global_var_header") + if gem5_global_var_header is not None: + write_atomic(os.path.join(write_path, "gem5_global_var.h"), gem5_global_var_header) + # The compile rewrites the kernel .mlir in place (run_python_passes) and reads + # it back (mlir-opt). Two compiles of the same source -- the autotune's chosen + # candidate and the final kernel -- share a write_path, so hold the per-path + # lock across the whole build to keep them from interleaving, and skip the + # rebuild when a prior build already finished (its trace.so exists). + from filelock import FileLock from PyTorchSimFrontend.mlir.passes import ( run_python_passes, run_module_passes, POST_OPT_PASSES, run_standard_lowering, run_tog, ) - run_python_passes(input_path, vectorlane=vectorlane_size) - new_input_path = os.path.splitext(input_path)[0] - raw_tog_path = new_input_path + "_tog.py" - tog_path = os.path.join(write_path, "tile_graph.onnx") - sample_mlir_path = new_input_path + "_sample" - validation_binary_path = os.path.join(write_path, validation_binary_name) - gem5_cmds = mlir_gem5_compile_command(new_input_path, sample_mlir_path, raw_tog_path, vectorlane_size) - - from filelock import FileLock - os.makedirs(write_path, exist_ok=True) + trace_so_path = os.path.join(write_path, "trace.so") lock = FileLock(get_lock_path(write_path), timeout=LOCK_TIMEOUT) - - if spad_info is not None: - link_option = f"-Wl,--section-start=.spad=0x{spad_info['spad_vaddr']:x}" - else: - link_option = "" - # Generate LLVM kernel calller and binary for validation - if extension_config.pytorchsim_functional_mode: + with lock: + key, input_path = write(source_code, "mlir", specified_dir=write_path) + if os.path.isfile(trace_so_path): + return key + # Run the Python out-of-line MLIR passes (MLIR bindings) on the kernel + # .mlir in place, before mlir-opt. Currently lowers torchsim.vlane_idx + # (replaces the old C++ -global-idx pass); add more in passes/__init__.py. + run_python_passes(input_path, vectorlane=vectorlane_size) + new_input_path = os.path.splitext(input_path)[0] + raw_tog_path = new_input_path + "_tog.py" + sample_mlir_path = new_input_path + "_sample" + validation_binary_path = os.path.join(write_path, validation_binary_name) + gem5_cmds = mlir_gem5_compile_command(new_input_path, sample_mlir_path, vectorlane_size) + + if spad_info is not None: + link_option = f"-Wl,--section-start=.spad=0x{spad_info['spad_vaddr']:x}" + else: + link_option = "" + # Compile a validation binary and measure its .spad section to reject + # over-spad tilings (SpadOverflowError) -- this must run even in + # timing-only / autotune (non-functional) mode, so a tiling that does not + # fit the spad is scored infeasible instead of wedging TOGSim. The Spike + # *execution* itself stays gated on functional_mode (run_spike, below). # Use custom malloc to avoid size error new_link_option = link_option + " -Wl,--wrap=malloc -Wl,--wrap=free" cmds = mlir_compile_command(new_input_path, vectorlane_size, vlen=vlen) @@ -161,51 +183,47 @@ def load(cls, source_code, translate_cmd = shlex.split(cmds[1]) llc_cmd = shlex.split(cmds[2]) llc_asm_cmd = shlex.split(cmds[3]) - with lock: - try: - # loop-padding (mlir-opt) -> Python fine-grained + vcix (one parse/print) - subprocess.check_call(opt_pad_cmd) - run_module_passes(new_input_path + "_padded.mlir", - new_input_path + "_custom.mlir", - POST_OPT_PASSES, vectorlane=vectorlane_size, vlen=vlen) - # Standard MLIR -> LLVM-dialect lowering (registered upstream - # passes) runs in-process via the bindings PassManager, picking - # up after the custom mlir-opt passes (memref-to-gemmini). - run_standard_lowering(new_input_path + "_custom.mlir", new_input_path + "_llvm.mlir") - subprocess.check_call(translate_cmd) - subprocess.check_call(llc_cmd) - subprocess.check_call(llc_asm_cmd) - except subprocess.CalledProcessError as e: - logger.error(f"Command failed with exit code {e.returncode}") - logger.error(f"Error output: {e.output.decode() if isinstance(e.output, bytes) else e.output}") - assert(0) - - val_llvm_caller = MLIRKernelCallerCodeGen(extension_config.pytorchsim_functional_mode, arg_attributes) - val_llvm_caller.generate_wrapper_file(write_path, validation_wrapper_name) - val_llvm_caller.compile_wih_kernel(write_path, key, validation_wrapper_name, - validation_binary_name, new_link_option) - - stack_size = val_llvm_caller.parse_stack_sizes(f"{write_path}/{key}.s", vlenb=vlenb) - spad_size = val_llvm_caller.get_spad_size(validation_binary_path) - spad_usage = stack_size + spad_size # Spad usage per lane - if extension_config.CONFIG_SPAD_INFO["spad_size"] < spad_usage: - logger.debug( - f"Scratchpad size exceeded: required {spad_usage} bytes, " - f"but only {extension_config.CONFIG_SPAD_INFO['spad_size']} bytes available." - ) - raise SpadOverflowError() - - # Skip if TOG file already exists - if os.path.isfile(tog_path): - return key + try: + # loop-padding (mlir-opt) -> Python fine-grained + vcix (one parse/print) + subprocess.check_call(opt_pad_cmd) + run_module_passes(new_input_path + "_padded.mlir", + new_input_path + "_custom.mlir", + POST_OPT_PASSES, vectorlane=vectorlane_size, vlen=vlen) + # Standard MLIR -> LLVM-dialect lowering (registered upstream + # passes) runs in-process via the bindings PassManager, picking + # up after the custom mlir-opt passes (memref-to-gemmini). + run_standard_lowering(new_input_path + "_custom.mlir", new_input_path + "_llvm.mlir") + subprocess.check_call(translate_cmd) + subprocess.check_call(llc_cmd) + subprocess.check_call(llc_asm_cmd) + except subprocess.CalledProcessError as e: + logger.error(f"Command failed with exit code {e.returncode}") + logger.error(f"Error output: {e.output.decode() if isinstance(e.output, bytes) else e.output}") + assert(0) - # Launch tile graph generator - gem5_pad_cmd = shlex.split(gem5_cmds[0]) - gem5_translate_cmd = shlex.split(gem5_cmds[1]) - gem5_llc_cmd = shlex.split(gem5_cmds[2]) + val_llvm_caller = MLIRKernelCallerCodeGen(extension_config.pytorchsim_functional_mode, arg_attributes) + val_llvm_caller.generate_wrapper_file(write_path, validation_wrapper_name) + val_llvm_caller.compile_wih_kernel(write_path, key, validation_wrapper_name, + validation_binary_name, new_link_option) + + # Only the .spad section consumes the scratchpad; the stack frame lives in main memory (sp in the -m region, not the scratchpad vaddr) so it is not charged against the per-lane spad budget. + spad_usage = val_llvm_caller.get_spad_size(validation_binary_path) + # Budget per dispatch = half the spad: two work-items run concurrently + # (double-buffer), so each must fit in spad/2 or they deadlock competing for + # the shared spad. Matches the GEMM tiling gate (max_spad_size = spad/2). + spad_budget = extension_config.CONFIG_SPAD_INFO["spad_size"] // 2 + if spad_budget < spad_usage: + raise SpadOverflowError( + f"Scratchpad size exceeded: kernel needs {spad_usage} bytes/lane, but only " + f"{spad_budget} bytes/lane (spad/2, double-buffer budget) are available. " + f"tile_size={kwargs.get('tile_size')}, origins={origins}, path={write_path}" + ) + + # Launch tile graph generator + gem5_pad_cmd = shlex.split(gem5_cmds[0]) + gem5_translate_cmd = shlex.split(gem5_cmds[1]) + gem5_llc_cmd = shlex.split(gem5_cmds[2]) - lock = FileLock(get_lock_path(write_path), timeout=LOCK_TIMEOUT) - with lock: try: # mlir-opt now runs only loop-padding/dma-fine-grained/pytorchsim-to-vcix # and writes the post-vcix IR. The tile-operation-graph pass is ported @@ -241,23 +259,39 @@ def load(cls, source_code, # Run cyclesim cyclesim = CycleSimulator() cycle_list = cyclesim.compile_and_simulate(os.path.join(write_path, cycle_binary_name), vectorlane_size, silent_mode=silent_mode) + cycle_list_for_trace = list(cycle_list) - # Create TOG + # Per-tile cycle offsets, shared with the trace cycle-table below. w_offset, x_offset = vectorlane_size, vectorlane_size if kwargs['loop_size'] is not None and kwargs['loop_size'][-3] < vectorlane_size: x_offset = kwargs['loop_size'][-3] if kwargs['loop_size'] is not None and kwargs['loop_size'][-1] < vectorlane_size: w_offset = kwargs['loop_size'][-1] w_offset = 0 # max(w_offset - x_offset, 0) - tile_graph_generator = tog_generator(origins) - tile_graph_generator.load_file(raw_tog_path) - tile_graph_generator.generate_tile_graph( - tog_path, - cycle_list=cycle_list, - x_offset=x_offset, # FIXME. - w_offset=w_offset, # FIXME. - vector_lane=vectorlane_size - ) + + # Trace pipeline (sole sim path): emit the compiled trace producer .so + + # the cycle-table TSV from the post-vcix IR and gem5 cycle_list/offsets; + # TOGSim builds its C++ TOG from this via trace_to_tilegraph. + try: + import mlir.ir as ir + from PyTorchSimFrontend.mlir.passes import ( + build_skeleton as _bs, cycle_table as _ct, lower_to_emitc as _l2e) + pv = sample_mlir_path + "_postvcix.mlir" + _ctx = ir.Context(); _ctx.allow_unregistered_dialects = True + with _ctx: + _mod = ir.Module.parse(open(pv).read(), _ctx) + _bs.build_skeleton(_mod) + _ntiles = len(_ct._compute_types(_mod)) + # align lengths: gem5 gives one numCycles per compute node; + # pad with the last value / truncate if it disagrees. + _cl = list(cycle_list_for_trace) + if _cl and len(_cl) != _ntiles: + _cl = (_cl + [_cl[-1]] * _ntiles)[:_ntiles] + _tbl = _ct.build_cycle_table(_mod, _cl, x_offset, w_offset) + _ct.dump_cycle_table_tsv(_tbl, os.path.join(write_path, "trace_cycles.tsv"), origins=origins) + _l2e.build_trace_so(pv, os.path.join(write_path, "trace.so")) + except Exception as e: + logger.warning(f"[P3-trace] trace .so/sidecar dump skipped: {e}") return key class CustomAsyncCompile(AsyncCompile): @@ -282,6 +316,9 @@ def task(): def run_kernel_simulation(*args, autotune_subprocess_timeout_sec=None, **kwargs): # Wait for compilation key = future.result() + if not autotune and origins: + logger.info("[kernel %s] origins: %s", + hash_prefix(key), ", ".join(sorted(str(o) for o in origins))) from filelock import FileLock result_path = os.path.join(extension_config.get_dump_path(), hash_prefix(key)) lock = FileLock(get_lock_path(result_path), timeout=LOCK_TIMEOUT) diff --git a/PyTorchSimFrontend/extension_config.py b/PyTorchSimFrontend/extension_config.py index 0e1bc422..f3fea6f2 100644 --- a/PyTorchSimFrontend/extension_config.py +++ b/PyTorchSimFrontend/extension_config.py @@ -57,6 +57,13 @@ def __getattr__(name): return config_yaml['pytorchsim_functional_mode'] if name == "pytorchsim_timing_mode": return config_yaml['pytorchsim_timing_mode'] + # Sub-option of functional mode: per-kernel CPU cross-check. When set (and + # functional mode is on), every realized buffer produced by Spike is compared + # against a CPU golden to localize the first kernel whose value diverges. + # Auto-disabled when functional mode is off (no Spike values to verify). + if name == "pytorchsim_functional_verify_per_kernel": + return bool(config_yaml.get('pytorchsim_functional_verify_per_kernel', False)) \ + and bool(config_yaml['pytorchsim_functional_mode']) # Mapping strategy if name == "codegen_mapping_strategy": diff --git a/PyTorchSimFrontend/extension_functional_verify.py b/PyTorchSimFrontend/extension_functional_verify.py new file mode 100644 index 00000000..6507f324 --- /dev/null +++ b/PyTorchSimFrontend/extension_functional_verify.py @@ -0,0 +1,168 @@ +"""Per-kernel CPU cross-check for the functional (Spike) path. + +This is a sub-option of ``pytorchsim_functional_mode``: enable it with the YAML +key ``pytorchsim_functional_verify_per_kernel: 1`` (auto-disabled when functional +mode is off -- there are no Spike values to verify otherwise). + +When enabled, the generated wrapper compares every realized buffer (the output of +each compiled, fused kernel that Spike just produced) against a CPU "golden" +reference. The golden is computed once per graph execution by running the +original aten graph (``V.graph.module``) on CPU with the same inputs. The first +buffer whose value diverges beyond tolerance pinpoints the fused op-cluster that +injected the error -- the finest granularity observable in a fused pipeline, +since intermediate aten ops inside a kernel are not separately materialized. + +Tolerances (read once at import): + TORCHSIM_FUNCTIONAL_VERIFY_RTOL relative tolerance (default 1e-4) + TORCHSIM_FUNCTIONAL_VERIFY_ATOL absolute tolerance (default 1e-4) + +The check raises FunctionalVerifyMismatch at the first divergent buffer +(stop-at-first), after logging the kernel, originating fx op, offending indices +and max abs diff. + +NOTE: codegen bakes the check calls into the wrapper only when enabled at +*compile* time. Toggle the option and clear the codegen cache together +(scripts/clear_codegen_cache.sh), or a cached wrapper without checks is replayed. +""" +import os + +import torch + +from PyTorchSimFrontend import extension_config +from PyTorchSimFrontend.extension_config import setup_logger + +logger = setup_logger(__name__) + +RTOL = float(os.environ.get("TORCHSIM_FUNCTIONAL_VERIFY_RTOL", "1e-4")) +ATOL = float(os.environ.get("TORCHSIM_FUNCTIONAL_VERIFY_ATOL", "1e-4")) + +# Codegen-time registry of runnable aten graphs, keyed by an int id baked into +# the generated wrapper. Persists in-process: the exec'd wrapper imports this +# very module, so the dict it sees is the one populated during codegen. +_GRAPHS = {} + +# Per-run state, reset by verify_init at the top of each call(args). +_STATE = {"golden": None, "n_checked": 0, "failed": False} + + +class FunctionalVerifyMismatch(RuntimeError): + """Raised at the first kernel buffer that diverges from the CPU golden.""" + + +def enabled(): + """True when functional mode AND the per-kernel verify sub-option are on. + + Read dynamically (the config can change inside a ``with TOGSimulator(...)`` + block); the config accessor already AND-gates this with functional mode. + """ + try: + return bool(extension_config.pytorchsim_functional_verify_per_kernel) + except Exception: + return False + + +def register_graph(gm): + """Register a runnable aten GraphModule, returning an id for the wrapper.""" + gid = len(_GRAPHS) + _GRAPHS[gid] = gm + return gid + + +class _GoldenInterpreter(torch.fx.Interpreter): + """Run the aten graph on CPU, recording each node's tensor output by name.""" + + def __init__(self, gm): + super().__init__(gm) + self.values = {} + + def run_node(self, n): + out = super().run_node(n) + # Move EVERY tensor output to CPU (preserving dtype) and return it, so a + # device-baked op (e.g. arange(device=npu)) or a downstream consumer + # (e.g. aten.index, which requires its index tensors on the indexed + # tensor's device) sees CPU operands. Only the recorded golden is cast to + # float32 for the allclose compare; the propagated value keeps its dtype + # so int index tensors stay usable. + out = torch.utils._pytree.tree_map( + lambda x: x.detach().to("cpu") if isinstance(x, torch.Tensor) else x, out) + if isinstance(out, torch.Tensor): + self.values[n.name] = out.to(torch.float32) + return out + + +def _to_cpu(x): + return x.detach().cpu() if isinstance(x, torch.Tensor) else x + + +def verify_init(gid, inputs): + """Compute the CPU golden for this graph execution (top of call(args)).""" + _STATE["golden"] = None + _STATE["n_checked"] = 0 + _STATE["failed"] = False + gm = _GRAPHS.get(gid) + if gm is None: + logger.warning("[FuncVerify] no graph registered for id %s", gid) + return + try: + cpu_inputs = [_to_cpu(x) for x in inputs] + interp = _GoldenInterpreter(gm) + interp.run(*cpu_inputs) + _STATE["golden"] = interp.values + logger.info("[FuncVerify] golden ready: %d node tensors (rtol=%g atol=%g)", + len(interp.values), RTOL, ATOL) + except Exception as e: # never let the verify shadow break the real run + logger.warning("[FuncVerify] golden computation failed (%r); " + "per-kernel verify disabled for this graph", e) + _STATE["golden"] = None + + +def verify_check(value, buffer_name, node_name, op): + """Compare one realized buffer against its golden; raise on first divergence.""" + if _STATE["failed"]: + return + golden = _STATE["golden"] + if golden is None or not isinstance(value, torch.Tensor): + return + ref = golden.get(node_name) + if ref is None: + return # no reference captured for this fx node (non-tensor / folded) + val = value.detach().to("cpu", torch.float32) + if val.shape != ref.shape: + if val.numel() != ref.numel(): + return + val = val.reshape(ref.shape) + + _STATE["n_checked"] += 1 + if torch.allclose(val, ref, rtol=RTOL, atol=ATOL, equal_nan=True): + logger.debug("[FuncVerify] PASS %-14s %-28s %s", + buffer_name, op, tuple(ref.shape)) + return + + # ---- divergence ---- + _STATE["failed"] = True + diff = (val - ref).abs() + tol = ATOL + RTOL * ref.abs() + bad = diff > tol + n_bad = int(bad.sum()) + maxd = float(diff.max()) + idxs = bad.nonzero() + first = idxs[0].tolist() if idxs.numel() else None + sample = [f" {tuple(r.tolist())}: npu={val[tuple(r.tolist())].item():.6g} " + f"cpu={ref[tuple(r.tolist())].item():.6g}" + for r in idxs[:6]] + logger.error( + "\n================= PER-KERNEL FUNCTIONAL VERIFY: DIVERGENCE =================\n" + " first divergent buffer : %s\n" + " originating fx op : %s (node '%s')\n" + " shape : %s\n" + " elements over tol : %d / %d\n" + " max abs diff : %.6g (rtol=%g atol=%g)\n" + " first bad index : %s\n" + " buffers verified OK : %d\n" + " sample mismatches (npu vs cpu):\n%s\n" + "===========================================================================", + buffer_name, op, node_name, tuple(ref.shape), n_bad, ref.numel(), + maxd, RTOL, ATOL, first, _STATE["n_checked"] - 1, "\n".join(sample)) + raise FunctionalVerifyMismatch( + f"[FuncVerify] first divergence at buffer '{buffer_name}' (op {op}): " + f"max abs diff {maxd:.6g}, {n_bad}/{ref.numel()} elements over tol") diff --git a/PyTorchSimFrontend/mlir/axis_split.py b/PyTorchSimFrontend/mlir/axis_split.py index 71ec4809..2cf58c8a 100644 --- a/PyTorchSimFrontend/mlir/axis_split.py +++ b/PyTorchSimFrontend/mlir/axis_split.py @@ -29,6 +29,77 @@ def _as_int(x): return None +def _as_digit(expr): + """If ``expr`` is a single-variable *digit extractor* -- any nesting of FloorDiv / + ModularIndexing whose innermost argument is one symbol ``v`` -- return ``(v, div, mod)`` + meaning ``(v // div) % mod`` (``mod is None`` -> a pure ``v // div``). Otherwise None. + + Every such nesting collapses to a single (div, mod) by composing divisors, from four + algebraic identities (v >= 0, all constants positive integers): + FloorDiv(v//a, b) = v // (a*b) + FloorDiv((v//a)%m, b) = (v // (a*b)) % (m//b) if b | m + ModularIndexing(v//a, b,m2)= (v // (a*b)) % m2 + ModularIndexing((v//a)%m, b,m2)= (v // (a*b)) % m2 if b*m2| m + The divisibility guards make every rewrite provably equality-preserving. A multi- + variable inner argument (e.g. torch.roll's v+shift) is not a digit extractor -> None. + """ + if isinstance(expr, sympy.Symbol): + return (expr, 1, None) + if isinstance(expr, FloorDiv): + inner, b = expr.args + b, e = _as_int(b), _as_digit(expr.args[0]) + if e is None or b is None: + return None + v, a, m = e + if m is None: + return (v, a * b, None) + if m % b == 0: + return (v, a * b, m // b) + return None + if isinstance(expr, ModularIndexing): + inner, b, m2 = expr.args + b, m2, e = _as_int(b), _as_int(m2), _as_digit(expr.args[0]) + if e is None or b is None or m2 is None: + return None + v, a, m = e + if m is None: + return (v, a * b, m2) + if m % (b * m2) == 0: + return (v, a * b, m2) + return None + return None + + +def _rebuild_digit(v, a, m): + """Canonical single-level form of ``(v // a) % m``.""" + x = v if a == 1 else FloorDiv(v, a) + return x if m is None else ModularIndexing(v, a, m) + + +def flatten_nested_floormod(expr): + """Collapse nested single-variable FloorDiv/ModularIndexing to one level. + + A composition of aligned reshapes on one iteration variable leaves a nested index like + ModularIndexing(ModularIndexing(p, 1, 64), 1, 8) that neither sympy nor + simplify_with_ranges reduces, so collect_boundaries skips its cut points (the inner base + is not a bare var) and the affine-only DMA check later rejects it. Rewriting each nested + digit extractor to its single-level (v // A) % M form (via _as_digit) exposes those cut + points to axis-split. General and pattern-free -- no per-shape special cases. + """ + try: + atoms = expr.atoms(FloorDiv, ModularIndexing) + except AttributeError: + return expr + replace = {} + for atom in atoms: + e = _as_digit(atom) + if e is not None: + canon = _rebuild_digit(*e) + if canon != atom: + replace[atom] = canon + return expr.xreplace(replace) if replace else expr + + def collect_boundaries(exprs, var_to_axis, var_ranges): """{axis_index: set(boundary cut points)} for the given index expressions. @@ -39,6 +110,7 @@ def collect_boundaries(exprs, var_to_axis, var_ranges): import collections bset = collections.defaultdict(set) for expr in exprs: + expr = flatten_nested_floormod(expr) # nested digit extractors -> single level for fd in expr.atoms(FloorDiv): base, div = fd.args k = _as_int(div) @@ -196,6 +268,7 @@ def _fold_with_ranges(expr, var_ranges): Iterated to a fixpoint (folding a mod can expose a foldable floor). """ from torch.utils._sympy.value_ranges import bound_sympy, ValueRanges + expr = flatten_nested_floormod(expr) # collapse any residual single-var nested digit ranges = {} for v, sz in var_ranges.items(): e = _as_int(sz) diff --git a/PyTorchSimFrontend/mlir/mlir_autotune.py b/PyTorchSimFrontend/mlir/mlir_autotune.py index 396396f3..e4876b5b 100644 --- a/PyTorchSimFrontend/mlir/mlir_autotune.py +++ b/PyTorchSimFrontend/mlir/mlir_autotune.py @@ -54,7 +54,7 @@ def __str__(self) -> str: def make_run_fn( self, input_tensors: torch.Tensor, output_tensors: torch.Tensor ) -> Callable[[], None]: - from PyTorchSimFrontend.extension_codecache import CustomAsyncCompile + from PyTorchSimFrontend.extension_codecache import CustomAsyncCompile, get_header custom_async_compile = CustomAsyncCompile() # Check already cached result. @@ -80,12 +80,15 @@ def cached_run_fn(*args, autotune_subprocess_timeout_sec=None, **kwargs): return cached_run_fn # Run a candidate code + _headers = get_header(self.source_code) + _header_kwargs = {} if _headers is None else { + "global_var_header": _headers[0], "gem5_global_var_header": _headers[1]} run_method = custom_async_compile.mlir( self.source_code, vectorlane_size=self.extra_args["vector_lane"], loop_size=self.extra_args["loop_size"], spad_info=self.extra_args["spad_info"], vlen=self.extra_args["vlen"], arg_attributes=self.extra_args["arg_attributes"], origins=self.extra_args["origins"], silent_mode=True, - autotune=self.extra_args['autotune']) + autotune=self.extra_args['autotune'], **_header_kwargs) args = [ tensor diff --git a/PyTorchSimFrontend/mlir/mlir_bmm_template.py b/PyTorchSimFrontend/mlir/mlir_bmm_template.py index c5fd902f..2bc8cff8 100644 --- a/PyTorchSimFrontend/mlir/mlir_bmm_template.py +++ b/PyTorchSimFrontend/mlir/mlir_bmm_template.py @@ -152,11 +152,13 @@ """ class MLIRBMMTemplate(MLIRTemplate): + # 3-D frame (batch x M x N): batch + M row indices + the reduced N index. + REDUCTION_EPILOGUE_ALIASING = {"index0": "index0", "index1": "index2", "index2": "index1"} + def __init__(self, input_nodes, layout, input_reorder=None): super().__init__("kernel", input_nodes, layout, input_reorder) self.support_epilogue_fusion = True self.support_prologue_fusion = True - self.support_reduction_fusion = True def render(self, kernel: MLIRTemplateKernel, @@ -165,10 +167,10 @@ def render(self, prologue_nodes: Optional[List[IRNode]] = None, tile_info = None, **kwargs): - X, W, Y, Bias, W_tensor, X_tensor, B, M, N, K, n_extra_node, n_prologue_node = self.extract_info(template_buffer_node, epilogue_nodes, prologue_nodes) + X, W, Y, Bias, W_tensor, X_tensor, B, M, N, K, n_extra_node, n_prologue_node, n_extra_read = self.extract_info(template_buffer_node, epilogue_nodes, prologue_nodes) precision_bytes = mlir_common.get_dtype_nbytes(X.get_dtype()) if tile_info is None: - TILE_M, TILE_N, TILE_K, SUB_TILE_M, SUB_TILE_N, SUB_TILE_K = self.select_tile(kernel, M, N, K, n_extra_node, 0, n_prologue_node, precision_bytes)[0] + TILE_M, TILE_N, TILE_K, SUB_TILE_M, SUB_TILE_N, SUB_TILE_K = self.select_tile(kernel, M, N, K, n_extra_node, n_extra_read, n_prologue_node, precision_bytes)[0] else: TILE_M, TILE_N, TILE_K, SUB_TILE_M, SUB_TILE_N, SUB_TILE_K = tile_info @@ -179,7 +181,7 @@ def render(self, nr_reduction_nodes = [node for node in epilogue_nodes if node.is_reduction()] if epilogue_nodes is not None else [] if nr_reduction_nodes: template = BMM_REDUCTION_TEMPLATE - epilogue_dim_aliasing = {"index0":"index0", "index1":"index2", "index2": "index1"} + epilogue_dim_aliasing = self.REDUCTION_EPILOGUE_ALIASING nr_rdim = 1 elif prologue_nodes: template = BMM_PROLOGUE_TEMPLATE @@ -342,7 +344,32 @@ def extract_info(self, template_buffer_node, epilogue_nodes, prologue_nodes): # Select tile size n_extra_node = len(epilogue_nodes) if epilogue_nodes is not None else 0 n_prologue_node = len(prologue_nodes) if prologue_nodes is not None else 0 - return X,W,Y,Bias,W_tensor,X_tensor,B,M,N,K,n_extra_node, n_prologue_node + n_extra_read = self.count_prologue_extra_buffers(prologue_nodes) + return X,W,Y,Bias,W_tensor,X_tensor,B,M,N,K,n_extra_node, n_prologue_node, n_extra_read + + def count_prologue_extra_buffers(self, prologue_nodes): + # Count prologue reads needing their own .spad global: the numel-matching main input reuses the matmul-operand buffer, every other read (e.g. softmax max/sum) gets a disjoint one (see codegen_template_code). + if not prologue_nodes: + return 0 + from functools import reduce + import operator + from torch._inductor.virtualized import V + buf_dict = {val.name: val for val in V.graph.buffers} + buf_dict.update(V.graph.graph_inputs) + prologue_outputs = {list(node.read_writes.writes)[0].name for node in prologue_nodes} + extra = set() + for node in prologue_nodes: + reads = sorted(i.name for i in node.read_writes.reads) + main_input = None + for candidate_read in reads: + if candidate_read in buf_dict and \ + reduce(operator.mul, buf_dict[candidate_read].get_size(), 1) == node.node.get_numel(): + main_input = candidate_read + break + for r in reads: + if r != main_input and r not in prologue_outputs: + extra.add(r) + return len(extra) def get_tile_candidates(self, kernel: MLIRTemplateKernel, @@ -350,12 +377,15 @@ def get_tile_candidates(self, epilogue_nodes: Optional[List[IRNode]] = None, prologue_nodes: Optional[List[IRNode]] = None, **kwargs): - X, W, Y, Bias, W_tensor, X_tensor, B, M, N, K, n_extra_node, n_prologue_node = self.extract_info(template_buffer_node, epilogue_nodes, prologue_nodes) + X, W, Y, Bias, W_tensor, X_tensor, B, M, N, K, n_extra_node, n_prologue_node, n_extra_read = self.extract_info(template_buffer_node, epilogue_nodes, prologue_nodes) precision_bytes = mlir_common.get_dtype_nbytes(X.get_dtype()) - return self.select_tile(kernel, M, N, K, n_extra_node, 0, n_prologue_node, precision_bytes) + return self.select_tile(kernel, M, N, K, n_extra_node, n_extra_read, n_prologue_node, precision_bytes) def select_tile(self, kernel, M, N, K, n_extra_node, n_extra_read, n_prologue_node, precision_bytes): - tile_candidates = kernel.gemm_combination_mapping(M, N, K, n_extra_node=n_extra_node, precision_bytes=precision_bytes) + # Budget the prologue extra-read globals as weight-tile buffers (their emitted size) so the chosen tile fits spad/2. + tile_candidates = kernel.gemm_combination_mapping( + M, N, K, n_extra_node=n_extra_node, n_prologue_extra_read=n_extra_read, + precision_bytes=precision_bytes) for idx, (TILE_M, TILE_N, TILE_K) in enumerate(tile_candidates): SUB_TILE_M = TILE_M if (TILE_M < kernel.vector_lane) or n_prologue_node else kernel.vector_lane SUB_TILE_N = TILE_N # if (TILE_N < kernel.vector_lane) or prologue_nodes else kernel.vector_lane diff --git a/PyTorchSimFrontend/mlir/mlir_cat_template.py b/PyTorchSimFrontend/mlir/mlir_cat_template.py index 7abdfee6..b922e51b 100644 --- a/PyTorchSimFrontend/mlir/mlir_cat_template.py +++ b/PyTorchSimFrontend/mlir/mlir_cat_template.py @@ -209,6 +209,22 @@ def _compute_excluded_dims(self, tile_sizes: list) -> list: tile_sizes[idx] = 1 return excluded + @staticmethod + def _largest_divisor_leq(extent, cap): + """Largest divisor of ``extent`` that does not exceed ``cap`` (>= 1). + + The concat-dim copy loop steps by the per-input tile over ``[0, extent)``. + If the tile does not divide ``extent`` the final iteration is ragged and, + because the DMA carries no remainder mask, over-reads the input and + over-writes the output. Snapping the tile down to a divisor keeps every + iteration full-width and in-bounds. + """ + cap = min(cap, extent) + for d in range(cap, 0, -1): + if extent % d == 0: + return d + return 1 + def _calculate_input_tile_sizes(self, kernel, input_sizes, tile_sizes, num_inputs, rank, precision_bytes): """Calculate tile sizes along the concat dimension for each input.""" non_dim_tile_elements = math.prod(tile_sizes) if tile_sizes else 1 @@ -218,7 +234,9 @@ def _calculate_input_tile_sizes(self, kernel, input_sizes, tile_sizes, num_input input_tile_sizes_dim = [] for i in range(num_inputs): if extra_concat > 0 and non_dim_tile_elements > 0: - tile_dim = min(input_sizes[i][self.dim], extra_concat) + # Snap to a divisor of the input's concat extent so the copy loop + # never emits a ragged (unmasked) tail tile. + tile_dim = self._largest_divisor_leq(input_sizes[i][self.dim], extra_concat) extra_concat -= tile_dim else: tile_dim = 1 diff --git a/PyTorchSimFrontend/mlir/mlir_codegen_backend.py b/PyTorchSimFrontend/mlir/mlir_codegen_backend.py index 725e0dc6..18ad4e4f 100644 --- a/PyTorchSimFrontend/mlir/mlir_codegen_backend.py +++ b/PyTorchSimFrontend/mlir/mlir_codegen_backend.py @@ -17,7 +17,6 @@ from torch._inductor.codegen import cpp, wrapper, common, memory_planning from torch._inductor.ir import GraphPartitionSignature from torch._inductor.virtualized import V, _ops as ops -from torch._inductor.codecache import write_atomic from torch._inductor.utils import ( IndentedBuffer, is_welford_reduction, @@ -25,6 +24,7 @@ ) from torch.utils._sympy.functions import ModularIndexing, FloorDiv from PyTorchSimFrontend import extension_codecache +from PyTorchSimFrontend import extension_functional_verify as _func_verify from . import mlir_common from .mlir_common import LoopLevel, LoopNest from .mlir_ops import ExtensionOverrides @@ -44,10 +44,16 @@ def reduction_init(reduction_type, dtype): return float(0) if dtype.is_floating_point else int(0) if reduction_type == "prod": return float(1) if dtype.is_floating_point else int(1) + # Integer reductions cannot use a +/-inf identity (invalid as an int constant and + # overflows torch.tensor(inf, dtype=int)); use the dtype's representable extreme. if reduction_type in {"max", "argmax"}: - return "-inf" + if dtype.is_floating_point: + return "-inf" + return 0 if dtype is torch.bool else torch.iinfo(dtype).min if reduction_type in {"min", "argmin"}: - return "inf" + if dtype.is_floating_point: + return "inf" + return 1 if dtype is torch.bool else torch.iinfo(dtype).max if reduction_type in {"welford_reduce"}: return f"0.0" raise AssertionError(reduction_type) @@ -104,6 +110,7 @@ def write_header(self): from PyTorchSimFrontend.extension_config import CONFIG_SRAM_BUFFER_PLAN, setup_logger from Simulator.simulator import TOGSimulator from PyTorchSimFrontend.extension_op import sparse_mm_dummy_stonne_outer + from PyTorchSimFrontend import extension_functional_verify as _fverify from torch._inductor.select_algorithm import extern_kernels # Configure logger for generated wrapper code @@ -113,6 +120,7 @@ def write_header(self): inductor_ops = torch.ops.inductor assert_size_stride = torch._C._dynamo.guards.assert_size_stride assert_alignment = torch._C._dynamo.guards.assert_alignment + empty_strided_cpu = torch._C._dynamo.guards._empty_strided_cpu alloc_from_pool = torch.ops.inductor._alloc_from_pool reinterpret_tensor = torch.ops.inductor._reinterpret_tensor custom_async_compile = CustomAsyncCompile() @@ -163,6 +171,16 @@ def call(args): self.prefix.writeline(f"{lhs} = args") self.prefix.writeline("args.clear()") + # Per-kernel functional verify: register the runnable aten graph and + # emit a CPU golden build at the top of call(), passing graph inputs. + if _func_verify.enabled(): + gm = getattr(V.graph, "module", None) + if gm is not None: + gid = _func_verify.register_graph(gm) + in_names = list(V.graph.graph_inputs.keys()) + self.prefix.writeline( + f"_fverify.verify_init({gid}, [{', '.join(in_names)}])") + self.codegen_inputs() self.codegen_input_size_asserts() self.codegen_sram_plan_prefix() @@ -205,6 +223,7 @@ def generate(self, is_inference): result = IndentedBuffer() # result.splice(self.header) + self._fverify_seen = set() with contextlib.ExitStack() as stack: stack.enter_context(self.wrapper_call.indent()) self.memory_plan_reuse() @@ -221,6 +240,8 @@ def generate(self, is_inference): line.codegen(self.wrapper_call) elif isinstance(line, wrapper.KernelCallLine): self.wrapper_call.writeline(self.wrap_kernel_call(line.kernel_name, line.call_args)) + if _func_verify.enabled(): + self._fverify_emit_checks(line.call_args) else: if isinstance(line, wrapper.WrapperLine): line.codegen(self.wrapper_call) @@ -250,6 +271,37 @@ def generate(self, is_inference): self.kernel_declarations.getvaluewithlinemap(), ) + def _fverify_emit_checks(self, call_args): + """Emit per-kernel CPU verify calls for this kernel's output buffers. + + A buffer's value is produced by the first kernel that names it (producer + precedes consumers in topo order), so we check each bare-identifier buffer + arg the first time it is seen -- that occurrence is its output. The buffer + is mapped to its originating fx node (op) so the runtime check can compare + against the CPU golden keyed by that node. + """ + for a in call_args: + if not isinstance(a, str): + continue + name = a.strip() + if not name.isidentifier() or name in self._fverify_seen: + continue + self._fverify_seen.add(name) + if name in V.graph.graph_inputs: + continue # placeholders: golden == input, nothing to verify + try: + buf = V.graph.get_buffer(name) + except Exception: + buf = None + if buf is None: + continue + origin = getattr(buf, "origin_node", None) + if origin is None: + continue + op = str(getattr(origin, "target", "?")) + self.wrapper_call.writeline( + f'_fverify.verify_check({name}, "{name}", "{origin.name}", "{op}")') + def memory_plan(self): self.lines = memory_planning.MemoryPlanner(self).plan(self.lines) @@ -265,6 +317,22 @@ def memory_plan(self): "MVOUT1": 3, } + +class Step: + """One load->compute->store unit of the kernel body (see codegen_loops). + + Bundles the DMA, mask, index and compute buffers so the body can be an + ordered list of steps; the formerly ad-hoc mask/index buffers are just + fields here. + """ + __slots__ = ("applys", "dma_loads", + "loads", "compute", "stores", "dma_stores") + + def __init__(self, **buffers): + for name, buf in buffers.items(): + setattr(self, name, buf) + + class MLIRKernel(mlir_common.BaseMLIRKernel): overrides = ExtensionOverrides newvar_prefix = "%" @@ -276,11 +344,15 @@ def __init__(self, kernel_group, reason=None): self.spad_buffer = IndentedBuffer() self.reduction_prefix = IndentedBuffer() self.reduction_suffix = IndentedBuffer() - self.applys = IndentedBuffer() - self.masks = IndentedBuffer() - self.dma_loads = IndentedBuffer() - self.dma_stores = IndentedBuffer() - self.indexed_buffer = IndentedBuffer() + # Kernel body = ordered load->compute->store steps; step 0 keeps the base + # loads/compute/stores (the CSE target default captured self.compute at init). + step0 = Step( + applys=IndentedBuffer(), + dma_loads=IndentedBuffer(), dma_stores=IndentedBuffer(), + loads=self.loads, compute=self.compute, stores=self.stores, + ) + self.steps = [step0] + self._bind_step(step0) self.global_vars = IndentedBuffer() self.header = IndentedBuffer() self.gem5_header = IndentedBuffer() @@ -319,6 +391,7 @@ def __init__(self, kernel_group, reason=None): self.welford_reduce_out = None self.reduce_iterator = {} self.spad_buffer_dict = dict() + self.indirect_symbols = set() # CSE-var names bound as indirect indices self.base_vector_initialized = False self.loop_size = None @@ -327,12 +400,21 @@ def reset(self, reason): self.__init__(self.kernel_group, reason=reason) self.exit_stack, self._nested_context_depth = save + @staticmethod + def _origin_is_exp(o): + """True iff the FX origin node is an aten.exp op -- matched by the op target, not a + name substring (so it does not fire on expand / expm1 / experimental).""" + t = getattr(o, "target", None) + pkt = getattr(t, "_overloadpacket", None) + name = getattr(pkt, "__name__", None) or getattr(t, "__name__", None) or "" + return name == "exp" + # padding type 0: zero-padding 1: negative-padding(-inf) ... def get_padding_type(self): ops = self.current_node.node.origins if self.current_node.is_reduction(): for op in ops: - if "exp" in op.name: # exponential reduciton case + if self._origin_is_exp(op): # exponential reduciton case return 1 # for op in ops: # TODO: padding has some problem in the case of max_pool # if "max_pool" in op.args[0].name: @@ -501,19 +583,9 @@ def parse_index_list(self, expr_list:list, offset=sympy.Number(0)) -> common.CSE return index def load(self, name: str, index: sympy.Expr): - index, comptute_depedency = self.convert_indirect_indexing(index) + index, offset_desc = self.convert_indirect_indexing(index) padding = self.get_padding_type() - # In case of special form of indirect access, we need to put load in dma_store buffer - if comptute_depedency: - apply_buffer = self.dma_stores - dma_buffer = self.dma_stores - load_buffer = self.dma_stores - else: - apply_buffer = None - dma_buffer = self.dma_loads - load_buffer = self.loads - # Extract dram info dram_var = self.kernel_group.args.input(name) dram_shape = mlir_common.MLIRKernelArgs.get_mlir_shape(self.buffer_types[name]) @@ -521,7 +593,7 @@ def load(self, name: str, index: sympy.Expr): mlir_dtype = mlir_common.DTYPE_TO_MLIR[dtype] # Extract sram info - local_tile_desc, index_var, dram_stride = self.get_dma_info(name, index, buffer=apply_buffer) + local_tile_desc, index_var, dram_stride, local_dims = self.get_dma_info(name, index) vlane_split_axis = local_tile_desc.vmap.vlane_split_axis vlane_stride = local_tile_desc.vmap.vlane_stride tile_numel_per_lane = local_tile_desc.get_numel_per_lane() @@ -535,40 +607,40 @@ def load(self, name: str, index: sympy.Expr): sram_var, sram_index_var = self.get_scratchpad_buffer(dtype, name, local_tile_desc, index) compute_index_var = ",".join(sram_index_var.split(",")[:-1] + [f"%{self.compute_idx}"]) + masked_bounds = self._masked_bounds(name, index, dram_stride, local_tile_desc, is_load=True, buffer=self.dma_loads, local_dims=local_dims) code = self.emit_transfer("MVIN", vlane_split_axis, vlane_stride, mlir_dtype, dram_var, index_var, sram_var, sram_index_var, - dram_shape, tile_shape, dram_stride, tile_stride, int(padding)) - self.cse.generate(dma_buffer, code, assignment = False) # FIXME: assignment = False does not support caching + dram_shape, tile_shape, dram_stride, tile_stride, int(padding), offset=offset_desc, + masked_bounds=masked_bounds, masked_fill=self._masked_fill_bits(dtype, index)) + self.cse.generate(self.dma_loads, code, assignment = False) # FIXME: assignment = False does not support caching - if not comptute_depedency: - # Generate vector load instruction - with self.override_buffer_cse(buffer=load_buffer): - out = ops._load(compute_vec_size, mlir_dtype, sram_var, compute_index_var, tile_shape) - else: - # FIXME. Any good idea? - out = sram_var - self.register_var_info(out, [compute_vec_size, mlir_dtype]) + with self.override_buffer_cse(buffer=self.loads): + out = ops._load(compute_vec_size, mlir_dtype, sram_var, compute_index_var, tile_shape) self.spad_buffer_dict[str(out)] = [sram_var, local_tile_desc.get_tile_size(), tile_numel_per_lane, sram_index_var, tile_shape, vshape] return out def store(self, name: str, index: sympy.Expr, value, mode=None, *args, **kwargs): dtype = V.graph.get_dtype(name) mlir_dtype = mlir_common.DTYPE_TO_MLIR[dtype] + offset_desc = None # Handle scatter store - if "tmp" in str(index): + accumulate = False + if self._has_indirect(index): # Convert the output buffer type to the inplace buffer arg_name = V.graph.scheduler.mutation_real_name.get(name, name) if arg_name not in self.kernel_group.args.inplace_buffers: self.kernel_group.args.make_inplace(arg_name, arg_name) - if mode == "atomic_add": - loaded_value = ops.load(name, index) - value = ops.add(loaded_value, value) - index, _ = self.convert_indirect_indexing(index) + # index_add: let the MVOUT do out[idx] += val. The DMA processes positions + # sequentially, so duplicate indices accumulate correctly regardless of tile + # size -- unlike the compute gather-add-overwrite, which loses duplicates that + # land in the same (non-dividing) tile. + accumulate = (mode == "atomic_add") + index, offset_desc = self.convert_indirect_indexing(index) dram_var = self.kernel_group.args.output(name) # Prepare dma instruction - local_tile_desc, index_var, dram_stride = self.get_dma_info(name, index) + local_tile_desc, index_var, dram_stride, local_dims = self.get_dma_info(name, index) vlane_split_axis = local_tile_desc.vmap.vlane_split_axis vlane_stride = local_tile_desc.vmap.vlane_stride @@ -605,8 +677,10 @@ def store(self, name: str, index: sympy.Expr, value, mode=None, *args, **kwargs) sram_index_var = self.spad_buffer_dict[str(value)][3] # Generate DMA instruction + masked_bounds = self._masked_bounds(name, index, dram_stride, local_tile_desc, is_load=False, buffer=self.dma_stores, local_dims=local_dims) code = self.emit_transfer("MVOUT", vlane_split_axis, vlane_stride, mlir_dtype, dram_var, index_var, sram_var, sram_index_var, - dram_shape, tile_shape, dram_stride, tile_stride, 0) + dram_shape, tile_shape, dram_stride, tile_stride, 0, offset=offset_desc, masked_bounds=masked_bounds, + accumulate=accumulate, acc_float=dtype.is_floating_point) self.dma_stores.writeline(common.DeferredLine(name, code)) def reduction(self, dtype, src_dtype, reduction_type, value): @@ -705,7 +779,7 @@ def store_reduction(self, name, index, value): with self.override_buffer_cse(cse=self.reduction_cse): # Tile is always reuduced in inner loop - local_tile_desc, index_var, dram_stride = self.get_dma_info(name, index, broadcast=False, store_reduction=True, buffer=self.reductions_suffix) + local_tile_desc, index_var, dram_stride, _ = self.get_dma_info(name, index, broadcast=False, store_reduction=True, buffer=self.reductions_suffix) vlane_split_axis = local_tile_desc.vmap.vlane_split_axis vlane_stride = local_tile_desc.vmap.vlane_stride @@ -738,17 +812,13 @@ def store_reduction(self, name, index, value): self.reductions_suffix.writeline(common.DeferredLine(name, code)) def indirect_indexing(self, index_var, size, check=True, wrap_neg=True): + self.indirect_symbols.add(str(index_var)) # record the bound indirect symbol return str(index_var) - def _index_expr(self, tile_desc, renamed_expression, index, base_vector_index): - # In case of index expr, dimension size should be divisible by tile size - if not self.kernel_group.tile_desc.is_dim_dividable(self.ranges): - new_tile_size = self.kernel_group.tile_desc.adjust_tile_to_divisible(self.ranges) - prior_tile_size, prior_ranges = self.kernel_group.tile_desc.get_tile_size(), self.ranges - self.kernel_group.tile_desc.set_tile_size(new_tile_size) - self.reset("recompile") - raise mlir_common.RecompileSignal(f"Index access (tile size {prior_tile_size} is not divisible by {prior_ranges})") + def _has_indirect(self, expr): + return any(s.name in self.indirect_symbols for s in expr.free_symbols) + def _index_expr(self, tile_desc, renamed_expression, index, base_vector_index): tile_size_per_lane = tile_desc.get_tile_size_per_lane() compute_vec_size = tile_desc.get_compute_vec_size() strides = tile_desc.get_tile_stride_per_lane() @@ -785,7 +855,9 @@ def _index_expr(self, tile_desc, renamed_expression, index, base_vector_index): if idx == tile_desc.vmap.vlane_split_axis: # Need to add vector lane offset stride_dim = ops.remainder(dim, vlane_stride_vec) outer_dim = ops.remainder(ops.truncdiv(dim, vlane_stride_vec), vlane_outer_vec) - dim = ops.add(stride_dim, ops.mul(outer_dim, nr_vector_lane_vec)) + # Next sublane-row stride is vector_lane*vlane_stride, not vector_lane alone. + row_stride_vec = ops.mul(nr_vector_lane_vec, vlane_stride_vec) + dim = ops.add(stride_dim, ops.mul(outer_dim, row_stride_vec)) with self.override_buffer_cse(buffer=self.const_buffer, cse=self.const_cse): vlane_offset = ops.vlane_offset(vlane_vec, vlane_vec, attributes={"vlane_offset": offset}, comment="vlane offset") @@ -861,8 +933,11 @@ def index_expr(self, index, dtype): c_type = "uint64_t" new_name = f"index_expr_{compute_vec_size}" if new_name not in self.global_vars_dict: - self.header.writeline(f"{c_type} {new_name}_spad[{compute_vec_size*self.vector_lane}] __attribute__ ((section(\".spad\")));") - self.gem5_header.writeline(f"{c_type} {new_name}_spad[{compute_vec_size}] __attribute__((aligned(64)));") + # The initializer below stores two elements per iteration, so its last + # iteration writes one slot past compute_vec_size. + numel_per_lane = compute_vec_size + 1 + self.header.writeline(f"{c_type} {new_name}_spad[{numel_per_lane}] __attribute__ ((section(\".spad\")));") + self.gem5_header.writeline(f"{c_type} {new_name}_spad[{numel_per_lane*self.vector_lane}] __attribute__((aligned(64)));") self.global_vars.writeline(f"memref.global @{new_name}_spad : {tile_shape}") self.global_vars_dict[new_name] = dict() sram_var = self.spad_cse.generate(self.spad_buffer, f"memref.get_global @{new_name}_spad : {tile_shape}") @@ -888,6 +963,30 @@ def index_expr(self, index, dtype): def codegen_global_init(self): return self.global_vars + def _bind_step(self, step): + # Make `step` the current emit sink: route the body buffers to its buffers + self.current_step = step + self.applys = step.applys + self.dma_loads = step.dma_loads + self.dma_stores = step.dma_stores + self.loads = step.loads + self.compute = step.compute + self.stores = step.stores + + def push_step(self): + # New load->compute->store step; later emits land here, steps bridge via spad + step = Step( + applys=IndentedBuffer(), + dma_loads=IndentedBuffer(), dma_stores=IndentedBuffer(), + loads=IndentedBuffer(), compute=IndentedBuffer(), stores=IndentedBuffer(), + ) + self.steps.append(step) + self._bind_step(step) + self.cse = self.cse.clone() # share name counter, fresh dedup cache (region-safe) + self.target_buffer_override.set(self.compute) + self.target_cse_override.set(self.cse) + return step + def codegen_loops(self): code = mlir_common.ParallelLoopBuffer() # Loop body part @@ -920,18 +1019,18 @@ def codegen_loops(self): epilogue = reduction_loop.epilogue_line() code.writelines(reduction_lines) stack.enter_context(code.indent(attribute="{accumulation_loop=true}", suffix=epilogue)) - code.splice(self.applys) - code.splice(self.indexed_buffer) - code.splice(self.dma_loads) - # Compute body - code.writelines(self.compute_body_loop.lines()) - with contextlib.ExitStack() as stack: - stack.enter_context(code.indent(attribute="{inner_loop=false}",suffix=self.compute_body_loop.epilogue_line())) - code.splice(self.masks) - code.splice(self.loads) - code.splice(self.compute) - code.splice(self.stores) - code.splice(self.dma_stores) + for step in self.steps: + code.splice(step.applys) + code.splice(step.dma_loads) + # Compute body -- only steps that have one get the loop + epilogue + if any(b.getvalue() for b in (step.loads, step.compute, step.stores)): + code.writelines(self.compute_body_loop.lines()) + with contextlib.ExitStack() as stack: + stack.enter_context(code.indent(attribute="{inner_loop=false}",suffix=self.compute_body_loop.epilogue_line())) + code.splice(step.loads) + code.splice(step.compute) + code.splice(step.stores) + code.splice(step.dma_stores) code.splice(self.reductions_suffix) # Non-outerloop end code.writeline(f"return") @@ -1120,28 +1219,23 @@ def codegen_nodes(self, nodes, kernel_name): src_code, meta_code = super().codegen_nodes(nodes, kernel_name) self._prepare_simulator_headers(src_code) if "autotune" in extension_config.codegen_mapping_strategy and extension_config.pytorchsim_timing_mode: - optimal_src_code, meta_code = self.autotune(nodes, kernel_name)[:2] + # Use temporaries: autotune returns [None, None, None] when it cannot + # autotune (e.g. a size-1 pointwise kernel with ranges == [1]), and + # unpacking into meta_code would clobber the valid arg_attributes that + # the fall-through below returns. + optimal_src_code, optimal_meta_code = self.autotune(nodes, kernel_name)[:2] if optimal_src_code is not None: - return optimal_src_code, meta_code + return optimal_src_code, optimal_meta_code return src_code, meta_code def _prepare_simulator_headers(self, src_code): - from filelock import FileLock - - write_path = extension_codecache.get_write_path(src_code) - os.makedirs(write_path, exist_ok=True) - - spike_write_path = os.path.join(write_path, "global_var.h") - gem5_write_path = os.path.join(write_path, "gem5_global_var.h") - spad_end_symbol = "int spad_end[0] __attribute__ ((section(\".spad\")));\n" spad_section_end_symbol = ( f"int spad_section_end[0] __attribute__ ((section(\".spad\"), aligned({self.spad_info['spad_size']*self.vector_lane})));" ) - lock = FileLock(extension_codecache.get_lock_path(write_path), timeout=extension_codecache.LOCK_TIMEOUT) - with lock: - write_atomic(spike_write_path, self.header.getvalue() + spad_end_symbol + spad_section_end_symbol) - write_atomic(gem5_write_path, self.gem5_header.getvalue()) + spike_content = self.header.getvalue() + spad_end_symbol + spad_section_end_symbol + gem5_content = self.gem5_header.getvalue() + extension_codecache.store_header(src_code, spike_content, gem5_content) def get_arg_info(self, name): arg_info = dict() @@ -1158,7 +1252,7 @@ def get_dma_info(self, name, index, broadcast=True, store_reduction=False, buffe """ # Use loads as default if buffer is None: - buffer = self.applys if "tmp" not in str(index) else self.dma_loads + buffer = self.applys if not self._has_indirect(index) else self.dma_loads # TODO. kg_tile_desc = self.kernel_group.tile_desc @@ -1168,7 +1262,7 @@ def get_dma_info(self, name, index, broadcast=True, store_reduction=False, buffe total_dims = [int(str(i)[5:]) for i in self.itervars] local_tile_desc = mlir_common.MLIRMultiDimTile([1], self.vector_lane) local_dims.sort() # Assume that smaller index is placed in the outer loop - indirect_syms = [s for s in index.free_symbols if "tmp" in s.name] + indirect_syms = [s for s in index.free_symbols if s.name in self.indirect_symbols] index = index.subs({s: 0 for s in indirect_syms}, simultaneous=True) indirect_dims = [f"{i}" for i in indirect_syms] @@ -1239,16 +1333,23 @@ def get_dma_info(self, name, index, broadcast=True, store_reduction=False, buffe local_tile_desc.set_tile_size([kg_tile_desc.get_dim_size(dim) for dim in local_dims]) local_tile_desc.vmap.vlane_split_axis = local_vlane_split_axis local_tile_desc.vmap.vlane_stride = kg_tile_desc.vmap.vlane_stride - # Case 4. Tile is 4-D tile (e.g., Convolution epilogue) - elif len(local_dims) == 4: - is_reduction = self.reduction_depth < 3 and not store_reduction - if is_reduction: - raise NotImplementedError("Currently not implemented... ;)") - local_tile_desc.set_tile_size([kg_tile_desc.get_dim_size(dim) for dim in local_dims]) - local_tile_desc.vmap.vlane_split_axis = local_vlane_split_axis - local_tile_desc.vmap.vlane_stride = kg_tile_desc.vmap.vlane_stride + # Case 4+. Tile is 4-D or higher (Convolution epilogue, gathered attention bias, + # var_mean over an axis whose batch dims got split into many loop vars). else: - local_tile_desc.set_tile_size([kg_tile_desc.get_dim_size(dim) for dim in local_dims]) + # A reduction tile carries the reduction axis (loop dims >= reduction_depth). + # It must place that axis-group OUTERMOST in the per-lane layout so the 2-D + # [reduction | batch] multi_reduction reduces the reduction axis (not a batch + # axis). Same reorder the 3-D case does, generalized to any rank: an indirect + # attention-bias gather blocks a head*query dim-merge and leaves head in-lane, + # and a var_mean's token axis can split into several batch loop vars -- both + # leave a batch axis inner-to-reduction under the default row-major order. + is_reduction = any(d >= self.reduction_depth for d in local_dims) and not store_reduction + if is_reduction: + r = self.get_nr_rdim() + axis_order = list(range(r, len(local_dims))) + list(range(r - 1, -1, -1)) + local_tile_desc.set_tile_size([kg_tile_desc.get_dim_size(dim) for dim in local_dims], axis_order) + else: + local_tile_desc.set_tile_size([kg_tile_desc.get_dim_size(dim) for dim in local_dims]) local_tile_desc.vmap.vlane_split_axis = local_vlane_split_axis local_tile_desc.vmap.vlane_stride = kg_tile_desc.vmap.vlane_stride @@ -1285,12 +1386,87 @@ def get_dma_info(self, name, index, broadcast=True, store_reduction=False, buffe if len(self.itervars) == 1 and self.reduction_depth == 0: # In case of reduction loop only case, we will add dummy loop so shift it once dram_stride = [0] + dram_stride[:-1] - return local_tile_desc, index_var, dram_stride + + # Return the tile-axis -> loop-dim map (local_dims) so load()/store() can pass it to + # _masked_bounds for the per-dim [low, high) clamp (it needs each tile axis' loop iv). + return local_tile_desc, index_var, dram_stride, local_dims + + _FILL_BITVIEW = {torch.float32: torch.int32, torch.float16: torch.int16, + torch.bfloat16: torch.int16, torch.float64: torch.int64} + + def _masked_fill_bits(self, dtype, index): + """Raw bits for the masked-DMA tail fill = the consuming reduction's identity + (reduction_init; sum->0, max->-inf, ...) in the LOAD dtype, 0 for a non-reduction + load. Log-sum-exp exception: a sum reducing exp(input) fills its PRIMARY input's + tail with -inf (exp(-inf)=0); broadcast operands keep their finite identity. See + docs/design/masked-dma-descriptor.md.""" + node = getattr(self, "current_node", None) + if node is None or getattr(node, "node", None) is None or not node.node.get_reduction_type(): + return 0 + rtype = node.node.get_reduction_type() + is_primary = bool(set(self.itervars[self.reduction_depth:]) & index.free_symbols) + if rtype == "sum" and is_primary and any(self._origin_is_exp(o) for o in node.node.origins): + init = "-inf" + else: + init = reduction_init(rtype, dtype) + val = {"-inf": float("-inf"), "inf": float("inf")}.get(init, init) + if isinstance(val, str): # e.g. welford_reduce -> "0.0" + val = float(val) + t = torch.tensor(val, dtype=dtype) + view = self._FILL_BITVIEW.get(dtype) + bits = int(t.view(view).item()) if view is not None else int(t.item()) + return bits & ((1 << (t.element_size() * 8)) - 1) + + def _masked_bounds(self, name, index, dram_stride, local_tile_desc, is_load, buffer, local_dims): + """Per tile-axis [low, high) clamp for a masked DMA -- ONLY the trailing tail of a + non-dividing loop extent (valid GLOBAL range per axis is [0, loop_extent)). _emit_clamp + turns it into the tile-local low/high SSA vars. Returns [(tile_axis, low_var, high_var)]. + + A padded load reads out-of-bounds positions, but we do NOT clamp those here: the + consumer already yields the correct value at pad positions (a compute-side arith.select + for a padded gather, or the pad op's own fill). Reverse-engineering per-dim padding from + the single flat index offset is ill-posed -- the offset mixes the tap shift with the + padding, and under channels_last the stride-1 (channel) axis absorbs the offset + remainder, yielding an impossible clamp (e.g. [4, 8) on a size-2 channel tile) that + zeroed the whole load and made channels_last depthwise conv 99.9% wrong. See + docs/design/masked-dma-descriptor.md. + """ + tile_size = local_tile_desc.get_tile_size() + axes = [] + for d, k in enumerate(local_dims): + if d >= len(tile_size) or k >= len(self.ranges): + continue + iv = str(self.itervars[k]) + glo, ghi = 0, int(self.ranges[k]) + axes.append((d, iv, glo, ghi, int(tile_size[d]))) + return self._emit_clamp(axes, buffer) + + def _emit_clamp(self, axes, buffer): + """Emit the per-axis dynamic clamp. axes: [(tile_axis, base_iv, glo, ghi, tile), ...] + -- low = max(0, glo - base), high = min(tile, ghi - base) as affine.max/affine.min of + the loop iv so the last partial tile and the pad borders fall out per iteration. + Returns [(tile_axis, low_var, high_var), ...] for the non-trivial axes only.""" + result = [] + for d, iv, glo, ghi, tile in axes: + if glo == 0 and ghi % tile == 0: # every tile fully valid -> no clamp + continue + high_var = self.apply_cse.generate( + buffer, f"affine.min affine_map<(d0) -> ({tile}, {ghi} - d0)>(%{iv})") + self.register_var_info(high_var, [1, "index"]) + if glo > 0: + low_var = self.apply_cse.generate( + buffer, f"affine.max affine_map<(d0) -> (0, {glo} - d0)>(%{iv})") + self.register_var_info(low_var, [1, "index"]) + else: + low_var = self.get_const_cse(0) + result.append((d, low_var, high_var)) + return result def emit_transfer(self, dma_type_name, vlane_split_axis, vlane_stride, mlir_dtype, dram_var, dram_index_var, sram_var, sram_index_var, dram_shape, tile_shape, dram_stride, tile_stride, padding, - subtile_size=None, async_type=None): + subtile_size=None, async_type=None, offset=None, masked_bounds=None, masked_fill=0, + accumulate=False, acc_float=False): """Emit a generic togsim.transfer op for a DMA whose access exceeds the 4D Gemmini descriptor limit. Carries the full N-D access (dram/tile strides + shapes) plus the SSA operands a memref.dma_start needs @@ -1331,12 +1507,32 @@ def emit_transfer(self, dma_type_name, vlane_split_axis, vlane_stride, mlir_dtyp if subtile_size: av = int(async_type) if async_type is not None else 1 attrs += f', subtile_size = {list(subtile_size)}, async = {av} : i64' - # operands: dram, dram_idx, sram, sram_idx, tag, dma_type, vlane_stride - return ( - f'"togsim.transfer"(%{dram_var}, %{dram_index_var}, %{sram_var}, %{zero_cse}, ' - f'%{tag}, %{dma_type}, %{vst}) {{{attrs}}} : ' - f'({dram_shape}, index, {tile_shape}, index, memref<1xi32>, index, index) -> ()' - ) + if accumulate: # index_add: MVOUT does out[idx] += val (float or integer add) + attrs += f', accumulate = true' + if acc_float: + attrs += f', acc_float = true' + # operands: dram, dram_idx, sram, sram_idx, tag, tag_idx, dma_type, vlane_stride [, offset spad] + operands = (f'%{dram_var}, %{dram_index_var}, %{sram_var}, %{zero_cse}, ' + f'%{tag}, %{zero_cse}, %{dma_type}, %{vst}') + optypes = f'{dram_shape}, index, {tile_shape}, index, memref<1xi32>, index, index, index' + if offset is not None: # indirect: per-position offset spad (decompose lifts it to a symbol attr) + offset_buf, offset_type, offset_stride = offset + operands += f', %{offset_buf}' + optypes += f', {offset_type}' + attrs += f', indirect = true, offset_stride = {int(offset_stride)} : i64' + # masked-DMA dynamic clamp: append (low, high) index operands per clamped tile axis; + # masked_axes names the tile axis of each pair so the lowering writes the runtime + # values into the descriptor's dim_low/dim_high before the DMA. See _masked_bounds. + if masked_bounds: + axes = [d for d, _lo, _hi in masked_bounds] + for _d, lo, hi in masked_bounds: + operands += f', %{lo}, %{hi}' + optypes += ', index, index' + attrs += f', masked_axes = {axes}' + # box-excluded positions are filled with the consuming reduction's identity + # (0/1/-inf/+inf, per dtype); 0 for non-reduction loads. See _masked_fill_bits. + attrs += f', masked_fill = {int(masked_fill)} : i64' + return f'"togsim.transfer"({operands}) {{{attrs}}} : ({optypes}) -> ()' def allocate_sram_buffer(self, dtype, dram_name, tile_desc, raw_index, buffer=None, forced_name=None): c_type = mlir_common.DTYPE_TO_C[dtype] @@ -1410,85 +1606,92 @@ def get_mask(self): upper_bound = ops.constant(self.compute_body_loop.size, "index") step_vec = ops.step(self.compute_body_loop.step, "index") - with self.override_buffer_cse(buffer=self.masks, cse=self.mask_cse): + with self.override_buffer_cse(buffer=self.compute, cse=self.mask_cse): gap = ops.sub(upper_bound, self.compute_idx) gap_vec = ops.broadcast(gap, self.compute_body_loop.step) mask_var = ops.lt(step_vec, gap_vec) return mask_shape, mask_var def convert_indirect_indexing(self, index :sympy.Expr): - if "tmp" not in str(index): + if not self._has_indirect(index): return index, None - # Note: In case of indirect indexing, dimensions should be divisible by tile size - if not self.kernel_group.tile_desc.is_dim_dividable(self.ranges): - new_tile_size = self.kernel_group.tile_desc.adjust_tile_to_divisible(self.ranges) - self.kernel_group.tile_desc.set_tile_size(new_tile_size) - self.reset("recompile") - raise mlir_common.RecompileSignal(f"Indirect access (tile size {self.kernel_group.tile_desc.get_tile_size()} is not divisible by {self.ranges})") - # Process start - indirect_dims = [str(dim) for dim in index.free_symbols if "tmp" in str(dim)] + indirect_dims = [str(dim) for dim in index.free_symbols if str(dim) in self.indirect_symbols] indirect_dims.sort() first_dim = indirect_dims[0] spad_vars = dict() compute_dependecy = any([target_dim not in self.spad_buffer_dict for target_dim in indirect_dims]) - target_dma_buffers = self.dma_stores if compute_dependecy else self.dma_loads - - # Load indirect operands + # Store each newly-produced indirect index into spad, in its producing step for target_dim in indirect_dims: if target_dim in self.spad_buffer_dict: - sram_var, _, tile_numel_per_lane, sram_index_var, tile_shape, vshape = self.spad_buffer_dict[target_dim] - else: - # FIXME. - var_info = [v for k, v in self.var_info.items() if str(k) == target_dim][0] - dtype = mlir_common.MLIR_TO_DTYPE[var_info[1]] - - local_tile_desc = self.kernel_group.tile_desc - tile_numel_per_lane = local_tile_desc.get_numel_per_lane() - tile_shape = local_tile_desc.get_mlir_shape(var_info[1]) - tile_vec = local_tile_desc.get_compute_vec_size() - vshape = f"vector<{var_info[0]}x{var_info[1]}>" - sram_var, sram_index_var = self.get_scratchpad_buffer(dtype, target_dim, local_tile_desc, target_dim) - self.spad_buffer_dict[target_dim] = [sram_var, local_tile_desc.get_tile_size(), tile_numel_per_lane, sram_index_var, tile_shape, vshape] - - # Store the indirect index variable - target_var = self.cse.varname_map[target_dim] - compute_index_var = ",".join(sram_index_var.split(",")[:-1] + [f"%{self.compute_idx}"]) - with self.override_buffer_cse(buffer=self.stores): - ops._store(target_var, sram_var, compute_index_var, tile_shape) - mlir_dtype = vshape.split("x")[1][:-1] - with self.override_buffer_cse(buffer=target_dma_buffers): - out = ops._load(tile_numel_per_lane, mlir_dtype, sram_var, sram_index_var, tile_shape) - spad_vars[target_dim] = out + continue + var_info = [v for k, v in self.var_info.items() if str(k) == target_dim][0] + dtype = mlir_common.MLIR_TO_DTYPE[var_info[1]] + local_tile_desc = self.kernel_group.tile_desc + tile_numel_per_lane = local_tile_desc.get_numel_per_lane() + tile_shape = local_tile_desc.get_mlir_shape(var_info[1]) + tile_vec = local_tile_desc.get_compute_vec_size() + vshape = f"vector<{var_info[0]}x{var_info[1]}>" + sram_var, sram_index_var = self.get_scratchpad_buffer(dtype, target_dim, local_tile_desc, target_dim) + self.spad_buffer_dict[target_dim] = [sram_var, local_tile_desc.get_tile_size(), tile_numel_per_lane, sram_index_var, tile_shape, vshape] + target_var = self.cse.varname_map[target_dim] + compute_index_var = ",".join(sram_index_var.split(",")[:-1] + [f"%{self.compute_idx}"]) + with self.override_buffer_cse(buffer=self.stores): + ops._store(target_var, sram_var, compute_index_var, tile_shape) - with self.override_buffer_cse(buffer=target_dma_buffers): - # Apply stride + # Offset build runs after the index is in spad -> own step when just produced + if compute_dependecy: + self.push_step() + + # Single indirect dim: the raw index IS the offset; the MVIN applies offset_stride (CONFIG4) + if len(indirect_dims) == 1: + offset_stride = 1 + for arg in list(index.args): + if not self._has_indirect(arg): + continue + if arg.is_Mul and arg.args[0].is_number: + offset_stride = int(arg.args[0]) + index = index.replace(arg, 0) + # A bare indirect index (e.g. x[idx]: index IS the symbol, so index.args is empty) + # is not caught by the loop above. Zero any remaining indirect symbol so the dram + # base offset does not reference the loop-local index value (the per-position gather + # is carried by the offset spad); otherwise the DMA offset affine.apply uses %sym + # before it is defined. + index = index.subs({s: 0 for s in index.free_symbols if str(s) in self.indirect_symbols}) + sram_var, _, _, _, tile_shape, _ = self.spad_buffer_dict[first_dim] + return index, (sram_var, tile_shape, offset_stride) + + # Multi indirect dim: sum the strided indices in the compute loop (chunked by compute_vec_size) + local_tile_desc = self.kernel_group.tile_desc + compute_vec_size = local_tile_desc.get_compute_vec_size() + for target_dim in indirect_dims: + sram_var, _, _, sram_index_var, tile_shape, vshape = self.spad_buffer_dict[target_dim] + mlir_dtype = vshape.split("x")[1][:-1] + compute_index_var = ",".join(sram_index_var.split(",")[:-1] + [f"%{self.compute_idx}"]) + with self.override_buffer_cse(buffer=self.loads): + spad_vars[target_dim] = ops._load(compute_vec_size, mlir_dtype, sram_var, compute_index_var, tile_shape) + with self.override_buffer_cse(buffer=self.compute): for arg in index.args: - if "tmp" not in str(arg): + if not self._has_indirect(arg): continue if arg.is_Mul and arg.args[0].is_number: coeff_dtype = self.var_info[spad_vars[str(arg.args[1])]][1] coeff = self.get_const_cse(int(arg.args[0]), coeff_dtype) spad_vars[str(arg.args[1])] = ops.mul(spad_vars[str(arg.args[1])], coeff) index = index.replace(arg, 0) - - # Sum for dim, var in spad_vars.items(): if dim == first_dim: continue spad_vars[first_dim] = ops.add(spad_vars[first_dim], var) - - # Store index var - sram_var, _, tile_numel_per_lane, sram_index_var, tile_shape, vshape = self.spad_buffer_dict[first_dim] - mlir_dtype = vshape.split("x")[1][:-1] - with self.override_buffer_cse(buffer=target_dma_buffers): - ops._store(spad_vars[first_dim], sram_var, sram_index_var, tile_shape) # FIXME. Maybe require fine grain compute... - - # Conversion - mlir_dtype = self.var_info[spad_vars[first_dim]][1] - with self.override_buffer_cse(buffer=target_dma_buffers): - out = ops._load(1, mlir_dtype, sram_var, sram_index_var, tile_shape) - if mlir_dtype != "index": - out = ops.index_cast(out, "index") - return index + sympy.Symbol(str(out)), compute_dependecy + # Summed offset goes to a DEDICATED spad (not an index buffer) to avoid clobbering a live index + var_info = [v for k, v in self.var_info.items() if str(k) == first_dim][0] + dtype = mlir_common.MLIR_TO_DTYPE[var_info[1]] + off_shape = local_tile_desc.get_mlir_shape(var_info[1]) + off_sram, off_index = self.get_scratchpad_buffer( + dtype, "indirect_offset_" + first_dim, local_tile_desc, "indirect_offset_" + first_dim) + off_compute_index = ",".join(off_index.split(",")[:-1] + [f"%{self.compute_idx}"]) + with self.override_buffer_cse(buffer=self.stores): + ops._store(spad_vars[first_dim], off_sram, off_compute_index, off_shape) + self.push_step() # offset-build compute loop must finish before the gather reads it + return index, (off_sram, off_shape, 1) diff --git a/PyTorchSimFrontend/mlir/mlir_common.py b/PyTorchSimFrontend/mlir/mlir_common.py index a70d1c7d..9d610bdc 100644 --- a/PyTorchSimFrontend/mlir/mlir_common.py +++ b/PyTorchSimFrontend/mlir/mlir_common.py @@ -50,7 +50,8 @@ torch.int8: "i8", torch.uint8: "i8", torch.bool: "i8", - torch.bfloat16: "bf16", + torch.bfloat16: "bf16", # present only to keep the dtype table total; bf16 is not + # actually supported (Spike has no bf16 and op-select rejects it) } MLIR_TO_DTYPE = { @@ -324,41 +325,6 @@ def apply_divisor(self, axis: int, divisor: int, mode: str = "split"): raise ValueError(f"Unknown mode: {mode}. Supported: 'pad', 'split'.") - def is_dim_dividable(self, dim_sizes: list[int]) -> bool: - if len(dim_sizes) != len(self._tile_size): - raise ValueError("dim_sizes must match the tile size dimensions") - - dim_sizes_cpy = list(dim_sizes) - axis, stride = self.vmap.vlane_split_axis, self.vmap.vlane_stride - remain = dim_sizes_cpy[axis] % stride - if remain: - dim_sizes_cpy[axis] += stride - remain - - return all(d % t == 0 for d, t in zip(dim_sizes_cpy, self._tile_size)) - - def adjust_tile_to_divisible(self, dim_sizes: list[int]) -> list[int]: - """Adjust current tile to be divisible by given dimensions.""" - if len(dim_sizes) != len(self._tile_size): - raise ValueError("dim_sizes must match the tile size dimensions") - - def _adjust_one(dim_size, tile_size): - for candidate in range(tile_size, 0, -1): - if dim_size % candidate == 0: - return candidate - return 1 - - candidate_tile_size = [_adjust_one(d, t) for d, t in zip(dim_sizes, self._tile_size)] - for i in range(len(candidate_tile_size)): - self.tile_constraint[i].must_divide_dim = True - - axis, stride = self.vmap.vlane_split_axis, self.vmap.vlane_stride - remain = candidate_tile_size[axis] % stride - - if remain: - # #201: relax vlane_stride constraints - self.vmap.vlane_stride = 1 - return candidate_tile_size - def scale_tile_dim(self, axis, dim_sz, scale_factor=2): axis_constrinat = self.tile_constraint[axis] current_sz = self._tile_size[axis] @@ -395,8 +361,6 @@ def trim_large_tail(self, ranges: list[int]): constraint = self.tile_constraint[i] if constraint.fixed: continue - elif constraint.must_divide_dim: - BETA = 0 padding_ratio = TileAdjustMixin.get_padding_ratio(tile_range, dim_range) if padding_ratio < self.tail_ratio_threshold: @@ -447,7 +411,8 @@ def init_tile_size(ranges, vlane_stride, vector_lane): return [1] tile_size = [1] * nr_dim if nr_dim == 1: - tile_size[0] = 1 if ranges[0] == 1 else 2 * vlane_stride * vector_lane + # Cap to extent so the tile never over-reads the DRAM buffer (extent 128 vs tile 512 -> 384 garbage folded into the reduction). No-op when extent >= tile. + tile_size[0] = 1 if ranges[0] == 1 else min(2 * vlane_stride * vector_lane, ranges[0]) elif nr_dim == 2: tile_size[-1] = vlane_stride * vector_lane tile_size[-2] = 2 * vector_lane @@ -469,23 +434,14 @@ def get_padding_ratio(tile_range: int, dim_range: int) -> float: @dataclass class TileConstraint: multiple_of: int = 1 - must_divide_dim: bool = False fixed: bool = False def adjust(self, old: int, new: int, dim: int) -> int: if self.fixed: return old # Fixed tile size - tail = new % self.multiple_of - new -= tail - if not self.must_divide_dim: - return max(new, self.multiple_of) - - while new > 0: - if dim % new == 0: - return new - new -= self.multiple_of - raise extension_codecache.TileSizeError("Cannot find suitable tile size under the given constraints.") + new -= new % self.multiple_of + return max(new, self.multiple_of) class MLIRMultiDimTile(TileAdjustMixin): def __init__(self, tile_size, vector_lane, vlane_split_axis=None, vlane_stride=None, forced_vec_size=None): diff --git a/PyTorchSimFrontend/mlir/mlir_conv_common.py b/PyTorchSimFrontend/mlir/mlir_conv_common.py index d577dbd8..b1c93f3b 100644 --- a/PyTorchSimFrontend/mlir/mlir_conv_common.py +++ b/PyTorchSimFrontend/mlir/mlir_conv_common.py @@ -14,7 +14,6 @@ def __init__(self, input_nodes, layout, input_reorder=None, **kwargs): super().__init__("kernel", input_nodes, layout, input_reorder) self.support_epilogue_fusion = True self.support_prologue_fusion = False - self.support_reduction_fusion = False self.stride = kwargs["stride"] self.padding = kwargs["padding"] self.dilation = kwargs["dilation"] diff --git a/PyTorchSimFrontend/mlir/mlir_conv_mt_template.py b/PyTorchSimFrontend/mlir/mlir_conv_mt_template.py index 8b8288a8..7964da0f 100644 --- a/PyTorchSimFrontend/mlir/mlir_conv_mt_template.py +++ b/PyTorchSimFrontend/mlir/mlir_conv_mt_template.py @@ -143,6 +143,10 @@ def render(self, TOG_latency = O_W if TILE_M > O_W else TILE_M TOG_latency = 8 if TOG_latency < 8 else TOG_latency kernel.loop_size = [TOG_latency, TILE_N, TILE_K] + # Real extent of each structural loop iv, for the masked-DMA clamp (def_dma_op). + # This template fuses channel and kernel-width into tile_k (loops 0..I_C*K_W). + kernel.loop_extents = {"tile_m": BATCH, "tile_n": O_C, "o_h": O_H, "o_w": O_W, + "k_h": K_H, "tile_k": I_C * K_W} # Prepare tile descriptors vlane_stride = 1 diff --git a/PyTorchSimFrontend/mlir/mlir_conv_sb_template.py b/PyTorchSimFrontend/mlir/mlir_conv_sb_template.py index 92efff66..dfca23ec 100644 --- a/PyTorchSimFrontend/mlir/mlir_conv_sb_template.py +++ b/PyTorchSimFrontend/mlir/mlir_conv_sb_template.py @@ -144,6 +144,9 @@ def render(self, TOG_latency = O_W if TILE_M > O_W else TILE_M TOG_latency = 8 if TOG_latency < 8 else TOG_latency kernel.loop_size = [TOG_latency, TILE_N, TILE_K] + # Real extent of each structural loop iv, for the masked-DMA clamp (def_dma_op). + kernel.loop_extents = {"tile_n": O_C, "o_h": O_H, "tile_m": O_W, + "k_h": K_H, "k_w": K_W, "tile_k": I_C} # Prepare tile descriptors vlane_stride = 1 vlane_split_axis = 1 diff --git a/PyTorchSimFrontend/mlir/mlir_conv_sbs_template.py b/PyTorchSimFrontend/mlir/mlir_conv_sbs_template.py index dfd418d9..f1a42964 100644 --- a/PyTorchSimFrontend/mlir/mlir_conv_sbs_template.py +++ b/PyTorchSimFrontend/mlir/mlir_conv_sbs_template.py @@ -144,6 +144,9 @@ def render(self, TOG_latency = O_W if TILE_M > O_W else TILE_M TOG_latency = 8 if TOG_latency < 8 else TOG_latency kernel.loop_size = [TOG_latency, TILE_N, TILE_K] + # Real extent of each structural loop iv, for the masked-DMA clamp (def_dma_op). + kernel.loop_extents = {"tile_n": O_C, "o_h": O_H, "tile_m": O_W, + "k_h": K_H, "k_w": K_W, "tile_k": I_C} # Prepare tile descriptors vlane_stride = 1 diff --git a/PyTorchSimFrontend/mlir/mlir_conv_template.py b/PyTorchSimFrontend/mlir/mlir_conv_template.py index 178ba7c6..8bb64d48 100644 --- a/PyTorchSimFrontend/mlir/mlir_conv_template.py +++ b/PyTorchSimFrontend/mlir/mlir_conv_template.py @@ -147,6 +147,9 @@ def render(self, TOG_latency = BATCH if TILE_M > BATCH else TILE_M TOG_latency = 8 if TOG_latency < 8 else TOG_latency kernel.loop_size = [TOG_latency, TILE_N, TILE_K] + # Real extent of each structural loop iv, for the masked-DMA clamp (def_dma_op). + kernel.loop_extents = {"tile_m": BATCH, "tile_n": O_C, "o_h": O_H, "o_w": O_W, + "k_h": K_H, "k_w": K_W, "tile_k": I_C} # Prepare tile descriptors vlane_stride = 1 diff --git a/PyTorchSimFrontend/mlir/mlir_decomposition.py b/PyTorchSimFrontend/mlir/mlir_decomposition.py index a0030e3b..ea7a7ebb 100644 --- a/PyTorchSimFrontend/mlir/mlir_decomposition.py +++ b/PyTorchSimFrontend/mlir/mlir_decomposition.py @@ -371,4 +371,56 @@ def decompose_native_multi_head_attention( attn_weights_mean = attn_weights.mean(dim=1) # Average over heads return output, attn_weights_mean else: - return (output, None) \ No newline at end of file + return (output, None) + + +# Lower roll ourselves as narrow + cat, then REALIZE the result. roll has no Inductor lowering; it +# is decomposed (torch's default is index_select(fmod(...)), i.e. a modular gather the affine-only +# DMA cannot express). Even our narrow+cat rewrite lets the slice offset fuse into a downstream +# modular reshape, re-creating a shifted index like (p+60)%8. copy_input forces a hard buffer +# boundary so the consumer reads a plain affine index -- a plain .contiguous()/clone is inlined by +# Inductor and does NOT create the boundary. Remove roll from the decomp table so it reaches this +# lowering instead of being decomposed first. +from torch._inductor.decomposition import decompositions as _inductor_decompositions +from torch._inductor import lowering as _ind_lowering +from torch._inductor import ir as _ind_ir + +_inductor_decompositions.pop(aten.roll.default, None) + + +def _roll_lowering(x, shifts, dims=()): + if not isinstance(shifts, (list, tuple)): + shifts = (shifts,) + if not isinstance(dims, (list, tuple)): + dims = (dims,) + slice_l = _ind_lowering.lowerings[aten.slice.Tensor] + cat_l = _ind_lowering.lowerings[aten.cat.default] + view_l = _ind_lowering.lowerings[aten.view.default] + + # Realize the INPUT: roll's producer is often a reshaped view (e.g. swinv2's window_reverse), + # and our slice's offset would otherwise fuse into that reshape's modular index. Reading a + # materialized buffer makes each slice a plain contiguous read. + x = _ind_ir.ExternKernel.copy_input(x) + + def roll_dim(t, shift, dim): + n = int(t.get_size()[dim]) + s = int(shift) % n + if s == 0: + return t + front = slice_l(t, dim, n - s, n) # narrow(t, dim, n-s, s) + back = slice_l(t, dim, 0, n - s) + return cat_l([front, back], dim) + + if len(dims) == 0: + numel = 1 + for d in x.get_size(): + numel *= int(d) + result = view_l(roll_dim(view_l(x, [numel]), shifts[0], 0), list(x.get_size())) + else: + result = x + for shift, dim in zip(shifts, dims): + result = roll_dim(result, shift, dim) + return _ind_ir.ExternKernel.copy_input(result) + + +_ind_lowering.lowerings[aten.roll.default] = _roll_lowering \ No newline at end of file diff --git a/PyTorchSimFrontend/mlir/mlir_gemm_template.py b/PyTorchSimFrontend/mlir/mlir_gemm_template.py index 8a8cd585..6fb2b9bc 100644 --- a/PyTorchSimFrontend/mlir/mlir_gemm_template.py +++ b/PyTorchSimFrontend/mlir/mlir_gemm_template.py @@ -103,11 +103,13 @@ """ class MLIRGemmTemplate(MLIRTemplate): + # 2-D frame (M rows x N cols): one row index + the reduced N index. + REDUCTION_EPILOGUE_ALIASING = {"index0": "index1", "index1": "index0"} + def __init__(self, input_nodes, layout, input_reorder=None): super().__init__("kernel", input_nodes, layout, input_reorder) self.support_epilogue_fusion = True self.support_prologue_fusion = True - self.support_reduction_fusion = True def render(self, kernel: MLIRTemplateKernel, @@ -130,7 +132,7 @@ def render(self, epilogue_dim_aliasing = {} elif n_epilogue_node>=1 and epilogue_nodes[0].is_reduction(): template = GEMM_REDUCTION_TEMPLATE - epilogue_dim_aliasing = {"index0":"index1", "index1":"index0"} + epilogue_dim_aliasing = self.REDUCTION_EPILOGUE_ALIASING nr_rdim = 1 else: template = GEMM_TEMPLATE @@ -329,7 +331,7 @@ def select_tile(self, kernel, M, N, K, n_extra_node, n_extra_read, n_prologue_no else: # case 2: use heuristic mapping min_tile = (n_extra_node + n_prologue_node) == 0 - tile_candidates = kernel.gemm_combination_mapping(M, N, K, max(n_extra_read-2, 0), n_prologue_node, min_tile=True, precision_bytes=precision_bytes) + tile_candidates = kernel.gemm_combination_mapping(M, N, K, n_extra_node + n_extra_read, n_prologue_node, min_tile=True, precision_bytes=precision_bytes) # Edge case if (M == 0) or (N == 0) or (K == 0): diff --git a/PyTorchSimFrontend/mlir/mlir_lowering.py b/PyTorchSimFrontend/mlir/mlir_lowering.py index 7f33d956..34f40f68 100644 --- a/PyTorchSimFrontend/mlir/mlir_lowering.py +++ b/PyTorchSimFrontend/mlir/mlir_lowering.py @@ -324,6 +324,19 @@ def _mlir_custom_sort_default( stable=stable_required, ) sorted_values = mlir_template.generate(template_buffer_node=value).output_node() + + def _unwrap(t): + t = t.data if isinstance(t, ir.TensorBox) else t + t = t.data if isinstance(t, ir.StorageBox) else t + return t + # The sort kernel writes `indices` in place (mlir_sort_template make_inplace), but only + # `sorted_values` is a scheduler-visible output. Advertise the indices write as a + # MutationOutput OWNED by the sort op (see MLIRTemplateBuffer) so the scheduler keeps the + # kernel alive when only indices are consumed (argsort: the values output is dead and + # would otherwise DCE the whole sort). + sort_op = _unwrap(sorted_values) + idx_buf = _unwrap(indices) + sort_op.add_mutation_output(ir.MutationOutput(idx_buf.get_layout(), idx_buf, sort_op)) return sorted_values, indices diff --git a/PyTorchSimFrontend/mlir/mlir_ops.py b/PyTorchSimFrontend/mlir/mlir_ops.py index f1fb4186..98e0272b 100644 --- a/PyTorchSimFrontend/mlir/mlir_ops.py +++ b/PyTorchSimFrontend/mlir/mlir_ops.py @@ -13,10 +13,15 @@ def reduction_combine_vec(reduction_type, vector_value, init_value, axis, shape, return f"vector.multi_reduction , %{vector_value}, %{init_value} [{axis}] : {shape} to {reduced_shape}" if reduction_type == "prod": return f"vector.multi_reduction , %{vector_value}, %{init_value} [{axis}] : {shape} to {reduced_shape}" + # element type of the reduced vector (e.g. "vector<8x2xi64>" -> "i64"); int max/min use + # the signed-integer reduction kinds, not the float ones (maximumf/minimumf reject ints). + _is_int = shape.rsplit("x", 1)[-1].rstrip(">").strip().startswith("i") if reduction_type == "max": - return f"vector.multi_reduction , %{vector_value}, %{init_value} [{axis}] : {shape} to {reduced_shape}" + kind = "maxsi" if _is_int else "maximumf" + return f"vector.multi_reduction <{kind}>, %{vector_value}, %{init_value} [{axis}] : {shape} to {reduced_shape}" if reduction_type == "min": - return f"vector.multi_reduction , %{vector_value}, %{init_value} [{axis}] : {shape} to {reduced_shape}" + kind = "minsi" if _is_int else "minimumf" + return f"vector.multi_reduction <{kind}>, %{vector_value}, %{init_value} [{axis}] : {shape} to {reduced_shape}" if reduction_type == "any": return f"vector.multi_reduction , %{vector_value}, %{init_value} [{axis}] : {shape} to {reduced_shape}" raise AssertionError(reduction_type) @@ -145,7 +150,7 @@ def where(condition, operand1, operand2, *args, **kwargs): operand2 = ops.broadcast(operand2, cond_type[0]) tile_size, ret_type = V.kernel.var_info[operand1] shape = f"vector<{tile_size}x{ret_type}>" if tile_size > 1 else ret_type - cond_shape = f"vector<{tile_size}xi1>" if tile_size > 1 else "" + cond_shape = f"vector<{tile_size}xi1>" if tile_size > 1 else "i1" op_str = f"arith.select %{condition}, %{operand1}, %{operand2}" shape = f"{cond_shape}, {shape}" @@ -309,7 +314,10 @@ def binary_elementwise_common(operand1, operand2): @staticmethod def abs(operand, *args, **kwargs): - raise NotImplementedError + tile_size, dtype = V.kernel.var_info[operand] + shape = f"vector<{tile_size}x{dtype}>" if tile_size > 1 else dtype + opcode = "math.absf" if dtype.startswith("f") else "math.absi" + return format_mlir_op(f'{opcode} %{operand}', shape, **kwargs), [tile_size, dtype] @staticmethod def exp(operand, *args, **kwargs): @@ -463,68 +471,263 @@ def erf(operand, *args, **kwargs): @staticmethod def cosh(operand, *args, **kwargs): - raise NotImplementedError + tile_size, dtype = V.kernel.var_info[operand] + + # Check scalar + if tile_size == 1: + operand = ops.broadcast(operand, 4) + val = ops.cosh(operand) + result = ops.extractelement(val, 0) + return result, V.kernel.var_info[result] + + # Float-only instruction: promote non-float inputs (e.g. integers) to f32 + # to run it. Native float widths (f16/f64) are left untouched. + if not dtype.startswith("f"): + operand = ops.to_dtype(operand, "f32") + dtype = "f32" + + exp_pos = ops.exp(operand) + exp_neg = ops.exp(ops.neg(operand)) + + sum_exp = ops.add(exp_pos, exp_neg) + half_const = ops.constant(0.5, dtype) + + res = ops.mul(sum_exp, half_const) + return res, V.kernel.var_info[res] @staticmethod def sinh(operand, *args, **kwargs): - raise NotImplementedError + tile_size, dtype = V.kernel.var_info[operand] + + # Check scalar + if tile_size == 1: + operand = ops.broadcast(operand, 4) + val = ops.sinh(operand) + result = ops.extractelement(val, 0) + return result, V.kernel.var_info[result] + + # Float-only instruction: promote non-float inputs (e.g. integers) to f32 + # to run it. Native float widths (f16/f64) are left untouched. + if not dtype.startswith("f"): + operand = ops.to_dtype(operand, "f32") + dtype = "f32" + + exp_pos = ops.exp(operand) + exp_neg = ops.exp(ops.neg(operand)) + + sub_exp = ops.sub(exp_pos, exp_neg) + half_const = ops.constant(0.5, dtype) + + res = ops.mul(sub_exp, half_const) + return res, V.kernel.var_info[res] @staticmethod def tanh(operand, *args, **kwargs): op_type = V.kernel.var_info[operand] + tile_size = op_type[0] + dtype = op_type[1] # Check scalar - op_type = V.kernel.var_info[operand] if op_type[0] == 1: operand = ops.broadcast(operand, 4) val = ops.tanh(operand) result = ops.extractelement(val, 0) return result, V.kernel.var_info[result] - op_type = V.kernel.var_info[operand] - tile_size = op_type[0] - dtype = op_type[1] - # Type check & auto cast - if dtype.startswith("f"): + # Float-only instruction: promote non-float inputs (e.g. integers) to f32 + # to run it. Native float widths (f16/f64) are left untouched. + if not dtype.startswith("f"): operand = ops.to_dtype(operand, "f32") + dtype = "f32" shape = f"vector<{tile_size}x{dtype}>" if tile_size > 1 else dtype return format_mlir_op(f'math.tanh %{operand}', shape, **kwargs), [tile_size, dtype] @staticmethod def acos(operand, *args, **kwargs): - raise NotImplementedError + tile_size, dtype = V.kernel.var_info[operand] + + # Check scalar + if tile_size == 1: + operand = ops.broadcast(operand, 4) + val = ops.acos(operand) + result = ops.extractelement(val, 0) + return result, V.kernel.var_info[result] + + # Float-only instruction: promote non-float inputs (e.g. integers) to f32 + # to run it. Native float widths (f16/f64) are left untouched. + if not dtype.startswith("f"): + operand = ops.to_dtype(operand, "f32") + dtype = "f32" + + asin_val = ops.asin(operand) + res = ops.sub(ops.constant(math.pi / 2, dtype), asin_val) + return res, V.kernel.var_info[res] @staticmethod def acosh(operand, *args, **kwargs): - raise NotImplementedError + tile_size, dtype = V.kernel.var_info[operand] + + # Check scalar + if tile_size == 1: + operand = ops.broadcast(operand, 4) + val = ops.acosh(operand) + result = ops.extractelement(val, 0) + return result, V.kernel.var_info[result] + + # Float-only instruction: promote non-float inputs (e.g. integers) to f32 + # to run it. Native float widths (f16/f64) are left untouched. + if not dtype.startswith("f"): + operand = ops.to_dtype(operand, "f32") + dtype = "f32" + + x2 = ops.square(operand) + val = ops.sub(x2, ops.constant(1.0, dtype)) + sqrt_val = ops.sqrt(val) + sum_val = ops.add(operand, sqrt_val) + + res = ops.log(sum_val) + return res, V.kernel.var_info[res] @staticmethod def asin(operand, *args, **kwargs): - raise NotImplementedError + tile_size, dtype = V.kernel.var_info[operand] + + # Check scalar + if tile_size == 1: + operand = ops.broadcast(operand, 4) + val = ops.asin(operand) + result = ops.extractelement(val, 0) + return result, V.kernel.var_info[result] + + # Float-only instruction: promote non-float inputs (e.g. integers) to f32 + # to run it. Native float widths (f16/f64) are left untouched. + if not dtype.startswith("f"): + operand = ops.to_dtype(operand, "f32") + dtype = "f32" + + x2 = ops.square(operand) + denom = ops.sqrt(ops.sub(ops.constant(1.0, dtype), x2)) + res = ops.atan(ops.truediv(operand, denom)) + return res, V.kernel.var_info[res] @staticmethod def asinh(operand, *args, **kwargs): - raise NotImplementedError + tile_size, dtype = V.kernel.var_info[operand] + + # Check scalar + if tile_size == 1: + operand = ops.broadcast(operand, 4) + val = ops.asinh(operand) + result = ops.extractelement(val, 0) + return result, V.kernel.var_info[result] + + # Float-only instruction: promote non-float inputs (e.g. integers) to f32 + # to run it. Native float widths (f16/f64) are left untouched. + if not dtype.startswith("f"): + operand = ops.to_dtype(operand, "f32") + dtype = "f32" + + x2 = ops.square(operand) + val = ops.add(x2, ops.constant(1.0, dtype)) + sqrt_val = ops.sqrt(val) + sum_val = ops.add(operand, sqrt_val) + + res = ops.log(sum_val) + return res, V.kernel.var_info[res] @staticmethod def atan2(operand1, operand2, *args, **kwargs): - raise NotImplementedError + tile_size, ret_type, y, x = ExtensionOverrides.binary_elementwise_common(operand1, operand2) + if not ret_type.startswith("f"): + y = ops.to_dtype(y, "f32") + x = ops.to_dtype(x, "f32") + ret_type = "f32" + + pi = ops.constant(math.pi, ret_type) + zero = ops.constant(0.0, ret_type) + + base = ops.atan(ops.truediv(y, x)) + corrected = ops.add(base, ops.copysign(pi, y)) + res = ops.where(ops.lt(x, zero), corrected, base) + return res, [tile_size, ret_type] @staticmethod def atan(operand, *args, **kwargs): - raise NotImplementedError + tile_size, dtype = V.kernel.var_info[operand] + + # Check scalar + if tile_size == 1: + operand = ops.broadcast(operand, 4) + val = ops.atan(operand) + result = ops.extractelement(val, 0) + return result, V.kernel.var_info[result] + + # Float-only instruction: promote non-float inputs (e.g. integers) to f32 + # to run it. Native float widths (f16/f64) are left untouched. + if not dtype.startswith("f"): + operand = ops.to_dtype(operand, "f32") + dtype = "f32" + + shape = f"vector<{tile_size}x{dtype}>" if tile_size > 1 else dtype + return format_mlir_op(f'math.atan %{operand}', shape, **kwargs), [tile_size, dtype] @staticmethod def atanh(operand, *args, **kwargs): - raise NotImplementedError + tile_size, dtype = V.kernel.var_info[operand] + + # Check scalar + if tile_size == 1: + operand = ops.broadcast(operand, 4) + val = ops.atanh(operand) + result = ops.extractelement(val, 0) + return result, V.kernel.var_info[result] + + # Float-only instruction: promote non-float inputs (e.g. integers) to f32 + # to run it. Native float widths (f16/f64) are left untouched. + if not dtype.startswith("f"): + operand = ops.to_dtype(operand, "f32") + dtype = "f32" + + one_const = ops.constant(1.0, dtype) + val1 = ops.add(one_const, operand) + val2 = ops.sub(one_const, operand) + div_val = ops.truediv(val1, val2) + + half_const = ops.constant(0.5, dtype) + res = ops.mul(ops.log(div_val), half_const) + return res, V.kernel.var_info[res] @staticmethod def copysign(operand1, operand2, *args, **kwargs): - raise NotImplementedError + tile_size, ret_type, operand1, operand2 = ExtensionOverrides.binary_elementwise_common(operand1, operand2) + if not ret_type.startswith("f"): + raise ValueError("copysign is only supported for floats") + shape = f"vector<{tile_size}x{ret_type}>" if tile_size > 1 else ret_type + op_str = f'math.copysign %{operand1}, %{operand2}' + return format_mlir_op(op_str, shape, **kwargs), [tile_size, ret_type] @staticmethod def erfc(operand, *args, **kwargs): - raise NotImplementedError + """ + There is no direct MLIR operation for erfc, so we can implement it using the relationship: + erfc(x) = 1 - erf(x) + """ + op_type = V.kernel.var_info[operand] + + # Check scalar + if op_type[0] == 1: + operand = ops.broadcast(operand, 4) + val = ops.erfc(operand) + result = ops.extractelement(val, 0) + return result, V.kernel.var_info[result] + + tile_size = op_type[0] + dtype = op_type[1] + erf_val = ops.erf(operand) + one_const = ops.constant(1.0, dtype) + res = ops.sub(one_const, erf_val) + + return res, V.kernel.var_info[res] @staticmethod def erfinv(operand, *args, **kwargs): @@ -536,7 +739,15 @@ def frexp(operand, *args, **kwargs): @staticmethod def hypot(operand1, operand2, *args, **kwargs): - raise NotImplementedError + tile_size, ret_type, operand1, operand2 = ExtensionOverrides.binary_elementwise_common(operand1, operand2) + if not ret_type.startswith("f"): + raise ValueError("hypot is only supported for floats") + + x_sq = ops.square(operand1) + y_sq = ops.square(operand2) + sum_sq = ops.add(x_sq, y_sq) + res = ops.sqrt(sum_sq) + return res, V.kernel.var_info[res] @staticmethod def log10(operand, *args, **kwargs): @@ -564,12 +775,20 @@ def log2(operand, *args, **kwargs): @staticmethod def log(operand, *args, **kwargs): op_type = V.kernel.var_info[operand] + if op_type[0] == 1: + operand = ops.broadcast(operand, 4) + val = ops.log(operand) + result = ops.extractelement(val, 0) + return result, V.kernel.var_info[result] tile_size = op_type[0] dtype = op_type[1] # Type check & auto cast - if dtype.startswith("f"): + # Float-only instruction: promote non-float inputs (e.g. integers) to f32 + # to run it. Native float widths (f16/f64) are left untouched. + if not dtype.startswith("f"): operand = ops.to_dtype(operand, "f32") + dtype = "f32" shape = f"vector<{tile_size}x{dtype}>" if tile_size > 1 else dtype return format_mlir_op(f'math.log %{operand}', shape, **kwargs), [tile_size, dtype] @@ -660,11 +879,21 @@ def bitwise_xor(operand1, operand2, *args, **kwargs): @staticmethod def bitwise_left_shift(operand1, operand2, *args, **kwargs): - raise NotImplementedError + tile_size, ret_type, operand1, operand2 = ExtensionOverrides.binary_elementwise_common(operand1, operand2) + if ret_type.startswith("f"): + raise ValueError("Bitwise left shift not supported for floats") + shape = f"vector<{tile_size}x{ret_type}>" if tile_size > 1 else ret_type + op_str = f'arith.shli %{operand1}, %{operand2}' + return format_mlir_op(op_str, shape, **kwargs), [tile_size, ret_type] @staticmethod def bitwise_right_shift(operand1, operand2, *args, **kwargs): - raise NotImplementedError + tile_size, ret_type, operand1, operand2 = ExtensionOverrides.binary_elementwise_common(operand1, operand2) + if ret_type.startswith("f"): + raise ValueError("Bitwise right shift not supported for floats") + shape = f"vector<{tile_size}x{ret_type}>" if tile_size > 1 else ret_type + op_str = f'arith.shrsi %{operand1}, %{operand2}' + return format_mlir_op(op_str, shape, **kwargs), [tile_size, ret_type] @staticmethod def rsqrt(operand, *args, **kwargs): @@ -689,15 +918,51 @@ def sigmoid(operand, *args, **kwargs): @staticmethod def fmod(operand1, operand2, *args, **kwargs): - raise NotImplementedError + tile_size, ret_type, operand1, operand2 = ExtensionOverrides.binary_elementwise_common(operand1, operand2) + + if ret_type.startswith("f"): + div_val = ops.truediv(operand1, operand2) + trunc_val = ops.trunc(div_val) + mul_val = ops.mul(trunc_val, operand2) + res = ops.sub(operand1, mul_val) + return res, V.kernel.var_info[res] + else: + shape = f"vector<{tile_size}x{ret_type}>" if tile_size > 1 else ret_type + op_str = f'arith.remsi %{operand1}, %{operand2}' + return format_mlir_op(op_str, shape, **kwargs), [tile_size, ret_type] @staticmethod def isinf(operand, *args, **kwargs): - raise NotImplementedError + tile_size, dtype = V.kernel.var_info[operand] + + if dtype.startswith("f"): + abs_val = ops.abs(operand) + inf_val = ops.constant("inf", dtype) + res = ops.eq(abs_val, inf_val) + return res, V.kernel.var_info[res] + else: + const_false = ops.constant(False, "i1") + if tile_size > 1: + const_false = ops.broadcast(const_false, tile_size) + return const_false, V.kernel.var_info[const_false] @staticmethod def isnan(operand, *args, **kwargs): - raise NotImplementedError + tile_size, dtype = V.kernel.var_info[operand] + if dtype.startswith("f"): + # Unordered comparison (uno) to detect NaN (uno returns true if either operand is NaN) + operand_shape = f"vector<{tile_size}x{dtype}>" if tile_size > 1 else dtype + op_str = f"arith.cmpf uno, %{operand}, %{operand}" + res = format_mlir_op(op_str, operand_shape, **kwargs) + + V.kernel.var_info[res] = [tile_size, "i1"] + return res, [tile_size, "i1"] + else: + # Integers cannot be NaN + const_false = ops.constant(False, "i1") + if tile_size > 1: + const_false = ops.broadcast(const_false, tile_size) + return const_false, V.kernel.var_info[const_false] @staticmethod def round(operand, *args, **kwargs): @@ -723,7 +988,30 @@ def floor(operand, *args, **kwargs): @staticmethod def sign(operand, *args, **kwargs): - raise NotImplementedError + tile_size, dtype = V.kernel.var_info[operand] + + if dtype.startswith("f"): + v_zero, v_one, v_neg_one = 0.0, 1.0, -1.0 + else: + v_zero, v_one, v_neg_one = 0, 1, -1 + + const_zero = ops.constant(v_zero, dtype) + const_one = ops.constant(v_one, dtype) + const_neg_one = ops.constant(v_neg_one, dtype) + + if tile_size > 1: + const_zero = ops.broadcast(const_zero, tile_size) + const_one = ops.broadcast(const_one, tile_size) + const_neg_one = ops.broadcast(const_neg_one, tile_size) + + is_pos = ops.gt(operand, const_zero) + is_neg = ops.lt(operand, const_zero) + + V.kernel.var_info[is_pos] = [tile_size, "i1"] + V.kernel.var_info[is_neg] = [tile_size, "i1"] + + res = ops.where(is_pos, const_one, ops.where(is_neg, const_neg_one, const_zero)) + return res, V.kernel.var_info[res] @staticmethod def trunc(operand, *args, **kwargs): @@ -933,11 +1221,11 @@ def xor(operand1, operand2, *args, **kwargs): @staticmethod def lshift(operand1, operand2, *args, **kwargs): - raise NotImplementedError + return ops.bitwise_left_shift(operand1, operand2) @staticmethod def rshift(operand1, operand2, *args, **kwargs): - raise NotImplementedError + return ops.bitwise_right_shift(operand1, operand2) @staticmethod def truncdiv(operand1, operand2, *args, **kwargs): diff --git a/PyTorchSimFrontend/mlir/mlir_scheduling.py b/PyTorchSimFrontend/mlir/mlir_scheduling.py index 41ec61af..3cdac26f 100644 --- a/PyTorchSimFrontend/mlir/mlir_scheduling.py +++ b/PyTorchSimFrontend/mlir/mlir_scheduling.py @@ -1,10 +1,7 @@ import os -import math import sympy -from functools import reduce -import operator -from sympy import symbols, sympify from PyTorchSimFrontend import extension_config +from PyTorchSimFrontend import extension_codecache from PyTorchSimFrontend.mlir.mlir_codegen_backend import MLIRKernel from torch.utils._ordered_set import OrderedSet @@ -12,8 +9,6 @@ from torch._inductor.scheduler import BaseScheduling, FusedSchedulerNode, SchedulerNode, BaseSchedulerNode from torch._inductor.utils import IndentedBuffer from torch._inductor.virtualized import V -from torch._inductor.ir import LoopBody -from torch._inductor import dependencies from torch._inductor.codegen.common import BackendFeature from . import mlir_common @@ -35,33 +30,12 @@ def __init__(self, scheduler): self.max_fusion_size = 5 def can_fuse_with_exceptions(self, node1: BaseSchedulerNode, node2: BaseSchedulerNode) -> bool: + # Monkey patch: Inductor's own can_fuse never considers prologue fusion into a + # template, so intercept that one shape and ask the template about it. if not extension_config.CONFIG_FUSION_PROLOGUE: return self.scheduler.can_fuse_origin(node1, node2) - - # Extract base template node - base_template_node1 = [node for node in node1.get_nodes() if node.is_template()] - base_template_node2 = [node for node in node2.get_nodes() if node.is_template()] - - # Case 3: Prologue(Pointwise) + Tempalte - if len(base_template_node1) == 0 and len(node1.get_nodes())==1 and len(node2.get_nodes())==1 and not node1.is_reduction() and len(base_template_node2) == 1 and extension_config.CONFIG_FUSION_PROLOGUE: - target_node = base_template_node2[0].node - - # Check if template supports prologue fusion - if not getattr(target_node.template, 'support_prologue_fusion', False): - return False - - if len(node1.read_writes.writes) != 1: - return False - if node1.node not in target_node.inputs or any(["view" in str(ori) for ori in node1.node.origins]): #FIXME - return False - - # We don't fuse this edge case... - if base_template_node2[0].group[1][0][0] == 1: - return False - - if list(node1.read_writes.writes)[0].name in [dep.name for dep in node2.read_writes.reads]: - node1 = self.revert_group(node1) - return True + if self._single_prologue_template_pair(node1, node2) is not None: + return self._prologue_plan_for(node1, node2) is not None return self.scheduler.can_fuse_origin(node1, node2) @@ -81,6 +55,51 @@ def can_fuse_vertical(self, node1, node2): def can_fuse_multi_outputs_template(self, node1, node2): return self.can_fuse_horizontal(node1, node2) + def _single_template_epilogue_pair(self, node1, node2): + """node1 is a lone template node and node2 a lone non-template node -> that template node.""" + templates = [n for n in node1.get_nodes() if n.is_template()] + if len(templates) != 1 or len(node1.get_nodes()) != 1: + return None + if len(node2.get_nodes()) != 1 or any(n.is_template() for n in node2.get_nodes()): + return None + return templates[0] + + def _single_prologue_template_pair(self, node1, node2): + """node1 is a lone non-template node feeding a lone template node2 -> that template node.""" + if len(node1.get_nodes()) != 1 or any(n.is_template() for n in node1.get_nodes()): + return None + if node1.is_reduction(): + return None + templates = [n for n in node2.get_nodes() if n.is_template()] + if len(templates) != 1 or len(node2.get_nodes()) != 1: + return None + if not ({d.name for d in node1.read_writes.writes} & {d.name for d in node2.read_writes.reads}): + return None + return templates[0] + + def _epilogue_plan_for(self, node1, node2): + """The FusionPlan the template approved for this pair, or None. Pure.""" + template_node = self._single_template_epilogue_pair(node1, node2) + if template_node is None: + return None + return template_node.node.template.try_fuse_epilogue(node1, [], node2) + + def _prologue_plan_for(self, node1, node2): + """The FusionPlan the template approved for prologue-fusing node1 into node2. Pure.""" + template_node = self._single_prologue_template_pair(node1, node2) + if template_node is None: + return None + return template_node.node.template.try_fuse_prologue(node2, node1) + + def fuse(self, node1, node2): + # Commit hook: templates defer their node mutations into the plan so that + # can_fuse stays a pure predicate. Recomputing the plan here (it is pure and + # cheap) avoids caching it across the many speculative can_fuse calls. + plan = self._epilogue_plan_for(node1, node2) or self._prologue_plan_for(node1, node2) + if plan is not None and plan.remap is not None: + plan.remap() + return super().fuse(node1, node2) + def can_fuse_horizontal(self, node1, node2): if not extension_config.CONFIG_FUSION: return False @@ -103,10 +122,6 @@ def can_fuse_horizontal(self, node1, node2): if '_unsafe_index' in node1.get_nodes()[0].node.origins or "_unsafe_index" in node2.get_nodes()[0].node.origins: return False - # Extract base template node - base_template_node1 = [node for node in node1.get_nodes() if node.is_template()] - base_template_node2 = [node for node in node2.get_nodes() if node.is_template()] - # Case 0: Reduction fusion if ( node1.is_reduction() @@ -123,122 +138,17 @@ def can_fuse_horizontal(self, node1, node2): ) return same_iter and no_dependency - # Case 1: Template + Pointwise fusion - if len(base_template_node1) == 1 and len(node1.get_nodes())==1 and len(node2.get_nodes())==1 and len(base_template_node2) == 0 and not node2.is_reduction(): - # Don't fuse maxpool template code - from PyTorchSimFrontend.mlir.mlir_maxpool_template import MLIRMaxPoolTemplate - - template_node = base_template_node1[0] - epilogue_node = node2 - - # Check if template supports epilogue fusion - if not getattr(template_node.node.template, 'support_epilogue_fusion', False): - return False - - if isinstance(template_node.node.template, MLIRMaxPoolTemplate): - return False - - # Pointwise check - v1_total = math.prod(vars1) if len(vars1) else 0 - v2_total = math.prod(vars2) if len(vars2) else 0 - if v1_total != v2_total: - return False - - # Pattern check: check data dependency between act_node and template_node - template_sched_nodes = list(template_node.get_nodes()) - # Buffers produced by the template (its outputs) - template_writes = { - dep - for n in template_sched_nodes - for dep in n.read_writes.writes - } - # Buffers still required by the activation node (unmet) or read by it - epilogue_unmet = { dep for dep in epilogue_node.unmet_dependencies } - has_dependency = bool(template_writes) and epilogue_unmet.issubset(template_writes) and not bool(reads1 & writes2) - if not has_dependency: - return False - - # Revert act_node.group : simplify_and_reorder() modified _body, _size, group - if template_node.group != epilogue_node.group: - # We don't fuse this case... - if getattr(template_node.node.template, 'support_prologue_fusion', False) and template_node.group[1][0][0] == 1: - return False - - if list(template_node.group[1][0]) != list(epilogue_node.get_nodes()[0].node.data.get_size()): - return False - self.revert_group(epilogue_node) - return True - - # Case 2: Tempalte + Reduction fusion - if len(base_template_node1) == 1 and len(node1.get_nodes())==1 and len(node2.get_nodes())==1 and len(base_template_node2) == 0 and node2.is_reduction() and extension_config.CONFIG_FUSION_REDUCTION_EPILOGUE: - target_node = base_template_node1[0].node - - # Check if template supports reduction fusion - if not getattr(target_node.template, 'support_reduction_fusion', False): - return False - - size_match = node1.get_nodes()[0].node.get_numel() == reduce(operator.mul, node2.get_nodes()[0].node.get_size(), 1) * reduce(operator.mul, node2.get_nodes()[0].node.get_reduction_size(), 1) - target_symbol = symbols("r0_0") - try: - stride = [i.strip()[:-1].split(",")[-1].strip() for i in str(node2.get_nodes()[0].node).split("\n") if "r0" in i][1] - stride = int(sympify(stride).coeff(target_symbol)) - except: - return False - - # We can't fuse dim=-1 & N == 1 - layout_possible = stride != 1 and (1 not in node1.node.get_size()) - # Directed linked? - dependency_check = writes1 & reads2 - dependency_size = all([i.get_numel() == node1.get_nodes()[0].node.get_numel() for i in node2.read_writes.reads]) - return size_match and layout_possible and dependency_check and dependency_size - - # Case 3: Prologue(Pointwise) + Tempalte - # if len(base_template_node1) == 0 and len(node1.get_nodes())==1 and not node1.is_reduction() and len(base_template_node2) == 1 and extension_config.CONFIG_FUSION_PROLOGUE: - # from PyTorchSimFrontend.mlir.mlir_gemm_template import MLIRGemmTemplate - # from PyTorchSimFrontend.mlir.mlir_bmm_template import MLIRBMMTemplate - - # target_node = base_template_node2[0].node - # # Currently only BMM, MM support prologue fusion - # if not isinstance(target_node.template, (MLIRBMMTemplate, MLIRGemmTemplate)): - # return False - - # if len(node1.read_writes.writes) != 1: - # return False - # if node1.node not in target_node.inputs or any(["view" in str(ori) for ori in node1.node.origins]): #FIXME - # return False - - # # We don't fuse this edge case... - # if base_template_node2[0].group[1][0][0] == 1: - # return False - - # if list(node1.read_writes.writes)[0].name in [dep.name for dep in node2.read_writes.reads]: - # node1 = self.revert_group(node1) - # return True + # Template + epilogue (pointwise or reduction): every condition is the template's. + if self._single_template_epilogue_pair(node1, node2) is not None: + return self._epilogue_plan_for(node1, node2) is not None + return False def revert_group(self, act_nodes, args=None, var_ranges=None): - for act_node in act_nodes.get_nodes(): - if args is None or var_ranges is None: - args, var_ranges = dependencies.index_vars_no_squeeze( - act_node.node.data.get_size(), act_node.node.data.get_reduction_size(), prefix="q" - ) - body = LoopBody( - act_node.node.get_store_function(), - (args if act_node.node.get_reduction_type() else args[:1]), - var_ranges, - args[0], - args[1] - ) - index_size = [] - reduce_size = [] - for v, s in var_ranges.items(): - if v in args[0]: - index_size.append(s) - else: - reduce_size.append(s) - node_device = act_node.get_device() - ranges = (index_size, reduce_size) - act_node._sizes, act_node._body, act_node.group = (ranges), body, (node_device, self.group_fn(ranges)) + # Used by axis-split to re-trace a node over split ranges. Fusion reaches the same + # re-derivation through FusionPlan.remap, so it never runs from a can_fuse predicate. + from PyTorchSimFrontend.mlir.mlir_template import realign_node_group + realign_node_group(act_nodes, args, var_ranges) def group_fn(self, sizes): return tuple(tuple(map(V.graph.sizevars.simplify, s)) for s in sizes) @@ -333,6 +243,10 @@ def define_kernel(self, src_code, meta_code, kernel_name, vector_lane, spad_info codecache_def.writeline(f"spad_info={spad_info},") codecache_def.writeline(f"origins={origins},") codecache_def.writeline(f"arg_attributes={meta_code},") + headers = extension_codecache.get_header(src_code) + if headers is not None: + codecache_def.writeline(f"global_var_header='''{headers[0]}''',") + codecache_def.writeline(f"gem5_global_var_header='''{headers[1]}''',") codecache_def.writeline(f"vlen={extension_config.vpu_vector_length_bits})") wrapper.define_kernel(kernel_name, codecache_def.getvalue(), gpu=False) return kernel_name diff --git a/PyTorchSimFrontend/mlir/mlir_sort_template.py b/PyTorchSimFrontend/mlir/mlir_sort_template.py index 24b3a460..338f9636 100644 --- a/PyTorchSimFrontend/mlir/mlir_sort_template.py +++ b/PyTorchSimFrontend/mlir/mlir_sort_template.py @@ -3,6 +3,7 @@ from torch._inductor.ir import Buffer, IRNode from torch._inductor.virtualized import _ops as ops +from torch._inductor.virtualized import V from torch._inductor.codegen import common from PyTorchSimFrontend.mlir import mlir_common @@ -38,7 +39,9 @@ {{ BITONIC_BODY }} {{ kernel.def_dma_op("MVOUT", "XI", [], XI_TILE_DESC, indent_size=INDENT_SIZE, dram_stride=XI_DRAM_STRIDE, dram_offset="xi_dram_offset") }} + {%- if YV_LIVE %} {{ kernel.def_dma_op("MVOUT", "YV", [], YV_TILE_DESC, indent_size=INDENT_SIZE, dram_stride=YV_DRAM_STRIDE, dram_offset="yv_dram_offset") }} + {%- endif %} {%- for d in range(RANK-1) %} } { outer_loop=true } {%- endfor %} @@ -433,6 +436,9 @@ def render( X=x, XI=xi, YV=yv, + # In argsort the sorted-values output is dead and dropped from the kernel args; + # skip its MVOUT so the body does not reference the pruned %YV (undeclared SSA). + YV_LIVE=yv.get_name() not in V.graph.removed_buffers, X_TILE_DESC=x_tile_desc, XI_TILE_DESC=xi_tile_desc, YV_TILE_DESC=yv_tile_desc, diff --git a/PyTorchSimFrontend/mlir/mlir_template.py b/PyTorchSimFrontend/mlir/mlir_template.py index 529a49b5..2979f704 100644 --- a/PyTorchSimFrontend/mlir/mlir_template.py +++ b/PyTorchSimFrontend/mlir/mlir_template.py @@ -10,18 +10,19 @@ import operator from collections import OrderedDict -from typing import List, Optional +import logging +from dataclasses import dataclass +from typing import Callable, List, Optional from unittest.mock import patch from PyTorchSimFrontend import extension_config from torch._inductor.codegen.common import KernelTemplate, CSE, DeferredLine -from torch._inductor.ir import Buffer, IRNode, TemplateBuffer, ChoiceCaller, ir_node_to_tensor +from torch._inductor.ir import Buffer, IRNode, TemplateBuffer, ChoiceCaller, ir_node_to_tensor, TensorBox from torch._inductor.select_algorithm import PartialRender -from torch._inductor.codegen.cuda.cuda_kernel import CUDATemplateCaller +from torch._inductor.codegen.cuda.cuda_kernel import CUDATemplateCaller, CUDATemplateBuffer from torch._inductor.autotune_process import TensorMeta from torch._inductor.virtualized import V, NullHandler, _ops as ops from torch._inductor.utils import IndentedBuffer -from torch._inductor.codecache import write_atomic import PyTorchSimFrontend.extension_codecache as extension_codecache from PyTorchSimFrontend.mlir.mlir_autotune import MLIRBenchmarkRequest @@ -93,6 +94,65 @@ def as_local(self): finally: self.restore_buffers() +fusion_log = logging.getLogger(__name__) + + +@dataclass +class FusionPlan: + """What the scheduler must do to commit a fusion that a template approved. + + `MLIRTemplate.try_fuse_*` is a pure predicate (the scheduler calls it speculatively + for many candidate pairs), so any node mutation the fusion needs -- a loop merge, a + group re-derivation -- is deferred here and applied by `MLIRScheduling.fuse()` once + the fusion is actually committed. + """ + remap: Optional[Callable] = None # zero-arg thunk, invoked from fuse() + + +def realign_node_group(node_to_realign, args=None, var_ranges=None): + """Re-derive a node's loop body/sizes/group from its data size. + + `simplify_and_reorder()` may have reordered the node's loops away from the template's + iteration order; rebuilding the body puts them back. Used as a `FusionPlan.remap` (so + it runs from `MLIRScheduling.fuse()`, never from a can_fuse predicate) and by + axis-split, which re-traces a node over split ranges. + """ + from torch._inductor.ir import LoopBody + from torch._inductor import dependencies + from torch._inductor.virtualized import V as _V + + for node in node_to_realign.get_nodes(): + if args is None or var_ranges is None: + args, var_ranges = dependencies.index_vars_no_squeeze( + node.node.data.get_size(), node.node.data.get_reduction_size(), prefix="q") + body = LoopBody( + node.node.get_store_function(), + (args if node.node.get_reduction_type() else args[:1]), + var_ranges, args[0], args[1]) + index_size, reduce_size = [], [] + for v, s in var_ranges.items(): + (index_size if v in args[0] else reduce_size).append(s) + ranges = (index_size, reduce_size) + group = tuple(tuple(map(_V.graph.sizevars.simplify, s)) for s in ranges) + node._sizes, node._body, node.group = ranges, body, (node.get_device(), group) + + +def merge_node_loops(node_to_merge): + """Collapse a node's contiguous loops so its iteration fits the template's frame.""" + node_to_merge.get_nodes()[0].merge_loops() + + +def why_no_fuse(template_node, node_to_fuse, reason): + """Record why a fusion was declined, and return the 'declined' value (None). + + Declining is a normal outcome -- upstream CUTLASS/CPP decline every reduction + epilogue outright -- so every decline carries a reason to keep the decision + debuggable (cf. Inductor's WhyNoFuseNames). + """ + fusion_log.debug("cannot fuse %s into template %s: %s", node_to_fuse, template_node, reason) + return None + + class MLIRTemplateKernel(MLIRKernel, BaseMLIRHardwareInfo): def __init__(self, kernel_name, @@ -205,7 +265,7 @@ def gemmini_gemm_mapping(self, M, N, K, precision_bytes=4): return inner_I, inner_J, inner_K - def gemm_combination_mapping(self, M, N, K, n_extra_node=0, n_prologue_node=0, pad_k=True, min_tile=False, is_conv=False, precision_bytes=4): + def gemm_combination_mapping(self, M, N, K, n_extra_node=0, n_prologue_node=0, n_prologue_extra_read=0, pad_k=True, min_tile=False, is_conv=False, precision_bytes=4): tile_candidates = [] spad_size_per_lane = self.spad_info["spad_size"] spad_size = spad_size_per_lane * self.vector_lane @@ -233,8 +293,8 @@ def gemm_combination_mapping(self, M, N, K, n_extra_node=0, n_prologue_node=0, p tile_M = i * self.vector_lane if M > self.vector_lane else M_padded for j in tile_N_range: tile_N = j * self.vector_lane if N > self.vector_lane else N_padded - used_spad_size = (tile_M * tile_K * (1 + n_prologue_node) + tile_K * tile_N + tile_M * tile_N * (1 + n_extra_node)) * precision_bytes - weight_size_per_lane = self.get_spad_size_per_lane(tile_K, tile_N) + used_spad_size = (tile_M * tile_K * (1 + n_prologue_node) + tile_K * tile_N * (1 + n_prologue_extra_read) + tile_M * tile_N * (1 + n_extra_node)) * precision_bytes + weight_size_per_lane = self.get_spad_size_per_lane(tile_K, tile_N) * (1 + n_prologue_extra_read) input_size_per_lane = self.get_spad_size_per_lane(tile_M * (1 + n_prologue_node), tile_K) output_size_per_lane = self.get_spad_size_per_lane(tile_M * (1 + n_extra_node), tile_N) used_spad_size_per_lane = (weight_size_per_lane + input_size_per_lane + output_size_per_lane) * precision_bytes @@ -259,8 +319,8 @@ def gemm_combination_mapping(self, M, N, K, n_extra_node=0, n_prologue_node=0, p tile_M = i * self.vector_lane if M > self.vector_lane else M_padded for j in tile_N_range: tile_N = j * self.vector_lane if N > self.vector_lane else N_padded - used_spad_size = (tile_M * tile_K * (1 + n_prologue_node) + tile_K * tile_N + tile_M * tile_N * (1 + n_extra_node)) * precision_bytes - weight_size_per_lane = self.get_spad_size_per_lane(tile_K, tile_N) + used_spad_size = (tile_M * tile_K * (1 + n_prologue_node) + tile_K * tile_N * (1 + n_prologue_extra_read) + tile_M * tile_N * (1 + n_extra_node)) * precision_bytes + weight_size_per_lane = self.get_spad_size_per_lane(tile_K, tile_N) * (1 + n_prologue_extra_read) input_size_per_lane = self.get_spad_size_per_lane(tile_M * (1 + n_prologue_node), tile_K) output_size_per_lane = self.get_spad_size_per_lane(tile_M * (1 + n_extra_node), tile_N) used_spad_size_per_lane = (weight_size_per_lane + input_size_per_lane + output_size_per_lane) * precision_bytes @@ -348,7 +408,13 @@ def conv_multi_tile_mapping(self, M, N, K, K_H, K_W, O_H, O_W, stride, dilation, max_used_spad_size = used_spad_size max_k_h_w = k_h mapping = (k_h, K_W, o_h, o_w, M, N, K) - if max_used_spad_size == 0: + # Raise only when NO tile fits SPAD. The max_used_spad_size / max_k_h_w + # tracking above only records the largest-k_h tile (max_k_h_w starts at + # K_W, so it never fires unless the full-kernel tile fits) and is not + # returned -- the sorted tile_candidates is. Guarding on it wrongly + # rejected convs whose full-kernel tile overflows SPAD (e.g. a batched + # CLIP patch conv) even though smaller-k_h tiles fit. See issue #252. + if not tile_candidates: raise RuntimeError("Cannot find a valid mapping") tile_candidates = sorted(tile_candidates, key=lambda x: x[0], reverse=True) tile_candidates = [v for _, v in tile_candidates] @@ -384,7 +450,7 @@ def conv_single_batch_mapping(self, M, N, K, K_H, K_W, O_H, O_W, stride, dilatio max_used_spad_size = used_spad_size max_k_h_w = k_h * k_w mapping = (k_h, k_w, o_h, M, M, N, K) - if max_used_spad_size == 0: + if not tile_candidates: raise RuntimeError("Cannot find a valid mapping") tile_candidates = sorted(tile_candidates, key=lambda x: x[0], reverse=True) tile_candidates = [v for _, v in tile_candidates] @@ -613,22 +679,11 @@ def codegen_nodes(self, tile_candidates, render, template_node, prologue_nodes, return src_code, meta_code def _prepare_simulator_headers(self, src_code): - from filelock import FileLock - spad_end_symbol = f"int spad_end[0] __attribute__ ((section(\".spad\")));\n" spad_section_end_symbol = f"int spad_section_end[0] __attribute__ ((section(\".spad\"), aligned({self.spad_info['spad_size']*self.vector_lane})));" - - write_path = extension_codecache.get_write_path(src_code) - os.makedirs(write_path, exist_ok=True) - spike_write_path = os.path.join(write_path, "global_var.h") - gem5_write_path = os.path.join(write_path, "gem5_global_var.h") - - lock = FileLock(extension_codecache.get_lock_path(write_path), timeout=extension_codecache.LOCK_TIMEOUT) - with lock: - if not os.path.exists(spike_write_path): - write_atomic(spike_write_path, self.header.getvalue()+spad_end_symbol+spad_section_end_symbol) - if not os.path.exists(gem5_write_path): - write_atomic(gem5_write_path, self.gem5_header.getvalue()) + spike_content = self.header.getvalue()+spad_end_symbol+spad_section_end_symbol + gem5_content = self.gem5_header.getvalue() + extension_codecache.store_header(src_code, spike_content, gem5_content) def codegen_prologue_body(self): body = IndentedBuffer() @@ -657,11 +712,24 @@ def template_store(): code = self.def_dma_op("MVOUT", dram_var, index_list, tile_desc, lazy_mode=False) self.cse.generate(self.dma_stores, code, assignment = False) + def template_buffer_live(): + # Inductor's remove_kernel_local_buffers() drops the template buffer only when + # every one of its users lives inside this fused kernel + # (Scheduler.can_buffer_be_removed_through_fusion). If it survived, some user is + # outside the kernel, so we must store it to DRAM -- whether or not a fused + # epilogue also stores its own output. + name = getattr(self, "template_buffer_name", None) + assert name is not None, ( + "store_output() used by a template that never declared its output buffer; " + "call def_kernel()/def_conv_kernel() with outputs=[...] first" + ) + return name not in self.removed_buffers + body = IndentedBuffer() with self.epilogue_buffer_group.as_local(): # Do dma store first to overlap epilogue nodes if self.reduction_fusion: - if len(self.stores._lines) == 0: + if template_buffer_live(): template_store() body.splice(self.dma_stores) self.dma_stores.clear() @@ -673,7 +741,6 @@ def template_store(): with contextlib.ExitStack() as stack: stack.enter_context(compute_body.indent(attribute="{inner_loop=false}",suffix=self.compute_body_loop.epilogue_line())) if self.reduction_fusion: - compute_body.splice(self.masks) compute_body.writelines(self.reduction_body_loop.lines()) stack.enter_context(compute_body.indent(attribute="{inner_loop=false}")) compute_body.splice(self.loads) @@ -681,7 +748,7 @@ def template_store(): else: compute_body.splice(self.loads) compute_body.splice(self.compute) - if len(self.stores._lines) == 0: + if template_buffer_live(): template_store() compute_body.splice(self.stores) if (compute_body.getvalue()): @@ -703,6 +770,12 @@ def def_kernel( f"{len(inputs) + len(outputs)=} != {len(names)=}, {inputs=}, {outputs=}, {names=}" ) + # The template's own output buffer. codegen_epilogue_body() stores it to DRAM iff + # it survived Inductor's kernel-local buffer removal -- i.e. it still has a user + # outside this fused kernel. + if outputs: + self.template_buffer_name = outputs[0].get_name() + if input_reorder is not None: assert len(inputs) == len(input_reorder) else: @@ -771,6 +844,12 @@ def def_conv_kernel( f"{len(inputs) + len(outputs)=} != {len(names)=}, {inputs=}, {outputs=}, {names=}" ) + # The template's own output buffer. codegen_epilogue_body() stores it to DRAM iff + # it survived Inductor's kernel-local buffer removal -- i.e. it still has a user + # outside this fused kernel. + if outputs: + self.template_buffer_name = outputs[0].get_name() + if input_reorder is not None: assert len(inputs) == len(input_reorder) else: @@ -952,9 +1031,43 @@ def generate_dma_code(): zero_cse = self.get_const_cse(0, "index") sram_index_var = ", ".join([f"%{str(zero_cse)}"]*tile_desc.get_nr_dim()) + # masked-DMA clamp: per tile dim, clamp to the real DRAM extent so a tile + # that pads past M/N/K (matmul) or a dim is filled with 0 instead of MAC-ing + # garbage. index_list[d] = iv * stride -> base iv; the extent comes from the + # kernel's loop_extents {iv_name: loop_bound} (the template's ranges/itervars + # equivalent -- needed for conv, whose repacked-weight strides do not match + # node_layout), else it is matched by that tile dim's stride (gemm). + # _emit_clamp skips dividing dims (no-op). Only a dim whose index is a single + # iv is clampable: the clamp base is that iv, and high/low are affine in it. + # A dim indexed by a SUM of ivs (e.g. an im2col spatial axis o_h + k_h) has + # no single base, so it is left unclamped -- correct here because such inputs + # are pre-padded (materialized), not masked. + # FIXME: loop_extents is declared by hand in each conv template (verbose, + # easy to drift from the affine.for bounds). Fold it into the template + # overhaul -- e.g. record each loop's (iv -> bound) as the affine.for is + # emitted, so def_dma_op derives extents the way pointwise uses ranges/itervars. + loop_ext = getattr(self, "loop_extents", None) + layout_sizes, layout_strides = node_layout.size, node_layout.stride + tile_sizes = tile_desc.get_tile_size() + clamp_axes = [] + for d, idx_expr in enumerate(index_list): + syms = list(idx_expr.free_symbols) + if len(syms) != 1 or d >= len(tile_sizes): + continue + base_iv = str(syms[0]) + if loop_ext: + extent = loop_ext.get(base_iv) # explicit: clamp only known ivs + else: + extent = next((int(layout_sizes[j]) for j, st in enumerate(layout_strides) + if layout_sizes[j].is_number and int(st) == int(_dram_stride[d])), None) + if extent is not None: + clamp_axes.append((d, base_iv, 0, int(extent), int(tile_sizes[d]))) + masked_bounds = self._emit_clamp(clamp_axes, local_code) + code = self.emit_transfer(dma_type, vlane_split_axis, vlane_stride, mlir_dtype, dram_var, index_var, sram_var, sram_index_var, dram_shape, tile_shape, _dram_stride, sram_strides, int(padding), - subtile_size=subtile_size if subtile_size else None, async_type=async_type) + subtile_size=subtile_size if subtile_size else None, async_type=async_type, + masked_bounds=masked_bounds, masked_fill=0) local_code.writeline(code) return textwrap.indent(local_code.getvalue(), " "*indent_size).strip() @@ -1087,9 +1200,26 @@ def store_epilogue(self, name: str, index: sympy.Expr, value, *args, **kwargs): with self.override_buffer_cse(buffer=self.stores): ops._store(value, sram_var, compute_index_var, tile_shape, buffer_name=buffer_name) - # Generate DMA instruction + # Generate DMA instruction. Clamp the output tail, else a non-dividing epilogue + # store writes the systolic pad region past the real output extent (fused matmul + + # relu/add on a non-dividing shape). The extent of each loop iv is ranges[k]; the + # tile dims are indexed by dim_aliasing (tile-dim order), so a dim whose iv extent + # does not divide the tile is clamped to [0, extent). Naming-agnostic (works for the + # index-N matmul epilogue and the c0/tile_n/... conv epilogue alike); _emit_clamp + # skips dividing dims, so a dividing output is a no-op. + iv_extent = {} + for itervar, rng in zip(self.itervars, self.ranges): + try: + iv_extent[str(itervar)] = int(rng) + except (TypeError, ValueError): + pass + tile_sizes = self.kernel_group.tile_desc.get_tile_size() + clamp_axes = [(d, iv, 0, iv_extent[iv], int(tile_sizes[d])) + for d, iv in enumerate(self.dim_aliasing.values()) + if d < len(tile_sizes) and iv in iv_extent] + masked_bounds = self._emit_clamp(clamp_axes, self.dma_stores) code = self.emit_transfer("MVOUT", vlane_split_axis, vlane_stride, mlir_dtype, dram_var, index_var, sram_var, sram_index_var, - dram_shape, tile_shape, dram_stride, tile_stride, 0) + dram_shape, tile_shape, dram_stride, tile_stride, 0, masked_bounds=masked_bounds) self.dma_stores.writeline(DeferredLine(name, code)) def reduction_epilogue(self, dtype, src_dtype, reduction_type, value): @@ -1273,7 +1403,41 @@ def set_tile_size(self, template_fusion_info, prologue=False): self.compute_body_loop.step = tile_desc.get_compute_vec_size() return tile_desc +class MLIRTemplateBuffer(CUDATemplateBuffer): + """Template output buffer that can own extra MutationOutputs beyond its primary output. + + The sort kernel's primary scheduler-visible output is the sorted values, but it also + writes the indices buffer in place (mlir_sort_template make_inplace). Registering that + write as a MutationOutput owned here -- so get_outputs() advertises it -- lets the + scheduler keep the kernel alive when only the indices are consumed (argsort), instead of + DCE-ing the whole sort. OperationBuffer.get_outputs() otherwise hardcodes [self]. + """ + + def add_mutation_output(self, mutation: IRNode) -> None: + if not hasattr(self, "_extra_mutation_outputs"): + self._extra_mutation_outputs = [] + self._extra_mutation_outputs.append(mutation) + + def get_outputs(self) -> List[Buffer]: + return [self, *getattr(self, "_extra_mutation_outputs", [])] + + class MLIRTemplateCaller(CUDATemplateCaller): + def output_node(self) -> TensorBox: + # Same as CUDATemplateCaller.output_node but builds a mutation-aware buffer so + # callers (e.g. the sort lowering) can attach in-place-write MutationOutputs. + self.bmreq.update_workspace_size() + return TensorBox.create( + MLIRTemplateBuffer( + layout=self.layout, + inputs=self.input_nodes, + make_kernel_render=self.make_kernel_render, + workspace_size=self.bmreq.workspace_size, + supports_epilogue_fusion=self.supports_epilogue_fusion, + template=self.template, + ) + ) + def __init__(self, name, category, input_nodes, layout, make_kernel_render, supports_epilogue_fusion, template, info_kwargs, description): bmreq = MLIRBenchmarkRequest( kernel_name=name, @@ -1292,6 +1456,12 @@ def call_name(self) -> str: class MLIRTemplate(KernelTemplate): index_counter = itertools.count() + # Maps a fused reduction epilogue's loop indices onto this template's tile axes. + # `render()` hands it to the kernel, and its LENGTH is the number of loop ranges the + # epilogue codegen can address (set_ranges asserts len(dim_aliasing) == len(ranges)). + # None means this template cannot absorb a reduction epilogue. + REDUCTION_EPILOGUE_ALIASING = None + def __init__(self, name, input_nodes, layout, input_reorder = None): """ Baseclass for MLIR Templates, derived from KernelTemplate. Not to be instantiated directly. @@ -1313,7 +1483,147 @@ def __init__(self, name, input_nodes, layout, input_reorder = None): # Fusion support flags (default to False) self.support_epilogue_fusion = False self.support_prologue_fusion = False - self.support_reduction_fusion = False + + def try_fuse_epilogue(self, template_node, existing_epilogues, node_to_fuse): + """Decide whether `node_to_fuse` can be fused as this template's epilogue. + + Only the template knows its output coordinate frame, so every fusion condition + that depends on it lives here -- the scheduler only identifies the template and + the direction, then asks. MUST BE PURE: the scheduler calls this speculatively + for many candidate pairs, so it may not mutate any node. Anything that has to + mutate goes into the returned plan's `remap`, which the scheduler applies from + `fuse()` when the fusion is actually committed. + + `existing_epilogues` are the epilogues already fused onto this template (always + empty for now; the argument is here so chained epilogue fusion can be enabled + later without changing every implementation). + + Returns a FusionPlan to fuse, or None to decline (declining is a normal result: + upstream CUTLASS/CPP decline every reduction epilogue outright).""" + if existing_epilogues: + return why_no_fuse(template_node, node_to_fuse, "chained epilogue fusion is not supported yet") + if node_to_fuse.is_reduction(): + if self.REDUCTION_EPILOGUE_ALIASING is None: + return why_no_fuse(template_node, node_to_fuse, "template does not fuse reduction epilogues") + return self._try_fuse_reduction_epilogue(template_node, node_to_fuse) + if not self.support_epilogue_fusion: + return why_no_fuse(template_node, node_to_fuse, "template does not support epilogue fusion") + return self._try_fuse_pointwise_epilogue(template_node, node_to_fuse) + + def _try_fuse_reduction_epilogue(self, template_node, epi): + """Frame-independent conditions for absorbing a reduction epilogue, plus the one + frame-dependent question: does it fit REDUCTION_EPILOGUE_ALIASING? Pure.""" + def why(reason): + return why_no_fuse(template_node, epi, reason) + + if not extension_config.CONFIG_FUSION_REDUCTION_EPILOGUE: + return why("reduction-epilogue fusion is disabled") + if epi.has_aliasing_or_mutation(): + return why("epilogue has aliasing or mutation") + + tnode = template_node.get_nodes()[0].node + esched = epi.get_nodes()[0] + enode = esched.node + + # The epilogue must iterate exactly the template output (rows x reduced cols). + if tnode.get_numel() != math.prod(enode.get_size()) * math.prod(enode.get_reduction_size()): + return why("epilogue does not iterate the whole template output") + if not all(d.get_numel() == tnode.get_numel() for d in epi.read_writes.reads): + return why("epilogue reads a buffer whose size differs from the template output") + + # It must read the template output at exactly one index expression (the CPP backend's + # template_fusion_with_epilogues_supported applies the same rule). Read the expressions + # off the LoopBody: a MemoryDep's index is normalized to a flat contiguous access and + # no longer carries the per-axis strides. + body = esched._body + template_bufs = {d.name for d in template_node.read_writes.writes} + read_exprs = {e for name in template_bufs for e in body.get_all_read_expr(name)} + if not read_exprs: + return why("epilogue does not read the template output") + if len(read_exprs) != 1: + return why("epilogue reads the template output at more than one index") + index = next(iter(read_exprs)) + + # The reduced axis must not be the contiguous (stride-1) column, and the output must + # not carry a size-1 dim. + reduce_vars = body.vars[1] + if len(reduce_vars) != 1: + return why("more than one reduction axis") + if index.coeff(reduce_vars[0]) == 1: + return why("reduces the contiguous (stride-1) axis") + if 1 in template_node.node.get_size(): + return why("template output has a size-1 dimension") + + # The only frame-dependent question: does the epilogue's iteration fit the coordinate + # map this template's reduction-epilogue codegen addresses? `set_ranges` asserts + # len(dim_aliasing) == len(ranges), so the map's length IS the frame's capacity, and + # checking it here is that assert, raised as a decline instead of a crash. See #255. + addressable = len(self.REDUCTION_EPILOGUE_ALIASING) + needed = len(esched._sizes[0]) + len(reduce_vars) + if needed <= addressable: + return FusionPlan() + + # It does not fit as-is. merge_loops() returns a NEW body, so ask whether merging the + # node's contiguous loops would make it fit -- without mutating anything. + merged = len(body.merge_loops().sizes[0]) + len(reduce_vars) + if merged > addressable: + # e.g. ConvNextV2's channels-first LayerNorm reduces the middle C axis, so batch + # and spatial are not contiguous and no loop merge can flatten them. + return why(f"epilogue needs {needed} loop ranges ({merged} after a loop merge) but " + f"this template's reduction epilogue addresses {addressable}") + return FusionPlan(remap=functools.partial(merge_node_loops, epi)) + + def _try_fuse_pointwise_epilogue(self, template_node, epi): + """Generic (frame-independent) pointwise-epilogue conditions. Pure.""" + def why(reason): + return why_no_fuse(template_node, epi, reason) + + # The epilogue must sweep exactly as many elements as the template output. + tmpl_iter, epi_iter = template_node.group[1][0], epi.group[1][0] + if (math.prod(tmpl_iter) if len(tmpl_iter) else 0) != (math.prod(epi_iter) if len(epi_iter) else 0): + return why("epilogue iterates a different number of elements than the template") + + # Everything the epilogue still needs must come from the template's outputs, and + # it must not overwrite anything the template reads. + template_writes = {dep for n in template_node.get_nodes() for dep in n.read_writes.writes} + if not template_writes: + return why("template writes nothing") + if not {dep for dep in epi.unmet_dependencies}.issubset(template_writes): + return why("epilogue depends on buffers the template does not produce") + if {d.name for d in template_node.read_writes.reads} & {d.name for d in epi.read_writes.writes}: + return why("epilogue overwrites a buffer the template reads") + + if template_node.group == epi.group: + return FusionPlan() + + # simplify_and_reorder() moved the epilogue's loops; they can be put back only if + # its data size still matches the template's iteration. + if self.support_prologue_fusion and template_node.group[1][0][0] == 1: + return why("degenerate first iteration dim on a prologue-fusing template") + if list(template_node.group[1][0]) != list(epi.get_nodes()[0].node.data.get_size()): + return why("epilogue loop order cannot be realigned to the template") + return FusionPlan(remap=functools.partial(realign_node_group, epi)) + + def try_fuse_prologue(self, template_node, node_to_fuse): + """Prologue counterpart of `try_fuse_epilogue`. Same purity contract. + + The scheduler has already established that `node_to_fuse` is a lone non-template + node feeding this lone template node.""" + def why(reason): + return why_no_fuse(template_node, node_to_fuse, reason) + + if not self.support_prologue_fusion: + return why("template does not support prologue fusion") + if len(node_to_fuse.read_writes.writes) != 1: + return why("prologue writes more than one buffer") + target = template_node.get_nodes()[0].node + if node_to_fuse.node not in target.inputs: + return why("prologue output is not a template input") + if any("view" in str(origin) for origin in node_to_fuse.node.origins): + return why("prologue is a view") + if template_node.group[1][0][0] == 1: + return why("template has a degenerate first iteration dim") + return FusionPlan(remap=functools.partial(realign_node_group, node_to_fuse)) def generate(self, **kwargs) -> ChoiceCaller: kernel_name = f"mlir_{self.name}" diff --git a/PyTorchSimFrontend/mlir/passes/__init__.py b/PyTorchSimFrontend/mlir/passes/__init__.py index 82cadc2f..0f1dec7e 100644 --- a/PyTorchSimFrontend/mlir/passes/__init__.py +++ b/PyTorchSimFrontend/mlir/passes/__init__.py @@ -34,6 +34,8 @@ def _ensure_mlir_bindings_on_path(): from . import decompose_transfer from . import dma_fine_grained from . import lower_to_vcix +from . import peel_transfer +from . import peel_transfer from .lower_to_llvm import run_standard_lowering # noqa: F401 (re-exported) from .build_tog import run_tog # noqa: F401 (re-exported; replaces C++ test-tile-operation-graph) from .dma_fine_grained import run_fine_grained # noqa: F401 (re-exported; standalone/CLI) @@ -41,15 +43,17 @@ def _ensure_mlir_bindings_on_path(): # Module rewrite passes around the one remaining mlir-opt pass (-test-loop-padding). # Each exposes MARKERS + run(module, **opts); run_module_passes parses once per phase. -# decompose_transfer first: togsim.transfer -> memref.dma_start (downstream expects it). +# togsim.transfer stays through the pipeline (no more memref.dma_start): it lowers +# directly to Gemmini at the end (lower_transfer_to_gemmini); loop-padding runs opaquely. PRE_OPT_PASSES = [ - decompose_transfer, lower_vlane_idx, ] # fine-grained first: splits the matmul DMAs that the vcix lowering then reads. +# peel_transfer last: split any >4D togsim.transfer so build_tog (trace) also sees <=4D. POST_OPT_PASSES = [ dma_fine_grained, lower_to_vcix, + peel_transfer, ] @@ -76,8 +80,12 @@ def run_module_passes(in_path, out_path, passes, **opts): p.run(module, **opts) out = str(module) - with open(out_path, "w") as f: - f.write(out) + # Atomic write: run_python_passes rewrites the kernel .mlir in place outside + # load()'s FileLock, so a concurrent compile of the same source must never see a + # truncated file -- mlir-opt would parse it to an empty module and silently drop + # the kernel (-> undefined reference to wrapper_kernel at link). + from torch._inductor.codecache import write_atomic + write_atomic(out_path, out) return True diff --git a/PyTorchSimFrontend/mlir/passes/_mlir_util.py b/PyTorchSimFrontend/mlir/passes/_mlir_util.py new file mode 100644 index 00000000..e39f9d6f --- /dev/null +++ b/PyTorchSimFrontend/mlir/passes/_mlir_util.py @@ -0,0 +1,87 @@ +"""Small, dependency-light helpers shared across the MLIR passes. + +Every pass had its own copy of the same op-walk generator (named variously +`_iter_ops` / `_walk` / `_walk_ops`) and the same one-line attribute builders +(`_i32` / `_i64` / ...). This module is the single source for both. + +Import-safety: `walk_ops` is pure block/op attribute access and needs no MLIR +bindings, so this module does NOT import `mlir.ir` at top level -- some passes +(e.g. lower_vlane_idx, decompose_transfer) are deliberately importable without +the bindings present and only touch `mlir.ir` inside their run functions. The +attribute builders therefore import `mlir.ir` lazily; they require an active +MLIR context (the caller's `with ctx:`), exactly as the per-pass copies did. +""" + + +def walk_ops(block): + """Yield every op under `block` in program order, recursing into regions. + + Snapshots each block's operation list, so a caller may erase ops while + iterating (the strictest of the former copies; a superset of the rest).""" + for op in list(block.operations): + yield op + for region in op.operation.regions: + for b in region.blocks: + yield from walk_ops(b) + + +def _ir(): + import mlir.ir as ir + return ir + + +def i32(v): + """`i32` IntegerAttr for `v` (uses the active MLIR context).""" + ir = _ir() + return ir.IntegerAttr.get(ir.IntegerType.get_signless(32), int(v)) + + +def i64(v): + """`i64` IntegerAttr for `v`.""" + ir = _ir() + return ir.IntegerAttr.get(ir.IntegerType.get_signless(64), int(v)) + + +def i64_array(vals): + """ArrayAttr of `i64` IntegerAttrs for `vals`.""" + ir = _ir() + i = ir.IntegerType.get_signless(64) + return ir.ArrayAttr.get([ir.IntegerAttr.get(i, int(v)) for v in vals]) + + +def str_attr(v): + """StringAttr of `str(v)`.""" + ir = _ir() + return ir.StringAttr.get(str(v)) + + +# --------------------------------------------------------------------------- +# attribute readers -- accept an OpView or an Operation; `default` is returned +# when `key` is absent (callers that want the strict "must be present" behaviour +# simply never pass an absent key). +# --------------------------------------------------------------------------- +def _attrs(op): + return getattr(op, "operation", op).attributes + + +def attr_int(op, key, default=None): + """Integer value of `op`'s `key` attribute, or `default` if absent.""" + ir = _ir() + a = _attrs(op) + return ir.IntegerAttr(a[key]).value if key in a else default + + +def attr_bool(op, key, default=False): + """Bool value of `op`'s `key` attribute, or `default` if absent.""" + ir = _ir() + a = _attrs(op) + return bool(ir.BoolAttr(a[key]).value) if key in a else default + + +def attr_i64_array(op, key, default=None): + """`op`'s `key` ArrayAttr of integers as a Python list, or `default` if + absent (pass `default=[]` for the "missing -> empty" convention).""" + ir = _ir() + a = _attrs(op) + return ([ir.IntegerAttr(x).value for x in ir.ArrayAttr(a[key])] + if key in a else default) diff --git a/PyTorchSimFrontend/mlir/passes/build_skeleton.py b/PyTorchSimFrontend/mlir/passes/build_skeleton.py new file mode 100644 index 00000000..5a8c35b7 --- /dev/null +++ b/PyTorchSimFrontend/mlir/passes/build_skeleton.py @@ -0,0 +1,597 @@ +"""build_skeleton pass (C2): reduce a kernel's post-vcix MLIR to the +*skeleton + API* form, in place. + +The trace pipeline (docs/design/togsim_cpp_trace.md) compiles a kernel to a +shape-parametric C++ trace producer. The producer is just the kernel's loop +skeleton with the data computation replaced by calls to the event-based runtime +API. This pass performs that reduction at the MLIR level: + + * `togsim.transfer` -> `togsim.dma(...) {tag_id, is_async, ...}` carrying the + runtime tag index operand (`%tag[%idx]`). + * `togsim.wait` -> `togsim.memory_barrier(tag_idx) {tag_id, write_bufs}`, + the explicit async-DMA sync. It pairs with its dma by + the RUNTIME tag slot (tag_id + the tag index), not a + compile-time id: one static dma op runs once per loop + iteration with a different `%tag[%idx]`, so only the + runtime slot can pair iteration i's dma with its wait. + * each compute node -> a single `togsim.compute {tile_id, compute_type}` + * everything else -> removed by a use-based DCE, keeping the loops and the + index/address arithmetic the survivors depend on. + +It reuses build_tog's traversal (`TogBuilder` / `_build`): loops, DMAs and +compute blocks are already identified there, each with a back-pointer to its +MLIR op(s), so this pass only adds the *rewrite*. Keeping a single traversal +guarantees the skeleton and the legacy TOG see the same structure. + +Counterpart to `build_tog.build_tog_and_mutate`. + +The DCE is safe by construction: it never erases an op whose results still have +uses, so at worst it leaves extra ops in the dump (visible for diagnosis) rather +than producing invalid IR. + +Requires the MLIR Python bindings (importing `build_tog` pulls in `mlir.ir`). +""" + +from . import togsim_ops as ts +from ._mlir_util import walk_ops, i32, i64, i64_array, str_attr +from .build_tog import ( + ir, + TogBuilder, + _build, + _reset_ids, + _find_kernel, + _value_key, + TOGDMANode, + TOGDMAWaitNode, + _COMPUTE_TYPE_NAME, +) + +#: Marker op names for the passes/__init__ fast-path (skip parsing if absent). +MARKERS = ("togsim.transfer", "togsim.wait") + +#: Ops the DCE must never remove (loops, terminators, our API ops). +_KEEP = { + "affine.for", "scf.for", "scf.while", + "affine.yield", "scf.yield", "func.return", + ts.DMA, ts.COMPUTE, ts.MEMORY_BAR, +} + + +def _kernel_block(module): + func_op = _find_kernel(module) + if func_op is None: + return None + return func_op.regions[0].blocks[0] + + +# --------------------------------------------------------------------------- +# op construction +# --------------------------------------------------------------------------- +def _arg_id_of(base_addr): + """Tensor func-arg ordinal from a build_tog base name ("arg3" -> 3); -1 if + it is not a plain block-arg base.""" + s = str(base_addr) + return int(s[3:]) if s.startswith("arg") and s[3:].isdigit() else -1 + + +def _emit_dma(ctx, dma_node, tag_id, dram_index, tag_index, read_bufs, write_bufs): + """Insert a `togsim.dma` before the original `togsim.transfer`. + + `tag_id` is the identity of this DMA's tag memref. An async DMA pairs with + its `togsim.memory_barrier` (the original togsim.wait) by the RUNTIME tag slot + -- (tag_id, tag_index) -- not a compile-time identifier: one static dma op runs + once per loop iteration, each with a different runtime `%tag[%idx]` slot, so + only a runtime key can pair iteration i's dma with iteration i's wait. + + `dram_index` is the original linear DRAM index Value (the `affine.apply` + result that indexed the tensor in the `togsim.transfer`) -- carried as an + operand so the DCE keeps the address arithmetic live and the C4 lowering can + compute the real `base_addr = base[arg_id] + index*elem` (P3, approach A). + + `tag_index` is the original SRAM tag index Value (`%tag[%idx]`), carried as a + second operand: the runtime tag slot, used both to pair with the barrier and + for the double-buffer / SRAM-capacity (WAR) model. + Operand order: [dram_index, tag_index] (each omitted if absent).""" + op = dma_node.op + attrs = { + ts.ATTR_DIR: i32(ts.DIR_STORE if dma_node.is_write else ts.DIR_LOAD), + ts.ATTR_DIMS: i64_array(dma_node.tile_size), + ts.ATTR_STRIDES: i64_array(dma_node.tile_stride), + ts.ATTR_ELEM_BITS: i32(dma_node.element_size), + ts.ATTR_IS_ASYNC: ir.BoolAttr.get(bool(dma_node.is_async)), + ts.ATTR_TAG_ID: i32(tag_id), + ts.ATTR_ARG_ID: i32(_arg_id_of(dma_node.base_addr)), + "base": str_attr(dma_node.base_addr), + # SRAM spad this DMA touches (load writes it, store reads it) -- sec 10. + ts.ATTR_READ_BUFS: i64_array(read_bufs), + ts.ATTR_WRITE_BUFS: i64_array(write_bufs), + } + operands = [v for v in (dram_index, tag_index) if v is not None] + ir.Operation.create( + ts.DMA, + results=[], + operands=operands, + attributes=attrs, + loc=ir.Location.unknown(ctx), + ip=ir.InsertionPoint(op), + ) + + +def _emit_memory_bar(ctx, anchor_op, tag_id, tag_index, write_bufs): + """Insert a `togsim.memory_barrier` before `anchor_op` -- the explicit + async-DMA sync that was the original `togsim.wait`. It pairs with its + async `togsim.dma` by the RUNTIME tag slot (tag_id + tag_index), and carries + the SRAM buffer that dma loaded so consumers gate on data-arrival, not on the + async dma's issue-complete.""" + attrs = { + ts.ATTR_TAG_ID: i32(tag_id), + ts.ATTR_WRITE_BUFS: i64_array(write_bufs), + } + operands = [tag_index] if tag_index is not None else [] + ir.Operation.create( + ts.MEMORY_BAR, results=[], operands=operands, attributes=attrs, + loc=ir.Location.unknown(ctx), ip=ir.InsertionPoint(anchor_op)) + + +def _flatten_add(expr): + """Top-level additive summands of an AffineExpr (`.lhs`/`.rhs` come back typed + as the base AffineExpr, so use the `isinstance`/cast pattern, not Python + isinstance).""" + if ir.AffineAddExpr.isinstance(expr): + a = ir.AffineAddExpr(expr) + return _flatten_add(a.lhs) + _flatten_add(a.rhs) + return [expr] + + +def _neg_coeff_dim(summand): + """If `summand` is `dim * c` with a negative constant `c`, return that dim's + position; else None. lower_to_vcix tags each accumulation (reduction) loop var + with coefficient -1 in the togsim.wait tag index -- a SENTINEL marking the + reduction axis, not an arithmetic offset (legacy TileGraphParser skips stride + -1 for the same reason).""" + if not ir.AffineMulExpr.isinstance(summand): + return None + mul = ir.AffineMulExpr(summand) + l, r = mul.lhs, mul.rhs + dim = l if ir.AffineDimExpr.isinstance(l) else (r if ir.AffineDimExpr.isinstance(r) else None) + con = l if ir.AffineConstantExpr.isinstance(l) else (r if ir.AffineConstantExpr.isinstance(r) else None) + if dim is None or con is None or ir.AffineConstantExpr(con).value >= 0: + return None + return ir.AffineDimExpr(dim).position + + +def _strip_accum_terms(ctx, tag_index, anchor_op): + """Return a tag-index Value with the accumulation-marked (-1 coefficient) terms + dropped, so a memory_barrier waits on the SAME subtile slot its async load + wrote. + + The wait tag index built by lower_to_vcix carries `-acc_iv` for each reduction + loop var; the matching load index (dma_fine_grained) is subtile-only. Without + this, at reduction iteration > 0 the producer EVALUATES `-acc_iv` to a negative + slot, so the recorded barrier slot diverges from the load slot and the runtime + tag pairing fails (TOGSim aborts with "Key does not exist in ... tag table"). + Dropping the -1 terms mirrors legacy TileGraphParser.cc, which skips stride -1 + and routes the reduction axis to a separate accum tag component; here the + per-iteration tag alloc (dma_fine_grained) already separates the reductions, so + the barrier only needs the subtile slot. + + Falls through (returns `tag_index` unchanged) for anything that is not an + affine.apply whose single result carries such a term -- e.g. the single-tile + case, whose index has no reduction term.""" + if tag_index is None: + return None + try: + apply_op = tag_index.owner + if apply_op.name != "affine.apply": + return tag_index + amap = ir.AffineMapAttr(apply_op.attributes["map"]).value + except Exception: + return tag_index + if amap.n_dims == 0 or amap.n_symbols != 0 or len(amap.results) != 1: + return tag_index + expr = amap.results[0] + dropped = sorted({p for p in (_neg_coeff_dim(s) for s in _flatten_add(expr)) + if p is not None}) + if not dropped: + return tag_index + n = amap.n_dims + kept = [i for i in range(n) if i not in dropped] + new_pos = {old: i for i, old in enumerate(kept)} + # compose the original expr with a selector that sends each dropped dim to 0 + # and renumbers the kept dims 0..k-1. + sel = [ir.AffineConstantExpr.get(0) if i in dropped + else ir.AffineDimExpr.get(new_pos[i]) for i in range(n)] + new_expr = expr.compose(ir.AffineMap.get(len(kept), 0, sel)) + new_map = ir.AffineMap.get(len(kept), 0, [new_expr]) + operands = list(apply_op.operands) + new_operands = [operands[i] for i in kept] + new_apply = ir.Operation.create( + "affine.apply", + results=[ir.IndexType.get(ctx)], + operands=new_operands, + attributes={"map": ir.AffineMapAttr.get(new_map)}, + loc=ir.Location.unknown(ctx), + ip=ir.InsertionPoint(anchor_op), + ) + return new_apply.results[0] + + +def _emit_compute(ctx, compute_node, tile_id, read_bufs, write_bufs): + front = compute_node.operations[0] + attrs = { + ts.ATTR_TILE_ID: i64(tile_id), + # int code (0 vector / 1 matmul / 2 preload) consumed by the C4 lowering; + # maps directly to the Core compute-unit enum. Keep the readable name too. + ts.ATTR_COMPUTE_TYPE: i32(int(compute_node.compute_type)), + "compute_type_name": str_attr(_COMPUTE_TYPE_NAME[compute_node.compute_type]), + # SRAM buffer ids read/written (sec 10 dataflow); the bridge builds the + # dependency DAG by last-writer per buffer. + ts.ATTR_READ_BUFS: i64_array(read_bufs), + ts.ATTR_WRITE_BUFS: i64_array(write_bufs), + } + ir.Operation.create( + ts.COMPUTE, + results=[], + operands=[], + attributes=attrs, + loc=ir.Location.unknown(ctx), + ip=ir.InsertionPoint(front), + ) + + +# --------------------------------------------------------------------------- +# DCE +# --------------------------------------------------------------------------- +def _has_nonempty_region(op): + for region in op.operation.regions: + for b in region.blocks: + if len(list(b.operations)) > 0: + return True + return False + + +def _results_unused(op): + for r in op.operation.results: + if len(list(r.uses)) > 0: + return False + return True + + +def _strip_loop_iter_args(block): + """Drop loop-carried values (iter_args) from every affine.for/scf.for. + + The skeleton only needs the loop STRUCTURE (iteration counts) and the + togsim.* markers -- not the data flowing through the loop. Reduction kernels + carry a *vector* accumulator as an iter_arg; EmitC/C++ cannot represent a + loop carrying a vector, so the trace .so emission fails. Since the trace is + timing-only (values come from the recorded run), we rebuild each loop without + iter_args: body uses of an iter_arg become its init value, the loop result + becomes its init, and the now-orphaned accumulate ops are removed by _dce. + """ + # Only strip a loop whose RESULTS are unused (dead for the trace): the carried + # value goes nowhere live, so dropping it is safe. A loop whose result still + # feeds a kept op (e.g. an index accumulator consumed by a togsim.dma address) + # is left untouched. Run after _dce so the result store is already gone; then + # nested reductions free up inner results round by round (outer stripped first). + while True: + tgt = None + for op in walk_ops(block): + n = op.operation.name + if (n in ("affine.for", "scf.for") and len(op.operation.results) > 0 + and _results_unused(op)): + tgt = op + break + if tgt is None: + return + _rebuild_loop_no_iter(tgt) + + +def _rebuild_loop_no_iter(op): + o = op.operation + nres = len(o.results) + n_in = len(o.operands) + inits = [o.operands[n_in - nres + i] for i in range(nres)] + keep_operands = [o.operands[i] for i in range(n_in - nres)] # bound operands only + old_block = o.regions[0].blocks[0] + oargs = list(old_block.arguments) # [iv, *iter_args] + + attrs = {na.name: na.attr for na in o.attributes} + # affine.for tags its operand groups; zero the iter-arg group (last entry). + if "operandSegmentSizes" in attrs: + seg = [int(x) for x in str(attrs["operandSegmentSizes"]).split(":")[1].strip(" >").split(",")] + seg[-1] = 0 + attrs["operandSegmentSizes"] = ir.Attribute.parse( + "array") + + loc = ir.Location.unknown(o.context) + with loc: # default loc for new block args + new = ir.Operation.create(o.name, results=[], operands=keep_operands, + attributes=attrs, regions=1, loc=loc, + ip=ir.InsertionPoint(o)) + nb = new.regions[0].blocks.append(oargs[0].type) # block with the iv arg only + + oargs[0].replace_all_uses_with(nb.arguments[0]) # iv + for ba, ini in zip(oargs[1:], inits): # iter-arg uses -> init + ba.replace_all_uses_with(ini) + for res, ini in zip(o.results, inits): # loop result -> init + res.replace_all_uses_with(ini) + + term_name = "affine.yield" if o.name == "affine.for" else "scf.yield" + with ir.InsertionPoint(nb): + ir.Operation.create(term_name, results=[], operands=[], loc=loc) + new_term = list(nb.operations)[0] + for bop in list(old_block.operations)[:-1]: # move body (drop old yield) + bop.operation.move_before(new_term) + o.erase() + + +def _dce(block): + """Erase non-kept ops with no used results, to a fixed point. Safe: an op + with live SSA uses is never touched.""" + changed = True + while changed: + changed = False + victims = [] + for op in walk_ops(block): + name = op.operation.name + if name in _KEEP: + continue + if _has_nonempty_region(op): + continue + if _results_unused(op): + victims.append(op) + for op in victims: + try: + op.operation.erase() + changed = True + except Exception: + # Still referenced via something we will erase next round; retry. + pass + + +# --------------------------------------------------------------------------- +# driver +# --------------------------------------------------------------------------- +def _collect_dma_nodes(builder): + """Map op-identity -> DMA/DMAWait node, by walking the built tree.""" + by_op = {} + seen = set() + + def visit(n): + if id(n) in seen: + return + seen.add(id(n)) + if isinstance(n, (TOGDMANode, TOGDMAWaitNode)) and n.op is not None: + by_op[id(n.op.operation)] = n + for c in n.children: + visit(c) + + for ln in builder.loop_nodes: + visit(ln) + return by_op + + +class _BufferIds: + """Assigns each SRAM buffer name a stable small int id, shared by DMA and + compute so the bridge can match a reader to its buffer's writer (sec 10). + The virtual SA_WEIGHTS buffer (preload -> matmul) is numbered here too, on + first sight. `None` (a non-buffer base) is -1.""" + + def __init__(self): + self._ids = {} + + def of(self, name): + if name is None: + return -1 + return self._ids.setdefault(name, len(self._ids)) + + +class _TagIds: + """Identity of a DMA's tag memref -> stable small int, plus the SRAM buffer + that tag's async DMA loads. An async dma and its memory_barrier (the original + togsim.wait) share a tag memref; this assigns it a tag_id (so the runtime can + pair them by the runtime tag slot) and remembers the loaded buffer so the + barrier can release it to consumers. Pairing is by tag, never a static id.""" + + def __init__(self): + self._ids = {} # tag value-key -> tag_id + self._buf = {} # tag value-key -> SRAM buffer id the dma loads + + def bind(self, key, buf): + tag_id = self._ids.setdefault(key, len(self._ids)) + self._buf[key] = buf + return tag_id + + def lookup(self, key): + """(tag_id, buffer) for a tag memref, or None if no dma used it.""" + if key not in self._ids: + return None + return self._ids[key], self._buf[key] + + +def _emit_computes(ctx, builder, bufs): + """Step 1: each compute node -> one togsim.compute carrying its tile_id and + the ids of the SRAM buffers it reads/writes. Returns the count.""" + from . import dep_analysis as dep # lazy: dep_analysis imports build_skeleton + n = 0 + for tile_id, cn in enumerate(builder.compute_nodes): + if not cn.operations: + continue + reads, writes = dep.compute_buffers(cn) + _emit_compute(ctx, cn, tile_id, + sorted(bufs.of(b) for b in reads), + sorted(bufs.of(b) for b in writes)) + n += 1 + return n + + +def _transfer_fields(op): + """Decode a `togsim.transfer`'s fixed operands by position. + + Layout (see mlir_codegen_backend.emit_transfer / lower_transfer_to_gemmini): + operands: dram, dram_idx, sram, sram_idx, tag, tag_idx, dma_type, vst + [, offset_spad] # 8 or 9 operands + Unlike the old `memref.dma_start`, dram/sram are FIXED (not direction-swapped): + the DRAM side is always operand[0]/[1], the SRAM spad always operand[2], the + runtime tag slot always operand[4] (tag memref) + operand[5] (tag_idx). The + optional indirect-offset spad is operand[8]; its owning `memref.get_global` + carries the offset symbol name in its "name" attribute (matching + lower_transfer_to_gemmini's offset_sym derivation).""" + operands = list(op.operands) + offset = operands[8] if "indirect" in op.attributes else None + return { + "dram": operands[0], "dram_idx": operands[1], + "sram": operands[2], "sram_idx": operands[3], + "tag": operands[4], "tag_idx": operands[5], + "dma_type": operands[6], "vst": operands[7], + "offset": offset, + } + + +def _emit_one_dma(ctx, op, node, builder, bufs, tags): + """Rewrite one togsim.transfer as togsim.dma. A load reads DRAM and writes + its SRAM spad; a store reads the spad and writes DRAM -- which sets the + read/write buffer that drives the dependency edge (sec 10). The tag memref is + bound to a tag_id (with its loaded buffer) so the paired memory_barrier finds + it by the runtime tag slot.""" + from . import dep_analysis as dep # lazy: dep_analysis imports build_skeleton + f = _transfer_fields(op) + # dram/sram are fixed operands now (not direction-swapped): the DRAM index is + # always operand[1], the SRAM spad always operand[2]. Direction (read/write) + # comes from the node (dma_kind attr / dma_type value). + dram_index = f["dram_idx"] + tag_index = f["tag_idx"] # single runtime tag slot operand (%tag[%idx]) + spad_id = bufs.of(dep._global_of(f["sram"])) + read_bufs = [spad_id] if node.is_write else [] + write_bufs = [] if node.is_write else [spad_id] + if f["offset"] is not None: # gather/scatter reads the offset spad -> dep on its build + # the offset symbol name lives on the offset operand's owning get_global + # ("name" attr), the same place lower_transfer_to_gemmini reads it. + off_owner = f["offset"].owner + off_sym = str(off_owner.attributes["name"]).strip('@" ') + off_id = bufs.of(off_sym) + if off_id not in read_bufs: + read_bufs = read_bufs + [off_id] + tag_id = tags.bind(_value_key(f["tag"]), spad_id) + _emit_dma(ctx, node, tag_id, dram_index, tag_index, read_bufs, write_bufs) + + +def _emit_one_wait(ctx, op, tags): + """Rewrite one togsim.wait as togsim.memory_barrier -- the explicit + async-DMA sync already in the IR. Paired with its dma by the tag memref + (tag_id) and the runtime tag index; carries the buffer the dma loaded. + Returns True iff emitted (a wait whose tag no dma used is dropped).""" + operands = list(op.operation.operands) + tag = operands[0] + tag_index = operands[1] if len(operands) >= 2 else None + binding = tags.lookup(_value_key(tag)) + if binding is None: + return False + tag_id, buf = binding + # honor lower_to_vcix's -1 accumulation marker: strip the reduction terms so + # the barrier slot equals the subtile slot the paired async load wrote. + tag_index = _strip_accum_terms(ctx, tag_index, op) + _emit_memory_bar(ctx, op, tag_id, tag_index, [buf]) + return True + + +def _emit_dmas_and_waits(ctx, block, builder, dma_by_op, bufs): + """Step 2: rewrite togsim.transfer -> togsim.dma and togsim.wait -> + togsim.memory_barrier in program order. An async dma and its barrier are + paired by the RUNTIME tag slot (tag_id + tag index), not a compile-time id: + one static dma op runs per loop iteration with a different `%tag[%idx]`, so + only the runtime slot can pair iteration i's dma with iteration i's wait. + Returns the original ops to erase and the (dma, wait) counts.""" + tags = _TagIds() + originals = [] + n_dma = n_wait = 0 + for op in list(walk_ops(block)): + name = op.operation.name + if name == "togsim.transfer": + node = dma_by_op.get(id(op.operation)) + if node is None: + continue + _emit_one_dma(ctx, op, node, builder, bufs, tags) + originals.append(op) + n_dma += 1 + elif name == "togsim.wait": + if _emit_one_wait(ctx, op, tags): + n_wait += 1 + originals.append(op) + return originals, n_dma, n_wait + + +def build_skeleton(module): + """Reduce `func.func @kernel` in `module` to the skeleton+API form, in place. + + Four steps: analyze the kernel into loop/compute/DMA nodes, emit a + togsim.compute per compute node, rewrite the DMAs/waits to togsim.dma/wait, + then DCE the leftover data computation. Returns a short text report (counts). + """ + _reset_ids() + builder = TogBuilder() + _build(module, builder) # populates loop/compute nodes + op back-pointers + + block = _kernel_block(module) + if block is None: + return "no @kernel found" + ctx = module.context + dma_by_op = _collect_dma_nodes(builder) + bufs = _BufferIds() + + n_compute = _emit_computes(ctx, builder, bufs) + originals, n_dma, n_wait = _emit_dmas_and_waits(ctx, block, builder, dma_by_op, bufs) + + # erase the now-replaced originals (result-less -> safe), then strip the + # leftover data computation. + for op in originals: + try: + op.operation.erase() + except Exception: + pass + _dce(block) # drop dead consumers (e.g. the result store) first, + _strip_loop_iter_args(block) # so a now-unused loop result lets us strip its iter_args + _dce(block) # then clean the orphaned accumulate ops + + return ("skeleton: compute=%d dma=%d wait=%d (unpaired waits dropped)" + % (n_compute, n_dma, n_wait)) + + +def run(module, vectorlane=128): + """passes/__init__ pass protocol entry (vectorlane unused; kept for parity).""" + build_skeleton(module) + + +def run_skeleton(in_path, out_path=None): + """Read post-vcix MLIR at `in_path`, reduce to skeleton+API, write it out. + + Requires the MLIR bindings. + """ + if out_path is None: + out_path = in_path + ctx = ir.Context() + ctx.allow_unregistered_dialects = True + with ctx: + module = ir.Module.parse(open(in_path).read(), ctx) + report = build_skeleton(module) + with open(out_path, "w") as fh: + fh.write(str(module)) + return report + + +def main(argv): + import argparse + + parser = argparse.ArgumentParser(prog="build_skeleton.py") + parser.add_argument("input") + parser.add_argument("--out", default=None) + args = parser.parse_args(argv[1:]) + report = run_skeleton(args.input, args.out) + import sys + sys.stderr.write(report + "\n") + return 0 + + +if __name__ == "__main__": + import sys + sys.exit(main(sys.argv)) diff --git a/PyTorchSimFrontend/mlir/passes/build_tog.py b/PyTorchSimFrontend/mlir/passes/build_tog.py index ae515010..5a40feec 100644 --- a/PyTorchSimFrontend/mlir/passes/build_tog.py +++ b/PyTorchSimFrontend/mlir/passes/build_tog.py @@ -608,11 +608,11 @@ def bool_true(k): self.print_operation(inner, loop_node) return - if name == "memref.dma_start": + if name == "togsim.transfer": self._handle_dma_start(op, node) return - if name == "memref.dma_wait": + if name == "togsim.wait": self._handle_dma_wait(op, node) return @@ -716,36 +716,60 @@ def _handle_compute(self, op, node): return self._append_vector_compute(node, op) - # ---- dma_start ---- - def _dma_start_fields(self, op): - """Decode memref.dma_start operands by memref ranks. + # ---- transfer (formerly memref.dma_start) ---- + @staticmethod + def _transfer_is_load(op, dma_type_operand): + """True if a `togsim.transfer` is a load (DRAM -> SRAM), False for a store. - Layout: src[srcIdx], dst[dstIdx], numElements, tag[tagIdx], stride, - numElementsPerStride. - """ + Prefer the `dma_kind` attr ("MVIN"/"MVIN2"/"MVIN3" load, "MVOUT" store); + fall back to the `dma_type` operand constant (MVIN=2/MVIN2=1/MVIN3=14 are + loads, MVOUT=3 is a store).""" + oper = op.operation + if "dma_kind" in oper.attributes: + try: + kind = ir.StringAttr(oper.attributes["dma_kind"]).value + except Exception: + kind = str(oper.attributes["dma_kind"]).strip('"') + if kind: + return kind.upper().startswith("MVIN") + c = _const_index_value(dma_type_operand) + if c is not None: + return c in (1, 2, 14) + return True + + def _dma_start_fields(self, op): + """Decode a `togsim.transfer` into the legacy src/dst view. + + togsim.transfer operand layout (mirrors build_skeleton._transfer_fields / + lower_transfer_to_gemmini): + dram, dram_idx, sram, sram_idx, tag, tag_idx, dma_type, vst[, offset] + The DRAM side is always operand[0]/[1], the SRAM spad operand[2]/[3], the + runtime tag slot operand[4] (tag memref) + operand[5] (tag_idx). The + optional indirect-offset spad is operand[8]. + + Direction (from dma_kind / dma_type) decides the src/dst mapping so the + rest of build_tog keeps the old memref.dma_start convention: for a load + the DRAM side is the SOURCE and the SRAM spad the DEST; a store reverses + it. src/dst therefore still carry the right memory spaces (DRAM=0, + SRAM=1) that `_handle_dma_start` recovers is_write from.""" operands = list(op.operands) - i = 0 - src = operands[i] - src_type = src.type - src_rank = len(ir.MemRefType(src_type).shape) - i += 1 - src_indices = operands[i:i + src_rank] - i += src_rank - dst = operands[i] - dst_type = dst.type - dst_rank = len(ir.MemRefType(dst_type).shape) - i += 1 - dst_indices = operands[i:i + dst_rank] - i += dst_rank - i += 1 # numElements - tag = operands[i] - tag_rank = len(ir.MemRefType(tag.type).shape) - i += 1 - tag_indices = operands[i:i + tag_rank] + dram, dram_idx = operands[0], operands[1] + sram, sram_idx = operands[2], operands[3] + tag, tag_idx = operands[4], operands[5] + dma_type = operands[6] + offset = operands[8] if len(operands) > 8 else None + + if self._transfer_is_load(op, dma_type): # DRAM -> SRAM + src, src_idx = dram, dram_idx + dst, dst_idx = sram, sram_idx + else: # SRAM -> DRAM + src, src_idx = sram, sram_idx + dst, dst_idx = dram, dram_idx return { - "src": src, "src_type": src_type, "src_indices": src_indices, - "dst": dst, "dst_type": dst_type, "dst_indices": dst_indices, - "tag": tag, "tag_indices": tag_indices, + "src": src, "src_type": src.type, "src_indices": [src_idx], + "dst": dst, "dst_type": dst.type, "dst_indices": [dst_idx], + "tag": tag, "tag_indices": [tag_idx], + "dma_type": dma_type, "offset": offset, } def _handle_dma_start(self, op, node): @@ -776,7 +800,7 @@ def _handle_dma_start(self, op, node): tile_size = [int(x) for x in tile_shape] tile_stride = [] - ds = _int_array_attr(oper, "dram_stride") + ds = _int_array_attr(oper, "dram_stride") # TOGDMANode.tile_stride keeps the DRAM stride (as before) if ds: tile_stride = list(ds) @@ -857,10 +881,11 @@ def _handle_dma_start(self, op, node): # ---- dma_wait ---- def _handle_dma_wait(self, op, node): oper = op.operation + # togsim.wait operands: (tag[0], tag_idx[1], num_elements[2]). tag_idx is + # now a single operand (memref.dma_wait had a variadic [tag_idx]). operands = list(oper.operands) tag = operands[0] - tag_rank = len(ir.MemRefType(tag.type).shape) - tag_indices = operands[1:1 + tag_rank] + tag_indices = operands[1:2] tag_index_list = [] tag_stride_list = [] @@ -880,11 +905,11 @@ def _handle_dma_wait(self, op, node): tag_stride_list = _collect_coefficients(amap.results[0]) tag_divider_list = _collect_dividers(amap.results[0]) - # base address: scan users of tag memref for a dma_start. + # base address: scan users of tag memref for a togsim.transfer. address = "arg" for use in tag.uses: user = use.owner - if user.name == "memref.dma_start": + if user.name == "togsim.transfer": f = self._dma_start_fields(user) dst_space = _memref_space(f["dst_type"]) src_space = _memref_space(f["src_type"]) diff --git a/PyTorchSimFrontend/mlir/passes/cycle_table.py b/PyTorchSimFrontend/mlir/passes/cycle_table.py new file mode 100644 index 00000000..53682131 --- /dev/null +++ b/PyTorchSimFrontend/mlir/passes/cycle_table.py @@ -0,0 +1,111 @@ +"""cycle_table (C3): the precomputed tile_id -> (cycle, overlapping_cycle) table +the C++ trace pipeline looks up at runtime (docs/design/togsim_cpp_trace.md sec +6, sec 9.8 task 4). + +A `togsim.compute(tile_id=...)` in the trace says *which* tile to compute, not +how long it takes. Because tiles are fixed size, each tile's cost is invariant +(only the trip count varies with shape), so it is sampled once and stored here, +keyed by `tile_id`. Two numbers per tile, mirroring the legacy TOG: + + * `cycle` -- full compute latency, sampled by gem5 sample-mode + (the existing measurement: `_rewrite_loop_steps` + + `_insert_compute_markers` in build_tog, run through + CycleSimulator -> the per-tile `cycle_list`). + * `overlapping_cycle` -- the portion that overlaps the previous instruction in + the systolic pipeline; the timing core uses it as + `finish = prev.finish + cycle - overlapped` (Core.cc). + Derived exactly as the legacy path does + (tog_generator.generate_tile_graph): + type 0 (VectorCompute) -> 0 + type 1 (MatmulCompute) -> max(cycle - x_offset, 0) + type 2 (MatmulPreload) -> max(cycle - w_offset, 0) + +This module only *builds/serializes* the table from a cycle_list; obtaining the +cycle_list reuses the existing sample-mode + gem5 path (wired in P3 task 5). The +`tile_id` order matches build_skeleton's `compute_nodes` order, which matches the +legacy TOG, so the same sampling keys both paths. + +Requires the MLIR Python bindings (to read the skeleton's togsim.compute ops). +""" + +import json + +from . import togsim_ops as ts +from ._mlir_util import walk_ops +from .build_tog import ( + ir, + VECTOR_COMPUTE, + MATMUL_COMPUTE, # noqa: F401 (documents the type enum used by the formula) + MATMUL_PRELOAD, +) + + +def overlapping_cycle(cycle, compute_type, x_offset, w_offset): + """Hideable (pipeline-overlapped) portion of `cycle`. Mirrors + tog_generator.generate_tile_graph.""" + if compute_type <= VECTOR_COMPUTE: # VectorCompute: no systolic overlap + return 0 + offset = w_offset if compute_type == MATMUL_PRELOAD else x_offset + return max(int(cycle) - int(offset), 0) + + +def _compute_types(skeleton_module): + """tile_id-ordered list of compute_type ints, from the skeleton's + togsim.compute ops.""" + items = [] + for op in walk_ops(skeleton_module.body): + if op.operation.name != ts.COMPUTE: + continue + tid = ir.IntegerAttr(op.operation.attributes[ts.ATTR_TILE_ID]).value + ct = ir.IntegerAttr(op.operation.attributes[ts.ATTR_COMPUTE_TYPE]).value + items.append((tid, ct)) + items.sort() + return [t for _, t in items] + + +def build_cycle_table(skeleton_module, cycle_list, x_offset, w_offset): + """Return `[(cycle, overlapping_cycle), ...]` indexed by tile_id. + + `cycle_list` is the per-tile gem5 measurement (compute_nodes order == + tile_id order). `x_offset`/`w_offset` are the systolic-fill offsets the + legacy path computes from the vector-lane size / loop size.""" + types = _compute_types(skeleton_module) + if len(cycle_list) != len(types): + raise ValueError( + "cycle_list (%d) does not match #compute tiles (%d)" + % (len(cycle_list), len(types))) + return [(int(c), overlapping_cycle(c, t, x_offset, w_offset)) + for c, t in zip(cycle_list, types)] + + +def dump_cycle_table(table, path, x_offset=None, w_offset=None): + """Serialize the table as a sidecar JSON next to the trace `.so`. The P3 C6 + loader reads it and sets compute_cycle + overlapping_cycle on each emitted + Instruction.""" + with open(path, "w") as fh: + json.dump({"x_offset": x_offset, "w_offset": w_offset, + "table": [list(e) for e in table]}, fh) + return path + + +def load_cycle_table(path): + with open(path) as fh: + return json.load(fh) + + +def dump_cycle_table_tsv(table, path, origins=None): + """Plain `cycleoverlapping` per line, in tile_id order -- the trivial + format the C++ `--cycle_table` loader (main.cc, P3 trace pipeline) reads with + ifstream (no JSON dependency in TOGSim). + + `origins` (the FX nodes this kernel came from) is recorded as a trailing + `# origins: ...` comment after the data rows -- the legacy ONNX TOG carried + this as node metadata. The C++ loader's `while (ct >> c >> o)` stops at the + `#` once all (cycle, overlapping) rows are read, so the comment is safe with + the current parser; a future TOGSim change can promote it to a real field.""" + with open(path, "w") as fh: + for cycle, overlapping in table: + fh.write("%d\t%d\n" % (int(cycle), int(overlapping))) + if origins: + fh.write("# origins: %s\n" % ", ".join(sorted(str(o) for o in origins))) + return path diff --git a/PyTorchSimFrontend/mlir/passes/decompose_transfer.py b/PyTorchSimFrontend/mlir/passes/decompose_transfer.py index c0e82b66..0bf04e30 100644 --- a/PyTorchSimFrontend/mlir/passes/decompose_transfer.py +++ b/PyTorchSimFrontend/mlir/passes/decompose_transfer.py @@ -32,13 +32,7 @@ OP_NAME = "togsim.transfer" MARKERS = (OP_NAME,) - -def _iter_ops(block): - for op in list(block.operations): - yield op - for region in op.operation.regions: - for b in region.blocks: - yield from _iter_ops(b) +from ._mlir_util import walk_ops def _int_array(attr): @@ -92,12 +86,15 @@ def run(module, vectorlane=128, **_): targets = [] for region in module.operation.regions: for b in region.blocks: - for op in _iter_ops(b): + for op in walk_ops(b): if op.operation.name == OP_NAME: targets.append(op.operation) for op in targets: - dram, dram_idx, sram, sram_idx, tag, dma_type, vst = op.operands + op_operands = list(op.operands) + dram, dram_idx, sram, sram_idx, tag, dma_type, vst = op_operands[:7] + # indirect: offset spad operand -> lift to a symbol attr (memref.dma_start can't take the operand) + offset_sym = op_operands[7].owner.attributes["name"] if len(op_operands) > 7 else None kind = op.attributes["dma_kind"].value # StringAttr -> "MVIN"/"MVOUT" vlane_axis = IntegerAttr(op.attributes["vlane_split_axis"]).value dram_stride = _int_array(op.attributes["dram_stride"]) @@ -133,6 +130,9 @@ def _emit(sram_mem, sram_indices, dram_idx_val, vsa_val, dr_attr, tl_attr, st_at if st_attr is not None: attrs["subtile_size"] = st_attr attrs["async"] = async_attr + if offset_sym is not None: + attrs["indirect_offset"] = offset_sym + attrs["offset_stride"] = op.attributes["offset_stride"] Operation.create( "memref.dma_start", results=[], operands=operands, attributes=attrs) diff --git a/PyTorchSimFrontend/mlir/passes/dep_analysis.py b/PyTorchSimFrontend/mlir/passes/dep_analysis.py new file mode 100644 index 00000000..06d8270d --- /dev/null +++ b/PyTorchSimFrontend/mlir/passes/dep_analysis.py @@ -0,0 +1,234 @@ +"""dep_analysis.py -- dependency-edge analysis for the C++ trace pipeline (P3, sec 10). + +The current TOG pass does NO dependency analysis (it emits a lexical loop tree + +runtime tags). This module derives the producer->consumer edges that the explicit +dataflow trace needs, from two sources available on the post-vcix IR (before +build_skeleton collapses the compute regions): + + 1. SRAM access: each DMA/compute's read/write SRAM buffer(s), recovered by + following SSA (a vcix.iv's input vector -> its vector.transfer_read -> the + memref -> @global), and the DMA's spad operand. Edge: a reader depends on + the last node that wrote the same buffer. + 2. vcix preload/matmul pairing: a matmul (vcix opcode 0) consumes the weights a + preceding preload (opcode 1) loaded into the systolic array -- an SA-internal + dependency NOT visible as a memref access, so it comes from the opcode order. + +This is a node-level analysis (one node per build_tog compute/DMA node); the loops +replay the nodes, so loop-carried edges (the Y_spad accumulator) are materialized +per iteration downstream. First cut: buffer granularity (slot-level value matching +is a later refinement). Output is an edge list for validation / to drive emit. +""" +import sys +import os + +from .build_tog import TogBuilder, ir, _reset_ids +from . import build_skeleton as _bs + + +def _global_of(memref_val): + """memref SSA value -> @global symbol name (e.g. 'X_spad'), or None.""" + owner = memref_val.owner + op = owner if isinstance(owner, ir.Operation) else getattr(owner, "operation", None) + if op is None: + return None + if op.name == "memref.get_global": + return str(op.attributes["name"]).strip('@" ') + # walk through view-like ops (subview/cast) to their source + if op.operands: + try: + return _global_of(op.operands[0]) + except Exception: + return None + return None + + +# Ops that touch SRAM-buffer DATA, by category. A view op (subview/reinterpret_cast) +# instead PRODUCES a memref -- pure address computation, skipped here; the real access +# is the load/store using it, whose memref operand _global_of traces back through the +# view to the @global. Anything else carrying a memref operand raises, so a NEW fusion +# pattern is caught at compile time rather than as a silent runtime deadlock. +_LOAD_OPS = {"vector.transfer_read", "affine.vector_load", "vector.load", + "memref.load", "affine.load"} +_STORE_OPS = {"vector.transfer_write", "affine.vector_store", "vector.store", + "memref.store", "affine.store"} +_IGNORE_OPS = {"memref.dealloc"} # lifetime, not a data access + + +def _is_memref(v): + try: + return ir.MemRefType.isinstance(v.type) + except Exception: + return False + + +def _walk_compute_ops(cn): + """Every op in the compute node, recursing into nested regions (loop bodies). A + fused epilogue (BatchNorm/ReLU) keeps its ops inside an un-unrolled affine.for, so + a top-level-only scan (cn.operations) sees just the loop and misses every access.""" + for top in cn.operations: + stack = [top] + while stack: + op = stack.pop() + yield op + for region in op.operation.regions: + for block in region.blocks: + stack.extend(block.operations) + + +def _rw_buffers_of_compute(cn): + """(reads, writes): the @global SRAM buffers a compute node reads/writes, walking + nested regions and classifying each op that touches a memref.""" + reads, writes = set(), set() + def rd(v): + b = _global_of(v) + if b: + reads.add(b) + def wr(v): + b = _global_of(v) + if b: + writes.add(b) + for op in _walk_compute_ops(cn): + if any(_is_memref(r) for r in op.results): + continue # view/cast/alloc -- address only + mrefs = [v for v in op.operands if _is_memref(v)] + if not mrefs: + continue + name = op.name + if name in _LOAD_OPS: + for v in mrefs: + rd(v) + elif name in _STORE_OPS: + for v in mrefs: + wr(v) # the store target memref + elif name == "memref.copy": + rd(mrefs[0]) + wr(mrefs[-1]) + elif name.startswith("linalg."): # DPS: ins read, outs read+write + for v in op.inputs: + if _is_memref(v): + rd(v) + for v in op.outputs: + if _is_memref(v): + rd(v) + wr(v) + elif name in _IGNORE_OPS: + continue + else: + raise RuntimeError( + f"dep_analysis: unclassified memref op '{name}' in a compute node -- " + f"it touches an SRAM buffer; classify it in _LOAD_OPS/_STORE_OPS") + return reads, writes + + +def _dma_buffer(builder, dma_node): + """The SRAM spad buffer a DMA touches (dst for load, src for store).""" + try: + f = builder._dma_start_fields(dma_node.op) + except Exception: + return None + val = f["dst"] if not dma_node.is_write else f["src"] + return _global_of(val) + + +# Virtual buffer for the systolic-array weight registers: a preload writes it, +# the following matmul reads it. This folds the SA-internal preload->matmul +# dependency (not a memref access) into the uniform "last-writer per buffer" rule. +SA_WEIGHTS = "__SA_WEIGHTS__" + + +def compute_buffers(cn): + """(read_buffers, write_buffers) for one compute node, including the virtual + SA_WEIGHTS edge (preload writes it, matmul reads it).""" + reads, writes = _rw_buffers_of_compute(cn) + if cn.compute_type == 1: # MATMUL consumes the preloaded weights + reads.add(SA_WEIGHTS) + elif cn.compute_type == 2: # PRELOAD loads them + writes.add(SA_WEIGHTS) + return reads, writes + + +def analyze(module): + """Return (nodes, edges). nodes: list of dicts; edges: list of (consumer_idx, + producer_idx, reason).""" + _reset_ids() + builder = TogBuilder() + _bs._build(module, builder) + + nodes = [] + # DMA nodes only (the map also contains TOGDMAWaitNode; keep real DMAs). + dma_nodes = [dn for dn in dict.fromkeys(_bs._collect_dma_nodes(builder).values()) + if hasattr(dn, "is_write")] + for dn in dma_nodes: + buf = _dma_buffer(builder, dn) + nodes.append({ + "kind": "STORE" if dn.is_write else "LOAD", + "buf": buf, "arg": str(dn.base_addr), + "reads": {buf} if dn.is_write else set(), + "writes": {buf} if not dn.is_write else set(), + "node": dn, + }) + for cn in builder.compute_nodes: + if not cn.operations: + continue + ct = {0: "VECTOR", 1: "MATMUL", 2: "PRELOAD"}.get(cn.compute_type, f"c{cn.compute_type}") + creads, cwrites = _rw_buffers_of_compute(cn) + nodes.append({ + "kind": ct, + "reads": creads, + "writes": cwrites, + "node": cn, + "compute_type": cn.compute_type, + }) + + # Order nodes by program position (last-writer needs program order: e.g. the + # store reads Y_spad written by the matmul, which lexically precedes it). + pos = {} + idx = [0] + def _index(op): + pos[op] = idx[0]; idx[0] += 1 + for r in op.regions: + for b in r.blocks: + for o in b.operations: + _index(o) + _index(module.operation) + def _key(n): + node = n["node"] + op = getattr(node, "op", None) or (node.operations[0] if getattr(node, "operations", None) else None) + return pos.get(op, 1 << 30) + nodes.sort(key=_key) + + # Edges: (1) buffer last-writer, (2) preload->matmul. + edges = [] + last_writer = {} # buffer -> node idx + prev_preload = None + for i, n in enumerate(nodes): + for b in sorted(n["reads"]): + if b in last_writer: + edges.append((i, last_writer[b], f"reads {b}")) + if n["kind"] == "MATMUL" and prev_preload is not None: + edges.append((i, prev_preload, "uses preloaded weights (vcix op1->op0)")) + for b in n["writes"]: + last_writer[b] = i + if n["kind"] == "PRELOAD": + prev_preload = i + return nodes, edges + + +def _main(): + path = sys.argv[1] + ctx = ir.Context(); ctx.allow_unregistered_dialects = True + with ctx: + module = ir.Module.parse(open(path).read(), ctx) + nodes, edges = analyze(module) + print("=== nodes ===") + for i, n in enumerate(nodes): + r = ",".join(sorted(n["reads"])) or "-" + w = ",".join(sorted(n["writes"])) or "-" + print(f" #{i:<2} {n['kind']:<8} reads[{r}] writes[{w}]") + print("=== edges (consumer -> producer) ===") + for c, p, why in edges: + print(f" #{c} ({nodes[c]['kind']}) -> #{p} ({nodes[p]['kind']}) [{why}]") + + +if __name__ == "__main__": + _main() diff --git a/PyTorchSimFrontend/mlir/passes/dma_fine_grained.py b/PyTorchSimFrontend/mlir/passes/dma_fine_grained.py index 3f583ef2..b9b482d6 100644 --- a/PyTorchSimFrontend/mlir/passes/dma_fine_grained.py +++ b/PyTorchSimFrontend/mlir/passes/dma_fine_grained.py @@ -11,16 +11,20 @@ IRMapping; the MLIR Python bindings expose no IRMapping, so this port builds the fused nest directly and emits each DMA inside it using the fused induction vars (equivalence target: same loop structure / counts, same offset maps, same -dma_start operands+attrs -- validated against mlir-opt -dma-fine-grained and the -end-to-end gemm/conv/model tests, not byte-exact SSA text). +togsim.transfer operands+attrs -- validated against mlir-opt -dma-fine-grained and +the end-to-end gemm/conv/model tests, not byte-exact SSA text). -Operates on the customized memref.dma_start convention (see lower_dma_to_gemmini): -operands = src, *src_idx, dst, *dst_idx, num_elements(dma_type), tag, *tag_idx, -stride(=vlane_split_axis), num_elements_per_stride(=vlane_stride). MVIN dma_type in -{2,1,14}; tile shape = dst shape for MVIN. +Operates on the togsim.transfer convention (see mlir_codegen_backend.emit_transfer +and lower_transfer_to_gemmini): operands = dram, dram_idx, sram, sram_idx, tag, +tag_idx, dma_type, vst(=vlane_stride)[, offset]; attrs = dma_kind, vlane_split_axis +(i64), dram_stride[], tile_stride[], padding, [subtile_size, async]. Direction is +derived from dma_kind / dma_type: MVIN => src=dram, dst=sram; MVOUT => src=sram, +dst=dram. tile shape = the sram memref shape for BOTH directions. MVIN dma_type in +{2,1,14}. Pipeline entry point: run_fine_grained(in_path, out_path, vectorlane). """ +import itertools import os import sys @@ -30,6 +34,8 @@ import mlir.ir as ir # noqa: E402 +from ._mlir_util import walk_ops, attr_i64_array + MARKERS = ("subtile_size",) # only subtile DMAs are split MVIN, MVIN2, MVIN3, MVOUT = 2, 1, 14, 3 @@ -54,36 +60,50 @@ def _const_int(value, default=-1): return default -def _int_array_attr(op, key): - if key not in op.attributes: - return [] - return [ir.IntegerAttr(a).value for a in ir.ArrayAttr(op.attributes[key])] - - def _is_block_arg(v): return isinstance(v, ir.BlockArgument) class _Dma: - """Positional view of a customized memref.dma_start op.""" + """Positional view of a togsim.transfer op. + + operands: dram, dram_idx, sram, sram_idx, tag, tag_idx, dma_type, vst[, offset] + Direction from dma_kind / dma_type: MVIN => src=dram, dst=sram (MVOUT swaps). + self.src_idx is a single-element list holding the base DRAM idx for MVIN (the + SRAM idx for MVOUT); tile_shape is always the sram memref shape. + """ def __init__(self, op): self.op = op operands = list(op.operands) - src_rank = len(ir.MemRefType(operands[0].type).shape) - i = 0 - self.src = operands[i]; i += 1 - self.src_idx = operands[i:i + src_rank]; i += src_rank - self.dst = operands[i]; i += 1 - dst_rank = len(ir.MemRefType(self.dst.type).shape) - self.dst_idx = operands[i:i + dst_rank]; i += dst_rank - self.num_elements = operands[i]; i += 1 - self.tag = operands[i]; i += 1 - tag_rank = len(ir.MemRefType(self.tag.type).shape) - self.tag_idx = operands[i:i + tag_rank]; i += tag_rank - self.stride = operands[i]; i += 1 # = vlane_split_axis - self.num_elements_per_stride = operands[i] # = vlane_stride - self.src_rank, self.dst_rank, self.tag_rank = src_rank, dst_rank, tag_rank + # dram, dram_idx, sram, sram_idx, tag, tag_idx, dma_type, vst[, offset] + self.dram = operands[0] + self.dram_idx = operands[1] + self.sram = operands[2] + self.sram_idx = operands[3] + self.tag = operands[4] + self.tag_idx = operands[5] + self.num_elements = operands[6] # = dma_type const operand + self.num_elements_per_stride = operands[7] # = vlane_stride (vst) + # trailing operands: [offset (indirect)] then (low, high) per masked axis. + _extra = operands[8:] + self.offset = None + if "indirect" in op.attributes: + self.offset = _extra[0] + _extra = _extra[1:] + self.masked_axes = attr_i64_array(op, "masked_axes", default=[]) + self.masked_ops = _extra # low0, high0, low1, high1, ... + + self.sram_rank = len(ir.MemRefType(self.sram.type).shape) + # Direction: MVIN reads dram -> sram; MVOUT writes sram -> dram. + if self.is_mvin: + self.src, self.dst = self.dram, self.sram + self.src_idx = [self.dram_idx] + else: + self.src, self.dst = self.sram, self.dram + self.src_idx = [self.sram_idx] + self.src_rank = len(ir.MemRefType(self.src.type).shape) + self.dst_rank = len(ir.MemRefType(self.dst.type).shape) @property def dma_type(self): @@ -95,24 +115,24 @@ def is_mvin(self): @property def vlane_split_axis(self): - return _const_int(self.stride) + return ir.IntegerAttr(self.op.attributes["vlane_split_axis"]).value @property def vlane_stride(self): return _const_int(self.num_elements_per_stride) & 0x7FFF def tile_shape(self): - mt = ir.MemRefType((self.dst if self.is_mvin else self.src).type) - return list(mt.shape) + return list(ir.MemRefType(self.sram.type).shape) def subtile_size(self): - return _int_array_attr(self.op, "subtile_size") + return attr_i64_array(self.op, "subtile_size", default=[]) def sram_stride(self): - return _int_array_attr(self.op, "sram_stride") + # togsim.transfer names the spad stride "tile_stride". + return attr_i64_array(self.op, "tile_stride", default=[]) def dram_stride(self): - return _int_array_attr(self.op, "dram_stride") + return attr_i64_array(self.op, "dram_stride", default=[]) def is_async(self): a = self.op.attributes @@ -203,10 +223,14 @@ def _apply(map_, operands, ip): def _dma_attrs(dma): - """Mirror getDmaAttrs: keep subtile/sram/dram strides, set async + fine_grained.""" + """Build the emitted togsim.transfer's attrs: copy dma_kind, vlane_split_axis, + dram_stride, tile_stride (the spad stride), subtile_size and padding straight + from the source op; set async (BoolAttr) + fine_grained (BoolAttr true).""" attrs = {} op = dma.op - for k in ("subtile_size", "sram_stride", "dram_stride"): + for k in ("dma_kind", "vlane_split_axis", "dram_stride", "tile_stride", + "subtile_size", "padding", "masked_axes", "masked_fill", "indirect", + "offset_stride", "accumulate", "acc_float"): if k in op.attributes: attrs[k] = op.attributes[k] attrs["async"] = ir.BoolAttr.get(dma.is_async()) @@ -214,27 +238,41 @@ def _dma_attrs(dma): return attrs +def _remap_bound(bound, iv, sub, is_high, ip): + """The masked low/high are full-tile-local; shift to this subtile: subtile position + p maps to full-tile p + iv*sub, so subtile-local high = min(sub, high - iv*sub) and + low = max(0, low - iv*sub). Out-of-window (neg high / low>sub) -> Spike skips all.""" + from mlir.dialects import affine + d0, d1 = ir.AffineDimExpr.get(0), ir.AffineDimExpr.get(1) + edge = ir.AffineConstantExpr.get(sub if is_high else 0) + m = ir.AffineMap.get(2, 0, [edge, d0 - d1 * sub]) + op = affine.AffineMinOp if is_high else affine.AffineMaxOp + return op(m, [bound, iv], ip=ip).result + + def _emit_dma(dma, ivs, vectorlane, ip): - """Emit one fine-grained memref.dma_start at `ip`, indexed by `ivs` (the fused + """Emit one fine-grained togsim.transfer at `ip`, indexed by `ivs` (the fused induction vars for this DMA's dims, in dim order).""" - idx_ty = ir.IndexType.get() - zero = _const_index(0, ip) - dram_off = _apply(_build_dram_map(dma), ivs, ip) - src_idx0 = dma.src_idx[0] - dram_idx = _apply(_sum_map(), [dram_off, src_idx0], ip) + # DRAM base index = the original transfer's dram_idx operand. + dram_idx = _apply(_sum_map(), [dram_off, dma.dram_idx], ip) + # SRAM offset is a SINGLE linear sram_idx operand (row-major stride 1). sram_off = _apply(_build_sram_map(dma, vectorlane), ivs, ip) + # Per-subtile tag index (required for async DMA<->barrier pairing downstream). tag_idx = _apply(_build_tag_map(dma, list(range(len(dma.tile_shape())))), ivs, ip) - # SRAM indices: zeros except the last = sram offset (mirror sramIndices.back()). - sram_indices = [zero] * dma.dst_rank - sram_indices[-1] = sram_off - - operands = [dma.src, dram_idx, dma.dst, *sram_indices, - dma.num_elements, dma.tag, tag_idx, - dma.stride, dma.num_elements_per_stride] - ir.Operation.create("memref.dma_start", results=[], operands=operands, + operands = [dma.dram, dram_idx, dma.sram, sram_off, + dma.tag, tag_idx, dma.num_elements, dma.num_elements_per_stride] + if dma.offset is not None: + operands.append(dma.offset) + # masked low/high are full-tile-local -> remap each per THIS subtile's offset. + sub = dma.subtile_size() + for i, axis in enumerate(dma.masked_axes): + low, high = dma.masked_ops[2 * i], dma.masked_ops[2 * i + 1] + operands.append(_remap_bound(low, ivs[axis], sub[axis], False, ip)) + operands.append(_remap_bound(high, ivs[axis], sub[axis], True, ip)) + ir.Operation.create("togsim.transfer", results=[], operands=operands, attributes=_dma_attrs(dma), ip=ip) @@ -244,6 +282,27 @@ def _const_index(v, ip): ir.IntegerAttr.get(ir.IndexType.get(), v), ip=ip).result +def _fresh_tag(dma): + """Give this DMA a fresh tag memref.alloc right BEFORE the (pre-split) coarse + dma_start, and rewire every use of the old tag -- the dma_start re-emitted + below AND its dma_wait -- to it. The coarse dma sits at the reduction-loop body + level (it has not been wrapped in a subtile load nest yet), so the alloc there + dominates both the load nest fine-grained is about to build and the sibling + wait nest. Each reduction iteration thus allocates its own tag -> successive + iterations are distinct (multi-tile-K / conv) and the per-iteration tag + semantics is in the IR, not reconstructed downstream. Old alloc becomes dead.""" + old = dma.tag + new_tag = ir.Operation.create("memref.alloc", results=[old.type], + operands=[], ip=ir.InsertionPoint(dma.op)).results[0] + old.replace_all_uses_with(new_tag) + dma.tag = new_tag + # the old (func-entry, per-tensor unique) alloc is now dead -- erase it. + try: + old.owner.erase() + except Exception: + pass + + # --------------------------------------------------------------------------- # Loop-nest construction # --------------------------------------------------------------------------- @@ -293,24 +352,16 @@ def _reaches(value, target): # --------------------------------------------------------------------------- # Pass driver # --------------------------------------------------------------------------- -def _iter_ops(block): - for op in list(block.operations): - yield op - for region in op.operation.regions: - for b in region.blocks: - yield from _iter_ops(b) - - def _run_func(func, vectorlane): from mlir.dialects import linalg # First matmul only. matmul = None dmas = [] - for op in _iter_ops(func.regions[0].blocks[0]): + for op in walk_ops(func.regions[0].blocks[0]): name = op.operation.name if name == "linalg.matmul" and matmul is None: matmul = op - elif name == "memref.dma_start": + elif name == "togsim.transfer": dmas.append(op) if matmul is None: return @@ -363,16 +414,30 @@ def _run_func(func, vectorlane): for d, f in enumerate(fuse["w_to_fused"]): bounds[f] = w_counts[d] + # Give each load a fresh per-iteration tag alloc just before its coarse dma + # (rewiring its dma_wait via the old tag's uses), so the tag is distinct per + # reduction iteration -- positioned to match the per-iteration tag semantics. + _fresh_tag(mvin_input) + _fresh_tag(mvin_weight) + # Insert the fused nest at the weight DMA (the later of the two): both DMAs' # original DRAM base indices (src_idx[0], computed in the enclosing loops) must # dominate the nest. Codegen emits input before weight, matching the C++ pass # which fuses after the weight subtile loop. ip = ir.InsertionPoint(mvin_weight.op) - fused_ivs, body_ip = _build_for_nest(bounds, ip) - in_ivs = [fused_ivs[fuse["in_to_fused"][d]] for d in range(rank)] - w_ivs = [fused_ivs[fuse["w_to_fused"][d]] for d in range(rank)] - _emit_dma(mvin_input, in_ivs, vectorlane, body_ip) - _emit_dma(mvin_weight, w_ivs, vectorlane, body_ip) + # Unroll the fused nest, emitting each distinct input/weight subtile ONCE (a load + # is invariant to the other operand's dims, so the cross-product re-emits it + # identically). Dedup by the operand's own coords; keep the fused issue order. + seen_in, seen_w = set(), set() + for it in itertools.product(*[range(b) for b in bounds]): + in_key = tuple(it[fuse["in_to_fused"][d]] for d in range(rank)) + if in_key not in seen_in: + seen_in.add(in_key) + _emit_dma(mvin_input, [_const_index(c, ip) for c in in_key], vectorlane, ip) + w_key = tuple(it[fuse["w_to_fused"][d]] for d in range(rank)) + if w_key not in seen_w: + seen_w.add(w_key) + _emit_dma(mvin_weight, [_const_index(c, ip) for c in w_key], vectorlane, ip) mvin_input.op.erase() mvin_weight.op.erase() diff --git a/PyTorchSimFrontend/mlir/passes/lower_dma_to_gemmini.py b/PyTorchSimFrontend/mlir/passes/lower_dma_to_gemmini.py index f5b841bb..5ca842c1 100644 --- a/PyTorchSimFrontend/mlir/passes/lower_dma_to_gemmini.py +++ b/PyTorchSimFrontend/mlir/passes/lower_dma_to_gemmini.py @@ -22,6 +22,8 @@ WAIT_NAME = "memref.dma_wait" MARKERS = (OP_NAME, WAIT_NAME) +from ._mlir_util import attr_i64_array + # func7 instruction codes (CustomDMAAttribute.h) CONFIG, CONFIG2, CONFIG3, CONFIG4 = 0, 4, 5, 6 MVIN, MVIN2, MVIN3, MVOUT = 2, 1, 14, 3 @@ -56,12 +58,18 @@ def run(module, timing=False): memref.dma_wait is erased in both modes (matches C++ DmaWaitOpLowering). """ from mlir.ir import (InsertionPoint, Operation, IntegerType, IndexType, - IntegerAttr, MemRefType) + IntegerAttr, MemRefType, FlatSymbolRefAttr, TypeAttr) from mlir.dialects import llvm, arith, memref i64 = IntegerType.get_signless(64) idx = IndexType.get() + # memref.global symbol -> type, to resolve the indirect_offset spad + sym2type = {} + for g in module.operation.regions[0].blocks[0].operations: + if g.operation.name == "memref.global": + sym2type[g.attributes["sym_name"].value] = MemRefType(TypeAttr(g.attributes["type"]).value) + def const_int(val): return IntegerAttr(val.owner.attributes["value"]).value @@ -117,15 +125,14 @@ def elem_addr_i64(memref_val, indices, mtype, elem_bytes): is_mvin = dma_type in (MVIN, MVIN2, MVIN3) elem_bytes = _elem_bytes(src_ty.element_type) - # Indirect (gather): the gather-side indices are src for mvin, dst for mvout. - gather_idx = src_idx if is_mvin else dst_idx - indirect, indirect_memref = _find_indirect(gather_idx) + # Indirect (gather): offset spad referenced by the indirect_offset symbol attr + indirect = "indirect_offset" in op.attributes tile_shape = _subtile(op) if tile_shape is None: tile_shape = list(dst_ty.shape) if is_mvin else list(src_ty.shape) - dram_strides = _int_array(op, "dram_stride") - spad_strides = _int_array(op, "sram_stride") + dram_strides = attr_i64_array(op, "dram_stride") + spad_strides = attr_i64_array(op, "sram_stride") assert len(tile_shape) == len(dram_strides) == len(spad_strides), \ f"shape/stride rank mismatch: {tile_shape} {dram_strides} {spad_strides}" @@ -153,10 +160,14 @@ def elem_addr_i64(memref_val, indices, mtype, elem_bytes): i64_const((spad4[2] << 32) | (spad4[3] & 0xFFFFFFFF))) if indirect: # CONFIG4: rs1 = indirect index-spad base address, rs2 = (elem_size<<16)|stride(1) + offset_sym = FlatSymbolRefAttr(op.attributes["indirect_offset"]).value + off_ty = sym2type[offset_sym] + indirect_memref = memref.GetGlobalOp(off_ty, offset_sym).result ind_base = memref.ExtractAlignedPointerAsIndexOp(indirect_memref).result ind_addr = arith.IndexCastOp(i64, ind_base).result - ind_esize = _elem_bytes(MemRefType(indirect_memref.type).element_type) - asm(CONFIG4, ind_addr, i64_const(((ind_esize & 0xFF) << 16) | (1 & 0xFFFF))) + ind_esize = _elem_bytes(off_ty.element_type) + off_stride = IntegerAttr(op.attributes["offset_stride"]).value + asm(CONFIG4, ind_addr, i64_const(((ind_esize & 0xFF) << 16) | (off_stride & 0xFFFF))) asm(dma_type, dram_addr, spad_addr) op.erase() @@ -180,11 +191,6 @@ def _subtile(op): return [IntegerAttr(a).value for a in ArrayAttr(op.attributes["subtile_size"])] -def _int_array(op, name): - from mlir.ir import ArrayAttr, IntegerAttr - return [IntegerAttr(a).value for a in ArrayAttr(op.attributes[name])] - - def _elem_bytes(elem_type): from mlir.ir import IntegerType, FloatType bits = (IntegerType(elem_type).width if IntegerType.isinstance(elem_type) @@ -192,23 +198,6 @@ def _elem_bytes(elem_type): return max(bits, 8) // 8 -def _find_indirect(indices): - """If a gather index is an affine.apply{indirect_access} whose operands include - index_cast(affine.load(%spad)), return (True, %spad memref); else (False, None).""" - for idx in indices: - ap = idx.owner - if getattr(ap, "name", None) != "affine.apply" or "indirect_access" not in ap.attributes: - continue - for operand in ap.operands: - ic = operand.owner - if getattr(ic, "name", None) != "arith.index_cast": - continue - ld = ic.operands[0].owner - if getattr(ld, "name", None) == "affine.load": - return True, ld.operands[0] # affine.load operand 0 == the index spad memref - return False, None - - def lower_text(text): if OP_NAME not in text: return text diff --git a/PyTorchSimFrontend/mlir/passes/lower_to_emitc.py b/PyTorchSimFrontend/mlir/passes/lower_to_emitc.py new file mode 100644 index 00000000..1470d13e --- /dev/null +++ b/PyTorchSimFrontend/mlir/passes/lower_to_emitc.py @@ -0,0 +1,628 @@ +"""lower_to_emitc pass (C4): skeleton+API MLIR -> EmitC -> C++ -> trace `.so`. + +Second stage of the C++ trace pipeline (docs/design/togsim_cpp_trace.md, sec +5-7). Takes the skeleton+API module from `build_skeleton` (loop nest + +`togsim.*` ops) and produces an EmitC module whose single entry function + + extern "C" void togsim_kernel(EmitCtx* ctx, int64_t* shape_args, int32_t n) + +mirrors the loop skeleton, with every `togsim.*` op as an `emitc.call_opaque` +to the matching `togsim_runtime.h` free function (`togsim_ops.EMITC_CALLEE`). +`mlir-translate --mlir-to-cpp` renders it to C++, compiled to a `.so` that +exports `togsim_kernel` and leaves `togsim_dma/wait/compute/signal` undefined for +the TOGSim loader to resolve at `dlopen`. + +How the lowering is done -- it drives the *upstream* EmitC conversion passes and +adds only the glue they cannot do: + + 1. (python) Rewrite the unregistered `togsim.*` ops to `emitc.call_opaque`. + Unregistered ops have no registered conversion patterns, so this must be a + custom rewrite (design sec 8). Also rewrite the kernel's signature to the + ABI form (drop the memref tensor args -- the trace producer never touches + tensor data; base addresses are deferred to P3) and drop the aux + globals / wrapper func. + 2. (upstream passes, in-process PassManager) + func.func(lower-affine) -> convert-scf-to-emitc + -> convert-arith-to-emitc -> convert-func-to-emitc + This is the EmitC infrastructure: it lowers the affine/scf loop nest to + `emitc.for`, the index/arith (loop bounds, and in P3 the address + arithmetic) to EmitC, and the func to `emitc.func`. + 3. (python) Two small fixups the passes leave behind in this LLVM 20 build: + * `convert-scf-to-emitc` emits `emitc.for` with `index`-typed bounds, so + `convert-arith-to-emitc` (which makes constants `!emitc.size_t`) leaves + `builtin.unrealized_conversion_cast` on the bounds that nothing folds + and `mlir-to-cpp` cannot print (design sec 8 "EmitC coverage" risk). + `_fold_for_bound_casts` rewrites those casts away. + * add the `extern "C"` specifier so `dlsym` finds the entry unmangled. + +Requires the MLIR Python bindings (incl. `mlir.passmanager`); the .cpp/.so +steps additionally require `mlir-translate` (TORCHSIM_LLVM_PATH) and a host C++ +compiler. +""" + +import os +import re +import subprocess + +from mlir.passmanager import PassManager + +from . import togsim_ops as ts +from ._mlir_util import walk_ops, i32, i64, attr_int, attr_i64_array +from .build_tog import ir, _find_kernel + +#: emitted entry symbol (== ts.ENTRY_SYMBOL == "togsim_kernel"). +ENTRY = ts.ENTRY_SYMBOL + +#: EmitC type of the opaque EmitCtx* threaded through every call. +CTX_TYPE = '!emitc.ptr>' + +#: upstream EmitC conversion pipeline (the infrastructure this pass drives). +_PIPELINE = ("builtin.module(" + "convert-vector-to-scf{full-unroll=true}," + "func.func(lower-affine)," + "func.func(lower-vector-multi-reduction)," + "convert-scf-to-emitc," + "convert-arith-to-emitc," + "convert-func-to-emitc)") + +#: includes every generated trace.cpp needs. +_INCLUDES = ( + "#include \n" + "#include \n" + "using std::size_t;\n" + '#include "togsim_runtime.h"\n' +) + + +def _trace_banner(include_dir): + """Self-documenting header for a generated trace.cpp: the ABI version (the + TOGSIM_ABI_VERSION #define) and the call-format banner, both READ FROM + togsim_runtime.h so they never drift when the ABI changes. Falls back to a + bare banner if the header is unreadable.""" + head = "// GENERATED by PyTorchSim -- TOGSim trace producer. DO NOT EDIT.\n" + try: + text = open(os.path.join(include_dir, "togsim_runtime.h")).read() + except OSError: + return head + ver = re.search(r"#define\s+TOGSIM_ABI_VERSION\s+(\d+)", text) + blk = re.search(r"// --- BEGIN trace-producer call formats[^\n]*\n(.*?)" + r"// --- END trace-producer call formats[^\n]*\n", text, re.S) + head = ("// GENERATED by PyTorchSim -- TOGSim trace producer (ABI v%s). DO NOT EDIT.\n" + % (ver.group(1) if ver else "?")) + return head + (blk.group(1) if blk else "") + + +# --------------------------------------------------------------------------- +# attribute builders / readers +# --------------------------------------------------------------------------- +def _idx(v): + return ir.IntegerAttr.get(ir.IndexType.get(), int(v)) + + +def _opaque(ctx, text): + return ir.Attribute.parse('#emitc.opaque<"%s">' % text, ctx) + + +def _arr(ctx, vals): + """A C compound-literal `(const int64_t[]){...}` arg, or `nullptr` if empty + (the call site decays it to a `const int64_t*`).""" + vals = list(vals) + if not vals: + return _opaque(ctx, "nullptr") + return _opaque(ctx, "(const int64_t[]){%s}" % ", ".join(str(int(v)) for v in vals)) + + +def _attr_bool(op, key): + return 1 if ir.BoolAttr(op.operation.attributes[key]).value else 0 + + +# --------------------------------------------------------------------------- +# step 1: rewrite signature + togsim.* ops (the unregistered-op glue) +# --------------------------------------------------------------------------- +def _strip_aux(module): + """Erase memref.global decls and every func except @kernel (the wrapper).""" + victims = [] + for op in module.body.operations: + name = op.operation.name + if name == "memref.global": + victims.append(op) + elif name == "func.func": + if ir.StringAttr(op.operation.attributes["sym_name"]).value != "kernel": + victims.append(op) + for op in victims: + op.operation.erase() + + +def _rewrite_signature(kernel, ctx): + """Replace @kernel's memref tensor args with the ABI args + (EmitCtx*, int64_t* shape_args, int32_t n) and rename it to togsim_kernel. + Returns the ctx Value.""" + block = kernel.regions[0].blocks[0] + for arg in block.arguments: + if len(list(arg.uses)) > 0: + raise ValueError( + "kernel arg still used after build_skeleton; cannot drop it " + "(expected the DCE to have removed all tensor-data ops)") + # erase existing (memref) args high-to-low, then append the ABI args. + for i in reversed(range(len(block.arguments))): + block.erase_argument(i) + ptr = ir.Type.parse(CTX_TYPE, ctx) + i64ptr = ir.Type.parse("!emitc.ptr", ctx) + i32 = ir.IntegerType.get_signless(32) + loc = ir.Location.unknown(ctx) + block.add_argument(ptr, loc) + block.add_argument(i64ptr, loc) + block.add_argument(i32, loc) + kernel.operation.attributes["function_type"] = ir.TypeAttr.get( + ir.FunctionType.get([ptr, i64ptr, i32], [])) + kernel.operation.attributes["sym_name"] = ir.StringAttr.get(ENTRY) + return block.arguments[0] + + +def _call(ctx, ctx_val, op, callee, arg_attrs): + """Insert emitc.call_opaque (ctx) {args=[0:index, ...]} before `op`. + The leading `0 : index` references operand 0 (ctx); other entries are + literal C args (integer attr -> literal, #emitc.opaque -> verbatim).""" + ir.Operation.create( + "emitc.call_opaque", results=[], operands=[ctx_val], + attributes={"callee": ir.StringAttr.get(callee), + "args": ir.ArrayAttr.get([_idx(0)] + arg_attrs)}, + loc=ir.Location.unknown(ctx), ip=ir.InsertionPoint(op)) + + +def _innermost_outer_loop(block): + """Deepest `affine.for {outer_loop=true}` (the PARALLEL/ACCUMULATION + boundary). Returns the op or None if the kernel has no parallel loop.""" + found = [None] + + def is_outer(op): + a = op.operation.attributes + return "outer_loop" in a and ir.BoolAttr(a["outer_loop"]).value + + def walk(b): + for op in b.operations: + if op.operation.name == "affine.for" and is_outer(op): + found[0] = op # nested outer loops overwrite -> deepest wins + for r in op.operation.regions: + for bb in r.blocks: + walk(bb) + + walk(block) + return found[0] + + +def _is_outer(forop): + a = forop.operation.attributes + return "outer_loop" in a and ir.BoolAttr(a["outer_loop"]).value + + +def _parallel_loop_chain(block): + """The nested chain of `affine.for {outer_loop}` from `block` inward (one + work-item's parallel indices). Empty if the kernel has no parallel loop.""" + chain = [] + cur = block + while True: + nxt = None + for op in cur.operations: + if op.operation.name == "affine.for" and _is_outer(op): + nxt = op + break + if nxt is None: + break + chain.append(nxt) + cur = nxt.operation.regions[0].blocks[0] + return chain + + +def _const_op(value): + """The defining arith/emitc constant Operation if `value` is a constant + result, else None (block args / other ops).""" + owner = value.owner + if isinstance(owner, ir.Block): + return None + return owner if owner.name in ("arith.constant", "emitc.constant") else None + + +def _outline_work_item(ctx, kernel, ctx_val): + """Outline the innermost parallel work-item body into a uniform + `togsim_kernel_tile(ctx, iv, n)` func, replacing it with a + `togsim_dispatch(ctx, togsim_kernel_tile, iv, n)` call (sec 9.3). The + work-item SCOPE becomes the function body; the runtime wrapper owns the + core-alloc + the TILE_BEGIN/TILE_END boundary (a decorator). One uniform tile + signature -> a single general dispatcher serves every kernel. + + Runs after `_rewrite_togsim_ops`, so the moved body holds emitc.call_opaque + (not togsim.* ops). The only values captured from outside the body are ctx, + the enclosing parallel induction vars, and constants -- threaded via the iv + array (parallel IVs) / cloned (constants); anything else is unsupported + (dynamic shape -> P4).""" + kblk = kernel.regions[0].blocks[0] + chain = _parallel_loop_chain(kblk) + if chain: + L = chain[-1] + Lbody = L.operation.regions[0].blocks[0] + ivs = [c.operation.regions[0].blocks[0].arguments[0] for c in chain] + else: # no parallel loop -> the whole kernel body is one work-item + L = None + Lbody = kblk + ivs = [] + + i64 = ir.IntegerType.get_signless(64) + i32 = ir.IntegerType.get_signless(32) + idxty = ir.IndexType.get() + ctxty = ir.Type.parse(CTX_TYPE, ctx) + i64ptr = ir.Type.parse("!emitc.ptr", ctx) + loc = ir.Location.unknown(ctx) + + # --- the outlined tile function (before the kernel so C defines it first) --- + tile = ir.Operation.create( + "func.func", results=[], regions=1, + attributes={ + "function_type": ir.TypeAttr.get(ir.FunctionType.get([ctxty, i64ptr, i32], [])), + "sym_name": ir.StringAttr.get(ts.TILE_SYMBOL), + "sym_visibility": ir.StringAttr.get("private")}, + loc=loc, ip=ir.InsertionPoint(kernel)) + with loc: + tblk = tile.regions[0].blocks.append(ctxty, i64ptr, i32) + ctx2, iv2, _n2 = tblk.arguments + with ir.InsertionPoint(tblk): + tret = ir.Operation.create("func.return", results=[], operands=[], loc=loc) + + # in the tile fn: recover each parallel index = index_cast(iv[k]). + idx_vals = [] + with ir.InsertionPoint(tret): + for k in range(len(ivs)): + kc = ir.Operation.create("emitc.constant", results=[i64], + attributes={"value": ir.IntegerAttr.get(i64, k)}, loc=loc).results[0] + elem = ir.Operation.create("emitc.subscript", results=[i64], + operands=[iv2, kc], loc=loc).results[0] + idx_vals.append(ir.Operation.create("arith.index_cast", results=[idxty], + operands=[elem], loc=loc).results[0]) + + # move the work-item body into the tile fn (terminators stay behind). + for op in [o for o in Lbody.operations + if o.operation.name not in ("affine.yield", "func.return")]: + op.operation.move_before(tret) + + # remap captures (Value `==` is identity): ctx -> ctx2, each parallel IV -> + # its index_cast, each external constant -> a clone inside the tile fn. A + # constant defined inside the tile fn (moved/read) is internal -> left alone. + caps = [(ctx_val, ctx2)] + list(zip(ivs, idx_vals)) + internal_consts = [] + def _collect_internal(block): + for op in block.operations: + c = _const_op(op.operation.results[0]) if len(op.operation.results) == 1 else None + if c is not None: + internal_consts.append(op.operation.results[0]) + for rg in op.operation.regions: + for b in rg.blocks: + _collect_internal(b) + _collect_internal(tblk) + const_clones = [] + ext_consts = [] + def _find_ext_consts(block): + for op in block.operations: + for opnd in op.operation.operands: + if _const_op(opnd) is None: + continue + if any(opnd == ic for ic in internal_consts): + continue + if any(opnd == e for e in ext_consts): + continue + ext_consts.append(opnd) + for rg in op.operation.regions: + for b in rg.blocks: + _find_ext_consts(b) + _find_ext_consts(tblk) + top = ir.InsertionPoint(tblk.operations[0]) + for e in ext_consts: + c = _const_op(e) + clone = ir.Operation.create(c.name, results=[e.type], + attributes={"value": c.attributes["value"]}, loc=loc, ip=top).results[0] + const_clones.append((e, clone)) + + allcaps = caps + const_clones + def _remap(block): + for op in block.operations: + for i in range(len(op.operation.operands)): + cur = op.operation.operands[i] + for orig, new in allcaps: + if cur == orig: + op.operation.operands[i] = new + break + for rg in op.operation.regions: + for b in rg.blocks: + _remap(b) + _remap(tblk) + + # --- the dispatcher: marshal the IVs and hand the tile fn to togsim_dispatch --- + term = [o for o in Lbody.operations + if o.operation.name in ("affine.yield", "func.return")][0] + fn_ref = _opaque(ctx, ts.TILE_SYMBOL) # function name -> verbatim pointer in C + with ir.InsertionPoint(term): + if ivs: + arrty = ir.Type.parse("!emitc.array<%dxi64>" % len(ivs), ctx) + arr = ir.Operation.create("emitc.variable", results=[arrty], + attributes={"value": _opaque(ctx, "")}, loc=loc).results[0] + for k, iv in enumerate(ivs): + kc = ir.Operation.create("emitc.constant", results=[i64], + attributes={"value": ir.IntegerAttr.get(i64, k)}, loc=loc).results[0] + v64 = ir.Operation.create("arith.index_cast", results=[i64], + operands=[iv], loc=loc).results[0] + sub = ir.Operation.create("emitc.subscript", results=[i64], + operands=[arr, kc], loc=loc).results[0] + # emitc.assign operands are (lvalue dest, value). + ir.Operation.create("emitc.assign", results=[], operands=[sub, v64], loc=loc) + ir.Operation.create( + "emitc.call_opaque", results=[], operands=[ctx_val, arr], + attributes={"callee": ir.StringAttr.get(ts.DISPATCH_CALLEE), + "args": ir.ArrayAttr.get( + [_idx(0), fn_ref, _idx(1), ir.IntegerAttr.get(i32, len(ivs))])}, + loc=loc) + else: + ir.Operation.create( + "emitc.call_opaque", results=[], operands=[ctx_val], + attributes={"callee": ir.StringAttr.get(ts.DISPATCH_CALLEE), + "args": ir.ArrayAttr.get( + [_idx(0), fn_ref, _opaque(ctx, "nullptr"), ir.IntegerAttr.get(i32, 0)])}, + loc=loc) + + +def _rewrite_togsim_ops(ctx, kernel, ctx_val): + block = kernel.regions[0].blocks[0] + victims = [] + for op in walk_ops(block): + name = op.operation.name + ipo = ir.InsertionPoint(op) + if name == ts.DMA: + dims = attr_i64_array(op, ts.ATTR_DIMS) + # The DRAM element offset is the togsim.dma operand (the original + # affine index, kept live by build_skeleton); pass it as a call + # operand so convert-arith-to-emitc lowers the address arithmetic + # into the producer (P3 approach A). The runtime adds the tensor base. + # Operands carried by build_skeleton: [dram_index, tag_index] (each + # optional). Pass each as a call operand so convert-arith-to-emitc + # lowers it; reference it from `args` by its operand position. offset + # -> DRAM byte address (runtime adds the tensor base); tag_slot -> the + # SRAM tile slot (runtime uses it for double-buffer/SRAM-capacity). + ins = list(op.operation.operands) + dram_operand = ins[0] if len(ins) >= 1 else None + tag_operand = ins[1] if len(ins) >= 2 else None + operands = [ctx_val] + offset_arg = i64(0) + tag_arg = i64(0) + if dram_operand is not None: + operands.append(dram_operand) + offset_arg = _idx(len(operands) - 1) + if tag_operand is not None: + operands.append(tag_operand) + tag_arg = _idx(len(operands) - 1) + args = [_idx(0), + i32(attr_int(op, ts.ATTR_DIR)), + i32(attr_int(op, ts.ATTR_ARG_ID)), + offset_arg, + i32(len(dims)), + _arr(ctx, dims), + _arr(ctx, attr_i64_array(op, ts.ATTR_STRIDES)), + i32(attr_int(op, ts.ATTR_ELEM_BITS)), + i32(_attr_bool(op, ts.ATTR_IS_ASYNC)), + i32(attr_int(op, ts.ATTR_TAG_ID)), + tag_arg] + _rb = attr_i64_array(op, ts.ATTR_READ_BUFS) + _wb = attr_i64_array(op, ts.ATTR_WRITE_BUFS) + args += [_arr(ctx, _rb), i32(len(_rb)), _arr(ctx, _wb), i32(len(_wb))] + # togsim_dma is void: the dma is paired with its barrier by the runtime + # (tag_id, tag_slot), not a returned handle. + ir.Operation.create( + "emitc.call_opaque", results=[], operands=operands, + attributes={"callee": ir.StringAttr.get(ts.EMITC_CALLEE[ts.DMA]), + "args": ir.ArrayAttr.get(args)}, + loc=ir.Location.unknown(ctx), ip=ipo) + victims.append(op) + elif name == ts.MEMORY_BAR: + # explicit async-DMA sync (the original dma_wait) -> + # togsim_memory_barrier(ctx, tag_id, tag_slot, write_bufs). The tag + # index operand (if any) is the runtime tag slot. + ins = list(op.operation.operands) + operands = [ctx_val] + tag_arg = i64(0) + if ins: + operands.append(ins[0]) + tag_arg = _idx(len(operands) - 1) + _wb = attr_i64_array(op, ts.ATTR_WRITE_BUFS) + ir.Operation.create( + "emitc.call_opaque", results=[], operands=operands, + attributes={"callee": ir.StringAttr.get(ts.EMITC_CALLEE[ts.MEMORY_BAR]), + "args": ir.ArrayAttr.get( + [_idx(0), i32(attr_int(op, ts.ATTR_TAG_ID)), tag_arg, + _arr(ctx, _wb), i32(len(_wb))])}, + loc=ir.Location.unknown(ctx), ip=ipo) + victims.append(op) + elif name == ts.COMPUTE: + # skeleton compute carries no dims (cost is keyed by tile_id) -> 0/null. + _rb = attr_i64_array(op, ts.ATTR_READ_BUFS) + _wb = attr_i64_array(op, ts.ATTR_WRITE_BUFS) + _call(ctx, ctx_val, op, ts.EMITC_CALLEE[ts.COMPUTE], + [i64(attr_int(op, ts.ATTR_TILE_ID)), + i32(attr_int(op, ts.ATTR_COMPUTE_TYPE)), + i32(0), _opaque(ctx, "nullptr"), + _arr(ctx, _rb), i32(len(_rb)), _arr(ctx, _wb), i32(len(_wb))]) + victims.append(op) + for op in victims: + op.operation.erase() + + +# --------------------------------------------------------------------------- +# step 3: post-conversion fixups +# --------------------------------------------------------------------------- +def _retype_for_to_size_t(module): + """Make every `emitc.for` use `!emitc.size_t` bounds + induction variable, + then drop the `index`<->`!emitc.size_t` `unrealized_conversion_cast` ops that + `convert-scf-to-emitc` / `convert-arith-to-emitc` leave behind (mlir-to-cpp + cannot print them; --reconcile cannot fold them). + + `emitc.for` accepts `size_t` bounds with the explicit type, and a `size_t` IV + makes the lowered address arithmetic (`convert-arith-to-emitc`, which works + in `size_t`) cast-free. So: set each IV to size_t, then for every + index<->size_t cast replace its result with its source (every consumer here + -- `emitc.for` bounds, `emitc.call_opaque` operands, `emitc` arith -- accepts + either, and after the IV retype each such cast bridges equal types).""" + idx = ir.IndexType.get() + st = ir.Type.parse("!emitc.size_t", module.context) + + for op in list(walk_ops(module.body)): + if op.operation.name == "emitc.for": + op.operation.regions[0].blocks[0].arguments[0].set_type(st) + + dead = [] + for op in list(walk_ops(module.body)): + if op.operation.name != "builtin.unrealized_conversion_cast": + continue + res = op.results[0] + src = list(op.operation.operands)[0] + # idx<->size_t bridges (incl. the size_t->size_t identities left after + # the IV retype): every consumer here accepts either, so fold to source. + if src.type in (idx, st) and res.type in (idx, st): + res.replace_all_uses_with(src) + dead.append(op) + for d in dead: + try: + d.operation.erase() + except Exception: + pass + + +def _add_extern_c(module, ctx): + for op in module.body.operations: + if (op.operation.name == "emitc.func" + and ir.StringAttr(op.operation.attributes["sym_name"]).value == ENTRY): + op.operation.attributes["specifiers"] = ir.ArrayAttr.get( + [ir.StringAttr.get('extern "C"')]) + return + raise ValueError("emitc.func @%s not found after conversion" % ENTRY) + + +# --------------------------------------------------------------------------- +# driver +# --------------------------------------------------------------------------- +def lower_to_emitc(skeleton_module): + """Lower a skeleton+API module (in place) to an EmitC module with the + `togsim_kernel` entry function. Returns the same module.""" + ctx = skeleton_module.context + kernel = _find_kernel(skeleton_module) + if kernel is None: + raise ValueError("no @kernel found in skeleton module") + + _strip_aux(skeleton_module) + ctx_val = _rewrite_signature(kernel, ctx) + _rewrite_togsim_ops(ctx, kernel, ctx_val) # togsim.* -> emitc.call_opaque + _outline_work_item(ctx, kernel, ctx_val) # work-item body -> togsim_kernel_tile + dispatch + + PassManager.parse(_PIPELINE, ctx).run(skeleton_module.operation) + + _retype_for_to_size_t(skeleton_module) + _add_extern_c(skeleton_module, ctx) + return skeleton_module + + +# --------------------------------------------------------------------------- +# C++ / .so backend +# --------------------------------------------------------------------------- +def _mlir_translate_bin(): + return os.path.join(os.environ.get("TORCHSIM_LLVM_PATH", "/usr/bin"), + "mlir-translate") + + +def emitc_to_cpp(emitc_module, mlir_translate=None, include_dir=None): + """Render `emitc_module` to C++ source (banner + includes + mlir-to-cpp body). + `include_dir` locates togsim_runtime.h for the ABI banner (default resolves it).""" + mlir_translate = mlir_translate or _mlir_translate_bin() + proc = subprocess.run( + [mlir_translate, "--mlir-to-cpp"], + input=str(emitc_module), capture_output=True, text=True) + if proc.returncode != 0: + raise RuntimeError("mlir-translate --mlir-to-cpp failed:\n" + proc.stderr) + return _trace_banner(include_dir or _default_include_dir()) + _INCLUDES + proc.stdout + + +def compile_so(cpp_text, so_path, include_dir, cxx=None): + """Compile producer C++ to `so_path`. `include_dir` must hold + togsim_runtime.h. togsim_* symbols are left undefined (resolved at dlopen).""" + cxx = cxx or os.environ.get("CXX", "g++") + cpp_path = os.path.splitext(so_path)[0] + ".cpp" + with open(cpp_path, "w") as fh: + fh.write(cpp_text) + proc = subprocess.run( + [cxx, "-shared", "-fPIC", "-std=gnu++17", "-O2", + "-I", include_dir, cpp_path, "-o", so_path], + capture_output=True, text=True) + if proc.returncode != 0: + raise RuntimeError("%s failed:\n%s" % (cxx, proc.stderr)) + return so_path + + +def _default_include_dir(): + root = os.environ.get("TORCHSIM_DIR") + if not root: + root = os.path.dirname(os.path.dirname(os.path.dirname( + os.path.dirname(os.path.abspath(__file__))))) + return os.path.join(root, "TOGSim", "include") + + +def skeleton_to_so(skeleton_module, so_path, include_dir=None): + """skeleton module -> EmitC -> C++ -> compiled trace `.so`. Returns the + EmitC module text (for inspection / caching).""" + emitc = lower_to_emitc(skeleton_module) + inc = include_dir or _default_include_dir() + cpp = emitc_to_cpp(emitc, include_dir=inc) + compile_so(cpp, so_path, inc) + return str(emitc) + + +def build_trace_so(postvcix_path, so_path, include_dir=None): + """Full P2 path from a post-vcix kernel .mlir to a trace `.so`.""" + from . import build_skeleton as bs + + ctx = ir.Context() + ctx.allow_unregistered_dialects = True + with ctx: + module = ir.Module.parse(open(postvcix_path).read(), ctx) + bs.build_skeleton(module) + return skeleton_to_so(module, so_path, include_dir) + + +def main(argv): + import argparse + + parser = argparse.ArgumentParser(prog="lower_to_emitc.py") + parser.add_argument("input", help="post-vcix kernel .mlir") + parser.add_argument("--so", required=True, help="output .so path") + parser.add_argument("--include-dir", default=None, + help="dir holding togsim_runtime.h (default: TOGSim/include)") + parser.add_argument("--emit-cpp", default=None, + help="also write the generated C++ here") + parser.add_argument("--emit-mlir", default=None, + help="also write the EmitC MLIR here") + args = parser.parse_args(argv[1:]) + + from . import build_skeleton as bs + ctx = ir.Context() + ctx.allow_unregistered_dialects = True + with ctx: + module = ir.Module.parse(open(args.input).read(), ctx) + bs.build_skeleton(module) + emitc = lower_to_emitc(module) + if args.emit_mlir: + open(args.emit_mlir, "w").write(str(emitc)) + cpp = emitc_to_cpp(emitc, include_dir=args.include_dir or _default_include_dir()) + if args.emit_cpp: + open(args.emit_cpp, "w").write(cpp) + compile_so(cpp, args.so, args.include_dir or _default_include_dir()) + import sys + sys.stderr.write("wrote %s\n" % args.so) + return 0 + + +if __name__ == "__main__": + import sys + sys.exit(main(sys.argv)) diff --git a/PyTorchSimFrontend/mlir/passes/lower_to_llvm.py b/PyTorchSimFrontend/mlir/passes/lower_to_llvm.py index ad287499..4629df29 100644 --- a/PyTorchSimFrontend/mlir/passes/lower_to_llvm.py +++ b/PyTorchSimFrontend/mlir/passes/lower_to_llvm.py @@ -50,15 +50,15 @@ def run_standard_lowering(in_path, out_path=None, timing=False): out_path = in_path from mlir.ir import Context, Module, Location from mlir.passmanager import PassManager - from . import lower_dma_to_gemmini + from . import lower_transfer_to_gemmini ctx = Context() ctx.allow_unregistered_dialects = True with ctx, Location.unknown(): with open(in_path) as f: module = Module.parse(f.read()) - # Imperative Python pass: memref.dma_start/dma_wait -> Gemmini asm (replaces - # the C++ test-memref-to-gemmini), then the registered standard lowering. - lower_dma_to_gemmini.run(module, timing=timing) + # Imperative Python pass: togsim.transfer -> Gemmini asm directly (no + # memref.dma_start intermediate), then the registered standard lowering. + lower_transfer_to_gemmini.run(module, timing=timing) PassManager.parse(STANDARD_PIPELINE, ctx).run(module.operation) with open(out_path, "w") as f: f.write(str(module)) diff --git a/PyTorchSimFrontend/mlir/passes/lower_to_vcix.py b/PyTorchSimFrontend/mlir/passes/lower_to_vcix.py index ac93ebc8..ccaca976 100644 --- a/PyTorchSimFrontend/mlir/passes/lower_to_vcix.py +++ b/PyTorchSimFrontend/mlir/passes/lower_to_vcix.py @@ -1,7 +1,7 @@ """Python port of the C++ `-test-pytorchsim-to-vcix` conversion pass (TestPyTorchSimToVCIXConversion.cpp). -Lowers `linalg.matmul` and the transcendental math ops (exp/erf/tanh/sin/cos) to +Lowers `linalg.matmul` and the transcendental math ops (exp/erf/tanh/sin/cos/log/atan) to VCIX dialect ops (RISC-V vector custom instructions). The C++ pass is a dialect-conversion (`applyPartialConversion`); the MLIR Python bindings expose no conversion framework, so each matchAndRewrite is reimplemented as imperative IR @@ -14,7 +14,7 @@ `allow_unregistered_dialects` -- so emitting generic vcix ops here is consistent with the current pipeline. -Covers all 6 C++ patterns: linalg.matmul (gemm + conv2d) and exp/erf/tanh/sin/cos. +Covers all 8 C++ patterns: linalg.matmul (gemm + conv2d) and exp/erf/tanh/sin/cos/log/atan. Wired into extension_codecache (run_to_vcix) after fine-grained, before the standard lowering; mlir-opt then runs only -test-loop-padding. Validated structurally against `mlir-opt -test-pytorchsim-to-vcix` (non-constant ops byte-identical incl. dma_wait tag @@ -29,15 +29,23 @@ import mlir.ir as ir # noqa: E402 -MARKERS = ("linalg.matmul", "math.exp", "math.erf", "math.tanh", "math.sin", "math.cos") +from ._mlir_util import walk_ops, i32, i64, attr_bool + +MARKERS = ("linalg.matmul", "math.exp", "math.erf", "math.tanh", "math.sin", + "math.cos", "math.log", "math.atan") # math op name -> (opcode, imm) for the vcix.v.iv lowering (mirror Math*ToVCIX). +# The sf.vc.v.iv opcode field is only 2 bits (uimm2, 0-3): erf(0)/tanh(1)/ +# sin,cos,log,atan(2)/exp(3). Opcode 2 is shared and disambiguated by imm +# (sin=0, cos=1, log=2, atan=3), matching the spike rs1 / gem5 VS1 sub-opcodes. _MATH_VIV = { "math.exp": (0b000011, 0), "math.erf": (0b000000, 0), "math.tanh": (0b000001, 0), "math.sin": (0b000010, 0), "math.cos": (0b000010, 1), + "math.log": (0b000010, 2), + "math.atan": (0b000010, 3), } @@ -80,20 +88,12 @@ def _legalize_vector_type(vt, vlen): return n, ir.VectorType.get([elt_count >> (n - 1)], elt_ty, scalable=[True]) -def _i64(v): - return ir.IntegerAttr.get(ir.IntegerType.get_signless(64), v) - - -def _i32(v): - return ir.IntegerAttr.get(ir.IntegerType.get_signless(32), v) - - def _viv(operand, result_ty, opcode, imm, rvl=None): """Create an unregistered vcix.v.iv (vcix::BinaryImmOp) op at the current IP.""" operands = [operand] if rvl is None else [operand, rvl] return ir.Operation.create( "vcix.v.iv", results=[result_ty], operands=operands, - attributes={"opcode": _i64(opcode), "imm": _i32(imm)}).results[0] + attributes={"opcode": i64(opcode), "imm": i32(imm)}).results[0] def _make_sf_vc_v_iv(vec, op_vt, n, legal_ty, opcode, imm): @@ -104,7 +104,7 @@ def _make_sf_vc_v_iv(vec, op_vt, n, legal_ty, opcode, imm): scalable = legal_ty.scalable rvl = None if scalable: - rvl = arith.ConstantOp(ir.IntegerType.get_signless(64), _i64(9)).result + rvl = arith.ConstantOp(ir.IntegerType.get_signless(64), i64(9)).result if n == 1: return _viv(vec, legal_ty, opcode, imm, rvl) elt_ty = legal_ty.element_type @@ -119,24 +119,16 @@ def _make_sf_vc_v_iv(vec, op_vt, n, legal_ty, opcode, imm): for i in range(total // elt_count): ext = vector.ExtractStridedSliceOp( legal_ty, vec, - ir.ArrayAttr.get([_i64(i * elt_count)]), - ir.ArrayAttr.get([_i64(elt_count)]), - ir.ArrayAttr.get([_i64(1)])).result + ir.ArrayAttr.get([i64(i * elt_count)]), + ir.ArrayAttr.get([i64(elt_count)]), + ir.ArrayAttr.get([i64(1)])).result v = _viv(ext, legal_ty, opcode, imm, rvl) res = vector.InsertStridedSliceOp( - v, res, ir.ArrayAttr.get([_i64(i * elt_count)]), - ir.ArrayAttr.get([_i64(1)])).result + v, res, ir.ArrayAttr.get([i64(i * elt_count)]), + ir.ArrayAttr.get([i64(1)])).result return res -def _iter_ops(block): - for op in list(block.operations): - yield op - for region in op.operation.regions: - for b in region.blocks: - yield from _iter_ops(b) - - # --------------------------------------------------------------------------- # matmul lowering helpers (mirror MatmulOpLowering) # --------------------------------------------------------------------------- @@ -146,11 +138,6 @@ def _elt_bits(elt_ty): return ir.FloatType(elt_ty).width -def _bool_attr_true(op, key): - a = op.attributes - return key in a and ir.BoolAttr(a[key]).value - - def _enclosing_loops(op): """Walk ancestor ops; return (accumulation, outer, inner) affine.for lists, outermost-first (mirror the C++ insert-at-begin).""" @@ -158,11 +145,11 @@ def _enclosing_loops(op): parent = op.operation.parent while parent is not None: if parent.name == "affine.for": - if _bool_attr_true(parent, "accumulation_loop"): + if attr_bool(parent, "accumulation_loop"): acc.insert(0, parent) - if _bool_attr_true(parent, "outer_loop"): + if attr_bool(parent, "outer_loop"): outer.insert(0, parent) - if _bool_attr_true(parent, "inner_loop"): + if attr_bool(parent, "inner_loop"): inner.insert(0, parent) parent = parent.parent return acc, outer, inner @@ -200,7 +187,7 @@ def _scan_conv_offsets(ow_loop, o_h, k_h, o_w, k_w): """Mirror the heuristic offset scan: find affine.apply(o_h,k_h)/(o_w,k_w) in the o_w loop and read the constant in its map (default 1).""" offset_h = offset_w = 1 - for o in _iter_ops(ow_loop.regions[0].blocks[0]): + for o in walk_ops(ow_loop.regions[0].blocks[0]): if o.operation.name != "affine.apply": continue ops = list(o.operation.operands) @@ -274,8 +261,9 @@ def _transfer_write(value, dest, indices): def _dma_wait(tag, idx, num_elements): - from mlir.dialects import memref - memref.DmaWaitOp(tag, [idx], num_elements) + # togsim-level counterpart of the async-DMA barrier (paired with togsim.transfer), + # instead of memref.dma_wait -- no memref.* DMA ops remain in the pipeline. + ir.Operation.create("togsim.wait", results=[], operands=[tag, idx, num_elements]) def _vcix(name, operands, result_tys, attrs): @@ -296,22 +284,29 @@ def _reaches(value, target): class _DmaView: - """Positional view of a customized memref.dma_start (see lower_dma_to_gemmini).""" + """Positional view of a togsim.transfer op (see emit_transfer / + lower_transfer_to_gemmini). + + New operand layout: (dram, dram_idx, sram, sram_idx, tag, tag_idx, dma_type, + vst [, offset]). Direction (which of dram/sram is source vs dest) comes from + the `dma_kind` attr ("MVIN"|"MVOUT"), not from operand position. To keep the + downstream _dram_is_write(src, dst) / `sram = d.dst` logic working (it + distinguishes MVIN loads from MVOUT stores by memory space), src/dst are + exposed direction-swapped: MVIN -> src=dram, dst=sram; MVOUT -> src=sram, + dst=dram.""" def __init__(self, op): self.op = op operands = list(op.operands) - src_rank = len(ir.MemRefType(operands[0].type).shape) - i = 0 - self.src = operands[i]; i += 1 - i += src_rank - self.dst = operands[i]; i += 1 - dst_rank = len(ir.MemRefType(self.dst.type).shape) - i += dst_rank - i += 1 # num_elements - self.tag = operands[i]; i += 1 - tag_rank = len(ir.MemRefType(self.tag.type).shape) - self.tag_idx = operands[i:i + tag_rank] + dram = operands[0] + sram = operands[2] + self.tag = operands[4] + self.tag_idx = [operands[5]] + kind = ir.StringAttr(op.attributes["dma_kind"]).value + if kind == "MVOUT": + self.src, self.dst = sram, dram + else: # MVIN (load) + self.src, self.dst = dram, sram def subtile_size(self): a = self.op.attributes @@ -378,7 +373,7 @@ def a64(v): return ir.IntegerAttr.get(i64, v) subtileM, subtileN, subtileK = M, N, K a_subk = b_subk = None # Mirror the C++ isAInitialized / isBInitialized flags: an operand is - # "initialized" either by an MVIN dma_start (tag found below) or by a + # "initialized" either by an MVIN togsim.transfer (tag found below) or by a # preceding affine.vector_store into its root memref (the fused case, e.g. # SDPA scores.V where B is the softmax output produced in-place, not DMAed). isAInit = isBInit = False @@ -391,7 +386,7 @@ def _root(v): return owner.operands[0] return v rootA, rootB = _root(A), _root(B) - for o in _iter_ops(outer[-1].regions[0].blocks[0]): + for o in walk_ops(outer[-1].regions[0].blocks[0]): if o.operation.name == "affine.vector_store": dest = _root(o.operation.operands[1]) if dest == rootA: @@ -399,7 +394,7 @@ def _root(v): elif dest == rootB: isBInit = True continue - if o.operation.name != "memref.dma_start": + if o.operation.name != "togsim.transfer": continue d = _DmaView(o.operation) dram, is_write = _dram_is_write(d.src, d.dst) @@ -488,6 +483,14 @@ def _root(v): # --- B dma_wait --- nacc = len(acc) acc_ivs = [_loop_iv(l) for l in acc] + # LEGACY behavior: coefficient -1 on each accumulation (reduction) loop var + # is a SENTINEL marking "this tag dim is the reduction axis", not an + # arithmetic offset. The legacy TOG path (TileGraphParser.cc) honors it by + # routing those vars to a separate accum tag component and skipping stride + # -1. The C++ trace path does NOT honor it: build_skeleton._strip_accum_terms + # drops these -1 terms so the memory_barrier slot stays subtile-only and + # pairs with its async load. Kept here for byte-identity with the C++ + # -test-pytorchsim-to-vcix pass; remove (do not flag) once legacy retires. bexpr = ir.AffineDimExpr.get(0) * -1 for i in range(1, nacc): bexpr = bexpr + ir.AffineDimExpr.get(i) * -1 @@ -544,6 +547,10 @@ def _root(v): with body_ip: # --- A dma_wait --- + # LEGACY behavior (see the B dma_wait above): the -1 coefficients mark the + # reduction axis for the legacy TOG path; the trace path strips them in + # build_skeleton._strip_accum_terms. Kept for byte-identity with the C++ + # -test-pytorchsim-to-vcix pass; remove once legacy retires. aexpr = ir.AffineDimExpr.get(0) * -1 for i in range(1, nacc): aexpr = aexpr + ir.AffineDimExpr.get(i) * -1 @@ -617,7 +624,7 @@ def run(module, vectorlane=128, vlen=128, **_): mms = [] for region in module.operation.regions: for b in region.blocks: - for o in _iter_ops(b): + for o in walk_ops(b): if o.operation.name == "linalg.matmul": mms.append(o.operation) for o in mms: @@ -625,7 +632,7 @@ def run(module, vectorlane=128, vlen=128, **_): targets = [] for region in module.operation.regions: for b in region.blocks: - for op in _iter_ops(b): + for op in walk_ops(b): if op.operation.name in _MATH_VIV: targets.append(op.operation) for op in targets: diff --git a/PyTorchSimFrontend/mlir/passes/lower_transfer_to_gemmini.py b/PyTorchSimFrontend/mlir/passes/lower_transfer_to_gemmini.py new file mode 100644 index 00000000..316454f5 --- /dev/null +++ b/PyTorchSimFrontend/mlir/passes/lower_transfer_to_gemmini.py @@ -0,0 +1,371 @@ +"""Lower togsim.transfer DIRECTLY to Gemmini RISC-V inline asm (no memref.dma_start). + +Merges decompose_transfer (the <=4D Gemmini-limit handling: drop unit dims / +collapse / >4D affine.for peel with lane-banked SRAM offset) with +lower_dma_to_gemmini (the CONFIG_DESC/MVIN|MVOUT asm emission). +togsim.transfer is unregistered so it carries every runtime descriptor as an +operand -- including the future masked-clamp low/high vectors -- which a registered +memref.dma_start cannot. See docs/design/transfer-direct-lowering.md. + +timing=False: emit the gemmini asm. timing=True: erase the transfer (the TOG carries +DMA timing; the cycle binary needs no asm). +""" + +OP_NAME = "togsim.transfer" +WAIT_NAME = "togsim.wait" +MARKERS = (OP_NAME, WAIT_NAME) + +from ._mlir_util import walk_ops +from .lower_dma_to_gemmini import _i64_signed, _row_major_strides, _elem_bytes, _asm, CONSTRAINTS +from .decompose_transfer import _int_array, _const_int, _squeeze_reassociation + +CONFIG_DESC = 7 # func7 for the TMA-style descriptor pointer (replaces CONFIG/2/3/4) +MVIN, MVIN2, MVIN3, MVOUT = 2, 1, 14, 3 +DESC_SLOTS = 18 # 144-byte DMA descriptor as 18 x i64 (see project-dma-descriptor) +CONFIG_TYPE = {MVIN: 0, MVIN2: 1, MVIN3: 2, MVOUT: 3} +MAX_TENSOR_DIM = 4 + + +def run(module, timing=False, vectorlane=128, **_): + from mlir.ir import (InsertionPoint, Operation, MemRefType, ArrayAttr, + IntegerAttr, IntegerType, IndexType, DenseI64ArrayAttr, + DenseI32ArrayAttr, StridedLayoutAttr, AffineMap, AffineMapAttr, + AffineExpr, BoolAttr, FlatSymbolRefAttr, TypeAttr, + DenseElementsAttr, RankedTensorType, StringAttr, UnitAttr) + from mlir.dialects import affine, llvm, arith, memref + i64 = IntegerType.get_signless(64) + idx_ty = IndexType.get() + module_top = module.operation.regions[0].blocks[0] + + sym2type = {} + for g in module_top.operations: + if g.operation.name == "memref.global": + sym2type[g.attributes["sym_name"].value] = MemRefType(TypeAttr(g.attributes["type"]).value) + + i32 = IntegerType.get_signless(32) + desc_ty = MemRefType.get([DESC_SLOTS], i64) + desc_i32_ty = MemRefType.get([DESC_SLOTS * 2], i32) # same bytes, i32-addressable (masked) + desc_globals = {} # slots tuple -> global sym name (dedup) + desc_counter = [0] + + def _i32_signed(v): + v &= 0xFFFFFFFF + return v - (1 << 32) if v >= (1 << 31) else v + + def _pack_desc(shape4, dram4, spad4, elem_bytes, vlstride, vsa4, cfg_type, indirect, + ind_stride, ind_esize, hi=None, accumulate=False, acc_float=False): + # 18 i64 slots matching the C dma_descriptor byte layout (little-endian). + lo = [0, 0, 0, 0] + if hi is None: + hi = list(shape4) + masked = any(h < s for h, s in zip(hi, shape4)) # dim_high clamps below extent + def s2(a, b): return (a & 0xFFFFFFFF) | ((b & 0xFFFFFFFF) << 32) + m = 0xFFFFFFFFFFFFFFFF + slots = [ + s2(shape4[0], shape4[1]), s2(shape4[2], shape4[3]), + s2(lo[0], lo[1]), s2(lo[2], lo[3]), + s2(hi[0], hi[1]), s2(hi[2], hi[3]), + dram4[0] & m, dram4[1] & m, dram4[2] & m, dram4[3] & m, + spad4[0] & m, spad4[1] & m, spad4[2] & m, spad4[3] & m, + (elem_bytes & 0xFFFF) | ((vlstride & 0xFFFF) << 16) | ((vsa4 & 0xFF) << 32) + | ((cfg_type & 0xFF) << 40) + | (((1 if indirect else 0) | (2 if masked else 0) + | (4 if accumulate else 0) | (8 if acc_float else 0)) << 48), + 0, # +120 indirect_addr (runtime) + (ind_stride & 0xFFFF) | ((ind_esize & 0xFFFF) << 16), # +128 + 0, # +136 fill (runtime/step3) + ] + return slots + + def _desc_global(slots): + key = tuple(slots) + if key not in desc_globals: + name = f"dma_desc_{desc_counter[0]}" + desc_counter[0] += 1 + import numpy as np + init = DenseElementsAttr.get( + np.array([_i64_signed(v) for v in slots], dtype=np.int64), + type=RankedTensorType.get([DESC_SLOTS], i64)) + with InsertionPoint.at_block_begin(module_top): + Operation.create("memref.global", results=[], operands=[], attributes={ + "sym_name": StringAttr.get(name), + "sym_visibility": StringAttr.get("private"), + "type": TypeAttr.get(desc_ty), + "initial_value": init}) + desc_globals[key] = name + return desc_globals[key] + + def desc_ptr(slots, masked_pairs=(), fill=0, ind_addr_i64=None): + """Byte pointer to the DMA descriptor global. A fully static descriptor (no + masked clamp, no indirect address) is a deduped i64 global. Anything with a + runtime-written field -- per-dim dim_low/dim_high (masked) and/or the indirect + address -- gets a UNIQUE i32-view global (same byte layout, i32-addressable) so + those int32/i64 fields can be stored individually.""" + import numpy as np + if not masked_pairs and ind_addr_i64 is None: + g = memref.GetGlobalOp(desc_ty, _desc_global(slots)).result + return arith.IndexCastOp(i64, memref.ExtractAlignedPointerAsIndexOp(g).result).result + slots = list(slots) + if masked_pairs: + slots[14] |= (2 << 48) # masked flag (+118 bit1) + slots[17] = fill & 0xFFFFFFFFFFFFFFFF # +136 fill: box-excluded positions + words = [] + for v in slots: + v &= 0xFFFFFFFFFFFFFFFF + words.append(_i32_signed(v & 0xFFFFFFFF)) + words.append(_i32_signed((v >> 32) & 0xFFFFFFFF)) + name = f"dma_desc_{desc_counter[0]}" + desc_counter[0] += 1 + init = DenseElementsAttr.get(np.array(words, dtype=np.int32), + type=RankedTensorType.get([DESC_SLOTS * 2], i32)) + with InsertionPoint.at_block_begin(module_top): + Operation.create("memref.global", results=[], operands=[], attributes={ + "sym_name": StringAttr.get(name), + "sym_visibility": StringAttr.get("private"), + "type": TypeAttr.get(desc_i32_ty), + "initial_value": init}) + g = memref.GetGlobalOp(desc_i32_ty, name).result + def store_word(v32, i32_idx): + memref.StoreOp(v32, g, [arith.ConstantOp(idx_ty, IntegerAttr.get(idx_ty, i32_idx)).result]) + for axis4, low_val, high_val in masked_pairs: # dim_low i32 idx 4 (+16B), dim_high 8 (+32B) + store_word(arith.IndexCastOp(i32, low_val).result, 4 + axis4) + store_word(arith.IndexCastOp(i32, high_val).result, 8 + axis4) + if ind_addr_i64 is not None: # indirect_addr (i64) at +120 -> words 30/31 + store_word(arith.TruncIOp(i32, ind_addr_i64).result, 30) + shamt = arith.ConstantOp(i64, IntegerAttr.get(i64, 32)).result + store_word(arith.TruncIOp(i32, arith.ShRUIOp(ind_addr_i64, shamt).result).result, 31) + return arith.IndexCastOp(i64, memref.ExtractAlignedPointerAsIndexOp(g).result).result + + def i64_const(value): + return arith.ConstantOp(i64, IntegerAttr.get(i64, _i64_signed(value))).result + + def asm(func7, rs1, rs2): + llvm.InlineAsmOp(None, [rs1, rs2], _asm(func7), CONSTRAINTS, + has_side_effects=True, asm_dialect=0) + + def elem_addr_i64(memref_val, indices, mtype, elem_bytes): + base = memref.ExtractAlignedPointerAsIndexOp(memref_val).result + strides = _row_major_strides(list(mtype.shape)) + off = None + for k, ival in enumerate(indices): + if strides[k] == 0: + continue + term = ival + if strides[k] != 1: + term = arith.MulIOp(ival, arith.ConstantOp(idx_ty, IntegerAttr.get(idx_ty, strides[k])).result).result + off = term if off is None else arith.AddIOp(off, term).result + if off is not None: + byte = arith.MulIOp(off, arith.ConstantOp(idx_ty, IntegerAttr.get(idx_ty, elem_bytes)).result).result + base = arith.AddIOp(base, byte).result + return arith.IndexCastOp(i64, base).result + + targets, waits = [], [] + for region in module.operation.regions: + for b in region.blocks: + for op in walk_ops(b): + if op.operation.name == OP_NAME: + targets.append(op.operation) + elif op.operation.name == WAIT_NAME: + waits.append(op.operation) + + for op in waits: # togsim.wait: erase in both modes (the barrier is a sync marker) + op.erase() + + for op in targets: + op_operands = list(op.operands) + dram, dram_idx, sram, sram_idx, tag, tag_idx, dma_type, vst = op_operands[:8] + offset_sym = (op_operands[8].owner.attributes["name"] if "indirect" in op.attributes else None) + kind = op.attributes["dma_kind"].value + dma_type_val = _const_int(dma_type) # MVIN(2)/MVIN2(1)/MVIN3(14)/MVOUT(3) + is_mvin = dma_type_val in (MVIN, MVIN2, MVIN3) + vlane_axis = IntegerAttr(op.attributes["vlane_split_axis"]).value + dram_stride = _int_array(op.attributes["dram_stride"]) + tile_stride = _int_array(op.attributes["tile_stride"]) + vlane_stride = _const_int(vst, 1) + try: + subtile = _int_array(op.attributes["subtile_size"]) + except KeyError: + subtile = None + # masked-DMA dynamic clamp: masked_axes lists the clamped tile axes; the trailing + # (low, high) index operands (2 per axis) are runtime-stored into dim_low/dim_high. + if "masked_axes" in op.attributes: + masked_axes = _int_array(op.attributes["masked_axes"]) + n_base = 9 if "indirect" in op.attributes else 8 + mvals = op_operands[n_base:] + masked_pairs = [(masked_axes[i], mvals[2 * i], mvals[2 * i + 1]) + for i in range(len(masked_axes))] + masked_fill = IntegerAttr(op.attributes["masked_fill"]).value + else: + masked_pairs = [] + masked_fill = 0 + accumulate = "accumulate" in op.attributes # index_add: MVOUT out[idx] += val + acc_float = "acc_float" in op.attributes + + if timing: + op.erase() + continue + + sram_ty = MemRefType(sram.type) + elem, space = sram_ty.element_type, sram_ty.memory_space + elem_bytes = _elem_bytes(sram_ty.element_type) + dram_ty = MemRefType(dram.type) + tile_shape = list(sram_ty.shape) + eff = [i for i, e in enumerate(tile_shape) if e > 1] + indirect = offset_sym is not None + + def _const(v): + return arith.ConstantOp(idx_ty, IntegerAttr.get(idx_ty, v)).result + + def _emit_asm(sram_mem, sram_indices, dram_idx_val, vsa_val, desc_shape, + desc_dram_strides, desc_spad_strides, subtile_shape, desc_masked_pairs=None): + cfg_shape = subtile_shape if subtile_shape is not None else desc_shape + expand = MAX_TENSOR_DIM - len(cfg_shape) + shape4 = [1] * expand + list(cfg_shape) + dram4 = [0] * expand + list(desc_dram_strides) + spad4 = [0] * expand + list(desc_spad_strides) + vsa4 = vsa_val + expand + config_type = CONFIG_TYPE[dma_type_val] + sram_c = MemRefType(sram_mem.type) + dram_addr = elem_addr_i64(dram, [dram_idx_val], dram_ty, elem_bytes) + spad_addr = elem_addr_i64(sram_mem, sram_indices, sram_c, elem_bytes) + ind_addr = None + ind_stride = ind_esize = 0 + if indirect: + sym = FlatSymbolRefAttr(offset_sym).value if not isinstance(offset_sym, str) else offset_sym + off_ty = sym2type[sym] + ind_base = memref.ExtractAlignedPointerAsIndexOp(memref.GetGlobalOp(off_ty, sym).result).result + ind_addr = arith.IndexCastOp(i64, ind_base).result + ind_esize = _elem_bytes(off_ty.element_type) + ind_stride = IntegerAttr(op.attributes["offset_stride"]).value + slots = _pack_desc(shape4, dram4, spad4, elem_bytes, vlane_stride, vsa4, + config_type, indirect, ind_stride, ind_esize, + accumulate=accumulate, acc_float=acc_float) + pairs4 = [(expand + d, lo, hi) for d, lo, hi in (desc_masked_pairs or ())] # 4D-expand axis + desc_ptr_val = desc_ptr(slots, pairs4, masked_fill, ind_addr) + asm(CONFIG_DESC, desc_ptr_val, i64_const(0)) + asm(dma_type_val, dram_addr, spad_addr) + + if offset_sym is not None: + offset_sym = FlatSymbolRefAttr(offset_sym).value if not isinstance(offset_sym, str) else offset_sym + + if len(tile_shape) <= 4: + with InsertionPoint(op): + # sram offset is linear (row-major stride 1) -> last index only; others 0. + sidx = [_const(0)] * (len(tile_shape) - 1) + [sram_idx] + _emit_asm(sram, sidx, dram_idx, vlane_axis, + tile_shape, dram_stride, tile_stride, subtile, masked_pairs) + op.erase() + continue + + if len(eff) <= 4: + groups, target = _squeeze_reassociation(tile_shape) + reassoc = ArrayAttr.get( + [ArrayAttr.get([IntegerAttr.get(i64, d) for d in g]) for g in groups]) + collapsed_ty = MemRefType.get(target, elem, memory_space=space) + keep = [next((d for d in g if tile_shape[d] > 1), g[-1]) for g in groups] + dr = [dram_stride[i] for i in keep] + tl = [tile_stride[i] for i in keep] + st = [subtile[i] for i in keep] if subtile is not None else None + # remap each masked tile axis to its collapsed group index. + mp = [(next(gi for gi, g in enumerate(groups) if d in g), lo, hi) + for d, lo, hi in masked_pairs] + new_vlane = next(gi for gi, g in enumerate(groups) if vlane_axis in g) + with InsertionPoint(op): + sram_c = Operation.create( + "memref.collapse_shape", results=[collapsed_ty], operands=[sram], + attributes={"reassociation": reassoc}).results[0] + sidx = [_const(0)] * (len(target) - 1) + [sram_idx] + _emit_asm(sram_c, sidx, dram_idx, new_vlane, target, dr, tl, st, mp) + op.erase() + continue + + # >4 effective dims: affine.for peel (mirrors decompose_transfer peel path) + peeled, inner = eff[:-4], eff[-4:] + ndim = len(tile_shape) + inner_shape = [tile_shape[d] for d in inner] + inner_strides = [tile_stride[d] for d in inner] + dr = [dram_stride[d] for d in inner] + tl = [tile_stride[d] for d in inner] + st = [subtile[d] for d in inner] if subtile is not None else None + if any(d in peeled for d, _lo, _hi in masked_pairs): + raise NotImplementedError("masked-DMA clamp on a peeled (outer-loop) axis") + mp = [(inner.index(d), lo, hi) for d, lo, hi in masked_pairs if d in inner] + if vlane_axis in inner: + new_vlane = inner.index(vlane_axis) + elif vlane_axis in peeled: + raise NotImplementedError( + f"vlane split axis {vlane_axis} peeled into the outer loop nest") + else: + new_vlane = 0 + split_extent = tile_shape[vlane_axis] + nr_outerloop = max( + (split_extent + vectorlane * vlane_stride - 1) // (vectorlane * vlane_stride), 1) + new_size = nr_outerloop * vlane_stride + target_stride = tile_stride[vlane_axis] + + def _phys(d): + s = tile_stride[d] + return s // split_extent * new_size if s > target_stride else s + + static_sizes = [1] * ndim + for d in inner: + static_sizes[d] = tile_shape[d] + res_ty = MemRefType.get( + inner_shape, elem, + layout=StridedLayoutAttr.get(0, inner_strides), memory_space=space) + + cur_ip = InsertionPoint(op) + ivs = [] + for d in peeled: + floop = affine.AffineForOp(0, tile_shape[d], 1, ip=cur_ip) + floop.operation.attributes["inner_loop"] = BoolAttr.get(True) + ivs.append(floop.induction_variable) + with InsertionPoint(floop.body): + affine.AffineYieldOp([]) + cur_ip = InsertionPoint.at_block_terminator(floop.body) + + npeel = len(peeled) + with cur_ip: + sub = Operation.create( + "memref.subview", results=[res_ty], operands=[sram], + attributes={"static_offsets": DenseI64ArrayAttr.get([0] * ndim), + "static_sizes": DenseI64ArrayAttr.get(static_sizes), + "static_strides": DenseI64ArrayAttr.get([1] * ndim), + "operandSegmentSizes": DenseI32ArrayAttr.get([1, 0, 0, 0])} + ).results[0] + sram_expr = AffineExpr.get_dim(0) * _phys(peeled[0]) + for k in range(1, npeel): + sram_expr = sram_expr + AffineExpr.get_dim(k) * _phys(peeled[k]) + sram_off_val = Operation.create( + "affine.apply", results=[idx_ty], operands=list(ivs), + attributes={"map": AffineMapAttr.get(AffineMap.get(npeel, 0, [sram_expr]))} + ).results[0] + dram_expr = AffineExpr.get_dim(0) + for k in range(npeel): + dram_expr = dram_expr + AffineExpr.get_dim(k + 1) * dram_stride[peeled[k]] + dram_idx_val = Operation.create( + "affine.apply", results=[idx_ty], operands=[dram_idx, *ivs], + attributes={"map": AffineMapAttr.get(AffineMap.get(npeel + 1, 0, [dram_expr]))} + ).results[0] + zero = _const(0) + _emit_asm(sub, [zero, zero, zero, sram_off_val], dram_idx_val, new_vlane, + inner_shape, dr, tl, st, mp) + op.erase() + + +def lower_text(text, timing=False): + if OP_NAME not in text: + return text + from mlir.ir import Context, Module, Location + ctx = Context() + ctx.allow_unregistered_dialects = True + with ctx, Location.unknown(): + m = Module.parse(text) + run(m, timing=timing) + return str(m) + + +if __name__ == "__main__": + import sys + out = lower_text(open(sys.argv[1]).read()) + (open(sys.argv[2], "w").write(out) if len(sys.argv) > 2 else sys.stdout.write(out)) diff --git a/PyTorchSimFrontend/mlir/passes/lower_vlane_idx.py b/PyTorchSimFrontend/mlir/passes/lower_vlane_idx.py index 76e30cb3..3ed0a394 100644 --- a/PyTorchSimFrontend/mlir/passes/lower_vlane_idx.py +++ b/PyTorchSimFrontend/mlir/passes/lower_vlane_idx.py @@ -24,13 +24,7 @@ OP_NAME = "torchsim.vlane_idx" MARKERS = (OP_NAME,) - -def _iter_ops(block): - for op in list(block.operations): - yield op - for region in op.operation.regions: - for b in region.blocks: - yield from _iter_ops(b) +from ._mlir_util import walk_ops def run(module, **_): @@ -46,7 +40,7 @@ def run(module, **_): targets = [] for region in module.operation.regions: for b in region.blocks: - for op in _iter_ops(b): + for op in walk_ops(b): if op.operation.name == OP_NAME: targets.append(op.operation) diff --git a/PyTorchSimFrontend/mlir/passes/peel_transfer.py b/PyTorchSimFrontend/mlir/passes/peel_transfer.py new file mode 100644 index 00000000..c2f3af4f --- /dev/null +++ b/PyTorchSimFrontend/mlir/passes/peel_transfer.py @@ -0,0 +1,217 @@ +"""Reduce a >4D togsim.transfer to <=4D (drop unit dims / peel outer dims). + +Both the Gemmini DMA descriptor and the TOGSim DMA model cap at 4 tile dims. A +logical tile can exceed 4D (e.g. pixel_shuffle splits two spatial axes -> a 5D +tile like [1,1,2,4,2]). lower_transfer_to_gemmini reduces >4D as part of emitting +Gemmini asm, but that runs only on the Spike/gem5 lowering path; the trace producer +(build_tog) reads togsim.transfer BEFORE that and would emit a >4D DMA that TOGSim +rejects ("issued tile is not supported format.. tile.size: 5"). + +This pass runs up front (POST_OPT, before build_tog) while KEEPING the op as +togsim.transfer, so both consumers see <=4D. It mirrors lower_transfer_to_gemmini's +two reductions: if the non-unit (effective) rank is <=4, collapse the unit dims +away (memref.collapse_shape); otherwise peel the outer effective dims into an +affine.for nest with the lane-banked physical SRAM offset. The innermost op is a +fresh <=4D togsim.transfer carrying the surviving dims' shape/strides/vlane axis +and the original dma_kind / masked / offset / subtile attributes. +""" + +OP_NAME = "togsim.transfer" +MARKERS = (OP_NAME,) + +from ._mlir_util import walk_ops +from .decompose_transfer import _int_array, _const_int, _squeeze_reassociation + + +def run(module, vectorlane=128, **_): + """Reduce every >4D togsim.transfer in `module` to <=4D, in place. Context active. + + vectorlane (= systolic-array size / number of vector lanes) feeds the lane-banked + physical SRAM offset in the peel, matching lower_transfer_to_gemmini. + """ + from mlir.ir import (InsertionPoint, Operation, MemRefType, ArrayAttr, + IntegerAttr, IntegerType, IndexType, DenseI64ArrayAttr, + DenseI32ArrayAttr, StridedLayoutAttr, AffineMap, AffineMapAttr, + AffineExpr, BoolAttr) + from mlir.dialects import affine + i64 = IntegerType.get_signless(64) + idx_ty = IndexType.get() + + def _arr(vals): + return ArrayAttr.get([IntegerAttr.get(i64, int(v)) for v in vals]) + + targets = [] + for region in module.operation.regions: + for b in region.blocks: + for op in walk_ops(b): + if op.operation.name == OP_NAME: + targets.append(op.operation) + + for op in targets: + op_operands = list(op.operands) + dram, dram_idx, sram, sram_idx, tag, tag_idx, dma_type, vst = op_operands[:8] + sram_ty = MemRefType(sram.type) + elem, space = sram_ty.element_type, sram_ty.memory_space + tile_shape = list(sram_ty.shape) + if len(tile_shape) <= 4: + continue # TOGSim / Gemmini accept <=4 raw tile dims -- nothing to do + eff = [i for i, e in enumerate(tile_shape) if e > 1] + + has_indirect = "indirect" in op.attributes + offset_operand = op_operands[8] if has_indirect else None + vlane_axis = IntegerAttr(op.attributes["vlane_split_axis"]).value + dram_stride = _int_array(op.attributes["dram_stride"]) + tile_stride = _int_array(op.attributes["tile_stride"]) + vlane_stride = _const_int(vst, 1) + subtile = _int_array(op.attributes["subtile_size"]) if "subtile_size" in op.attributes else None + if "masked_axes" in op.attributes: + masked_axes = _int_array(op.attributes["masked_axes"]) + n_base = 9 if has_indirect else 8 + mvals = op_operands[n_base:] + masked_pairs = [(masked_axes[i], mvals[2 * i], mvals[2 * i + 1]) + for i in range(len(masked_axes))] + else: + masked_pairs = [] + + def _emit_inner(sram_mem, sram_idx_val, dram_idx_val, new_vlane, dr, tl, st, mp): + operands = [dram, dram_idx_val, sram_mem, sram_idx_val, tag, tag_idx, dma_type, vst] + if has_indirect: + operands.append(offset_operand) + for _axis, lo, hi in mp: + operands += [lo, hi] + attrs = { + "dma_kind": op.attributes["dma_kind"], + "vlane_split_axis": IntegerAttr.get(i64, new_vlane), + "dram_stride": _arr(dr), + "tile_stride": _arr(tl), + "padding": op.attributes["padding"], + } + if st is not None: + attrs["subtile_size"] = _arr(st) + if "async" in op.attributes: + attrs["async"] = op.attributes["async"] + if mp: + attrs["masked_axes"] = _arr([a for a, _lo, _hi in mp]) + attrs["masked_fill"] = op.attributes["masked_fill"] + if has_indirect: + attrs["indirect"] = op.attributes["indirect"] + attrs["offset_stride"] = op.attributes["offset_stride"] + if "accumulate" in op.attributes: + attrs["accumulate"] = op.attributes["accumulate"] + if "acc_float" in op.attributes: + attrs["acc_float"] = op.attributes["acc_float"] + Operation.create(OP_NAME, results=[], operands=operands, attributes=attrs) + + # <=4 effective dims: collapse the unit dims so the raw rank reaches <=4. + if len(eff) <= 4: + groups, target = _squeeze_reassociation(tile_shape) + reassoc = ArrayAttr.get( + [ArrayAttr.get([IntegerAttr.get(i64, d) for d in g]) for g in groups]) + collapsed_ty = MemRefType.get(target, elem, memory_space=space) + keep = [next((d for d in g if tile_shape[d] > 1), g[-1]) for g in groups] + dr = [dram_stride[i] for i in keep] + tl = [tile_stride[i] for i in keep] + st = [subtile[i] for i in keep] if subtile is not None else None + mp = [(next(gi for gi, g in enumerate(groups) if d in g), lo, hi) + for d, lo, hi in masked_pairs] + new_vlane = next(gi for gi, g in enumerate(groups) if vlane_axis in g) + with InsertionPoint(op): + sram_c = Operation.create( + "memref.collapse_shape", results=[collapsed_ty], operands=[sram], + attributes={"reassociation": reassoc}).results[0] + _emit_inner(sram_c, sram_idx, dram_idx, new_vlane, dr, tl, st, mp) + op.erase() + continue + + # >4 effective dims: peel the outer effective dims into an affine.for nest and + # keep the innermost 4. The SRAM slice offset is the lane-banked physical offset + # (dims outer than the vlane axis rescaled by stride/split_extent*new_size), + # delivered as the transfer's sram_idx; the DRAM offset folds into dram_idx. + peeled, inner = eff[:-4], eff[-4:] + ndim = len(tile_shape) + inner_shape = [tile_shape[d] for d in inner] + inner_strides = [tile_stride[d] for d in inner] + dr = [dram_stride[d] for d in inner] + tl = [tile_stride[d] for d in inner] + st = [subtile[d] for d in inner] if subtile is not None else None + if any(d in peeled for d, _lo, _hi in masked_pairs): + raise NotImplementedError("masked-DMA clamp on a peeled (outer-loop) axis") + mp = [(inner.index(d), lo, hi) for d, lo, hi in masked_pairs if d in inner] + if vlane_axis in inner: + new_vlane = inner.index(vlane_axis) + elif vlane_axis in peeled: + raise NotImplementedError( + f"vlane split axis {vlane_axis} peeled into the outer loop nest") + else: + new_vlane = 0 + + split_extent = tile_shape[vlane_axis] + nr_outerloop = max( + (split_extent + vectorlane * vlane_stride - 1) // (vectorlane * vlane_stride), 1) + new_size = nr_outerloop * vlane_stride + target_stride = tile_stride[vlane_axis] + + def _phys(d): + s = tile_stride[d] + return s // split_extent * new_size if s > target_stride else s + + static_sizes = [1] * ndim + for d in inner: + static_sizes[d] = tile_shape[d] + res_ty = MemRefType.get( + inner_shape, elem, + layout=StridedLayoutAttr.get(0, inner_strides), memory_space=space) + + cur_ip = InsertionPoint(op) + ivs = [] + for d in peeled: + floop = affine.AffineForOp(0, tile_shape[d], 1, ip=cur_ip) + floop.operation.attributes["inner_loop"] = BoolAttr.get(True) + ivs.append(floop.induction_variable) + with InsertionPoint(floop.body): + affine.AffineYieldOp([]) + cur_ip = InsertionPoint.at_block_terminator(floop.body) + + npeel = len(peeled) + with cur_ip: + sub = Operation.create( + "memref.subview", results=[res_ty], operands=[sram], + attributes={"static_offsets": DenseI64ArrayAttr.get([0] * ndim), + "static_sizes": DenseI64ArrayAttr.get(static_sizes), + "static_strides": DenseI64ArrayAttr.get([1] * ndim), + "operandSegmentSizes": DenseI32ArrayAttr.get([1, 0, 0, 0])} + ).results[0] + sram_expr = AffineExpr.get_dim(0) * _phys(peeled[0]) + for k in range(1, npeel): + sram_expr = sram_expr + AffineExpr.get_dim(k) * _phys(peeled[k]) + sram_off_val = Operation.create( + "affine.apply", results=[idx_ty], operands=list(ivs), + attributes={"map": AffineMapAttr.get(AffineMap.get(npeel, 0, [sram_expr]))} + ).results[0] + dram_expr = AffineExpr.get_dim(0) + for k in range(npeel): + dram_expr = dram_expr + AffineExpr.get_dim(k + 1) * dram_stride[peeled[k]] + dram_idx_val = Operation.create( + "affine.apply", results=[idx_ty], operands=[dram_idx, *ivs], + attributes={"map": AffineMapAttr.get(AffineMap.get(npeel + 1, 0, [dram_expr]))} + ).results[0] + _emit_inner(sub, sram_off_val, dram_idx_val, new_vlane, dr, tl, st, mp) + op.erase() + + +def peel_text(text): + if OP_NAME not in text: + return text + from mlir.ir import Context, Module, Location + ctx = Context() + ctx.allow_unregistered_dialects = True + with ctx, Location.unknown(): + m = Module.parse(text) + run(m) + return str(m) + + +if __name__ == "__main__": + import sys + out = peel_text(open(sys.argv[1]).read()) + (open(sys.argv[2], "w").write(out) if len(sys.argv) > 2 else sys.stdout.write(out)) diff --git a/PyTorchSimFrontend/mlir/passes/togsim_ops.py b/PyTorchSimFrontend/mlir/passes/togsim_ops.py new file mode 100644 index 00000000..21983da0 --- /dev/null +++ b/PyTorchSimFrontend/mlir/passes/togsim_ops.py @@ -0,0 +1,102 @@ +"""Shared vocabulary for the skeleton+API MLIR form (C1). + +The trace pipeline (docs/design/togsim_cpp_trace.md) reduces a kernel's MLIR to +a *loop skeleton + API calls*: native `affine.for`/`scf.for` loops (bounds kept +as-is, symbolic preserved) plus a handful of `togsim.*` ops that stand for the +runtime API. This module is the single source of truth for those op names and +attribute keys, shared by: + + * build_skeleton (C2) -- produces the skeleton+API MLIR, and + * togsim->emitc lowering (C4) -- rewrites each op to an `emitc.call_opaque`. + +The ops are kept *unregistered* (like the existing `togsim.transfer`), so there +is no C++ dialect to register; C4 is a custom rewrite, not a registered +ConversionPass. + +Grammar (each op lowers 1:1 to a `togsim_runtime.h` free function): + + "togsim.dma"(%dram_idx, %tag_idx) { -> togsim_dma(ctx, dir, arg_id, + dir = 0 | 1, # LOAD|STORE offset, ndim, dims, strides, + dims = [..], strides = [..], elem_bits, is_async, + elem_bits = i32, is_async = bool, tag_id, tag_slot, + tag_id = i32, arg_id = i32, read_bufs, write_bufs) + read_bufs = [..], write_bufs = [..] + } : (index, index) -> () + + "togsim.compute"() { -> togsim_compute(ctx, tile_id, + tile_id = i64, compute_type = i32, compute_type, ndim, dims, + read_bufs = [..], write_bufs = [..] read_bufs, write_bufs) + } : () -> () + + "togsim.memory_barrier"(%tag_idx) { -> togsim_memory_barrier(ctx, + tag_id = i32, write_bufs = [..] tag_id, tag_slot, write_bufs) + } : (index) -> () + +How an async dma pairs with its sync point: NOT by a compile-time id. One static +`togsim.dma` op runs once per loop iteration, each with a different RUNTIME tag +slot `%tag[%idx]`, so the pairing must be a runtime key. `togsim.dma` carries a +`tag_id` (its tag memref identity) and the runtime `%tag[%idx]` operand; the +original `memref.dma_wait` becomes an explicit `togsim.memory_barrier` carrying +the same `tag_id` + tag index. They pair at runtime by `(tag_id, tag_slot)` via +the Core's tag table (the dma signals the tag at data-arrival; the barrier waits +it). `tag_id` (which tag memref) is distinct from `tag_slot` (the SRAM tile slot, +used for the double-buffer / capacity model). A sync (non-async) dma is blocking, +so it needs no barrier. (Supersedes the earlier static `event_id` + `togsim.wait` +design, which could not express per-iteration pairing.) + +Keep this in lockstep with TOGSim/include/togsim_runtime.h (TOGSIM_ABI_VERSION). +""" + +# ---- op names ------------------------------------------------------------- +DMA = "togsim.dma" +COMPUTE = "togsim.compute" +MEMORY_BAR = "togsim.memory_barrier" # explicit async-DMA sync (the original dma_wait); tag-keyed + +#: every op this module owns (for matchers / DCE roots in C2). +OP_NAMES = (DMA, COMPUTE, MEMORY_BAR) + +#: op name -> the togsim_runtime.h symbol C4 lowers it to. +EMITC_CALLEE = { + DMA: "togsim_dma", + COMPUTE: "togsim_compute", + MEMORY_BAR: "togsim_memory_barrier", +} + +#: producer entry-point symbol the TOGSim loader resolves (see togsim_runtime.h). +ENTRY_SYMBOL = "togsim_kernel" + +#: outlined per-work-item function the dispatcher hands to togsim_dispatch +#: (uniform signature (ctx, int64* iv, i32 n); see togsim_cpp_trace.md sec 9.3). +TILE_SYMBOL = "togsim_kernel_tile" + +#: runtime callees emitted directly by lower_to_emitc (not skeleton ops), kept in +#: lockstep with togsim_runtime.h. DISPATCH_CALLEE is the higher-order wrapper the +#: dispatcher loop calls per work-item (round-robins a core + TILE_BEGIN/END); +#: TILE_SYMBOL is passed to it as the function pointer. +DISPATCH_CALLEE = "togsim_dispatch" + +# ---- attribute keys ------------------------------------------------------- +ATTR_DIR = "dir" # i32: DIR_LOAD | DIR_STORE +ATTR_DIMS = "dims" # i64 array: tile extents +ATTR_STRIDES = "strides" # i64 array: tile strides +ATTR_ELEM_BITS = "elem_bits" # i32 +ATTR_IS_ASYNC = "is_async" # bool +ATTR_TILE_ID = "tile_id" # i64: key into the precomputed tile_id->cycle table +ATTR_COMPUTE_TYPE = "compute_type" # i32: 0 vector / 1 matmul / 2 preload (Core enum) +ATTR_READ_BUFS = "read_bufs" # i64 array: SRAM buffer ids this op reads (sec 10 dataflow) +ATTR_WRITE_BUFS = "write_bufs" # i64 array: SRAM buffer ids this op writes (sec 10 dataflow) +ATTR_TAG_ID = "tag_id" # i32: identity of the DMA's tag memref; pairs an async dma with + # its memory_barrier by the RUNTIME tag slot (tag_id + tag index) +ATTR_ARG_ID = "arg_id" # i32: which tensor (func arg) this DMA's base is + +# Must match togsim_dma_dir in togsim_runtime.h. +DIR_LOAD = 0 +DIR_STORE = 1 + + +def is_togsim_op(op): + """True if `op` (an Operation or a wrapping view) is one of ours.""" + name = getattr(op, "name", None) + if name is None: + name = getattr(getattr(op, "operation", None), "name", None) + return name in OP_NAMES diff --git a/README.md b/README.md index f0bdc772..8b90b87b 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,9 @@ PyTorchSim **supports**: | Stable-diffusion v1 | 🤗 | ✅ | | | Llama 2/3 | 🤗 | ✅ | `tests/models/Llama/` (blocks & decode-style paths) | | DeepSeek-V3 (base) | 🤗 | ✅ | `tests/models/DeepSeek/` — several ops(e.g., gate ops) are not cycle-modeled | +| SwinV2 | 🤗 | ✅ | `tests/models/test_swinv2.py` (shifted-window attention) | +| CLIP (vision) | 🤗 | ✅ | `tests/models/test_clip.py` | +| ConvNeXt V2 | 🤗 | ✅ | `tests/models/test_convnextv2.py` (channels-first LayerNorm, depthwise conv) | | Llama-4 | 🤗 | ⏳ | In development | | Broader model support | — | ⏳ | In development | C++ --g++ -shared--> trace.so + | TOGSim loader (C6): dlopen + EmitCtx callbacks + v + TraceRec stream (materializing sink) + | togsim_trace_bridge.cc -> existing Core timing + v + cycles / DRAM traffic (real Core) +``` + +Side artifact: cycle table `tile_id -> (cycle, overlapping_cycle)` (cycle_table.py). + +## 3. Milestones + +| | State | +|---|---| +| P0 ABI header + togsim vocabulary | DONE (ABI evolved to v11) | +| P1 build_skeleton | DONE, verified (compute/dma/barrier match legacy TOG) | +| P2 lower_to_emitc -> .so | DONE (real GEMM .so built and run) | +| P3 loader/runtime + cycle table + real-Core run | DONE (runs end-to-end through the real Simulator/Core; below) | +| P4 symbolic/dynamic shape, streaming sink | TODO | +| P5 op-family migration (conv/SDPA/vector) | TODO | + +P3 detail: + +| | State | +|---|---| +| ABI (core_alloc, runtime tag pairing, dma address) | DONE (v11) | +| work-item boundary (togsim_core_alloc) | DONE | +| real tile DRAM addresses (approach A) | DONE, verified on 1024^3 | +| cycle_table builder (cycle + overlapping) | DONE | +| async DMA <-> consumer sync (runtime tag slot, memory_barrier) | DONE | +| explicit dataflow DAG (read/write_bufs last-writer) | DONE | +| C6 runtime + dlopen loader (materializing) | DONE | +| TraceRec -> existing Core timing feed | DONE (runs end-to-end through real Core) | +| cycle comparison vs build_tog (real gem5 table) | DONE: trace 2518 vs legacy 2698 | +| SRAM tile lifecycle / preload-occupancy refinements | partial (see §7) | + +### TraceRec -> Core: now running end-to-end + +`TOGSim/src/togsim_trace_bridge.cc` (`trace_to_tilegraph`) + a `--trace_so` mode +in `main.cc` feed the recorded trace into the REAL Simulator/Core. The producer +`.so` is `dlopen`'d (the Simulator is built with ENABLE_EXPORTS so the `.so` +resolves the `togsim_*` callbacks back into the binary), its trace recorded, then +bridged to a `TileGraph`: one `TileSubGraph` per work-item (core_alloc marker) +bound to its core, one `Tile` of MOVIN/MOVOUT/COMP/MEMORY_BAR/COMPUTE_BAR +`Instruction`s. Dependency edges are built by **last-writer per SRAM buffer** +(`read_bufs`/`write_bufs`); an async load's last-writer is the MEMORY_BAR paired +to it by the runtime `(tag_id, tag_slot)` (so a consumer waits actual data +arrival), and a COMPUTE_BAR drains the systolic-array pipeline before a store. +Build it (`cd TOGSim/build && cmake .. && make`) and run: +`bin/Simulator --config --trace_so gemm_trace.so`. + +### Cycle comparison vs legacy build_tog (256^3 GEMM, real gem5 table) + +Ran the same kernel through the legacy path (torch.compile -> gem5 -> build_tog +-> Simulator) and the trace path (the same post-vcix IR -> trace .so + the SAME +gem5 cycle_list -> --trace_so), both through the REAL Core. extension_codecache +has an opt-in TORCHSIM_DUMP_TRACE_SO=1 hook that dumps trace.so + trace_cycles.tsv +from the same cycle_list/offsets (best-effort, never breaks the legacy path); +compute-unit routing uses compute_type and the tag key uses a per-tensor addr_id +(set_addr_name(arg_id)+prepare_tag_key) so A and B don't collide on tag_slot 0. + +**Result: the trace path totals 2518 cycles vs the legacy path's 2698 on the +same gem5 cycle table.** All togsim python tests pass; TOGSim builds. Compute +work and DRAM traffic match; the remaining difference is scheduling (the +explicit dataflow DAG plus the occupancy/latency SA-pipeline model overlap +differently than legacy's per-iteration BARs). + +**Subtile + multi-tile-K now runs** (256x512x256 forced to 128x128 subtiles, 2 +K-tiles: 5774 cycles, no crash). This needed `build_skeleton` to strip the +`-acc_iv` accumulation marker from the dma_wait tag index so the memory_barrier +slot stays subtile-only and pairs with its load (see §3, `tag_slot`); before the +strip the producer evaluated `-acc_iv` to a negative slot at the 2nd K-tile and +TOGSim aborted with "Key does not exist in ... tag table". + +## 4. Components + +- `build_skeleton.py` + `dep_analysis.py` — in-place reduction of post-vcix to + "loop skeleton + togsim.* API"; `memref.dma_wait` mapped through to an explicit + `togsim.memory_barrier`; read/write SRAM buffer ids attached; reuses legacy + `TogBuilder` traversal. +- `lower_to_emitc.py` — skeleton -> EmitC by driving the upstream conversion + passes plus `_retype_for_to_size_t` (clears residual index<->size_t casts). + `togsim_dma` carries `(tag_id, runtime tag-index, is_async, read/write_bufs)` + and returns void; `togsim_memory_barrier` carries `(tag_id, tag_slot, + write_bufs)`; `togsim_core_alloc` inserted at the work-item boundary. +- `cycle_table.py` — `tile_id -> (cycle, overlapping)`, overlapping + `= max(cycle - offset[type], 0)` (legacy formula); JSON sidecar. +- `TOGSim/src/togsim_runtime.cc` + `TOGSim/include/togsim_loader.h` — C6 runtime + and `run_producer` (dlopen -> togsim_kernel -> records TraceRec). dma resolves + `base[arg] + offset*elem_bytes` and signals its tag at data arrival; the + matching memory_barrier waits the `(tag_id, tag_slot)`; compute looks up the + cycle table; core_alloc round-robins a runtime core pool. +- `TOGSim/src/togsim_trace_bridge.cc` — bridges the recorded TraceRec stream into + the existing `TileGraph`/`Instruction` form for the real Core. +- `TOGSim/include/togsim_runtime.h` — producer ABI v11. + +## 5. Locked design decisions + +1. **Trace is a DAG, not a time order.** The consumer (existing Core) schedules + per-core timelines from: op kind -> hardware unit, SRAM-buffer last-writer -> + data dependency, same-core -> serial (reduction accumulate), SRAM slot -> + capacity. Emission order != execution order. +2. **Async-DMA sync = runtime tag slot.** A `togsim.dma` carries `(tag_id, + tag_slot)`; the matching `togsim.memory_barrier` (lowered from the source + `memref.dma_wait`) waits on the same pair through the existing Core tag table + (`prepare_tag_key`/`set_tag_finish`/`register_tag_waiter`). The DMA signals at + data arrival; the barrier becomes the loaded buffer's last-writer so consumers + gate on arrival. A sync DMA is blocking (no barrier). This replaced an earlier + `event_id` / heap event-handle design, which could not pair a DMA op with its + wait per loop iteration (one static op, a different tag slot each iteration). + No `calc_tag` content-hash, no magic values, no FIFO. +3. **Core = runtime allocation.** `togsim_core_alloc` returns a core id (no free). + `num_cores` is never baked into the producer -- it is the runtime pool size. + A work-item's reduction stays on one core (sticky); different work-items get + different cores -> multi-core. +4. **Intrinsic baked / extrinsic parametric.** vlane / tile sizes / systolic + define instructions (baked); num_cores only distributes (runtime). +5. **Execution model:** P3 materializing (run producer to completion -> record -> + feed existing Core); P4 streaming (coroutine, alloc-blocks on resources). +6. **Double-buffer = resource constraint.** Producer emits everything (no skew); + capacity is the consumer's throttle. Requires SRAM tile lifecycle + (alloc/free) in the trace -- the currently missing piece. + +## 6. Verification (reproducible) + +- togsim python tests pass: skeleton (contract + fixture), emitc (build + dlopen + run), cycle_table, runtime. TOGSim builds. +- 256^3 GEMM: core_alloc -> dma(tag_id, tag_slot) -> memory_barrier(tag_id, + tag_slot) -> compute; addresses A/B/C resolved (offset 0, single tile). +- 1024^3 GEMM: per-tile addresses correct (A[m,k]=m*1024+k -> 0,256,512; + B[k,n]=k*1024+n -> 0,262144,524288). +- End-to-end through the real Core (256^3 GEMM, real gem5 table): trace 2518 + cycles vs legacy 2698. +- Legacy ONNX-TOG path untouched (comment-only diff), marked DEPRECATED, kept as + the comparison reference. + +## 6b. Reference timer (early sanity check; superseded by the real Core feed) + +`togsim::simulate(RunResult, TimingParams)` (togsim_runtime.cc) was an early +standalone scheduler that timed the recorded TraceRec to prove the stream is +sufficient to be timed: per core a DMA-engine timeline (DMAs serialize, overlap +compute), a compute timeline (serial = reduction accumulate, with the `finish = +prev.finish + cycle - overlapped` pipeline overlap of Core.cc), and data deps. +It is NOT the production Core (no DRAM/NoC/L2 contention). It has since been +superseded: the recorded stream is now bridged into the real Tile/TileGraph -> +Core (see §3, and the 2518-vs-2698 result above). Retained here as context. + +## 7. Remaining work (priority order) + +1. DONE. Map TraceRec -> existing TOGSim Core Instructions (Tile/TileGraph, + compute_cycle+overlapping, dataflow-buffer deps + runtime-tag barriers) and + run through the real Core. Result: trace 2518 vs legacy 2698 on the same gem5 + table. +2. SRAM tile lifecycle in the trace (double-buffer throttle). togsim_dma carries + `tag_slot` (the lowered SRAM tag index = the slot key the existing Core's + Instruction.tag_idx needs); 0 for single-buffer kernels. Remaining: the + consumer must use it to throttle in-flight loads to the buffer depth. The + SRAM-buffer key is effectively (arg_id, tag_slot) since each load's DRAM + tensor maps to its spad. +3. Preload concurrency cap / preload occupancy (design doc §10.5): give a preload + a non-zero occupancy so concurrent preloads are capped at the SA count. + Pre-existing in BOTH paths. +4. (later) deeper double-buffer pipelines (more tag slots), two-function outline, + P4 streaming, symbolic shape, P5 op coverage (conv/SDPA/vector). + +## 8. Risks / open + +- SRAM lifecycle (double-buffer throttle) not yet implemented -- central to + double-buffer/capacity accuracy on multi-tile kernels. +- LLVM 20 emitc constraints absorbed: emitc.for index bounds; old + subscript-returns-element model; arith.divui/remui not lowerable -> core id is + a runtime allocation (which became a design improvement). + +### Explicit dataflow-edge dependency model: implemented + +The dependency model is an explicit dataflow DAG, not in-order or runtime-tag +content-hashing. `togsim_dma`/`togsim_compute` carry read_bufs/write_bufs (SRAM +buffer ids; a virtual SA_WEIGHTS buffer folds the preload->matmul edge). +dep_analysis + build_skeleton attach them; lower_to_emitc emits them; the runtime +records them; the bridge builds the Instruction DAG by last-writer per buffer, +scoped per work-item. The one runtime-paired edge is the async-DMA data wait, +routed through an explicit `togsim.memory_barrier` keyed on `(tag_id, tag_slot)` +(see design doc §10.7.4). The systolic-array pipeline uses the occupancy/latency +split (§10.7), so accumulating matmuls pipeline rather than serialize. + +Net (256^3 GEMM, real gem5 table, real Core): trace 2518 vs legacy 2698. +Per-output-tile dispatch for multi-core distribution is the next refinement +(today one dispatch per work-item). diff --git a/docs/design/transfer-direct-lowering.md b/docs/design/transfer-direct-lowering.md new file mode 100644 index 00000000..7e693d91 --- /dev/null +++ b/docs/design/transfer-direct-lowering.md @@ -0,0 +1,66 @@ +# Direct togsim.transfer -> Gemmini lowering (drop memref.dma_start) + +## Why +`togsim.transfer` currently lowers `decompose_transfer` -> `memref.dma_start` -> +... -> `lower_dma_to_gemmini` -> gemmini asm. `memref.dma_start` is a REGISTERED +MLIR op with a fixed operand list, so it cannot carry extra RUNTIME operands. The +indirect offset worked around this with a static symbol attribute; the masked-DMA +`low`/`high` clamp bounds are RUNTIME index values (dynamic shapes) and cannot be +attributes -- so they cannot ride on `memref.dma_start` at all. + +Fix: keep `togsim.transfer` (unregistered -> arbitrary operands) alive through the +pipeline and lower it DIRECTLY to gemmini, carrying every runtime descriptor +(dram_idx, vlane, offset, low/high) as operands. This also lets `test-loop-padding` +retire later (the clamp replaces it), collapsing the mlir-opt step. + +## Target transfer op (superset, all optional beyond the base) +``` +togsim.transfer(dram, dram_idx, sram, sram_idx, tag, dma_type, vst, + [offset_spad], # indirect (gather/scatter) + [low_vec, high_vec]) # masked clamp: per-dim valid [low, high) + attrs: dma_kind, dram_stride[], tile_stride[], padding, [subtile_size, async] +``` +- no `low`/`high` -> full transfer `[0, memref_dim)` (current behaviour). +- no `offset` -> base address (current behaviour). +- `low`/`high` are runtime index operands (vectors length ndim), NOT attributes. + +## Semantics of the clamp (step 2; recorded here for the target) +dest tile stays FULL (banking unchanged -> no vlane shift); only the SOURCE sub-box +`[low, high)` per dim is read; dest positions outside it get `fill` (= ops.masked +`other`). This is "source subview + full dest + fill", not a dest subview. + +## memref.dma_start consumers to port (the scope -- all-or-nothing) +1. `lower_dma_to_gemmini` (dma_start -> asm): consume togsim.transfer; ABSORB + decompose_transfer's 4D handling (<=4D direct / collapse unit dims / >4D + affine.for peel + subview + lane-banked phys offset). +2. `dma_fine_grained` (matmul subtile split, marker=subtile_size): split + togsim.transfer instead of dma_start (same loop structure/offsets). +3. `lower_to_vcix._DmaView` (positional read for compute coord): read + togsim.transfer operand layout. +4. `test-loop-padding` (C++ mlir-opt): verify it tolerates an unregistered + togsim.transfer in the module (allow-unregistered) and pads loops as before. + +## Staging (step 1 = behaviour-preserving; regression 0; low/high NOT added yet) +- 1i. Draft merged `lower_transfer_to_gemmini` (transfer -> asm + 4D handling) in a + NEW file. A/B validate its gemmini asm against the current + decompose->...->lower chain on sample post-vcix MLIR (gemm, conv, pad, + pointwise, gather). NOT wired into the live pipeline yet. +- 1ii. Port `dma_fine_grained` + `_DmaView` to the togsim.transfer operand layout. +- 1iii. Remove `decompose_transfer` from PRE_OPT; rewire so togsim.transfer survives + to the merged lowering. Confirm test-loop-padding still runs (unregistered). +- 1iv. Full regression (the CI allowlist locally): add/matmul/conv/attention/pad/ + gather/models. Gate = regression 0. + +## Step 2 (feature, on top of step 1) +- Add `low`/`high` operands to `emit_transfer` (from load index-affine intersect + operand shape, D2) + `fill`; merged lowering emits the clamp into the gemmini + CONFIG/MVIN; Spike MVIN gates per-position `low[d] <= idx[d] < high[d]` else fill. + Drop the ops.masked `where` for pure-load bodies; keep it for compute-mixed. +- Gate: constant_pad correct with divisibility ON (regression 0), then P5 removes + divisibility -> mobilenet wrapper3 holes/segfault fixed. + +## Validation harness +A/B equivalence: for each stage, run the OLD chain and the NEW pass on the same +post-vcix MLIR dump and diff the emitted gemmini asm (structurally: same +CONFIG/CONFIG2/3/[4]/MVIN sequence, same packed rs1/rs2, same loop nests). Then the +end-to-end Spike allclose + timing tests. diff --git a/docs/per-kernel-functional-verify.md b/docs/per-kernel-functional-verify.md new file mode 100644 index 00000000..2870f18f --- /dev/null +++ b/docs/per-kernel-functional-verify.md @@ -0,0 +1,111 @@ +# Per-kernel functional verify + +A debugging tool that pinpoints the **first compiled kernel** whose simulated +(Spike) output diverges from a CPU reference. Use it when a whole-model run gives +a wrong final result and you need to know *which operation* introduced the error, +instead of only seeing that the final `torch.allclose` failed. + +## TL;DR + +```yaml +# in your TOGSim config YAML (e.g. configs/systolic_ws_8x8_c1_simple_noc_tpuv3.yml) +pytorchsim_functional_mode: 1 # required (this is its parent) +pytorchsim_functional_verify_per_kernel: 1 # turn the verify on +``` + +```bash +# checks are baked into the wrapper at compile time, so clear the codegen cache +# whenever you toggle this option (see the "Gotchas" note in CLAUDE.md) +bash scripts/clear_codegen_cache.sh +python tests/models/Yolov5/test_yolov5.py +``` + +On the first divergent kernel you get, and the run stops there: + +``` +================= PER-KERNEL FUNCTIONAL VERIFY: DIVERGENCE ================= + first divergent buffer : buf1 + originating fx op : aten.relu.default (node 'relu') + shape : (16, 16) + elements over tol : 90 / 256 + max abs diff : 1.43051e-06 (rtol=1e-4 atol=1e-4) + first bad index : [0, 0] + buffers verified OK : 0 + sample mismatches (npu vs cpu): + (0, 0): npu=0.323295 cpu=0.323294 + ... +=========================================================================== +``` + +## Options + +| Option | Where | Default | Meaning | +|---|---|---|---| +| `pytorchsim_functional_verify_per_kernel` | config YAML | `0` (off) | enable the per-kernel CPU cross-check | +| `TORCHSIM_FUNCTIONAL_VERIFY_RTOL` | env | `1e-4` | relative tolerance for the compare | +| `TORCHSIM_FUNCTIONAL_VERIFY_ATOL` | env | `1e-4` | absolute tolerance for the compare | + +It is a **sub-option of `pytorchsim_functional_mode`** and is auto-disabled when +functional mode is off (there are no Spike values to verify otherwise). The +config accessor AND-gates the two, so setting the key alone with functional mode +off does nothing. + +## How it works + +The value of every tensor in a compiled graph comes from Spike running the +generated kernels (the timing path / TOGSim cannot change tensor values). This +tool compares those values against a CPU "golden" at the boundary of each +compiled kernel. + +1. **Golden (once per `call(args)`).** At the top of the generated wrapper, + `verify_init(gid, [inputs])` looks up the original aten graph + (`V.graph.module`, registered at codegen time), **copies the inputs to CPU**, + and runs the whole graph on CPU with an `fx.Interpreter` that records every + node's output tensor by name. These are the absolute-correct reference values + (computed from the original inputs, with no accumulated npu error). + +2. **Check (after each kernel).** After a kernel writes its output buffer, + `verify_check(buf, "buf", node_name, op)` copies that npu buffer to CPU and + `torch.allclose`-compares it to `golden[node_name]`. The buffer is mapped to + its originating fx node via `V.graph.get_buffer(name).origin_node`, which is + how the report can name the offending op. + +3. **Stop at first.** Each buffer is checked once, on its first appearance as a + kernel argument (the producer kernel precedes any consumer in topological + order). The first buffer that exceeds tolerance is the injection point -- its + inputs were still within tolerance -- so the check logs the report and raises + `FunctionalVerifyMismatch` immediately. + +Comparison granularity is the **fused-cluster output**: Inductor fuses several +aten ops into one kernel and only the cluster's realized output buffer is +observable. The check verifies that buffer and names the cluster's output op. For +example `relu(a @ b + bias)` is one kernel writing one buffer, reported as +`aten.relu.default`. + +## Limitations + +- **Granularity is the fused kernel, not the individual aten op.** If the bug is + in an op that was fused into the middle of a cluster (e.g. the matmul inside + `relu(a@b+bias)`), it is reported at the cluster's output buffer/op (`relu`), + not the internal culprit. Ops that get their own kernel (matmul, conv, cat, + sdpa, sort, ...) are named precisely. +- **Requires a codegen-cache clear when toggling**, because the `verify_*` calls + are emitted into the wrapper only when the option is on at compile time. A + cached wrapper compiled without it will be replayed without checks. +- **Coverage, not correctness, degrades gracefully.** A buffer with no + `origin_node`, a non-tensor, or a name the golden did not capture is silently + skipped (fewer checks, never a false alarm). The golden run is wrapped in + try/except: if the aten graph fails to run on CPU, checks are disabled for that + graph rather than crashing the real run. +- **Overhead.** The full aten graph is run on CPU once per `call(args)`, and each + buffer is copied to CPU for the compare. This is a debugging mode; leave it off + for normal runs. + +## Code + +- `PyTorchSimFrontend/extension_functional_verify.py` -- graph registry, golden + interpreter, compare/report (`register_graph`, `verify_init`, `verify_check`). +- `PyTorchSimFrontend/mlir/mlir_codegen_backend.py` -- injects the calls into the + wrapper (`write_prefix`, `generate`, `_fverify_emit_checks`). +- `PyTorchSimFrontend/extension_config.py` -- reads the YAML key and AND-gates it + with `pytorchsim_functional_mode`. diff --git a/scripts/chiplet.sh b/scripts/chiplet.sh index e622874b..40aa77c4 100755 --- a/scripts/chiplet.sh +++ b/scripts/chiplet.sh @@ -35,7 +35,12 @@ for ATTRIBUTE in "$@"; do fi ATTRIBUTE_FILES+=("$ATTRIBUTE_FILE") done -MODELS_LIST="$GEMM_PATH/tile_graph.onnx" +# Trace (C++ TOG) path. NOTE: TOGSim currently stubs per-tensor addresses for the +# trace path (build_trace_tilegraph), so chiplet NoC/DRAM-partition accuracy is +# approximate until the trace path consumes real addresses; --attributes_list is +# no longer a Simulator option. +TRACE_SO="$GEMM_PATH/trace.so" +CYCLE_TABLE="$GEMM_PATH/trace_cycles.tsv" ATTRIBUTE_PATH="$GEMM_PATH/runtime_0000/attribute" for CONFIG in "${CONFIG_LIST[@]}"; do @@ -49,8 +54,7 @@ for CONFIG in "${CONFIG_LIST[@]}"; do OUTPUT_FILE="$RESULTS_DIR/${CONFIG_NAME}_result.txt" # Run Simulator - echo "$SIMULATOR_PATH" --config "$CONFIG" --models_list "$MODELS_LIST" --attributes_list "$ATTRIBUTE_PATH/$ATTRIBUTE_NAME" - "$SIMULATOR_PATH" --config "$CONFIG" --models_list "$MODELS_LIST" --log_level trace --attributes_list "$ATTRIBUTE_PATH/$ATTRIBUTE_NAME" > "$OUTPUT_FILE" & + echo "$SIMULATOR_PATH" --config "$CONFIG" --trace_so "$TRACE_SO" --cycle_table "$CYCLE_TABLE" "$SIMULATOR_PATH" --config "$CONFIG" --trace_so "$TRACE_SO" --cycle_table "$CYCLE_TABLE" --log_level trace --attributes_list "$ATTRIBUTE_PATH/$ATTRIBUTE_NAME" > "$OUTPUT_FILE" & echo "[TOGSim] for $CONFIG stored to \"$(pwd)/$OUTPUT_FILE\"" done done @@ -63,8 +67,7 @@ for CONFIG in "${CONFIG_LIST2[@]}"; do OUTPUT_FILE="$RESULTS_DIR/${CONFIG_NAME}_result.txt" # Run Simulator - # echo "$SIMULATOR_PATH" --config "$CONFIG" --models_list "$MODELS_LIST" --attributes_list "$ATTRIBUTE_PATH/$ATTRIBUTE_NAME" - "$SIMULATOR_PATH" --config "$CONFIG" --models_list "$MODELS_LIST" --log_level trace --attributes_list "$ATTRIBUTE_PATH/$ATTRIBUTE_NAME" > "$OUTPUT_FILE" & + # echo "$SIMULATOR_PATH" --config "$CONFIG" --trace_so "$TRACE_SO" --cycle_table "$CYCLE_TABLE" "$SIMULATOR_PATH" --config "$CONFIG" --trace_so "$TRACE_SO" --cycle_table "$CYCLE_TABLE" --log_level trace --attributes_list "$ATTRIBUTE_PATH/$ATTRIBUTE_NAME" > "$OUTPUT_FILE" & echo "[TOGSim] for $CONFIG stored to \"$(pwd)/$OUTPUT_FILE\"" done wait \ No newline at end of file diff --git a/scripts/trace_timeline.py b/scripts/trace_timeline.py new file mode 100644 index 00000000..5cf9608b --- /dev/null +++ b/scripts/trace_timeline.py @@ -0,0 +1,249 @@ +#!/usr/bin/env python3 +"""Convert a TOGSim `--log_level trace` log into a Chrome Trace Event JSON that +opens in Perfetto (https://ui.perfetto.dev) or chrome://tracing as an interactive +timeline (Gantt). + +Each instruction becomes one duration slice, grouped per core (pid). Lanes: + dram-rd -- loads crossing the DRAM bus (read bandwidth) + dram-wr -- stores crossing the DRAM bus (write bandwidth) + sa / sa0.. -- COMP compute_type 1 (matmul) / 2 (preload) + vector -- COMP compute_type 0 (vector) +Time unit = core cycles. Barriers (MEMORY_BAR/COMPUTE_BAR) are not drawn. A DMA bar +runs from the op's first DRAM response (DRAM_RESP_FIRST, logged by the Core -- so it +captures data moving even while still injecting) to its completion (load: data-ready; +store: finished), serialized per direction so each is one visible bar (packed row = +saturated bus). A compute slice's width is its occupancy (compute_cycle - overlapping). + +Usage: + bin/Simulator --config --trace_so --cycle_table --log_level trace \ + 2>&1 | python scripts/trace_timeline.py -o timeline.json + # or + python scripts/trace_timeline.py trace.log -o timeline.json +Then drag timeline.json into https://ui.perfetto.dev . +""" +import argparse +import json +import re +import sys + +# [cycle][Core C][TAG ][INST_ID=N] OPCODE (detail...) +_LINE = re.compile( + r"\[(\d+)\]\[Core (\d+)\]\[([A-Z_]+)\s*\](?:\[INST_ID=(-?\d+)\])?\s*(\w+)?(.*)") + +# Only 3 lanes per core. Barriers are dropped (see _HIDE). +_LANE = {"MOVIN": "dma", "MOVOUT": "dma"} +_HIDE = {"MEMORY_BAR", "COMPUTE_BAR", "TILE_BEGIN", "TILE_END"} +_CT_NAME = {0: "vector", 1: "matmul", 2: "preload"} + +# Perfetto/catapult reserved color names; slices are tinted by tile (= the +# togsim_dispatch work-item / output tile) so one tile's ops share a color across +# lanes/cores. 16 names so a core's tiles (which stride by num_cores) stay +# distinct -- an 8-name palette collapsed to 4 colors per core under 2-core +# even/odd assignment. +_TILE_PALETTE = ["good", "bad", "terrible", "yellow", "olive", "rail_response", + "rail_load", "rail_animation", "rail_idle", "thread_state_running", + "thread_state_runnable", "thread_state_iowait", + "thread_state_uninterruptible", "generic_work", "startup", + "vsync_highlight_color"] + + +def _tile_color(detail): + m = re.search(r"\btile=(\d+)", detail or "") + return _TILE_PALETTE[int(m.group(1)) % len(_TILE_PALETTE)] if m else None + + +_DMA_SHORT = {"MOVIN": "MVIN", "MOVOUT": "MVOUT"} + + +def _tile_of(detail): + m = re.search(r"\btile=(-?\d+)", detail or "") + return m.group(1) if m else "?" + + +def _label(opcode, detail): + if opcode == "COMP": + m = re.search(r"compute_type=(\d+)", detail) + ct = int(m.group(1)) if m else -1 + return f"T{_tile_of(detail)} {_CT_NAME.get(ct, 'comp')}" + # DMA: keep each load's OWN identity (addr_name) so the input/weight/K-panel + # loads stay distinct; tile is conveyed by color (and args), not the name. + m = re.search(r"addr_name=(\w+)", detail or "") + who = m.group(1) if m else "?" + return f"{who} (T{_tile_of(detail)} {_DMA_SHORT.get(opcode, opcode)})" + + +def _lane(opcode, detail): + if opcode == "COMP": + m = re.search(r"compute_type=(\d+)", detail) + ct = int(m.group(1)) if m else -1 + return "vector" if ct == 0 else "sa" + return _LANE.get(opcode, "dma") + + +def parse(lines): + # key = (core, inst_id) -> record + insts = {} + for ln in lines: + m = _LINE.search(ln) + if not m: + continue + cyc, core, tag, iid, opcode, detail = m.groups() + if iid is None or opcode is None: + continue + cyc, core, iid = int(cyc), int(core), int(iid) + key = (core, iid) + r = insts.setdefault(key, { + "core": core, "iid": iid, "opcode": opcode, "detail": detail, + "issued": None, "finished": None, "resp": None, "dma_issue": None, + "first_resp": None}) + if not r["opcode"] or r["opcode"] == opcode: + r["opcode"] = opcode + if detail.strip(): + r["detail"] = detail + if tag == "INST_ISSUED" and r["issued"] is None: + r["issued"] = cyc + elif tag == "INST_FINISHED": + r["finished"] = cyc + elif tag == "DRAM_RESP_DONE": + r["resp"] = cyc + elif tag == "DRAM_RESP_FIRST" and r["first_resp"] is None: # first data arrived + r["first_resp"] = cyc + elif tag == "ASYNC_DMA_ISSUE": # all requests injected (engine done) + r["dma_issue"] = cyc + return insts + + +def _occ(detail): + """(compute_cycle, overlapping_cycle) from a COMP detail string.""" + cc = re.search(r"compute_cycle=(\d+)", detail) + ov = re.search(r"overlapping_cycle=(\d+)", detail) + return (int(cc.group(1)) if cc else 0, int(ov.group(1)) if ov else 0) + + +def to_chrome(insts, num_sa=1): + """Model each hardware unit as a server and replay its ops in issue order, so + real idle gaps (bubbles) show and slices don't nest: + dma : MOVIN/MOVOUT -- 1 DMA engine; slice = actual transfer + (ASYNC_DMA_ISSUE -> data-ready). + vector : COMP type 0 -- 1 VPU. + sa : COMP type 1/2 -- each op on the SA the Core reports (`sa=` field; + weight-pinned), so lanes auto-split sa0..; rr fallback if absent. + A compute slice's width is compute_cycle - overlapping_cycle (its occupancy = + latency minus the tail that overlaps the next op), starting when the unit + actually picks it up: start = max(issue, unit_free). num_sa>1 -> lanes sa0.. .""" + by_core = {} + for r in insts.values(): + op, detail, core = r["opcode"], r["detail"], r["core"] + if op in _HIDE: + continue + u = by_core.setdefault(core, {"dma": [], "vector": [], "sa": []}) + if op == "COMP": + m = re.search(r"compute_type=(\d+)", detail) + ct = int(m.group(1)) if m else -1 + u["vector" if ct == 0 else "sa"].append(r) + else: + u["dma"].append(r) + + events, lanes, cores = [], set(), set() + + def add(core, lane, ts, dur, name, r): + lanes.add((core, lane)) + cores.add(core) + args = {"inst_id": r["iid"], "tile": _tile_of(r["detail"]), + "issued": r["issued"], "first_data": r["first_resp"], + "finished": r["finished"], "data_ready": r["resp"]} + am = re.search(r"addr_name=(\w+)", r["detail"] or "") + if am: + args["addr"] = am.group(1) + ev = {"name": name, "cat": lane, "ph": "X", "ts": ts, + "dur": max(dur, 1), "pid": core, "tid": lane, "args": args} + cname = _tile_color(r["detail"]) + if cname: + ev["cname"] = cname + events.append(ev) + + def issue_key(r): + return r["issued"] if r["issued"] is not None else 0 + + nsa = max(num_sa, 1) + for core, u in sorted(by_core.items()): + # DMA data crossing the DRAM bus, split by direction (reads and writes are + # asymmetric). A LOAD's data comes back on the response, so its bar runs + # [first DRAM response, data-ready]. A STORE's data goes out with the + # request (fire-and-forget; its acks arrive after it has finished), so its + # bar runs [issued, finished]. Serialized per direction so each op is one + # visible bar: a packed row = the bus is saturated, gaps = it is idle. + for lane, op, sk, ek in (("dram-rd", "MOVIN", "first_resp", "resp"), + ("dram-wr", "MOVOUT", "issued", "finished")): + free = 0 + rows = [r for r in u["dma"] if r["opcode"] == op + and r[sk] is not None and r[ek] is not None and r[ek] > r[sk]] + for r in sorted(rows, key=lambda r: r[ek]): + start = max(r[sk], free) + free = max(r[ek], start + 1) + add(core, lane, start, free - start, _label(r["opcode"], r["detail"]), r) + # VPU: one server; slice = occupancy (compute_cycle - overlapping_cycle). + free = 0 + for r in sorted(u["vector"], key=issue_key): + if r["issued"] is None: + continue + cc, ov = _occ(r["detail"]) + dur = max(cc - ov, 1) + start = max(r["issued"], free) + free = start + dur + add(core, "vector", start, dur, "vector", r) + # SA: each op runs on the systolic array the Core reports (the `sa=` field + # = its weight-pinned / round-robin assignment); fall back to round-robin + # by issue order for older logs without the field. Each SA is one server. + rows = sorted(u["sa"], key=issue_key) + + def _sa_of(r, i): + m = re.search(r"\bsa=(-?\d+)", r["detail"]) + return int(m.group(1)) if (m and int(m.group(1)) >= 0) else (i % nsa) + + max_sa = max([nsa] + [_sa_of(r, i) + 1 for i, r in enumerate(rows)]) + sa_free = [0] * max_sa + for i, r in enumerate(rows): + if r["issued"] is None: + continue + s = _sa_of(r, i) + cc, ov = _occ(r["detail"]) + dur = max(cc - ov, 1) + start = max(r["issued"], sa_free[s]) + sa_free[s] = start + dur + lane = "sa" if max_sa == 1 else f"sa{s}" + add(core, lane, start, dur, _label(r["opcode"], r["detail"]), r) + + for c in sorted(cores): + events.append({"name": "process_name", "ph": "M", "pid": c, "tid": 0, + "args": {"name": f"Core {c}"}}) + order = {"dram-rd": 0, "dram-wr": 1, + "sa": 2, "sa0": 2, "sa1": 3, "sa2": 4, "sa3": 5, "vector": 7} + for c, lane in sorted(lanes, key=lambda x: (x[0], order.get(x[1], 5))): + events.append({"name": "thread_name", "ph": "M", "pid": c, "tid": lane, + "args": {"name": lane}}) + events.append({"name": "thread_sort_index", "ph": "M", "pid": c, "tid": lane, + "args": {"sort_index": order.get(lane, 5)}}) + return {"traceEvents": events, "displayTimeUnit": "ns"} + + +def main(argv): + ap = argparse.ArgumentParser() + ap.add_argument("input", nargs="?", help="trace log file (default: stdin)") + ap.add_argument("-o", "--out", default="timeline.json") + ap.add_argument("-s", "--num-sa", type=int, default=1, + help="systolic arrays per core (num_systolic_array_per_core); " + ">1 splits into sa0..saN-1 lanes") + a = ap.parse_args(argv[1:]) + src = open(a.input) if a.input else sys.stdin + insts = parse(src) + trace = to_chrome(insts, a.num_sa) + with open(a.out, "w") as fh: + json.dump(trace, fh) + n = sum(1 for e in trace["traceEvents"] if e["ph"] == "X") + sys.stderr.write(f"wrote {a.out}: {n} slices -> open in https://ui.perfetto.dev\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/tests/fixtures/gemm256_postvcix.mlir b/tests/fixtures/gemm256_postvcix.mlir new file mode 100644 index 00000000..740e8ab2 --- /dev/null +++ b/tests/fixtures/gemm256_postvcix.mlir @@ -0,0 +1,419 @@ +#map = affine_map<(d0, d1) -> (d0 * 256 + d1)> +#map1 = affine_map<(d0, d1) -> (d0 * 65536 + d1 * 256)> +#map2 = affine_map<(d0, d1) -> (d0 + d1)> +#map3 = affine_map<(d0, d1) -> (d0 * 256 + d1 * 512)> +#map4 = affine_map<(d0, d1, d2) -> (-d0 + d1 + d2 floordiv 2)> +#map5 = affine_map<(d0, d1, d2)[s0, s1] -> (d0 * s0 + d1 * s1 + d2)> +#map6 = affine_map<(d0)[s0] -> (d0 floordiv s0)> +#map7 = affine_map<(d0)[s0] -> (d0 mod s0)> +#map8 = affine_map<(d0, d1, d2) -> (-d0 + d1 * 2 + d2)> +module { + memref.global @X_spad : memref<256x256xf32, 1> + memref.global @W_spad : memref<256x256xf32, 1> + memref.global @Y_spad : memref<256x256xf32, 1> + func.func @kernel(%arg0: memref<65536xf32>, %arg1: memref<65536xf32>, %arg2: memref<65536xf32>) { + %0 = memref.get_global @X_spad : memref<256x256xf32, 1> + %1 = memref.get_global @W_spad : memref<256x256xf32, 1> + %2 = memref.get_global @Y_spad : memref<256x256xf32, 1> + %cst = arith.constant dense<0.000000e+00> : vector<512xf32> + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %c3 = arith.constant 3 : index + %c2 = arith.constant 2 : index + %alloc = memref.alloc() : memref<1xi32> + affine.for %arg3 = 0 to 256 step 256 { + affine.for %arg4 = 0 to 256 step 256 { + affine.vector_store %cst, %2[0, 0] : memref<256x256xf32, 1>, vector<512xf32> + affine.for %arg5 = 0 to 256 step 256 { + %4 = affine.apply #map(%arg3, %arg5) + %c1_1 = arith.constant 1 : index + %alloc_2 = memref.alloc() : memref<1xi32> + %5 = affine.apply #map(%arg5, %arg4) + %c1_3 = arith.constant 1 : index + %alloc_4 = memref.alloc() : memref<1xi32> + %c0_5 = arith.constant 0 : index + %c0_6 = arith.constant 0 : index + %c0_7 = arith.constant 0 : index + %6 = affine.apply #map1(%c0_5, %c0_6) + %7 = affine.apply #map2(%6, %4) + %8 = affine.apply #map3(%c0_5, %c0_6) + %9 = affine.apply #map2(%c0_5, %c0_6) + memref.dma_start %arg0[%7], %0[%c0_7, %8], %c2, %alloc_2[%9], %c1_1, %c1 : memref<65536xf32>, memref<256x256xf32, 1>, memref<1xi32> {async = true, dram_stride = [256, 1], fine_grained = true, sram_stride = [1, 256], subtile_size = [256, 256]} + %c0_8 = arith.constant 0 : index + %c0_9 = arith.constant 0 : index + %c0_10 = arith.constant 0 : index + %10 = affine.apply #map1(%c0_8, %c0_9) + %11 = affine.apply #map2(%10, %5) + %12 = affine.apply #map3(%c0_8, %c0_9) + %13 = affine.apply #map2(%c0_8, %c0_9) + memref.dma_start %arg1[%11], %1[%c0_10, %12], %c2, %alloc_4[%13], %c1_3, %c1 : memref<65536xf32>, memref<256x256xf32, 1>, memref<1xi32> {async = true, dram_stride = [256, 1], fine_grained = true, sram_stride = [1, 256], subtile_size = [256, 256]} + %c0_11 = arith.constant 0 : index + %c8_i64 = arith.constant 8 : i64 + %c256 = arith.constant 256 : index + %c256_12 = arith.constant 256 : index + %c256_13 = arith.constant 256 : index + %c128 = arith.constant 128 : index + %c1_14 = arith.constant 1 : index + %cst_15 = arith.constant 0.000000e+00 : f32 + affine.for %arg6 = 0 to 2 { + affine.for %arg7 = 0 to 2 { + %14 = affine.apply #map4(%arg5, %c0_11, %c0_11) + memref.dma_wait %alloc_4[%14], %c1_14 : memref<1xi32> + %c0_16 = arith.constant 0 : index + %c128_17 = arith.constant 128 : index + %15 = affine.apply #map5(%arg6, %arg7, %c0_16)[%c256, %c128_17] + %16 = affine.apply #map6(%15)[%c256_12] + %17 = affine.apply #map7(%15)[%c256_12] + %18 = vector.transfer_read %1[%16, %17], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%18, %c8_i64) {imm = 0 : i64, opcode = 1 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c8 = arith.constant 8 : index + %c128_18 = arith.constant 128 : index + %19 = affine.apply #map5(%arg6, %arg7, %c8)[%c256, %c128_18] + %20 = affine.apply #map6(%19)[%c256_12] + %21 = affine.apply #map7(%19)[%c256_12] + %22 = vector.transfer_read %1[%20, %21], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%22, %c8_i64) {imm = 0 : i64, opcode = 1 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c16 = arith.constant 16 : index + %c128_19 = arith.constant 128 : index + %23 = affine.apply #map5(%arg6, %arg7, %c16)[%c256, %c128_19] + %24 = affine.apply #map6(%23)[%c256_12] + %25 = affine.apply #map7(%23)[%c256_12] + %26 = vector.transfer_read %1[%24, %25], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%26, %c8_i64) {imm = 0 : i64, opcode = 1 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c24 = arith.constant 24 : index + %c128_20 = arith.constant 128 : index + %27 = affine.apply #map5(%arg6, %arg7, %c24)[%c256, %c128_20] + %28 = affine.apply #map6(%27)[%c256_12] + %29 = affine.apply #map7(%27)[%c256_12] + %30 = vector.transfer_read %1[%28, %29], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%30, %c8_i64) {imm = 0 : i64, opcode = 1 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c32 = arith.constant 32 : index + %c128_21 = arith.constant 128 : index + %31 = affine.apply #map5(%arg6, %arg7, %c32)[%c256, %c128_21] + %32 = affine.apply #map6(%31)[%c256_12] + %33 = affine.apply #map7(%31)[%c256_12] + %34 = vector.transfer_read %1[%32, %33], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%34, %c8_i64) {imm = 0 : i64, opcode = 1 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c40 = arith.constant 40 : index + %c128_22 = arith.constant 128 : index + %35 = affine.apply #map5(%arg6, %arg7, %c40)[%c256, %c128_22] + %36 = affine.apply #map6(%35)[%c256_12] + %37 = affine.apply #map7(%35)[%c256_12] + %38 = vector.transfer_read %1[%36, %37], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%38, %c8_i64) {imm = 0 : i64, opcode = 1 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c48 = arith.constant 48 : index + %c128_23 = arith.constant 128 : index + %39 = affine.apply #map5(%arg6, %arg7, %c48)[%c256, %c128_23] + %40 = affine.apply #map6(%39)[%c256_12] + %41 = affine.apply #map7(%39)[%c256_12] + %42 = vector.transfer_read %1[%40, %41], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%42, %c8_i64) {imm = 0 : i64, opcode = 1 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c56 = arith.constant 56 : index + %c128_24 = arith.constant 128 : index + %43 = affine.apply #map5(%arg6, %arg7, %c56)[%c256, %c128_24] + %44 = affine.apply #map6(%43)[%c256_12] + %45 = affine.apply #map7(%43)[%c256_12] + %46 = vector.transfer_read %1[%44, %45], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%46, %c8_i64) {imm = 0 : i64, opcode = 1 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c64 = arith.constant 64 : index + %c128_25 = arith.constant 128 : index + %47 = affine.apply #map5(%arg6, %arg7, %c64)[%c256, %c128_25] + %48 = affine.apply #map6(%47)[%c256_12] + %49 = affine.apply #map7(%47)[%c256_12] + %50 = vector.transfer_read %1[%48, %49], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%50, %c8_i64) {imm = 0 : i64, opcode = 1 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c72 = arith.constant 72 : index + %c128_26 = arith.constant 128 : index + %51 = affine.apply #map5(%arg6, %arg7, %c72)[%c256, %c128_26] + %52 = affine.apply #map6(%51)[%c256_12] + %53 = affine.apply #map7(%51)[%c256_12] + %54 = vector.transfer_read %1[%52, %53], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%54, %c8_i64) {imm = 0 : i64, opcode = 1 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c80 = arith.constant 80 : index + %c128_27 = arith.constant 128 : index + %55 = affine.apply #map5(%arg6, %arg7, %c80)[%c256, %c128_27] + %56 = affine.apply #map6(%55)[%c256_12] + %57 = affine.apply #map7(%55)[%c256_12] + %58 = vector.transfer_read %1[%56, %57], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%58, %c8_i64) {imm = 0 : i64, opcode = 1 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c88 = arith.constant 88 : index + %c128_28 = arith.constant 128 : index + %59 = affine.apply #map5(%arg6, %arg7, %c88)[%c256, %c128_28] + %60 = affine.apply #map6(%59)[%c256_12] + %61 = affine.apply #map7(%59)[%c256_12] + %62 = vector.transfer_read %1[%60, %61], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%62, %c8_i64) {imm = 0 : i64, opcode = 1 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c96 = arith.constant 96 : index + %c128_29 = arith.constant 128 : index + %63 = affine.apply #map5(%arg6, %arg7, %c96)[%c256, %c128_29] + %64 = affine.apply #map6(%63)[%c256_12] + %65 = affine.apply #map7(%63)[%c256_12] + %66 = vector.transfer_read %1[%64, %65], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%66, %c8_i64) {imm = 0 : i64, opcode = 1 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c104 = arith.constant 104 : index + %c128_30 = arith.constant 128 : index + %67 = affine.apply #map5(%arg6, %arg7, %c104)[%c256, %c128_30] + %68 = affine.apply #map6(%67)[%c256_12] + %69 = affine.apply #map7(%67)[%c256_12] + %70 = vector.transfer_read %1[%68, %69], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%70, %c8_i64) {imm = 0 : i64, opcode = 1 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c112 = arith.constant 112 : index + %c128_31 = arith.constant 128 : index + %71 = affine.apply #map5(%arg6, %arg7, %c112)[%c256, %c128_31] + %72 = affine.apply #map6(%71)[%c256_12] + %73 = affine.apply #map7(%71)[%c256_12] + %74 = vector.transfer_read %1[%72, %73], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%74, %c8_i64) {imm = 0 : i64, opcode = 1 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c120 = arith.constant 120 : index + %c128_32 = arith.constant 128 : index + %75 = affine.apply #map5(%arg6, %arg7, %c120)[%c256, %c128_32] + %76 = affine.apply #map6(%75)[%c256_12] + %77 = affine.apply #map7(%75)[%c256_12] + %78 = vector.transfer_read %1[%76, %77], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%78, %c8_i64) {imm = 0 : i64, opcode = 1 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + affine.for %arg8 = 0 to 2 { + %79 = affine.apply #map8(%arg5, %c0_11, %c0_11) + memref.dma_wait %alloc_2[%79], %c1_14 : memref<1xi32> + %c0_33 = arith.constant 0 : index + %80 = affine.apply #map5(%arg7, %arg8, %c0_33)[%c256_13, %c128] + %81 = affine.apply #map6(%80)[%c256] + %82 = affine.apply #map7(%80)[%c256] + %83 = vector.transfer_read %0[%81, %82], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%83, %c8_i64) {imm = 0 : i64, opcode = 0 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c8_34 = arith.constant 8 : index + %84 = affine.apply #map5(%arg7, %arg8, %c8_34)[%c256_13, %c128] + %85 = affine.apply #map6(%84)[%c256] + %86 = affine.apply #map7(%84)[%c256] + %87 = vector.transfer_read %0[%85, %86], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%87, %c8_i64) {imm = 0 : i64, opcode = 0 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c16_35 = arith.constant 16 : index + %88 = affine.apply #map5(%arg7, %arg8, %c16_35)[%c256_13, %c128] + %89 = affine.apply #map6(%88)[%c256] + %90 = affine.apply #map7(%88)[%c256] + %91 = vector.transfer_read %0[%89, %90], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%91, %c8_i64) {imm = 0 : i64, opcode = 0 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c24_36 = arith.constant 24 : index + %92 = affine.apply #map5(%arg7, %arg8, %c24_36)[%c256_13, %c128] + %93 = affine.apply #map6(%92)[%c256] + %94 = affine.apply #map7(%92)[%c256] + %95 = vector.transfer_read %0[%93, %94], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%95, %c8_i64) {imm = 0 : i64, opcode = 0 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c32_37 = arith.constant 32 : index + %96 = affine.apply #map5(%arg7, %arg8, %c32_37)[%c256_13, %c128] + %97 = affine.apply #map6(%96)[%c256] + %98 = affine.apply #map7(%96)[%c256] + %99 = vector.transfer_read %0[%97, %98], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%99, %c8_i64) {imm = 0 : i64, opcode = 0 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c40_38 = arith.constant 40 : index + %100 = affine.apply #map5(%arg7, %arg8, %c40_38)[%c256_13, %c128] + %101 = affine.apply #map6(%100)[%c256] + %102 = affine.apply #map7(%100)[%c256] + %103 = vector.transfer_read %0[%101, %102], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%103, %c8_i64) {imm = 0 : i64, opcode = 0 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c48_39 = arith.constant 48 : index + %104 = affine.apply #map5(%arg7, %arg8, %c48_39)[%c256_13, %c128] + %105 = affine.apply #map6(%104)[%c256] + %106 = affine.apply #map7(%104)[%c256] + %107 = vector.transfer_read %0[%105, %106], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%107, %c8_i64) {imm = 0 : i64, opcode = 0 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c56_40 = arith.constant 56 : index + %108 = affine.apply #map5(%arg7, %arg8, %c56_40)[%c256_13, %c128] + %109 = affine.apply #map6(%108)[%c256] + %110 = affine.apply #map7(%108)[%c256] + %111 = vector.transfer_read %0[%109, %110], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%111, %c8_i64) {imm = 0 : i64, opcode = 0 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c64_41 = arith.constant 64 : index + %112 = affine.apply #map5(%arg7, %arg8, %c64_41)[%c256_13, %c128] + %113 = affine.apply #map6(%112)[%c256] + %114 = affine.apply #map7(%112)[%c256] + %115 = vector.transfer_read %0[%113, %114], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%115, %c8_i64) {imm = 0 : i64, opcode = 0 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c72_42 = arith.constant 72 : index + %116 = affine.apply #map5(%arg7, %arg8, %c72_42)[%c256_13, %c128] + %117 = affine.apply #map6(%116)[%c256] + %118 = affine.apply #map7(%116)[%c256] + %119 = vector.transfer_read %0[%117, %118], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%119, %c8_i64) {imm = 0 : i64, opcode = 0 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c80_43 = arith.constant 80 : index + %120 = affine.apply #map5(%arg7, %arg8, %c80_43)[%c256_13, %c128] + %121 = affine.apply #map6(%120)[%c256] + %122 = affine.apply #map7(%120)[%c256] + %123 = vector.transfer_read %0[%121, %122], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%123, %c8_i64) {imm = 0 : i64, opcode = 0 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c88_44 = arith.constant 88 : index + %124 = affine.apply #map5(%arg7, %arg8, %c88_44)[%c256_13, %c128] + %125 = affine.apply #map6(%124)[%c256] + %126 = affine.apply #map7(%124)[%c256] + %127 = vector.transfer_read %0[%125, %126], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%127, %c8_i64) {imm = 0 : i64, opcode = 0 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c96_45 = arith.constant 96 : index + %128 = affine.apply #map5(%arg7, %arg8, %c96_45)[%c256_13, %c128] + %129 = affine.apply #map6(%128)[%c256] + %130 = affine.apply #map7(%128)[%c256] + %131 = vector.transfer_read %0[%129, %130], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%131, %c8_i64) {imm = 0 : i64, opcode = 0 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c104_46 = arith.constant 104 : index + %132 = affine.apply #map5(%arg7, %arg8, %c104_46)[%c256_13, %c128] + %133 = affine.apply #map6(%132)[%c256] + %134 = affine.apply #map7(%132)[%c256] + %135 = vector.transfer_read %0[%133, %134], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%135, %c8_i64) {imm = 0 : i64, opcode = 0 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c112_47 = arith.constant 112 : index + %136 = affine.apply #map5(%arg7, %arg8, %c112_47)[%c256_13, %c128] + %137 = affine.apply #map6(%136)[%c256] + %138 = affine.apply #map7(%136)[%c256] + %139 = vector.transfer_read %0[%137, %138], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%139, %c8_i64) {imm = 0 : i64, opcode = 0 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + %c120_48 = arith.constant 120 : index + %140 = affine.apply #map5(%arg7, %arg8, %c120_48)[%c256_13, %c128] + %141 = affine.apply #map6(%140)[%c256] + %142 = affine.apply #map7(%140)[%c256] + %143 = vector.transfer_read %0[%141, %142], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + "vcix.iv"(%143, %c8_i64) {imm = 0 : i64, opcode = 0 : i64, rd = 0 : i64} : (vector<8xf32>, i64) -> () + "vcix.i"(%c8_i64) {imm = 4 : i64, lmul = 0 : i64, opcode = 1 : i64, rd = 0 : i64, rs2 = 0 : i64, sew = 32 : i64} : (i64) -> () + %c0_49 = arith.constant 0 : index + %144 = affine.apply #map5(%arg6, %arg8, %c0_49)[%c256_13, %c128] + %145 = "vcix.v.i"(%c8_i64) {imm = 0 : i64, opcode = 2 : i64, rs2 = 0 : i64} : (i64) -> vector<8xf32> + %146 = affine.apply #map6(%144)[%c256_12] + %147 = affine.apply #map7(%144)[%c256_12] + %148 = vector.transfer_read %2[%146, %147], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + %149 = arith.addf %148, %145 : vector<8xf32> + vector.transfer_write %149, %2[%146, %147] : vector<8xf32>, memref<256x256xf32, 1> + %c8_50 = arith.constant 8 : index + %150 = affine.apply #map5(%arg6, %arg8, %c8_50)[%c256_13, %c128] + %151 = "vcix.v.i"(%c8_i64) {imm = 0 : i64, opcode = 2 : i64, rs2 = 0 : i64} : (i64) -> vector<8xf32> + %152 = affine.apply #map6(%150)[%c256_12] + %153 = affine.apply #map7(%150)[%c256_12] + %154 = vector.transfer_read %2[%152, %153], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + %155 = arith.addf %154, %151 : vector<8xf32> + vector.transfer_write %155, %2[%152, %153] : vector<8xf32>, memref<256x256xf32, 1> + %c16_51 = arith.constant 16 : index + %156 = affine.apply #map5(%arg6, %arg8, %c16_51)[%c256_13, %c128] + %157 = "vcix.v.i"(%c8_i64) {imm = 0 : i64, opcode = 2 : i64, rs2 = 0 : i64} : (i64) -> vector<8xf32> + %158 = affine.apply #map6(%156)[%c256_12] + %159 = affine.apply #map7(%156)[%c256_12] + %160 = vector.transfer_read %2[%158, %159], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + %161 = arith.addf %160, %157 : vector<8xf32> + vector.transfer_write %161, %2[%158, %159] : vector<8xf32>, memref<256x256xf32, 1> + %c24_52 = arith.constant 24 : index + %162 = affine.apply #map5(%arg6, %arg8, %c24_52)[%c256_13, %c128] + %163 = "vcix.v.i"(%c8_i64) {imm = 0 : i64, opcode = 2 : i64, rs2 = 0 : i64} : (i64) -> vector<8xf32> + %164 = affine.apply #map6(%162)[%c256_12] + %165 = affine.apply #map7(%162)[%c256_12] + %166 = vector.transfer_read %2[%164, %165], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + %167 = arith.addf %166, %163 : vector<8xf32> + vector.transfer_write %167, %2[%164, %165] : vector<8xf32>, memref<256x256xf32, 1> + %c32_53 = arith.constant 32 : index + %168 = affine.apply #map5(%arg6, %arg8, %c32_53)[%c256_13, %c128] + %169 = "vcix.v.i"(%c8_i64) {imm = 0 : i64, opcode = 2 : i64, rs2 = 0 : i64} : (i64) -> vector<8xf32> + %170 = affine.apply #map6(%168)[%c256_12] + %171 = affine.apply #map7(%168)[%c256_12] + %172 = vector.transfer_read %2[%170, %171], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + %173 = arith.addf %172, %169 : vector<8xf32> + vector.transfer_write %173, %2[%170, %171] : vector<8xf32>, memref<256x256xf32, 1> + %c40_54 = arith.constant 40 : index + %174 = affine.apply #map5(%arg6, %arg8, %c40_54)[%c256_13, %c128] + %175 = "vcix.v.i"(%c8_i64) {imm = 0 : i64, opcode = 2 : i64, rs2 = 0 : i64} : (i64) -> vector<8xf32> + %176 = affine.apply #map6(%174)[%c256_12] + %177 = affine.apply #map7(%174)[%c256_12] + %178 = vector.transfer_read %2[%176, %177], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + %179 = arith.addf %178, %175 : vector<8xf32> + vector.transfer_write %179, %2[%176, %177] : vector<8xf32>, memref<256x256xf32, 1> + %c48_55 = arith.constant 48 : index + %180 = affine.apply #map5(%arg6, %arg8, %c48_55)[%c256_13, %c128] + %181 = "vcix.v.i"(%c8_i64) {imm = 0 : i64, opcode = 2 : i64, rs2 = 0 : i64} : (i64) -> vector<8xf32> + %182 = affine.apply #map6(%180)[%c256_12] + %183 = affine.apply #map7(%180)[%c256_12] + %184 = vector.transfer_read %2[%182, %183], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + %185 = arith.addf %184, %181 : vector<8xf32> + vector.transfer_write %185, %2[%182, %183] : vector<8xf32>, memref<256x256xf32, 1> + %c56_56 = arith.constant 56 : index + %186 = affine.apply #map5(%arg6, %arg8, %c56_56)[%c256_13, %c128] + %187 = "vcix.v.i"(%c8_i64) {imm = 0 : i64, opcode = 2 : i64, rs2 = 0 : i64} : (i64) -> vector<8xf32> + %188 = affine.apply #map6(%186)[%c256_12] + %189 = affine.apply #map7(%186)[%c256_12] + %190 = vector.transfer_read %2[%188, %189], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + %191 = arith.addf %190, %187 : vector<8xf32> + vector.transfer_write %191, %2[%188, %189] : vector<8xf32>, memref<256x256xf32, 1> + %c64_57 = arith.constant 64 : index + %192 = affine.apply #map5(%arg6, %arg8, %c64_57)[%c256_13, %c128] + %193 = "vcix.v.i"(%c8_i64) {imm = 0 : i64, opcode = 2 : i64, rs2 = 0 : i64} : (i64) -> vector<8xf32> + %194 = affine.apply #map6(%192)[%c256_12] + %195 = affine.apply #map7(%192)[%c256_12] + %196 = vector.transfer_read %2[%194, %195], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + %197 = arith.addf %196, %193 : vector<8xf32> + vector.transfer_write %197, %2[%194, %195] : vector<8xf32>, memref<256x256xf32, 1> + %c72_58 = arith.constant 72 : index + %198 = affine.apply #map5(%arg6, %arg8, %c72_58)[%c256_13, %c128] + %199 = "vcix.v.i"(%c8_i64) {imm = 0 : i64, opcode = 2 : i64, rs2 = 0 : i64} : (i64) -> vector<8xf32> + %200 = affine.apply #map6(%198)[%c256_12] + %201 = affine.apply #map7(%198)[%c256_12] + %202 = vector.transfer_read %2[%200, %201], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + %203 = arith.addf %202, %199 : vector<8xf32> + vector.transfer_write %203, %2[%200, %201] : vector<8xf32>, memref<256x256xf32, 1> + %c80_59 = arith.constant 80 : index + %204 = affine.apply #map5(%arg6, %arg8, %c80_59)[%c256_13, %c128] + %205 = "vcix.v.i"(%c8_i64) {imm = 0 : i64, opcode = 2 : i64, rs2 = 0 : i64} : (i64) -> vector<8xf32> + %206 = affine.apply #map6(%204)[%c256_12] + %207 = affine.apply #map7(%204)[%c256_12] + %208 = vector.transfer_read %2[%206, %207], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + %209 = arith.addf %208, %205 : vector<8xf32> + vector.transfer_write %209, %2[%206, %207] : vector<8xf32>, memref<256x256xf32, 1> + %c88_60 = arith.constant 88 : index + %210 = affine.apply #map5(%arg6, %arg8, %c88_60)[%c256_13, %c128] + %211 = "vcix.v.i"(%c8_i64) {imm = 0 : i64, opcode = 2 : i64, rs2 = 0 : i64} : (i64) -> vector<8xf32> + %212 = affine.apply #map6(%210)[%c256_12] + %213 = affine.apply #map7(%210)[%c256_12] + %214 = vector.transfer_read %2[%212, %213], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + %215 = arith.addf %214, %211 : vector<8xf32> + vector.transfer_write %215, %2[%212, %213] : vector<8xf32>, memref<256x256xf32, 1> + %c96_61 = arith.constant 96 : index + %216 = affine.apply #map5(%arg6, %arg8, %c96_61)[%c256_13, %c128] + %217 = "vcix.v.i"(%c8_i64) {imm = 0 : i64, opcode = 2 : i64, rs2 = 0 : i64} : (i64) -> vector<8xf32> + %218 = affine.apply #map6(%216)[%c256_12] + %219 = affine.apply #map7(%216)[%c256_12] + %220 = vector.transfer_read %2[%218, %219], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + %221 = arith.addf %220, %217 : vector<8xf32> + vector.transfer_write %221, %2[%218, %219] : vector<8xf32>, memref<256x256xf32, 1> + %c104_62 = arith.constant 104 : index + %222 = affine.apply #map5(%arg6, %arg8, %c104_62)[%c256_13, %c128] + %223 = "vcix.v.i"(%c8_i64) {imm = 0 : i64, opcode = 2 : i64, rs2 = 0 : i64} : (i64) -> vector<8xf32> + %224 = affine.apply #map6(%222)[%c256_12] + %225 = affine.apply #map7(%222)[%c256_12] + %226 = vector.transfer_read %2[%224, %225], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + %227 = arith.addf %226, %223 : vector<8xf32> + vector.transfer_write %227, %2[%224, %225] : vector<8xf32>, memref<256x256xf32, 1> + %c112_63 = arith.constant 112 : index + %228 = affine.apply #map5(%arg6, %arg8, %c112_63)[%c256_13, %c128] + %229 = "vcix.v.i"(%c8_i64) {imm = 0 : i64, opcode = 2 : i64, rs2 = 0 : i64} : (i64) -> vector<8xf32> + %230 = affine.apply #map6(%228)[%c256_12] + %231 = affine.apply #map7(%228)[%c256_12] + %232 = vector.transfer_read %2[%230, %231], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + %233 = arith.addf %232, %229 : vector<8xf32> + vector.transfer_write %233, %2[%230, %231] : vector<8xf32>, memref<256x256xf32, 1> + %c120_64 = arith.constant 120 : index + %234 = affine.apply #map5(%arg6, %arg8, %c120_64)[%c256_13, %c128] + %235 = "vcix.v.i"(%c8_i64) {imm = 0 : i64, opcode = 2 : i64, rs2 = 0 : i64} : (i64) -> vector<8xf32> + %236 = affine.apply #map6(%234)[%c256_12] + %237 = affine.apply #map7(%234)[%c256_12] + %238 = vector.transfer_read %2[%236, %237], %cst_15 : memref<256x256xf32, 1>, vector<8xf32> + %239 = arith.addf %238, %235 : vector<8xf32> + vector.transfer_write %239, %2[%236, %237] : vector<8xf32>, memref<256x256xf32, 1> + } {inner_loop = true} + } {inner_loop = true} + } {inner_loop = true} + } {accumulation_loop = true, subtile_loop = "k"} + affine.for %arg5 = 0 to 1 { + } {inner_loop = false} + %3 = affine.apply #map(%arg3, %arg4) + %c1_0 = arith.constant 1 : index + memref.dma_start %2[%c0, %c0], %arg2[%3], %c3, %alloc[%c0], %c1_0, %c1 : memref<256x256xf32, 1>, memref<65536xf32>, memref<1xi32> {dram_stride = [256, 1], padding = 0 : i64, sram_stride = [1, 256]} + } {outer_loop = true, subtile_loop = "n"} + } {outer_loop = true, subtile_loop = "m"} + return + } + func.func @wrapper_kernel(%arg0: memref<65536xf32>, %arg1: memref<65536xf32>, %arg2: memref<65536xf32>) { + call @kernel(%arg0, %arg1, %arg2) : (memref<65536xf32>, memref<65536xf32>, memref<65536xf32>) -> () + return + } +} diff --git a/tests/lowering/__init__.py b/tests/lowering/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/lowering/test_lower_transfer_to_gemmini.py b/tests/lowering/test_lower_transfer_to_gemmini.py new file mode 100644 index 00000000..6b7bf1d5 --- /dev/null +++ b/tests/lowering/test_lower_transfer_to_gemmini.py @@ -0,0 +1,141 @@ +"""Unit tests for the lower_transfer_to_gemmini pass (no torch, no Spike). + +Hand-write a `togsim.transfer`, run the pass in-process, and assert the lowered IR +matches an embedded golden -- the exact expected output (MLIR SSA numbering is +deterministic for a fixed input). If a lowering change is intended, regenerate the +golden and review the diff. Skipped without the MLIR bindings. +""" +import importlib.util +import textwrap + +import pytest + +_MLIR = importlib.util.find_spec("mlir") is not None +pytestmark = pytest.mark.skipif(not _MLIR, reason="MLIR Python bindings not installed") + + +def _lower_transfer(ir_text, timing=False): + from mlir.ir import Context, Module, Location + from PyTorchSimFrontend.mlir.passes import lower_transfer_to_gemmini as L + ctx = Context() + ctx.allow_unregistered_dialects = True + with ctx, Location.unknown(): + m = Module.parse(ir_text) + L.run(m, timing=timing) + return str(m).strip() + + +# INPUT: one masked MVOUT (store an SRAM tile back to DRAM) of a [1,2,8,8] tile. +# The togsim.transfer operands are positional (see emit_transfer): +# %arg1 DRAM base buffer %c0 dram_idx (element offset into it) +# %s SRAM tile (the [1,2,8,8] spad global) %c0 sram_idx +# %alloc async tag buffer %c0 tag_idx +# %c3 dma_type (3 = MVOUT) %c1 vlane_stride +# %c0, %c7 the masked clamp (low, high) -- ONE (low, high) pair per masked axis. +# Attrs: dram_stride/tile_stride = row-major [1,2,8,8] strides; vlane_split_axis=3; +# masked_axes=[2] clamps tile axis 2 to [low, high) = [0, 7); masked_fill=0. So on +# store, axis-2 positions >= 7 (the ragged tail) are skipped instead of written. +# masked_axes is a SPARSE overlay, NOT one pair per rank: the descriptor always carries +# all 4 axes' dim_low/dim_high, defaulting to [0, dim_size) (= no clamp). Only axes that +# are actually ragged are listed (the frontend skips axes that divide the tile evenly), +# so a single-axis clamp on a 4D tile is the normal case, not a rank mismatch. +_MASKED_MVOUT = """ +module { + memref.global @buf1_spad : memref<1x2x8x8xf32, 1> + func.func @k(%arg1: memref<2048xf32>) { + %c0 = arith.constant 0 : index + %c7 = arith.constant 7 : index + %alloc = memref.alloc() : memref<1xi32> + %s = memref.get_global @buf1_spad : memref<1x2x8x8xf32, 1> + %c3 = arith.constant 3 : index + %c1 = arith.constant 1 : index + "togsim.transfer"(%arg1, %c0, %s, %c0, %alloc, %c0, %c3, %c1, %c0, %c7) {dma_kind="MVOUT", dram_stride=[128,64,8,1], tile_stride=[128,64,8,1], vlane_split_axis=3:i64, masked_axes=[2], masked_fill=0:i64} : (memref<2048xf32>, index, memref<1x2x8x8xf32,1>, index, memref<1xi32>, index, index, index, index, index) -> () + return + } +}""" + +# OUTPUT (golden): the transfer lowers to a DMA descriptor + two RISC-V custom insns. +# @dma_desc_0 is the descriptor as 36 i32 (= 18 packed i64 slots); the dense init reads: +# words[0:4] = [1,2,8,8] dim_size (the tile / config shape) +# words[4:8] = [0,0,0,0] dim_low (default; runtime-overwritten below) +# words[8:12] = [1,2,8,8] dim_high (defaults to dim_size; runtime-overwritten) +# words[12:20] = dram_stride 128,64,8,1 words[20:28] = tile_stride 128,64,8,1 (i64 pairs) +# words[28:30] = 65540,131843 = the packed flags slot: elem_bytes 4 | vlane_stride 1 | +# vlane_split_axis 3 | config_type 3 (MVOUT) | flags 2 (masked) +# words[30:36] = 0 (masked_fill / indirect, unused here) +# Then the masked clamp is written at RUN TIME into the descriptor: low=%c0 -> i32 idx 6 +# (dim_low base 4 + axis 2), high=%c7 -> i32 idx 10 (dim_high base 8 + axis 2). The rest +# is address arithmetic building the DRAM byte addr (%3) and SRAM byte addr (%12), then two +# `.insn r CUSTOM_1` ops: func7=7 = CONFIG_DESC (hands the descriptor pointer to the DMA +# engine), func7=3 = MVOUT (hands it the DRAM + SRAM addresses -> issues the store). +_MASKED_MVOUT_LOWERED = textwrap.dedent("""\ + module { + memref.global "private" @dma_desc_0 : memref<36xi32> = dense<[1, 2, 8, 8, 0, 0, 0, 0, 1, 2, 8, 8, 128, 0, 64, 0, 8, 0, 1, 0, 128, 0, 64, 0, 8, 0, 1, 0, 65540, 131843, 0, 0, 0, 0, 0, 0]> + memref.global @buf1_spad : memref<1x2x8x8xf32, 1> + func.func @k(%arg0: memref<2048xf32>) { + %c0 = arith.constant 0 : index + %c7 = arith.constant 7 : index + %alloc = memref.alloc() : memref<1xi32> + %0 = memref.get_global @buf1_spad : memref<1x2x8x8xf32, 1> + %c3 = arith.constant 3 : index + %c1 = arith.constant 1 : index + %c0_0 = arith.constant 0 : index + %intptr = memref.extract_aligned_pointer_as_index %arg0 : memref<2048xf32> -> index + %c4 = arith.constant 4 : index + %1 = arith.muli %c0, %c4 : index + %2 = arith.addi %intptr, %1 : index + %3 = arith.index_cast %2 : index to i64 + %intptr_1 = memref.extract_aligned_pointer_as_index %0 : memref<1x2x8x8xf32, 1> -> index + %c128 = arith.constant 128 : index + %4 = arith.muli %c0_0, %c128 : index + %c64 = arith.constant 64 : index + %5 = arith.muli %c0_0, %c64 : index + %6 = arith.addi %4, %5 : index + %c8 = arith.constant 8 : index + %7 = arith.muli %c0_0, %c8 : index + %8 = arith.addi %6, %7 : index + %9 = arith.addi %8, %c0 : index + %c4_2 = arith.constant 4 : index + %10 = arith.muli %9, %c4_2 : index + %11 = arith.addi %intptr_1, %10 : index + %12 = arith.index_cast %11 : index to i64 + %13 = memref.get_global @dma_desc_0 : memref<36xi32> + %14 = arith.index_cast %c0 : index to i32 + %c6 = arith.constant 6 : index + memref.store %14, %13[%c6] : memref<36xi32> + %15 = arith.index_cast %c7 : index to i32 + %c10 = arith.constant 10 : index + memref.store %15, %13[%c10] : memref<36xi32> + %intptr_3 = memref.extract_aligned_pointer_as_index %13 : memref<36xi32> -> index + %16 = arith.index_cast %intptr_3 : index to i64 + %c0_i64 = arith.constant 0 : i64 + llvm.inline_asm has_side_effects asm_dialect = att ".insn r CUSTOM_1, 0x3, 7, x0, $0, $1", "r,r,~{dirflag},~{fpsr},~{flags}" %16, %c0_i64 : (i64, i64) -> () + llvm.inline_asm has_side_effects asm_dialect = att ".insn r CUSTOM_1, 0x3, 3, x0, $0, $1", "r,r,~{dirflag},~{fpsr},~{flags}" %3, %12 : (i64, i64) -> () + return + } + }""") + + +def test_masked_transfer_lowering_golden(): + assert _lower_transfer(_MASKED_MVOUT) == _MASKED_MVOUT_LOWERED + + +# Same transfer with subtile_size=[1,1,4,8] (the H axis is subtiled 8 -> 4). The +# descriptor's dim_size is the SUBTILE (config) shape, not the full tile; the masked +# axis + clamp stores are unchanged (a 4D subtile -> expand 0 -> same idx 6/10). +_MASKED_MVOUT_SUBTILE = _MASKED_MVOUT.replace( + 'vlane_split_axis=3:i64,', 'vlane_split_axis=3:i64, subtile_size=[1,1,4,8],') + +_MASKED_MVOUT_SUBTILE_LOWERED = _MASKED_MVOUT_LOWERED.replace( + "dense<[1, 2, 8, 8, 0, 0, 0, 0, 1, 2, 8, 8,", + "dense<[1, 1, 4, 8, 0, 0, 0, 0, 1, 1, 4, 8,") + + +def test_masked_transfer_subtile_lowering_golden(): + assert _lower_transfer(_MASKED_MVOUT_SUBTILE) == _MASKED_MVOUT_SUBTILE_LOWERED + + +def test_timing_mode_erases_transfer(): + # In timing mode the TOG carries DMA timing -> the transfer + descriptor are erased. + out = _lower_transfer(_MASKED_MVOUT, timing=True) + assert "togsim.transfer" not in out and "dma_desc" not in out diff --git a/tests/lowering/test_masked_fill.py b/tests/lowering/test_masked_fill.py new file mode 100644 index 00000000..f2abf4af --- /dev/null +++ b/tests/lowering/test_masked_fill.py @@ -0,0 +1,30 @@ +"""Unit test for the masked-DMA fill's exp-reduction detection. + +A log-sum-exp reduction (softmax / log_softmax) fills its masked tail with -inf so that +exp(-inf) = 0; a plain sum fills with the sum identity 0. `MLIRKernel._origin_is_exp` +decides which, and it must match the op TARGET, not a name substring -- otherwise `expand` +/ `expm1` (whose names contain "exp") would wrongly trigger the -inf fill on an ordinary +non-dividing sum, corrupting it to -inf. Skipped if torch / the frontend is unavailable. +""" +import importlib.util + +import pytest + +pytestmark = pytest.mark.skipif( + importlib.util.find_spec("torch") is None, reason="torch not available") + + +def test_origin_is_exp_matches_target_not_name_substring(): + import torch + from types import SimpleNamespace as NS + from PyTorchSimFrontend.mlir.mlir_codegen_backend import MLIRKernel + is_exp = MLIRKernel._origin_is_exp + + # the genuine exp op -> True + assert is_exp(NS(target=torch.ops.aten.exp.default, name="exp")) is True + # names contain "exp" but are NOT exp -> must be False (the substring bug this guards) + assert is_exp(NS(target=torch.ops.aten.expand.default, name="expand")) is False + assert is_exp(NS(target=torch.ops.aten.expm1.default, name="expm1")) is False + # unrelated op / a non-call origin (placeholder target is a str) -> False + assert is_exp(NS(target=torch.ops.aten.log.default, name="log")) is False + assert is_exp(NS(target="primals_1", name="primals_1")) is False diff --git a/tests/models/test_clip.py b/tests/models/test_clip.py new file mode 100644 index 00000000..35566aa1 --- /dev/null +++ b/tests/models/test_clip.py @@ -0,0 +1,71 @@ +import argparse +import os +import sys + +import torch +from transformers import CLIPVisionConfig, CLIPVisionModel + +sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim"), "tests")) +from _pytorchsim_utils import test_result + + +def _init_weights(m): + if isinstance(m, torch.nn.Linear): + torch.nn.init.normal_(m.weight, mean=0.0, std=0.02) + if m.bias is not None: + torch.nn.init.zeros_(m.bias) + elif isinstance(m, torch.nn.Conv2d): + torch.nn.init.normal_(m.weight, mean=0.0, std=0.02) + if m.bias is not None: + torch.nn.init.zeros_(m.bias) + elif isinstance(m, torch.nn.LayerNorm): + if m.weight is not None: + torch.nn.init.ones_(m.weight) + if m.bias is not None: + torch.nn.init.zeros_(m.bias) + + +def test_clip(device, batch=2, image_size=224, patch_size=32, num_layers=2): + """CLIP vision backbone with batch > 1. The patch-embedding conv (kernel = stride = + patch_size) routes to the multi-tile conv mapping, whose full-kernel tile overflows + SPAD at batch > 1 -- that used to raise "Cannot find a valid mapping" (GitHub issue + #252).""" + torch.manual_seed(0) + cfg = CLIPVisionConfig( + hidden_size=768, + intermediate_size=3072, + num_hidden_layers=num_layers, + num_attention_heads=12, + image_size=image_size, + patch_size=patch_size, + ) + with torch.no_grad(): + model = CLIPVisionModel(cfg).eval() + model.apply(_init_weights) + + x = torch.randn(batch, 3, image_size, image_size) + out_cpu = model(pixel_values=x.cpu()).last_hidden_state + + model.to(device) + 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) + print("Max diff >", torch.max(torch.abs(out_device.cpu() - out_cpu))) + print("CLIP Simulation Done") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Run CLIP vision test") + parser.add_argument("--batch", type=int, default=2) + parser.add_argument("--image_size", type=int, default=224) + parser.add_argument("--patch_size", type=int, default=32) + parser.add_argument("--num_layers", type=int, default=2) + args = parser.parse_args() + test_clip( + torch.device("npu:0"), + batch=args.batch, + image_size=args.image_size, + patch_size=args.patch_size, + num_layers=args.num_layers, + ) diff --git a/tests/models/test_convnextv2.py b/tests/models/test_convnextv2.py new file mode 100644 index 00000000..bfde58f4 --- /dev/null +++ b/tests/models/test_convnextv2.py @@ -0,0 +1,67 @@ +import argparse +import os +import sys + +import torch +from transformers import ConvNextV2Config, ConvNextV2Model + +sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim"), "tests")) +from _pytorchsim_utils import test_result + + +def _init_weights(m): + if isinstance(m, torch.nn.Linear): + torch.nn.init.normal_(m.weight, mean=0.0, std=0.02) + if m.bias is not None: + torch.nn.init.zeros_(m.bias) + elif isinstance(m, torch.nn.Conv2d): + torch.nn.init.normal_(m.weight, mean=0.0, std=0.02) + if m.bias is not None: + torch.nn.init.zeros_(m.bias) + elif isinstance(m, torch.nn.LayerNorm): + if m.weight is not None: + torch.nn.init.ones_(m.weight) + if m.bias is not None: + torch.nn.init.zeros_(m.bias) + + +def test_convnextv2(device, batch=2, image_size=64, patch_size=4): + """ConvNeXt V2 with batch > 1. Two things used to break here (GitHub issue #255): + the channels-first LayerNorm reduces the contiguous axis, which the GEMM template's + 2-D reduction-epilogue frame cannot express, and the depthwise 7x7 conv lowers to + gather kernels whose index-expression scratch buffer exhausted the SPAD budget.""" + torch.manual_seed(0) + cfg = ConvNextV2Config( + depths=[1, 1, 1, 1], + hidden_sizes=[96, 192, 384, 768], + image_size=image_size, + patch_size=patch_size, + ) + with torch.no_grad(): + model = ConvNextV2Model(cfg).eval() + model.apply(_init_weights) + + x = torch.randn(batch, 3, image_size, image_size) + out_cpu = model(pixel_values=x.cpu()).last_hidden_state + + model.to(device) + 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) + print("Max diff >", torch.max(torch.abs(out_device.cpu() - out_cpu))) + print("ConvNeXt V2 Simulation Done") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Run ConvNeXt V2 test") + parser.add_argument("--batch", type=int, default=2) + parser.add_argument("--image_size", type=int, default=64) + parser.add_argument("--patch_size", type=int, default=4) + args = parser.parse_args() + test_convnextv2( + torch.device("npu:0"), + batch=args.batch, + image_size=args.image_size, + patch_size=args.patch_size, + ) diff --git a/tests/models/test_swinv2.py b/tests/models/test_swinv2.py new file mode 100644 index 00000000..3caf06da --- /dev/null +++ b/tests/models/test_swinv2.py @@ -0,0 +1,69 @@ +import argparse +import os +import sys + +import torch +from transformers import Swinv2Config, Swinv2Model + +sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim"), "tests")) +from _pytorchsim_utils import test_result + + +def _init_weights(m): + if isinstance(m, torch.nn.Linear): + torch.nn.init.normal_(m.weight, mean=0.0, std=0.02) + if m.bias is not None: + torch.nn.init.zeros_(m.bias) + elif isinstance(m, torch.nn.Conv2d): + torch.nn.init.normal_(m.weight, mean=0.0, std=0.02) + if m.bias is not None: + torch.nn.init.zeros_(m.bias) + elif isinstance(m, torch.nn.LayerNorm): + if m.weight is not None: + torch.nn.init.ones_(m.weight) + if m.bias is not None: + torch.nn.init.zeros_(m.bias) + + +def test_swinv2(device, batch=2, image_size=64, window_size=8): + """SwinV2 backbone with batch > 1 exercises the SHIFTED-window attention (torch.roll + composed with window partition/reverse) -- the path that used to fail codegen with + "Unlinearized floor/mod in DMA index" (GitHub issue #251).""" + torch.manual_seed(0) + cfg = Swinv2Config( + image_size=image_size, + patch_size=4, + embed_dim=96, + depths=[2], # 2 blocks -> block 1 is the shifted-window block + num_heads=[3], + window_size=window_size, + ) + with torch.no_grad(): + model = Swinv2Model(cfg).eval() + model.apply(_init_weights) + + x = torch.randn(batch, 3, image_size, image_size) + x_device = x.to(device=device) + model.to(device) + opt_model = torch.compile(dynamic=False)(model) + out_device = opt_model(pixel_values=x_device).last_hidden_state + + out_cpu = model.cpu()(pixel_values=x.cpu()).last_hidden_state + + test_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") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Run SwinV2 shifted-window test") + parser.add_argument("--batch", type=int, default=2) + parser.add_argument("--image_size", type=int, default=64) + parser.add_argument("--window_size", type=int, default=8) + args = parser.parse_args() + test_swinv2( + torch.device("npu:0"), + batch=args.batch, + image_size=args.image_size, + window_size=args.window_size, + ) diff --git a/tests/ops/conv/test_conv2d.py b/tests/ops/conv/test_conv2d.py index 820e990f..d4cfeff1 100644 --- a/tests/ops/conv/test_conv2d.py +++ b/tests/ops/conv/test_conv2d.py @@ -39,4 +39,7 @@ def custom_conv2d(a, b, bias): test_conv2d(device, batch_size=1, in_channels=128, out_channels=256, input_size=2, kernel_size=1, stride=1, padding=0) test_conv2d(device, batch_size=1, in_channels=128, out_channels=256, input_size=14, kernel_size=1, stride=2, padding=0) test_conv2d(device, batch_size=1, in_channels=3, out_channels=768, input_size=224, kernel_size=16,stride=16, padding=0) + # batch>1 patch conv (large kernel/out-channels): the multi-tile mapping's + # full-kernel tile overflows SPAD while smaller-k_h tiles still fit (issue #252) + test_conv2d(device, batch_size=2, in_channels=3, out_channels=768, input_size=64, kernel_size=32, stride=32, padding=0) test_conv2d(device, batch_size=1, in_channels=8, out_channels=16, input_size=1, kernel_size=1,stride=1, padding=0) diff --git a/tests/ops/elementwise/test_pointwise.py b/tests/ops/elementwise/test_pointwise.py new file mode 100644 index 00000000..74e6656d --- /dev/null +++ b/tests/ops/elementwise/test_pointwise.py @@ -0,0 +1,214 @@ +import torch +import os + +def clear_caches(): + from torch._functorch._aot_autograd.autograd_cache import AOTAutogradCache + from torch._inductor.codecache import FxGraphCache + AOTAutogradCache.clear() + torch._dynamo.reset() + os.environ["TORCHINDUCTOR_CACHE"] = "0" + FxGraphCache.clear() + +def test_result(name, out, cpu_out, rtol=1e-4, atol=1e-4): + if torch.allclose(out.cpu(), cpu_out, rtol=rtol, atol=atol): + message = f"|{name} Test Passed|" + print("-" * len(message)) + print(message) + print("-" * len(message)) + else: + message = f"|{name} Test Failed|" + print("-" * len(message)) + print(message) + print("-" * len(message)) + print("custom out: ", out.cpu()) + print("cpu out: ", cpu_out) + exit(1) + +def run_test(name, device, fn, inputs, size_desc, rtol=1e-4, atol=1e-4): + """ + Harness function to compile, execute on NPU, compare with CPU, and print details. + inputs: single tensor or tuple/list of tensors (on CPU) + """ + if not isinstance(inputs, (tuple, list)): + inputs = [inputs] + + npu_inputs = [x.to(device=device) for x in inputs] + cpu_inputs = [x.clone() for x in inputs] + + clear_caches() + + opt_fn = torch.compile(dynamic=False)(fn) + res = opt_fn(*npu_inputs) + out = fn(*cpu_inputs) + + # Print input / output slices (up to 10 elements) + for idx, x in enumerate(inputs): + label = f"X" if len(inputs) == 1 else f"X{idx+1}" + val = x.flatten()[:10].tolist() if x.numel() > 1 else x.item() + print(f"[{size_desc}] {name} Input {label}: {val}") + + out_val = res.flatten()[:10].tolist() if res.numel() > 1 else res.item() + print(f"[{size_desc}] {name} Output: {out_val}") + + test_result(f"{name}_{size_desc}", res, out, rtol=rtol, atol=atol) + + +# aligned, scalar, small tail, large tail +STD_SIZES = [(128, 128), (1, 1), (15, 15), (129, 129)] + + +def run_op(name, device, fn, make_input, cases=None, sizes=STD_SIZES, rtol=1e-4, atol=1e-4): + torch.manual_seed(0) + for rows, cols in sizes: + run_test(name, device, fn, make_input(rows, cols), f"{rows}x{cols}", rtol=rtol, atol=atol) + for desc, inputs in (cases or []): + run_test(name, device, fn, inputs, desc, rtol=rtol, atol=atol) + + +def test_abs(device): + run_op("Abs", device, torch.abs, lambda r, c: torch.randn(r, c) * 10, + cases=[ + ("int", torch.randint(-100, 100, (128, 128), dtype=torch.int32)), + ("strided_transposed", (torch.randn(128, 128) * 10).t()), + ("strided_sliced", (torch.randn(128, 256) * 10)[:, ::2]), + ]) + +def test_sign(device): + def make(r, c): + x = torch.randn(r, c) + x[x.abs() < 0.3] = 0.0 + return x + run_op("Sign", device, torch.sign, make, + cases=[ + ("zero", torch.tensor([[0.0]])), + ("nonzero", torch.tensor([[-4.5]])), + ("int", torch.randint(-5, 5, (128, 128), dtype=torch.int32)), + ]) + +def test_isnan(device): + def make(r, c): + x = torch.randn(r, c) + x[x.abs() < 0.3] = float('nan') + return x + run_op("IsNaN", device, torch.isnan, make, + cases=[("scalar_nan", torch.tensor([[float('nan')]]))]) + +def test_isinf(device): + def make(r, c): + x = torch.randn(r, c) + x[x > 1.0] = float('inf') + x[x < -1.0] = float('-inf') + return x + run_op("IsInf", device, torch.isinf, make, + cases=[("scalar_inf", torch.tensor([[float('-inf')]]))]) + +def test_fmod(device): + run_op("Fmod", device, torch.fmod, + lambda r, c: (torch.randn(r, c) * 10, torch.randn(r, c) * 3 + 1), + cases=[("broadcast", (torch.randn(128, 1) * 10, torch.randn(1, 128) * 3 + 1))]) + +def test_lshift(device): + run_op("LShift", device, torch.bitwise_left_shift, + lambda r, c: (torch.randint(1, 100, (r, c), dtype=torch.int32), + torch.randint(1, 5, (r, c), dtype=torch.int32)), + cases=[("broadcast", (torch.randint(1, 100, (128, 1), dtype=torch.int32), + torch.randint(1, 5, (1, 128), dtype=torch.int32)))]) + +def test_rshift(device): + run_op("RShift", device, torch.bitwise_right_shift, + lambda r, c: (torch.randint(10, 1000, (r, c), dtype=torch.int32), + torch.randint(1, 5, (r, c), dtype=torch.int32)), + cases=[("broadcast", (torch.randint(10, 1000, (128, 1), dtype=torch.int32), + torch.randint(1, 5, (1, 128), dtype=torch.int32)))]) + +def test_copysign(device): + run_op("Copysign", device, torch.copysign, + lambda r, c: (torch.randn(r, c) * 10, torch.randn(r, c)), + cases=[ + ("negzero", (torch.tensor([[3.0]]), torch.tensor([[-0.0]]))), + ("broadcast", (torch.randn(128, 1) * 10, torch.randn(1, 128))), + ]) + +def test_erfc(device): + run_op("Erfc", device, torch.erfc, lambda r, c: torch.randn(r, c), + cases=[("large", torch.tensor([[4.5]]))]) + +def test_hypot(device): + run_op("Hypot", device, torch.hypot, + lambda r, c: (torch.randn(r, c), torch.randn(r, c)), + cases=[ + ("3-4-5", (torch.tensor([[3.0]]), torch.tensor([[4.0]]))), + ("broadcast", (torch.randn(128, 1), torch.randn(1, 128))), + ]) + +def test_cosh(device): + run_op("Cosh", device, torch.cosh, lambda r, c: torch.randn(r, c), + cases=[("large", torch.tensor([[4.5]]))]) + +def test_sinh(device): + run_op("Sinh", device, torch.sinh, lambda r, c: torch.randn(r, c), + cases=[("large", torch.tensor([[4.5]]))]) + +def test_log(device): + # domain: x > 0 + run_op("Log", device, torch.log, lambda r, c: torch.rand(r, c) + 1e-5, + cases=[("e", torch.tensor([[2.71828]]))]) + +def test_acosh(device): + # domain: x >= 1 + run_op("Acosh", device, torch.acosh, lambda r, c: torch.rand(r, c) + 1, + cases=[("one", torch.tensor([[1.0]]))]) + +def test_asinh(device): + run_op("Asinh", device, torch.asinh, lambda r, c: torch.randn(r, c)) + +def test_atanh(device): + # domain: (-1, 1) + run_op("Atanh", device, torch.atanh, lambda r, c: torch.rand(r, c) * 2 - 1) + +def test_atan(device): + # domain: all reals; boundary: zero, unit, large |x| (range-reduction path) + run_op("Atan", device, torch.atan, lambda r, c: torch.randn(r, c) * 5, + cases=[("boundary", torch.tensor([[0.0, 1.0, -1.0, 1e3, -1e3, 1e-4]]))]) + +def test_asin(device): + # domain: [-1, 1]; boundary includes the +/-1 endpoints + run_op("Asin", device, torch.asin, lambda r, c: torch.rand(r, c) * 2 - 1, + cases=[("boundary", torch.tensor([[0.0, 1.0, -1.0, 0.5, -0.5]]))]) + +def test_acos(device): + # domain: [-1, 1]; boundary includes the +/-1 endpoints + run_op("Acos", device, torch.acos, lambda r, c: torch.rand(r, c) * 2 - 1, + cases=[("boundary", torch.tensor([[0.0, 1.0, -1.0, 0.5, -0.5]]))]) + +def test_atan2(device): + # atan2(y, x); boundary: axes and diagonals across all four quadrants + # (0, 0) excluded: composition yields atan(0/0)=nan while torch returns 0 + y = torch.tensor([[1.0, 0.0, -1.0, 0.0, 1.0, -1.0, 1.0, -1.0]]) + x = torch.tensor([[0.0, 1.0, 0.0, -1.0, 1.0, -1.0, -1.0, 1.0]]) + run_op("Atan2", device, torch.atan2, lambda r, c: (torch.randn(r, c), torch.randn(r, c)), + cases=[("boundary", (y, x))]) + +if __name__ == "__main__": + device = torch.device("npu:0") + + test_abs(device) + test_sign(device) + test_isnan(device) + test_isinf(device) + test_fmod(device) + test_lshift(device) + test_rshift(device) + test_copysign(device) + test_erfc(device) + test_hypot(device) + test_cosh(device) + test_sinh(device) + test_log(device) + test_acosh(device) + test_asinh(device) + test_atanh(device) + test_atan(device) + test_asin(device) + test_acos(device) + test_atan2(device) \ No newline at end of file diff --git a/tests/ops/fusion/test_matmul_reduction.py b/tests/ops/fusion/test_matmul_reduction.py index d5dde2af..6be02fb8 100644 --- a/tests/ops/fusion/test_matmul_reduction.py +++ b/tests/ops/fusion/test_matmul_reduction.py @@ -25,6 +25,21 @@ def matmul_fused(a, b): test_result("Matmul Reduction Fusion activation", res[0], y[0]) test_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 + 2-D reduction-epilogue frame, so the reduction has to run as its own kernel. Fusing it + anyway silently produces wrong values, so this only checks the numbers.""" + def matmul_fused(a, b): + result = torch.matmul(a, b) + return result - result.mean(dim=-1, keepdim=True) + torch.manual_seed(0) + input = torch.randn(M, K) + weight = torch.randn(K, N) + 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"), weight.to("cpu")) + test_result("Matmul reduce over contiguous axis", res, y) + def test_matmul_var_mean(device, size=512): def matmul_fused(a, b, c): result = torch.matmul(a, b.T) @@ -76,5 +91,6 @@ def matmul_fused(a, b, c, d): if __name__ == "__main__": device = torch.device("npu:0") test_matmul_reduce(device, 3072, 512, 768) + test_matmul_reduce_last_dim(device) test_matmul_var_mean(device) test_matmul_add_var_mean(device) diff --git a/tests/ops/misc/test_indirect_access.py b/tests/ops/misc/test_indirect_access.py index f64fe50d..cf57ef66 100644 --- a/tests/ops/misc/test_indirect_access.py +++ b/tests/ops/misc/test_indirect_access.py @@ -52,6 +52,31 @@ def scatter_only(out, token_indices, weighted_output): res = opt_fn(out, token_indices, weighted_output) test_result("ScatterAdd(index_add_)", res, cpu_out) +def test_multidim_indirect(device, size=(64, 64), n=256): + torch.manual_seed(0) + def gather2d(x, ix, iy): + return x[ix, iy] + 1.0 + x = torch.randn(size, dtype=torch.float32).to(device=device) + ix = torch.randint(0, size[0], [n]).to(device=device) + iy = torch.randint(0, size[1], [n]).to(device=device) + 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) + +def test_multidim_indirect_index_reuse(device, size=(64, 64), n=256): + torch.manual_seed(0) + def gather_reuse(x, ix, iy): + # ix is reused after the gather -> the offset spad must not clobber the index spad + return x[ix, iy] + ix.float() + x = torch.randn(size, dtype=torch.float32).to(device=device) + ix = torch.randint(0, size[0], [n]).to(device=device) + iy = torch.randint(0, size[1], [n]).to(device=device) + 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) + def test_scatter_full(device, size=(128, 128)): def vectoradd(a, idx, b): a[idx, :] = b @@ -71,4 +96,6 @@ def vectoradd(a, idx, b): test_scatter_full(device, size=(2048, 2048)) test_scatter_add(device) test_indirect_vectoradd(device) - #test_embedding(device, 1024, 2048) \ No newline at end of file + test_multidim_indirect(device) + test_multidim_indirect_index_reuse(device) + #test_embedding(device, 1024, 2048) diff --git a/tests/ops/misc/test_masked_nondividing.py b/tests/ops/misc/test_masked_nondividing.py new file mode 100644 index 00000000..20d12c8a --- /dev/null +++ b/tests/ops/misc/test_masked_nondividing.py @@ -0,0 +1,77 @@ +"""Masked-DMA non-dividing regression tests. + +Dropping the tile-divisibility constraint (is_dim_dividable / must_divide_dim and the +_index_expr / convert_indirect_indexing RecompileSignal) means a non-dividing shape no +longer falls back to a dividing tile -- correctness now rests entirely on the masked-DMA +[low, high) clamp + reduction-identity fill. These cases pin that path: what used to be a +(slow but safe) recompile is now a silent wrong answer if the clamp regresses. +""" +import os +import sys + +import torch +import torch.nn.functional as F + +sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim"), "tests")) +from _pytorchsim_utils import test_result + + +def test_pad_2d(device, size=(5, 10), pad=(2, 3, 1, 1)): + # 2-D constant pad on a non-dividing shape -> exercises the per-dim greedy pad recovery + # in _masked_bounds (both padded axes must be attributed to the right tile dim). + 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())) + + +def test_sum_over_broadcast(device, size=(5, 13)): + # sum over a non-dividing dim with a broadcast operand -- the tail fill must be the sum + # identity 0, NOT -inf (regression guard for the exp-origin substring bug: an origin + # name containing "exp" like expand/expm1 must not trigger the log-sum-exp -inf fill). + def fn(a, b): + return (a * b).sum(dim=1) + 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())) + + +def test_softmax_nondividing(device, size=(4, 10)): + # genuine log-sum-exp reduction: the exp path must still fill -inf and stay correct. + 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())) + + +def test_elementwise_nondividing(device, size=(7, 13)): + def fn(a, b): + return torch.relu(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())) + + +def test_gather_nondividing(device, rows=13, cols=10, n=17): + # indirect (gather) on a non-dividing shape -- the divisibility RecompileSignal is gone. + def fn(x, idx): + return 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())) + + +if __name__ == "__main__": + device = torch.device("npu:0") + test_pad_2d(device, (5, 10), (2, 3, 1, 1)) + test_pad_2d(device, (7, 13), (1, 1, 3, 2)) + test_pad_2d(device, (1, 3, 10, 10), (2, 1, 1, 2)) + test_sum_over_broadcast(device, (5, 13)) + test_softmax_nondividing(device, (4, 10)) + test_elementwise_nondividing(device, (7, 13)) + test_gather_nondividing(device) diff --git a/tests/ops/reduce/test_reduce.py b/tests/ops/reduce/test_reduce.py index d80e17b9..c829261b 100644 --- a/tests/ops/reduce/test_reduce.py +++ b/tests/ops/reduce/test_reduce.py @@ -25,6 +25,24 @@ def reduce_sum(a, dim, keepdim): out = reduce_sum(x.cpu(), dim, keepdim) test_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 + attention: score[w,h,q,k] + table[idx[q,k], h] -> amax over the key axis. The gather + blocks the head*query dim-merge, so the reduction tile stays 4-D. The reduction axis + must be hoisted to the outermost in-lane position; the 4-D reduction tile path used to + skip that reorder and reduce a batch axis (head) instead of the key axis, so head 0's + max picked up head 1's values (needs H>=2 and NW>=2 to expose the head bleed).""" + def fn(score, idx, table): + bias = table[idx.reshape(-1)].reshape(Q, K, H).permute(2, 0, 1).unsqueeze(0) + return (score + bias).amax(dim=-1) + torch.manual_seed(0) + score = torch.randn(NW, H, Q, K).to(device=device) + idx = torch.randint(0, T, (Q, K)).to(device=device) + 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) + if __name__ == "__main__": import argparse @@ -38,4 +56,5 @@ def reduce_sum(a, dim, keepdim): test_reduce_sum(device, (17, 68), 0, keepdim=True) test_reduce_sum(device, (327, 447), 1, keepdim=True) test_reduce_sum(device, (327, 447), 0, keepdim=True) - test_reduce_sum2(device, shape) \ No newline at end of file + test_reduce_sum2(device, shape) + test_reduce_gather_bias(device) \ No newline at end of file diff --git a/tests/test_togsim_emitc.py b/tests/test_togsim_emitc.py new file mode 100644 index 00000000..b0bd2d8e --- /dev/null +++ b/tests/test_togsim_emitc.py @@ -0,0 +1,152 @@ +"""Tests for the C4 emitc lowering + compiled .so trace producer (P2). + +The pipeline under test (docs/design/togsim_cpp_trace.md, sec 5-7): + + post-vcix .mlir --build_skeleton--> skeleton+API + --lower_to_emitc--> EmitC module + --mlir-translate--> C++ + --g++ -shared----> trace .so (exports togsim_kernel; + togsim_* left undefined) + +`test_build_trace_so` builds the .so and checks the EmitC/symbol-table shape. +`test_trace_so_runs` additionally dlopens it against a stub runtime and confirms +the producer executes and emits a non-empty deterministic trace. + +Both are skipped unless the MLIR bindings, `mlir-translate` (from +TORCHSIM_LLVM_PATH), a host C++ compiler, AND a post-vcix `.mlir` fixture (via +`TOGSIM_SKELETON_FIXTURE`) are available -- the same fixture used by +test_togsim_skeleton.py. +""" +import importlib.util +import os +import pathlib +import shutil +import subprocess +import sys +import tempfile + +import pytest + +_ROOT = pathlib.Path(__file__).resolve().parents[1] +_CXX = os.environ.get("CXX", "g++") +_INCLUDE = _ROOT / "TOGSim" / "include" + + +def _mlir_translate(): + return os.path.join(os.environ.get("TORCHSIM_LLVM_PATH", "/usr/bin"), + "mlir-translate") + + +def _tools_ready(): + return (importlib.util.find_spec("mlir") is not None + and os.path.isfile(_mlir_translate()) + and shutil.which(_CXX) is not None) + + +def _fixture(): + fix = os.environ.get("TOGSIM_SKELETON_FIXTURE") + if not fix or not os.path.isfile(fix): + pytest.skip("set TOGSIM_SKELETON_FIXTURE to a post-vcix kernel .mlir") + return fix + + +_HARNESS = r''' +#include +#include +#include +#include +#include "togsim_runtime.h" +static int n_dma=0, n_membar=0, n_compute=0, n_core=0, bad=0; +extern "C" { +void togsim_dma(EmitCtx*, int32_t, int32_t, uint64_t, int32_t, + const int64_t*, const int64_t*, int32_t, int32_t, + int32_t, uint64_t, const int64_t*, int32_t, + const int64_t*, int32_t){ ++n_dma; } +void togsim_compute(EmitCtx*, uint64_t, int32_t, int32_t, const int64_t*, + const int64_t*, int32_t, const int64_t*, int32_t){ ++n_compute; } +void togsim_memory_barrier(EmitCtx*, int32_t tag_id, uint64_t, const int64_t*, int32_t){ + ++n_membar; if(tag_id<0) ++bad; } // tag_id pairs it with its async dma +void togsim_dispatch(EmitCtx* ctx, togsim_tile_fn fn, int64_t* iv, int32_t n){ + ++n_core; fn(ctx, iv, n); } // count a work-item + run its (outlined) body +void togsim_compute_barrier(EmitCtx*){} +} +int main(int argc, char** argv){ + void* h = dlopen(argv[1], RTLD_NOW | RTLD_GLOBAL); + if(!h){ printf("dlopen failed: %s\n", dlerror()); return 2; } + auto emit = (void(*)(EmitCtx*, int64_t*, int32_t))dlsym(h, "togsim_kernel"); + if(!emit){ printf("dlsym failed: %s\n", dlerror()); return 3; } + emit(nullptr, nullptr, 0); + printf("TRACE core=%d dma=%d membar=%d compute=%d bad=%d\n", + n_core, n_dma, n_membar, n_compute, bad); + return 0; +} +''' + + +@pytest.mark.skipif(not _tools_ready(), + reason="need mlir bindings + mlir-translate + C++ compiler") +def test_build_trace_so(): + fix = _fixture() + sys.path.insert(0, str(_ROOT)) + from PyTorchSimFrontend.mlir.passes import lower_to_emitc as c4 + + with tempfile.TemporaryDirectory() as d: + so = os.path.join(d, "trace.so") + emitc_text = c4.build_trace_so(fix, so) + assert os.path.isfile(so) + + # EmitC form: one entry func, dma/memory_barrier/compute as call_opaque targets. + assert "emitc.func" in emitc_text + assert ("@%s" % c4.ENTRY) in emitc_text + assert 'emitc.call_opaque "togsim_dma"' in emitc_text + assert 'emitc.call_opaque "togsim_memory_barrier"' in emitc_text + assert 'emitc.call_opaque "togsim_compute"' in emitc_text + + # Symbol table: entry exported (defined, text), runtime hooks undefined + # so the TOGSim loader resolves them at dlopen. + nm = subprocess.run(["nm", "-D", so], capture_output=True, text=True).stdout + syms = {parts[-1]: parts[-2] for parts in + (ln.split() for ln in nm.splitlines()) if len(parts) >= 2} + assert syms.get("togsim_kernel") == "T", nm + assert syms.get("togsim_dma") == "U", nm + assert syms.get("togsim_dispatch") == "U", nm + assert syms.get("togsim_memory_barrier") == "U", nm + # The per-work-item dispatch wrapper is emitted (outlined tile fn). + assert 'emitc.call_opaque "togsim_dispatch"' in emitc_text + + +@pytest.mark.skipif(not _tools_ready(), + reason="need mlir bindings + mlir-translate + C++ compiler") +def test_trace_so_runs(): + fix = _fixture() + sys.path.insert(0, str(_ROOT)) + from PyTorchSimFrontend.mlir.passes import lower_to_emitc as c4 + + with tempfile.TemporaryDirectory() as d: + so = os.path.join(d, "trace.so") + c4.build_trace_so(fix, so) + + harness_cpp = os.path.join(d, "harness.cpp") + harness_bin = os.path.join(d, "harness") + with open(harness_cpp, "w") as fh: + fh.write(_HARNESS) + # -rdynamic so the harness's togsim_* are visible to the dlopened .so. + build = subprocess.run( + [_CXX, "-std=gnu++17", "-O2", "-rdynamic", "-I", str(_INCLUDE), + harness_cpp, "-o", harness_bin, "-ldl"], + capture_output=True, text=True) + assert build.returncode == 0, build.stderr + + run = subprocess.run([harness_bin, so], capture_output=True, text=True) + assert run.returncode == 0, run.stdout + run.stderr + out = run.stdout.strip() + assert out.startswith("TRACE "), out + counts = dict(kv.split("=") for kv in out.split()[1:]) + # The producer ran and emitted a real trace, with >=1 work-item (core alloc). + assert int(counts["core"]) >= 1 + assert int(counts["dma"]) >= 1 + assert int(counts["compute"]) >= 1 + # Async loads are synced by explicit memory barriers, each carrying a + # valid (non-negative) tag_id that pairs it with its dma. + assert int(counts["membar"]) >= 1, out + assert int(counts["bad"]) == 0, out diff --git a/tests/test_togsim_runtime.py b/tests/test_togsim_runtime.py new file mode 100644 index 00000000..a5d6cb3d --- /dev/null +++ b/tests/test_togsim_runtime.py @@ -0,0 +1,189 @@ +"""P3 task 5: the TOGSim C6 runtime + loader (togsim_runtime.cc / togsim_loader.h). + +Builds a producer `.so` from a post-vcix fixture, links the real C6 runtime, runs +the loader (`run_producer`) against the `.so`, and checks the recorded trace: +DRAM addresses are resolved (base[arg_id] + offset*elem_bytes), compute cycles +are looked up from the cycle table, and every wait gets a handle a dma minted. + +Uses a checked-in post-vcix `.mlir` fixture (tests/fixtures/), so it is +self-contained; skipped only when the MLIR bindings, `mlir-translate`, or a C++ +compiler are missing. +""" +import importlib.util +import os +import pathlib +import shutil +import subprocess +import sys +import tempfile + +import pytest + +_ROOT = pathlib.Path(__file__).resolve().parents[1] +_CXX = os.environ.get("CXX", "g++") +_INCLUDE = _ROOT / "TOGSim" / "include" +_RUNTIME = _ROOT / "TOGSim" / "src" / "togsim_runtime.cc" + + +def _mlir_translate(): + return os.path.join(os.environ.get("TORCHSIM_LLVM_PATH", "/usr/bin"), + "mlir-translate") + + +def _tools_ready(): + return (importlib.util.find_spec("mlir") is not None + and os.path.isfile(_mlir_translate()) + and shutil.which(_CXX) is not None + and _RUNTIME.is_file()) + + +# Checked-in post-vcix kernel: a 256^3 single-output-tile GEMM (X/W/Y_spad +# 256x256), matching the trace assertions below. Self-contained so the test +# runs wherever the tools are present -- no setup/env needed. +_FIXTURE = pathlib.Path(__file__).resolve().parent / "fixtures" / "gemm256_postvcix.mlir" + + +def _fixture(): + if not _FIXTURE.is_file(): + pytest.skip(f"missing checked-in fixture {_FIXTURE}") + return str(_FIXTURE) + + +# Drives the loader with known tensor bases + a synthetic cycle table, then +# checks the recorded trace. Tailored to a single-output-tile GEMM (256^3): +# 3 dmas A/B/C at offset 0 -> addr == base; args 0/1/2; dirs load/load/store. +_MAIN = r''' +#include +#include +#include +#include +#include "togsim_loader.h" +using namespace togsim; +int main(int argc, char** argv) { + uint64_t bases[3] = {0x1000, 0x2000, 0x3000}; + int64_t cyc[3] = {100, 200, 300}; + int64_t ovl[3] = {0, 200, 172}; + int32_t pcores[1] = {0}; // round-robin work-items over core 0 (single-core harness) + RunResult r = run_producer(argv[1], nullptr, 0, bases, 3, cyc, ovl, 3, pcores, 1); + if (!r.ok) { printf("run failed\n"); return 2; } + int ndisp=0, nd=0, nc=0, nm=0, fail=0; + std::vector dma_a; std::vector dma_arg, dma_dir; + std::vector> async_tags; // (tag_id, tag_slot) of async dmas + for (auto& t : r.trace) { + if (t.kind == TraceRec::TILE_BEGIN) ndisp++; // one per work-item + else if (t.kind == TraceRec::DMA) { + nd++; dma_a.push_back(t.addr); + dma_arg.push_back(t.arg_id); dma_dir.push_back(t.dir); + if (t.is_async) async_tags.push_back({t.tag_id, t.tag_slot}); + } else if (t.kind == TraceRec::COMPUTE) { + nc++; + int64_t want = (t.tile_id < 3) ? cyc[t.tile_id] : -1; + if (t.cycle != want) { printf("compute %lu cyc %ld!=%ld\n", + (unsigned long)t.tile_id, (long)t.cycle, (long)want); fail++; } + } else if (t.kind == TraceRec::MEMORY_BAR) { + nm++; bool ok=false; + for (auto& k : async_tags) if (k.first==t.tag_id && k.second==t.tag_slot) ok=true; + if (!ok) { printf("membar tag (%d,%lu) pairs no async dma\n", + t.tag_id, (unsigned long)t.tag_slot); fail++; } + } + } + const uint64_t exp[3] = {0x1000, 0x2000, 0x3000}; + const int ea[3] = {0,1,2}, ed[3] = {0,0,1}; + for (int i = 0; i < nd && i < 3; ++i) + if (dma_a[i]!=exp[i] || dma_arg[i]!=ea[i] || dma_dir[i]!=ed[i]) { + printf("dma[%d] addr=%#lx arg=%d dir=%d\n", i, + (unsigned long)dma_a[i], dma_arg[i], dma_dir[i]); fail++; + } + printf("dispatch=%d dma=%d compute=%d membar=%d fail=%d\n", ndisp, nd, nc, nm, fail); + printf(fail ? "RESULT FAIL\n" : "RESULT PASS\n"); + return fail ? 1 : 0; +} +''' + + +@pytest.mark.skipif(not _tools_ready(), + reason="need mlir bindings + mlir-translate + C++ compiler + runtime") +def test_runtime_loads_and_records(): + fix = _fixture() + sys.path.insert(0, str(_ROOT)) + from PyTorchSimFrontend.mlir.passes import lower_to_emitc as c4 + + with tempfile.TemporaryDirectory() as d: + so = os.path.join(d, "trace.so") + c4.build_trace_so(fix, so) + + main_cpp = os.path.join(d, "main.cpp") + binp = os.path.join(d, "runtime_test") + with open(main_cpp, "w") as fh: + fh.write(_MAIN) + build = subprocess.run( + [_CXX, "-std=gnu++17", "-O2", "-rdynamic", "-I", str(_INCLUDE), + main_cpp, str(_RUNTIME), "-o", binp, "-ldl"], + capture_output=True, text=True) + assert build.returncode == 0, build.stderr + + run = subprocess.run([binp, so], capture_output=True, text=True) + out = run.stdout + assert "RESULT PASS" in out, out + run.stderr + assert run.returncode == 0, out + # at least the GEMM's 3 dmas were recorded with resolved addresses. + line = [l for l in out.splitlines() if l.startswith("dispatch=")][0] + counts = dict(kv.split("=") for kv in line.split()) + assert int(counts["dma"]) >= 1 + assert int(counts["compute"]) >= 1 + assert int(counts["fail"]) == 0 + + +_SIM_MAIN = r''' +#include +#include +#include "togsim_loader.h" +using namespace togsim; +int main(int argc, char** argv) { + uint64_t bases[3] = {0x1000, 0x2000, 0x3000}; + int64_t cyc[3] = {100, 200, 300}; + int64_t ovl[3] = {0, 200, 172}; + int32_t pcores[1] = {0}; // round-robin work-items over core 0 (single-core harness) + RunResult r = run_producer(argv[1], nullptr, 0, bases, 3, cyc, ovl, 3, pcores, 1); + if (!r.ok) { printf("run failed\n"); return 2; } + TimingParams p; p.dma_latency = 100; + SimResult s = simulate(r, p); + // serial baseline: no overlap at all. + uint64_t serial = 0; + for (auto& t : r.trace) { + if (t.kind == TraceRec::DMA) serial += p.dma_latency; + else if (t.kind == TraceRec::COMPUTE) serial += (uint64_t)t.cycle; + } + printf("SIM total=%lu compute=%d dma=%d serial=%lu\n", + (unsigned long)s.total_cycle, s.n_compute, s.n_dma, (unsigned long)serial); + // The trace is schedulable into cycles; overlap (dma||compute, compute + // pipelining) makes it no worse than the fully-serial baseline. + bool ok = s.total_cycle > 0 && s.n_compute > 0 && s.total_cycle <= serial; + printf(ok ? "RESULT PASS\n" : "RESULT FAIL\n"); + return ok ? 0 : 1; +} +''' + + +@pytest.mark.skipif(not _tools_ready(), + reason="need mlir bindings + mlir-translate + C++ compiler + runtime") +def test_simulate_produces_cycles(): + fix = _fixture() + sys.path.insert(0, str(_ROOT)) + from PyTorchSimFrontend.mlir.passes import lower_to_emitc as c4 + + with tempfile.TemporaryDirectory() as d: + so = os.path.join(d, "trace.so") + c4.build_trace_so(fix, so) + main_cpp = os.path.join(d, "sim.cpp") + binp = os.path.join(d, "sim_test") + with open(main_cpp, "w") as fh: + fh.write(_SIM_MAIN) + build = subprocess.run( + [_CXX, "-std=gnu++17", "-O2", "-rdynamic", "-I", str(_INCLUDE), + main_cpp, str(_RUNTIME), "-o", binp, "-ldl"], + capture_output=True, text=True) + assert build.returncode == 0, build.stderr + run = subprocess.run([binp, so], capture_output=True, text=True) + assert "RESULT PASS" in run.stdout, run.stdout + run.stderr + assert run.returncode == 0, run.stdout diff --git a/tests/test_togsim_skeleton.py b/tests/test_togsim_skeleton.py new file mode 100644 index 00000000..56601966 --- /dev/null +++ b/tests/test_togsim_skeleton.py @@ -0,0 +1,184 @@ +"""Tests for the C++ trace-generation front-end pieces (docs/design/togsim_cpp_trace.md). + +Two layers: + +* `test_togsim_ops_contract` runs anywhere (no MLIR bindings, no torch). It pins + the skeleton+API vocabulary (`togsim_ops.py`) and checks it stays in lockstep + with the runtime ABI header (`togsim_runtime.h`) -- the single thing most + likely to silently drift. +* `test_build_skeleton_on_fixture` exercises the real `build_skeleton` pass, and + is skipped unless the MLIR bindings are importable AND a post-vcix `.mlir` + fixture is supplied via the `TOGSIM_SKELETON_FIXTURE` env var. (A valid + build_tog-compatible fixture is hard to hand-write reliably; point this at a + kernel dump from a real run.) +""" +import os +import importlib.util +import pathlib + +import pytest + +_ROOT = pathlib.Path(__file__).resolve().parents[1] +_OPS_PY = _ROOT / "PyTorchSimFrontend" / "mlir" / "passes" / "togsim_ops.py" +_HEADER = _ROOT / "TOGSim" / "include" / "togsim_runtime.h" + + +def _load_togsim_ops(): + spec = importlib.util.spec_from_file_location("togsim_ops", _OPS_PY) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def test_togsim_ops_contract(): + ts = _load_togsim_ops() + header = _HEADER.read_text() + + # Every op maps to a callee, and every callee is the header's free function. + assert set(ts.EMITC_CALLEE) == set(ts.OP_NAMES) + for callee in ts.EMITC_CALLEE.values(): + assert callee in header, f"{callee} missing from togsim_runtime.h" + + # Entry point symbol agrees with the header. + assert ts.ENTRY_SYMBOL == "togsim_kernel" + assert ts.ENTRY_SYMBOL in header + + # Runtime callee emitted directly by lower_to_emitc: the work-item dispatch + # wrapper. (The outlined tile fn TILE_SYMBOL is producer-generated.) + assert ts.DISPATCH_CALLEE in header + + # Direction enum agrees with the header's togsim_dma_dir. + assert (ts.DIR_LOAD, ts.DIR_STORE) == (0, 1) + assert "TOGSIM_DMA_LOAD = 0" in header + assert "TOGSIM_DMA_STORE = 1" in header + + +def _mlir_available(): + return importlib.util.find_spec("mlir") is not None + + +@pytest.mark.skipif(not _mlir_available(), reason="MLIR Python bindings not installed") +def test_build_skeleton_on_fixture(): + fixture = os.environ.get("TOGSIM_SKELETON_FIXTURE") + if not fixture or not os.path.isfile(fixture): + pytest.skip("set TOGSIM_SKELETON_FIXTURE to a post-vcix kernel .mlir") + + import sys + sys.path.insert(0, str(_ROOT)) + from PyTorchSimFrontend.mlir.passes import build_skeleton + + import mlir.ir as ir + ctx = ir.Context() + ctx.allow_unregistered_dialects = True + with ctx: + module = ir.Module.parse(pathlib.Path(fixture).read_text(), ctx) + report = build_skeleton.build_skeleton(module) + out = str(module) + + # The data-movement ops are gone; the API ops took their place. + assert "memref.dma_start" not in out + assert "memref.dma_wait" not in out + assert "togsim.dma" in out + assert "togsim.memory_barrier" in out # the explicit async-DMA sync (was dma_wait) + assert "event_id" not in out # static pairing replaced by the runtime tag + # Loop skeleton is preserved. + assert ("affine.for" in out) or ("scf.for" in out) + assert module.operation.verify() + print(report) + + +@pytest.mark.skipif(not _mlir_available(), reason="MLIR Python bindings not installed") +def test_strip_accum_terms_drops_reduction_marker(): + """Regression: the dma_wait tag index built by lower_to_vcix carries a `-d_i` + term for each accumulation (reduction) loop var -- a sentinel marker, not an + offset. build_skeleton must drop those so a memory_barrier waits on the same + subtile slot the async load wrote; otherwise the producer evaluates `-acc_iv` + to a negative slot at reduction iteration > 0, the recorded barrier slot + diverges from the load slot, and TOGSim aborts with "Key does not exist in ... + tag table" on subtile + multi-tile-K. See docs/design/togsim_cpp_trace.md and + legacy TileGraphParser.cc (which skips stride -1 for the same reason).""" + import sys + sys.path.insert(0, str(_ROOT)) + from PyTorchSimFrontend.mlir.passes import build_skeleton as bs + + import mlir.ir as ir + ctx = ir.Context() + ctx.allow_unregistered_dialects = True + with ctx, ir.Location.unknown(ctx): + module = ir.Module.parse( + "func.func @k() {\n" + " %r = arith.constant 1 : index\n" # stand-in reduction iv + " %a = arith.constant 0 : index\n" # subtile dim 1 + " %b = arith.constant 0 : index\n" # subtile dim 2 + " return\n" + "}", ctx) + block = module.body.operations[0].regions[0].blocks[0] + consts = [op.results[0] for op in block.operations if op.name == "arith.constant"] + anchor = [op for op in block.operations if op.name == "func.return"][0] + r, a, b = consts + + def neg_dims(val): + amap = ir.AffineMapAttr(val.owner.attributes["map"]).value + return [p for p in (bs._neg_coeff_dim(s) for s in bs._flatten_add(amap.results[0])) + if p is not None] + + # #map8-style: -d0 (reduction) + d1 + d2 floordiv 2. + d0, d1, d2 = (ir.AffineDimExpr.get(i) for i in range(3)) + expr = d0 * -1 + d1 + ir.AffineExpr.get_floor_div(d2, 2) + with ir.InsertionPoint(anchor): + apply = ir.Operation.create( + "affine.apply", results=[ir.IndexType.get()], operands=[r, a, b], + attributes={"map": ir.AffineMapAttr.get(ir.AffineMap.get(3, 0, [expr]))}) + tag_in = apply.results[0] + assert neg_dims(tag_in) == [0] # the reduction marker is present + + tag_out = bs._strip_accum_terms(ctx, tag_in, anchor) + assert tag_out is not tag_in # a new, reduced apply was emitted + out_map = ir.AffineMapAttr(tag_out.owner.attributes["map"]).value + assert out_map.n_dims == 2 # the reduction dim was dropped + assert neg_dims(tag_out) == [] # no reduction marker remains + assert list(tag_out.owner.operands) == [a, b] # only the subtile operands survive + + # No-op: an index with no reduction marker is returned unchanged. + plain = d0 + d1 + with ir.InsertionPoint(anchor): + papply = ir.Operation.create( + "affine.apply", results=[ir.IndexType.get()], operands=[a, b], + attributes={"map": ir.AffineMapAttr.get(ir.AffineMap.get(2, 0, [plain]))}) + pin = papply.results[0] + assert bs._strip_accum_terms(ctx, pin, anchor) is pin + + assert module.operation.verify() + + +@pytest.mark.skipif(not _mlir_available(), reason="MLIR Python bindings not installed") +def test_cycle_table_on_fixture(): + fixture = os.environ.get("TOGSIM_SKELETON_FIXTURE") + if not fixture or not os.path.isfile(fixture): + pytest.skip("set TOGSIM_SKELETON_FIXTURE to a post-vcix kernel .mlir") + + import sys + sys.path.insert(0, str(_ROOT)) + from PyTorchSimFrontend.mlir.passes import build_skeleton, cycle_table + + import mlir.ir as ir + ctx = ir.Context() + ctx.allow_unregistered_dialects = True + with ctx: + module = ir.Module.parse(pathlib.Path(fixture).read_text(), ctx) + build_skeleton.build_skeleton(module) + types = cycle_table._compute_types(module) + # synthetic per-tile cycles (gem5 sample-mode is reused at P3 task 5). + cyc = [10 * (i + 1) for i in range(len(types))] + x_off, w_off = 4, 0 + table = cycle_table.build_cycle_table(module, cyc, x_off, w_off) + + assert len(table) == len(types) >= 1 + # cycle is carried verbatim; overlapping_cycle follows the legacy formula. + for (cy, ov), t, raw in zip(table, types, cyc): + assert cy == raw + if t == cycle_table.VECTOR_COMPUTE: + assert ov == 0 + else: + off = w_off if t == cycle_table.MATMUL_PRELOAD else x_off + assert ov == max(raw - off, 0) diff --git a/thirdparty/github-releases.json b/thirdparty/github-releases.json index 4af6ccbd..1265d380 100644 --- a/thirdparty/github-releases.json +++ b/thirdparty/github-releases.json @@ -3,7 +3,7 @@ "pytorch_image": "ubuntu:22.04", "gem5": { "repository": "PSAL-POSTECH/gem5", - "release_tag": "v1.0.1", + "release_tag": "v1.0.2", "asset_name": "gem5-release.tar.gz" }, "llvm_project": { @@ -13,7 +13,7 @@ }, "spike": { "repository": "PSAL-POSTECH/riscv-isa-sim", - "release_tag": "v1.0.2", + "release_tag": "v1.0.6", "asset_name": "spike-release.tar.gz" } }