CPU_SIM

CPU_SIM is a CPU-based backend designed for execution on CPU-only systems. It has some limitations and differences comparing to NPU backends at this moment:

  • PTO instructions execute synchronously in each CPU worker. Supported synchronization and communication operations, including the TileData TPUSH/TPOP/TFREE FIFO flow, are simulated with CPU synchronization primitives.
  • Specific memory model to mimic NPU memory (see below)
  • Multithreading support is not complete. Memory access in Tile objects is not synchronized across threads, so tiles should not be shared across threads except through supported communication operations. Tile lazy allocation is also not synchronized.

Enabling CPU_SIM

You may enable CPU backend (CPU_SIM) by setting __CPU_SIM compiler definition. In this case, programs can be built using standard CPU-targeted compiler (gcc or clang).

Note, for compatibility with NPU-based programs, some Ascend-specific functions are implemented for CPU platform in include/pto/common/cpu_stub.hpp. Including this file into existing program already using NPU-backend will make it compilable for CPU with only minor changes. You may not include this file, but in this you'll have to remove all functions like aclInit, aclrtSetDevice from your code or replace them with corresponding CPU-based code if needed.

The CPU stubs for aclInit, aclrtSetDevice, and aclrtCreateStream initialize the CPU_SIM runtime, retain the selected non-negative device ID, and create a lightweight host stream handle. Runtime environment variables are read by aclInit or by the first API that lazily initializes the runtime, whichever occurs first.

CPU_SIM memory model

Generally, all tiles memory in CPU_SIM is allocated in system memory (contrary to NPU backend where memory is divided into host and device memory, and device itself has several different memory locations). But to make CPU_SIM memory model closer to NPU, it simulates separate memory locations corresponding to NPU architecture.

CPU_SIM memory model allocates following memory locations for each thread: UB, L1, L0A, L0B, L0C. Each of this locations is basically pre-allocated array of the size corresponding to simulating NPU architecture. TASSIGN operation uses one of these arrays to assign some memory chunk from it to the tile. I.e., if TASSIGN is called for the tile with Loc==Mat and offset 10, it will assign memory starting from the L1[10] to that tile.

Selecting the simulated architecture

A2A3 and A5 identify the simulated target, not the NPU installed on the host. CPU_SIM does not need an NPU to run. The selection controls memory configuration and architecture-aware instruction paths such as TROWSUM; it does not mean that every CPU instruction has separate, bit-exact implementations for both architectures.

  • To select the default for subsequently initialized thread-local memory models, call pto::NPUMemoryModel::SetDefaultArch(pto::NPUArch::A5) once during startup, before any thread uses the model. Without this call, the default is pto::NPUArch::A2A3.
  • To initialize only the calling thread explicitly, use pto::NPUMemoryModel::Instance().Initialize(pto::NPUArch::A5) before binding/accessing its Tiles.
  • For both default selection and calling-thread initialization, use pto::NPU_MEMORY_INIT(pto::NPUArch::A5) once at startup, before other threads use the model. This helper calls both SetDefaultArch and Initialize; it does not reconfigure already initialized models in other threads. Calling NPU_MEMORY_INIT() without an argument explicitly resets the default and initializes the calling thread to A2A3.
  • SetDefaultArch does not reconfigure already initialized thread-local instances. Do not change the default concurrently with execution or reinitialize a memory model while Tiles still reference its storage.

External simulator integrations must select the target before running kernels. An integration's a5sim name alone is not an architecture selector inside pto-isa. See include/pto/cpu/NPUMemoryModel.hpp and include/pto/cpu/TAssign.hpp.

Memory capacity overrides

The simulated memory capacities can be overridden with the following environment variables. Values are specified in bytes and must be positive integers:

  • PTO_CPU_SIM_UB_BYTES
  • PTO_CPU_SIM_L1_BYTES
  • PTO_CPU_SIM_L0A_BYTES
  • PTO_CPU_SIM_L0B_BYTES
  • PTO_CPU_SIM_L0C_BYTES

By default, CPU_SIM provides at least 512 KiB of UB scratch space. Set the variables before initializing the memory model.

When __PTO_AUTO__ is defined, regular Tile objects support lazy fallback storage in CPU_SIM. If a tile has not been bound by TASSIGN, its first data() access allocates private host storage. Without __PTO_AUTO__, regular tiles must be bound explicitly before access.

Fallback storage is allocated from host memory regardless of the tile location and does not overlap the simulated UB, L1, L0A, L0B, or L0C buffers. Use TASSIGN when the simulated memory location, offset, aliasing, or communication behavior matters. Tile abstractions that do not provide lazy fallback storage must still be explicitly bound.

To avoid concurrent first access in __PTO_AUTO__ mode, the CPU_SIM implementation of TMATMUL materializes the backing storage for the destination, optional accumulator, and both matrix input Tiles on the caller thread before launching parallel workers. The TMATMUL_MX path also materializes both scale Tiles.

To summarize:

For regular Tile objects, use one of these strategies:

  • Direct memory assignment: Every tile should have corresponding TASSIGN operation call to assign memory directly. Proper offset should be calculated manually and provided to TASSIGN operation.
  • Lazy fallback storage: Define __PTO_AUTO__, then leave the tile unbound and let its first data() access allocate private host storage.

Direct assignment models the configured NPU memory regions. Lazy fallback storage is intended for private CPU-side correctness testing and does not model a specific on-chip address.

Supported behavior and backend differences

  • CPU_SIM TROWSUM selects its reduction and validation path from the calling thread's initialized architecture. Both paths accept but do not access tmp. See TROWSUM for types, layouts, and numerical limits, and TROWSUM implementation notes below for the computation.
  • CPU_SIM TADD and TABS accept independently typed operand Tiles when their element types and runtime valid shapes match. This includes mixing static and dynamic ValidRow/ValidCol template arguments. Each operand is indexed using its own Tile layout and physical shape; a runtime valid-shape mismatch triggers an assertion.
  • CPU_SIM implements both TCI(dst, start) and TCI(dst, start, tmp). The three-argument form accepts but does not access tmp, and otherwise has the same ascending or descending sequence semantics as the two-argument form. Keep the target-specific scratch allocation required by the NPU backend when writing portable kernels.
  • CPU_SIM implements all four TCVT overloads, with or without an explicit scratch Tile and SaturationMode. FP32-to-FP8 E4M3/E5M2 conversions honor rounding and saturation; CAST_NONE and unsupported FP8 CAST_ODD fall back to nearest-even, matching A5. See TCVT for format and overflow semantics. Scratch-Tile forms accept but do not access tmp and match the corresponding no-scratch conversion. The default CPU_SIM saturation mode is SaturationMode::OFF; portable kernels must retain any NPU scratch allocation.
  • TSTORE from a TileType::Vec tile with SLayout::NoneBox picks its GM traversal from the tile's own layout in one case, the way the hardware DMA does: the single-row or single-column pairing that TSTORE allows on top of matching ND/DN/NZ layouts. A ColMajor [N, 1] tile stored through an ND GlobalTensor, or a RowMajor [1, N] tile stored through a DN one, lands as a contiguous vector instead of one element per the other axis' stride. Every other combination, including a ColMajor tile wider than one column, still takes its mapping from the GlobalTensor layout. TLOAD needs no such case: TileType::Vec loads only accept matching layouts.
  • TileData TPUSH/TPOP/TFREE use a host-side TPipe FIFO model. The model waits for free slots and ready data. For Direction::DIR_BOTH, C2V and V2C have independent rings, each with SlotNum slots and separate payload, cursor, and synchronization state. The model coordinates split lanes through the simulated block/subblock context. TileData payloads stay in host-owned slot storage even if generated code supplies a non-null NPU GM workspace; CPU_SIM does not access that workspace for this flow. TFREE participates in the CPU FIFO release protocol and releases the corresponding direction; it is not the A2A3 TileData no-op. For TileSplitAxis::TILE_NO_SPLIT, a TileData TPUSH lays the slot payload out with the shape of the window it actually transfers, that is the pushed tile's valid shape, so pushing a narrow view of a wider tile stays row-aligned with the tile the consumer pops it into; the split axes keep using the producer tile's declared shape. The public GlobalData TALLOC/TPUSH/TPOP/TFREE flow is not currently available in CPU_SIM.
  • The Tile-vs-Tile TCMPS overload compares src0[i,j] with src1[i,j] in CPU_SIM. This matches A5 and differs from the A2/A3 scalar-broadcast behavior. The scalar overload has the usual scalar comparison semantics.
  • CPU arg-reduce implementations (TCOLARGMIN, TCOLARGMAX, TROWARGMIN, and TROWARGMAX) accept integral, half, bfloat16_t, and float source elements. Index outputs must use int32_t or uint32_t; the temporary tile argument is unused by CPU_SIM.
  • CPU_SIM supports the AIV paths of TGATHER and TSCATTER, but does not provide a functional CollEngine::CCU path. The CPU headers include deferred compile-time rejection for unsupported CCU calls; use the A5 NPU backend.
  • SYNCALL, including its workspace-bearing Soft forms, is currently a compatibility no-op in CPU_SIM. It must not be used as a CPU worker barrier. Use a synchronization or communication operation with an implemented CPU path when workers need to exchange data.
  • Simulator integrations can provide subblock-ID and shared-TPipe-state callbacks through pto::cpu_sim::register_hooks. If callbacks are not registered directly, CPU_SIM also resolves the pto_sim_get_subblock_id and pto_sim_get_pipe_shared_state symbols from the host process.

A2/A3 FFTS cross-core events

The normal <pto/pto-inst.hpp> CPU include path exposes pto::getFFTSMsg, ffts_cross_core_sync, wait_flag_dev, and set_ffts_base_addr through ffts.hpp. These are the public interfaces used by the NPU A2/A3 implementation. CPU_SIM implements the signal and wait operations directly under these public names; CCE owns the hardware builtins. The CPU signatures are:

Interface CPU behavior
uint16_t pto::getFFTSMsg(uint16_t mode, uint16_t eventId, uint16_t baseCount = 1) Validate and encode a message for the supported protocol below.
void ffts_cross_core_sync(int pipe, uint16_t message) Publish a notification from the explicitly selected AIC or AIV role; ignore pipe.
void wait_flag_dev(int eventId) Wait for and consume the matching notification for the selected role.
void set_ffts_base_addr(uint64_t address) Accept the hardware address without accessing it or resetting CPU event state.

CPU_SIM provides no compatibility entry points for compiler-private FFTS builtins. Update kernel generators to emit the public interfaces, then regenerate and rebuild affected kernels. Recompiling old generated source or regenerating it with a generator that still emits private names will fail. The matching interface names do not imply support for every NPU FFTS mode or hardware pipeline timing; CPU support is limited to the protocol and behavior below.

Compile AIC kernels with __DAV_CUBE__ and AIV kernels with __DAV_VEC__, in addition to __CPU_SIM. Exactly one role must be selected. When neither role is specified, generic CPU headers enable both PTO_COMPILE_CUBE and PTO_COMPILE_VEC for library code. FFTS signal/wait rejects a missing or ambiguous explicit kernel role. Generic CPU simulation code can check PTO_COMPILE_CUBE / PTO_COMPILE_VEC after including <pto/common/arch_macro.hpp>. The CPU include structure follows the NPU A2/A3 TSync.hpp, which also provides FFTS helpers. TSYNC is no longer a public instruction; the internal CPU TSYNC_IMPL() remains empty, while the NPU implementation uses pipe_barrier in manual mode.

  • Supported protocol: mode 2, base count 1, event IDs 0–15, AIV lane IDs 0 or 1. Invalid protocol arguments throw std::invalid_argument; missing shared storage or a missing or ambiguous kernel role throws std::runtime_error. Credit counter overflow throws std::overflow_error; an overflowing AIC broadcast leaves both lane counters unchanged.
  • An AIC signal publishes one credit to each AIV lane. An AIV wait consumes its lane's credit; an AIV signal publishes one credit from that lane to the AIC. An AIC wait consumes one credit from each lane, so two signals from the same lane cannot substitute for the other lane. Credits accumulate across repeated signals.
  • Release/acquire synchronization makes producer data visible after the matching wait. CPU operations execute synchronously; the pipe argument is ignored. Waiting polls and yields until a credit arrives, with no internal deadline. Any timeout must be supplied by the caller/runtime.
  • set_ffts_base_addr accepts but ignores the hardware address. It neither accesses MMIO nor resets events; CPU event storage comes from the runtime.

Shared storage is selected in this order: the callback injected by pto::cpu_sim::register_hooks, then the process-visible pto_sim_get_pipe_shared_state symbol, then (only if neither is available) pto_cpu_sim_get_shared_storage. A selected callback returning null is an error, not a request to try another provider. There is no library-local fallback pool.

The numeric-key callbacks use a separate FFTS key namespace from TPipe. They must return the same stable, aligned, initially zero-filled allocation of at least the requested size for a given key and device/group, shared by one AIC worker and its two AIV workers. Each role/lane has one producer; concurrent AIC publishers for the same group are not supported. The string-key provider uses pto-ffts-<task_cookie>-<block_idx>-<event_id>; it must additionally isolate devices/runs. The runtime must keep storage alive until all participants finish, and reset or replace it between runs with workers stopped. ISA initializes event counters on first use, not at each task or base-address call. AIV lane identity comes from the existing get_subblockid() hook/context path and must identify the calling lane correctly. Configure hooks and context before executing kernels.

Run python3 tests/run_cpu.py --testcase ffts --clean for the cross-library regression. Its 12 cases cover injected and dynamically resolved numeric-key hooks, queued events, two-lane joins, consumption, device/group/event isolation, runtime reset, invalid arguments, a null storage callback, and a three-slot producer/consumer pipeline. The AIC/AIV test libraries call ffts_cross_core_sync, wait_flag_dev, and set_ffts_base_addr through the public CPU include path. Run python3 tests/run_cpu.py --testcase ffts_hooks --clean for 9 additional cases covering the string-key fallback, task/block isolation, injected-provider precedence, null providers, kernel-role validation, and overflow without counter wraparound or a partial AIC broadcast. The suites use separate executables: ffts_hooks omits the process-visible numeric-key provider so that the lower-priority string-key fallback can be exercised.

TROWSUM implementation notes

See TROWSUM CPU_SIM implementation checks for type, layout, and valid-region constraints. The following describes the CPU implementation, not additional NPU interface constraints.

  • The A5 floating-point path uses rowSumTree with consecutive 256-byte groups: 64 lanes for float, 128 for half. Each group uses an adjacent-pair binary tree; unused tail lanes are zero-filled without reading source padding. Group sums are accumulated in increasing column order from positive zero. Every tree addition and group accumulation is cast back to the element type, including half rounding between groups.
  • The A5 integer path uses rowSumModular with unsigned modular arithmetic to avoid signed-overflow undefined behavior. int16_t uses a 32-bit accumulator followed by low-16-bit truncation; other supported integers wrap at their own width. Signed outputs preserve the resulting bit pattern without saturation.
  • A2A3 retains the legacy CPU accumulation loop using TypeSum<TileDst>: half/bfloat16_t outputs accumulate in float and convert on store; other outputs use their own type. This path uses neither the A5 reduction tree nor its unsigned modular-overflow handling. The row-major loop retains vectorization hints: Clang may reorder floating-point additions even without -ffast-math. Strict left-to-right accumulation and bit-identical results across compilers are not guaranteed.
  • On toolchains without native BF16, bfloat16_t may alias half; that placeholder follows the half path and is not BF16 simulation.
  • CPU reduction entry points and execution functions carry valid-row and valid-column counts as uint32_t to avoid 16-bit truncation. This does not support arbitrary 32-bit sizes: Tile dimensions and Numel still use int, and layout, representable element counts, and available storage constraints still apply.
  • The calling thread ensures its memory model is initialized before selecting the architecture. Internal row-parallel workers receive that decision by value rather than reading their own thread-local default. This does not initialize unrelated caller threads or simulated-core workers. See Multicore execution for thread configuration.

The A5 implementation models a specific reduction order, not full bit-exact A5 hardware behavior: NaN payloads, subnormal/flush-to-zero behavior, and other host-versus-device differences are not established as equivalent. The A2A3 compatibility path does not promise bit-exact hardware behavior either. Do not enable reassociation options such as -ffast-math when relying on the A5 reduction order.

Multicore execution

Simulated-core workers are separate from an instruction's internal row-parallel workers. For example, TROWSUM uses the compile-time controls in include/pto/cpu/parallel.hpp; PTO_CPU_SIM_NUM_CORES does not configure that group of workers. Internal row parallelism requires at least two rows and two available threads, and rows * cols >= PTO_CPU_PARALLEL_THRESHOLD_ELEMS (default 16384). PTO_CPU_MAX_THREADS is a compile-time cap (0 uses hardware concurrency), not a runtime environment variable.

pto::cpu_sim::LaunchKernelMultiCore launches one CPU worker for each active simulated core and initializes the worker's block and subblock execution context. The default configured core count is 4 and can be changed with PTO_CPU_SIM_NUM_CORES. Set this environment variable before CPU_SIM runtime initialization.

The launch options can specify the requested core count, total work items, work quantum, subblocks per block, and an explicit block count. get_block_idx(), get_subblockid(), and get_subblockdim() reflect the worker's launch context, and get_coreid() aliases get_block_idx(). get_block_num() returns the configured PTO_CPU_SIM_NUM_CORES value; it can be greater than the active block count when a launch is explicitly limited or reduced to fit its work items.

Instruction tracing

Instruction tracing is disabled at build time by default. For CPU STs, enable it with:

python3 tests/run_cpu.py --trace-mode

This sets the PTO_CPU_SIM_TRACE_MODE CMake option. A trace-enabled build records instruction opcodes, block indexes, subblock IDs, sequence IDs, tile operands, and scalar operands. Within each launch, group records by (block_idx, subblock_id) and use sequence_id for the order within that worker. With tracing enabled and KernelLaunchOptions::write_trace_files set to true (the default), LaunchKernelMultiCore writes the combined JSON Lines trace to:

cpu_sim_traces/<kernel_name>/launch_<id>/trace.jsonl

The following environment variables control tracing at runtime:

  • PTO_CPU_SIM_TRACE_ENABLE: supplies the default collection setting during runtime initialization. Set to 0 or false to disable tracing unless an explicit API setting overrides it.
  • PTO_CPU_SIM_TRACE_DIR: override the default cpu_sim_traces output directory.

Set these variables before CPU_SIM runtime initialization. The trace APIs in include/pto/cpu/trace.hpp can also be used to reset, inspect, copy, or serialize the current thread's instruction records.

Run the focused tracing regressions with python3 tests/run_cpu.py --testcase ttrace --trace-mode. They check instruction operands, environment defaults, explicit settings before and after initialization, and separate trace files for repeated launches with multiple blocks and subblocks. The same testcase without --trace-mode also verifies computation with tracing compiled out.

For a standalone CPU example that needs no CANN runtime:

cmake -S kernels/custom/fused_add_relu_mul -B build/fused_trace \
  -DPTO_CPU_SIM_STANDALONE=ON -DPTO_CPU_SIM_TRACE_MODE=ON \
  -DCMAKE_BUILD_TYPE=Release
cmake --build build/fused_trace --parallel 2
PTO_CPU_SIM_NUM_CORES=4 PTO_CPU_SIM_TRACE_ENABLE=1 PTO_CPU_SIM_TRACE_DIR=build/fused_trace/traces \
  build/fused_trace/fused_add_relu_mul_cpu_sim --functional-only

This validates basic, double-buffered, and large-tile kernels, including partial tiles, without running the performance benchmark. Each launch produces a separate trace.jsonl file. For regression coverage, run this functional example with tracing enabled and the ttrace regressions with tracing compiled both in and out. The example checks numerical results; the ttrace regressions check trace records and file export.

An external runtime that calls kernels directly must compile them with PTO_CPU_SIM_TRACE_MODE=1 and manage ResetInstructionTrace() / DumpInstructionTraceJson() on the executing thread. Calling a kernel directly does not invoke LaunchKernelMultiCore or automatically export a trace. SetInstructionTraceEnabled(bool) controls collection and, when write_trace_files is enabled, automatic launch export in a trace-enabled build; IsInstructionTraceEnabled() reports the current setting. An explicit API setting overrides the environment default and survives runtime initialization, including when set before the first launch. Set this process-wide option before starting a launch or between launches. It cannot enable tracing in a build compiled with tracing disabled. The build-time constant kInstructionTraceEnabled reports whether tracing was compiled in. For direct kernel calls, the environment default is applied only if the external runtime initializes the CPU_SIM runtime; alternatively, set collection explicitly with SetInstructionTraceEnabled(bool).