For the complete documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /max/get-started.md).
Mojo function
mha_single_batch
def mha_single_batch[q_type: DType, k_t: MHAOperand, v_t: MHAOperand, output_type: DType, mask_t: MHAMask, *, config: MHAConfig[config.dtype], group: Int = Int(1), sink: Bool = False](q_ptr: Pointer[Scalar[q_type], ImmutAnyOrigin, _safe=False], k: k_t, v: v_t, output_ptr: Pointer[Scalar[output_type], MutAnyOrigin, _safe=False], scale: Float32, seq_len: Int, max_seq_len: Int, start_pos: UInt32, num_keys: Int, mask_tensor_col: Int, mask: mask_t, batch_idx: Int, sink_weights: OptionalReg[LayoutTensor[q_type, Layout.row_major(Int(-1)), ImmutAnyOrigin]])
MHA for token gen where seqlen = 1 and num_keys >= 1.
The general data layout and steps conform to flash attention. Two exceptions:
1 Partition across B, H, and num_keys (TODO). The last one is split-K and will need a separate reduction kernel at the end.
2 First bmm becomes gemv and second bmm becomes gevm. TODO: use more optimized kernels for them
Parameters:
- βq_type (
DType): Element type of the query tensor. - βk_t (
MHAOperand): Key operand type implementingMHAOperand. - βv_t (
MHAOperand): Value operand type implementingMHAOperand. - βoutput_type (
DType): Element type of the output tensor. - βmask_t (
MHAMask): Attention mask type implementingMHAMask. - βconfig (
MHAConfig[config.dtype]): Tile and pipeline configuration for the kernel. - βgroup (
Int): GQA group size, query heads per key/value head (defaults to 1). - βsink (
Bool):Trueto enable attention-sink mode where the first tokens always attend (defaults toFalse).
Args:
- βq_ptr (
Pointer[Scalar[q_type], ImmutAnyOrigin, _safe=False]): Pointer to the query tensor data in global memory. - βk (
k_t): Key operand backed by a KV cache or dense tensor. - βv (
v_t): Value operand backed by a KV cache or dense tensor. - βoutput_ptr (
Pointer[Scalar[output_type], MutAnyOrigin, _safe=False]): Pointer to the output buffer in global memory. - βscale (
Float32): Softmax temperature scale applied to QΒ·Kα΅. - βseq_len (
Int): Valid query sequence length excluding padding. - βmax_seq_len (
Int): Padded query sequence length used for batch offsets. - βstart_pos (
UInt32): Starting position of the current tokens in the KV cache. - βnum_keys (
Int): Number of key/value entries to attend over. - βmask_tensor_col (
Int): Second dimension of the mask tensor, equal to the key sequence length. - βmask (
mask_t): Mask instance used to apply the attention mask. - βbatch_idx (
Int): Index of the current sequence within the batch. - βsink_weights (
OptionalReg[LayoutTensor[q_type, Layout.row_major(Int(-1)), ImmutAnyOrigin]]): Optional sink-token weight tensor; required whensinkisTrue.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!