diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index e7f02328f..a82125550 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -10,7 +10,7 @@ PyTorchSim is a cycle-accurate NPU simulation framework. It plugs into the PyTor 2. **Spike** — functional simulator that validates generated code correctness 3. **TOGSim** — the project's own cycle-accurate Tile-Operation-Graph simulator that models DRAM (Ramulator2), NoC (BookSim2), L2, systolic arrays, VPU lanes -The pipeline runs in that order on every `torch.compile` invocation; you'll see the three banners (`[Gem5]`, `[Spike]`, `[TOGSim]`) in the log when something is right. +Spike runs on every compiled kernel; gem5 and TOGSim run only with `TORCHSIM_TIMING_MODE=1` (off by default). With timing on you'll see the three banners (`[Gem5]`, `[Spike]`, `[TOGSim]`) in the log when something is right. ## Every operation runs on the NPU — a CPU fallback is a defect @@ -71,11 +71,11 @@ report next to the number it produced — never folded into a pass. | `pytorchsim/contract.py` | What the stages share, so none of them imports another for it: the axes and programs of a launch, how far a strided layout reaches in storage, and the kernel workdir (the manifest and artifacts the compiler left, and each process's launch directory) | | `pytorchsim/codegen/` | What runs while Inductor generates code: `inductor_hooks.py` (the scheduling and wrapper classes registered for `npu`; Inductor writes the Triton source, these wrap it), `kernel_metadata.py` (what the compile step needs from an Inductor kernel), `tiling.py` (block sizes, a template's grid, this machine's mm tiles), `verify.py` (the per-kernel CPU cross-check, both the lines put in the wrapper and the check they call) | | `pytorchsim/driver/` | Building a kernel and having it run: `codecache.py` (the compile entry point, the cache and the identity that admits it, the launcher), `select.py` (a template's config: Inductor's selection timed on TOGSim, and the recorded picks), `autotune.py` (smaller pinned blocks when the compiler says too big), `compiler_input.py` (what the compiler is handed: the rewritten Triton source and the KernelSpec file), `compiler_bridge.py` (PyTorchSim-Triton-Backend in a subprocess, the target description) | -| `pytorchsim/simulator/` | What runs a kernel object: `functional.py` (tensors to disk, Spike, tensors back), `timing.py` (gem5 tile cycles, the cycle and unit tables beside the TOG, TOGSim), `togsim.py` (`TOGSimulator`, the TOGSim process, and `poisson_request_generator`), `wallclock.py` (where the run's own time went) | +| `pytorchsim/simulator/` | What runs a kernel object: `functional.py` (tensors to disk, Spike, tensors back), `timing.py` (gem5 tile cycles, the cycle and unit tables beside the TOG, TOGSim), `togsim.py` (`TOGSimProcess`, the TOGSim process, and `poisson_request_generator`), `wallclock.py` (where the run's own time went) | | `device/` | C++ PyTorch backend registering the `npu` device. Built as a pip-installed package via `setup.py`. Based on `torch_openreg` (PrivateUse1 example). Produces `_C.cpython-*.so` | | `$TOGSIM_DIR` (not in this repo) | TOGSim, the repository PSAL-POSTECH/TOGSim, as the compiler checkout carries it: `$TORCHSIM_COMPILE_DIR/third_party/TOGSim`. C++ source in `src/` and `include/` (`include/togsim_runtime.h` is the C ABI a TOG is compiled against), the built `build/bin/Simulator`, and `configs/` | -| `$TOGSIM_DIR/configs/` | TOGSim hardware configs (YAML); `config.CONFIG_TOGSIM_CONFIG_DIR`. The default is `systolic_ws_256x256_c1_simple_noc_tpuv6e_functional_only.yml` -- the same machine as `..._tpuv6e.yml` and one line apart, `pytorchsim_timing_mode: 0`. Naming pattern: `systolic_ws__c__.yml` | -| `tests/` | Op- and model-level tests organized under `ops//` (elementwise, reduce, gemm, conv, attention, view, sort, misc, fusion), `models//` (Llama, Mixtral8x7B, DeepSeek, Diffusion, MoE, MLP, MobileNet, Yolov5) plus single-file model tests (test_resnet, test_transformer, test_vit, test_mlp, test_single_perceptron), and `system/` (scheduler, eager, vectorops). Shared helper: `tests/_utils.py`. **Which of them pass is `scripts/ci/triton_route_passing.txt`**; the rest are known gaps, swept and reported by `scripts/ci/triton_route_sweep.py --all` | +| `$TOGSIM_DIR/configs/` | TOGSim machine files (YAML); `config.CONFIG_TOGSIM_CONFIG_DIR`. `TORCHSIM_TARGET` names one (`tpuv6e` by default, i.e. `tpuv6e.yml`) | +| `tests/` | Op- and model-level tests organized under `ops//` (elementwise, reduce, gemm, conv, attention, view, sort, misc, fusion), `models//` (Llama, Mixtral8x7B, DeepSeek, Diffusion, MoE, MLP, MobileNet, Yolov5) plus single-file model tests (test_resnet, test_transformer, test_vit, test_mlp, test_single_perceptron), and `system/` (eager, vectorops, TOGSim session and result, selection). Shared helper: `tests/_pytorchsim_utils.py`. **Which of them pass is `scripts/ci/triton_route_passing.txt`**; the rest are known gaps, swept and reported by `scripts/ci/triton_route_sweep.py --all` | | `experiments/artifact/` | Paper reproduction scripts (`cycle_validation/run_cycle.sh`, `speedup/run_speedup.sh`) | | `scripts/` | Dev tools (`util_viewer.py`, `trace_timeline.py`, `op_coverage.py`, `clear_codegen_cache.sh`, `setup_worktree.sh`) and CI helpers (`ci/`). `build_from_source.sh` builds the compiler and its simulators through PTB | | `docker/` | CI's images: `Dockerfile.base` (the compiler's published image at the pin plus the test stack) and `Dockerfile` (this tree on top of it), each with its own `.dockerignore`. The build context is the repository root | @@ -91,7 +91,6 @@ Most tests follow the same pattern: build CPU reference, compile via `torch.comp python tests/ops/elementwise/test_add.py # vector add (smoke test, fastest) python tests/ops/gemm/test_matmul.py # GEMM python tests/models/test_mlp.py # MLP forward + backward (training path) -python tests/system/test_scheduler.py # multi-tenant launch_model python tests/system/test_eager.py # eager-fallback registration ``` @@ -103,7 +102,7 @@ Run a model from `tests/models/Llama/`, `tests/models/DeepSeek/`, etc. similarly **For fast iteration** (skip functional check): ```bash -export pytorchsim_functional_mode=False # skips Spike +export TORCHSIM_FUNCTIONAL_MODE=0 # skips Spike; outputs are not computed, so result checks fail ``` **To read the IR a kernel went through:** every stage is left in @@ -112,8 +111,8 @@ export pytorchsim_functional_mode=False # skips Spike reach is the one that owns it. **To find which op a wrong result first diverges at** (per-kernel CPU cross-check; -sub-option of functional mode, `pytorchsim/codegen/verify.py`). Set `pytorchsim_functional_verify_per_kernel: 1` -in the config YAML, clear the codegen cache, and re-run: each compiled kernel's +sub-option of functional mode, `pytorchsim/codegen/verify.py`). Set `TORCHSIM_FUNCTIONAL_VERIFY_PER_KERNEL=1`, +clear the codegen cache, and re-run: each compiled kernel's output is compared to a CPU golden and the run stops at the first divergent kernel, naming the op and offending indices. @@ -124,8 +123,11 @@ Read in `pytorchsim/config.py`: | Var | Default | Purpose | |---|---|---| | `TORCHSIM_DIR` | `/workspace/PyTorchSim` | repo root | -| `TOGSIM_CONFIG` | `$TOGSIM_DIR/configs/systolic_ws_256x256_c1_simple_noc_tpuv6e_functional_only.yml` | TOGSim hardware YAML | -| `TORCHSIM_TIMING_MODE` | unset | overrides the config's `pytorchsim_timing_mode` for one run (`1` to time, `0` not to) | +| `TORCHSIM_TARGET` | `tpuv6e` | the machine: a name under `$TOGSIM_DIR/configs` or a path to a YAML; the compiler compiles for it and TOGSim times on it | +| `TORCHSIM_TIMING_MODE` | `0` | `1` times each kernel on gem5 + TOGSim | +| `TORCHSIM_FUNCTIONAL_MODE` | `1` | `0` skips Spike (outputs are not computed) | +| `TORCHSIM_FUNCTIONAL_VERIFY_PER_KERNEL` | `0` | `1` checks each kernel against a CPU golden (needs functional mode) | +| `TORCHSIM_CODEGEN_AUTOTUNE_TEMPLATE_TOPK` | `4` | GEMM tiles offered to the selection | | `GEM5_PATH` | `$VCIX_ENV_ROOT/gem5/build/RISCV/gem5.opt` | gem5 binary (vcix-accelerator environment) | | `TORCHSIM_LOG_PATH` | `$TORCHSIM_DIR/togsim_results` | where TOGSim logs go | | `TORCHSIM_DUMP_PATH` | `$TORCHSIM_DIR` | misc dumps | @@ -136,7 +138,7 @@ Read in `pytorchsim/config.py`: | `TOGSIM_DIR` | `$TORCHSIM_COMPILE_DIR/third_party/TOGSim` | TOGSim repository root: the header is `$TOGSIM_DIR/include/togsim_runtime.h`, the binary `$TOGSIM_DIR/build/bin/Simulator`. Also handed to the compiler subprocess | | `TOGSIM_DEBUG_LEVEL` | unset | passed to TOGSim `--log_level` | -Note: `TOGSIM_CONFIG` is **overwritten** while inside a `with TOGSimulator(config_path=...)` block (and restored on exit). Compilation reads the same YAML as TOGSim that way. +Note: `TORCHSIM_TARGET` is **overwritten** while inside a `with torch.npu.TOGSimulator(config_path=...)` block (and restored on exit). Compilation reads the same YAML as TOGSim that way. ## TOGSim YAML knobs (the ones I edit most) @@ -144,20 +146,18 @@ Located under `$TOGSIM_DIR/configs/*.yml` (the TOGSim repository; a change there - `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` +- `vpu_num_lanes`, `vpu_spad_size_kb_per_lane`, `isa`, `vcix`, `address_map` (the compiler refuses a machine without them) - `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` +- `icnt_type` (`simple` | `booksim2`), `icnt_latency_cycles`, `icnt_freq_mhz`, `booksim_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) - `num_partition` + `partition: {core_0: 0, core_1: 1}` for multi-tenant `stream_index` mapping ## Multi-tenant API (pytorchsim/simulator/togsim.py) ```python -from pytorchsim.simulator.togsim import TOGSimulator, poisson_request_generator +from pytorchsim.simulator.togsim import poisson_request_generator -with TOGSimulator(config_path=...): +with torch.npu.TOGSimulator(config_path=...): torch.npu.launch_model(opt_model, x, stream_index=0, timestamp=0) # timestamp in ns torch.npu.synchronize() # barrier ``` @@ -185,12 +185,11 @@ with TOGSimulator(config_path=...): ## Gotchas / things I've already learned - The repo expects `python` to be a Python 3.10+ binary with `torch==2.14.0` (torchvision `0.29.0`, triton `3.8.0`). The frontend extends the PyTorch 2 Inductor stack — pin to this version: 2.14's Inductor targets triton 3.8, the version PyTorchSim-Triton-Backend is built against. The device extension builds as C++20, which 2.14's headers require. The pins live in `docker/Dockerfile.base`, and editing that file changes the base-image tag automatically (the tag is `thirdparty-`, see `scripts/ci/third_party_base_pin.sh`). -- gem5 and Spike are the vcix-accelerator environment's, found through `VCIX_ENV_ROOT`; both load the accelerator model `TORCHSIM_COMPILE_VCIX_MODEL` (default `$TORCHSIM_PREFIX/vcix-build/libtpu.so`). Override with `GEM5_PATH` / `TORCHSIM_SPIKE` if you build elsewhere. +- gem5 and Spike are the vcix-accelerator environment's, found through `VCIX_ENV_ROOT`; both load the accelerator model the kernel names from `$TORCHSIM_PREFIX/vcix-build/` (`config.CONFIG_VCIX_BUILD`). Override with `GEM5_PATH` / `TORCHSIM_SPIKE` if you build elsewhere. - `_C.cpython-311-*.so` and `torch_openreg/lib/` are build artifacts — already in `.gitignore`, don't commit. - **Parallel runs sharing a `TORCHSIM_DUMP_PATH`** share every per-kernel workdir, and that is deliberate: the workdir holds what compiling produced, which is a function of the source and the machine. A **launch** is not, so each process gets `/launch-/` (`pytorchsim/contract.py`) holding its own `runtime/*.raw`, its own `tog_shape.txt` and symlinks to the shared TOG — TOGSim resolves the cycle table and the shape from the directory of the TOG it is handed, so linking is enough. What is left locked is only *building* the shared thing, once: `.compile.lock` (compile) and `.timing.lock` (the gem5 cycle and unit tables of `tog.so`). Launches take no lock. Measured on a warm cache, two `test_add.py` in parallel: 40s when launches were locked, **31s** now, against 30s for one run alone. - TOGSim creates a per-PID FIFO under `/tmp/togsim_fifo_` for command/event comm; if a previous run crashed and left stale FIFOs, they get cleaned up on the next start, but watch for orphaned processes if you Ctrl-C mid-run. -- Multi-tenant runs **must** use the `with TOGSimulator(...)` context manager — otherwise compile-time `TOGSIM_CONFIG` and runtime config can diverge. -- `pytorchsim_functional_mode` exists as both an **env var** and a **YAML key**; the env var path is via `config.py` while the YAML key is read inside the same module. They should agree. +- Multi-tenant runs **must** use the `with torch.npu.TOGSimulator(...)` context manager — otherwise compile-time `TORCHSIM_TARGET` and runtime config can diverge. - "No CUDA runtime is found" warnings on `import torch` are expected — this is a CPU + simulated-NPU environment, not real CUDA. - **Codegen changes are sticky across runs because of caches.** When iterating on `pytorchsim/*` or the compiler, clear `$TORCHSIM_DUMP_PATH` (default `$TORCHSIM_DIR/outputs/`) before re-running — it holds Inductor's compile cache (`.torchinductor/`, set via `TORCHINDUCTOR_CACHE_DIR` inside `config.get_dump_path()`) and the per-kernel artifacts (`triton_/`). A compiler-side fix does NOT move the Inductor hash, so `triton_*` is the one that most often needs deleting; `scripts/clear_codegen_cache.sh` does both. Otherwise a buggy graph compiled before your fix is replayed verbatim. `togsim_results/` (TOGSim run logs) is cosmetic and not part of the codegen replay path. For parallel worktrees see `docs/worktrees.md`. diff --git a/README.md b/README.md index 4ba12a911..64c2ab166 100644 --- a/README.md +++ b/README.md @@ -112,9 +112,9 @@ The script checks out the commit pinned in [`third_party/pytorchsim-triton-backe ### Run Examples The `tests` directory contains several AI workload examples. ```bash -python tests/ops/gemm/test_matmul.py +TORCHSIM_TIMING_MODE=1 python tests/ops/gemm/test_matmul.py ``` -The result is written to `${TORCHSIM_LOG_PATH}/togsim_result/XXX.log`. The log file contains detailed core, memory, and interconnect stats. +Timing is off by default (`TORCHSIM_TIMING_MODE=0`): each kernel is compiled and checked on Spike, and gem5 and TOGSim do not run. With `TORCHSIM_TIMING_MODE=1`, the TOGSim log is written to `${TORCHSIM_LOG_PATH}/_.log`. The log file contains detailed core, memory, and interconnect stats. ### Run Your Own Model on PyTorchSim You can run your own PyTorch model on PyTorchSim by setting up a custom NPU device. @@ -215,17 +215,16 @@ compiled_step() By default, each compiled operation can run TOGSim in a standalone way—typically **one simulator process and one log file per kernel**. That matches single-kernel workflows but splits traces when you run many forwards in a row. -`with TOGSimulator(config_path=...)` keeps **one TOGSim session** open for the block: successive calls (e.g. multiple `compiled_model(...)` forwards) run in sequence in the same process, so the timeline and shared resources continue in a single log instead of restarting for every op. `TOGSIM_CONFIG` is set to the given YAML for the block so codegen and TOGSim still share one hardware file. +`with torch.npu.TOGSimulator(config_path=...)` keeps **one TOGSim session** open for the block: successive calls (e.g. multiple `compiled_model(...)` forwards) run in sequence in the same process, so the timeline and shared resources continue in a single log instead of restarting for every op. `TORCHSIM_TARGET` is set to the given YAML for the block so codegen and TOGSim still share one hardware file. Use the same API you already use; only wrap the region you want co-simulated: ```python import torch -from pytorchsim.simulator.togsim import TOGSimulator # ... build model, torch.compile, tensors on npu:0 as usual ... -with TOGSimulator(config_path=config): +with torch.npu.TOGSimulator(config_path=config): y = compiled_model(x) ``` @@ -240,7 +239,7 @@ For **multi-tenant** or **interleaved** execution, you usually need to attach a `timestamp`** is in **nanoseconds** (simulation time for ordering launches). Use `0` when you do not need explicit times beyond submission order. ```python -with TOGSimulator(config_path=config): +with torch.npu.TOGSimulator(config_path=config): torch.npu.launch_model(opt_model1, x1, stream_index=0, timestamp=0) torch.npu.launch_model(opt_model2, x2, stream_index=1, timestamp=0) torch.npu.synchronize() @@ -250,10 +249,6 @@ with TOGSimulator(config_path=config): Here `synchronize()` acts as a barrier: it does not return until every `launch_model` issued **above** it has finished in the simulator. The later pair of `launch_model` calls therefore runs only after those earlier models have fully completed—so the sync is the point in the timeline where **all preceding launches are done**. -```bash -python tests/system/test_scheduler.py -``` - Use a TOGSim config(`.yml`) that defines **partitions** when mapping queues to cores, for example: - `num_partition`: Number of independent request queues (valid `stream_index` values are `0 … num_partition-1`). @@ -271,7 +266,7 @@ Here `stream_index=0` selects queue `0` (core_0), `stream_index=1` selects queue ### 3. Load generation (Poisson arrivals) -The `poisson_request_generator` in `pytorchsim.simulator.togsim` yields synthetic **arrival times** (in **milliseconds**). Merge those with `launch_model`: convert each time to **nanoseconds** for `timestamp`, set `stream_index` to the target partition queue, and run all launches inside one `with TOGSimulator(...)` so a **single** log captures the full trace. +The `poisson_request_generator` in `pytorchsim.simulator.togsim` yields synthetic **arrival times** (in **milliseconds**). Merge those with `launch_model`: convert each time to **nanoseconds** for `timestamp`, set `stream_index` to the target partition queue, and run all launches inside one `with torch.npu.TOGSimulator(...)` so a **single** log captures the full trace. ```python from pytorchsim.simulator.togsim import poisson_request_generator @@ -289,7 +284,7 @@ for t in poisson_request_generator(model1_lambda, max_msec_time=max_time_msec): x = torch.randn(128, 768, device=device) events.append((t, 1, opt_model1, (x,))) # stream_index 1 → queue / partition 1 -with TOGSimulator(config_path=config): +with torch.npu.TOGSimulator(config_path=config): for t_msec, stream_index, model, args in events: torch.npu.launch_model( model, @@ -331,67 +326,56 @@ Each kernel's `meta.json` says where its tile came from: `tile_source` is `timed `recorded_unfused` (a recorded pick built with an epilogue fused) or `heuristic`. ## L2 Cache -It supports L2 cache as persistent cache. User can provide software-managed allocation/eviction strategy for tensors with persistent cache. - -Common Memory (CMEM) is a new feature introduced in the latest TPUs (newer than TPUv3). Multiple cores share this memory, which provides high bandwidth. Reusable tensors are stored and loaded from CMEM to avoid off-chip traffic. Our L2 cache can work like CMEM. - -To allocate a tensor in L2 cache, set the environment variable as shown below. The `tpuv4` directory provides example plans for L2 cache obtained from TPUv4 profiling. -```bash -export SRAM_BUFFER_PLAN_PATH=tpuv4/gemm_plan.py -``` -The L2 cache strategy file is composed as follows: -``` -plan = { - "arg0_1" -} -``` -In this example, only one input tensor is registered in L2 cache. You can refer to the tensor name from the wrapper code. After running the code, you can find the wrapper codegen path in the [result](#result) section. - -Last but not least, you must set `l2d_type` and `l2d_config` in the [TOGSim config](#togsim-configuration) to use L2 cache. The `l2d_config` follows the same configuration method as [AccelSim](https://github.com/accel-sim/accel-sim-framework). +TOGSim models an optional L2 data cache between the cores and DRAM. Set `l2d_type: datacache` and `l2d_config` in the [TOGSim config](#togsim-configuration) to use it. The `l2d_config` follows the same configuration method as [AccelSim](https://github.com/accel-sim/accel-sim-framework). ## Compiler Configuration -`pytorchsim/config.py` contains target hardware configuration to compile. - -You can configure these options using environment variables. +`pytorchsim/config.py` reads PyTorchSim's settings from environment variables. The machine itself is a TOGSim YAML file (see [TOGSim Configuration](#togsim-configuration)). ```bash export TORCHSIM_DIR=/workspace/PyTorchSim # home directory export TOGSIM_DIR=/workspace/pytorchsim-triton-compiler/third_party/TOGSim # TOGSim checkout: include/, build/bin/Simulator, configs/ (default: the one the compiler carries) +export TORCHSIM_TARGET=tpuv6e # the machine: a name under $TOGSIM_DIR/configs, or a path to a .yml (default tpuv6e) -# Plan which tensors are allocated in TPUv4's CMEM -export SRAM_BUFFER_PLAN_PATH=/workspace/PyTorchSim/tpuv4/gemm_plan.py -export TORCHSIM_USE_TIMING_POOLING=0 # use lightweight pooling for timing +export TORCHSIM_TIMING_MODE=1 # 1 = time each kernel on gem5 and TOGSim (default 0) +export TORCHSIM_FUNCTIONAL_MODE=0 # 0 = skip Spike for faster runs; outputs are then not computed (default 1) +export TORCHSIM_FUNCTIONAL_VERIFY_PER_KERNEL=1 # check each kernel against a CPU golden (default 0) +export TORCHSIM_CODEGEN_AUTOTUNE_TEMPLATE_TOPK=4 # GEMM tiles offered to the selection (default 4) ``` ## TOGSim Configuration ![NPU_Core](./docs/npu_core.jpg) -TOGSim is its own repository, [PSAL-POSTECH/TOGSim](https://github.com/PSAL-POSTECH/TOGSim), which the compiler carries as `third_party/TOGSim`. Its `configs/` directory holds **YAML** (`.yml`) hardware descriptions: `$TOGSIM_DIR/configs`, which is `/workspace/pytorchsim-triton-compiler/third_party/TOGSim/configs` in the Docker image. Set `TOGSIM_CONFIG` to one of these files. The **same file** is read by **PyTorchSim** (`pytorchsim/config.py`) for `vpu_*`, `pytorchsim_*`, and `codegen_*` fields, and by **TOGSim** (`src/Common.cc` there) for the simulator-specific keys below. +TOGSim is its own repository, [PSAL-POSTECH/TOGSim](https://github.com/PSAL-POSTECH/TOGSim), which the compiler carries as `third_party/TOGSim`. Its `configs/` directory holds **YAML** (`.yml`) hardware descriptions: `$TOGSIM_DIR/configs`, which is `/workspace/pytorchsim-triton-compiler/third_party/TOGSim/configs` in the Docker image. Set `TORCHSIM_TARGET` to one of them, by name (`tpuv6e`) or by path. The **same file** is read by the **compiler** (`vpu_*`, `isa`, `vcix`, `address_map`) and by **TOGSim** (`src/Common.cc` there) for the simulator-specific keys below. ### Reference layout +The default machine, `configs/tpuv6e.yml`, with the optional keys commented out: + ```yaml # --- Core (TOGSim) --- num_cores: 1 -core_freq_mhz: 940 -core_stats_print_period_cycles: 10000 +core_freq_mhz: 1751 +core_stats_print_period_cycles: 200 num_systolic_array_per_core: 2 -sa_weight_buffer_depth: 2 # per-SA resident weight slots; must be > 0 (default 2). Raise to loosen the preload throttle. -# Optional: one entry per core, default ws_mesh -# core_type: [ws_mesh, ws_mesh] -# Optional STONNE cores: stonne_config_path, num_stonne_per_core, num_stonne_port - -# --- VPU / scratchpad (compiler codegen; same YAML) --- +systolic_array_split: round_robin +systolic_array_unit: TPUV6E_MXU +dma_load_latency_cycles: 27 +dma_load_ready_cycles: 842 +# sa_weight_buffer_depth: 2 # per-SA resident weight slots; must be > 0 (default 2). Raise to loosen the preload throttle. +# core_type: [ws_mesh] # one entry per core; ws_mesh is the only core type + +# --- VPU / scratchpad / ISA (compiler; same YAML) --- vpu_num_lanes: 128 -vpu_spad_size_kb_per_lane: 128 -vpu_vector_length_bits: 256 +vpu_spad_size_kb_per_lane: 1024 +isa: [m, a, f, d, c, v, zvfh, zvfbfmin, zvl256b, vcix_tpuv6e] +vcix: {tpu_mxu_queue_entries: 512} +address_map: {spad_vaddr: 0xd0000000, spad_paddr: 0x2000000000, dram_base: 0x80000000, dram_size: 107374182400} # --- DRAM config --- dram_type: ramulator2 # ramulator2 | simple -dram_freq_mhz: 940 -dram_channels: 16 -dram_stats_print_period_cycles: 10000 -ramulator_config_path: ../configs/ramulator2_configs/HBM2_TPUv3.yaml # resolved relative to this YAML’s directory +dram_channels: 32 +dram_stats_print_period_cycles: 200 +ramulator_config_path: ../configs/ramulator2_configs/HBM3_TPUv6e.yaml # resolved relative to this YAML's directory # For ramulator2: request size, DRAM MHz, and per-channel peak GB/s are derived from the Ramulator YAML. -# dram_freq_mhz must exactly match MHz derived from Ramulator tCK or startup fails. +# dram_freq_mhz, if given, must exactly match MHz derived from Ramulator tCK or startup fails. # simple DRAM (alternative to ramulator2): # dram_type: simple @@ -406,30 +390,21 @@ ramulator_config_path: ../configs/ramulator2_configs/HBM2_TPUv3.yaml # resolved # Optional: NUMA-style DRAM partitions (channels must divide evenly) # dram_num_partitions: 2 +# --- Optional L2 (TOGSim) --- +l2d_type: datacache # nocache (default if omitted) | datacache +l2d_config: S:128:128:512,32,L:T:m:W:L,A:192:4,32:0,32 # AccelSim-style string, required for datacache +# l2d_hit_latency: ... + # --- Interconnect (TOGSim) --- icnt_type: simple # simple | booksim2 icnt_latency_cycles: 10 # used when icnt_type is simple -icnt_freq_mhz: 940 -icnt_injection_ports_per_core: 16 +icnt_freq_mhz: 1751 +icnt_injection_ports_per_core: 32 # icnt_stats_print_period_cycles: 0 # optional -# For icnt_type: booksim2, use booksim_config_path (not icnt_config_path): +# For icnt_type: booksim2, use booksim_config_path: # booksim_config_path: ../configs/booksim2_configs/fly_c16_m16.icnt -# --- Functional / timing flags (compiler; same YAML) --- -pytorchsim_functional_mode: 1 # 1 = run Spike validation, 0 = skip for faster runs -pytorchsim_timing_mode: 1 - -# --- Compiler mapping / optimizations (same YAML) --- -codegen_autotune_template_topk: 4 -codegen_compiler_optimization: all # all | none | list of option names - -# --- Optional L2 (TOGSim) --- -# l2d_type: nocache # default if omitted -# l2d_type: datacache -# l2d_config: "S:64:128:512,32,..." # required when l2d_type is datacache (AccelSim-style string) - -# --- Optional scheduler / partitions (TOGSim; multi-queue) --- -# scheduler: simple +# --- Optional partitions (TOGSim; multi-queue) --- # num_partition: 2 # partition: # core_0: 0 @@ -440,15 +415,13 @@ codegen_compiler_optimization: all # all | none | list of option names One-line meaning for each group (details in the YAML block above). -- **Core (`num_cores`, `core_freq_mhz`, `core_stats_print_period_cycles`, `num_systolic_array_per_core`, `sa_weight_buffer_depth`, optional `core_type`, STONNE keys)**: how many cores, their clock, stats cadence, systolic count per core, the per-SA resident weight-slot count (must be > 0; bounds preload run-ahead—raise it to loosen the throttle), and optional non-default mesh vs STONNE mix. -- **VPU (`vpu_*`)**: vector lane count, per-lane scratchpad (KB), and vector register width—**compiler** uses these for tiling/codegen. +- **Core (`num_cores`, `core_freq_mhz`, `core_stats_print_period_cycles`, `num_systolic_array_per_core`, `systolic_array_*`, `dma_*`, `sa_weight_buffer_depth`, optional `core_type`)**: how many cores, their clock, stats cadence, systolic count per core and its unit, DMA costs, and the per-SA resident weight-slot count (must be > 0; bounds preload run-ahead—raise it to loosen the throttle). +- **VPU / ISA (`vpu_*`, `isa`, `vcix`, `address_map`)**: vector lane count and per-lane scratchpad (KB), the ISA and accelerator the **compiler** targets, and the address map. A machine file that leaves any of them out is refused. - **DRAM (`dram_type`, `dram_channels`, …)**: `ramulator2` uses `ramulator_config_path`; `simple` uses fixed latency and optional bandwidth caps (`dram_bandwidth_gbps_*`, `dram_freq_mhz` when capped). `dram_num_partitions` splits channels for NUMA-style addressing. - **Interconnect (`icnt_*`, `booksim_config_path`)**: `simple` adds fixed hop latency (`icnt_latency_cycles`); `booksim2` points at a BookSim2 topology file. -- **Codegen (`codegen_*`)**: how many of this machine's GEMM tiles are offered to the selection (see Mapping), and the fusion/optimization set for the PyTorch compiler path. - **L2 (`l2d_type`, `l2d_config`, optional `l2d_hit_latency`)**: optional data cache between cores and DRAM; `l2d_config` uses AccelSim-style cache geometry strings. -- **Scheduler (`scheduler`, `num_partition`, `partition`)**: request queues per partition and `core_i` → queue index mapping for multi-tenant / `launch_model` routing. -- **`pytorchsim_functional_mode`**: **`1`** runs **Spike** on generated code; **`0`** skips it for faster iteration. -- **`pytorchsim_timing_mode`**: **`1`** keeps the cycle-aware tile-graph path that feeds **TOGSim**; **`0`** turns that timing path off (functional-style runs; often paired with `pytorchsim_functional_mode` in tutorial configs). +- **Partitions (`num_partition`, `partition`)**: request queues per partition and `core_i` → queue index mapping for multi-tenant / `launch_model` routing. The shipped machines define one queue. +- Run settings (timing, Spike, per-kernel check, GEMM tiles offered) are environment variables, not YAML keys: see [Compiler Configuration](#compiler-configuration). ## Tutorial Check out our [ISPASS 2026 tutorial](https://www.youtube.com/playlist?list=PLYIb5dkr4isJ1ERKTKFoWdCKMUOaay2Nn) to learn: diff --git a/device/torch_openreg/openreg/__init__.py b/device/torch_openreg/openreg/__init__.py index 6684aa3c0..c951363cb 100644 --- a/device/torch_openreg/openreg/__init__.py +++ b/device/torch_openreg/openreg/__init__.py @@ -11,7 +11,7 @@ _initialized = False _default_streams = {} # Dictionary to store default streams per device -_tog_simulator = None # Singleton TOGSimulator instance +_tog_simulator = None # Singleton TOGSimProcess instance _launch_context = threading.local() # storage for launch_kernel context _eager_compiled = set() # op names already given an eager_to_compile wrapper @@ -150,7 +150,7 @@ def default_stream(device=None): def launch_kernel(tog_path, attribute_path): - """Launch a kernel on TOGSimulator. + """Launch a kernel on the open TOGSimProcess. Args: tog_path: Path to TOG file @@ -160,14 +160,14 @@ def launch_kernel(tog_path, attribute_path): int: The kernel ID assigned to this launch """ - # Get TOGSimulator instance + # Get TOGSimProcess instance sim = get_tog_simulator() if sim is None: - raise RuntimeError("[torch.npu] TOGSimulator is not initialized. Call torch.npu.init() first.") + raise RuntimeError("[torch.npu] No TOGSim is open. Launch inside `with torch.npu.TOGSimulator(...)`.") device_idx = current_device() stream_index, timestamp = get_launch_context() - # Create a task function that calls TOGSimulator.launch_kernel + # Create a task function that calls TOGSimProcess.launch_kernel def launch_task(): return sim.launch_kernel(device_idx, stream_index, tog_path, attribute_path, timestamp) @@ -178,16 +178,16 @@ def synchronize(): """Synchronize all streams on the current device. This function: - 1. Registers TOGSimulator.device_synchronize as a task on the default stream + 1. Registers TOGSimProcess.device_synchronize as a task on the default stream 2. Calls the underlying device_synchronize to wait for all tasks to complete """ - # Get TOGSimulator instance + # Get TOGSimProcess instance sim = get_tog_simulator() if sim is not None: # Get current device index device_idx = current_device() - # Create a task function that calls TOGSimulator.device_synchronize + # Create a task function that calls TOGSimProcess.device_synchronize def sync_task(): return sim.device_synchronize(device_idx) @@ -202,15 +202,15 @@ def get_tog_simulator(): return _tog_simulator def set_tog_simulator(simulator): - """Set the global TOGSimulator instance. + """Set the global TOGSimProcess instance. Args: - simulator: TOGSimulator instance or None + simulator: TOGSimProcess instance or None """ global _tog_simulator _tog_simulator = simulator -class simulator: +class TOGSimulator: """Open a TOGSim backend and make it this device's simulator for the block. The machine file TOGSim times on is the one kernels are compiled for, so its path @@ -225,10 +225,10 @@ def __init__(self, config_path=None, togsim_path=None): self._backend = None def __enter__(self): - from pytorchsim.simulator.togsim import TOGSimulator + from pytorchsim.simulator.togsim import TOGSimProcess - self._backend = TOGSimulator(config_path=self.config_path, - togsim_path=self.togsim_path) + self._backend = TOGSimProcess(config_path=self.config_path, + togsim_path=self.togsim_path) self._old_config_env = os.environ.get("TORCHSIM_TARGET", self._CONFIG_ENV_UNSET) os.environ["TORCHSIM_TARGET"] = os.path.abspath(self._backend.config_path) self._old_simulator = get_tog_simulator() @@ -291,7 +291,7 @@ def __exit__(self, exc_type, exc_val, exc_tb): return False def launch_model(model, *args, stream_index=0, timestamp=0, **kwargs): - """Launch a compiled model on TOGSimulator. + """Launch a compiled model on the open TOGSimulator. Args: model: Compiled model (torch.compile()) @@ -465,7 +465,7 @@ def register_eager_to_compile(ops): "synchronize", "get_tog_simulator", "set_tog_simulator", - "simulator", + "TOGSimulator", "eager_to_compile", "register_eager_to_compile", "DEFAULT_EAGER_TO_COMPILE", diff --git a/docs/worktrees.md b/docs/worktrees.md index abd52c240..6aeabde0e 100644 --- a/docs/worktrees.md +++ b/docs/worktrees.md @@ -109,7 +109,7 @@ Worktree-scoped (auto-set by `.envrc`): | `TORCHSIM_DIR` | `$PWD` of the worktree | | `TORCHSIM_DUMP_PATH` | `$PWD/outputs` | | `TORCHSIM_LOG_PATH` | `$PWD/togsim_results` | -| `TOGSIM_CONFIG` | `systolic_ws_256x256_c1_simple_noc_tpuv6e.yml` in the TOGSim checkout's `configs/` | +| `TORCHSIM_TARGET` | `tpuv6e` (the machine file `tpuv6e.yml` in the TOGSim checkout's `configs/`) | | `PYTHONPATH` | `$PWD/device:$PWD:$PYTHONPATH` | Shared (container-dedicated, set the same in every `.envrc`): diff --git a/experiments/BERT.py b/experiments/BERT.py index 2ce994661..4f0e640c5 100644 --- a/experiments/BERT.py +++ b/experiments/BERT.py @@ -37,7 +37,7 @@ model_input = torch.randn(args.input_size, hidden_dim).to(device=device) opt_fn = torch.compile(dynamic=False)(model) - with torch.npu.simulator(), torch.no_grad(): + with torch.npu.TOGSimulator(), torch.no_grad(): torch.npu.launch_model(opt_fn, model_input, stream_index=0, timestamp=0) torch.npu.synchronize() print(f"BERT-{args.size} Simulation Done") diff --git a/experiments/attention.py b/experiments/attention.py index 88aabb946..55b001d21 100644 --- a/experiments/attention.py +++ b/experiments/attention.py @@ -29,7 +29,7 @@ def attention(query, key, value): value = torch.randn(*size).to(device=device) opt_fn = torch.compile(dynamic=False)(attention) - with torch.npu.simulator(), torch.no_grad(): + with torch.npu.TOGSimulator(), torch.no_grad(): torch.npu.launch_model(opt_fn, query, key, value, stream_index=0, timestamp=0) torch.npu.synchronize() print(f"Attention {size} Simulation Done") diff --git a/experiments/conv.py b/experiments/conv.py index 0b1782a58..34b2f1b55 100644 --- a/experiments/conv.py +++ b/experiments/conv.py @@ -32,7 +32,7 @@ def _conv(a, b, bias): custom_conv = conv2d_fn(batch_size, i_h, i_w, i_c, o_c, kernel_size, stride, padding) opt_fn = torch.compile(dynamic=False)(custom_conv) - with torch.npu.simulator(), torch.no_grad(): + with torch.npu.TOGSimulator(), torch.no_grad(): torch.npu.launch_model(opt_fn, conv_input, conv_kernel, conv_bias, stream_index=0, timestamp=0) torch.npu.synchronize() print(f"CONV {batch_size}_{i_h}_{i_w}_{i_c}_{o_c}_{kernel_size}_{stride}_{padding} Simulation Done") diff --git a/experiments/gemm.py b/experiments/gemm.py index 0a322402b..f74ef6ab1 100644 --- a/experiments/gemm.py +++ b/experiments/gemm.py @@ -25,7 +25,7 @@ def matmul_fn(a, b): input_b = torch.randn(K, N).to(device=device) opt_fn = torch.compile(dynamic=False)(matmul_fn) - with torch.npu.simulator(), torch.no_grad(): + with torch.npu.TOGSimulator(), torch.no_grad(): torch.npu.launch_model(opt_fn, input_a, input_b, stream_index=0, timestamp=0) torch.npu.synchronize() print(f"GEMM {M}x{K}x{N} (MxKxN) Simulation Done") diff --git a/experiments/layernorm.py b/experiments/layernorm.py index c91ac1608..c3c8efeed 100644 --- a/experiments/layernorm.py +++ b/experiments/layernorm.py @@ -22,7 +22,7 @@ opt_fn = torch.compile(dynamic=False)(model) model_input = torch.randn(*size).to(device=device) - with torch.npu.simulator(), torch.no_grad(): + with torch.npu.TOGSimulator(), torch.no_grad(): torch.npu.launch_model(opt_fn, model_input, stream_index=0, timestamp=0) torch.npu.synchronize() print(f"LayerNorm {size} Simulation Done") diff --git a/experiments/resnet18.py b/experiments/resnet18.py index ef929a46c..ebf969013 100644 --- a/experiments/resnet18.py +++ b/experiments/resnet18.py @@ -21,7 +21,7 @@ opt_fn = torch.compile(dynamic=False)(model) model_input = torch.randn(args.batch, 3, 224, 224).to(device=device) - with torch.npu.simulator(), torch.no_grad(): + with torch.npu.TOGSimulator(), torch.no_grad(): torch.npu.launch_model(opt_fn, model_input, stream_index=0, timestamp=0) torch.npu.synchronize() print("ResNet18 Simulation Done") diff --git a/experiments/resnet50.py b/experiments/resnet50.py index f7a5cb6a4..27790a01b 100644 --- a/experiments/resnet50.py +++ b/experiments/resnet50.py @@ -21,7 +21,7 @@ opt_fn = torch.compile(dynamic=False)(model) model_input = torch.randn(args.batch, 3, 224, 224).to(device=device) - with torch.npu.simulator(), torch.no_grad(): + with torch.npu.TOGSimulator(), torch.no_grad(): torch.npu.launch_model(opt_fn, model_input, stream_index=0, timestamp=0) torch.npu.synchronize() print("ResNet50 Simulation Done") diff --git a/experiments/softmax.py b/experiments/softmax.py index de487f0ea..232d31594 100644 --- a/experiments/softmax.py +++ b/experiments/softmax.py @@ -22,7 +22,7 @@ opt_fn = torch.compile(dynamic=False)(model) model_input = torch.randn(*size).to(device=device) - with torch.npu.simulator(), torch.no_grad(): + with torch.npu.TOGSimulator(), torch.no_grad(): torch.npu.launch_model(opt_fn, model_input, stream_index=0, timestamp=0) torch.npu.synchronize() print(f"Softmax {size} Simulation Done") diff --git a/experiments/tpu_validation/README.md b/experiments/tpu_validation/README.md index 447a22261..7e9bf9908 100644 --- a/experiments/tpu_validation/README.md +++ b/experiments/tpu_validation/README.md @@ -33,7 +33,7 @@ softmax 157), which takes many hours; the large shapes dominate. | `--keep COLS=VALUES` | only these shapes. `C=128,512`, or several columns at once: `KxN=768x768,2048x3072`. Repeatable; a shape must match every `--keep` | | `--drop COLS=VALUES` | skip these shapes, same syntax | | `--set KEY=VALUE` | change one line of the config, e.g. `--set vpu_num_lanes=128 --set core_freq_mhz=1750`. Repeatable | -| `--config FILE` | base config, default `configs/tpuv6e_nocache.yml` | +| `--config NAME\|FILE` | base machine: a name under `$TOGSIM_DIR/configs` or a file, default `tpuv6e` (L2 off, `l2d_type=nocache`, before `--set`) | | `--timeout S` | seconds per shape, default 7200; a shape over it is killed and logged in `failed.csv` | | `--out DIR` | where the tag directories live, default `runs/` here. Keep it on a real disk, not a RAM tmpfs | diff --git a/experiments/tpu_validation/sim_op.py b/experiments/tpu_validation/sim_op.py index 168921639..3d628c99c 100644 --- a/experiments/tpu_validation/sim_op.py +++ b/experiments/tpu_validation/sim_op.py @@ -31,7 +31,7 @@ device = torch.device("npu:0") inputs = [t.to(device=device) for t in inputs] opt_fn = torch.compile(dynamic=False)(fn) -with torch.npu.simulator(), torch.no_grad(): +with torch.npu.TOGSimulator(), torch.no_grad(): torch.npu.launch_model(opt_fn, *inputs, stream_index=0, timestamp=0) torch.npu.synchronize() print(f"{op} {'x'.join(map(str, shape))} Simulation Done") diff --git a/pytorchsim/codegen/verify.py b/pytorchsim/codegen/verify.py index da6325603..cc2771653 100644 --- a/pytorchsim/codegen/verify.py +++ b/pytorchsim/codegen/verify.py @@ -57,7 +57,7 @@ class FunctionalVerifyMismatch(RuntimeError): def enabled(): """True when functional mode AND the per-kernel verify sub-option are on. - Read dynamically (the config can change inside a ``with torch.npu.simulator(...)`` + Read dynamically (the config can change inside a ``with torch.npu.TOGSimulator(...)`` block); the config accessor already AND-gates this with functional mode. """ try: diff --git a/pytorchsim/driver/select.py b/pytorchsim/driver/select.py index a0f6ab2a0..dc025e5bb 100644 --- a/pytorchsim/driver/select.py +++ b/pytorchsim/driver/select.py @@ -42,7 +42,7 @@ def _time_tile(src_code, meta, kernel_name, workdir, cut=None): """TOGSim cycles of one kernel, simulated alone; inf if it does not compile or run, or `cut` stops its simulation. TOGSim refuses a tile over the spad at load, and that refusal and a cut reach here as RuntimeError.""" - from pytorchsim.simulator.togsim import Cut, TOGSimulator + from pytorchsim.simulator.togsim import Cut, TOGSimProcess os.makedirs(workdir, exist_ok=True) spec_path = os.path.join(workdir, f"{kernel_name}_spec.py") with open(os.path.join(workdir, "kernel.py"), "w") as f: @@ -55,10 +55,10 @@ def _time_tile(src_code, meta, kernel_name, workdir, cut=None): mine = contract.link_shared(workdir, timing.SHARED) timing.write_shape(workdir, meta) timing.write_tensors(workdir) - result = TOGSimulator.run_standalone(os.path.join(mine, "tile_graph.onnx"), - os.path.join(mine, "attribute"), - autotune_mode=True, cut=cut) - return TOGSimulator.get_result_from_file(result)[-1] + result = TOGSimProcess.run_standalone(os.path.join(mine, "tile_graph.onnx"), + os.path.join(mine, "attribute"), + autotune_mode=True, cut=cut) + return TOGSimProcess.get_result_from_file(result)[-1] except (compiler_bridge.CompilerError, RuntimeError, FileNotFoundError) as exc: why = autotune.too_big(exc) or (f"cut, {exc}" if isinstance(exc, Cut) else type(exc).__name__) logger.info("[select] %s %s: %s", kernel_name, workdir, why) diff --git a/pytorchsim/simulator/timing.py b/pytorchsim/simulator/timing.py index d9010e458..57d9519fd 100644 --- a/pytorchsim/simulator/timing.py +++ b/pytorchsim/simulator/timing.py @@ -176,7 +176,7 @@ def run_togsim(workdir, meta, args=()): """ import torch - from pytorchsim.simulator.togsim import TOGSimulator + from pytorchsim.simulator.togsim import TOGSimProcess for need in SHARED: if not os.path.isfile(os.path.join(workdir, need)): @@ -190,8 +190,8 @@ def run_togsim(workdir, meta, args=()): if torch.npu.get_tog_simulator() is not None: return torch.npu.launch_kernel(handle, attribute) - result_path = TOGSimulator.run_standalone(handle, attribute) - return TOGSimulator.get_result_from_file(result_path) + result_path = TOGSimProcess.run_standalone(handle, attribute) + return TOGSimProcess.get_result_from_file(result_path) def run(workdir, meta, args=()): diff --git a/pytorchsim/simulator/togsim.py b/pytorchsim/simulator/togsim.py index 5c5f26338..d5b14d5d2 100644 --- a/pytorchsim/simulator/togsim.py +++ b/pytorchsim/simulator/togsim.py @@ -63,7 +63,7 @@ def __exit__(self, exc_type, exc_val, exc_tb): return False -class TOGSimulator(): +class TOGSimProcess(): TOGSIM_RESULT_PATH_KEY = "TOGSIM_RESULT_PATH" FINISH_STR = "Simulation finished" def __init__(self, config_path=None, togsim_path=None) -> None: @@ -346,7 +346,7 @@ def run_standalone( cycle_tsv = os.path.join(os.path.dirname(str(model_path)), "tog_cycles.tsv") if not os.path.exists(tog_so): raise FileNotFoundError(f"{tog_so} not found -- the kernel has no TOG to simulate") - base_cmd = TOGSimulator.get_togsim_command(config_path, togsim_path) + base_cmd = TOGSimProcess.get_togsim_command(config_path, togsim_path) unit_tsv = os.path.join(os.path.dirname(str(model_path)), "tog_units.tsv") cmd = f"{base_cmd} --tog_so {tog_so} --cycle_table {cycle_tsv} --unit_table {unit_tsv}" if config.CONFIG_TOGSIM_DEBUG_LEVEL: @@ -409,7 +409,7 @@ def get_result_from_file(result_path): lines = f.readlines() for idx, line in enumerate(lines): - if TOGSimulator.FINISH_STR in line: + if TOGSimProcess.FINISH_STR in line: break else: logger.warning(f"[TOGSim] Warning: Unable to parse the output file ({result_path}). The file may be improperly formatted.") @@ -418,17 +418,17 @@ def get_result_from_file(result_path): units = {} combined = None for line in lines[idx:]: - m = TOGSimulator._UNIT_LINE.search(line) + m = TOGSimProcess._UNIT_LINE.search(line) if m: units.setdefault(m.group(1), {})[m.group(2)] = { "utilization": float(m.group(3)), "active_cycles": int(m.group(4)), "idle_cycles": int(m.group(5))} continue - m = TOGSimulator._DRAM_CHANNEL.search(line) + m = TOGSimProcess._DRAM_CHANNEL.search(line) if m: dram_channel_bw[f"CH[{m.group(1)}]"] = float(m.group(2)) continue - m = TOGSimulator._DRAM_COMBINED.search(line) + m = TOGSimProcess._DRAM_COMBINED.search(line) if m: combined = float(m.group(1)) elif 'Total execution cycles' in line: @@ -482,7 +482,7 @@ def poisson_request_generator(lambda_requests, max_msec_time=None): ap.add_argument("--repeat", type=int, default=1) args = ap.parse_args() - sim = TOGSimulator(config_path=args.config) + sim = TOGSimProcess(config_path=args.config) for _ in range(args.repeat): sim.launch_kernel(0, 0, args.kernel_dir, args.attribute) sim.device_synchronize(0) diff --git a/tests/ops/attention/test_gqa_decode.py b/tests/ops/attention/test_gqa_decode.py index 3c9add881..f8bba9560 100644 --- a/tests/ops/attention/test_gqa_decode.py +++ b/tests/ops/attention/test_gqa_decode.py @@ -178,7 +178,7 @@ def test_gqa_decode_optimized(model, device, seq_len: int = 10240, tile_size: in q_dev, k_dev, v_dev = q.to(device), k.to(device), v.to(device) with torch.no_grad(): - with torch.npu.simulator(): + with torch.npu.TOGSimulator(): out_dev = compiled(q_dev, k_dev, v_dev, scale=scale) # ── CPU reference ────────────────────────────────────────────────────── diff --git a/tests/ops/conv/test_group_conv.py b/tests/ops/conv/test_group_conv.py index 165fbbae9..57dd10bad 100644 --- a/tests/ops/conv/test_group_conv.py +++ b/tests/ops/conv/test_group_conv.py @@ -2,7 +2,7 @@ import sys import torch import torch._dynamo -from pytorchsim.simulator.togsim import TOGSimulator +from pytorchsim.simulator.togsim import TOGSimProcess sys.path.insert(0, os.path.join(os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim"), "tests")) from _pytorchsim_utils import test_result diff --git a/tests/system/test_togsim_exit.py b/tests/system/test_togsim_exit.py index d0fa2c7a8..41dacef29 100644 --- a/tests/system/test_togsim_exit.py +++ b/tests/system/test_togsim_exit.py @@ -9,7 +9,7 @@ sys.path.insert(0, os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim")) from pytorchsim import config -from pytorchsim.simulator.togsim import TOGSimulator +from pytorchsim.simulator.togsim import TOGSimProcess REFUSAL = "[error] [TOGSim] TOG k/tog.so: work-item 0 (key 10) needs 49153 bytes in the spad at once" STUB = """#!/bin/sh @@ -54,7 +54,7 @@ def _raised(fn): def test_standalone_refusal_is_a_runtime_error(): with tempfile.TemporaryDirectory() as root, _logs_in(root): machine, handle, attribute = _checkout(root, 1) - said = _raised(lambda: TOGSimulator.run_standalone( + said = _raised(lambda: TOGSimProcess.run_standalone( handle, attribute, autotune_mode=True, config_path=machine, togsim_path=root)) assert said is not None and "status 1" in said and REFUSAL in said, said @@ -62,7 +62,7 @@ def test_standalone_refusal_is_a_runtime_error(): def test_session_refusal_is_a_runtime_error(): with tempfile.TemporaryDirectory() as root, _logs_in(root): machine, handle, attribute = _checkout(root, 1) - sim = TOGSimulator(config_path=machine, togsim_path=root) + sim = TOGSimProcess(config_path=machine, togsim_path=root) sim.launch_kernel(0, 0, handle, attribute) said = _raised(sim.shutdown) assert said is not None and "status 1" in said, said @@ -72,7 +72,7 @@ def test_session_refusal_is_a_runtime_error(): def test_session_that_ran_shuts_down_quietly(): with tempfile.TemporaryDirectory() as root, _logs_in(root): machine, handle, attribute = _checkout(root, 0) - sim = TOGSimulator(config_path=machine, togsim_path=root) + sim = TOGSimProcess(config_path=machine, togsim_path=root) sim.launch_kernel(0, 0, handle, attribute) assert _raised(sim.shutdown) is None diff --git a/tests/system/test_togsim_result.py b/tests/system/test_togsim_result.py index 0a5f1b29a..02a55faeb 100644 --- a/tests/system/test_togsim_result.py +++ b/tests/system/test_togsim_result.py @@ -7,13 +7,13 @@ sys.path.insert(0, os.environ.get("TORCHSIM_DIR", default="/workspace/PyTorchSim")) from pytorchsim import config -from pytorchsim.simulator.togsim import TOGSimulator +from pytorchsim.simulator.togsim import TOGSimProcess DATA = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data") def test_unit_table_rows(): - core, channels, avg_bw, wall, total = TOGSimulator.get_result_from_file( + core, channels, avg_bw, wall, total = TOGSimProcess.get_result_from_file( os.path.join(DATA, "togsim_tpuv6e.log")) units = core["units"]["Core [0]"] array = units[config.CONFIG_MACHINE.togsim_unit] @@ -31,7 +31,7 @@ def test_unfinished_log_has_the_same_shape(): with tempfile.NamedTemporaryFile("w", suffix=".log") as log: log.write("[info] Core [0] : Total_cycles: 3\n") log.flush() - assert TOGSimulator.get_result_from_file(log.name) == ({}, {}, 0.0, float("inf"), float("inf")) + assert TOGSimProcess.get_result_from_file(log.name) == ({}, {}, 0.0, float("inf"), float("inf")) if __name__ == "__main__":