Skip to content

v0.14.0 — KernelOperator fused kernel matmul, cached NKI handles, fp64 policy

Choose a tag to compare

@scttfrdmn scttfrdmn released this 03 Nov 20:48
· 71 commits to main since this release
v0.14.0
3ca948c

Validated on Trn2 (trn2.3xlarge, Neuron SDK 2.33.0, native TorchNeuron) — see trnsci/trnsci#35.

Headline: kernel_matmul / KernelOperator, a fused kernel-matrix product for matrix-free GP and kernel methods (#93, #102, #103), cached eager NKI handles, and the trnsci float64 policy with a dtype guard at the kernel boundary; cg_bsr and power_iteration_bsr gradients and from_scipy dtypes fixed.

Performance

  • Eager NKI kernel calls skip the per-call handle rebuild and the custom-op
    layer (same fix as trnblas#92).
    On the native path a trnsparse::
    custom-op call cost about 0.1 ms of host time before the kernel was queued,
    against 0.016 ms for aten. Most of it went to nki's Kernel.__call__,
    which rebuilds the torch handle on every call, plus the torch.library
    layer. dispatch._run / _launch and the direct keyed-op calls (keyed
    bsr_spmm, attention forward and backward, fused CG and power iteration,
    ShardedBSR / ShardedAttention) now call a torch_neuronx.wrap_nki
    handle built once per kernel, with the op body's int() / tuple() /
    float() conversions of the static arguments. On trn2 (LNC=2), a
    256x256x128 spmm_dense launch drops from 0.126 to 0.036 ms of issue time
    (e2e 0.201 to 0.124 ms), a keyed bsr_spmm from 0.255 to 0.157 ms e2e, and
    cg_bsr_fused n=256 from 1.36 to 1.19 ms. Results are bit-identical.
    torch.compile, requires-grad, int64 and tensor-subclass inputs, and the
    composite bsr_attn / bsr_attn_bwd ops keep the custom op, as does
    the screened-tile op (screened_tiles_keyed, #61) for now. This is the
    same handle cache that kernel_matmul launches use (keyed there by
    operand shapes, one handle shared by every row block and core), so
    TRNSPARSE_NKI_EAGER_HANDLE=0 turns both off;
    scripts/bench_eager_handle.py measures it.

Added

  • kernel_matmul / KernelOperator: fused kernel-matrix product
    K(X, Y) @ V that never forms K
    (#93, for trnsci/trnsci#109). RBF and
    Matern-1/2, 3/2, 5/2; per-dimension lengthscales; noise * V on the
    square operator. One NKI launch per application: squared distances as a
    TensorEngine matmul on augmented coordinates into PSUM, the kernel
    function on ScalarE straight from PSUM, the product with V on the
    TensorEngine. Coordinates are augmented and transposed on chip
    (nl.load + nisa.nc_transpose); tile loops are rolled
    (nl.fori_loop), so trace and compile time do not grow with n; ragged
    n, m and R are handled in the kernel. Both physical cores at LNC=2 with
    the same control flow on each, and bit-identical results at LNC=1 and
    LNC=2. Hyperparameters are a tensor argument (aws-neuron-sdk#1454).
    Eager launches use a cached torch_neuronx.wrap_nki handle (the
    trnblas#92 pattern). CPU tests: PyTorch path against float64
    torch.cdist; nki.simulate at LNC=1/2, MLIR verify and (with
    neuronx-cc) NEFF compile with NKI allocation at LNC=1/2.
    benchmarks/bench_kernel_matmul_trn2.py measures kernel entries/s
    against aten on the device and the host CPU at 2 threads and all vCPUs.
    tile_mask is reserved and raises for now.
  • kernel_matmul: row blocks spread across all visible logical
    NeuronCores
    (#102). On trn2.3xlarge at LNC=2 (neuron:0..3, with
    NEURON_RT_VISIBLE_CORES=0-3) a row-blocked product issues its blocks
    round-robin over the cores. The block count rounds up to a multiple of
    the core count (kmv_block_rows(..., parts=k); 20 blocks of 53248 rows
    on 4 cores at n = m = 2^20), so each core gets the same number. Y, V and
    params are staged through the host once and placed on each core before
    any kernel is queued. Launches are issued asynchronously from the calling
    thread (NKI tracing stays on one thread, aws-neuron-sdk#1453) and
    gathered in row order on the operands' device, bit-identical to one
    core. TRNSPARSE_KMV_CORES: auto (default: every visible core when
    n * m exceeds the 6e10-entry block budget, else one), all, or an
    int. TRNSPARSE_KMV_THREADS=1 is a fallback that issues each core's
    blocks from a worker thread, after the first block per core has been
    launched on the calling thread. Target: n = 2^20 from about 42 s to about
    11 s per apply on 4 cores. CPU stand-in tests cover block-to-core
    assignment, per-core placement and the gather (bitwise against single
    core). A neuron test compares multi-core with single-core bitwise and
    skips below 2 visible cores.

Changed

  • kernel_matmul: about 70% fewer instructions per launch (#103). The
    Trn2 profile on #93 showed the kernel issue-bound: 41% of a launch with
    no engine active. The @v product now takes V's tile as the stationary
    operand and the kernel tile as the moving one. That makes one
    nc_matmul per 128 columns of V over all 512 X points of a tile, where
    it was four (one per 128-row chunk, kernel tile stationary). The
    accumulator, out^T, is now one PSUM bank per 128 columns, against four,
    and is transposed back (nisa.nc_transpose) once per output block.
    The freed PSUM holds a ring of distance tiles, so a loop body is no
    longer capped at 4 Y tiles. Each body loads its V rows in one DMA,
    against one per Y tile. The body size now defaults to kmv_group(m):
    about sqrt(m / 128) Y tiles, from 4 to 16 (TRNSPARSE_KMV_GROUP still
    overrides it, 1 to 32).

    • Instructions per launch, n = 131072, LNC=2, both physical cores,
      counted from the compiled NEFF: 11.5M before, 3.5M now at group
      16; 6.2M with the old body of 4. That is 44 against 13 instructions per
      128 x 512 tile per core.
    • Summation order: with a body of 4 Y tiles (m < 3200 by default,
      or TRNSPARSE_KMV_GROUP=4) the result is bit-identical to 0.13.0.
      That is checked in the simulator, with its matmul summed in
      contraction order like the TensorEngine; the device check is on the
      PR. Larger bodies change where the PSUM partial sums are split, so the
      bits change.
    • Error against float64 goes from about g + m/(128 g) fp32 roundings
      to its minimum: at m = 131072 the max relative error drops from
      9.0e-7 to 5.2e-7 (simulator, rbf and Matern-5/2, R = 1 and 33).
    • Bit-identical at LNC=1 and LNC=2, across row blocks and across cores,
      as before: the body size depends on m only.
    • The simulator tests now run nc_matmul as a sum in contraction order
      (numpy's BLAS rounds a column differently with the moving operand's
      width). So the LNC=1 against LNC=2 and row-blocked checks are bitwise
      at every d and every ragged tail. The ragged tails were tolerance-only
      before.
    • benchmarks/bench_kernel_matmul_trn2.py --dump DIR saves the results,
      to compare two checkouts with --compare.
  • float64 under auto now computes in torch at float64 accuracy
    (previously cast to fp32 on the NKI path)
    — the trnsci suite fp64
    policy (#84). Trainium computes float64 at fp32 precision, so no kernel
    can give a float64-accurate result. For spmm, bsr_spmm,
    screened_spmm, block_sparse_attention_tiled (forward and backward),
    cg_bsr (through bsr_spmm), cg_bsr_fused and
    power_iteration_bsr_fused, a float64 value operand (and complex128 in
    bsr_spmm, whose complex path runs as real kernel launches):

    • under set_backend("auto") (the default) takes the PyTorch path that
      set_backend("pytorch") takes, at float64 accuracy, and no kernel runs
      (the fused solvers take their host path);
    • under an explicit set_backend("nki") is cast to fp32 (complex64) for
      the kernel as before, now with a one-time UserWarning per op saying
      precision is reduced to fp32;
    • under TRNSPARSE_REQUIRE_NKI=1 raises NotImplementedError (on either
      backend; this takes precedence over the explicit-nki cast).

    The result dtype always equals the pytorch backend's for the same inputs,
    including bf16 / fp16 and mixed-dtype promotion; a kernel result computed
    in fp32 is cast to that dtype. Callers of 0.2.0 through 0.13.0 who
    relied on float64 inputs running on the kernels under auto now get
    torch (more precise; on the host or device aten instead of the kernel):
    pass float32 operands, or select set_backend("nki"), to keep the
    kernel. float64 validation runs under REQUIRE_NKI must pass fp32 operands
    (or call the autograd Functions directly, as the hardware gradchecks do).
    Lands in 0.14.0. screened_spmm decides on A and B; a float64 bound
    vector diag_integrals alone does not change the route. See
    docs/architecture.md, "Precision and dtypes".

    float64 on the neuron device runs on the host under auto. Device
    aten computes float64 at fp32 precision as well (measured on Trn2), so
    the torch path alone does not give float64 accuracy for device-resident
    data. When a float64 / complex128 operand of spmv, spmm,
    spmv_symmetric, bsr_spmm, screened_spmm,
    block_sparse_attention_tiled (forward and backward), cg_bsr,
    chebyshev_bsr, richardson_bsr, power_iteration_bsr or the
    jacobi_preconditioner_bsr preconditioner lives on a neuron device
    (dense, or a CSR / COO / BSR matrix's values), the operands are copied to
    the host, host torch computes at float64, and the result returns to the
    dense operand's device in float64, with one UserWarning per op ("float64
    on the neuron device is computed on the host for float64 accuracy (device
    arithmetic is fp32); pass float32 to stay on device").
    TRNSPARSE_FP64_ON_DEVICE=1 keeps device aten (fp32 precision, no
    copies). Host-resident float64, explicit nki and the pytorch backend
    are unchanged; the fused solvers already ran float64 on the host.
    TRNSPARSE_REQUIRE_NKI=1 raises for float64 / complex128 on the neuron
    device
    at every public op (backends auto and nki, also with
    TRNSPARSE_FP64_ON_DEVICE=1), before any host copy or kernel. Before, the
    routes with no kernel (CSR spmv, spmv_symmetric, spmm, the Jacobi
    preconditioner) ran device aten at fp32 precision with no error under
    REQUIRE_NKI and auto (Trn2 conformance: test_spmv[float64-*] rel err
    1e-8..2e-7 against the 1e-10 tolerance).

    kernel_matmul / KernelOperator (#93, new in this release) follow the
    same rules through dispatch._fp64_route: under REQUIRE_NKI float64 now
    raises NotImplementedError (it raised TypeError), and the explicit-nki
    fp32 warning fires once per op (it fired on every call). Integer, bool and
    complex inputs on the NKI path take the PyTorch path, as the pytorch
    backend does (they raised TypeError), or raise NotImplementedError
    under REQUIRE_NKI. Device-resident float64 under auto: kernel_matmul
    is guarded like the other ops, and a float64 KernelOperator bound for
    the neuron device is built and applied on the host (one UserWarning),
    returning each product on V's device.

Fixed

  • No NKI kernel is reached with an operand dtype it does not take (one
    guard at the kernel boundary; trnsci/trnsci#35, the class of #78 and #79).
    At each entry (spmm, bsr_spmm, screened_spmm,
    block_sparse_attention_tiled forward and backward), integer and bool
    values, and complex values except in bsr_spmm (real kernel launches,
    #78), now take the PyTorch path that set_backend("pytorch") takes, or
    raise NotImplementedError under TRNSPARSE_REQUIRE_NKI. Before, they went
    into the fp32/bf16 kernels on the NKI and auto backends: complex operands of
    spmm / screened_spmm reached the kernel unchanged, the static attention
    kernels cast complex Q/K/V to fp32 (imaginary part dropped), the static
    bsr_spmm and attention kernels cast integers to fp32 and back, and
    REQUIRE_NKI failed with whatever error the kernel raised. float64 follows
    the fp64 policy below (#84); fp32, bf16 and fp16 are unchanged. Every
    launch now also checks a per-kernel, per-operand dtype table itself
    (_KERNEL_OPERAND_DTYPES: the native op table, _run on the XLA path and
    the simulator) and raises TypeError naming the op and dtypes, so a future
    wrapper without the entry check cannot hand a kernel an unsupported dtype.
    The eager-handle fast path (_native_call, and _kmv_launch for
    kernel_matmul, whose kernels kmv_self / kmv_cross / kmv_selfblk
    are now in the table as fp32-only) skips the guarded op body, so it checks
    the table itself before the launch.
    Affects every release with NKI kernels, through 0.13.0.

  • spmm with a 1-D B raised on the NKI path (#105). Affected
    0.2.0–0.13.0: under set_backend("nki") / "auto" on a Neuron host,
    spmm(A, b) with a vector b failed in the NKI GEMM wrapper with
    ValueError: not enough values to unpack (expected 2, got 1), while the
    pytorch backend returns A @ b of shape (m,). The vector now goes to the
    kernel as one column and the result is squeezed back. Matrix B is
    unchanged.

  • kernel_matmul no longer hits the Neuron runtime's 30 s execution
    timeout at n >= 1e6
    (#100). One launch at n = 2^20, R = 33 takes about
    40 s at LNC=2 and 80 s at LNC=1 on Trn2 and failed with NRT status 5.
    Products above 6e10 kernel entries (n * m; the rate is flat in R, so
    the budget is not weighted by d + R) now run as host-side row blocks of
    X: the fewest launches the budget allows, split into equal blocks of a
    multiple of 1024 rows (19 launches of 55296 rows at n = m = 2^20, about
    2.2 s each at LNC=2 and 4.5 s at LNC=1), R kept whole. Large blocks keep
    the fixed per-launch cost (~75 ms, staging Y) near 1% of the run; Y, V
    and params are placed on the device once for all blocks. The ragged last
    block is zero-padded (less than 1024 rows per block), so every launch has
    one shape, one compile and one cached wrap_nki handle (now keyed per
    kernel and shape). Blocks of the square operator use a new
    _kmv_selfblk_kernel (custom op trnsparse::kmv_selfblk) that adds
    noise * V for the block's rows in the same fused epilogue, so blocked
    results are bit-identical to one launch. Below the budget nothing
    changes. TRNSPARSE_KMV_BLOCK_WORK overrides the budget.

  • cg_bsr raised UnboundLocalError with max_iter=0 or on a first-step
    breakdown, and reported iters=max_iter on any breakdown
    (#71, #86).
    r_norm was only assigned inside the loop, so max_iter=0, A p = 0
    (e.g. a zero matrix) or p . A p = 0 at k=0 (an exact x0 with tol=0)
    raised. A later breakdown (|p . A p| < 1e-30, e.g. after exact
    convergence with tol=0) returned iters = max_iter (500 or 1000 for a
    1-2 step solve). cg_bsr now returns the number of steps actually taken
    and the residual of the returned x; max_iter=0 gives
    (x0, 0, ||b - A x0|| / ||b||). Solutions are unchanged. Affects 0.3.2
    through 0.13.0.

  • power_iteration_bsr gave silently wrong gradients (#96), as
    cg_bsr did (#70). The norms were taken with .item(), so autograd
    differentiated the iterations with frozen normalisation instead of the
    eigenvector, and v0 received a spurious gradient. The eigenvector now
    differentiates as the exact unit eigenvector of A (implicit
    differentiation of A v = lam v, ||v|| = 1): backward solves a dense
    bordered (N+1) x (N+1) system, so it costs O(N^3), and gives
    grad_A = -w v^T on the stored blocks. v0 gets no gradient, the
    eigenvalue stays a Python float, and backward raises NotImplementedError
    for complex A. Forward values are unchanged. Affects 0.3.2 through 0.13.0.

  • from_scipy downcast float64 and integer matrices to float32 (silent,
    #69). Every real scipy matrix was stored as float32 (float64 rounded to
    ~3e-8 relative error; int64 exact only up to 2^24) and complex128 as
    complex64, which contradicted the "zero-copy" description in
    docs/migration_scipy.md. The values now keep the scipy dtype, and for CSR
    input share memory with sp_matrix.data. Affects 0.1.1 through 0.13.0.
    Behaviour change: float64 scipy input now gives a float64 matrix, so
    mixing it with float32 vectors (spmv(from_scipy(M64), x32)) raises the
    usual torch dtype-mismatch error; cast one side (M.astype(np.float32)).
    docs/migration_scipy.md no longer refers to a nonexistent .to_scipy().

  • cg_bsr gave silently wrong gradients (#70). The CG step sizes were
    taken with .item(), so autograd differentiated a frozen-coefficient
    polynomial in A applied to b, not the solve: with b along an
    eigenvector (one-step convergence) b.grad was ~20% off A^{-1} g, and
    A.blocks.grad had the same problem. cg_bsr now differentiates as the
    exact solve (implicit differentiation, like torch.linalg.solve):
    backward runs a second CG solve A lam = grad_x with the same
    tol / max_iter / M, giving grad_b = lam and
    grad_A = -lam x^H on the stored blocks. x0 and M no longer receive
    gradients. Forward values are unchanged. Affects 0.3.2 through 0.13.0.

  • cg_bsr_fused / power_iteration_bsr_fused gave wrong results for
    complex, integer and bool inputs
    (silent, #85). Both pack A and the
    vectors into real float tiles, so on every backend (including
    set_backend("pytorch")) a complex A or b lost its imaginary part, and an
    integer or bool b gave a truncated x of b's dtype. They (and
    prepare_cg_bsr) now raise TypeError for a non-real-float A.blocks,
    b, x0 or v0, before any backend runs. Affects 0.11.0 through 0.13.0.