nativeAttention function

void nativeAttention(
  1. Float32List q,
  2. Float32List keys,
  3. Float32List values,
  4. Float32List? gate,
  5. Float32List out, {
  6. required int n,
  7. required int position,
  8. required int heads,
  9. required int kvHeads,
  10. required int headDim,
  11. required int window,
})

Grouped-query attention of n tokens at positions position, ... in C (src/c/lab_native.c, lab_attention), with an optional per-head output gate. Shapes as in LayerShard: q and out n, heads * headDim, keys and values maxSeq, kvHeads * headDim already holding this chunk, gate n, heads before the sigmoid. window 0 is full attention.

Implementation

void nativeAttention(
  Float32List q,
  Float32List keys,
  Float32List values,
  Float32List? gate,
  Float32List out, {
  required int n,
  required int position,
  required int heads,
  required int kvHeads,
  required int headDim,
  required int window,
}) {
  final kvDim = kvHeads * headDim;
  if (q.length < n * heads * headDim ||
      out.length < n * heads * headDim ||
      (gate != null && gate.length < n * heads) ||
      keys.length < (position + n) * kvDim ||
      values.length < (position + n) * kvDim ||
      heads % kvHeads != 0 ||
      headDim % 4 != 0) {
    throw ArgumentError('native attention: bad shapes');
  }
  final threads = NativeKernels.instance.threads;
  if (gate == null) {
    _attention(
      q.address,
      keys.address,
      values.address,
      nullptr,
      out.address,
      n,
      position,
      heads,
      kvHeads,
      headDim,
      window,
      threads,
    );
    return;
  }
  _attention(
    q.address,
    keys.address,
    values.address,
    gate.address,
    out.address,
    n,
    position,
    heads,
    kvHeads,
    headDim,
    window,
    threads,
  );
}