Class Native
smile_torch native library. This class glues the idiomatic
smile.deep.tensor API to the raw smile_torch_h
downcall stubs generated by jextract.
It centralizes three concerns: converting native error sentinels into Java
exceptions, freeing native handles when their Java wrappers become
unreachable (via a shared Cleaner), and a handful of downcalls for
functions that are not yet covered by the generated bindings.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final recordFrees anST_TensorIndexhandle exactly once.static final recordFrees anST_Tensorhandle exactly once. -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final CleanerShared cleaner that releases native handles owned by Java wrappers (tensors, indices, modules, …) once those wrappers are no longer reachable.static final intstatic final intstatic final intstatic final intat::blas::ScalingTypeordinals forscaledMmV2(Tensor, Tensor, Tensor, Tensor, int, int, int). -
Method Summary
Modifier and TypeMethodDescriptionstatic Tensor[]addGemmaRmsNorm(Tensor x, Tensor r, Tensor weight, double eps) Residual add fused with Gemma RMSNorm:sum = x + r,y = gemmaRmsNorm(sum), one launch.static Tensor[]applyRotaryPosEmb(Tensor xq, Tensor xk, Tensor cos, Tensor sin, int rotaryDim) HFapply_rotary_pos_emb/rotate_halfon query and key.static TensorcausalConv1dUpdate(Tensor hidden, Tensor convState, Tensor weight) Fused causal depthwise conv1d update for decode (S==1): writes SiLU output and rollsconvStatein place.static Tensor[]causalConv1dUpdateSplitQkv(Tensor hidden, Tensor convState, Tensor weight, int numKHeads, int numVHeads, int headKDim, int headVDim) Fused decode conv + QKV split + head repeat.static MemorySegmentcheck(MemorySegment handle) Verifies that a native call returned a non-null handle, throwing the native error message otherwise.static voidCopiessrcintodstin-place.static long[]cudaAllocatorStats(int deviceIndex) Queries CUDACachingAllocator live vs reserved bytes for a device.static int[]cudaComputeCapability(int deviceIndex) Returns CUDA compute capability{major, minor}for a device.static booleanstatic voidcudaGraphCaptureBegin(MemorySegment handle, int deviceIndex) static voidcudaGraphCaptureEnd(MemorySegment handle) static MemorySegmentstatic voidcudaGraphDestroy(MemorySegment handle) static booleancudaGraphIsReady(MemorySegment handle) static voidcudaGraphReplay(MemorySegment handle) static long[]cudaMemGetInfo(int deviceIndex) Queries free and total CUDA device memory via LibTorch's caching allocator (cudaMemGetInfounder a device guard).static MemorySegmentstatic TensorflashInferAttention(Tensor query, Tensor mask, AttentionContext ctx) Runs paged attention usingAttentionContext.static TensorflashInferAttentionPagedRaw(Tensor query, Tensor kCache, Tensor vCache, Tensor kvIndptr, Tensor kvIndices, Tensor kvLastPageLen, int pageSize, int numKvHeads, int headDim, int cacheLen, double scale, boolean isCausal, Tensor mask, MemorySegment workspace) Raw-tensor paged attention (existing eager S==1/S>1 dispatch), bypassingAttentionContext/KvCachePool.static TensorflashInferAttentionVerifyCapturable(Tensor query, Tensor kCache, Tensor vCache, Tensor qoIndptr, Tensor kvIndptr, Tensor kvIndices, Tensor kvLastPageLen, int pageSize, int numKvHeads, int headDim, int qoLen, double scale, float kScale, float vScale, boolean isCausal, MemorySegment workspace) Stage 1 (SMILE_VERIFY_CUDA_GRAPH): graph-capturable multi-token (S>1) causal paged attention for MTP window verify (seesmile_flashinfer_paged_attention_verify_cuda).static TensorflashInferAttentionVerifyEager(Tensor query, AttentionContext ctx, Tensor qoIndptr) Verify attention for calls that are not part of a CUDA graph bucket (eager verify windows, batched/ragged verify).static TensorflashInferAttentionVerifyGraph(Tensor query, AttentionContext ctx, Tensor qoIndptr) Production entry point for the graph-capturable MTP window-verify kernel, built onAttentionContext(KV pool layer slice + CSR + workspace) — the verify-graph sibling offlashInferAttention(Tensor, Tensor, AttentionContext), targetingsmile_flashinfer_paged_attention_verifyinstead ofsmile_flashinfer_paged_attention.static booleanstatic TensorflashInferRaggedAttention(Tensor query, Tensor key, Tensor value, Tensor mask, AttentionContext ctx) Runs ragged contiguous self-attention (BatchPrefillWithRaggedKVCacheor SDPA fallback).static voidflashInferSetAotDir(String path) Sets the FlashInfer AOT / jit-cache directory for the native loader.static MemorySegmentflashInferWorkspaceCreate(int deviceIndex, long workspaceBytes) Creates a FlashInfer workspace ondeviceIndex.static voidflashInferWorkspaceFree(MemorySegment handle) Frees a FlashInfer workspace handle.static voidClears only prefill gather caches on the workspace.static voidClears cached FlashInfer decode plans and prefill gather slots.static voidClears only the cached verify-graph (SMILE_VERIFY_CUDA_GRAPH) plan.static Tensor[]fp8Quant1x128(Tensor input) Dynamic BlockWise1x128 activation quantize on CUDA.static booleanstatic booleanstatic TensorgatedDeltaComputeG(Tensor a, Tensor aLog, Tensor dtBias) Fusedg = -exp(A_log) * softplus(a + dt_bias)(float).static Tensor[]gatedDeltaComputeGates(Tensor a, Tensor b, Tensor aLog, Tensor dtBias) Fusedbeta = sigmoid(b)and decay gateg.static TensorgatedDeltaDecodeFused(Tensor hidden, Tensor convState, Tensor convWeightF, Tensor a, Tensor b, Tensor aLogF, Tensor dtBiasF, Tensor recState, int numKHeads, int numVHeads, int headKDim, int headVDim) static TensorgatedDeltaVerifyWindow(Tensor hidden, Tensor convState, Tensor convWeight, Tensor g, Tensor beta, Tensor recState, int numKHeads, int numVHeads, int headKDim, int headVDim, boolean qkL2norm, Tensor[] convCkpts, Tensor[] recCkpts) Fused MTP verify window for one DeltaNet layer: conv + SiLU + QKV split in one kernel (rollsconvState, emits per-position conv checkpoints) followed by the fused recurrent rule (updatesrecState, emits per-position state checkpoints).static TensorgatedDeltaVerifyWindowFused(Tensor hidden, Tensor convState, Tensor convWeight, Tensor a, Tensor b, Tensor aLogF, Tensor dtBiasF, Tensor recState, int numKHeads, int numVHeads, int headKDim, int headVDim, Tensor[] convCkpts, Tensor[] recCkpts) gatedDeltaVerifyWindow(Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, int, int, int, int, boolean, Tensor[], Tensor[])with the gates computed inside the recurrent kernel from the rawa/bprojections[B, S, Hv](bf16) and floataLogF/dtBiasF;convWeightshould be a bf16[C, K]contiguous copy so no per-call conversion is needed.static TensorgemmaRmsNorm(Tensor x, Tensor weight, double eps) Gemma RMSNormx * rsqrt(mean(x^2) + eps) * (1 + w)in one launch.static Tensor[]Two small bf16 projectionsx . wa^Tandx . wb^Tin one launch (at most 8 rows).static booleanWhether the FlashInfer paged-prefill verify entry point is linked.static booleanWhole Gated DeltaNet decode core (S == 1, bf16): conv update + QKV split + gates + recurrent rule in two launches.static booleanWhethergatedDeltaVerifyWindow(Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, int, int, int, int, boolean, Tensor[], Tensor[])is available in the loaded native library.static booleanstatic booleanWhetherrecurrentGatedDeltaRuleCkpt(Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, boolean, Tensor[])is available in the loaded native library.static booleanWrites new K/V rows into one layer's caches atslots(int64) in one launch.static StringReturns the message describing the most recent native failure, or an empty string if none.static TensorlinearWeight(MemorySegment linear) The weight[out, in]of asmile_linearlayer as an alias of the module parameter, ornull.static voidloadStateDict(MemorySegment module, Map<String, Tensor> stateDict, boolean strict) Loads a flat state dict into a module by matchingnamed_parameters()keys.static booleanstatic booleanstatic booleanstatic TensormarlinFp8Gemm(Tensor a, Tensor qweight, Tensor scales) MXFP8 weight-only GEMM:A @ dequant(W)^T.static TensormarlinFp8RepackBlockScales(Tensor scaleInv) Repacks block-FP8 scales (W = fp8 * scaleper 128x128 tile) for the group-128 Marlin kernel.static TensormarlinFp8RepackScales(Tensor scales) Permutes E8M0 scales into the Marlin layout.static TensormarlinFp8RepackScalesStack(Tensor scales) Stacked variant ofmarlinFp8RepackScales(Tensor).static TensormarlinFp8RepackWeight(Tensor weight) Repacks an MXFP8 weight into the Marlin tile layout.static TensormarlinFp8RepackWeightStack(Tensor weights) Stacked variant ofmarlinFp8RepackWeight(Tensor).static booleanstatic TensormarlinMoeFp8Gemm(Tensor a, Tensor qweight, Tensor scales, Tensor align, Tensor topkWeights, int blockSize, int topK, boolean mulTopkWeights) MXFP8 Marlin MoE GEMM; seesmile_marlin_fp8.h.static TensorMarlin FP16×INT4 GEMM.static voidmoduleSetRequiresGrad(MemorySegment module, boolean requiresGrad) Setsrequires_gradon every parameter ofmodule(recursive).static TensormoeAlignBlockSize(Tensor topkIds, int expertStart, int numLocalExperts, int blockSize) Groups top-k assignments by expert on the device for the Marlin MoE kernel.static Tensor[]MoE routing (sigmoid, bias-corrected top-k, normalise, scale) in one launch.static TensormsaDecodeMask(Tensor q, Tensor cache, Tensor slots, Tensor positions, int length, int blockSize, int topk, int initBlocks, int localBlocks) MSA block selection for single-token decode; seesmile_minimax_ops.h.static TensormsaDecodeSelect(Tensor q, Tensor cache, Tensor slots, Tensor positions, int length, int blockSize, int topk, int initBlocks, int localBlocks, int seqlen) MSA block selection for single-token decode returning block ids; seesmile_minimax_ops.h.static TensormulSigmoid(Tensor x, Tensor gate) x * sigmoid(gate).static Tensor[]mxfp8ToBlockFp8(Tensor weight, Tensor scale) Re-expresses MXFP8 weights (1x32 E8M0 scales) as block FP8 (one float32 scale per 128x128 tile).static booleanstatic longReturns the storage size oftensorin bytes.static voidncclAllReduceSum(MemorySegment comm, int rank, Tensor local) In-place NCCL sum all-reduce onlocalforrank.static voidncclBroadcast(MemorySegment comm, int rank, int root, Tensor local) NCCL broadcast oflocalfromroot.static MemorySegmentncclCommCreate(int[] deviceIndices) Creates a local NCCL communicator fordeviceIndices, or returnsMemorySegment.NULLwhen NCCL is unavailable.static MemorySegmentncclCommCreateRanks(int[] deviceIndices, int worldSize, int rankOffset, byte[] uniqueId) Creates this process's ranks of a communicator spanningworldSizeranks:deviceIndices.lengthlocal ranks starting at world rankrankOffset.static voidncclCommFree(MemorySegment comm) Destroys an NCCL communicator fromncclCommCreate(int[]).static byte[]A fresh NCCL unique id (128 bytes) for a communicator that spans processes.static Tensor[]qkNormRope(Tensor q, Tensor k, Tensor qWeight, Tensor kWeight, Tensor cos, Tensor sin, int rotaryDim, double eps) Per-head Gemma RMSNorm ofqandkthen partial RoPE, one launch; seesmile_minimax_ops.h.static TensorrecurrentGatedDeltaRule(Tensor query, Tensor key, Tensor value, Tensor g, Tensor beta, Tensor state, boolean qkL2norm) Fused recurrent gated delta rule.static TensorrecurrentGatedDeltaRuleCkpt(Tensor query, Tensor key, Tensor value, Tensor g, Tensor beta, Tensor state, boolean qkL2norm, Tensor[] ckpts) Fused recurrent gated delta rule over a whole window that also writes the state after steptintockpts[t](CUDA only).static TensorrepeatKvHeads(Tensor x, int rep) Repeat heads on dim 2 ([B,S,H,D] → [B,S,H*rep,D]).static TensorresizeBicubicAa(Tensor x, int outH, int outW) Bicubic resize with antialiasing (torchvisionresize(antialias=True)).static TensorQwen RMSNormrms_norm(x)*(1+weight).static TensorrmsNormGated(Tensor x, Tensor gate, Tensor weight, double eps) Fused gated RMSNorm.static TensorScaled FP8 matrix multiply via LibTorchat::_scaled_mm(cuBLASLt).static TensorscaledMmV2(Tensor a, Tensor b, Tensor scaleA, Tensor scaleB, int recipeA, int recipeB, int outDtype) Block-scaled FP8 matrix multiply via LibTorchat::_scaled_mm_v2.static booleanstatic TensorsigmoidGateMul(Tensor attn, Tensor gate) attn * sigmoid(gate)wheregateis a strided[B,S,H,D]view;nullwhen unsupported.static Tensorsilu(gate) * upin one launch, ornullwhen unavailable or unsupported.static TensorNativetorch::softplus.static TensorsparseDecodeAttention(Tensor q, Tensor kLayer, Tensor vLayer, Tensor slots, Tensor positions, Tensor sel, int length, double scale, int seqlen) Block-sparse decode attention over the blocks chosen bymsaDecodeSelect(Tensor, Tensor, Tensor, Tensor, int, int, int, int, int, int); seesmile_minimax_ops.h.static TensorTheswigluoaiactivation in one launch.static voidtpAllReduceSum(Tensor[] tensors) In-place sum all-reduce across tensors that already reside on distinct devices.static voidtpBroadcast(Tensor[] tensors, int root) Broadcaststensors[root]onto every other entry.static voidunregisterModule(MemorySegment module, String name) Unregisters a child module by name, dropping the parent's shared_ptr.
-
Field Details
-
CLEANER
Shared cleaner that releases native handles owned by Java wrappers (tensors, indices, modules, …) once those wrappers are no longer reachable. It is a safety net; callers should still close resources deterministically via try-with-resources or anAutoScopewhere possible. -
SCALING_TENSOR_WISE
public static final int SCALING_TENSOR_WISEat::blas::ScalingTypeordinals forscaledMmV2(Tensor, Tensor, Tensor, Tensor, int, int, int).- See Also:
-
SCALING_ROW_WISE
public static final int SCALING_ROW_WISE- See Also:
-
SCALING_BLOCK_WISE_1X128
public static final int SCALING_BLOCK_WISE_1X128- See Also:
-
SCALING_BLOCK_WISE_128X128
public static final int SCALING_BLOCK_WISE_128X128- See Also:
-
-
Method Details
-
lastError
Returns the message describing the most recent native failure, or an empty string if none.- Returns:
- the last native error message.
-
check
Verifies that a native call returned a non-null handle, throwing the native error message otherwise.- Parameters:
handle- the handle returned by a native call.- Returns:
- the validated handle.
-
copy_
-
loadStateDict
public static void loadStateDict(MemorySegment module, Map<String, Tensor> stateDict, boolean strict) Loads a flat state dict into a module by matchingnamed_parameters()keys.- Parameters:
module- the nativeST_Modulehandle.stateDict- map from fully-qualified parameter name to tensor.strict- whentrue, every module parameter must be present and every state-dict key must match a module parameter.
-
cudaMemGetInfo
public static long[] cudaMemGetInfo(int deviceIndex) Queries free and total CUDA device memory via LibTorch's caching allocator (cudaMemGetInfounder a device guard).Requires a
smile_torchbinary built withUSE_CUDA(CUDA Toolkit + CUDA LibTorch). A CPU-only build fails with a clear native error rather than a silent-1.- Parameters:
deviceIndex- the CUDA device index.- Returns:
long[2]of{freeBytes, totalBytes}.- Throws:
RuntimeException- if the query fails (e.g. CUDA unavailable).
-
cudaAllocatorStats
public static long[] cudaAllocatorStats(int deviceIndex) Queries CUDACachingAllocator live vs reserved bytes for a device.allocatedis storage owned by live tensors;reservedis the cudaMalloc footprint (includes free cached blocks thatDevice.emptyCache()can return to the driver).- Parameters:
deviceIndex- the CUDA device index.- Returns:
long[2]of{allocatedBytes, reservedBytes}.- Throws:
RuntimeException- if the query fails.
-
cudaComputeCapability
public static int[] cudaComputeCapability(int deviceIndex) Returns CUDA compute capability{major, minor}for a device.- Parameters:
deviceIndex- CUDA device index.- Returns:
int[2]of{major, minor}.- Throws:
RuntimeException- if the query fails or the symbol is missing (rebuildlibsmile_torchwith CUDA).
-
scaledMm
Scaled FP8 matrix multiply via LibTorchat::_scaled_mm(cuBLASLt).- Parameters:
a- FP8 activation[M,K].b- FP8 weight layout expected by_scaled_mm[N,K].scaleA- float scale fora.scaleB- float scale forb.outDtype- outputScalarTypecode (smile_torch_h.ST_DTYPE_BFLOAT16()etc.).- Returns:
- output tensor, or
nullif the native path is unavailable.
-
scaledMmV2
public static Tensor scaledMmV2(Tensor a, Tensor b, Tensor scaleA, Tensor scaleB, int recipeA, int recipeB, int outDtype) Block-scaled FP8 matrix multiply via LibTorchat::_scaled_mm_v2.- Parameters:
a- FP8 activation[M,K].b- FP8 weight[N,K].scaleA- float32 scales fora(BlockWise1x128 layout).scaleB- float32 scales forb(BlockWise128x128 layout).recipeA-ScalingTypeordinal fora.recipeB-ScalingTypeordinal forb.outDtype- output dtype code.- Returns:
- output tensor, or
nullif unavailable.
-
scaledMmV2Available
public static boolean scaledMmV2Available()- Returns:
truewhenscaledMmV2(Tensor, Tensor, Tensor, Tensor, int, int, int)is compiled intolibsmile_torch.
-
fp8Quant1x128
-
fp8Quant1x128Available
public static boolean fp8Quant1x128Available()- Returns:
truewhenfp8Quant1x128(Tensor)is compiled intolibsmile_torch.
-
marlinAvailable
public static boolean marlinAvailable()- Returns:
truewhen Marlin is compiled intolibsmile_torch.
-
marlinMul
Marlin FP16×INT4 GEMM. Returnsnullwhen Marlin is not built.- Parameters:
a- FP16 activations[M,K].b- Marlin-packed INT4 weights.scales- group scales.workspace- scratch buffer (may be empty).threadK- Marlin thread_k (-1 = auto).
-
marlinFp8Available
public static boolean marlinFp8Available()- Returns:
truewhen the MXFP8 Marlin kernels are compiled intolibsmile_torch.
-
marlinMoeFp8Available
public static boolean marlinMoeFp8Available()- Returns:
truewhen the MoE token-grouping and Marlin MoE GEMM kernels are available.
-
marlinFp8RepackWeight
-
marlinFp8BlockScalesAvailable
public static boolean marlinFp8BlockScalesAvailable()- Returns:
truewhen the block-FP8 scale repack (Qwen/DeepSeek checkpoints on Ampere) is compiled in.
-
marlinFp8RepackBlockScales
-
marlinFp8RepackScales
-
marlinFp8Gemm
MXFP8 weight-only GEMM:A @ dequant(W)^T.- Parameters:
a- bfloat16 activations[M, K]on CUDA.qweight- output ofmarlinFp8RepackWeight(Tensor).scales- output ofmarlinFp8RepackScales(Tensor).- Returns:
- bfloat16
[M, N].
-
marlinFp8RepackWeightStack
Stacked variant ofmarlinFp8RepackWeight(Tensor).- Parameters:
weights- FP8[E, N, K].- Returns:
- int32
[E, K / 16, N * 4].
-
marlinFp8RepackScalesStack
Stacked variant ofmarlinFp8RepackScales(Tensor).- Parameters:
scales- uint8[E, N, K / 32].- Returns:
- uint8
[E, K / 32, N].
-
moeAlignBlockSize
public static Tensor moeAlignBlockSize(Tensor topkIds, int expertStart, int numLocalExperts, int blockSize) Groups top-k assignments by expert on the device for the Marlin MoE kernel.- Parameters:
topkIds- expert ids[T, topK](int64 or int32) on CUDA.expertStart- first expert owned by this rank.numLocalExperts- experts owned by this rank.blockSize- MoE block size (8, 16, 32, 48 or 64).- Returns:
- one int32 tensor: sorted token ids, per-block expert ids, then the padded length.
-
marlinMoeFp8Gemm
public static Tensor marlinMoeFp8Gemm(Tensor a, Tensor qweight, Tensor scales, Tensor align, Tensor topkWeights, int blockSize, int topK, boolean mulTopkWeights) MXFP8 Marlin MoE GEMM; seesmile_marlin_fp8.h.- Parameters:
a- bfloat16[M, K].qweight- int32[E, K/16, N*4].scales- uint8[E, K/32, N].align- result ofmoeAlignBlockSize(Tensor, int, int, int).topkWeights- float32,T * topKrouting weights.blockSize- the block size passed tomoeAlignBlockSize(Tensor, int, int, int).topK- top-k of the routing (1for the second GEMM).mulTopkWeights- whether to scale each row by its routing weight.- Returns:
- bfloat16
[M * topK, N].
-
fusedOpsAvailable
public static boolean fusedOpsAvailable()- Returns:
truewhen the fused decode kernels are compiled in and not disabled bySMILE_FUSED_OPS=0.
-
gemmaRmsNorm
-
addGemmaRmsNorm
-
linearWeight
The weight[out, in]of asmile_linearlayer as an alias of the module parameter, ornull.- Parameters:
linear- theST_Linearhandle.
-
gemv2
-
sigmoidGateMul
-
kvWrite
-
siluMul
-
qkNormRope
-
swigluOai
-
moeRoute
-
msaDecodeMask
public static Tensor msaDecodeMask(Tensor q, Tensor cache, Tensor slots, Tensor positions, int length, int blockSize, int topk, int initBlocks, int localBlocks) MSA block selection for single-token decode; seesmile_minimax_ops.h.- Parameters:
q- index queries[B, G, D].cache- one layer of the index-key cache[numSlots, 1, D], contiguous.slots- int64[B * length]physical slots.positions- int32[B]query positions on the device.- Returns:
- additive mask
[B, G, 1, length], ornullwhen unavailable or unsupported.
-
msaDecodeSelect
public static Tensor msaDecodeSelect(Tensor q, Tensor cache, Tensor slots, Tensor positions, int length, int blockSize, int topk, int initBlocks, int localBlocks, int seqlen) MSA block selection for single-token decode returning block ids; seesmile_minimax_ops.h.- Parameters:
q- index queries[T, G, D],T = B * seqlen.seqlen- query tokens per row (1 for decode); tokentis atpositions[t / seqlen] + t % seqlen.- Returns:
- int32
[T, G, topk](-1 pads), ornullwhen unavailable or unsupported.
-
sparseDecodeAttention
public static Tensor sparseDecodeAttention(Tensor q, Tensor kLayer, Tensor vLayer, Tensor slots, Tensor positions, Tensor sel, int length, double scale, int seqlen) Block-sparse decode attention over the blocks chosen bymsaDecodeSelect(Tensor, Tensor, Tensor, Tensor, int, int, int, int, int, int); seesmile_minimax_ops.h.- Parameters:
q- bfloat16[T, H, 128],T = B * seqlen.- Returns:
- bfloat16
[T, H, 128], ornullwhen unavailable or unsupported.
-
resizeBicubicAa
Bicubic resize with antialiasing (torchvisionresize(antialias=True)).- Parameters:
x-[N, C, H, W], uint8 or floating point, on any device.outH- target height.outW- target width.- Returns:
[N, C, outH, outW]of the same dtype.- Throws:
IllegalStateException- if the loaded native library predates this function.
-
mxfp8ToBlockFp8Available
public static boolean mxfp8ToBlockFp8Available()- Returns:
truewhen the MXFP8 to block-FP8 converter is compiled intolibsmile_torch.
-
mxfp8ToBlockFp8
Re-expresses MXFP8 weights (1x32 E8M0 scales) as block FP8 (one float32 scale per 128x128 tile).- Parameters:
weight- FP8 E4M3[N, K]or[E, N, K]on CUDA,NandKmultiples of 128.scale- uint8 E8M0 scales[.., N, K / 32].- Returns:
{fp8, scaleInv}wherescaleInvis float32[.., N/128, K/128]andW = fp8 * scaleInvper tile.
-
moduleSetRequiresGrad
Setsrequires_gradon every parameter ofmodule(recursive).- Parameters:
module- nativeST_Modulehandle.requiresGrad-trueto enable autograd on parameters.
-
unregisterModule
Unregisters a child module by name, dropping the parent's shared_ptr. Used when replacing denseLinearLayershells with quantized ops so GPU storage is released before KV pool sizing.- Parameters:
module- parentST_Module.name- registered child name (e.g."wq").
-
nbytes
Returns the storage size oftensorin bytes.- Parameters:
tensor- the tensor.- Returns:
tensor.nbytes().
-
dataPtr
Returns a writableMemorySegmentcovering the contiguous storage oftensor(nbytesbytes). The tensor must be contiguous and remain reachable for the lifetime of the segment.- Parameters:
tensor- the contiguous tensor.- Returns:
- the storage segment.
-
tpAllReduceSum
In-place sum all-reduce across tensors that already reside on distinct devices.- Parameters:
tensors- one tensor per TP rank (same shape/dtype).
-
tpBroadcast
Broadcaststensors[root]onto every other entry. -
ncclCommCreate
Creates a local NCCL communicator fordeviceIndices, or returnsMemorySegment.NULLwhen NCCL is unavailable. -
ncclUniqueId
public static byte[] ncclUniqueId()A fresh NCCL unique id (128 bytes) for a communicator that spans processes.- Returns:
- the id.
- Throws:
IllegalStateException- when NCCL is unavailable.
-
ncclCommCreateRanks
public static MemorySegment ncclCommCreateRanks(int[] deviceIndices, int worldSize, int rankOffset, byte[] uniqueId) Creates this process's ranks of a communicator spanningworldSizeranks:deviceIndices.lengthlocal ranks starting at world rankrankOffset. Every process must call this at the same time with the sameuniqueId; it returns once all ranks have joined. The collectives take local rank indices.- Returns:
- the communicator handle.
- Throws:
IllegalStateException- when it cannot be created.
-
ncclCommFree
Destroys an NCCL communicator fromncclCommCreate(int[]). -
ncclAllReduceSum
In-place NCCL sum all-reduce onlocalforrank. Every TP rank must call concurrently. -
ncclBroadcast
NCCL broadcast oflocalfromroot. Every rank must call concurrently with its buffer. -
recurrentGatedDeltaRule
public static Tensor recurrentGatedDeltaRule(Tensor query, Tensor key, Tensor value, Tensor g, Tensor beta, Tensor state, boolean qkL2norm) Fused recurrent gated delta rule. Mutates floatstatein place. Returns output[B,S,H,Dv](caller owns).- Returns:
- output tensor, or
nullif the native path is unavailable.
-
hasGatedDeltaVerifyWindow
public static boolean hasGatedDeltaVerifyWindow()WhethergatedDeltaVerifyWindow(Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, int, int, int, int, boolean, Tensor[], Tensor[])is available in the loaded native library.- Returns:
truewhen the symbol resolved.
-
gatedDeltaVerifyWindow
public static Tensor gatedDeltaVerifyWindow(Tensor hidden, Tensor convState, Tensor convWeight, Tensor g, Tensor beta, Tensor recState, int numKHeads, int numVHeads, int headKDim, int headVDim, boolean qkL2norm, Tensor[] convCkpts, Tensor[] recCkpts) Fused MTP verify window for one DeltaNet layer: conv + SiLU + QKV split in one kernel (rollsconvState, emits per-position conv checkpoints) followed by the fused recurrent rule (updatesrecState, emits per-position state checkpoints). CUDA only.- Parameters:
hidden- pre-conv QKV projection[B, S, C](contiguous).g- decay gate[B, S, Hv].beta- input gate[B, S, Hv].- Returns:
- core output
[B, S, Hv, Dv]inhidden's dtype, ornullwhen unsupported (nothing modified) so the caller can use another path.
-
hasGatedDeltaVerifyWindowFused
public static boolean hasGatedDeltaVerifyWindowFused() -
gatedDeltaVerifyWindowFused
public static Tensor gatedDeltaVerifyWindowFused(Tensor hidden, Tensor convState, Tensor convWeight, Tensor a, Tensor b, Tensor aLogF, Tensor dtBiasF, Tensor recState, int numKHeads, int numVHeads, int headKDim, int headVDim, Tensor[] convCkpts, Tensor[] recCkpts) gatedDeltaVerifyWindow(Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, int, int, int, int, boolean, Tensor[], Tensor[])with the gates computed inside the recurrent kernel from the rawa/bprojections[B, S, Hv](bf16) and floataLogF/dtBiasF;convWeightshould be a bf16[C, K]contiguous copy so no per-call conversion is needed.- Returns:
- core
[B, S, Hv, Dv], ornullwhen unsupported (nothing modified).
-
hasRecurrentGatedDeltaRuleCkpt
public static boolean hasRecurrentGatedDeltaRuleCkpt()WhetherrecurrentGatedDeltaRuleCkpt(Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, boolean, Tensor[])is available in the loaded native library.- Returns:
truewhen the symbol resolved.
-
recurrentGatedDeltaRuleCkpt
public static Tensor recurrentGatedDeltaRuleCkpt(Tensor query, Tensor key, Tensor value, Tensor g, Tensor beta, Tensor state, boolean qkL2norm, Tensor[] ckpts) Fused recurrent gated delta rule over a whole window that also writes the state after steptintockpts[t](CUDA only). Mutatesstateto the end-of-window state.- Parameters:
ckpts- float, contiguous per-step state sinks (at least as large asstate).- Returns:
- output
[B,S,H,Dv](caller owns), ornullwhen unavailable (older library or non-fused fallback) so the caller can use a per-position loop.
-
softplus
-
gatedDeltaComputeG
-
gatedDeltaComputeGates
-
repeatKvHeads
-
rmsNorm
-
rmsNormGated
-
mulSigmoid
-
causalConv1dUpdate
-
causalConv1dUpdateSplitQkv
public static Tensor[] causalConv1dUpdateSplitQkv(Tensor hidden, Tensor convState, Tensor weight, int numKHeads, int numVHeads, int headKDim, int headVDim) Fused decode conv + QKV split + head repeat. Returns[query, key, value]with shapes[B,1,numVHeads,headKDim]/[B,1,numVHeads,headVDim], ornullwhen unavailable. -
hasGatedDeltaDecodeFused
public static boolean hasGatedDeltaDecodeFused()Whole Gated DeltaNet decode core (S == 1, bf16): conv update + QKV split + gates + recurrent rule in two launches. UpdatesconvStateandrecStatein place.- Returns:
- the core
[B * numVHeads, headVDim], ornull(nothing modified) when unsupported.
-
gatedDeltaDecodeFused
-
applyRotaryPosEmb
-
flashInferSetAotDir
Sets the FlashInfer AOT / jit-cache directory for the native loader.- Parameters:
path- absolute directory, ornull/empty to clear.
-
flashInferAvailable
public static boolean flashInferAvailable()- Returns:
truewhen FlashInfer paged attention is compiled intolibsmile_torch.
-
flashInferWorkspaceCreate
Creates a FlashInfer workspace ondeviceIndex.- Returns:
- native handle, or null when unavailable.
-
flashInferWorkspaceFree
Frees a FlashInfer workspace handle. -
flashInferWorkspaceInvalidateRuntimeCache
Clears cached FlashInfer decode plans and prefill gather slots. -
flashInferWorkspaceInvalidatePrefillRuntimeCache
Clears only prefill gather caches on the workspace. -
flashInferWorkspaceInvalidateVerifyRuntimeCache
Clears only the cached verify-graph (SMILE_VERIFY_CUDA_GRAPH) plan. Independent offlashInferWorkspaceInvalidateRuntimeCache(MemorySegment)/flashInferWorkspaceInvalidatePrefillRuntimeCache(MemorySegment)— decode's routine cohort/CSR-rebuild invalidation must not clear a still-valid verify plan, and vice versa. -
flashInferAttentionPagedRaw
public static Tensor flashInferAttentionPagedRaw(Tensor query, Tensor kCache, Tensor vCache, Tensor kvIndptr, Tensor kvIndices, Tensor kvLastPageLen, int pageSize, int numKvHeads, int headDim, int cacheLen, double scale, boolean isCausal, Tensor mask, MemorySegment workspace) Raw-tensor paged attention (existing eager S==1/S>1 dispatch), bypassingAttentionContext/KvCachePool.Exists so a Stage 1 (SMILE_VERIFY_CUDA_GRAPH) smoke test can compare
flashInferAttentionVerifyCapturable(Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, int, int, int, int, double, float, float, boolean, MemorySegment)'s output against this existing, proven path on identical raw tensors, without needing to stand up the full production KV-pool machinery.flashInferAttention(Tensor, Tensor, AttentionContext)is the production entry point built on the same underlying call; this is a thin sibling at the same tensor-level boundary.- Parameters:
query- query[B, Hq, S, D]kCache- key cache[numSlots, Hkv, D](one layer slice)vCache- value cache[numSlots, Hkv, D]kvIndptr- int32[B+1]kvIndices- int32[numPages]kvLastPageLen- int32[B]pageSize- tokens per pagenumKvHeads- HkvheadDim- DcacheLen- total sequence length (for CSR validation;0to skip)scale- attention scale (<= 0→1/sqrt(D))isCausal- whether to apply causal masking; ignored (SDPA requires the caller not set both) whenmask != nullmask- optional explicit additive mask, e.g.[S, cacheLen](broadcastable); pass non-null for "continuation window" causal semantics (bottom-right-aligned: column j valid for row i iffj <= i + (cacheLen - S)) — plainisCausal=truewith no mask uses PyTorch SDPA's own is_causal, which is top-left-aligned for S != cacheLen and therefore wrong for this use case. May benull.workspace- FlashInfer workspace handle- Returns:
- output
[B, Hq, S, D]
-
flashInferAttention
Runs paged attention usingAttentionContext.- Parameters:
query- query[B, Hq, S, D]mask- optional additive attention mask (same as torch_native); may be nullctx- paged context with pool + CSR + workspace- Returns:
- output
[B, Hq, S, D]
-
flashInferAttentionVerifyCapturable
public static Tensor flashInferAttentionVerifyCapturable(Tensor query, Tensor kCache, Tensor vCache, Tensor qoIndptr, Tensor kvIndptr, Tensor kvIndices, Tensor kvLastPageLen, int pageSize, int numKvHeads, int headDim, int qoLen, double scale, float kScale, float vScale, boolean isCausal, MemorySegment workspace) Stage 1 (SMILE_VERIFY_CUDA_GRAPH): graph-capturable multi-token (S>1) causal paged attention for MTP window verify (seesmile_flashinfer_paged_attention_verify_cuda). Isolated sibling offlashInferAttention(Tensor, Tensor, AttentionContext)— not wired into the live verify path yet; this exists so Stage 1's eager-mode correctness can be validated directly againstflashInferAttention(Tensor, Tensor, AttentionContext)'s existing SDPA path before any later stage touchesQwen/QwenModel.No additive mask parameter (FlashInfer's masking here is compile-time
MaskMode, unlike the additive-mask SDPA path).- Parameters:
query- query[B, Hq, S, D]kCache- key cache[numSlots, Hkv, D](one layer slice)vCache- value cache[numSlots, Hkv, D]qoIndptr- int32[B+1], values{0,S,2S,...}kvIndptr- int32[B+1]kvIndices- int32[numPages]kvLastPageLen- int32[B]pageSize- tokens per pagenumKvHeads- HkvheadDim- DqoLen- S (must equalquery's 3rd dim)scale- attention scale (<= 0→1/sqrt(D))kScale- FP8 KV key dequant scale (1.0 when KV is bf16/fp16)vScale- FP8 KV value dequant scale (1.0 when KV is bf16/fp16)isCausal- diagnostic-only toggle (MaskMode::kCausal vs kNone); production callers always passtrueworkspace- FlashInfer workspace handle- Returns:
- output
[B, Hq, S, D]
-
hasFlashInferAttentionVerify
public static boolean hasFlashInferAttentionVerify()Whether the FlashInfer paged-prefill verify entry point is linked.- Returns:
truewhenflashInferAttentionVerifyGraph(Tensor, AttentionContext, Tensor)can be called.
-
flashInferAttentionVerifyGraph
public static Tensor flashInferAttentionVerifyGraph(Tensor query, AttentionContext ctx, Tensor qoIndptr) Production entry point for the graph-capturable MTP window-verify kernel, built onAttentionContext(KV pool layer slice + CSR + workspace) — the verify-graph sibling offlashInferAttention(Tensor, Tensor, AttentionContext), targetingsmile_flashinfer_paged_attention_verifyinstead ofsmile_flashinfer_paged_attention.ctx.isCausal()must betrue(this kernel has no additive-mask parameter; causal masking is the compile-time, bottom-right-alignedMaskMode::kCausalvalidated in Stage 1/2).- Parameters:
query- query[B, Hq, S, D]ctx- paged context with pool + CSR + workspace (seqLenis the query window length)qoIndptr- int32[B+1], values{0,S,2S,...}(KvCachePool.verifyQoIndptrBuf(int, int))- Returns:
- output
[B, Hq, S, D]
-
flashInferAttentionVerifyEager
public static Tensor flashInferAttentionVerifyEager(Tensor query, AttentionContext ctx, Tensor qoIndptr) Verify attention for calls that are not part of a CUDA graph bucket (eager verify windows, batched/ragged verify). Plans into a scratch workspace disjoint fromflashInferAttentionVerifyGraph(Tensor, AttentionContext, Tensor)'s, so a captured graph's baked plan arrays can never be overwritten by an eager plan of a different shape. Falls back to the graph entry point on an older native library. -
flashInferRaggedAttention
public static Tensor flashInferRaggedAttention(Tensor query, Tensor key, Tensor value, Tensor mask, AttentionContext ctx) Runs ragged contiguous self-attention (BatchPrefillWithRaggedKVCacheor SDPA fallback).- Parameters:
query-[N, H, D]NHDkey-[N, H, D]value-[N, H, D]mask- optional additive mask; may be nullctx- ragged context withAttentionContext.raggedIndptr()- Returns:
- output
[N, H, D]
-
cudaGraphAvailable
public static boolean cudaGraphAvailable()- Returns:
truewhensmile_cuda_graph_createis exported.
-
cudaGraphCreate
- Returns:
- opaque graph handle, or null when unavailable.
-
cudaGraphDestroy
- Parameters:
handle- graph fromcudaGraphCreate().
-
cudaGraphCaptureBegin
- Parameters:
handle- graph handle. @param deviceIndex CUDA device ordinal.
-
cudaGraphCaptureEnd
- Parameters:
handle- graph handle aftercudaGraphCaptureBegin(MemorySegment, int).
-
cudaGraphReplay
- Parameters:
handle- instantiated graph handle.
-
cudaGraphIsReady
- Parameters:
handle- graph handle.
-