This document is relevant for: Trn2, Trn3
Output Projection CTE Kernel API Reference#
Computes output projection (attention @ weight + bias) optimized for Context Encoding (prefill) use cases.
The kernel supports:
Efficient projection of attention outputs
Optional bias addition
LNC sharding for distributed computation
Optimized memory access patterns
Head dimension packing for improved performance
Background#
The Output Projection CTE kernel computes the operation out = attention @ weight + bias, which is commonly used to project the output scores after an attention block in transformer models. This kernel is specifically optimized for Context Encoding (Prefill) use cases, where the sequence length can be large (typically S ≥ 512).
The kernel employs efficient tiling strategies and memory access patterns to maximize performance on Neuron hardware, with support for sharding across multiple Logical Neuron Cores (LNCs) to handle large hidden dimensions. When LNC>1, the H dimension is sharded across the cores, which avoids the need for any inter-core collective operations as each core produces part of the output tensor.
API Reference#
Source code for this kernel API can be found at: output_projection_cte.py
output_projection_cte#
- nkilib.core.output_projection.output_projection_cte.output_projection_cte(attention: nl.NkiTensor, weight: nl.NkiTensor, bias: Optional[nl.NkiTensor] = None, quantization_type: QuantizationType = QuantizationType.NONE, input_scales: Optional[nl.NkiTensor] = None, weight_scales: Optional[nl.NkiTensor] = None, output_dtype: Optional[type] = None, dtype_mode: DtypeMode = DtypeMode.NON_OCP, compact_weight_scales: bool = False, attention_layout: Optional[OProjAttentionLayout] = None, out: Optional[nl.NkiTensor] = None, out_s_offset: int = 0) nl.NkiTensor#
Output Projection Kernel optimized for Context Encoding (Prefill) use cases.
This kernel computes
out = attention @ weight + bias, typically used to project the output scores after an attention block in transformer models.This kernel is optimized for Context Encoding (aka Prefill) use cases where sequence length
Sis large. Using this kernel withS < 512may result in degraded performance.This kernel uses a layout also used by other Context Encoding kernels to avoid need for transposes.
- Parameters:
attention (
nl.NkiTensor) – [B, N, D, S], Input tensor in HBM from attention block.weight (
nl.NkiTensor) – [N * D, H], Weight tensor in HBM.bias (
Optional[nl.NkiTensor]) – [1, H], Optional bias tensor in HBM.quantization_type (
QuantizationType) – Type of quantization (NONE, STATIC for FP8, or MX).input_scales (
Optional[nl.NkiTensor]) – [128, 1], Input scale tensor for FP8 quantization.weight_scales (
Optional[nl.NkiTensor]) – [128, 1], Weight scale tensor for FP8 quantization.output_dtype (
Optional[type]) – Output data type. Defaults to attention.dtype for non-MX, or nl.bfloat16 for MX quantization. Can be set to nl.float16 for higher precision.dtype_mode (
DtypeMode) – Quantization dtype policy for STATIC/ROW attention and weight-tile allocation. -DtypeMode.NON_OCP(default):nl.float8_e4m3(max=240). -DtypeMode.OCP:nl.float8_e4m3fn(max=448). TRN3 only. -DtypeMode.AUTO:nl.float8_e4m3fnon TRN3, elsenl.float8_e4m3.compact_weight_scales (
bool) – When True (and quantization_type is MX),weight_scalesis interpreted as the block-128 compact layout[N*D // 128, H // 128]uint8, with one scale per 128x128 weight block. The kernel expands the compact scales to the hardware MX layout on-device. Defaults to False (block-32 dense layout).attention_layout (
Optional[OProjAttentionLayout]) – Dimension order ofattention. When declared it is taken as-is, asserted to be supported byquantization_type. Every layout is 4D, so a tag that does not describe the tensor passed in permutes N, D, and S rather than failing; the caller owns getting this right. -None(default): the layoutquantization_typeimplies — [B, S, N, D] forQuantizationType.ROW, [B, N, D, S] for every other type. -OProjAttentionLayout.BNdS:attentionis [B, N, D, S]. Supported by everyquantization_typeexcept ROW. -OProjAttentionLayout.BSNd:attentionis [B, S, N, D]. Supported byQuantizationType.NONEandQuantizationType.ROW. -OProjAttentionLayout.BNSd:attentionis [B, N, S, D] — the attention CTE output with heads folded into batch andtp_out=False. Supported byQuantizationType.NONE.out (
Optional[nl.NkiTensor]) – [B, S_total, H], caller-allocated output. When given, results are written here instead of into a freshly allocated tensor, and the same tensor is returned. Lets a caller project several S chunks into one result without a stitching copy.out_s_offset (
int) – Row offset intoout’s S dimension for this call’s chunk. Only meaningful together without. Float (non-quantized) path only.
- Returns:
[B, S, H], Output tensor in HBM.
- Return type:
nl.NkiTensor
- Data Types:
This kernel supports
nl.float32,nl.float16andnl.bfloat16data types. However, fornl.float32, large inputs may not fit in SBUF.- Dimensions:
B: Batch sizeN: Number of headsS: Sequence lengthH: Hidden dimension sizeD: Head dimension size
Restrictions:
The contract dimension of input and weight tensors must match (
N*D == weight.shape[0])Output projection kernel currently only supports
Hto be no more than 32768Hidden dimension (
H) needs to be divisible by LNC size since LNC sharding is on the weight hidden dimensionHead dimension (
D) must be <= 128Maximum validated
Hsize is 20705Maximum validated
B*Ssize is 131072Maximum validated
Nsize is 17
Implementation Details#
The kernel implementation includes several key optimizations:
Dimension Packing: Optimizes the contraction dimension by folding
N(number of heads) intoD(head dimension) when beneficial, improving computational efficiency.Efficient Tiling Strategy: Uses carefully chosen tile sizes for processing batches and sequences to maximize hardware utilization.
LNC Sharding: Supports sharding across multiple Logical Neuron Cores (LNCs) by dividing the hidden dimension, enabling processing of larger models.
Memory Access Optimization: Employs optimized memory access patterns to maximize bandwidth utilization and minimize data movement.
PSUM Bank Utilization: Efficiently utilizes PSUM banks for accumulating partial results during matrix multiplication operations.
Stream Shuffle Broadcast: Uses stream shuffle broadcast for bias tensors to efficiently distribute them across processing elements.
Specialized Engine Selection: Alternates between scalar and vector engines for tensor copy operations to balance workload and improve performance.
See Also#
This document is relevant for: Trn2, Trn3