Chapter 12

layers/mha — attention

github.com/openfluke/welvet/layers/mha


Why it exists

Transformers need multi-head attention with masks, RoPE/ALiBi, GQA/MQA, and cross-attn — without forking MatVec for every projection.

What it is

Q/K/V/O are Dense children. Presets: DecoderCausal, EncoderBidirectional, CrossAttention, … Attn/RoPE ALU is host today; on-device attn shaders are still open.

Go example

examples/12-mha/main.go

Run:cd welvet/examples/12-mha && source ../env.sh && go run .
package main

import (
	"fmt"

	"github.com/openfluke/welvet/core"
	"github.com/openfluke/welvet/layers/mha"
)

func main() {
	l, err := mha.New(mha.DecoderCausal(32, 4, 4))
	if err != nil {
		panic(err)
	}
	x := core.NewTensor[float32](1, 8, 32) // [batch, seq, dim]
	pre, post, err := mha.Forward(l, x)
	fmt.Println(pre != nil, len(post.Data), err)
}

Output

exit 0 · last run via go run .

true 256 <nil>