attn

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 38 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package attn provides scaled dot-product, paged GQA, Multi-head Latent Attention (MLA), split-K decode, Gated DeltaNet, Kimi Delta Attention (KDA), tree attention, manifold-constrained hyper-connections (mHC), attention residuals, context-parallel 3D pipelines, and fused transformer layers.

CausalFlashAttentionTemplate includes both CausalFlashAttentionDecode and CausalFlashAttentionDecodeDevicePos, which reads the decode position from device memory for launches captured in a CUDA graph.

This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.

Package contextparallel compiles persistent 3D Pipeline + Tensor + Context Parallel (PP x TP x CP) schedules, including Zero-Bubble ZB-V (V-shape bi-directional stage assignment with split B_X input-gradient and W weight-gradient backward steps), fused with intra-step Ring-CP KV exchange, TP NVSwitch multimem collectives, and .sys-scope P2P stage-handoff ready barriers.

Index

Examples

Constants

View Source
const (
	RegionRMSNorm   = "rmsnorm"
	RegionQKV       = "qkv"
	RegionRoPE      = "rope"
	RegionAttn      = "attn"
	RegionOProj     = "o_proj"
	RegionMLP       = "mlp"
	MarkerTokenDone = "token_done"
)

Canonical IKET region and marker names for a single-GPU transformer decoder layer.

View Source
const (
	EventIDRMSNorm   uint16 = 1
	EventIDQKV       uint16 = 2
	EventIDRoPE      uint16 = 3
	EventIDAttn      uint16 = 4
	EventIDOProj     uint16 = 5
	EventIDMLP       uint16 = 6
	EventIDTokenDone uint16 = 10
)

Canonical cudaprofile event IDs for InstrumentDecoderKernelSource.

View Source
const (
	EventIDMegaRMSNormQKV uint16 = 1
	EventIDMegaRoPE       uint16 = 2
	EventIDMegaAttn       uint16 = 3
	EventIDMegaOProj      uint16 = 4
	EventIDMegaMLP        uint16 = 5
	EventIDMegaTokenDone  uint16 = 10
)

Canonical cudaprofile / IKET event IDs for LlamaDecodeMegakernelSource.

View Source
const (
	// DefaultResidualRMSNormThreads is the default block width for the
	// warp-cooperative residual RMSNorm kernels (8 warps per CTA).
	DefaultResidualRMSNormThreads = 256

	// MaxResidualRMSNormSmemFloats is the maximum hidden dimension cached
	// in default 48 KiB dynamic shared memory without opt-in attributes:
	// (36 header floats + 12000 row floats) * 4 bytes = 48144 <= 49152 bytes.
	MaxResidualRMSNormSmemFloats = 12000
)
View Source
const AttentionResidualCUDA = `` /* 4257-byte string literal not displayed */

AttentionResidualCUDA holds the composed and fused attention-residual CUDA C++ kernels.

View Source
const AttentionVariantCDecl = `` /* 280-byte string literal not displayed */

AttentionVariantCDecl declares eg_attn_variant, the C layout of an AttentionVariant: 24 bytes, 8-byte aligned.

View Source
const BatchedPagedAttentionTemplate = RoPEAngleSource + `
// status is set to 1 when device metadata names an invalid sequence length or
// physical block. Callers must initialize it to zero and inspect it after the
// dispatch. Invalid rows are filled with NaNs, never plausible output.

extern "C" __global__ void BatchedPagedAttentionDecode(
    const float* __restrict__ q,              // [num_seqs, num_q_heads, head_dim]
    const float* __restrict__ k_blocks,       // [total_blocks, block_size, num_kv_heads, head_dim]
    const float* __restrict__ v_blocks,       // [total_blocks, block_size, num_kv_heads, head_dim]
    const int* __restrict__ block_tables,     // [num_seqs, max_blocks_per_seq]
    const int* __restrict__ seq_lens,         // [num_seqs]
    float* __restrict__ out,                  // [num_seqs, num_q_heads, head_dim]
    int max_blocks_per_seq,
    int block_size,
    int num_q_heads,
    int num_kv_heads,
    int head_dim,
    float scale,
    int num_seqs,
    int total_blocks,
    int max_seq_len,
    int* __restrict__ status
) {
    int seq_idx = blockIdx.y;
    int head_idx = blockIdx.x;
	if (seq_idx >= num_seqs || head_idx >= num_q_heads) return;
	if (blockDim.x == 0 || (blockDim.x & (blockDim.x - 1)) != 0 || block_size <= 0 || max_blocks_per_seq <= 0 || total_blocks <= 0 || num_kv_heads <= 0 || head_dim <= 0) {
		if (threadIdx.x == 0) atomicExch(status, 1);
		return;
	}

    int seq_len = seq_lens[seq_idx];
	float* out_ptr = out + (seq_idx * num_q_heads + head_idx) * head_dim;
	if (seq_len <= 0 || seq_len > max_seq_len || num_q_heads % num_kv_heads != 0) {
		if (threadIdx.x == 0) atomicExch(status, 1);
		for (int d = threadIdx.x; d < head_dim; d += blockDim.x) out_ptr[d] = nanf("");
		return;
	}

    int kv_group_size = num_q_heads / num_kv_heads;
    int kv_head_idx = head_idx / kv_group_size;
    const int* seq_block_table = block_tables + seq_idx * max_blocks_per_seq;

    extern __shared__ float smem[];
	float* s_scores = smem; // seq_len floats
	float* reduce = s_scores + seq_len; // blockDim.x floats

    const float* q_ptr = q + (seq_idx * num_q_heads + head_idx) * head_dim;

    // Step 1: Compute Q * K^T through paged block lookups
	for (int t = 0; t < seq_len; t++) {
        int block_idx = seq_block_table[t / block_size];
        int block_offset = t % block_size;
		bool valid = block_idx >= 0 && block_idx < total_blocks;
		float dot = 0.0f;
		if (valid) {
			const float* k_ptr = k_blocks + ((block_idx * block_size + block_offset) * num_kv_heads + kv_head_idx) * head_dim;
			for (int d = threadIdx.x; d < head_dim; d += blockDim.x) dot += q_ptr[d] * k_ptr[d];
		}
		reduce[threadIdx.x] = dot;
		__syncthreads();
		for (int stride = blockDim.x / 2; stride > 0; stride >>= 1) {
			if (threadIdx.x < stride) reduce[threadIdx.x] += reduce[threadIdx.x + stride];
			__syncthreads();
		}
		if (threadIdx.x == 0) {
			if (!valid) atomicExch(status, 1);
			s_scores[t] = valid ? reduce[0] * scale : nanf("");
		}
		__syncthreads();
    }

	// One thread normalizes the scores. This is intentionally conservative:
	// unlike the old kernel it is mathematically correct for every block size.
	if (threadIdx.x == 0) {
		float max_score = -3.402823466e+38F;
		for (int t = 0; t < seq_len; t++) max_score = fmaxf(max_score, s_scores[t]);
		float sum_exp = 0.0f;
		for (int t = 0; t < seq_len; t++) {
			s_scores[t] = expf(s_scores[t] - max_score);
			sum_exp += s_scores[t];
		}
		for (int t = 0; t < seq_len; t++) s_scores[t] /= sum_exp;
	}
    __syncthreads();

    // Step 3: Weighted sum over Paged V
	for (int d = threadIdx.x; d < head_dim; d += blockDim.x) {
		float acc = 0.0f;
		for (int t = 0; t < seq_len; t++) {
			int block_idx = seq_block_table[t / block_size];
			int block_offset = t % block_size;
			if (block_idx < 0 || block_idx >= total_blocks) {
				acc = nanf("");
				break;
			}
			const float* v_ptr = v_blocks + ((block_idx * block_size + block_offset) * num_kv_heads + kv_head_idx) * head_dim;
			acc += s_scores[t] * v_ptr[d];
        }
        out_ptr[d] = acc;
    }
}

// BatchedPagedAttentionCausal consumes compact packed-token metadata. Token
// positions and causal lengths are independent: positions identify the query,
// while causal lengths bound the KV prefix visible to it. Status is per stable
// request row, so one bad row cannot make another row's output look failed.
extern "C" __global__ void BatchedPagedAttentionCausal(
    const float* __restrict__ q,
    const float* __restrict__ k_blocks,
    const float* __restrict__ v_blocks,
    const int* __restrict__ block_tables,
    const int* __restrict__ final_seq_lens,
    const unsigned long long* __restrict__ row_generations,
    const int* __restrict__ token_rows,
    const int* __restrict__ token_positions,
    const int* __restrict__ causal_lens,
    const unsigned long long* __restrict__ token_generations,
    float* __restrict__ out,
    int max_blocks_per_seq,
    int block_size,
    int num_q_heads,
    int num_kv_heads,
    int head_dim,
    float scale,
    int num_tokens,
    int metadata_rows,
    int total_blocks,
    int max_seq_len,
    int* __restrict__ row_status
) {
    int token_idx = blockIdx.y;
    int head_idx = blockIdx.x;
    if (token_idx >= num_tokens || head_idx >= num_q_heads) return;

    int row = token_rows[token_idx];
    float* out_ptr = out + (token_idx * num_q_heads + head_idx) * head_dim;
    bool valid_row = row >= 0 && row < metadata_rows;
    int position = valid_row ? token_positions[token_idx] : -1;
    int seq_len = valid_row ? causal_lens[token_idx] : 0;
    bool valid = valid_row && blockDim.x > 0 && (blockDim.x & (blockDim.x - 1)) == 0 &&
        block_size > 0 && max_blocks_per_seq > 0 && total_blocks > 0 &&
        num_kv_heads > 0 && head_dim > 0 && num_q_heads % num_kv_heads == 0 &&
        position >= 0 && position < final_seq_lens[row] &&
        seq_len > 0 && seq_len <= final_seq_lens[row] && seq_len <= max_seq_len &&
		(seq_len + block_size - 1) / block_size <= max_blocks_per_seq &&
        token_generations[token_idx] != 0 && token_generations[token_idx] == row_generations[row];
    if (!valid) {
        if (threadIdx.x == 0 && metadata_rows > 0) atomicExch(row_status + (valid_row ? row : 0), 1);
        for (int d = threadIdx.x; d < head_dim; d += blockDim.x) out_ptr[d] = nanf("");
        return;
    }

    int kv_head_idx = head_idx / (num_q_heads / num_kv_heads);
    const int* table = block_tables + row * max_blocks_per_seq;
    const float* q_ptr = q + (token_idx * num_q_heads + head_idx) * head_dim;
    extern __shared__ float smem[];
    float* scores = smem;
    float* reduce = scores + seq_len;

    for (int t = 0; t < seq_len; t++) {
        int block_idx = table[t / block_size];
        int block_offset = t % block_size;
        bool valid_block = block_idx >= 0 && block_idx < total_blocks;
        float dot = 0.0f;
        if (valid_block) {
            const float* k_ptr = k_blocks + ((block_idx * block_size + block_offset) * num_kv_heads + kv_head_idx) * head_dim;
            for (int d = threadIdx.x; d < head_dim; d += blockDim.x) dot += q_ptr[d] * k_ptr[d];
        }
        reduce[threadIdx.x] = dot;
        __syncthreads();
        for (int stride = blockDim.x / 2; stride > 0; stride >>= 1) {
            if (threadIdx.x < stride) reduce[threadIdx.x] += reduce[threadIdx.x + stride];
            __syncthreads();
        }
        if (threadIdx.x == 0) {
            if (!valid_block) atomicExch(row_status + row, 1);
            scores[t] = valid_block ? reduce[0] * scale : nanf("");
        }
        __syncthreads();
    }

    if (threadIdx.x == 0) {
        float max_score = -3.402823466e+38F;
        for (int t = 0; t < seq_len; t++) max_score = fmaxf(max_score, scores[t]);
        float sum_exp = 0.0f;
        for (int t = 0; t < seq_len; t++) {
            scores[t] = expf(scores[t] - max_score);
            sum_exp += scores[t];
        }
        for (int t = 0; t < seq_len; t++) scores[t] /= sum_exp;
    }
    __syncthreads();

    for (int d = threadIdx.x; d < head_dim; d += blockDim.x) {
        float acc = 0.0f;
        for (int t = 0; t < seq_len; t++) {
            int block_idx = table[t / block_size];
            int block_offset = t % block_size;
            if (block_idx < 0 || block_idx >= total_blocks) {
                acc = nanf("");
                break;
            }
            const float* v_ptr = v_blocks + ((block_idx * block_size + block_offset) * num_kv_heads + kv_head_idx) * head_dim;
            acc += scores[t] * v_ptr[d];
        }
        out_ptr[d] = acc;
    }
}

extern "C" __global__ void PagedRoPEStoreKV(
	const float* __restrict__ q,
	const float* __restrict__ k,
	const float* __restrict__ v,
	float* __restrict__ q_rope,
	float* __restrict__ k_blocks,
	float* __restrict__ v_blocks,
	const int* __restrict__ block_tables,
	const int* __restrict__ seq_indices,
	const int* __restrict__ positions,
	int num_tokens,
	int max_blocks_per_seq,
	int block_size,
	int num_q_heads,
	int num_kv_heads,
	int head_dim,
	int num_seqs,
	int total_blocks,
	const float* __restrict__ inv_freq,
	int* __restrict__ status
) {
	int token = blockIdx.y;
	int i = blockIdx.x * blockDim.x + threadIdx.x;
	if (token >= num_tokens) return;
	int seq = seq_indices[token];
	int pos = positions[token];
	int block_number = pos >= 0 && block_size > 0 ? pos / block_size : -1;
	if (seq < 0 || seq >= num_seqs || pos < 0 || block_size <= 0 || max_blocks_per_seq <= 0 ||
		head_dim <= 0 || (head_dim & 1) != 0 || num_q_heads <= 0 || num_kv_heads <= 0 || inv_freq == nullptr ||
		block_number >= max_blocks_per_seq) {
		if (i == 0) atomicExch(status, 1);
		return;
	}
	int slot = block_tables[seq * max_blocks_per_seq + block_number];
	if (slot < 0 || slot >= total_blocks) {
		if (i == 0) atomicExch(status, 1);
		return;
	}
	int half = head_dim / 2;
	int q_dim = num_q_heads * head_dim;
	if (i < q_dim) {
		int d = i % head_dim;
		int pair_d = d < half ? d + half : d - half;
		int freq_d = d < half ? d : pair_d;
		float sin_val, cos_val;
		sincos_2pi(rope_turns((float)pos, inv_freq[freq_d]), &sin_val, &cos_val);
		float a = q[token * q_dim + i];
		float b = q[token * q_dim + (i - d) + pair_d];
		q_rope[token * q_dim + i] = d < half ? a * cos_val - b * sin_val : b * sin_val + a * cos_val;
	}
	int kv_dim = num_kv_heads * head_dim;
	if (i < kv_dim) {
		int d = i % head_dim;
		int pair_d = d < half ? d + half : d - half;
		int freq_d = d < half ? d : pair_d;
		float sin_val, cos_val;
		sincos_2pi(rope_turns((float)pos, inv_freq[freq_d]), &sin_val, &cos_val);
		float a = k[token * kv_dim + i];
		float b = k[token * kv_dim + (i - d) + pair_d];
		float rotated = d < half ? a * cos_val - b * sin_val : b * sin_val + a * cos_val;
		int dst = ((slot * block_size + pos % block_size) * num_kv_heads * head_dim) + i;
		k_blocks[dst] = rotated;
		v_blocks[dst] = v[token * kv_dim + i];
	}
}

// PackedPagedRoPEStoreKV writes only generation-valid packed tokens into the
// private physical pages already pinned by the batch transaction.
extern "C" __global__ void PackedPagedRoPEStoreKV(
    const float* __restrict__ q,
    const float* __restrict__ k,
    const float* __restrict__ v,
    float* __restrict__ q_rope,
    float* __restrict__ k_blocks,
    float* __restrict__ v_blocks,
    const int* __restrict__ block_tables,
    const int* __restrict__ final_seq_lens,
    const unsigned long long* __restrict__ row_generations,
    const int* __restrict__ token_rows,
    const int* __restrict__ token_positions,
    const unsigned long long* __restrict__ token_generations,
    int num_tokens,
    int metadata_rows,
    int max_blocks_per_seq,
    int block_size,
    int num_q_heads,
    int num_kv_heads,
    int head_dim,
    int total_blocks,
    const float* __restrict__ inv_freq,
    int* __restrict__ row_status
) {
    int token = blockIdx.y;
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (token >= num_tokens) return;
    int row = token_rows[token];
    bool valid_row = row >= 0 && row < metadata_rows;
    int pos = valid_row ? token_positions[token] : -1;
    int block_number = pos >= 0 && block_size > 0 ? pos / block_size : -1;
    bool valid = valid_row && pos >= 0 && pos < final_seq_lens[row] && block_size > 0 &&
        max_blocks_per_seq > 0 && block_number < max_blocks_per_seq && head_dim > 0 &&
        (head_dim & 1) == 0 && num_q_heads > 0 && num_kv_heads > 0 && inv_freq != nullptr &&
        token_generations[token] != 0 && token_generations[token] == row_generations[row];
    int slot = valid ? block_tables[row * max_blocks_per_seq + block_number] : -1;
    valid = valid && slot >= 0 && slot < total_blocks && row_status[row] == 0;
    if (!valid) {
        if (i == 0 && metadata_rows > 0) atomicExch(row_status + (valid_row ? row : 0), 1);
        int q_dim = num_q_heads * head_dim;
        if (i < q_dim) q_rope[token * q_dim + i] = nanf("");
        return;
    }
    int half = head_dim / 2;
    int q_dim = num_q_heads * head_dim;
    if (i < q_dim) {
        int d = i % head_dim;
        int pair_d = d < half ? d + half : d - half;
        int freq_d = d < half ? d : pair_d;
        float sin_val, cos_val;
        sincos_2pi(rope_turns((float)pos, inv_freq[freq_d]), &sin_val, &cos_val);
        float a = q[token * q_dim + i];
        float b = q[token * q_dim + (i - d) + pair_d];
        q_rope[token * q_dim + i] = d < half ? a * cos_val - b * sin_val : b * sin_val + a * cos_val;
    }
    int kv_dim = num_kv_heads * head_dim;
    if (i < kv_dim) {
        int d = i % head_dim;
        int pair_d = d < half ? d + half : d - half;
        int freq_d = d < half ? d : pair_d;
        float sin_val, cos_val;
        sincos_2pi(rope_turns((float)pos, inv_freq[freq_d]), &sin_val, &cos_val);
        float a = k[token * kv_dim + i];
        float b = k[token * kv_dim + (i - d) + pair_d];
        float rotated = d < half ? a * cos_val - b * sin_val : b * sin_val + a * cos_val;
        int dst = ((slot * block_size + pos % block_size) * num_kv_heads * head_dim) + i;
        k_blocks[dst] = rotated;
        v_blocks[dst] = v[token * kv_dim + i];
    }
}
`

BatchedPagedAttentionTemplate is the embedded CUDA C++ kernel for multi-sequence paged KV-cache attention.

PagedRoPEStoreKV and PackedPagedRoPEStoreKV rotate q and k by inv_freq, a device table of head_dim/2 inverse frequencies: pair i (dimensions i and i+head_dim/2) turns by pos*inv_freq[i]. The table carries any rope scaling; the kernels apply none of their own.

View Source
const CausalFlashAttentionTemplate = `` /* 5009-byte string literal not displayed */

CausalFlashAttentionTemplate is the embedded CUDA C++ source for causal single-sequence decode attention. Launch one block per query head with any block width. Use BatchedPagedAttentionTemplate for multiple sequences.

It defines two entry points that compute the same function. CausalFlashAttentionDecode takes the position cur_pos as an argument and needs shared memory from DecodeSharedMemoryBytes for cur_pos+1 tokens. CausalFlashAttentionDecodeDevicePos reads it from pos_ptr[0] in device memory, clamped to [0, max_seq_len-1], so a captured CUDA graph can replay it at every position without a parameter update. Its shared memory must cover max_seq_len tokens.

View Source
const DefaultBarrierTimeout = time.Second

DefaultBarrierTimeout is the LlamaDecodeConfig.BarrierTimeout used when none is set. A step's longest phase takes milliseconds alone, and tens of milliseconds while a co-running kernel holds SMs until it is told to yield, so a second leaves room for both.

View Source
const FusedResidualRMSNormSource = `` /* 7867-byte string literal not displayed */

FusedResidualRMSNormSource is the CUDA C++ source for the single-pass fused ResidualAdd + RMSNorm kernels: fused_residual_rmsnorm_f32 (FP32 output) and fused_residual_rmsnorm_bf16 (RNE-packed BF16 output).

Each CTA processes one row using a multiple-of-32 block width (typically 256 threads) and dynamic shared memory sized by ResidualRMSNormSharedBytes. On the aligned fast path, x and residual are loaded with 128-bit float4 loads, summed once, written back to residual in-place, staged in shared memory (eliminating any global re-read of residual), reduced across warps with __shfl_down_sync and __syncthreads, and scaled by weight to write out. Odd hidden dimensions and unaligned row pointers fall back cleanly to a scalar tail loop.

View Source
const IndexedSource = `` /* 4356-byte string literal not displayed */

IndexedSource is an independently written ordinary FP32 CUDA baseline. One thread handles each query head. Mode 0 validates mapping, mode 1 additionally validates selection, mode 2 computes attention, and mode 3 computes scores. Compute modes are submitted only after the separate validation has completed. Scores are the maximum scaled Q dot K over visible tokens in each block; fully masked blocks have negative infinity. This is a deterministic proxy, not a learned selector or a claim of equivalence to full dense attention.

View Source
const KDAFP32 = "kda-d128-fp32-rn-separate-vk-v1"

KDAFP32 names the preactivated, per-key-channel, separately rounded FP32 numerical mode. It does not identify upstream FlashKDA's BF16 chunk mode.

View Source
const KDASource = `` /* 1372-byte string literal not displayed */

KDASource is the ordinary D=128 FP32 recurrence. One CUDA thread executes the bounded batch in order. State is [sequence,head,value,key]; token arrays are [token,head,channel]. Every multiply and add rounds separately to nearest FP32, with increasing-key reductions, no FMA and no flush-to-zero. Scratch receives all results; status is zero only when every result is finite. Public output/state publication is a separate operation after completion.

View Source
const Kernel = "fused_rmsnorm_swiglu_gemv"

Kernel is the name of each candidate's entry function in its Lines.

View Source
const KernelStreamBlockThreads = 256

KernelStreamBlockThreads is the block size every candidate is written for: each stage indexes 256 elements by threadIdx.x, the shared reductions span 256 threads, and __launch_bounds__ names 256. The grid is one block.

View Source
const Llama1BMaxVerifyM = 8

Llama1BMaxVerifyM is the maximum number of tokens (M = K + 1, 1 pending token plus up to 7 draft tokens) verified in parallel per weight read by the persistent decode megakernel.

View Source
const MHCBF16PostSource = `` /* 995-byte string literal not displayed */

MHCBF16PostSource holds the BF16 mHC post-mix CUDA C++ kernel.

View Source
const MHCNormalizeSource = `` /* 1334-byte string literal not displayed */

Scaling the positive denominator keeps finite positive epsilon, including very large epsilon, from overflowing a four-element sum in FP32.

View Source
const MHCPostSource = `` /* 587-byte string literal not displayed */
View Source
const MLACUDATemplate = `` /* 2074-byte string literal not displayed */

MLACUDATemplate contains the low-rank Multi-Head Latent Attention CUDA decode kernel.

View Source
const OuterKernelTemplate = `` /* 1007-byte string literal not displayed */

OuterKernelTemplate is the outer kernel template that splices a fused MLP device function. Template authors should write C++ nested-brace initializers such as {{x}} as { {x} }, because {{IDENT}} is reserved placeholder syntax.

View Source
const ProjectionResidualRMSNormTemplate = `` /* 6888-byte string literal not displayed */

ProjectionResidualRMSNormTemplate is the CUDA source for the shared-weight projections and normalization stages of one packed decoder layer.

View Source
const RegionRMSNormQKV = "rmsnorm_qkv"

RegionRMSNormQKV is the canonical IKET region name for the fused pre-attention RMSNorm + QKV projection stage in the Llama decode megakernel.

View Source
const RoPEAngleSource = `` /* 1441-byte string literal not displayed */

RoPEAngleSource is CUDA C++ source for the two device functions the paged RoPE kernels compute their angles with. rope_turns(pos, inv_freq) returns the angle pos*inv_freq in turns (1 turn = 2π), reduced to [-0.5, 0.5] without first rounding the angle to float; sincos_2pi(turns, &s, &c) sets the sine and cosine of that many turns. They match eg_rope_turns and eg_sincos_2pi_f32 in github.com/tmc/lib/nvidia/x/tile/tcgen05. BatchedPagedAttentionTemplate begins with it.

View Source
const SplitKCUDATemplate = `` /* 3516-byte string literal not displayed */

SplitKCUDATemplate contains the 2-stage parallel Split-K FlashDecoding CUDA kernel.

View Source
const TreeAttentionCUDA = `` /* 3365-byte string literal not displayed */

TreeAttentionCUDA is the CUDA C++ kernel executing 2D Causal Tree Attention with 64-bit row bitmasks.

Launch it with grid (num_nodes, num_heads), a power-of-two block size, and TreeAttentionSharedBytes of dynamic shared memory. Trees wider than TreeAttentionMaxNodes have no bitmask representation and are truncated.

View Source
const TreeAttentionMaxNodes = 64

TreeAttentionMaxNodes is the largest candidate tree a uint64 row bitmask can encode.

View Source
const UnfusedRMSNormSource = `` /* 6275-byte string literal not displayed */

UnfusedRMSNormSource is the CUDA C++ source for pass 2 of the unfused 2-kernel baseline. It provides rmsnorm_unfused_f32 (FP32 output) and rmsnorm_unfused_f32_to_bf16 (RNE-packed BF16 output). Launch one CTA per row with a multiple-of-32 block width (typically 256 threads) and 0 dynamic shared memory.

View Source
const UnfusedResidualAddSource = `` /* 997-byte string literal not displayed */

UnfusedResidualAddSource is the CUDA C++ source for pass 1 of the unfused 2-kernel baseline: residual_add_f32 computes residual[i] += x[i] using 128-bit float4 vectorization when pointers are 16-byte aligned, plus a scalar tail for unaligned lengths or pointers.

Variables

View Source
var ErrBarrierTimeout = errors.New("cudalayer: grid barrier timed out")

ErrBarrierTimeout matches an *AbortError whose cause is [stepdesc.AbortDeadline]: a grid barrier wait outlived the config's LlamaDecodeConfig.BarrierTimeout.

View Source
var ErrInvalidConfig = errors.New("cudaattn: invalid configuration")

ErrInvalidConfig reports an attention shape that the kernels cannot execute.

View Source
var ErrInvalidMLPConfig = errors.New("cudalayer: invalid fused MLP configuration")

ErrInvalidMLPConfig reports an invalid MLP architecture configuration.

View Source
var ErrTreeAttentionShape = ref.ErrTreeAttentionShape

ErrTreeAttentionShape indicates invalid dimensions for tree attention.

Functions

func BF16ToFloat32

func BF16ToFloat32(b uint16) float32

BF16ToFloat32 widens a bfloat16 bit pattern to float32 by zero-extending the low 16 mantissa bits.

func CandidateBlockMaxCPU

func CandidateBlockMaxCPU(
	blockScores []float32,
	seqLen int,
	cfg CandidateBlockConfig,
) (selectedBlocks []int32, paddedTokens []int32, err error)

CandidateBlockMaxCPU implements _candidate_block_max_kernel (deepinfer/kernels/candidate_block.py): forces the first block (0) and last RecentBlocks blocks to +inf, masks out-of-bounds blocks to -inf, selects top BlockTopK blocks, expands each selected block into BlockSize token indices, and pads with -1 to a multiple of ChunkBlocks * BlockSize.

Example
package main

import (
	"fmt"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	cfg := nnattn.CandidateBlockConfig{
		BlockSize:        4,
		BlockTopK:        3,
		TokenTopK:        8,
		RecentBlocks:     1,
		ChunkBlocks:      2,
		ComputeChunkSize: 8192,
	}
	scores := []float32{0.1, 2.5, 9.0, 1.0, 0.2}
	blocks, tokens, err := nnattn.CandidateBlockMaxCPU(scores, 18, cfg)
	if err != nil {
		panic(err)
	}
	fmt.Printf("blocks=%v paddedLen=%d\n", blocks, len(tokens))
}
Output:
blocks=[0 4 2] paddedLen=16

func CheckAttentionVariant

func CheckAttentionVariant(kernel string, has AttentionFeatures, v AttentionVariant, headDim int) error

CheckAttentionVariant returns an error naming each feature v needs that a kernel implementing has does not.

func CheckIndexedStatus

func CheckIndexedStatus(status []int32, rows int) error

CheckIndexedStatus requires successful evidence from every expected row. Status 1 is metadata/ID damage, 2 is nonfinite input or arithmetic.

Example
package main

import (
	"fmt"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	fmt.Println(nnattn.CheckIndexedStatus([]int32{0, 0}, 2))
}
Output:
<nil>

func Compile

func Compile(major, minor int) (*nvrtc.CompiledModule, error)

Compile builds the JIT FlashAttention decode module.

func CompileIndexedArtifact

func CompileIndexedArtifact(target string) (*cudakernel.Artifact, error)

CompileIndexedArtifact compiles the exact baseline into a direct CUBIN, without a device or a driver JIT. target is an explicit physical architecture, such as sm_121. Compiler selection is supplied through nvrtc's existing loader API.

Example
package main

import (
	"fmt"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	_, err := nnattn.CompileIndexedArtifact("compute_121")
	fmt.Println(err)
}
Output:
cudaattn: invalid indexed physical target

func CompileLayer

func CompileLayer(major, minor int) (*nvrtc.CompiledModule, error)

Compile builds the decoder-layer JIT module for a CUDA architecture.

func CompilePaged

func CompilePaged(major, minor int) (*nvrtc.CompiledModule, error)

CompilePaged builds the JIT Batched Paged Attention decode module.

func DecodeBF16

func DecodeBF16(b uint16) float32

DecodeBF16 widens a bfloat16 bit pattern to float32.

func DecodeFP8E4M3

func DecodeFP8E4M3(b uint8) float32

DecodeFP8E4M3 widens an FP8 E4M3FN byte to float32 using the exact device bit-manipulation schedule.

func DecodeSharedMemoryBytes

func DecodeSharedMemoryBytes(seqLen, threads int) (int, error)

DecodeSharedMemoryBytes returns the dynamic shared-memory requirement for a single-sequence decode block covering seqLen tokens with the given block width. The block reduces its per-thread maximum and sum through a scratch buffer of one float per thread, which sits after the scores.

A single-thread block skips the reduction and never touches the scratch buffer, so callers launching with a width of one may still allocate only 4*seqLen bytes.

Example
package main

import (
	"fmt"
	"log"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	cfg := nnattn.DefaultConfig(32, 8, 128)
	if err := cfg.Validate(); err != nil {
		log.Fatal(err)
	}
	// One block per query head, 128 threads, 4096 cached tokens.
	shared, err := nnattn.DecodeSharedMemoryBytes(4096, 128)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(cfg.NumQHeads, "blocks,", shared, "bytes of shared memory each")
}
Output:
32 blocks, 16896 bytes of shared memory each

func DecoderIKETDAG

func DecoderIKETDAG() (*iket.DAG, error)

DecoderIKETDAG constructs the six-stage causal dependency DAG (rmsnorm -> qkv -> rope -> attn -> o_proj -> mlp) for a decoder layer.

Example
dag, err := DecoderIKETDAG()
if err != nil {
	fmt.Println(err)
	return
}
fmt.Printf("name=%s regions=%d edges=%d first=%s->%s last=%s->%s\n",
	dag.Name, len(dag.Regions), len(dag.Edges),
	dag.Edges[0].Source, dag.Edges[0].Target,
	dag.Edges[len(dag.Edges)-1].Source, dag.Edges[len(dag.Edges)-1].Target)
Output:
name=decoder_layer regions=6 edges=5 first=rmsnorm->qkv last=o_proj->mlp

func DecoderIKETEventNames

func DecoderIKETEventNames() map[uint16]string

DecoderIKETEventNames returns the event-ID-to-name mapping used by InstrumentDecoderKernelSource and TraceDecoderLayer.

func DecoderIKETRegions

func DecoderIKETRegions() []string

DecoderIKETRegions returns the six ordered causal regions of a single-rank transformer decoder layer (without collective all-reduce).

func EmitEGraphCompositeAdd

func EmitEGraphCompositeAdd(kernelName, precision string) string

func EmitEGraphFusedGEMVPipeline

func EmitEGraphFusedGEMVPipeline(kernelName, precision string) string

func EmitEGraphFusedRoPEStoreKV

func EmitEGraphFusedRoPEStoreKV(kernelName string) string

func EmitEGraphRMSNormGEMV

func EmitEGraphRMSNormGEMV(kernelName, precision, epsExpr, weightExpr string) string

func EmitEGraphSwiGLU

func EmitEGraphSwiGLU(kernelName, precision string) string

func EmitMHCFusedCUDA

func EmitMHCFusedCUDA(normSource string) (string, error)

EmitMHCFusedCUDA splices the Sinkhorn normalization body from normSource into a single fused mHC kernel.

func EncodeBF16RNE

func EncodeBF16RNE(f float32) uint16

EncodeBF16RNE converts a float32 to round-to-nearest-even bfloat16 bits.

func EncodeFP8E4M3

func EncodeFP8E4M3(f float32) uint8

EncodeFP8E4M3 quantizes a float32 to the nearest FP8 E4M3FN byte.

func ExecuteMHCPrePostCPU

func ExecuteMHCPrePostCPU(
	yPrev []float32,
	hPrev []float32,
	postMixPrev []float32,
	resMixPrev []float32,
	preMixNext []float32,
	numTokens, numStreams, hiddenDim int,
) (xInNext []float32, hOut []float32, err error)

ExecuteMHCPrePostCPU fuses the previous sub-layer's post-mix residual update

hOut[t, s, d] = sum_j(resMixPrev[t, s, j] * hPrev[t, j, d]) + postMixPrev[t, s] * yPrev[t, d]

with the next sub-layer's pre-mix stream contraction

xInNext[t, d] = sum_s(preMixNext[t, s] * hOut[t, s, d])

in a single pass without an intermediate HBM round-trip, matching DeepInfer's _hc_fused_post_pre_kernel.

func Float32ToBF16RNE

func Float32ToBF16RNE(f float32) uint16

Float32ToBF16RNE converts f to IEEE-754 bfloat16 using round-to-nearest-even (RNE), matching CUDA's __float2bfloat16_rn and the bit-level packing in FusedResidualRMSNormSource and UnfusedRMSNormSource.

func FormatStageBreakdown

func FormatStageBreakdown(summaries []iket.RegionSummary) string

FormatStageBreakdown formats the five IKET region summaries for diagnostic logging.

func FusedNormRoPEHadamardCastStoreKVSource

func FusedNormRoPEHadamardCastStoreKVSource(cfg NormRoPEHadamardKVConfig) (string, error)

FusedNormRoPEHadamardCastStoreKVSource generates NVRTC-compilable CUDA C++ kernel source with warp-butterfly Walsh-Hadamard transform (__shfl_xor_sync), RMSNorm, RoPE, and quantized KV page write.

func FusedNormRoPEHadamardQuantStoreKVCPU

func FusedNormRoPEHadamardQuantStoreKVCPU(
	ckv []float32,
	kpe []float32,
	rmsWeight []float32,
	cosSin []float32,
	cfg NormRoPEHadamardKVConfig,
) (quantNoPE []byte, scales []float32, rotKPE []float32, err error)

FusedNormRoPEHadamardQuantStoreKVCPU fuses RMSNorm on ckv, RoPE rotation on kpe, normalized Walsh-Hadamard butterfly transform across both ckv and kpe, and block quantization into FP8/FP4 cache slots.

func GenerateMLACUDAShader

func GenerateMLACUDAShader(cfg MLAConfig) string

GenerateMLACUDAShader returns the MLA CUDA C++ shader source.

func GenerateSplitKCUDAShader

func GenerateSplitKCUDAShader(cfg SplitKConfig) string

GenerateSplitKCUDAShader returns the Split-K CUDA C++ shader source.

func GenerateTreeAttentionCUDAShader

func GenerateTreeAttentionCUDAShader() string

GenerateTreeAttentionCUDAShader returns the TreeFlashAttention CUDA C++ shader source.

func IdentityPreMix

func IdentityPreMix(numTokens, numStreams int, scale float32) ([]float32, error)

IdentityPreMix generates uniform pre-mix weights of shape [numTokens, numStreams] for Layer 0 hc_shifted initialization. When scale == 0, scale defaults to 1.0 / float32(numStreams).

func IndexedSchema

func IndexedSchema() (kernel.Schema, error)

IndexedSchema returns the exact pointer/scalar ABI shared by all four modes.

Example
package main

import (
	"fmt"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	s, err := nnattn.IndexedSchema()
	fmt.Println(len(s.Params), err)
}
Output:
28 <nil>

func IndexedTopKConfig

func IndexedTopKConfig(c IndexedConfig) (layout.TopKConfig, error)

IndexedTopKConfig returns the exact public TopK configuration for the proxy pipeline. Shared KV-head selection is unsupported by this per-query-head proxy.

Example
package main

import (
	"fmt"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	c := nnattn.IndexedConfig{Batch: 1, Queries: 1, QueryHeads: 2, KVHeads: 1, HeadDim: 8, BlockSize: 4, MaxSequence: 9, PhysicalBlocks: 3, SelectedBlocks: 2, Selection: nnattn.IndexedQueryHeads, Scale: 0.5}
	s, err := nnattn.IndexedTopKConfig(c)
	fmt.Println(s.Rows, s.Width, s.K, err)
}
Output:
2 3 2 <nil>

func InstrumentDecoderKernelSource

func InstrumentDecoderKernelSource(cfg ProjectionNormConfig) (source, entry string, err error)

InstrumentDecoderKernelSource emits a CUDA C++ kernel that executes a transformer decoder layer instrumented with cudaprofile.cuh range tokens across the six canonical regions (rmsnorm, qkv, rope, attn, o_proj, mlp).

func KDASchema

func KDASchema() (kernel.Schema, error)

KDASchema describes the exact kda_fp32 kernel parameter ABI.

Example
package main

import (
	"fmt"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	schema, err := nnattn.KDASchema()
	fmt.Println(len(schema.Params), err)
}
Output:
13 <nil>

func KernelStreamEntry

func KernelStreamEntry(index int) string

KernelStreamEntry returns the name of the entry function KernelStreamTU gives the candidate with the given index. KernelStreamTU declares it extern "C", so the name is not mangled.

func KernelStreamRewrite

func KernelStreamRewrite(baseLines, rules []string) (lines, applied []string)

KernelStreamRewrite applies the named rewrite rules, in order, to baseLines, a candidate's 30 source lines, and returns the rewritten lines and the rules it applied: lowercased, without duplicates or unknown names. If baseLines has fewer than 30 elements, KernelStreamRewrite starts from the first candidate's lines with baseLines laid over them; if more, it uses the first 30. It does not modify baseLines.

The rules are:

vec4_ldg128         128-bit float4 loads in Stage s0
warp_shfl_bfly      warp butterfly reduction in Stage s0
swizzle_128b        128-byte XOR swizzle of s_norm
reg_tile_2x4        two float4 weights per loop step in Stage s1
launch_bounds_4cta  __launch_bounds__(256, 4)
fast_math_mufu      __expf and __frcp_rn in Stage s1
cp_async_2stage     streaming __ldcs weight loads in Stage s1
l2_evict_last       __ldca activation loads in Stage s0
Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	lines, applied := attn.KernelStreamRewrite(nil, []string{"launch_bounds_4cta", "bogus"})
	fmt.Println(applied)
	fmt.Println(lines[0])
	fmt.Println(lines[26])
}
Output:
[launch_bounds_4cta]
// Stage s0: Fused RMSNorm (launch_bounds_4cta)
__global__ void __launch_bounds__(256, 4) fused_rmsnorm_swiglu_gemv(const float* x, const float* w, const float* W_up, float* out) {

func KernelStreamTU

func KernelStreamTU(cands []KernelStreamCandidate) string

KernelStreamTU returns one CUDA C++ translation unit holding cands. It prefixes each candidate's functions with cand_NN_, after its Index, so that they do not collide, and declares each entry function extern "C".

func LaunchDecoderLayerIKET

func LaunchDecoderLayerIKET(ctx context.Context, dev *cuda.Device, cfg ProjectionNormConfig, tokens int) (*iket.Trace, []float32, error)

LaunchDecoderLayerIKET compiles and executes the instrumented decoder-layer kernel on dev for the given number of tokens, returning the decoded GPU IKET trace (with token_id payloads 0..tokens-1 recorded directly on the device) and output activations.

func LlamaDecodeMegakernelSource

func LlamaDecodeMegakernelSource(cfg LlamaDecodeConfig) (source, entry string, err error)

LlamaDecodeMegakernelSource emits the persistent multi-CTA CUDA C++ decode megakernel source and entry point for cfg.

func LlamaMegakernelIKETDAG

func LlamaMegakernelIKETDAG() (*iket.DAG, error)

LlamaMegakernelIKETDAG constructs the five-stage causal dependency DAG (rmsnorm_qkv -> rope -> attn -> o_proj -> mlp) for the fused Llama decode megakernel.

Example
package main

import (
	"fmt"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	dag, err := nnattn.LlamaMegakernelIKETDAG()
	if err != nil {
		panic(err)
	}
	for _, e := range dag.Edges {
		fmt.Printf("%s -> %s\n", e.Source, e.Target)
	}
}
Output:
rmsnorm_qkv -> rope
rope -> attn
attn -> o_proj
o_proj -> mlp

func LlamaMegakernelIKETEventNames

func LlamaMegakernelIKETEventNames() map[uint16]string

LlamaMegakernelIKETEventNames returns the event-ID-to-name mapping for the five fused megakernel stage regions and the token_done marker.

func LlamaMegakernelIKETRegions

func LlamaMegakernelIKETRegions() []string

LlamaMegakernelIKETRegions returns the five ordered causal stage regions of the fused Llama decode megakernel (rmsnorm_qkv -> rope -> attn -> o_proj -> mlp).

func MHCPrePostFusedSource

func MHCPrePostFusedSource(cfg MHCPrePostConfig) (string, error)

MHCPrePostFusedSource returns self-contained NVRTC-compilable CUDA C++ source implementing _hc_fused_post_pre_kernel and _hc_PreSplitMixes_kernel.

func PadAttentionHeads

func PadAttentionHeads(numHeads int) (paddedHeads int, padCount int, err error)

PadAttentionHeads snaps numHeads up to hardware-supported FlashMLA head counts ({64, 128}), returning cudaerrors.ErrUnsupported if numHeads <= 0 || numHeads > 128.

Example
package main

import (
	"fmt"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	padded, padCount, err := nnattn.PadAttentionHeads(48)
	if err != nil {
		panic(err)
	}
	fmt.Printf("padded=%d padCount=%d\n", padded, padCount)
}
Output:
padded=64 padCount=16

func PagedSharedMemoryBytes

func PagedSharedMemoryBytes(maxSeqLen, threads int) (int, error)

PagedSharedMemoryBytes returns the dynamic shared-memory requirement for a paged decode block. Threads must be a positive power of two.

Example

The paged kernel needs shared memory proportional to the longest sequence a block will scan; ask for the size before launching it.

package main

import (
	"fmt"
	"log"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	n, err := nnattn.PagedSharedMemoryBytes(1024, 256)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(n)
}
Output:
5120

func PermuteQBProj

func PermuteQBProj(weights []float32, numHeads, qNopeDim, qRopeDim, inDim int) ([]float32, error)

PermuteQBProj permutes q_b_proj weights by splitting the RoPE tail (qRopeDim) from [numHeads, qRopeDim/2, 2, inDim] and transposing pairs (dim 1, dim 2) to [numHeads, 2, qRopeDim/2, inDim] so FlashMLA's interleaved RoPE layout matches non-interleaved weights (MLA.weight_rearrange).

func PermuteWVProj

func PermuteWVProj(weights []float32, numHeads, kvLoraRank, vHeadDim int, padHeads int) ([]float32, error)

PermuteWVProj transposes w_v from [numHeads, vHeadDim, kvLoraRank] to [padHeads, kvLoraRank, vHeadDim] and zero-pads the head dimension up to padHeads ({64, 128}).

func ResidualRMSNormHardwareStatus

func ResidualRMSNormHardwareStatus(arch string) error

ResidualRMSNormHardwareStatus reports native hardware qualification status for the residual RMSNorm kernels on arch.

Known CUDA architectures wrap cuda.ErrHardwarePending until a native run on that target is recorded. Unknown architectures wrap cuda.ErrUnsupported.

func ResidualRMSNormRef

func ResidualRMSNormRef(x, residual, weight []float32, shape ResidualRMSNormShape) (out, updatedResidual []float32, err error)

ResidualRMSNormRef computes the pure-Go float64 reference oracle for fused ResidualAdd + RMSNorm over [shape.Rows, shape.Hidden]:

r[row, c] = x[row, c] + residual[row, c]
invRMS[row] = 1 / sqrt(mean_c(r[row, c]^2) + eps)
out[row, c] = r[row, c] * invRMS[row] * weight[c]

Input slices are never mutated. Both out and updatedResidual are returned freshly allocated with length Rows*Hidden.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	shape := attn.ResidualRMSNormShape{Rows: 1, Hidden: 2, Eps: 1e-5}
	x := []float32{1, 2}
	residual := []float32{2, 2}
	weight := []float32{1, 0.5}

	out, updatedResidual, err := attn.ResidualRMSNormRef(x, residual, weight, shape)
	if err != nil {
		panic(err)
	}
	fmt.Printf("residual=[%.1f %.1f] out=[%.4f %.4f]\n",
		updatedResidual[0], updatedResidual[1], out[0], out[1])
}
Output:
residual=[3.0 4.0] out=[0.8485 0.5657]

func ResidualRMSNormRefBF16

func ResidualRMSNormRefBF16(x, residual, weight []float32, shape ResidualRMSNormShape) (outBF16 []uint16, updatedResidual []float32, err error)

ResidualRMSNormRefBF16 computes the pure-Go float64 reference oracle with IEEE round-to-nearest-even (RNE) bfloat16 output packing, matching fused_residual_rmsnorm_bf16 and rmsnorm_unfused_f32_to_bf16.

func ResidualRMSNormSharedBytes

func ResidualRMSNormSharedBytes(hidden int) (smemBytes int, smemFloats int)

ResidualRMSNormSharedBytes returns the dynamic shared memory size in bytes and the number of cached row elements (smem_floats) to pass to fused_residual_rmsnorm_f32 or fused_residual_rmsnorm_bf16.

When hidden fits within MaxResidualRMSNormSmemFloats, the entire row of updated residuals r = x + residual is staged in shared memory so pass 2 never re-reads residual from global memory. Larger hidden dimensions pass smemFloats=0 and fall back to reading the updated residual through L2.

func RestoreCandidateIndices

func RestoreCandidateIndices(
	topPositionsInCandidates []int32,
	candidateTokens []int32,
	seqLen int,
	tokenTopK int,
) ([]int32, error)

RestoreCandidateIndices maps Stage-2 top-k positions back to global KV token indices (restore_indices), returning identity 0..seqLen-1 padded with -1 when seqLen <= tokenTopK.

func SparseMQALogitsCPU

func SparseMQALogitsCPU(
	q []float32,
	kPool []float32,
	weights []float32,
	candidateTokens []int32,
	numHeads, headDim int,
	seqLen int,
) ([]float32, error)

SparseMQALogitsCPU computes weighted ReLU MQA scores sum_h w_h * max(0, q_h . k_cand) only at candidateTokens (fp8_Loads_and_mqa_logits), setting invalid or causal-masked positions to -inf.

func TraceDecoderLayer

func TraceDecoderLayer(ctx context.Context, cfg ProjectionNormConfig, tokens int) (*iket.Trace, []float32, error)

TraceDecoderLayer executes the instrumented decoder-layer kernel across the given number of tokens under cudahostemu, recording each region range and marker with its token_id payload (0..tokens-1) directly on the device via iket.cuh, and returns the resulting IKET trace and output activations.

func TreeAttentionReference

func TreeAttentionReference(q, k, v []float32, bitmasks []uint64, numNodes, numHeads, headDim int, scale float32) ([]float32, error)

TreeAttentionReference evaluates tree attention on the CPU in float64 using row bitmasks.

Example

Node 1 of a two-node candidate tree attends to its parent, node 0, and to itself; node 0 attends only to itself.

package main

import (
	"fmt"
	"log"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	q := []float32{1, 0, 1, 0}
	k := []float32{1, 0, 1, 0}
	v := []float32{2, 4, 6, 8}
	masks := []uint64{0b01, 0b11}
	out, err := nnattn.TreeAttentionReference(q, k, v, masks, 2, 1, 2, 1)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(out)
}
Output:
[2 4 4 6]

func TreeAttentionSharedBytes

func TreeAttentionSharedBytes(numNodes, blockSize int) int

TreeAttentionSharedBytes returns the dynamic shared memory, in bytes, that TreeFlashAttentionCUDA needs for a tree of numNodes nodes launched with blockSize threads per block. blockSize must be a power of two.

func TreeDenseReferenceMask

func TreeDenseReferenceMask(bitmasks []uint64, numNodes int) [][]bool

TreeDenseReferenceMask expands row bitmasks into a dense boolean mask matrix.

func ValidateIndexedRequest

func ValidateIndexedRequest(c IndexedConfig, r IndexedRequest) error

ValidateIndexedRequest checks metadata without using a device. Execute repeats this admission on device, including device-produced IDs, before reading KV.

Example
package main

import (
	"fmt"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	c := nnattn.IndexedConfig{Batch: 1, Queries: 1, QueryHeads: 1, KVHeads: 1, HeadDim: 2, BlockSize: 2, MaxSequence: 3, PhysicalBlocks: 2, SelectedBlocks: 2, Selection: nnattn.IndexedQueryHeads, Scale: 1, Causal: true}
	r := nnattn.IndexedRequest{Sequences: []int32{0}, Positions: []int32{2}, Lengths: []int32{3}, Pages: []int32{1, 0}, IDs: []int32{1, -1}, Counts: []int32{1}}
	fmt.Println(nnattn.ValidateIndexedRequest(c, r))
}
Output:
<nil>

Types

type AbortError

type AbortError struct {
	Cause uint32

	// Barrier names the barrier where the first CTA saw the cause, such
	// as "attn" or "lm_head", and Layer is its decoder layer, or -1 for a
	// barrier outside the layers. Barrier is empty if no CTA recorded one.
	Barrier string
	Layer   int

	// Epoch is the barrier's number in the step, counting from 1, and
	// Arrived how many of the grid's CTAs had arrived at it. Missing
	// lists the CTAs that had not, each with the last barrier it reached
	// before the stop: epoch 0 for a CTA that was not yet resident, a
	// lower epoch for one still in an earlier phase.
	Epoch   uint32
	Arrived int
	Grid    int
	Missing []BarrierCTA
}

An AbortError reports that the decode megakernel stopped early, at a grid barrier, and the [stepdesc] cause its abort word held: the barrier timed out ([stepdesc.AbortDeadline]) or the host raised one. The kernel's outputs are then incomplete.

func (*AbortError) Error

func (e *AbortError) Error() string

func (*AbortError) Is

func (e *AbortError) Is(target error) bool

Is reports whether target is ErrBarrierTimeout and e's cause is a barrier deadline.

type AttentionFeatures

type AttentionFeatures uint8

AttentionFeatures is a set of the variant paths an attention kernel implements, or that an AttentionVariant needs.

const (
	AttnWindow  AttentionFeatures = 1 << iota // a lower bound on each query's keys
	AttnSoftcap                               // logit softcap
	AttnSinks                                 // per-head sink logits
)

func (AttentionFeatures) String

func (f AttentionFeatures) String() string

String returns the features' names joined by "+", or "none".

type AttentionVariant

type AttentionVariant struct {
	// Window is the keys a query attends, its own included: a query at
	// position p sees positions p-Window+1 .. p. 0 means all of 0 .. p.
	Window int

	// Theta is the layer's RoPE base, the local base on a sliding layer
	// of a model that has one.
	Theta float64

	// RotaryDim is the leading lanes of a head that RoPE rotates; the
	// rest pass through. 0 means the whole head.
	RotaryDim int

	// Softcap, when positive, caps each scaled logit s at
	// Softcap·tanh(s/Softcap) before the softmax.
	Softcap float32

	// Sinks reports that each query head has a learned sink logit that
	// joins the softmax's denominator and adds no value. The launch
	// passes the logits, float [query heads], in the sinks pointer.
	Sinks bool
}

An AttentionVariant is one layer's attention parameters beyond plain causal attention, as a model's resolved configuration states them. The zero value is plain causal attention with no RoPE facts.

Kernels take it as the fixed-layout C struct eg_attn_variant (AttentionVariantCDecl), passed by value at launch. An attention kernel reads Window, Softcap and the sinks pointer; a RoPE kernel reads Theta and RotaryDim.

func AttentionVariantFor

func AttentionVariantFor(l modelfacts.Layer) (AttentionVariant, error)

AttentionVariantFor returns the attention variant of the layer l describes. A layer's facts come from a model's resolved configuration; modelfacts has no softcap or sinks yet, so the result has neither.

func (AttentionVariant) Attend

func (v AttentionVariant) Attend(pos int, score func(t int) float64, value func(t, j int) float64, sink float64, out []float64)

Attend writes to out the float64 attention output of a query at position pos under v: score(t) is its scaled logit for key position t, value(t, j) lane j of that key's value, and sink the head's sink logit when v has Sinks.

func (AttentionVariant) CInit

func (v AttentionVariant) CInit(sinks string) string

CInit returns a C++ expression of type eg_attn_variant holding v, with sinks, a C++ expression of type const float*, as its sinks pointer ("nullptr" when v has none).

func (AttentionVariant) Features

func (v AttentionVariant) Features() AttentionFeatures

Features returns the attention-kernel paths v needs. Theta and RotaryDim are RoPE's and need none.

func (AttentionVariant) RoPETable

func (v AttentionVariant) RoPETable(maxPos, headDim int, interleaved bool) ([]float32, error)

RoPETable returns the cos_sin_table a RoPE kernel such as [QKNormRoPEKVAppend] reads to rotate positions 0 .. maxPos-1 with v's theta, for heads of headDim lanes. Row pos holds v's rotary dim floats (headDim when RotaryDim is 0): the cosines of its pairs, then their sines, or each pair's cosine and sine side by side when interleaved. A model whose local and global layers differ only in theta runs one kernel with two tables.

func (AttentionVariant) Validate

func (v AttentionVariant) Validate(headDim int) error

Validate checks v's values for heads of headDim lanes.

type BarrierCTA

type BarrierCTA struct {
	CTA   int
	Epoch uint32
}

A BarrierCTA is a CTA missing from a barrier that timed out, and the epoch of the last barrier it reached.

type CUDALowerAttnGeom

type CUDALowerAttnGeom struct {
	G int
	// contains filtered or unexported fields
}

CUDALowerAttnGeom carries precomputed geometry for CUDALowerPagedAttnOpts.

func NewCUDALowerAttnGeom

func NewCUDALowerAttnGeom(G, rows, mrows, mt, kw, hpb, rb int) CUDALowerAttnGeom

NewCUDALowerAttnGeom constructs a CUDALowerAttnGeom.

type CUDALowerBroadcast

type CUDALowerBroadcast uint8

CUDALowerBroadcast mirrors the cudalower Broadcast enum.

type CUDALowerDType

type CUDALowerDType uint8

CUDALowerDType mirrors the cudalower DType enum for extracted kernel emitters.

func (CUDALowerDType) String

func (d CUDALowerDType) String() string

type CUDALowerDecodeAttnOpts

type CUDALowerDecodeAttnOpts struct {
	Name                                 string
	NumHeads, KVHeads, HeadDim, PageSize int
	Scale                                float32
	Variants                             AttentionFeatures
}

CUDALowerDecodeAttnOpts configures CUDALowerDecodeAttnOpts.CUDA.

func (CUDALowerDecodeAttnOpts) CUDA

func (a CUDALowerDecodeAttnOpts) CUDA() (string, error)

CUDA returns the kernel source, which needs [Prelude].

type CUDALowerMLAAttnOpts

type CUDALowerMLAAttnOpts struct {
	Name                                             string
	NumHeads, LatentDim, RopeDim, PageSize, MaxPages int
	Scale                                            float32
	KVFP8, Swizzle, WGMMA                            bool
	Params                                           []string
}

CUDALowerMLAAttnOpts configures CUDALowerMLAAttnOpts.CUDA.

func (CUDALowerMLAAttnOpts) CUDA

func (a CUDALowerMLAAttnOpts) CUDA() (string, error)

CUDA returns the device kernel source (without [Prelude]).

type CUDALowerOperand

type CUDALowerOperand struct {
	Name      string
	DType     CUDALowerDType
	Broadcast CUDALowerBroadcast
}

CUDALowerOperand mirrors the cudalower epilogue extra Operand.

type CUDALowerPagedAttnOpts

type CUDALowerPagedAttnOpts struct {
	Name            string
	Hq, Hkv         int
	QLen            int
	Window          int
	Page            int
	Q, Out          CUDALowerDType
	QScale, SMScale float32
	Chunk           int
	KVHeadsPerBlock int
	DeviceSplits    bool
	Depth           int
	Stages          int
	TableAhead      int
	QKFP8           bool
	WGMMA           bool
	Swizzle         bool
	ClusterCombine  bool
	Gate            bool
	GateStride      int
	GateOffset      int
	GateEps         float32
	Geom            CUDALowerAttnGeom
	Params          []string
}

CUDALowerPagedAttnOpts configures CUDALowerPagedAttnOpts.CUDA.

func (CUDALowerPagedAttnOpts) CUDA

func (a CUDALowerPagedAttnOpts) CUDA() (string, error)

CUDA returns the kernel source (without [Prelude]):

__global__ void Name(q, k_cache, v_cache, page_table, max_pages,
    seqlens, k_scale, v_scale, out, ws)

type CUDALowerPrefillAttnOpts

type CUDALowerPrefillAttnOpts struct {
	Name                                           string
	NumHeads, KVHeads, HeadDim, PageSize, MaxPages int
	Scale                                          float32
	Batched                                        bool
	Variants                                       AttentionFeatures
}

CUDALowerPrefillAttnOpts configures CUDALowerPrefillAttnOpts.CUDA.

func (CUDALowerPrefillAttnOpts) CUDA

CUDA returns the kernel's source, which needs [Prelude].

type CUDALowerQKRopeKVOpts

type CUDALowerQKRopeKVOpts struct {
	Name            string
	NumHeads        int
	KVHeads         int
	HeadDim         int
	RotaryDim       int
	PageSize        int
	MaxPages        int
	Eps             float32
	QKNorm          bool
	InterleavedRoPE bool
	KVFP8           bool
	DType           CUDALowerDType
	Params          []string
}

CUDALowerQKRopeKVOpts configures CUDALowerQKRopeKVOpts.CUDA.

func (CUDALowerQKRopeKVOpts) CUDA

func (k CUDALowerQKRopeKVOpts) CUDA() (string, error)

CUDA returns the device kernel source (without [Prelude]).

type CUDALowerScaleLayout

type CUDALowerScaleLayout uint8

CUDALowerScaleLayout mirrors the cudalower ScaleLayout enum.

func (CUDALowerScaleLayout) String

func (l CUDALowerScaleLayout) String() string

type CUDALowerStore

type CUDALowerStore uint8

CUDALowerStore mirrors the cudalower GEMMStore enum.

type CUDALowerTileEpilogue

type CUDALowerTileEpilogue uint8

CUDALowerTileEpilogue mirrors the cudalower TileEpilogue enum.

func (CUDALowerTileEpilogue) String

func (e CUDALowerTileEpilogue) String() string

type CUDALowerWeight

type CUDALowerWeight uint8

CUDALowerWeight mirrors the cudalower WeightFormat enum.

func (CUDALowerWeight) String

func (f CUDALowerWeight) String() string

type CandidateBlockConfig

type CandidateBlockConfig struct {
	BlockSize        int
	BlockTopK        int
	TokenTopK        int
	RecentBlocks     int
	ChunkBlocks      int
	ComputeChunkSize int
}

CandidateBlockConfig configures the DeepSelect two-stage block-level top-k indexer.

func (CandidateBlockConfig) Validate

func (c CandidateBlockConfig) Validate() error

Validate checks that c satisfies the DeepSelect two-stage indexer constraints: ComputeChunkSize > 0 && ComputeChunkSize <= 8192, BlockSize > 0, BlockTopK > 0, TokenTopK > 0.

type Config

type Config struct {
	NumQHeads  int
	NumKVHeads int
	HeadDim    int
	Scale      float32
}

Config defines the dimensional configuration for Multi-Head or Grouped Query Attention.

func DefaultConfig

func DefaultConfig(numQHeads, numKVHeads, headDim int) Config

DefaultConfig creates an attention configuration with the standard 1/sqrt(headDim) softmax scale.

func (Config) Validate

func (c Config) Validate() error

Validate checks the shape invariants shared by the dense and paged kernels. HeadDim must be even because PagedRoPEStoreKV applies split-half rotary embeddings. The kernels otherwise support arbitrary positive head sizes.

type DecodeMegakernelRunner

type DecodeMegakernelRunner interface {
	StepDecode(ctx context.Context, tokenID int32, pos int) (nextTokenID int32, err error)
	StepVerify(ctx context.Context, pendingToken int32, draftTokens []int32, pos int) (VerifyStepResult, error)
	Close() error
}

DecodeMegakernelRunner is the clean interface exposed to llama-infer for single-token and M=K+1 speculative decode steps.

type DecodeOption

type DecodeOption func(*decodeOptions)

A DecodeOption configures NewLlamaDecodeMegakernelGPU and NewLlamaDecodeMegakernelGPUBenchmark.

func WithDecodeStream

func WithDecodeStream(s *cuda.Stream, sms int) DecodeOption

WithDecodeStream runs the runner's kernel launches on s, in s's device's context, instead of on a stream of the runner's own, with a persistent grid of sms CTAs: one per SM that work on s may use. s must belong to the runner's device. A stream from cuda.Device.NewGreenStream confines the runner to that green context's SMs, and sms must then be the green context's SM count, or the grid barrier waits for CTAs that cannot be resident. The runner does not close s.

Example

ExampleWithDecodeStream confines a decode runner to a green context: its persistent grid is sized to the green context's SMs and every launch goes to a stream in it. It needs a GPU, so it has no output.

package main

import (
	"context"
	"fmt"

	"github.com/tmc/lib/nvidia/driver"
	"github.com/tmc/lib/nvidia/x/cuda"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	ctx := context.Background()
	dev, err := cuda.NewDevice(0)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer dev.Close()
	var green driver.GreenCtx // from cudagreen.Partitions.GreenCtx, with 32 SMs
	s, err := dev.NewGreenStream(green)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer s.Close()
	runner, err := nnattn.NewLlamaDecodeMegakernelGPUBenchmark(ctx, dev, nnattn.Llama32_1BConfig(), nnattn.WithDecodeStream(s, 32))
	if err != nil {
		fmt.Println(err)
		return
	}
	defer runner.Close()
	next, err := runner.StepDecode(ctx, 1, 0)
	fmt.Println(next, err)
}

type DecodeRoofline

type DecodeRoofline struct {
	WeightDType              DecodeWeightDType
	VerifyM                  int
	SeqLen                   int
	LayerWeightBytes         int64
	AllLayersWeightBytes     int64
	LMHeadWeightBytes        int64
	FinalNormBytes           int64
	TotalWeightBytes         int64
	KVCacheBytes             int64
	TotalHBMBytes            int64
	HBMBandwidthGBps         float64
	StepRooflineMs           float64
	SingleTokenTPOTMs        float64
	SingleTokenTokPerSec     float64
	VerifyEffectiveTPOTMs    float64
	VerifyEffectiveTokPerSec float64
}

DecodeRoofline summarizes the exact HBM byte traffic and theoretical bandwidth ceiling for a single decode or M-token speculative verification step.

type DecodeWeightDType

type DecodeWeightDType string

DecodeWeightDType identifies the weight storage format of the decode megakernel. FP8 mode is strictly labelled "fp8" so benchmark records never compare 1-byte FP8 runs against 2-byte BF16 baselines.

const (
	WeightDTypeBF16 DecodeWeightDType = "bf16"
	WeightDTypeFP8  DecodeWeightDType = "fp8"
)

func (DecodeWeightDType) BytesPerWeight

func (d DecodeWeightDType) BytesPerWeight() (int, error)

BytesPerWeight returns the byte width of one projection weight element.

type DraftProposer

type DraftProposer interface {
	Propose(ctx context.Context, history []int32, pendingToken int32, maxDraft int) ([]int32, error)
}

DraftProposer proposes up to maxDraft speculative continuation token IDs given the committed token history ending with pendingToken (for example, an EAGLE-style draft head, early-exit layer drafter, small draft model, or prompt-lookup n-gram drafter).

type FusedMLP

type FusedMLP struct {
	// contains filtered or unexported fields
}

FusedMLP expresses dense layers as a composable cudair tree. Forward child results use local vectors; each child saves its input and preactivation in bounded context for backward. Compiler register residency is not guaranteed.

func NewFusedMLP

func NewFusedMLP(inputWidth, hiddenWidth, outputWidth, numLayers int) (*FusedMLP, error)

NewFusedMLP constructs an MLP tree consisting of numLayers dense layers. For a 3-layer width-64 MLP, pass (64, 64, 64, 3).

Example
package main

import (
	"fmt"

	irgraph "github.com/tmc/lib/nvidia/x/ir/graph"
	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	// Construct a 3-layer width-64 MLP
	mlp, err := nnattn.NewFusedMLP(64, 64, 64, 3)
	if err != nil {
		fmt.Printf("err: %v\n", err)
		return
	}

	unit, err := irgraph.EmitTree(mlp, "fused_mlp_eval")
	if err != nil {
		fmt.Printf("err: %v\n", err)
		return
	}

	fmt.Printf("num symbols: %d\n", len(unit.Symbols))
}
Output:
num symbols: 4

func NewFusedMLPWithActivation

func NewFusedMLPWithActivation(inputWidth, hiddenWidth, outputWidth, numLayers int, activation string) (*FusedMLP, error)

NewFusedMLPWithActivation selects none, relu or silu for hidden layers. The output layer remains linear. ReLU's derivative at zero is zero. SiLU uses NVRTC __expf in both forward and backward. Architectures admit at most 1024 layers and checked signed-32-bit parameter and warp-context extents.

Example
package main

import (
	"fmt"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	m, _ := nnattn.NewFusedMLPWithActivation(5, 7, 3, 2, "silu")
	fmt.Println(m.ParameterCount())
}
Output:
56

func (*FusedMLP) BackwardBatch

func (m *FusedMLP) BackwardBatch(dev *cuda.Device, input, params, outputGradient, previous []float32, o MLPBackwardOptions) (result MLPGradients, err error)

BackwardBatch runs separate forward and backward CUDA kernels, then a separate deterministic parameter reduction in increasing sample order. It does not update weights or mutate any supplied host slice. Context is owned for this invocation and freed only after synchronous completion. An unresolved cleanup error implements io.Closer, reachable with errors.As; retry Close before closing dev. A failed synchronization retains all device buffers and the loaded module until a retry establishes completion. SiLU uses NVRTC __expf; ReLU's derivative at zero is zero. Parameter-only, input-only and combined requests share the same checked forward context.

Example
package main

import (
	"fmt"
	irgraph "github.com/tmc/lib/nvidia/x/ir/graph"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	m, _ := nnattn.NewFusedMLP(5, 3, 3, 1)
	o := nnattn.MLPBackwardOptions{Samples: 7, Input: true, ParameterMode: irgraph.GradientModeOverwrite, MaxBytes: 1 << 20}
	// A real CUDA device is required after host buffer validation.
	_, err := m.BackwardBatch(nil, make([]float32, 35), make([]float32, 15), make([]float32, 21), nil, o)
	fmt.Println(err)
}
Output:
cudalayer: nil backward device

func (*FusedMLP) BackwardShmemBytes

func (m *FusedMLP) BackwardShmemBytes(nThreads int, mode irgraph.GradientMode) int

BackwardShmemBytes reports the maximum demand of the child backward passes.

func (*FusedMLP) Children

func (m *FusedMLP) Children() []irgraph.Emitter

Children returns the ordered list of child layers for irgraph.EmitTree.

func (*FusedMLP) EmitBackward

func (m *FusedMLP) EmitBackward(name string, nThreads int) (string, error)

EmitBackward composes input gradients. Parameter writes are selected by irgraph.EmitBackwardTree's gradient mode.

func (*FusedMLP) EmitBackwardWithChildren

func (m *FusedMLP) EmitBackwardWithChildren(name string, children []irgraph.ChildSymbol, nThreads int, mode irgraph.GradientMode) (string, error)

EmitBackwardWithChildren composes backward functions in reverse layer order using the child symbols selected by irgraph.EmitBackwardTree.

func (*FusedMLP) EmitForward

func (m *FusedMLP) EmitForward(name string) (string, error)

EmitForward requires the tree emitter to assign child symbols and context.

func (*FusedMLP) EmitForwardWithChildren

func (m *FusedMLP) EmitForwardWithChildren(name string, children []irgraph.ChildSymbol) (string, error)

EmitForwardWithChildren composes the layers using symbols and context offsets assigned by irgraph.EmitTree.

func (*FusedMLP) FwdCtxAlignedPerElement

func (m *FusedMLP) FwdCtxAlignedPerElement() bool

FwdCtxAlignedPerElement reports whether context is aligned per element.

func (*FusedMLP) FwdCtxBytes

func (m *FusedMLP) FwdCtxBytes() (int, error)

FwdCtxBytes returns the parent's own context size, zero. irgraph.EmitTree includes the separately owned child regions in Unit.FwdCtxBytes.

func (*FusedMLP) InputWidth

func (m *FusedMLP) InputWidth() int

InputWidth returns model input width.

func (*FusedMLP) Name

func (m *FusedMLP) Name() string

Name returns the identifier of this MLP.

func (*FusedMLP) OutputWidth

func (m *FusedMLP) OutputWidth() int

OutputWidth returns model output width.

func (*FusedMLP) PaddedOutputWidth

func (m *FusedMLP) PaddedOutputWidth() int

PaddedOutputWidth returns model padded output width.

func (*FusedMLP) ParameterCount

func (m *FusedMLP) ParameterCount() int

ParameterCount returns the number of weights, with no bias or padding.

Example
package main

import (
	"fmt"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	m, _ := nnattn.NewFusedMLP(5, 7, 3, 2)
	fmt.Println(m.ParameterCount())
}
Output:
56

type IndexedAttention

type IndexedAttention struct {
	// contains filtered or unexported fields
}

IndexedAttention owns the ordinary artifact and loaded module. The zero value is closed. Methods serialize; do not copy an IndexedAttention. A returned nonnil error-result owner must be closed before closing its device.

func CompileIndexedAttention

func CompileIndexedAttention(dev *cuda.Device, c IndexedConfig) (*IndexedAttention, error)

CompileIndexedAttention compiles for the actual device and loads the baseline.

Example
package main

import (
	"fmt"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	c := nnattn.IndexedConfig{Batch: 1, Queries: 1, QueryHeads: 1, KVHeads: 1, HeadDim: 2, BlockSize: 2, MaxSequence: 3, PhysicalBlocks: 2, SelectedBlocks: 2, Selection: nnattn.IndexedQueryHeads, Scale: 1}
	_, err := nnattn.CompileIndexedAttention(nil, c)
	fmt.Println(err)
}
Output:
cudaattn: nil indexed device

func LoadIndexedAttention

func LoadIndexedAttention(dev *cuda.Device, c IndexedConfig, a *cudakernel.Artifact) (*IndexedAttention, error)

LoadIndexedAttention admits an independently retained baseline image and ABI. It verifies the exact schema, source identity and entry before loading. A digest binds bytes; it does not attest compiler provenance or correctness.

Example
package main

import (
	"fmt"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	c := nnattn.IndexedConfig{Batch: 1, Queries: 1, QueryHeads: 1, KVHeads: 1, HeadDim: 2, BlockSize: 2, MaxSequence: 3, PhysicalBlocks: 2, SelectedBlocks: 2, Selection: nnattn.IndexedQueryHeads, Scale: 1}
	_, err := nnattn.LoadIndexedAttention(nil, c, nil)
	fmt.Println(err)
}
Output:
cudaattn: nil indexed device

func (*IndexedAttention) Artifact

func (t *IndexedAttention) Artifact() *cudakernel.Artifact

Artifact returns a detached descriptor of the loaded image.

Example
package main

import (
	"fmt"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	var a nnattn.IndexedAttention
	fmt.Println(a.Artifact() == nil)
}
Output:
true

func (*IndexedAttention) Close

func (t *IndexedAttention) Close() error

Close drains a failed invocation and then unloads the module. A failed drain or cleanup retains ownership for a later retry. It never publishes scratch.

Example
package main

import (
	"fmt"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	var a nnattn.IndexedAttention
	fmt.Println(a.Close())
}
Output:
<nil>

func (*IndexedAttention) Execute

func (t *IndexedAttention) Execute(ctx context.Context, stream *cuda.Stream, b IndexedBuffers) error

Execute validates the device metadata/IDs in a separate completed dispatch, computes into scratch, validates status, then publishes output and LSE. A pre-publication refusal leaves output untouched. Publication failure leaves outputs undefined. Cancellation/drain failure retains every allocation borrow for retry Close; cancellation does not stop the GPU or release its resources.

Example
package main

import (
	"fmt"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	var a nnattn.IndexedAttention
	fmt.Println(a.Execute(nil, nil, nnattn.IndexedBuffers{}))
}
Output:
cudaattn: indexed closed or awaiting drain

func (*IndexedAttention) ExecuteSelection

func (t *IndexedAttention) ExecuteSelection(ctx context.Context, stream *cuda.Stream, b IndexedBuffers, selector *layout.TopK, selection layout.TopKBuffers) error

ExecuteSelection runs the real proxy-score -> public TopK.Execute -> indexed attention pipeline. selector must be compiled with IndexedTopKConfig. TopK's Input/Lengths/Offsets and published Indices/Counts must be the corresponding IndexedBuffers allocations; all its other buffers must be disjoint. No CPU score/sort or inferred head sharing participates. The caller retains selector and closes it after any failure, before freeing its allocations or device. TopK.Execute is synchronous and has no cancellation API; ctx is checked at each indexed stream drain. No timing channel is substituted for GPU duration.

Example
package main

import (
	"fmt"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
	"github.com/tmc/lib/nvidia/x/tile/layout"
)

func main() {
	var a nnattn.IndexedAttention
	fmt.Println(a.ExecuteSelection(nil, nil, nnattn.IndexedBuffers{}, nil, layout.TopKBuffers{}))
}
Output:
cudaattn: missing indexed topk selector

type IndexedBuffers

type IndexedBuffers struct {
	Q, K, V                                                   cuda.Slice[float32]
	Sequences, Positions, Lengths, Pages, IDs, Counts, Status cuda.Slice[int32]
	ScratchOutput, ScratchLSE, Output, LSE                    cuda.Slice[float32]
	Scores                                                    cuda.Slice[float32]
	ScoreLengths, ScoreOffsets                                cuda.Slice[int32]
}

IndexedBuffers contains caller-owned exact-sized device allocations. All active ranges must be disjoint, including read-only ranges. IDs and Counts use the explicitly configured selection heads. Status and scratch are never admitted output. Scores and its lengths/offsets are needed only by the pipeline. K/V may be slices from an actual cudakv contiguous cache or an externally leased physical pool. Allocation borrows prevent Free, not serving-page reuse: the caller excludes writes, remapping/recycling and all concurrent buffer, stream and device use until success or a successful retry Close.

type IndexedConfig

type IndexedConfig struct {
	Batch, Queries, QueryHeads, KVHeads, HeadDim           int
	BlockSize, MaxSequence, PhysicalBlocks, SelectedBlocks int
	Selection                                              IndexedSelection
	Causal                                                 bool
	Scale                                                  float32
}

IndexedConfig describes ordinary FP32 attention. Q and output are [queries, query heads, dimension]. Physical K and V are [physical blocks, block size, KV heads, dimension]. IDs name logical blocks, not physical pages. Pages maps [batch, maximum logical blocks] to physical blocks. Each query names a sequence and its actual position; causal masking compares actual KV token positions. Query values and every loaded KV value must be finite, and scale must be finite and positive. Unvisited KV storage is outside the numerical domain. Empty or fully masked rows produce zero output and negative infinity LSE.

func (IndexedConfig) Extents

func (c IndexedConfig) Extents() (IndexedExtents, error)

Extents checks the finite baseline domain before allocations or native calls. It supports batch 1..2, queries 1..64, heads 1..32, dimension 1..128, block size 1..128, sequence capacity 1..4096, physical blocks 1..256, and selected blocks 1..32. FP32 is the only admitted storage/accumulation type.

Example
package main

import (
	"fmt"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	c := nnattn.IndexedConfig{Batch: 1, Queries: 1, QueryHeads: 2, KVHeads: 1, HeadDim: 8, BlockSize: 4, MaxSequence: 9, PhysicalBlocks: 3, SelectedBlocks: 2, Selection: nnattn.IndexedQueryHeads, Scale: 0.5, Causal: true}
	e, err := c.Extents()
	fmt.Println(e.Query, e.KV, e.IDs, e.MaxBlocks, err)
}
Output:
16 96 4 3 <nil>

type IndexedExtents

type IndexedExtents struct {
	Query, KV, Pages, Sets, IDs, Rows, Scores, MaxBlocks int
}

IndexedExtents contains exact element counts for caller allocations.

type IndexedRequest

type IndexedRequest struct {
	Sequences, Positions, Lengths, Pages, IDs, Counts []int32
}

IndexedRequest is host-owned metadata with exact extents. Live IDs occupy the prefix specified by Counts; every remaining slot must be -1. Duplicate IDs and invalid physical page mappings are refused. Positions may be -1 to admit a fully masked causal query. A position otherwise lies within its sequence.

type IndexedSelection

type IndexedSelection int

IndexedSelection declares who owns a selected set. No head dimension is inferred.

const (
	// IndexedQueryHeads uses an independent set for every query head.
	IndexedQueryHeads IndexedSelection = iota + 1
	// IndexedKVHeads shares one explicitly supplied set across a KV head's query heads.
	IndexedKVHeads
)

type KDA

type KDA struct {
	// contains filtered or unexported fields
}

KDA owns an ordinary recurrence artifact and bounded scratch. Its zero value is closed. Only one invocation may be pending; keep device and stream live and exclude other buffer users until its result completes. Close retries failed drains before releasing resources.

func CompileKDA

func CompileKDA(dev *cuda.Device, c KDAConfig) (*KDA, error)

CompileKDA compiles the ordinary kernel for the actual device. A nonnil KDA returned with an error owns cleanup and must be closed. Geometry is one block, one thread, zero dynamic shared bytes; this baseline makes no speed claim.

func (*KDA) Artifact

func (k *KDA) Artifact() *cudakernel.Artifact

Artifact returns a detached descriptor of the loaded kernel image and ABI.

func (*KDA) Close

func (k *KDA) Close() error

Close drains outstanding work, then frees scratch and unloads the artifact. Cleanup errors retain the remaining resources for another Close call.

func (*KDA) Execute

func (k *KDA) Execute(ctx context.Context, stream *cuda.Stream, initial *KDAState, expected []KDAIdentity, offsets []int32, b KDABuffers) (*KDAResult, error)

Execute validates actual device inputs, identity and offsets before submitting the ordinary recurrence. It reads input data back solely for admission; all recurrence arithmetic runs in CUDA. Offsets are copied into owned device storage. A nonnil result returned with an error retains partial submission ownership; call Wait or Close until the stream drains successfully.

Example

This device consumer requires an inherited GPU lock. It deliberately has no Output directive, so ordinary host example tests never dispatch hardware.

package main

import (
	"context"
	"fmt"
	"github.com/tmc/lib/nvidia/x/cuda"
	"github.com/tmc/lib/nvidia/x/cuda/lock"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
	"os"
)

func main() {
	if _, err := lock.Inherited(os.Getenv); err != nil {
		panic(err)
	}
	dev, err := cuda.NewDevice(0)
	if err != nil {
		panic(err)
	}
	defer dev.Close()
	stream, err := dev.NewStream()
	if err != nil {
		panic(err)
	}
	c := nnattn.KDAConfig{Dimension: 128, Heads: 1, Sequences: 1, Tokens: 1, Scale: 1}
	k, err := nnattn.CompileKDA(dev, c)
	if err != nil {
		if k != nil {
			k.Close()
		}
		stream.Close()
		panic(err)
	}
	var allocations []cuda.Slice[float32]
	defer func() {
		if err := k.Close(); err != nil {
			panic(err)
		}
		if err := stream.Close(); err != nil {
			panic(err)
		}
		for _, s := range allocations {
			if err := s.Close(); err != nil {
				panic(err)
			}
		}
	}()
	alloc := func(data []float32) cuda.Slice[float32] {
		s, err := cuda.Alloc[float32](dev, len(data))
		if err != nil {
			panic(err)
		}
		allocations = append(allocations, s)
		if err := s.CopyFromHost(data); err != nil {
			panic(err)
		}
		return s
	}
	unit := make([]float32, 128)
	unit[0] = 1
	value, decay := make([]float32, 128), make([]float32, 128)
	for i := range value {
		value[i] = 0.5
		decay[i] = 0.9
	}
	initialValues := make([]float32, 128*128)
	for i := range initialValues {
		initialValues[i] = 0.01
	}
	ids := []nnattn.KDAIdentity{{Sequence: "sequence-a", Mode: nnattn.KDAFP32}}
	initial, err := nnattn.NewKDAState(c, alloc(initialValues), ids)
	if err != nil {
		panic(err)
	}
	b := nnattn.KDABuffers{Q: alloc(unit), Key: alloc(unit), Value: alloc(value), Decay: alloc(decay), Beta: alloc([]float32{0.5}), FinalState: alloc(make([]float32, 128*128)), Output: alloc(make([]float32, 128))}
	result, err := k.Execute(context.Background(), stream, initial, ids, []int32{0, 1}, b)
	if result != nil {
		if waitErr := result.Wait(context.Background()); waitErr != nil {
			panic(waitErr)
		}
	}
	if err != nil {
		panic(err)
	}
	state, err := result.State()
	if err != nil {
		panic(err)
	}
	fmt.Println("published prefix:", state.Identities()[0].Prefix)
	// The imported initial snapshot remains unchanged and can start another arm.
}

type KDABuffers

type KDABuffers struct {
	Q, Key, Value, Decay, Beta cuda.Slice[float32]
	FinalState, Output         cuda.Slice[float32]
}

KDABuffers contains contiguous caller-owned inputs and separate publication destinations. No active ranges may overlap, including read-only inputs. Inputs and imported state must remain immutable during execution. Outputs may be consumed only after successful KDAResult.Wait. Failed publication leaves raw destinations undefined and never returns an admitted state.

type KDAConfig

type KDAConfig struct {
	Dimension, Heads, Sequences, Tokens int
	Scale                               float32
}

KDAConfig bounds one ordinary recurrence invocation. Dimension must be 128, Heads and Sequences 1 or 2, Tokens 0 through 66, and each sequence at most 33 tokens. Scale must be positive and finite. Empty segments preserve their state.

func (KDAConfig) Extents

func (c KDAConfig) Extents() (KDAExtents, error)

Extents validates the bounded shape and returns checked allocation counts.

Example
package main

import (
	"fmt"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	c := nnattn.KDAConfig{Dimension: 128, Heads: 1, Sequences: 1, Tokens: 1, Scale: 1}
	e, err := c.Extents()
	fmt.Println(e.Vectors, e.State, err)
}
Output:
128 16384 <nil>

type KDAExtents

type KDAExtents struct{ Vectors, Betas, State, Offsets, WorkspaceBytes int }

KDAExtents contains exact scalar counts, including separate scratch results.

type KDAIdentity

type KDAIdentity struct {
	Sequence string
	Prefix   uint64
	Mode     string
}

KDAIdentity binds a consumer state to its sequence, consumed prefix and numerical mode. Scale and head count are additionally bound by KDAState.

type KDAResult

type KDAResult struct {
	// contains filtered or unexported fields
}

KDAResult retains an invocation and its publication destinations. Its zero value is unusable. Wait may be retried after cancellation or a failed drain; it never publishes a consumer identity before successful native completion.

func (*KDAResult) Close

func (r *KDAResult) Close() error

Close waits without cancellation for this result's compute and publication.

func (*KDAResult) State

func (r *KDAResult) State() (*KDAState, error)

State returns the successfully published state, or an error while pending or after failure. It cannot expose a speculative consumer prefix.

func (*KDAResult) Wait

func (r *KDAResult) Wait(ctx context.Context) error

Wait drains compute, checks every device status, submits publication, then drains publication. All borrows span both phases. A partially failed copy cannot publish state; its queued work is drained before releasing pins.

type KDAState

type KDAState struct {
	// contains filtered or unexported fields
}

KDAState is an immutable imported or successfully published [N,H,V,K] state. The caller must preserve its data and keep the device live until all users complete. Import establishes a caller assertion, not proof of data provenance.

func NewKDAState

func NewKDAState(c KDAConfig, data cuda.Slice[float32], ids []KDAIdentity) (*KDAState, error)

NewKDAState imports an explicit initial snapshot without taking allocation ownership. Sequence names must be nonempty and distinct, with mode KDAFP32.

func (*KDAState) Data

func (s *KDAState) Data() cuda.Slice[float32]

Data returns the immutable state allocation. The caller owns its allocation; writing or freeing it while an invocation uses it violates the contract.

func (*KDAState) Identities

func (s *KDAState) Identities() []KDAIdentity

Identities returns a detached copy of the published consumer identities.

type KernelStreamCandidate

type KernelStreamCandidate struct {
	// Index is the candidate's position in the trajectory. KernelStreamTU names the
	// candidate's entry function after it; see KernelStreamEntry.
	Index int

	// Phase names the rewrite the candidate applies. It appears in the
	// comments of Lines and of KernelStreamTU.
	Phase string

	// Lines is the candidate's CUDA C++ source, one line per element:
	// Stage s0 (RMSNorm) on lines 1-14, Stage s1 (SwiGLU GEMV) on lines
	// 15-26 and the __global__ entry, named Kernel, on lines 27-30.
	Lines []string
}

A KernelStreamCandidate is one step of the trajectory.

func KernelStreamCandidates

func KernelStreamCandidates() []KernelStreamCandidate

KernelStreamCandidates returns the 24 candidates of the trajectory, in order.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	cands := attn.KernelStreamCandidates()
	tu := attn.KernelStreamTU(cands)
	fmt.Println(len(cands), strings.Count(tu, "__global__"))
	fmt.Println(cands[0].Phase, attn.KernelStreamEntry(cands[0].Index))
	fmt.Println(cands[0].Lines[26])
}
Output:
24 24
baseline_scalar_f32 cand_00_fused_rmsnorm_swiglu_gemv
__global__ void __launch_bounds__(256, 1) fused_rmsnorm_swiglu_gemv(const float* x, const float* w, const float* W_up, float* out) {

type LlamaCPUReference

type LlamaCPUReference struct {
	// contains filtered or unexported fields
}

LlamaCPUReference is the exact float32 CPU oracle for LlamaDecodeMegakernelGPU and TraceLlamaDecodeMegakernelHostEmu.

func NewLlamaCPUReference

func NewLlamaCPUReference(cfg LlamaDecodeConfig, weights *LlamaModelWeightsF32) (*LlamaCPUReference, error)

NewLlamaCPUReference constructs a float32 CPU reference runner for cfg and weights.

func (*LlamaCPUReference) Reset

func (r *LlamaCPUReference) Reset()

Reset zeroes the CPU reference KV cache.

func (*LlamaCPUReference) StepDecode

func (r *LlamaCPUReference) StepDecode(tokenID int32, pos int) (int32, []float32, error)

StepDecode executes one float32 reference decode step at pos and returns the greedy argmax next token ID and the full vocabulary logits.

func (*LlamaCPUReference) StepVerify

func (r *LlamaCPUReference) StepVerify(pendingToken int32, draftTokens []int32, pos int) (VerifyStepResult, error)

StepVerify executes M = len(draftTokens) + 1 sequential target steps starting at pos with pendingToken followed by draftTokens, verifies the drafts via nnspec.VerifyGreedy, and rolls the KV cache position back to pos + AcceptedCount + 1.

type LlamaDecodeConfig

type LlamaDecodeConfig struct {
	HiddenSize        int
	IntermediateSize  int
	NumHiddenLayers   int
	NumAttentionHeads int
	NumKeyValueHeads  int
	HeadDim           int
	VocabSize         int
	MaxSeqLen         int
	PageSize          int
	RMSNormEps        float32
	RoPETheta         float32
	RoPEScaling       LlamaRoPEScaling
	TieWordEmbeddings bool
	WeightDType       DecodeWeightDType
	FP8Scale          float32
	GridCTAs          int

	// ThreadsPerCTA is the block width. Above 256 the kernel is
	// compiled with __launch_bounds__ of it, so the launch fits, but the
	// register cap that implies is below what the kernel uses, and it
	// spills.
	ThreadsPerCTA int

	// BarrierTimeout bounds each CTA's wait at a grid barrier, measured
	// on %globaltimer. A wait that outlives it aborts the step with an
	// [*AbortError] that matches [ErrBarrierTimeout], so a grid whose CTAs
	// are not all resident fails instead of hanging the device. Zero means
	// [DefaultBarrierTimeout].
	BarrierTimeout time.Duration
}

LlamaDecodeConfig specifies the model geometry, launch grid, and weight precision for the persistent Llama decode megakernel.

func Llama32_1BConfig

func Llama32_1BConfig() LlamaDecodeConfig

Llama32_1BConfig returns the canonical configuration for unsloth/Llama-3.2-1B-Instruct (rev 5a8abab4a5d6f164389b1079fb721cfab8d7126c).

func (LlamaDecodeConfig) Roofline

func (c LlamaDecodeConfig) Roofline(seqLen, verifyM int, hbmBandwidthGBps float64) (DecodeRoofline, error)

Roofline computes the exact HBM weight + KV-cache byte traffic and theoretical latency ceiling at sequence length seqLen and verification batch verifyM (M = K + 1) for a measured streaming-read HBM bandwidth in GB/s (10^9 B/s).

Example
package main

import (
	"fmt"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
	"github.com/tmc/lib/nvidia/x/obs/diag"
)

func main() {
	// Price the step at each device's measured read ceiling.
	readGBps := func(product string) float64 {
		c, err := diag.LookupDeviceCeiling(product, diag.DeviceResident)
		if err != nil {
			panic(err)
		}
		return c.PeakMemoryGBps
	}
	cfg := nnattn.Llama32_1BConfig()
	l4, err := cfg.Roofline(364, 1, readGBps("NVIDIA L4"))
	if err != nil {
		panic(err)
	}
	gb10, err := cfg.Roofline(364, 1, readGBps("NVIDIA GB10"))
	if err != nil {
		panic(err)
	}
	fp8Cfg := cfg
	fp8Cfg.WeightDType = nnattn.WeightDTypeFP8
	l4FP8, err := fp8Cfg.Roofline(364, 1, readGBps("NVIDIA L4"))
	if err != nil {
		panic(err)
	}
	fmt.Printf("bf16 weights=%d kv=%d total=%d\n", l4.TotalWeightBytes, l4.KVCacheBytes, l4.TotalHBMBytes)
	fmt.Printf("L4 bf16 TPOT=%.3f ms (%.1f tok/s)\n", l4.SingleTokenTPOTMs, l4.SingleTokenTokPerSec)
	fmt.Printf("GB10 bf16 TPOT=%.3f ms (%.1f tok/s)\n", gb10.SingleTokenTPOTMs, gb10.SingleTokenTokPerSec)
	fmt.Printf("L4 fp8 weights=%d TPOT=%.3f ms (%.1f tok/s)\n", l4FP8.TotalWeightBytes, l4FP8.SingleTokenTPOTMs, l4FP8.SingleTokenTokPerSec)
}
Output:
bf16 weights=2471628800 kv=11927552 total=2483556352
L4 bf16 TPOT=9.494 ms (105.3 tok/s)
GB10 bf16 TPOT=10.365 ms (96.5 tok/s)
L4 fp8 weights=1235881984 TPOT=4.770 ms (209.6 tok/s)

func (LlamaDecodeConfig) Validate

func (c LlamaDecodeConfig) Validate() error

Validate checks all model and launch invariants.

type LlamaDecodeMegakernelGPU

type LlamaDecodeMegakernelGPU struct {
	// contains filtered or unexported fields
}

LlamaDecodeMegakernelGPU owns the compiled module, device weight buffers, KV cache, and scratchpad for executing the persistent Llama decode megakernel on a CUDA device. A step whose grid barrier times out or sees a raised cause fails with an *AbortError.

func NewLlamaDecodeMegakernelGPU

func NewLlamaDecodeMegakernelGPU(ctx context.Context, dev *cuda.Device, cfg LlamaDecodeConfig, weights *LlamaModelWeightsF32, opts ...DecodeOption) (*LlamaDecodeMegakernelGPU, error)

NewLlamaDecodeMegakernelGPU compiles and loads the persistent Llama decode megakernel on dev and uploads weights. With WithDecodeStream it launches on the caller's stream, such as a green context's, instead of its own.

func NewLlamaDecodeMegakernelGPUBenchmark

func NewLlamaDecodeMegakernelGPUBenchmark(ctx context.Context, dev *cuda.Device, cfg LlamaDecodeConfig, opts ...DecodeOption) (*LlamaDecodeMegakernelGPU, error)

NewLlamaDecodeMegakernelGPUBenchmark compiles and loads the persistent Llama decode megakernel on dev and allocates full-model device weight buffers initialized with a deterministic periodic pattern without allocating multi-GB float32 host weight structs. It takes the same options as NewLlamaDecodeMegakernelGPU.

func (*LlamaDecodeMegakernelGPU) Close

func (g *LlamaDecodeMegakernelGPU) Close() error

Close releases all device allocations, stream, and compiled module.

func (*LlamaDecodeMegakernelGPU) CorruptFinalNormForTest

func (g *LlamaDecodeMegakernelGPU) CorruptFinalNormForTest(corrupted []float32) (func() error, error)

CorruptFinalNormForTest overwrites the device final_norm_w buffer with mutated values for planted negative-control verification, returning a restore function.

func (*LlamaDecodeMegakernelGPU) CorruptLMHeadForTest

func (g *LlamaDecodeMegakernelGPU) CorruptLMHeadForTest(forcedToken int, scale float32) (func() error, error)

CorruptLMHeadForTest overwrites the device lm_head_w buffer with a biased row so argmax shifts deterministically for planted negative-control verification, returning a restore function.

func (*LlamaDecodeMegakernelGPU) Residency

func (g *LlamaDecodeMegakernelGPU) Residency() (grid, maxGrid, sms int)

Residency returns the runner's grid in CTAs, the most CTAs the SMs its launches may use hold at once, and that SM count, as the driver reported them when the runner was built.

func (*LlamaDecodeMegakernelGPU) SetDisableCausalMaskForTest

func (g *LlamaDecodeMegakernelGPU) SetDisableCausalMaskForTest(disable bool)

SetDisableCausalMaskForTest toggles the disable_causal_mask kernel parameter for planted causal-leakage negative controls (token m=0 sees KV from m>0).

func (*LlamaDecodeMegakernelGPU) SpeculateWithNgram

func (g *LlamaDecodeMegakernelGPU) SpeculateWithNgram(
	ctx context.Context,
	drafter *nnspec.NgramDrafter,
	history []int32,
	pendingToken int32,
	maxDraft int,
	pos int,
) (VerifyStepResult, error)

SpeculateWithNgram drafts up to maxDraft tokens from history + pendingToken using drafter (effective on code-edit and summarization workloads), verifies all M = 1 + len(drafts) tokens in a single persistent megakernel launch at pos, feeds the emitted tokens back into drafter, and returns the verification result.

func (*LlamaDecodeMegakernelGPU) SpeculateWithProposer

func (g *LlamaDecodeMegakernelGPU) SpeculateWithProposer(
	ctx context.Context,
	proposer DraftProposer,
	history []int32,
	pendingToken int32,
	maxDraft int,
	pos int,
) (VerifyStepResult, error)

SpeculateWithProposer obtains up to maxDraft draft tokens from proposer (such as an EAGLE-style draft head or small draft model for chat workloads) and verifies all M = 1 + len(drafts) tokens in a single persistent megakernel launch at pos.

func (*LlamaDecodeMegakernelGPU) StepDecode

func (g *LlamaDecodeMegakernelGPU) StepDecode(ctx context.Context, tokenID int32, pos int) (int32, error)

StepDecode executes one persistent megakernel decode step (M=1) at pos and returns the greedy argmax next token ID.

func (*LlamaDecodeMegakernelGPU) StepVerify

func (g *LlamaDecodeMegakernelGPU) StepVerify(ctx context.Context, pendingToken int32, draftTokens []int32, pos int) (VerifyStepResult, error)

StepVerify executes one persistent megakernel speculative verification step over M = 1 + len(draftTokens) tokens starting at pos.

func (*LlamaDecodeMegakernelGPU) StepVerifyWithIKET

func (g *LlamaDecodeMegakernelGPU) StepVerifyWithIKET(ctx context.Context, pendingToken int32, draftTokens []int32, pos int) (*iket.Trace, VerifyStepResult, []float32, error)

StepVerifyWithIKET executes one persistent megakernel speculative verification step with live iket.cuh instrumentation and returns the decoded IKET trace, verification result, and output logits.

type LlamaLayerWeightsF32

type LlamaLayerWeightsF32 struct {
	InputNorm []float32
	WQ        []float32
	WK        []float32
	WV        []float32
	WO        []float32
	PostNorm  []float32
	WGate     []float32
	WUp       []float32
	WDown     []float32
}

LlamaLayerWeightsF32 holds the float32 weights of one decoder layer.

type LlamaModelWeightsF32

type LlamaModelWeightsF32 struct {
	Embed     []float32
	FinalNorm []float32
	LMHead    []float32
	Layers    []LlamaLayerWeightsF32
}

LlamaModelWeightsF32 holds the float32 weights of a Llama decoder model.

func NewSyntheticLlamaModelWeights

func NewSyntheticLlamaModelWeights(cfg LlamaDecodeConfig, seed uint64) (*LlamaModelWeightsF32, error)

NewSyntheticLlamaModelWeights generates deterministic, quantized-clean float32 model weights for cfg suitable for greedy parity and IKET verification tests.

type LlamaRoPEScaling

type LlamaRoPEScaling struct {
	Factor         float64
	LowFreqFactor  float64
	HighFreqFactor float64
	OrigMaxPos     int
}

LlamaRoPEScaling configures Llama-3 smooth wavelength rotary frequency scaling. The factors are float64, as a checkpoint's config.json gives them: transformers divides by them in float64 before rounding to float32, so a factor rounded to float32 first can move a frequency by an ulp.

func (LlamaRoPEScaling) Enabled

func (s LlamaRoPEScaling) Enabled() bool

Enabled reports whether Llama-3 smooth wavelength scaling is active.

type MHCPrePostConfig

type MHCPrePostConfig struct {
	NumTokens     int
	NumStreams    int
	HiddenDim     int
	Eps           float32
	PreEnd        int
	PostEnd       int
	ResEnd        int
	SinkhornIters int
	SinkhornEps   float32
}

MHCPrePostConfig configures cross-layer fused Multi-Headed Residual Connections (mHC) pre/post mixing and Sinkhorn-Knopp normalization.

type MLAConfig

type MLAConfig struct {
	KVLatentDim  int // c_KV dimension (512)
	QHeadDim     int // d_h (128)
	NumQHeads    int // n_h (128)
	RoPEDim      int // d_r (64)
	SoftmaxScale float32
}

MLAConfig defines dimensional configuration for DeepSeek Multi-Head Latent Attention.

type MLPBackwardOptions

type MLPBackwardOptions struct {
	Samples       int
	Input         bool
	ParameterMode irgraph.GradientMode
	MaxBytes      uint64
}

MLPBackwardOptions bounds one batch of FP32 differentiation. The loss is sum(output*outputGradient)/Samples. Input selects input gradients. Ignore suppresses parameter gradients; overwrite replaces them, while accumulate adds them to the supplied previous gradient. At least one output is required. MaxBytes is a positive limit on the combined device allocation sizes.

Example
package main

import (
	"fmt"
	irgraph "github.com/tmc/lib/nvidia/x/ir/graph"

	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	o := nnattn.MLPBackwardOptions{Samples: 7, Input: true, ParameterMode: irgraph.GradientModeOverwrite, MaxBytes: 1 << 20}
	fmt.Println(o.Samples, o.Input, o.ParameterMode)
}
Output:
7 true Overwrite

type MLPGradients

type MLPGradients struct {
	Output     []float32
	Input      []float32
	Parameters []float32
}

MLPGradients contains owned host copies after device synchronization. Each layer's weights and gradients use input-major, unpadded output-width order.

type MLPLayer

type MLPLayer struct {
	// contains filtered or unexported fields
}

MLPLayer represents a single dense linear layer with activation in an MLP.

func NewMLPLayer

func NewMLPLayer(name string, inWidth, outWidth int, activation string) (*MLPLayer, error)

NewMLPLayer creates an MLP layer with input and output widths and an activation function.

func (*MLPLayer) BackwardShmemBytes

func (l *MLPLayer) BackwardShmemBytes(nThreads int, mode irgraph.GradientMode) int

BackwardShmemBytes reports shared memory demand for backward pass.

func (*MLPLayer) EmitBackward

func (l *MLPLayer) EmitBackward(name string, nThreads int) (string, error)

EmitBackward emits input gradients without parameter writes.

func (*MLPLayer) EmitBackwardMode

func (l *MLPLayer) EmitBackwardMode(name string, nThreads int, mode irgraph.GradientMode) (string, error)

EmitBackwardMode emits derivatives using the saved input and preactivation. Parameter outputs are per sample in input-major order: in*OutputWidth+out. Overwrite and accumulate operate on a disjoint sample buffer, not a shared batch buffer. Input gradients are always overwritten when requested.

func (*MLPLayer) EmitForward

func (l *MLPLayer) EmitForward(name string) (string, error)

EmitForward renders the layer as a self-contained CUDA __device__ function.

func (*MLPLayer) FwdCtxAlignedPerElement

func (l *MLPLayer) FwdCtxAlignedPerElement() bool

FwdCtxAlignedPerElement reports whether context is aligned per element.

func (*MLPLayer) FwdCtxBytes

func (l *MLPLayer) FwdCtxBytes() (int, error)

FwdCtxBytes returns the forward context bytes required by this layer.

func (*MLPLayer) InputWidth

func (l *MLPLayer) InputWidth() int

InputWidth returns input feature dimension.

func (*MLPLayer) Name

func (l *MLPLayer) Name() string

Name returns the identifier of this layer.

func (*MLPLayer) OutputWidth

func (l *MLPLayer) OutputWidth() int

OutputWidth returns unpadded output feature dimension.

func (*MLPLayer) PaddedOutputWidth

func (l *MLPLayer) PaddedOutputWidth() int

PaddedOutputWidth returns padded output feature dimension.

type MicroStep3D

type MicroStep3D struct {
	PPStage              int
	VirtualChunk         int // 0 for first V-leg (0..P-1), 1 for second V-leg (P-1..0) in ZB-V
	LayerChunk           int // logical model chunk index in 0..2*P-1 (ZB-V) or 0..P-1 (1F1B)
	MicroBatchID         int
	Phase                StepPhase
	StartUs              float64
	EndUs                float64
	ComputeDurationUs    float64
	RingCPSteps          int
	RingCPOverlapped     bool
	TPMultimemAllReduces int
	TPMultimemOp         string
	WaitBarrierID        int64 // -1 if no upstream P2P stage handoff needed
	SignalBarrierID      int64 // -1 if no downstream P2P stage handoff emitted
}

MicroStep3D represents a single scheduled `F`, `B`, or `W` micro-step on one Pipeline Parallel stage, fused with intra-step Ring-CP KV steps and TP `multimem` collectives.

type NormRoPEHadamardKVConfig

type NormRoPEHadamardKVConfig struct {
	Tokens        int
	NopeDim       int
	RopeDim       int
	HadamardBlock int
	Eps           float32
	StoreFP4      bool
}

NormRoPEHadamardKVConfig configures fused RMSNorm, RoPE, Walsh-Hadamard transform, and block quantization for KV cache storage.

func (NormRoPEHadamardKVConfig) Validate

func (c NormRoPEHadamardKVConfig) Validate() error

Validate checks that c has valid dimensions and a power-of-two HadamardBlock.

type P2PReadyBarrier

type P2PReadyBarrier struct {
	BarrierID      uint64
	Epoch          uint32
	MicroBatchID   int
	VirtualChunk   int
	Phase          StepPhase
	FromPPStage    int
	ToPPStage      int
	Scope          string // ".sys"
	ReleasePTX     string // e.g. st.release.sys.global.u64 [ready_flag], epoch;
	AcquireWaitPTX string // e.g. ld.acquire.sys.global.u64 %rd, [ready_flag];
	ReadyAtUs      float64
}

P2PReadyBarrier describes a `.sys`-scope P2P stage-handoff ready barrier synchronizing producer and consumer PP stages across NVLink / IBGDA RDMA.

type PagedMLAConfig

type PagedMLAConfig struct {
	NumHeads        int
	HeadDimCKV      int
	HeadDimKPE      int
	PageBlockSize   int
	TopK            int
	WindowSize      int
	SoftmaxScale    float32
	HasAttnSink     bool
	HasExtraKVCache bool
	BatchInvariant  bool
	EmitFP8Output   bool
	ReturnLSE       bool
}

PagedMLAConfig configures FlashMLA V4.1 paged decode attention.

func (PagedMLAConfig) Validate

func (c PagedMLAConfig) Validate() error

Validate checks that c has supported dimensions.

type PagedMLAResult

type PagedMLAResult struct {
	Output    []float32
	FP8Output []uint8
	FP8Scales []float32
	LSE       []float32
}

PagedMLAResult holds the outputs of PagedMLAForwardCPU.

func PagedMLAForwardCPU

func PagedMLAForwardCPU(
	qNope []float32,
	qPe []float32,
	kvNoPE []float32,
	kPE []float32,
	attnSink []float32,
	extraKVNoPE []float32,
	extraKPE []float32,
	extraLSE []float32,
	cfg PagedMLAConfig,
) (PagedMLAResult, error)

PagedMLAForwardCPU executes the deterministic CPU reference for FlashMLA V4.1, supporting attention sinks, LSE output, extra KV cache LSE-weighted online softmax merge, and optional fused per-head/block FP8 output quantization.

type Parallel3DSchedule

type Parallel3DSchedule struct {
	Spec                  Parallel3DSpec
	ScheduleKind          string // "ZeroBubble-ZB-V" or "Standard-1F1B"
	WorldSize             int    // PPStages * TPDegree * CPDegree
	Stages                [][]MicroStep3D
	Barriers              []P2PReadyBarrier
	MakespanUs            float64
	StageComputeUs        float64
	BubbleFraction        float64
	Baseline1F1BBubble    float64
	BubbleReductionRatio  float64
	PeakInflight          []int
	SysBarrierPreludeCUDA string
}

Parallel3DSchedule is the compiled per-PP-stage timeline of `F`, `B`, and `W` micro-steps, exact pipeline bubble telemetry, and `.sys`-scope P2P stage-handoff ready-barrier metadata.

func Compile3DParallelSchedule

func Compile3DParallelSchedule(spec Parallel3DSpec) (*Parallel3DSchedule, error)

Compile3DParallelSchedule compiles a complete per-PP-stage timeline of `F` (Forward), `B` (Activation Backward), and `W` (Weight Gradient) micro-steps using the Zero-Bubble `ZB-V` schedule when `spec.ZeroBubbleZBV` is true (or standard `1F1B` otherwise), fused with intra-step Ring-CP KV exchange and TP `multimem` collectives, and emits `.sys`-scope P2P stage-handoff ready barrier metadata.

type Parallel3DSpec

type Parallel3DSpec struct {
	PPStages      int // Pipeline Parallel stages
	TPDegree      int // Tensor Parallel degree (intra-node NVSwitch)
	CPDegree      int // Context Parallel degree (Ring / Ulysses)
	NumMicroBatch int
	ZeroBubbleZBV bool // Split backward into B (input grad) and W (weight grad) for zero bubble
	MicroStepUs   float64
	P2PLatencyUs  float64
}

Parallel3DSpec configures a 3D Pipeline + Tensor + Context Parallel (`PP x TP x CP`) persistent schedule compiler.

func (Parallel3DSpec) Validate

func (s Parallel3DSpec) Validate() error

Validate checks that s has valid positive dimensions and non-negative latencies.

type PreSplitMixesResult

type PreSplitMixesResult struct {
	PreMix  []float32
	PostMix []float32
	ResMix  []float32
}

PreSplitMixesResult holds the split per-token hyper-connection mixing weights:

  • PreMix: [NumTokens, NumStreams]
  • PostMix: [NumTokens, NumStreams]
  • ResMix: [NumTokens, NumStreams*NumStreams]

func PreSplitMixesCPU

func PreSplitMixesCPU(
	x []float32,
	rmsWeight []float32,
	phiCombined []float32,
	bias []float32,
	alphaPre, alphaPost, alphaRes float32,
	cfg MHCPrePostConfig,
) (PreSplitMixesResult, error)

PreSplitMixesCPU computes the fused RMSNorm + linear projection + inv_rms scaling + sigmoid (for PreMix), 2*sigmoid (for PostMix), and Sinkhorn-Knopp doubly stochastic normalization (for ResMix), matching DeepInfer's _hc_PreSplitMixes_kernel.

Input shapes:

  • x: [NumTokens, NumStreams*HiddenDim]
  • rmsWeight: optional [NumStreams*HiddenDim] or [HiddenDim] (nil uses unit weights)
  • phiCombined: [NumStreams*HiddenDim, ResEnd] row-major projection matrix
  • bias: optional [ResEnd] additive bias

type ProjectionNormConfig

type ProjectionNormConfig struct {
	Dim     int
	Threads int
	Epsilon float32
}

ProjectionNormConfig describes a projection, residual addition, and RMS normalization over packed token rows.

Example
package main

import (
	"fmt"
	nnattn "github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	config := nnattn.ProjectionNormConfig{Dim: 4096, Threads: 256, Epsilon: 1e-5}
	bytes, err := config.SharedMemoryBytes()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(bytes)
}
Output:
1024

func (ProjectionNormConfig) KernelSharedMemoryBytes

func (c ProjectionNormConfig) KernelSharedMemoryBytes(entry string) (int, error)

KernelSharedMemoryBytes returns the dynamic shared memory, in bytes per block of c.Threads threads, that the kernel entry of ProjectionResidualRMSNormTemplate must be launched with. RMSNormQKV and ProjectionResidualRMSNorm reduce through one float per thread; GateUpSiLU and DownResidual need none.

func (ProjectionNormConfig) SharedMemoryBytes

func (c ProjectionNormConfig) SharedMemoryBytes() (int, error)

SharedMemoryBytes returns the reduction storage required by RMSNormQKV and ProjectionResidualRMSNorm.

func (ProjectionNormConfig) Validate

func (c ProjectionNormConfig) Validate() error

Validate checks the kernel shape and numerical invariants.

type RelativeGatedDecode

type RelativeGatedDecode struct {
	NumHeads, KVHeads int
	Window            int
	Scale             float32
}

RelativeGatedDecode configures single-token causal BF16 attention with grouped query heads of width 128. Window is the key/value ring capacity and includes the current key. It must be between 1 and 1921. Scale is a positive finite multiplier on the query-key dot product.

Example
package main

import (
	"fmt"
	"math"

	"github.com/tmc/lib/nvidia/x/nn/attn"
)

func main() {
	cfg := attn.RelativeGatedDecode{NumHeads: 24, KVHeads: 8, Window: 1024, Scale: 1 / float32(math.Sqrt(128))}
	p, err := cfg.Plan()
	if err != nil {
		panic(err)
	}
	fmt.Println(p.Partial.Geometry.Grid, p.Merge.Geometry.Grid)
	fmt.Println(p.PartialElements, p.LogSumElements)
}
Output:
[24 9 1] [24 1 1]
27648 216

func (RelativeGatedDecode) CUDA

func (a RelativeGatedDecode) CUDA() (string, error)

CUDA returns self-contained source for sm_80 or newer. Compile with floating-point contraction disabled to preserve the explicit rounding order. The two entries have these arguments, in order:

partial(q, k, v, relative, partials, logsum, position)
merge(partials, logsum, gate, sink, output)

All buffers except partials and logsum contain BF16. The buffers use row-major layout and must not overlap. q, gate, and output have shape [NumHeads, 128]. k and v have shape [Window, KVHeads, 128], with each absolute key position stored modulo Window, including the current key. sink has shape [NumHeads] and contributes only to the denominator.

position is a nonnegative int32 no greater than 2³¹−256. relative has shape [NumHeads, min(position+1, Window)]. Each row is ordered from the oldest visible key to the current key. The caller supplies precomputed additive relative logits in natural-log units. For a distance-indexed table, relative[h, j] is the bias at distance visible−1−j from head h. Inputs and scaled logits must be finite.

The partial kernel applies the scale and relative term after the BF16 MMA dot product. It accumulates the softmax denominator in float32 and rounds the unnormalized probabilities to BF16 for the value MMA. Merge applies the channel gate and the sink sigmoid to the merged output, in that order, before rounding to BF16.

The launch and scratch contracts are returned by RelativeGatedDecode.Plan. Scratch layouts are [splits, NumHeads, 128] and [splits, NumHeads].

func (RelativeGatedDecode) Plan

Plan returns the two launches and float32 scratch sizes. Both kernels must run in order on the same stream, or with an equivalent dependency.

type RelativeGatedLaunch

type RelativeGatedLaunch struct {
	Entry    string
	Geometry kernel.LaunchGeometry
}

RelativeGatedLaunch describes one launch in the two-kernel decode. Entry is the symbol name in the source from RelativeGatedDecode.CUDA.

type RelativeGatedPlan

type RelativeGatedPlan struct {
	Partial, Merge                  RelativeGatedLaunch
	PartialElements, LogSumElements int
}

RelativeGatedPlan describes the launches in order and the number of float32 elements in each scratch buffer.

type ResidualRMSNormRoofline

type ResidualRMSNormRoofline struct {
	Architecture        string                `json:"architecture"`
	Device              string                `json:"device,omitempty"`
	Residency           obsmodel.Residency    `json:"residency"`
	PeakMemoryGBps      float64               `json:"peak_memory_gbps"`
	MemoryProvenance    obsmodel.Provenance   `json:"memory_provenance"`
	PeakTFLOPS          float64               `json:"peak_tflops"`
	ComputeProvenance   obsmodel.Provenance   `json:"compute_provenance"`
	KneeIntensity       float64               `json:"knee_intensity"`
	UnfusedMinNs        float64               `json:"unfused_min_ns"`
	FusedMinNs          float64               `json:"fused_min_ns"`
	UnfusedLimitingAxis obsmodel.LimitingAxis `json:"unfused_limiting_axis"`
	FusedLimitingAxis   obsmodel.LimitingAxis `json:"fused_limiting_axis"`
}

ResidualRMSNormRoofline is the analytical roofline floor derived by combining a TrafficModel with a hardware ceiling from obsmodel.LookupCeiling.

type ResidualRMSNormShape

type ResidualRMSNormShape struct {
	Rows   int
	Hidden int
	Eps    float32
}

ResidualRMSNormShape describes the tensor dimensions and stabilization epsilon for a fused ResidualAdd + RMSNorm operation over [Rows, Hidden].

func (ResidualRMSNormShape) Elements

func (s ResidualRMSNormShape) Elements() (int, error)

Elements returns Rows * Hidden after validating the shape.

func (ResidualRMSNormShape) Validate

func (s ResidualRMSNormShape) Validate() error

Validate reports an error wrapping ErrInvalidConfig if shape dimensions are non-positive, overflow int indexing, or Eps is non-positive or non-finite.

type SplitKConfig

type SplitKConfig struct {
	NumSplits int // Number of K partitions along sequence dimension
	BlockSize int // Tokens per partition
}

SplitKConfig configures sequence partitioning for long-context CUDA FlashDecoding.

type StepPhase

type StepPhase string

StepPhase identifies a micro-step phase in a 3D parallel pipeline schedule.

const (
	// PhaseF is the Forward pass micro-step.
	PhaseF StepPhase = "F"
	// PhaseB is the Activation / Input-Gradient Backward micro-step (dX) on the
	// critical inter-stage path (or monolithic B+W when ZeroBubbleZBV is false).
	PhaseB StepPhase = "B"
	// PhaseW is the Weight-Gradient Backward micro-step (dW), decoupled from
	// inter-stage P2P dependencies to fill pipeline bubbles in ZB-V.
	PhaseW StepPhase = "W"
)

type TrafficModel

type TrafficModel struct {
	Shape                      ResidualRMSNormShape `json:"shape"`
	BF16Out                    bool                 `json:"bf16_out"`
	Elements                   int64                `json:"elements"`
	FLOPs                      int64                `json:"flops"`
	UnfusedAddBytes            int64                `json:"unfused_add_bytes"`
	UnfusedNormBytes           int64                `json:"unfused_norm_bytes"`
	UnfusedBytes               int64                `json:"unfused_bytes"`
	UnfusedTwoPassBytes        int64                `json:"unfused_two_pass_bytes"`
	FusedBytes                 int64                `json:"fused_bytes"`
	BytesSaved                 int64                `json:"bytes_saved"`
	TrafficReductionPct        float64              `json:"traffic_reduction_pct"`
	TwoPassTrafficReductionPct float64              `json:"two_pass_traffic_reduction_pct"`
	UnfusedArithmeticIntensity float64              `json:"unfused_arithmetic_intensity"`
	FusedArithmeticIntensity   float64              `json:"fused_arithmetic_intensity"`
	TheoreticalSpeedup         float64              `json:"theoretical_speedup"`
	TwoPassTheoreticalSpeedup  float64              `json:"two_pass_theoretical_speedup"`
}

TrafficModel holds the analytical global-memory traffic, FLOP counts, arithmetic intensity, and theoretical fusion speedup for ResidualAdd+RMSNorm.

UnfusedBytes is the compulsory 2-kernel DRAM floor: AddResidual reads x and residual and writes residual (12*N bytes), then RMSNorm re-reads residual, reads weight once, and writes out ((4+outBytes)*N + 4*H bytes).

UnfusedTwoPassBytes models an unfused RMSNorm that does not cache the row between its reduction and scaling passes (+4*N bytes).

FusedBytes is the single-pass fused floor: reads x, residual, and weight once and writes updated residual and out once ((12+outBytes)*N + 4*H bytes).

func ResidualRMSNormTraffic

func ResidualRMSNormTraffic(shape ResidualRMSNormShape, bf16Out bool) (TrafficModel, error)

ResidualRMSNormTraffic derives the exact compulsory memory traffic, FLOPs, arithmetic intensities, and theoretical speedup for shape.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/nn/attn"
	"github.com/tmc/lib/nvidia/x/obs/diag/obsmodel"
)

func main() {
	shape := attn.ResidualRMSNormShape{Rows: 1024, Hidden: 4096, Eps: 1e-5}
	tm, err := attn.ResidualRMSNormTraffic(shape, true)
	if err != nil {
		panic(err)
	}
	rf, err := tm.Roofline("sm_121a", obsmodel.DeviceResident)
	if err != nil {
		panic(err)
	}
	fmt.Printf("unfused=%d fused=%d saved=%.1f%% ceiling=%.1fGB/s axis=%s\n",
		tm.UnfusedBytes, tm.FusedBytes, tm.TrafficReductionPct, rf.PeakMemoryGBps, rf.FusedLimitingAxis)
}
Output:
unfused=75513856 fused=58736640 saved=22.2% ceiling=239.6GB/s axis=memory

func (TrafficModel) Roofline

func (m TrafficModel) Roofline(arch string, residency obsmodel.Residency) (ResidualRMSNormRoofline, error)

Roofline projects the traffic model onto the hardware ceiling for arch (or a known product name such as "NVIDIA GB10") at residency using obsmodel.

func (TrafficModel) RooflineWithCeiling

func (m TrafficModel) RooflineWithCeiling(c obsmodel.Ceiling) (ResidualRMSNormRoofline, error)

RooflineWithCeiling projects the traffic model onto an explicit validated obsmodel.Ceiling.

type VerifyStepResult

type VerifyStepResult struct {
	TargetTokens   []int32
	AcceptedTokens []int32
	EmittedTokens  []int32
	BonusToken     int32
	NextTokenID    int32
	AcceptedCount  int
	NewPos         int
}

VerifyStepResult holds the outcome of a single-token decode (M=1) or multi-token speculative verification step (M=K+1).

func TraceLlamaDecodeMegakernelHostEmu

func TraceLlamaDecodeMegakernelHostEmu(
	ctx context.Context,
	cfg LlamaDecodeConfig,
	weights *LlamaModelWeightsF32,
	pendingToken int32,
	draftTokens []int32,
	basePos int,
	kCacheInit, vCacheInit []float32,
) (*iket.Trace, VerifyStepResult, []float32, []float32, []float32, error)

TraceLlamaDecodeMegakernelHostEmu runs the persistent Llama decode megakernel under nnhostemu.Run for M = 1 + len(draftTokens) tokens starting at basePos, returning the decoded iket.Trace, the speculative verification result, and the M * VocabSize output logits.

If a grid barrier stops the kernel, the error is an *AbortError, the trace is nil, and the result holds only the accepted count, position and next token the kernel left, with the logits and KV cache as it left them.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL