Skip to main content

GroupedQueryAttention

Struct GroupedQueryAttention 

Source
pub struct GroupedQueryAttention {
    pub dim: usize,
    pub num_heads: usize,
    pub num_kv_heads: usize,
    pub head_dim: usize,
    pub num_groups: usize,
    pub causal: bool,
    pub dropout_prob: f32,
    /* private fields */
}
Expand description

Grouped Query Attention (GQA) - Efficient attention with fewer KV heads

GQA uses fewer key-value heads than query heads, reducing memory and computation while maintaining quality. This is the attention mechanism used by Llama 3, Mistral, and many modern LLMs.

§Memory Savings

  • Standard MHA: num_heads K and V projections
  • GQA: num_kv_heads K and V projections (typically 2-8x fewer)

§Example

let ctx = pollster::block_on(WgpuContext::new());
let engine = ComputeEngine::new(&ctx);
// [batch, seq_len, hidden]
let q = UnifiedTensor::zeros(&ctx, &[1, 128, 4096]);
let k = UnifiedTensor::zeros(&ctx, &[1, 128, 1024]);
let v = UnifiedTensor::zeros(&ctx, &[1, 128, 1024]);
// Llama 3 8B: 32 query heads share 8 KV heads (no dropout, no mask)
let gqa = GroupedQueryAttention::new(4096, 32, 8, true, 0.0);
let output = gqa.forward(&q, &k, &v, None, &ctx, &engine);

Fields§

§dim: usize

Total hidden dimension

§num_heads: usize

Number of query heads

§num_kv_heads: usize

Number of key-value heads (fewer than query heads)

§head_dim: usize

Dimension per head

§num_groups: usize

Number of query heads per KV head

§causal: bool

Whether to use causal masking

§dropout_prob: f32

Dropout probability (0.0 = no dropout)

Implementations§

Source§

impl GroupedQueryAttention

Source

pub fn new( dim: usize, num_heads: usize, num_kv_heads: usize, causal: bool, dropout_prob: f32, ) -> Self

Create a new GQA layer.

§Arguments
  • dim - Total hidden dimension
  • num_heads - Number of query heads
  • num_kv_heads - Number of key-value heads (must divide num_heads evenly)
  • causal - Whether to apply causal masking
  • dropout_prob - Dropout probability
§Panics

Panics if num_heads is not divisible by num_kv_heads

Source

pub fn forward( &self, q: &UnifiedTensor, k: &UnifiedTensor, v: &UnifiedTensor, mask: Option<&UnifiedTensor>, ctx: &WgpuContext, engine: &ComputeEngine, ) -> UnifiedTensor

Forward pass with grouped query attention.

§Arguments
  • q - Query tensor [batch, seq_q, num_heads, head_dim]
  • k - Key tensor [batch, seq_k, num_kv_heads, head_dim]
  • v - Value tensor [batch, seq_k, num_kv_heads, head_dim]
§Returns

Output tensor [batch, seq_q, num_heads, head_dim]

Source

pub fn forward_at( &self, q: &UnifiedTensor, k: &UnifiedTensor, v: &UnifiedTensor, mask: Option<&UnifiedTensor>, pos: usize, ctx: &WgpuContext, engine: &ComputeEngine, ) -> UnifiedTensor

Like forward, with the first query at absolute position pos: query i attends to keys 0..=pos + i when causal. Used to decode against a KV cache, where k/v hold the cache.

Source

pub fn memory_savings(&self) -> String

Get memory savings compared to standard MHA

Trait Implementations§

Source§

impl Debug for GroupedQueryAttention

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> Downcast<T> for T

Source§

fn downcast(&self) -> &T

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> Upcast<T> for T

Source§

fn upcast(&self) -> Option<&T>

Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,