Repository navigation
v0.14.0 — KernelOperator fused kernel matmul, cached NKI handles, fp64 policy
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 atrnsparse::
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'sKernel.__call__,
which rebuilds the torch handle on every call, plus thetorch.library
layer.dispatch._run/_launchand the direct keyed-op calls (keyed
bsr_spmm, attention forward and backward, fused CG and power iteration,
ShardedBSR/ShardedAttention) now call atorch_neuronx.wrap_nki
handle built once per kernel, with the op body'sint()/tuple()/
float()conversions of the static arguments. On trn2 (LNC=2), a
256x256x128spmm_denselaunch drops from 0.126 to 0.036 ms of issue time
(e2e 0.201 to 0.124 ms), a keyedbsr_spmmfrom 0.255 to 0.157 ms e2e, and
cg_bsr_fusedn=256 from 1.36 to 1.19 ms. Results are bit-identical.
torch.compile, requires-grad, int64 and tensor-subclass inputs, and the
compositebsr_attn/bsr_attn_bwdops keep the custom op, as does
the screened-tile op (screened_tiles_keyed, #61) for now. This is the
same handle cache thatkernel_matmullaunches use (keyed there by
operand shapes, one handle shared by every row block and core), so
TRNSPARSE_NKI_EAGER_HANDLE=0turns both off;
scripts/bench_eager_handle.pymeasures 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 * Von 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 cachedtorch_neuronx.wrap_nkihandle (the
trnblas#92 pattern). CPU tests: PyTorch path against float64
torch.cdist;nki.simulateat LNC=1/2, MLIR verify and (with
neuronx-cc) NEFF compile with NKI allocation at LNC=1/2.
benchmarks/bench_kernel_matmul_trn2.pymeasures kernel entries/s
against aten on the device and the host CPU at 2 threads and all vCPUs.
tile_maskis 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 * mexceeds the 6e10-entry block budget, else one),all, or an
int.TRNSPARSE_KMV_THREADS=1is 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_matmulper 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 tokmv_group(m):
about sqrt(m / 128) Y tiles, from 4 to 16 (TRNSPARSE_KMV_GROUPstill
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,
orTRNSPARSE_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_matmulas 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 DIRsaves the results,
to compare two checkouts with--compare.
- Instructions per launch, n = 131072, LNC=2, both physical cores,
-
float64 under
autonow 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. Forspmm,bsr_spmm,
screened_spmm,block_sparse_attention_tiled(forward and backward),
cg_bsr(throughbsr_spmm),cg_bsr_fusedand
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-timeUserWarningper op saying
precision is reduced to fp32; - under
TRNSPARSE_REQUIRE_NKI=1raisesNotImplementedError(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 underautonow get
torch (more precise; on the host or device aten instead of the kernel):
pass float32 operands, or selectset_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_spmmdecides onAandB; a float64 bound
vectordiag_integralsalone does not change the route. See
docs/architecture.md, "Precision and dtypes".float64 on the
neurondevice runs on the host underauto. 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 ofspmv,spmm,
spmv_symmetric,bsr_spmm,screened_spmm,
block_sparse_attention_tiled(forward and backward),cg_bsr,
chebyshev_bsr,richardson_bsr,power_iteration_bsror the
jacobi_preconditioner_bsrpreconditioner lives on aneurondevice
(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 oneUserWarningper 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=1keeps device aten (fp32 precision, no
copies). Host-resident float64, explicitnkiand the pytorch backend
are unchanged; the fused solvers already ran float64 on the host.
TRNSPARSE_REQUIRE_NKI=1raises for float64 / complex128 on the neuron
device at every public op (backendsautoandnki, also with
TRNSPARSE_FP64_ON_DEVICE=1), before any host copy or kernel. Before, the
routes with no kernel (CSRspmv,spmv_symmetric,spmm, the Jacobi
preconditioner) ran device aten at fp32 precision with no error under
REQUIRE_NKI andauto(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 throughdispatch._fp64_route: under REQUIRE_NKI float64 now
raisesNotImplementedError(it raisedTypeError), 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 raisedTypeError), or raiseNotImplementedError
under REQUIRE_NKI. Device-resident float64 underauto:kernel_matmul
is guarded like the other ops, and a float64KernelOperatorbound for
the neuron device is built and applied on the host (oneUserWarning),
returning each product on V's device. - under
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_tiledforward and backward), integer and bool
values, and complex values except inbsr_spmm(real kernel launches,
#78), now take the PyTorch path thatset_backend("pytorch")takes, or
raiseNotImplementedErrorunderTRNSPARSE_REQUIRE_NKI. Before, they went
into the fp32/bf16 kernels on the NKI and auto backends: complex operands of
spmm/screened_spmmreached the kernel unchanged, the static attention
kernels cast complex Q/K/V to fp32 (imaginary part dropped), the static
bsr_spmmand 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,_runon the XLA path and
the simulator) and raisesTypeErrornaming 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_launchfor
kernel_matmul, whose kernelskmv_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. -
spmmwith a 1-DBraised on the NKI path (#105). Affected
0.2.0–0.13.0: underset_backend("nki")/"auto"on a Neuron host,
spmm(A, b)with a vectorbfailed in the NKI GEMM wrapper with
ValueError: not enough values to unpack (expected 2, got 1), while the
pytorch backend returnsA @ bof shape(m,). The vector now goes to the
kernel as one column and the result is squeezed back. MatrixBis
unchanged. -
kernel_matmulno 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 withNRT 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 cachedwrap_nkihandle (now keyed per
kernel and shape). Blocks of the square operator use a new
_kmv_selfblk_kernel(custom optrnsparse::kmv_selfblk) that adds
noise * Vfor 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_WORKoverrides the budget. -
cg_bsrraisedUnboundLocalErrorwithmax_iter=0or on a first-step
breakdown, and reportediters=max_iteron any breakdown (#71, #86).
r_normwas only assigned inside the loop, somax_iter=0,A p = 0
(e.g. a zero matrix) orp . A p = 0at k=0 (an exactx0withtol=0)
raised. A later breakdown (|p . A p| < 1e-30, e.g. after exact
convergence withtol=0) returnediters = max_iter(500 or 1000 for a
1-2 step solve).cg_bsrnow returns the number of steps actually taken
and the residual of the returnedx;max_iter=0gives
(x0, 0, ||b - A x0|| / ||b||). Solutions are unchanged. Affects 0.3.2
through 0.13.0. -
power_iteration_bsrgave silently wrong gradients (#96), as
cg_bsrdid (#70). The norms were taken with.item(), so autograd
differentiated the iterations with frozen normalisation instead of the
eigenvector, andv0received a spurious gradient. The eigenvector now
differentiates as the exact unit eigenvector ofA(implicit
differentiation ofA 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^Ton the stored blocks.v0gets no gradient, the
eigenvalue stays a Python float, and backward raisesNotImplementedError
for complexA. Forward values are unchanged. Affects 0.3.2 through 0.13.0. -
from_scipydowncast 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 withsp_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_bsrgave silently wrong gradients (#70). The CG step sizes were
taken with.item(), so autograd differentiated a frozen-coefficient
polynomial inAapplied tob, not the solve: withbalong an
eigenvector (one-step convergence)b.gradwas ~20% offA^{-1} g, and
A.blocks.gradhad the same problem.cg_bsrnow differentiates as the
exact solve (implicit differentiation, liketorch.linalg.solve):
backward runs a second CG solveA lam = grad_xwith the same
tol/max_iter/M, givinggrad_b = lamand
grad_A = -lam x^Hon the stored blocks.x0andMno longer receive
gradients. Forward values are unchanged. Affects 0.3.2 through 0.13.0. -
cg_bsr_fused/power_iteration_bsr_fusedgave 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 raiseTypeErrorfor a non-real-floatA.blocks,
b,x0orv0, before any backend runs. Affects 0.11.0 through 0.13.0.