Skip to content

Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.

llama: clean up dead code from llama-server work (#17007)

Daniel Hiltgen7b22ac968356
diff --git a/kvcache/cache.go b/kvcache/cache.go
deleted file mode 100644
index 5c6fc250b..000000000
--- a/kvcache/cache.go
+++ /dev/null
@@ -1,84 +0,0 @@
-package kvcache
-
-import (
- "errors"
-
- "github.com/ollama/ollama/ml"
- "github.com/ollama/ollama/model/input"
-)
-
-var (
- ErrKvCacheFull = errors.New("could not find a kv cache slot")
- ErrNotSupported = errors.New("model does not support operation")
-)
-
-type Cache interface {
- // ** used by model implementations **
-
- // SetLayer sets the active layer of the cache
- SetLayer(layer int)
-
- // Get returns the history of key and value tensors plus a mask
- //
- // The shape of the tensors is documented in the specific
- // cache implementation used.
- Get(ctx ml.Context) (ml.Tensor, ml.Tensor, ml.Tensor)
-
- // Put stores a batch of key and value in the cache
- //
- // The shape of the tensors is documented in the specific
- // cache implementation used.
- Put(ctx ml.Context, key, value ml.Tensor)
-
- // SetConfig controls optimizations (mostly backend-specific) that may transform
- // the output of the cache to work better with specific kernels. If not called,
- // the backend settings will be used. This works well when calling Attention.
- //
- // The config can be overridden by models, especially if they require vanilla
- // output when implementing their own version of attention. To do this, pass
- // an empty ml.CacheConfig.
- //
- // Most models will not need to use this.
- SetConfig(ml.CacheConfig)
-
- // ** cache management **
-
- // Init sets up runtime parameters.
- // backend: Used to allocate cache data storage and execute management operations (such as defrag)
- // dtype: The data type for storing cache entries
- // maxSequences: The maximum number of sequences stored in the cache - across all batches
- // capacity: The number of cache entries to store, per sequence
- // maxBatch: The maximum number of tokens that can occur in a single batch
- Init(backend ml.Backend, dtype ml.DType, maxSequences, capacity, maxBatch int)
-
- // Close closes the cache and frees resources associated with it
- Close()
-
- // StartForward is called before the start of the model's forward pass.
- // For each token in the coming batch, there must be a corresponding
- // entry in positions and seqs. reserve is to preallocate memory
- // without actually storing data in the cache.
- StartForward(ctx ml.Context, batch input.Batch, reserve bool) error
-
- // CopyPrefix copies tokens in the range [0, len) from srcSeq to dstSeq
- CopyPrefix(srcSeq, dstSeq int, len int32)
-
- // CanResume returns true if the cache can continue with the next token at
- // the given position and sequence. Assumes that the caller has already
- // verified the contents of the cache.
- CanResume(seq int, pos int32) bool
-
- // Remove deletes tokens in the range [beginIndex, endIndex) from seq. Set
- // endIndex to math.MaxInt32 to remove everything starting at beginIndex.
- //
- // If an error occurs, the entire context for the sequence should be
- // removed by calling Remove(seq, 0, math.MaxInt32)
- Remove(seq int, beginIndex, endIndex int32) error
-}
-
-// CheckpointCache optionally supports restoring recurrent state to a prior
-// position to avoid full prompt reprocessing when a prefix mismatch occurs.
-// The returned position is the number of tokens that can be kept (prefix length).
-type CheckpointCache interface {
- PrepareRestore(seq int, targetPos int32) (int32, bool)
-}
diff --git a/kvcache/causal.go b/kvcache/causal.go
deleted file mode 100644
index e04f828e5..000000000
--- a/kvcache/causal.go
+++ /dev/null
@@ -1,666 +0,0 @@
-package kvcache
-
-import (
- "errors"
- "fmt"
- "math"
- "slices"
-
- "github.com/ollama/ollama/ml"
- "github.com/ollama/ollama/model/input"
-)
-
-type shiftFn func(ctx ml.Context, layer int, key, shift ml.Tensor) (ml.Tensor, error)
-
-// Causal cache stores K and V tensors according to their position in the
-// sequence. Returns the history and a mask for attending to past tokens
-//
-// The tensors are of shape embed dim, kv heads, batch size
-// The mask is of shape history size, batch size
-type Causal struct {
- DType ml.DType
-
- // swaWindowSize is the number of tokens that will be included in the mask
- // during attention operations. swaMemorySize is the number of tokens that
- // will be retained in memory for partial prefix caching. Set to math.MaxInt32
- // for unlimited or if sliding window attention is not being used.
- swaWindowSize int32
- swaMemorySize int32
-
- chunkSize int32
-
- opts CausalOptions
-
- // maxBatch is the largest batch that we might receive
- maxBatch int
-
- // config controls mostly backend-specific optimizations
- config *ml.CacheConfig
-
- // ** current forward pass **
-
- // size of the current batch
- curBatchSize int
-
- // locations for data storage for this batch
- curLoc ml.Tensor
-
- // mask of the cache as used by this batch
- curMask ml.Tensor
-
- // the active layer for Get and Put
- curLayer int
-
- // locations in the cache that are needed for this batch
- curCellRange cellRange
-
- // curSequences is the sequences corresponding to this pass's entries in the cache
- curSequences []int
-
- // curPositions is the positions corresponding to this pass's entries in the cache
- curPositions []int32
-
- // ** cache metadata **
-
- // for each possible location in the cache, stores the position and set of sequences
- // that reference the data there
- cells []cacheCell
-
- // maps from sequence to the range of locations where it is stored in the cache
- cellRanges map[int]cellRange
-
- // ** cache data storage **
-
- shiftFn shiftFn
- backend ml.Backend
- ctxs map[int]ml.Context
- keys, values map[int]ml.Tensor
-}
-
-type cacheCell struct {
- pos int32
- sequences []int
-}
-
-type cellRange struct {
- min int
- max int
-}
-
-func NewCausalCache(shift shiftFn) *Causal {
- return &Causal{
- shiftFn: shift,
- ctxs: make(map[int]ml.Context),
- keys: make(map[int]ml.Tensor),
- values: make(map[int]ml.Tensor),
- }
-}
-
-func NewSWACache(windowSize int32, shift shiftFn) *Causal {
- return &Causal{
- swaWindowSize: windowSize,
- shiftFn: shift,
- ctxs: make(map[int]ml.Context),
- keys: make(map[int]ml.Tensor),
- values: make(map[int]ml.Tensor),
- }
-}
-
-func NewSWAMemCache(windowSize int32, memorySize int32, shift shiftFn) *Causal {
- return &Causal{
- swaWindowSize: windowSize,
- swaMemorySize: memorySize,
- shiftFn: shift,
- ctxs: make(map[int]ml.Context),
- keys: make(map[int]ml.Tensor),
- values: make(map[int]ml.Tensor),
- }
-}
-
-func NewChunkedAttentionCache(chunkSize int32, shift shiftFn) *Causal {
- return &Causal{
- chunkSize: chunkSize,
- shiftFn: shift,
- ctxs: make(map[int]ml.Context),
- keys: make(map[int]ml.Tensor),
- values: make(map[int]ml.Tensor),
- }
-}
-
-func (c *Causal) Init(backend ml.Backend, dtype ml.DType, maxSequences, capacity, maxBatch int) {
- if c.config == nil {
- var config ml.CacheConfig
- if cc, ok := backend.(ml.BackendCacheConfig); ok {
- config = cc.CacheConfig()
- }
- c.config = &config
- }
-
- if c.config.CachePadding == 0 {
- c.config.CachePadding = 1
- }
-
- if c.config.MaskDType == ml.DTypeOther {
- c.config.MaskDType = ml.DTypeF32
- }
-
- if c.swaWindowSize == 0 {
- c.swaWindowSize = math.MaxInt32
- }
- if c.swaMemorySize == 0 {
- c.swaMemorySize = c.swaWindowSize
- }
- // We will allocate space in the cache for the stop token, which won't be part of a follow on
- // sequence, so allocate an extra token of storage to ensure that we can jump back without
- // causing a cache break. As an optimization, only do this when we have parallel sequences
- // because the extra token will live in the batch buffer and won't get overwritten if we
- // only have a single sequence.
- if c.swaMemorySize != math.MaxInt32 && maxSequences > 1 {
- c.swaMemorySize = max(c.swaMemorySize, c.swaWindowSize+1)
- }
- if int(c.swaMemorySize) >= capacity {
- c.swaMemorySize = math.MaxInt32
- }
-
- if c.swaMemorySize < c.swaWindowSize {
- panic(fmt.Errorf("sliding window memory (%v) must be at least as large as the window (%v)", c.swaMemorySize, c.swaWindowSize))
- }
-
- var cacheSize int
- if c.swaMemorySize == math.MaxInt32 {
- cacheSize = maxSequences * capacity
- } else {
- cacheSize = (maxSequences * int(c.swaMemorySize)) + maxBatch
- }
- cacheSize = roundUp(cacheSize, c.config.CachePadding)
- c.cells = make([]cacheCell, cacheSize)
-
- c.DType = dtype
- c.cellRanges = make(map[int]cellRange)
- c.backend = backend
- c.maxBatch = maxBatch
-}
-
-func (c *Causal) SetConfig(config ml.CacheConfig) {
- if c.config != nil {
- panic("config cannot be changed after being previously set, either by the model or backend")
- }
-
- c.config = &config
-}
-
-func (c *Causal) Close() {
- for _, ctx := range c.ctxs {
- ctx.Close()
- }
-}
-
-func (c *Causal) StartForward(ctx ml.Context, batch input.Batch, reserve bool) error {
- c.curBatchSize = len(batch.Positions)
- c.curSequences = batch.Sequences
- c.curPositions = batch.Positions
- c.opts.Except = nil
-
- var locs []int32
- if !reserve {
- c.updateSlidingWindow()
-
- var err error
- locs, err = c.findLocs()
- if err != nil {
- return err
- }
-
- for i, pos := range batch.Positions {
- seq := batch.Sequences[i]
- loc := int(locs[i])
-
- c.cells[loc] = cacheCell{pos: pos, sequences: []int{seq}}
-
- seqRange, ok := c.cellRanges[seq]
- if !ok {
- seqRange = newRange()
- }
-
- seqRange.min = min(seqRange.min, loc)
- c.curCellRange.min = min(c.curCellRange.min, loc)
-
- seqRange.max = max(seqRange.max, loc)
- c.curCellRange.max = max(c.curCellRange.max, loc)
-
- c.cellRanges[seq] = seqRange
- }
- } else {
- // If we are reserving memory, don't update any of the cache metadata but set the size
- // to the worst case.
- locs = make([]int32, c.curBatchSize)
- for i := range locs {
- locs[i] = int32(i)
- }
- c.curCellRange.min = 0
- c.curCellRange.max = len(c.cells) - 1
- }
-
- c.curLoc = ctx.Input().FromInts(locs, len(locs))
- c.curMask = c.buildMask(ctx)
-
- return nil
-}
-
-func newRange() cellRange {
- return cellRange{
- min: math.MaxInt,
- max: 0,
- }
-}
-
-// Returns a slice of locations where each token in the batch should be stored
-func (c *Causal) findLocs() ([]int32, error) {
- loc := make([]int32, 0, c.curBatchSize)
-
- for i := range c.cells {
- if len(c.cells[i].sequences) == 0 {
- loc = append(loc, int32(i))
- if len(loc) >= c.curBatchSize {
- return loc, nil
- }
- }
- }
-
- return nil, fmt.Errorf("%w (cache: %v batch: %v)", ErrKvCacheFull, len(c.cells), c.curBatchSize)
-}
-
-func (c *Causal) updateSlidingWindow() {
- c.curCellRange = newRange()
-
- if c.swaMemorySize == math.MaxInt32 {
- for _, seq := range c.curSequences {
- if seqRange, ok := c.cellRanges[seq]; ok {
- c.curCellRange.min = min(c.curCellRange.min, seqRange.min)
- c.curCellRange.max = max(c.curCellRange.max, seqRange.max)
- }
- }
-
- return
- }
-
- type lowestPosition struct {
- pos int32
- curBatch bool
- }
-
- // create a map of unique sequences to the lowest position in that sequence
- lowestPos := make(map[int]lowestPosition)
- for i := range c.curPositions {
- seq := c.curSequences[i]
-
- lowest, ok := lowestPos[seq]
- if !ok {
- lowest = lowestPosition{pos: c.curPositions[i], curBatch: true}
- } else if c.curPositions[i] < lowest.pos {
- lowest.pos = c.curPositions[i]
- }
-
- lowestPos[seq] = lowest
- }
-
- // for any sequences are not part of this batch, clean up any tokens
- // that are no longer needed after the processing of the previous
- // batch
- for seq, seqRange := range c.cellRanges {
- if _, ok := lowestPos[seq]; !ok {
- var last int32
- for i := seqRange.min; i <= seqRange.max; i++ {
- if slices.Contains(c.cells[i].sequences, seq) {
- last = max(last, c.cells[i].pos)
- }
- }
-
- lowestPos[seq] = lowestPosition{pos: last + 1, curBatch: false}
- }
- }
-
- // delete any entries that are beyond the window of the oldest position in the sequence
- for seq, lowest := range lowestPos {
- oldRange, ok := c.cellRanges[seq]
- if !ok {
- continue
- }
-
- newRange := newRange()
-
- for i := oldRange.min; i <= oldRange.max; i++ {
- if slices.Contains(c.cells[i].sequences, seq) {
- if c.cells[i].pos < lowest.pos-c.swaMemorySize {
- c.cells[i].sequences = slices.DeleteFunc(c.cells[i].sequences, func(s int) bool { return s == seq })
- } else {
- newRange.min = min(newRange.min, i)
- newRange.max = max(newRange.max, i)
- }
- if lowest.curBatch && c.cells[i].pos >= lowest.pos-c.swaWindowSize {
- c.curCellRange.min = min(c.curCellRange.min, i)
- c.curCellRange.max = max(c.curCellRange.max, i)
- }
- }
- }
-
- c.cellRanges[seq] = newRange
- }
-}
-
-func roundDown(length, pad int) int {
- return (length / pad) * pad
-}
-
-func roundUp(length, pad int) int {
- return ((length + pad - 1) / pad) * pad
-}
-
-// Builds a mask of history x batch indicating whether for each token in the batch the
-// token in the history should apply. This is based on both the sequence and causality (the
-// position of the history is not ahead of the token in the batch).
-func (c *Causal) buildMask(ctx ml.Context) ml.Tensor {
- c.curCellRange.min = roundDown(c.curCellRange.min, c.config.CachePadding)
- c.curCellRange.max = roundUp(c.curCellRange.max+1, c.config.CachePadding) - 1
-
- length := c.curCellRange.max - c.curCellRange.min + 1
-
- mask := make([]float32, c.curBatchSize*length)
-
- for i := range c.curBatchSize {
- enabled := !slices.Contains(c.opts.Except, i)
- for j := c.curCellRange.min; j <= c.curCellRange.max; j++ {
- if !slices.Contains(c.cells[j].sequences, c.curSequences[i]) ||
- (enabled && c.cells[j].pos > c.curPositions[i]) ||
- c.chunkSize > 0 && c.cells[j].pos < c.curPositions[i]-c.curPositions[i]%c.chunkSize ||
- c.cells[j].pos < c.curPositions[i]-c.swaWindowSize {
- mask[i*length+(j-c.curCellRange.min)] = float32(math.Inf(-1))
- }
- }
- }
-
- maskTensor := ctx.Input().FromFloats(mask, length, c.curBatchSize)
-
- if c.config.MaskDType != ml.DTypeF32 {
- maskTensor = maskTensor.Cast(ctx, c.config.MaskDType)
- }
-
- return maskTensor
-}
-
-func (c *Causal) SetLayer(layer int) {
- c.curLayer = layer
-}
-
-type CausalOptions struct {
- // Enabled controls whether the causal mask is generated for a particular index in a batch
- Except []int
-}
-
-// SetCausal disables causal mask generation for a particular range of indicies in
-// the current batch for subsequent calls to Get. The state resets for the next forward pass.
-func (c *Causal) SetCausal(ctx ml.Context, opts CausalOptions) {
- if !slices.Equal(c.opts.Except, opts.Except) {
- c.opts = opts
- if ctx != nil {
- c.curMask = c.buildMask(ctx)
- }
- }
-}
-
-func (c *Causal) Get(ctx ml.Context) (ml.Tensor, ml.Tensor, ml.Tensor) {
- key := c.keys[c.curLayer]
- value := c.values[c.curLayer]
-
- kHeadDim := key.Dim(0)
- numKVHeads := key.Dim(1)
- rowSize := key.Stride(2)
- cachedSize := c.curMask.Dim(0)
-
- key = key.View(ctx, rowSize*c.curCellRange.min,
- kHeadDim, key.Stride(1),
- numKVHeads, key.Stride(2),
- cachedSize,
- )
-
- if c.config.PermutedV {
- vHeadDim := value.Dim(1)
- elemSize := value.Stride(0)
-
- value = value.View(ctx, elemSize*c.curCellRange.min,
- cachedSize, value.Stride(1),
- vHeadDim, value.Stride(2),
- numKVHeads,
- )
- } else {
- vHeadDim := value.Dim(0)
- rowSize := value.Stride(2)
-
- value = value.View(ctx, rowSize*c.curCellRange.min,
- vHeadDim, value.Stride(1),
- numKVHeads, value.Stride(2),
- cachedSize,
- )
- }
-
- return key, value, c.curMask
-}
-
-func (c *Causal) Put(ctx ml.Context, key, value ml.Tensor) {
- kHeadDim := key.Dim(0)
- vHeadDim := value.Dim(0)
- numKVHeads := key.Dim(1)
- batchSize := key.Dim(2)
-
- if c.curBatchSize != batchSize {
- panic(fmt.Errorf("inconsistent batch sizes (layer: %v, batch size: %v layer batch size: %v)", c.curLayer, c.curBatchSize, batchSize))
- }
-
- if _, ok := c.ctxs[c.curLayer]; !ok {
- c.ctxs[c.curLayer] = c.backend.NewContextSize(2).Layer(c.curLayer)
- }
-
- if _, ok := c.keys[c.curLayer]; !ok {
- c.keys[c.curLayer] = c.ctxs[c.curLayer].Zeros(c.DType, kHeadDim, numKVHeads, len(c.cells))
- }
-
- if _, ok := c.values[c.curLayer]; !ok {
- if c.config.PermutedV {
- c.values[c.curLayer] = c.ctxs[c.curLayer].Zeros(c.DType, len(c.cells), vHeadDim, numKVHeads)
- } else {
- c.values[c.curLayer] = c.ctxs[c.curLayer].Zeros(c.DType, vHeadDim, numKVHeads, len(c.cells))
- }
- }
-
- key = key.Reshape(ctx, kHeadDim*numKVHeads, batchSize)
- keyCache := c.keys[c.curLayer]
- keyCache = keyCache.Reshape(ctx, kHeadDim*numKVHeads, len(c.cells))
- ctx.Forward(keyCache.SetRows(ctx, key, c.curLoc))
-
- if c.config.PermutedV {
- value = value.Reshape(ctx, vHeadDim*numKVHeads, 1, batchSize)
- value = value.Permute(ctx, 2, 0, 1, 3)
-
- valueCache := c.values[c.curLayer]
- valueCache = valueCache.Reshape(ctx, 1, len(c.cells), vHeadDim*numKVHeads)
-
- ctx.Forward(valueCache.SetRows(ctx, value, c.curLoc))
- } else {
- value = value.Reshape(ctx, vHeadDim*numKVHeads, batchSize)
- valueCache := c.values[c.curLayer]
- valueCache = valueCache.Reshape(ctx, vHeadDim*numKVHeads, len(c.cells))
-
- ctx.Forward(valueCache.SetRows(ctx, value, c.curLoc))
- }
-}
-
-func (c *Causal) CopyPrefix(srcSeq, dstSeq int, len int32) {
- seqRange := newRange()
-
- for i := range c.cells {
- // Remove the contents of dstSeq so that we only have the copied prefix, metadata will be reset at the end
- if slices.Contains(c.cells[i].sequences, dstSeq) {
- c.cells[i].sequences = slices.DeleteFunc(c.cells[i].sequences, func(s int) bool { return s == dstSeq })
- }
-
- if slices.Contains(c.cells[i].sequences, srcSeq) && c.cells[i].pos < len {
- c.cells[i].sequences = append(c.cells[i].sequences, dstSeq)
- if i < seqRange.min {
- seqRange.min = i
- }
- if i > seqRange.max {
- seqRange.max = i
- }
- }
- }
-
- c.cellRanges[dstSeq] = seqRange
-}
-
-func (c *Causal) CanResume(seq int, pos int32) bool {
- if c.swaMemorySize == math.MaxInt32 {
- return true
- }
-
- seqRange, ok := c.cellRanges[seq]
- if !ok {
- return false
- }
-
- // for sliding window, check that the window of the new sequence is contained in
- // the window of what we are storing
- var first int32 = math.MaxInt32
- var last int32 = -1
- for i := seqRange.min; i <= seqRange.max; i++ {
- if slices.Contains(c.cells[i].sequences, seq) {
- first = min(first, c.cells[i].pos)
- last = max(last, c.cells[i].pos)
- }
- }
-
- if last == -1 {
- return false
- }
-
- posWindowStart := max(0, pos-c.swaWindowSize)
- return posWindowStart >= first && pos <= last+1
-}
-
-func (c *Causal) shift(seq int, beginIndex, offset int32) error {
- if c.shiftFn == nil {
- return ErrNotSupported
- }
-
- seqRange := c.cellRanges[seq]
-
- for start := seqRange.min; start <= seqRange.max; start += c.maxBatch {
- size := min(seqRange.max-start+1, c.maxBatch)
- offsets := make([]int32, size)
-
- var batchFirst, batchLast int
-
- batchFirst = -1
- for i := range offsets {
- cell := c.cells[start+i]
-
- if slices.Contains(cell.sequences, seq) && cell.pos >= beginIndex {
- offsets[i] = offset
- if batchFirst < 0 {
- batchFirst = i
- }
- batchLast = i
- }
- }
-
- if batchFirst < 0 {
- continue
- }
-
- offsets = offsets[batchFirst : batchLast+1]
-
- ctx := c.backend.NewContext()
- kShift := ctx.Input().FromInts(offsets, len(offsets))
-
- for i, key := range c.keys {
- if key == nil {
- continue
- }
-
- kHeadDim := key.Dim(0)
- numKVHeads := key.Dim(1)
- rowSize := key.Stride(2)
-
- key = key.View(ctx, rowSize*(start+batchFirst),
- kHeadDim, key.Stride(1),
- numKVHeads, key.Stride(2),
- len(offsets),
- )
-
- roped, err := c.shiftFn(ctx, i, key, kShift)
- if err != nil {
- ctx.Close()
- return err
- }
-
- ctx.Forward(roped.Copy(ctx, key))
- }
-
- ctx.Compute()
- ctx.Close()
- }
-
- return nil
-}
-
-func (c *Causal) Remove(seq int, beginIndex, endIndex int32) error {
- // TODO(jessegross): We should check to see if removing the middle of the sequence will
- // cause the sliding window to encompass tokens that we no longer have. If so, then we
- // should return an error, which will trigger the runner to evaluate the full history and
- // rebuild the window. However, if we have multimodal inputs in our history, this reuse
- // results in use after free, so we don't do it for now.
-
- var offset int32
- if endIndex != math.MaxInt32 {
- offset = beginIndex - endIndex
- }
-
- seqRange := newRange()
-
- for i := range c.cells {
- if slices.Contains(c.cells[i].sequences, seq) {
- if c.cells[i].pos >= beginIndex && c.cells[i].pos < endIndex {
- c.cells[i].sequences = slices.DeleteFunc(c.cells[i].sequences, func(s int) bool { return s == seq })
- } else {
- if c.cells[i].pos >= endIndex {
- if slices.ContainsFunc(c.cells[i].sequences, func(s int) bool { return s != seq }) {
- return errors.New("shifting cells shared by multiple sequences not supported")
- }
-
- c.cells[i].pos += offset
- }
- if i < seqRange.min {
- seqRange.min = i
- }
- if i > seqRange.max {
- seqRange.max = i
- }
- }
- }
- }
-
- if seqRange == newRange() {
- delete(c.cellRanges, seq)
- return nil
- }
-
- c.cellRanges[seq] = seqRange
-
- if endIndex != math.MaxInt32 {
- err := c.shift(seq, endIndex+offset, offset)
- if err != nil {
- return err
- }
- }
-
- return nil
-}
diff --git a/kvcache/causal_test.go b/kvcache/causal_test.go
deleted file mode 100644
index aeda93bc6..000000000
--- a/kvcache/causal_test.go
+++ /dev/null
@@ -1,973 +0,0 @@
-package kvcache
-
-import (
- "fmt"
- "math"
- "slices"
- "testing"
-
- "github.com/ollama/ollama/ml"
- "github.com/ollama/ollama/model/input"
-)
-
-type testCase struct {
- name string
- in []float32
- inShape []int
- seqs []int
- pos []int32
- expected []float32
- expectedShape []int
- expectedMask []float32
-}
-
-func runPermutedVariants(t *testing.T, fn func(t *testing.T, backend *testBackend)) {
- t.Helper()
- for _, permuted := range []bool{false, true} {
- t.Run(fmt.Sprintf("PermutedV=%t", permuted), func(t *testing.T) {
- fn(t, &testBackend{permutedV: permuted})
- })
- }
-}
-
-func TestStore(t *testing.T) {
- runPermutedVariants(t, func(t *testing.T, backend *testBackend) {
- cache := NewCausalCache(nil)
- defer cache.Close()
-
- cache.Init(backend, ml.DTypeF16, 1, 16, 16)
-
- tests := []testCase{
- {
- name: "FirstBatch",
- in: []float32{111, 211, 121, 221, 131, 231, 112, 212, 122, 222, 132, 232, 113, 213, 123, 223, 133, 233, 114, 214, 124, 224, 134, 234},
- inShape: []int{2, 3, 4},
- seqs: []int{0, 0, 0, 0},
- pos: []int32{0, 1, 2, 3},
- expected: []float32{111, 211, 121, 221, 131, 231, 112, 212, 122, 222, 132, 232, 113, 213, 123, 223, 133, 233, 114, 214, 124, 224, 134, 234},
- expectedShape: []int{2, 3, 4},
- expectedMask: []float32{0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, 0, float32(math.Inf(-1)), 0, 0, 0, 0},
- },
- {
- name: "SecondBatch",
- in: []float32{115, 215, 125, 225, 135, 235},
- inShape: []int{2, 3, 1},
- seqs: []int{0},
- pos: []int32{4},
- expected: []float32{111, 211, 121, 221, 131, 231, 112, 212, 122, 222, 132, 232, 113, 213, 123, 223, 133, 233, 114, 214, 124, 224, 134, 234, 115, 215, 125, 225, 135, 235},
- expectedShape: []int{2, 3, 5},
- expectedMask: []float32{0, 0, 0, 0, 0},
- },
- }
-
- testCache(t, backend, cache, tests)
- })
-}
-
-func TestSWA(t *testing.T) {
- runPermutedVariants(t, func(t *testing.T, backend *testBackend) {
- cache := NewSWACache(1, nil)
- defer cache.Close()
-
- cache.Init(backend, ml.DTypeF16, 1, 16, 16)
-
- x := float32(math.Inf(-1))
-
- tests := []testCase{
- {
- name: "FirstBatch",
- in: []float32{1, 2, 3, 4},
- inShape: []int{1, 1, 4},
- seqs: []int{0, 0, 0, 0},
- pos: []int32{0, 1, 2, 3},
- expected: []float32{1, 2, 3, 4},
- expectedShape: []int{1, 1, 4},
- expectedMask: []float32{
- 0, x, x, x,
- 0, 0, x, x,
- x, 0, 0, x,
- x, x, 0, 0,
- },
- },
- {
- name: "SecondBatch",
- in: []float32{5, 6},
- inShape: []int{1, 1, 2},
- seqs: []int{0, 0},
- pos: []int32{4, 5},
- expected: []float32{5, 6, 3, 4},
- expectedShape: []int{1, 1, 4},
- expectedMask: []float32{
- 0, x, x, 0,
- 0, 0, x, x,
- },
- },
- }
-
- testCache(t, backend, cache, tests)
- })
-}
-
-func TestSWASeparateBatches(t *testing.T) {
- runPermutedVariants(t, func(t *testing.T, backend *testBackend) {
- cache := NewSWACache(1, nil)
- defer cache.Close()
-
- cache.Init(backend, ml.DTypeF16, 2, 16, 2)
-
- x := float32(math.Inf(-1))
-
- tests := []testCase{
- {
- name: "First seq 0",
- in: []float32{1, 2},
- inShape: []int{1, 1, 2},
- seqs: []int{0, 0},
- pos: []int32{0, 1},
- expected: []float32{1, 2},
- expectedShape: []int{1, 1, 2},
- expectedMask: []float32{
- 0, x,
- 0, 0,
- },
- },
- {
- name: "Second seq 0",
- in: []float32{3, 4},
- inShape: []int{1, 1, 2},
- seqs: []int{0, 0},
- pos: []int32{2, 3},
- expected: []float32{2, 3, 4},
- expectedShape: []int{1, 1, 3},
- expectedMask: []float32{
- 0, 0, x,
- x, 0, 0,
- },
- },
- {
- name: "First seq 1",
- in: []float32{5, 6},
- inShape: []int{1, 1, 2},
- seqs: []int{1, 1},
- pos: []int32{0, 1},
- expected: []float32{5, 6},
- expectedShape: []int{1, 1, 2},
- expectedMask: []float32{
- 0, x,
- 0, 0,
- },
- },
- {
- name: "Second seq 1",
- in: []float32{7, 8},
- inShape: []int{1, 1, 2},
- seqs: []int{1, 1},
- pos: []int32{2, 3},
- expected: []float32{6, 3, 4, 7, 8},
- expectedShape: []int{1, 1, 5},
- expectedMask: []float32{
- 0, x, x, 0, x,
- x, x, x, 0, 0,
- },
- },
- {
- name: "Third seq 0",
- in: []float32{9, 10},
- inShape: []int{1, 1, 2},
- seqs: []int{0, 0},
- pos: []int32{4, 5},
- expected: []float32{9, 10, 3, 4},
- expectedShape: []int{1, 1, 4},
- expectedMask: []float32{
- 0, x, x, 0,
- 0, 0, x, x,
- },
- },
- }
-
- testCache(t, backend, cache, tests)
- })
-}
-
-func TestSWAMem(t *testing.T) {
- runPermutedVariants(t, func(t *testing.T, backend *testBackend) {
- cache := NewSWAMemCache(1, 3, nil)
- defer cache.Close()
-
- cache.Init(backend, ml.DTypeF16, 1, 16, 16)
-
- x := float32(math.Inf(-1))
-
- tests := []testCase{
- {
- name: "FirstBatch",
- in: []float32{1, 2, 3, 4},
- inShape: []int{1, 1, 4},
- seqs: []int{0, 0, 0, 0},
- pos: []int32{0, 1, 2, 3},
- expected: []float32{1, 2, 3, 4},
- expectedShape: []int{1, 1, 4},
- expectedMask: []float32{
- 0, x, x, x,
- 0, 0, x, x,
- x, 0, 0, x,
- x, x, 0, 0,
- },
- },
- {
- name: "SecondBatch",
- in: []float32{5, 6},
- inShape: []int{1, 1, 2},
- seqs: []int{0, 0},
- pos: []int32{4, 5},
- expected: []float32{5, 2, 3, 4, 6},
- expectedShape: []int{1, 1, 5},
- expectedMask: []float32{
- 0, x, x, 0, x,
- 0, x, x, x, 0,
- },
- },
- }
-
- testCache(t, backend, cache, tests)
- })
-}
-
-func TestChunkedAttention(t *testing.T) {
- runPermutedVariants(t, func(t *testing.T, backend *testBackend) {
- cache := NewChunkedAttentionCache(2, nil)
- defer cache.Close()
-
- cache.Init(backend, ml.DTypeF16, 1, 16, 16)
-
- x := float32(math.Inf(-1))
-
- testCache(
- t, backend, cache,
- []testCase{
- {
- name: "FirstBatch",
- in: []float32{1, 2, 3, 4},
- inShape: []int{1, 1, 4},
- seqs: []int{0, 0, 0, 0},
- pos: []int32{0, 1, 2, 3},
- expected: []float32{1, 2, 3, 4},
- expectedShape: []int{1, 1, 4},
- expectedMask: []float32{
- 0, x, x, x,
- 0, 0, x, x,
- x, x, 0, x,
- x, x, 0, 0,
- },
- },
- {
- name: "SecondBatch",
- in: []float32{5, 6, 7},
- inShape: []int{1, 1, 3},
- seqs: []int{0, 0, 0},
- pos: []int32{4, 5, 6},
- expected: []float32{1, 2, 3, 4, 5, 6, 7},
- expectedShape: []int{1, 1, 7},
- expectedMask: []float32{
- x, x, x, x, 0, x, x,
- x, x, x, x, 0, 0, x,
- x, x, x, x, x, x, 0,
- },
- },
- {
- name: "ThirdBatch",
- in: []float32{8, 9},
- inShape: []int{1, 1, 2},
- seqs: []int{0, 0},
- pos: []int32{7, 8},
- expected: []float32{1, 2, 3, 4, 5, 6, 7, 8, 9},
- expectedShape: []int{1, 1, 9},
- expectedMask: []float32{
- x, x, x, x, x, x, 0, 0, x,
- x, x, x, x, x, x, x, x, 0,
- },
- },
- },
- )
- })
-}
-
-func TestSequences(t *testing.T) {
- runPermutedVariants(t, func(t *testing.T, backend *testBackend) {
- cache := NewCausalCache(nil)
- defer cache.Close()
-
- cache.Init(backend, ml.DTypeF16, 1, 16, 16)
-
- tests := []testCase{
- {
- name: "FirstBatch",
- in: []float32{1, 2, 3, 4},
- inShape: []int{1, 1, 4},
- seqs: []int{0, 0, 1, 1},
- pos: []int32{0, 1, 0, 1},
- expected: []float32{1, 2, 3, 4},
- expectedShape: []int{1, 1, 4},
- expectedMask: []float32{0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0},
- },
- {
- name: "SecondBatch",
- in: []float32{5, 6},
- inShape: []int{1, 1, 2},
- seqs: []int{0, 1},
- pos: []int32{2, 2},
- expected: []float32{1, 2, 3, 4, 5, 6},
- expectedShape: []int{1, 1, 6},
- expectedMask: []float32{0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), 0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, float32(math.Inf(-1)), 0},
- },
- }
-
- testCache(t, backend, cache, tests)
- })
-}
-
-func TestRemove(t *testing.T) {
- runPermutedVariants(t, func(t *testing.T, backend *testBackend) {
- cache := NewCausalCache(func(ctx ml.Context, layer int, key, shift ml.Tensor) (ml.Tensor, error) {
- return key.Add(ctx, shift), nil
- })
- defer cache.Close()
-
- cache.Init(backend, ml.DTypeF16, 1, 16, 16)
-
- x := float32(math.Inf(-1))
-
- tests := []testCase{
- {
- name: "FirstBatch",
- in: []float32{1, 2, 3, 4},
- inShape: []int{1, 1, 4},
- seqs: []int{0, 0, 1, 1},
- pos: []int32{0, 1, 0, 1},
- expected: []float32{1, 2, 3, 4},
- expectedShape: []int{1, 1, 4},
- expectedMask: []float32{
- 0, x, x, x,
- 0, 0, x, x,
- x, x, 0, x,
- x, x, 0, 0,
- },
- },
- }
-
- testCache(t, backend, cache, tests)
-
- err := cache.Remove(0, 1, math.MaxInt32)
- if err != nil {
- panic(err)
- }
-
- tests = []testCase{
- {
- name: "RemoveEnd",
- in: []float32{5, 6},
- inShape: []int{1, 1, 2},
- seqs: []int{0, 1},
- pos: []int32{1, 2},
- expected: []float32{1, 5, 3, 4, 6},
- expectedShape: []int{1, 1, 5},
- expectedMask: []float32{
- 0, 0, x, x, x,
- x, x, 0, 0, 0,
- },
- },
- }
-
- testCache(t, backend, cache, tests)
-
- err = cache.Remove(0, 0, 1)
- if err != nil {
- panic(err)
- }
-
- tests = []testCase{
- {
- name: "RemoveMiddle",
- in: []float32{7, 8},
- inShape: []int{1, 1, 2},
- seqs: []int{0, 0},
- pos: []int32{1, 2},
- expected: []float32{7, 4, 3, 4, 6, 8},
- expectedShape: []int{1, 1, 6},
- expectedMask: []float32{
- 0, 0, x, x, x, x,
- 0, 0, x, x, x, 0,
- },
- },
- }
-
- testCache(t, backend, cache, tests)
- })
-}
-
-func TestCopy(t *testing.T) {
- runPermutedVariants(t, func(t *testing.T, backend *testBackend) {
- cache := NewCausalCache(func(ctx ml.Context, layer int, key, shift ml.Tensor) (ml.Tensor, error) { return key, nil })
- defer cache.Close()
-
- cache.Init(backend, ml.DTypeF16, 1, 16, 16)
-
- tests := []testCase{
- {
- name: "FirstBatch",
- in: []float32{1, 2, 3, 4},
- inShape: []int{1, 1, 4},
- seqs: []int{0, 0, 0, 0},
- pos: []int32{0, 1, 2, 3},
- expected: []float32{1, 2, 3, 4},
- expectedShape: []int{1, 1, 4},
- expectedMask: []float32{0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, 0, float32(math.Inf(-1)), 0, 0, 0, 0},
- },
- }
-
- testCache(t, backend, cache, tests)
-
- cache.CopyPrefix(0, 1, 2)
-
- tests = []testCase{
- {
- name: "Copy",
- in: []float32{5, 6},
- inShape: []int{1, 1, 2},
- seqs: []int{1, 1},
- pos: []int32{3, 4},
- expected: []float32{1, 2, 3, 4, 5, 6},
- expectedShape: []int{1, 1, 6},
- expectedMask: []float32{0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), 0, float32(math.Inf(-1)), 0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0},
- },
- }
-
- testCache(t, backend, cache, tests)
- })
-}
-
-func testCache(t *testing.T, backend ml.Backend, cache Cache, tests []testCase) {
- for _, test := range tests {
- t.Run(test.name, func(t *testing.T) {
- context := backend.NewContext()
- defer context.Close()
-
- err := cache.StartForward(context, input.Batch{Positions: test.pos, Sequences: test.seqs}, false)
- if err != nil {
- panic(err)
- }
-
- cache.SetLayer(0)
- tensor := context.FromFloats(test.in, test.inShape...)
- cache.Put(context, tensor, tensor)
-
- out, _, mask := cache.Get(context)
-
- context.Forward(out, mask).Compute(out, mask)
-
- if !slices.Equal(out.Floats(), test.expected) {
- t.Errorf("TestCache: have %v; want %v", out.Floats(), test.expected)
- }
-
- if !slices.Equal(out.Shape(), test.expectedShape) {
- t.Errorf("TestCache: has shape %v; want %v", out.Shape(), test.expectedShape)
- }
-
- if !slices.Equal(mask.Floats(), test.expectedMask) {
- t.Errorf("TestCache: have mask: have %v want %v", mask.Floats(), test.expectedMask)
- }
- })
- }
-}
-
-func TestCanResume(t *testing.T) {
- runPermutedVariants(t, func(t *testing.T, backend *testBackend) {
- windowSize := int32(4)
- cache := NewSWACache(windowSize, nil)
- defer cache.Close()
-
- cache.Init(backend, ml.DTypeF16, 1, 16, 16)
-
- context := backend.NewContext()
- defer context.Close()
-
- err := cache.StartForward(context, input.Batch{
- Positions: []int32{0, 1, 2, 3, 4},
- Sequences: []int{0, 0, 0, 0, 0},
- }, false)
- if err != nil {
- t.Fatalf("StartForward failed: %v", err)
- }
-
- cache.SetLayer(0)
- tensor := context.FromFloats([]float32{1, 2, 3, 4, 5}, 1, 1, 5)
- cache.Put(context, tensor, tensor)
-
- // with window size 4, nothing has slid out of the window yet
- if !cache.CanResume(0, 0) {
- t.Errorf("CanResume(0, 0) = false, want true (within window)")
- }
- if !cache.CanResume(0, 1) {
- t.Errorf("CanResume(0, 1) = false, want true (within window)")
- }
- if !cache.CanResume(0, 2) {
- t.Errorf("CanResume(0, 2) = false, want true (within window)")
- }
- if !cache.CanResume(0, 3) {
- t.Errorf("CanResume(0, 3) = false, want true (latest position)")
- }
- if !cache.CanResume(0, 4) {
- t.Errorf("CanResume(0, 4) = false, want true (latest position)")
- }
-
- // shift window by adding position 5
- err = cache.StartForward(context, input.Batch{
- Positions: []int32{5},
- Sequences: []int{0},
- }, false)
- if err != nil {
- t.Fatalf("StartForward failed: %v", err)
- }
-
- cache.SetLayer(0)
- tensor = context.FromFloats([]float32{6}, 1, 1, 1)
- cache.Put(context, tensor, tensor)
-
- // only the latest position has overlapping windows
- if cache.CanResume(0, 0) {
- t.Errorf("after shift: CanResume(0, 0) = true, want false (outside window)")
- }
- if cache.CanResume(0, 1) {
- t.Errorf("after shift: CanResume(0, 1) = true, want false (outside window)")
- }
- if cache.CanResume(0, 2) {
- t.Errorf("after shift: CanResume(0, 2) = true, want false (outside window)")
- }
- if cache.CanResume(0, 3) {
- t.Errorf("after shift: CanResume(0, 3) = true, want false (outside window)")
- }
- if cache.CanResume(0, 4) {
- t.Errorf("after shift: CanResume(0, 4) = true, want false (outside window)")
- }
- if !cache.CanResume(0, 5) {
- t.Errorf("after shift: CanResume(0, 5) = false, want true (latest position)")
- }
- })
-}
-
-func TestCanResumeSWAMem(t *testing.T) {
- runPermutedVariants(t, func(t *testing.T, backend *testBackend) {
- windowSize := int32(4)
- memSize := int32(5)
- cache := NewSWAMemCache(windowSize, memSize, nil)
- defer cache.Close()
-
- cache.Init(backend, ml.DTypeF16, 1, 16, 16)
-
- context := backend.NewContext()
- defer context.Close()
-
- err := cache.StartForward(context, input.Batch{
- Positions: []int32{0, 1, 2, 3, 4, 5, 6},
- Sequences: []int{0, 0, 0, 0, 0, 0, 0},
- }, false)
- if err != nil {
- t.Fatalf("StartForward failed: %v", err)
- }
-
- cache.SetLayer(0)
- tensor := context.FromFloats([]float32{1, 2, 3, 4, 5, 6, 7}, 1, 1, 7)
- cache.Put(context, tensor, tensor)
-
- // shift window by adding position 7
- err = cache.StartForward(context, input.Batch{
- Positions: []int32{7},
- Sequences: []int{0},
- }, false)
- if err != nil {
- t.Fatalf("StartForward failed: %v", err)
- }
-
- cache.SetLayer(0)
- tensor = context.FromFloats([]float32{8}, 1, 1, 1)
- cache.Put(context, tensor, tensor)
-
- // only the latest position has overlapping windows
- if cache.CanResume(0, 0) {
- t.Errorf("after shift: CanResume(0, 0) = true, want false (outside window)")
- }
- if cache.CanResume(0, 1) {
- t.Errorf("after shift: CanResume(0, 1) = true, want false (outside window)")
- }
- if cache.CanResume(0, 2) {
- t.Errorf("after shift: CanResume(0, 2) = true, want false (outside window)")
- }
- if cache.CanResume(0, 3) {
- t.Errorf("after shift: CanResume(0, 3) = true, want false (outside window)")
- }
- if cache.CanResume(0, 4) {
- t.Errorf("after shift: CanResume(0, 4) = true, want false (outside window)")
- }
- if cache.CanResume(0, 5) {
- t.Errorf("after shift: CanResume(0, 5) = true, want false (outside window)")
- }
- if !cache.CanResume(0, 6) {
- t.Errorf("after shift: CanResume(0, 6) = false, want true (inside window)")
- }
- if !cache.CanResume(0, 7) {
- t.Errorf("after shift: CanResume(0, 7) = false, want true (latest position)")
- }
- })
-}
-
-type testBackend struct {
- ml.Backend
- permutedV bool
-}
-
-func (b *testBackend) NewContext() ml.Context {
- return &testContext{}
-}
-
-func (b *testBackend) NewContextSize(int) ml.Context {
- return &testContext{}
-}
-
-func (b *testBackend) CacheConfig() ml.CacheConfig {
- return ml.CacheConfig{PermutedV: b.permutedV}
-}
-
-type testContext struct {
- ml.Context
-}
-
-func (c *testContext) Empty(dtype ml.DType, shape ...int) ml.Tensor {
- total := 0
-
- if len(shape) > 0 {
- total = 1
- for _, s := range shape {
- total *= s
- }
- }
-
- return &testTensor{dtype: dtype, elementSize: 4, data: make([]float32, total), shape: shape}
-}
-
-func (c *testContext) Zeros(dtype ml.DType, shape ...int) ml.Tensor {
- return c.Empty(dtype, shape...)
-}
-
-func (c *testContext) FromFloats(s []float32, shape ...int) ml.Tensor {
- t := c.Empty(ml.DTypeF32, shape...).(*testTensor)
-
- copy(t.data, s)
-
- return t
-}
-
-func (c *testContext) FromInts(s []int32, shape ...int) ml.Tensor {
- f := make([]float32, len(s))
- for i := range f {
- f[i] = float32(s[i])
- }
-
- out := c.FromFloats(f, shape...)
- out.(*testTensor).dtype = ml.DTypeI32
-
- return out
-}
-
-func (c *testContext) Arange(start, stop, step float32, dtype ml.DType) ml.Tensor {
- s := make([]float32, 0, int((stop-start)/step))
- for i := start; i < stop; i += step {
- s = append(s, i)
- }
-
- out := c.FromFloats(s, len(s))
- out.(*testTensor).dtype = dtype
- return out
-}
-
-func (c *testContext) Input() ml.Context { return c }
-func (c *testContext) Layer(int) ml.Context { return c }
-
-func (c *testContext) Forward(...ml.Tensor) ml.Context { return c }
-
-func (c *testContext) Compute(...ml.Tensor) {}
-
-func (c *testContext) Reserve() {}
-
-func (c *testContext) MaxGraphNodes() int {
- return 10
-}
-
-func (c *testContext) Close() {}
-
-type testTensor struct {
- ml.Tensor
-
- dtype ml.DType
- elementSize int
- data []float32
- shape []int
-}
-
-func (t *testTensor) Dim(n int) int {
- return t.shape[n]
-}
-
-func (t *testTensor) Stride(n int) int {
- stride := t.elementSize
- for i := range n {
- stride *= t.shape[i]
- }
-
- return stride
-}
-
-func (t *testTensor) Shape() []int {
- return t.shape
-}
-
-func (t *testTensor) DType() ml.DType {
- return t.dtype
-}
-
-func (t *testTensor) Floats() []float32 {
- out := make([]float32, len(t.data))
- copy(out, t.data)
- return out
-}
-
-func (t *testTensor) Neg(ctx ml.Context) ml.Tensor {
- out := ctx.Empty(t.DType(), t.Shape()...).(*testTensor)
- for i := range out.data {
- out.data[i] = -t.data[i]
- }
- return out
-}
-
-func (t *testTensor) Add(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
- out := ctx.Empty(t.DType(), t.Shape()...).(*testTensor)
-
- for i := range out.data {
- out.data[i] = t.data[i] + t2.(*testTensor).data[i]
- }
-
- return out
-}
-
-func (t *testTensor) Reshape(ctx ml.Context, shape ...int) ml.Tensor {
- return &testTensor{
- dtype: t.dtype,
- elementSize: t.elementSize,
- data: t.data,
- shape: shape,
- }
-}
-
-func (t *testTensor) View(ctx ml.Context, offset int, shape ...int) ml.Tensor {
- offset /= t.elementSize
-
- var s []int
-
- switch len(shape) {
- case 1:
- s = []int{shape[0]}
- case 3:
- s = []int{shape[0], shape[2]}
- case 5:
- s = []int{shape[0], shape[2], shape[4]}
- default:
- panic("unsupported number of dimensions")
- }
-
- context := &testContext{}
-
- view := context.Empty(t.dtype, s...).(*testTensor)
- view.data = t.data[offset : offset+len(view.data)]
-
- return view
-}
-
-func (t *testTensor) Permute(ctx ml.Context, order ...int) ml.Tensor {
- if len(t.shape) > 4 || len(order) > 4 {
- panic("permute only supports up to 4 dimensions")
- }
-
- if len(order) != len(t.shape) && len(order) != 4 {
- panic("invalid number of dimensions for permute")
- }
-
- // ggml_permute expects 4 axes, so fill in any missing dimensions.
- orderFull := append(make([]int, 0, 4), order...)
- for len(orderFull) < 4 {
- orderFull = append(orderFull, len(orderFull))
- }
-
- seen := [4]bool{}
-
- shape4 := [4]int{1, 1, 1, 1}
- for i := 0; i < len(t.shape) && i < 4; i++ {
- shape4[i] = t.shape[i]
- }
-
- newShape4 := [4]int{1, 1, 1, 1}
- for axis := range 4 {
- dst := orderFull[axis]
- if dst < 0 || dst >= 4 {
- panic("invalid axis for permute")
- }
- if seen[dst] {
- panic("duplicate axis for permute")
- }
- seen[dst] = true
- newShape4[dst] = shape4[axis]
- }
-
- total := len(t.data)
- newData := make([]float32, total)
-
- if total > 0 {
- oldDims := shape4
- newDims := newShape4
-
- oldStride := [4]int{1, 1, 1, 1}
- newStride := [4]int{1, 1, 1, 1}
- for i := 1; i < 4; i++ {
- oldStride[i] = oldStride[i-1] * oldDims[i-1]
- newStride[i] = newStride[i-1] * newDims[i-1]
- }
-
- var coords [4]int
- var newCoords [4]int
-
- for idx := range total {
- remainder := idx
- for axis := range 4 {
- dim := oldDims[axis]
- if dim == 0 {
- coords[axis] = 0
- continue
- }
- coords[axis] = remainder % dim
- remainder /= dim
- }
-
- for axis := range 4 {
- newCoords[orderFull[axis]] = coords[axis]
- }
-
- newIndex := 0
- for axis := range 4 {
- if newDims[axis] == 0 {
- continue
- }
- newIndex += newCoords[axis] * newStride[axis]
- }
-
- newData[newIndex] = t.data[idx]
- }
- }
-
- numDims := 4
- for numDims > 1 && newShape4[numDims-1] <= 1 {
- numDims--
- }
-
- newShape := make([]int, numDims)
- copy(newShape, newShape4[:numDims])
-
- return &testTensor{
- dtype: t.dtype,
- elementSize: t.elementSize,
- data: newData,
- shape: newShape,
- }
-}
-
-func (t *testTensor) SetRows(ctx ml.Context, src ml.Tensor, idxs ml.Tensor) ml.Tensor {
- dst := t
- srcTensor := src.(*testTensor)
- idxTensor := idxs.(*testTensor)
-
- shapeTo4D := func(shape []int) [4]int {
- out := [4]int{1, 1, 1, 1}
- for i := 0; i < len(shape) && i < 4; i++ {
- out[i] = shape[i]
- }
- return out
- }
-
- computeStrides := func(shape [4]int) [4]int {
- out := [4]int{1, 1, 1, 1}
- for i := 1; i < 4; i++ {
- out[i] = out[i-1] * shape[i-1]
- }
- return out
- }
-
- dstShape4D := shapeTo4D(dst.shape)
- srcShape4D := shapeTo4D(srcTensor.shape)
- idxShape4D := shapeTo4D(idxTensor.shape)
-
- if dstShape4D[0] != srcShape4D[0] || dstShape4D[2] != srcShape4D[2] || dstShape4D[3] != srcShape4D[3] {
- panic("SetRows requires matching tensor shapes")
- }
-
- if srcShape4D[1] != idxShape4D[0] {
- panic("SetRows rows/index mismatch")
- }
-
- if srcShape4D[2]%idxShape4D[1] != 0 || srcShape4D[3]%idxShape4D[2] != 0 {
- panic("SetRows cannot broadcast indices")
- }
-
- if idxShape4D[3] != 1 {
- panic("SetRows expects 1D or 2D index tensors")
- }
-
- dstStride := computeStrides(dstShape4D)
- srcStride := computeStrides(srcShape4D)
- idxStride := computeStrides(idxShape4D)
-
- numColumns := srcShape4D[0]
- numRows := srcShape4D[1]
-
- for dim3Index := range dstShape4D[3] {
- for dim2Index := range dstShape4D[2] {
- idxDim2 := 0
- idxDim3 := 0
- if idxShape4D[1] > 0 {
- idxDim2 = dim2Index % idxShape4D[1]
- }
- if idxShape4D[2] > 0 {
- idxDim3 = dim3Index % idxShape4D[2]
- }
-
- idxBase := idxDim3*idxStride[2] + idxDim2*idxStride[1]
- srcBase := dim3Index*srcStride[3] + dim2Index*srcStride[2]
- dstBase := dim3Index*dstStride[3] + dim2Index*dstStride[2]
-
- for row := range numRows {
- idx := int(idxTensor.data[idxBase+row*idxStride[0]])
- if idx < 0 || idx >= dstShape4D[1] {
- panic("SetRows index out of range")
- }
-
- srcOffset := srcBase + row*srcStride[1]
- dstOffset := dstBase + idx*dstStride[1]
-
- copy(dst.data[dstOffset:dstOffset+numColumns], srcTensor.data[srcOffset:srcOffset+numColumns])
- }
- }
- }
-
- return dst
-}
-
-func (t *testTensor) Copy(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
- copy(t2.(*testTensor).data, t.data)
- return nil
-}
diff --git a/kvcache/encoder.go b/kvcache/encoder.go
deleted file mode 100644
index 0f269c3ee..000000000
--- a/kvcache/encoder.go
+++ /dev/null
@@ -1,156 +0,0 @@
-package kvcache
-
-import (
- "fmt"
-
- "github.com/ollama/ollama/ml"
- "github.com/ollama/ollama/model/input"
-)
-
-// Encoder cache stores K and V tensors that are position independent
-//
-// The tensors can be of any shape and will be returned as they were stored
-// The mask is currently always nil
-//
-// Not currently safe for multiple sequences
-type EncoderCache struct {
- // config controls mostly backend-specific optimizations
- config *ml.CacheConfig
-
- // ** current forward pass **
-
- // the active layer for Get and Put
- curLayer int
-
- // if something is stored during this pass, this
- // will be the position (but there is no guarantee
- // anything will be stored)
- curPos int32
-
- // curReserve indicates that this forward pass is only for
- // memory reservation and we should not update our metadata
- // based on it.
- curReserve bool
-
- // ** cache metadata **
-
- // was something stored in the cache?
- encoderCached bool
-
- // position of the cached data
- encoderPos int32
-
- // ** cache data storage **
- backend ml.Backend
- ctxs map[int]ml.Context
- keys, values map[int]ml.Tensor
-}
-
-func NewEncoderCache() *EncoderCache {
- return &EncoderCache{
- ctxs: make(map[int]ml.Context),
- keys: make(map[int]ml.Tensor),
- values: make(map[int]ml.Tensor),
- }
-}
-
-func (c *EncoderCache) Init(backend ml.Backend, dtype ml.DType, maxSequences, capacity, maxBatch int) {
- if c.config == nil {
- var config ml.CacheConfig
- if cc, ok := backend.(ml.BackendCacheConfig); ok {
- config = cc.CacheConfig()
- }
- c.config = &config
- }
-
- if maxSequences > 1 {
- panic(fmt.Errorf("encoder cache does not support multiple sequences; requested: %v", maxSequences))
- }
-
- if c.config.CachePadding != 0 && c.config.CachePadding != 1 {
- panic(fmt.Errorf("encoder cache is unable to enforce requested CachePadding (%v)", c.config.CachePadding))
- }
-
- c.backend = backend
-}
-
-func (c *EncoderCache) SetConfig(config ml.CacheConfig) {
- if c.config != nil {
- panic("config cannot be changed after being previously set, either by the model or backend")
- }
-
- c.config = &config
-}
-
-func (c *EncoderCache) Close() {
- for _, ctx := range c.ctxs {
- ctx.Close()
- }
-}
-
-func (c *EncoderCache) StartForward(ctx ml.Context, batch input.Batch, reserve bool) error {
- // We work with the most recent image
- if len(batch.Multimodal) > 0 {
- c.curPos = batch.Positions[batch.Multimodal[len(batch.Multimodal)-1].Index]
- }
-
- c.curReserve = reserve
-
- return nil
-}
-
-func (c *EncoderCache) SetLayer(layer int) {
- c.curLayer = layer
-}
-
-func (c *EncoderCache) EncoderCached() bool {
- return c.encoderCached
-}
-
-func (c *EncoderCache) Get(ctx ml.Context) (ml.Tensor, ml.Tensor, ml.Tensor) {
- return c.keys[c.curLayer], c.values[c.curLayer], nil
-}
-
-func (c *EncoderCache) Put(ctx ml.Context, key, value ml.Tensor) {
- if !c.curReserve {
- c.encoderPos = c.curPos
- c.encoderCached = true
- }
-
- if c.config.PermutedV {
- value = value.Permute(ctx, 1, 2, 0, 3)
- }
-
- if _, ok := c.ctxs[c.curLayer]; !ok {
- c.ctxs[c.curLayer] = c.backend.NewContextSize(2).Layer(c.curLayer)
- }
-
- if _, ok := c.keys[c.curLayer]; !ok {
- c.keys[c.curLayer] = c.ctxs[c.curLayer].Empty(key.DType(), key.Shape()...)
- }
-
- if _, ok := c.values[c.curLayer]; !ok {
- c.values[c.curLayer] = c.ctxs[c.curLayer].Empty(value.DType(), value.Shape()...)
- }
-
- ctx.Forward(
- key.Copy(ctx, c.keys[c.curLayer]),
- value.Copy(ctx, c.values[c.curLayer]),
- )
-}
-
-func (c *EncoderCache) CopyPrefix(srcSeq, dstSeq int, len int32) {
- panic("encoder cache does not support multiple sequences")
-}
-
-func (c *EncoderCache) CanResume(seq int, pos int32) bool {
- return true
-}
-
-func (c *EncoderCache) Remove(seq int, beginIndex, endIndex int32) error {
- if c.encoderPos >= beginIndex && c.encoderPos < endIndex {
- c.encoderCached = false
- }
-
- return nil
-}
diff --git a/kvcache/recurrent.go b/kvcache/recurrent.go
deleted file mode 100644
index be2e7469f..000000000
--- a/kvcache/recurrent.go
+++ /dev/null
@@ -1,752 +0,0 @@
-package kvcache
-
-import (
- "errors"
- "fmt"
- "math"
- "slices"
-
- "github.com/ollama/ollama/ml"
- "github.com/ollama/ollama/model/input"
-)
-
-const (
- DefaultCheckpointCount = 24
- DefaultCheckpointMinPos = int32(16)
- DefaultCheckpointInterval = int32(1664)
-)
-
-var ErrInvalidRecurrentShape = errors.New("kvcache: invalid recurrent state shape")
-
-// Config configures a shared hybrid recurrent cache.
-type RecurrentConfig struct {
- Shift func(ctx ml.Context, layer int, key, shift ml.Tensor) (ml.Tensor, error)
- ConvDim int
- ConvChannels int
- RecurrentStateSize int
- CheckpointLogPrefix string
-}
-
-var (
- _ Cache = (*Recurrent)(nil)
- _ CheckpointCache = (*Recurrent)(nil)
-)
-
-// Cache stores:
-// - a standard causal KV cache
-// - per-sequence conv state for recurrent operators
-// - per-sequence recurrent state for recurrent operators
-//
-// Conv state shape (per layer, per sequence): [convDim, convChannels]
-// Recurrent state shape (per layer, per sequence): [recurrentStateSize]
-type Recurrent struct {
- kv *Causal
-
- backend ml.Backend
- dtype ml.DType
- maxSequences int
-
- // Conv state dimensions
- convDim int
- convChannels int
-
- // Recurrent state dimensions
- recurrentStateSize int
-
- logPrefix string
-
- // slot mapping for recurrent state (copy-on-write)
- slotForSeq map[int]int
- refCount []int
- freeSlots []int
- seqCounts map[int]int
- slotScratch [1]int32
-
- // per-layer conv state buffers (allocated lazily)
- convCtxs map[int]ml.Context
- convStates map[int]ml.Tensor // [convDim*convChannels, maxSlots]
-
- // per-layer recurrent state buffers (allocated lazily)
- recurrentCtxs map[int]ml.Context
- recurrentStates map[int]ml.Tensor // [recurrentStateSize, maxSlots]
-
- // recurrent checkpoints (per slot)
- checkpointCount int
- checkpointMinPos int32
- checkpointInterval int32
- checkpointCtxSize int
- checkpoints map[int]*slotCheckpointStore
- pendingRestore map[int]checkpointRestore
- curCheckpointPos []int32
- curCheckpointSlots map[int]int
- reserveCheckpoints bool
- checkpointConvCtxs map[int]ml.Context
- checkpointRecurCtxs map[int]ml.Context
- checkpointReserved map[int]struct{}
-
- // current forward batch (derived in StartForward)
- curSeqs []int
- curSlots []int
- curSlotsInput ml.Tensor
- curSeqTokens int
-
- // track if EnsureWritable has been called for this forward pass
- writableEnsured bool
- writableError error
-}
-
-func NewRecurrentCache(config RecurrentConfig) *Recurrent {
- return &Recurrent{
- kv: NewCausalCache(config.Shift),
- convDim: config.ConvDim,
- convChannels: config.ConvChannels,
- recurrentStateSize: config.RecurrentStateSize,
- logPrefix: config.CheckpointLogPrefix,
- slotForSeq: make(map[int]int),
- seqCounts: make(map[int]int),
- convCtxs: make(map[int]ml.Context),
- convStates: make(map[int]ml.Tensor),
- recurrentCtxs: make(map[int]ml.Context),
- recurrentStates: make(map[int]ml.Tensor),
- checkpointCount: DefaultCheckpointCount,
- checkpointMinPos: DefaultCheckpointMinPos,
- checkpointInterval: DefaultCheckpointInterval,
- checkpoints: make(map[int]*slotCheckpointStore),
- pendingRestore: make(map[int]checkpointRestore),
- curCheckpointSlots: make(map[int]int),
- checkpointConvCtxs: make(map[int]ml.Context),
- checkpointRecurCtxs: make(map[int]ml.Context),
- checkpointReserved: make(map[int]struct{}),
- }
-}
-
-func (c *Recurrent) Init(backend ml.Backend, dtype ml.DType, maxSequences, capacity, maxBatch int) {
- c.backend = backend
- c.dtype = dtype
- c.maxSequences = maxSequences
- c.checkpoints = make(map[int]*slotCheckpointStore)
- c.pendingRestore = make(map[int]checkpointRestore)
- c.curCheckpointPos = c.curCheckpointPos[:0]
- c.curCheckpointSlots = make(map[int]int)
- c.checkpointReserved = make(map[int]struct{})
- c.checkpointCtxSize = c.checkpointCount * c.maxSequences
- if c.checkpointCtxSize < 8 {
- c.checkpointCtxSize = 8
- }
-
- // initialize slot allocator
- c.refCount = make([]int, maxSequences)
- c.freeSlots = c.freeSlots[:0]
- for i := maxSequences - 1; i >= 0; i-- {
- c.freeSlots = append(c.freeSlots, i)
- }
-
- c.kv.Init(backend, dtype, maxSequences, capacity, maxBatch)
-}
-
-func (c *Recurrent) Close() {
- for _, ctx := range c.convCtxs {
- ctx.Close()
- }
- for _, ctx := range c.recurrentCtxs {
- ctx.Close()
- }
- for _, ctx := range c.checkpointConvCtxs {
- ctx.Close()
- }
- for _, ctx := range c.checkpointRecurCtxs {
- ctx.Close()
- }
- c.kv.Close()
-}
-
-func (c *Recurrent) SetConfig(config ml.CacheConfig) {
- c.kv.SetConfig(config)
-}
-
-func (c *Recurrent) SetLayer(layer int) {
- c.kv.SetLayer(layer)
-}
-
-func (c *Recurrent) Get(ctx ml.Context) (ml.Tensor, ml.Tensor, ml.Tensor) {
- return c.kv.Get(ctx)
-}
-
-func (c *Recurrent) Put(ctx ml.Context, key, value ml.Tensor) {
- c.kv.Put(ctx, key, value)
-}
-
-func (c *Recurrent) StartForward(ctx ml.Context, batch input.Batch, reserve bool) error {
- if err := c.kv.StartForward(ctx, batch, reserve); err != nil {
- return err
- }
-
- nTokens := len(batch.Sequences)
- if nTokens == 0 {
- c.curSeqs = c.curSeqs[:0]
- c.curSlots = c.curSlots[:0]
- c.curSlotsInput = nil
- c.curSeqTokens = 0
- c.reserveCheckpoints = false
- c.writableEnsured = false
- c.writableError = nil
- return nil
- }
-
- // Fast path for single-sequence batches (common during decode and prefill).
- firstSeq := batch.Sequences[0]
- singleSeq := true
- for _, s := range batch.Sequences[1:] {
- if s != firstSeq {
- singleSeq = false
- break
- }
- }
- if singleSeq {
- return c.startForwardSingleSeq(ctx, firstSeq, nTokens, batch, reserve)
- }
-
- // Derive equal-length sequence layout for recurrent layers.
- seqCounts := c.seqCounts
- for s := range seqCounts {
- delete(seqCounts, s)
- }
-
- c.curSeqs = c.curSeqs[:0]
- for _, s := range batch.Sequences {
- if seqCounts[s] == 0 {
- c.curSeqs = append(c.curSeqs, s)
- }
- seqCounts[s]++
- }
-
- nSeqs := len(c.curSeqs)
- want := nTokens / nSeqs
- for _, s := range c.curSeqs {
- if seqCounts[s] != want {
- return ErrNotSupported
- }
- }
-
- c.curSeqTokens = want
-
- if reserve {
- c.curSlots = c.curSlots[:0]
- for i := range nSeqs {
- c.curSlots = append(c.curSlots, i)
- }
- c.finalizeStartForward(ctx, batch, true)
- return nil
- }
-
- // Ensure slots exist for sequences in this batch.
- c.curSlots = c.curSlots[:0]
- var newSlots []int
- for _, s := range c.curSeqs {
- slot, ok := c.slotForSeq[s]
- if !ok {
- var err error
- slot, err = c.allocSlot()
- if err != nil {
- return err
- }
- c.slotForSeq[s] = slot
- c.refCount[slot] = 1
- newSlots = append(newSlots, slot)
- }
- c.curSlots = append(c.curSlots, slot)
- }
-
- if len(newSlots) > 0 {
- c.zeroSlots(ctx, newSlots)
- }
-
- c.finalizeStartForward(ctx, batch, false)
-
- return nil
-}
-
-func (c *Recurrent) startForwardSingleSeq(ctx ml.Context, seq, seqTokens int, batch input.Batch, reserve bool) error {
- c.curSeqs = append(c.curSeqs[:0], seq)
- c.curSeqTokens = seqTokens
-
- if reserve {
- c.curSlots = append(c.curSlots[:0], 0)
- c.finalizeStartForward(ctx, batch, true)
- return nil
- }
-
- slot, ok := c.slotForSeq[seq]
- if !ok {
- var err error
- slot, err = c.allocSlot()
- if err != nil {
- return err
- }
-
- c.slotForSeq[seq] = slot
- c.refCount[slot] = 1
- slotList := [1]int{slot}
- c.zeroSlots(ctx, slotList[:])
- }
-
- c.curSlots = append(c.curSlots[:0], slot)
- c.finalizeStartForward(ctx, batch, false)
-
- return nil
-}
-
-func (c *Recurrent) finalizeStartForward(ctx ml.Context, batch input.Batch, reserve bool) {
- c.setCurSlotsInput(ctx)
- c.writableEnsured = false
- c.writableError = nil
- c.reserveCheckpoints = reserve
- c.planCheckpoints(batch)
-}
-
-func (c *Recurrent) setCurSlotsInput(ctx ml.Context) {
- c.curSlotsInput = c.slotsInput(ctx, c.curSlots)
-}
-
-func (c *Recurrent) slotsInput(ctx ml.Context, slots []int) ml.Tensor {
- switch len(slots) {
- case 0:
- return nil
- case 1:
- c.slotScratch[0] = int32(slots[0])
- return ctx.Input().FromInts(c.slotScratch[:], 1)
- default:
- slotIndices := make([]int32, len(slots))
- for i, v := range slots {
- slotIndices[i] = int32(v)
- }
- return ctx.Input().FromInts(slotIndices, len(slotIndices))
- }
-}
-
-func (c *Recurrent) allocSlot() (int, error) {
- if len(c.freeSlots) == 0 {
- return 0, ErrKvCacheFull
- }
- slot := c.freeSlots[len(c.freeSlots)-1]
- c.freeSlots = c.freeSlots[:len(c.freeSlots)-1]
- return slot, nil
-}
-
-func (c *Recurrent) freeSlot(slot int) {
- if slot >= 0 && slot < c.maxSequences {
- c.freeSlots = append(c.freeSlots, slot)
- }
-}
-
-// zeroSlots zeros recurrent state for the given slots across all cached layers.
-func (c *Recurrent) zeroSlots(ctx ml.Context, slots []int) {
- if len(slots) == 0 {
- return
- }
-
- inputCtx := ctx.Input()
- slotsTensor := c.slotsInput(ctx, slots)
-
- if len(c.convStates) > 0 {
- zeros := inputCtx.Zeros(ml.DTypeF32, c.convDim*c.convChannels, len(slots))
- for _, buf := range c.convStates {
- ctx.Forward(buf.SetRows(ctx, zeros, slotsTensor))
- }
- }
-
- if len(c.recurrentStates) > 0 {
- zeros := inputCtx.Zeros(ml.DTypeF32, c.recurrentStateSize, len(slots))
- for _, buf := range c.recurrentStates {
- ctx.Forward(buf.SetRows(ctx, zeros, slotsTensor))
- }
- }
-}
-
-// EnsureWritable ensures sequences have private slots (copy-on-write).
-func (c *Recurrent) EnsureWritable(ctx ml.Context) error {
- for i, seq := range c.curSeqs {
- slot, ok := c.slotForSeq[seq]
- if !ok {
- continue
- }
-
- if slot < 0 || slot >= len(c.refCount) {
- continue
- }
-
- if c.refCount[slot] <= 1 {
- continue
- }
-
- newSlot, err := c.allocSlot()
- if err != nil {
- return err
- }
- c.refCount[slot]--
- c.refCount[newSlot] = 1
- c.slotForSeq[seq] = newSlot
- c.curSlots[i] = newSlot
-
- c.copyRecurrentState(ctx, slot, newSlot)
- c.copyCheckpoints(ctx, slot, newSlot)
- }
-
- c.setCurSlotsInput(ctx)
-
- return nil
-}
-
-func (c *Recurrent) copyRecurrentState(ctx ml.Context, srcSlot, dstSlot int) {
- src := ctx.Input().FromInts([]int32{int32(srcSlot)}, 1)
- dst := ctx.Input().FromInts([]int32{int32(dstSlot)}, 1)
-
- for _, buf := range c.convStates {
- rows := buf.Rows(ctx, src)
- if rows.DType() != ml.DTypeF32 {
- rows = rows.Cast(ctx, ml.DTypeF32)
- }
- ctx.Forward(buf.SetRows(ctx, rows, dst))
- }
-
- for _, buf := range c.recurrentStates {
- rows := buf.Rows(ctx, src)
- if rows.DType() != ml.DTypeF32 {
- rows = rows.Cast(ctx, ml.DTypeF32)
- }
- ctx.Forward(buf.SetRows(ctx, rows, dst))
- }
-}
-
-func (c *Recurrent) CopyPrefix(srcSeq, dstSeq int, prefixLen int32) {
- c.kv.CopyPrefix(srcSeq, dstSeq, prefixLen)
-
- if dstSlot, ok := c.slotForSeq[dstSeq]; ok {
- if c.validSlot(dstSlot) {
- c.refCount[dstSlot]--
- if c.refCount[dstSlot] <= 0 {
- c.refCount[dstSlot] = 0
- c.freeSlot(dstSlot)
- }
- }
- delete(c.slotForSeq, dstSeq)
- }
-
- srcSlot, ok := c.slotForSeq[srcSeq]
- if !ok {
- return
- }
-
- if c.validSlot(srcSlot) {
- c.slotForSeq[dstSeq] = srcSlot
- c.refCount[srcSlot]++
- }
-}
-
-func (c *Recurrent) CanResume(seq int, pos int32) bool {
- if !c.kv.CanResume(seq, pos) {
- return false
- }
- if pos == 0 {
- return true
- }
- return c.hasCheckpoint(seq, pos)
-}
-
-func (c *Recurrent) Remove(seq int, beginIndex, endIndex int32) error {
- if beginIndex > 0 && endIndex != math.MaxInt32 {
- if err := c.kv.Remove(seq, beginIndex, endIndex); err != nil {
- return err
- }
- delete(c.pendingRestore, seq)
-
- slot, ok := c.slotForSeq[seq]
- if !ok || !c.validSlot(slot) {
- return nil
- }
-
- // Detach shared recurrent state/checkpoints before mutating checkpoint positions.
- if c.refCount[slot] > 1 {
- newSlot, err := c.allocSlot()
- if err != nil {
- return err
- }
- ctx := c.backend.NewContext()
- c.copyRecurrentState(ctx, slot, newSlot)
- c.copyCheckpoints(ctx, slot, newSlot)
- if len(c.convStates) > 0 || len(c.recurrentStates) > 0 {
- ctx.Compute()
- }
- ctx.Close()
-
- c.refCount[slot]--
- c.refCount[newSlot] = 1
- c.slotForSeq[seq] = newSlot
- slot = newSlot
- }
-
- c.shiftCheckpoints(slot, beginIndex, endIndex)
- return nil
- }
-
- if beginIndex > 0 {
- restore, ok := c.pendingRestore[seq]
- if !ok || restore.pos+1 != beginIndex {
- return ErrNotSupported
- }
- if !c.restoreComplete(restore) {
- return ErrNotSupported
- }
- if slot, ok := c.slotForSeq[seq]; ok && c.validSlot(slot) && c.refCount[slot] > 1 {
- newSlot, err := c.allocSlot()
- if err != nil {
- return err
- }
- ctx := c.backend.NewContext()
- c.copyRecurrentState(ctx, slot, newSlot)
- c.copyCheckpoints(ctx, slot, newSlot)
- if len(c.convStates) > 0 || len(c.recurrentStates) > 0 {
- ctx.Compute()
- }
- ctx.Close()
-
- c.refCount[slot]--
- c.refCount[newSlot] = 1
- c.slotForSeq[seq] = newSlot
-
- restore.slot = newSlot
- c.pendingRestore[seq] = restore
- }
- }
-
- if err := c.kv.Remove(seq, beginIndex, endIndex); err != nil {
- return err
- }
-
- if beginIndex > 0 {
- restore := c.pendingRestore[seq]
- delete(c.pendingRestore, seq)
- return c.applyCheckpointRestore(restore)
- }
-
- slot, ok := c.slotForSeq[seq]
- delete(c.pendingRestore, seq)
- if !ok {
- return nil
- }
-
- if !c.validSlot(slot) {
- delete(c.slotForSeq, seq)
- return nil
- }
-
- c.refCount[slot]--
- if c.refCount[slot] <= 0 {
- c.refCount[slot] = 0
- c.clearCheckpoints(slot)
- c.freeSlot(slot)
- }
- delete(c.slotForSeq, seq)
-
- return nil
-}
-
-func (c *Recurrent) validSlot(slot int) bool {
- return slot >= 0 && slot < len(c.refCount)
-}
-
-func (c *Recurrent) SlotsTensor() ml.Tensor {
- return c.curSlotsInput
-}
-
-// contiguousSlots returns the starting slot if current slots are contiguous and ordered.
-func (c *Recurrent) contiguousSlots() (int, bool) {
- if len(c.curSlots) == 0 {
- return 0, false
- }
- start := c.curSlots[0]
- for i, s := range c.curSlots {
- if s != start+i {
- return 0, false
- }
- }
- return start, true
-}
-
-func (c *Recurrent) SeqTokens() int {
- return c.curSeqTokens
-}
-
-func (c *Recurrent) NumSeqs() int {
- return len(c.curSeqs)
-}
-
-func (c *Recurrent) convBuffer(layer int) ml.Tensor {
- if buf, ok := c.convStates[layer]; ok {
- return buf
- }
-
- if _, ok := c.convCtxs[layer]; !ok {
- c.convCtxs[layer] = c.backend.NewContextSize(1).Layer(layer)
- }
-
- buf := c.convCtxs[layer].Zeros(ml.DTypeF32, c.convDim*c.convChannels, c.maxSequences)
- c.convStates[layer] = buf
- return buf
-}
-
-func (c *Recurrent) recurrentBuffer(layer int) ml.Tensor {
- if buf, ok := c.recurrentStates[layer]; ok {
- return buf
- }
-
- if _, ok := c.recurrentCtxs[layer]; !ok {
- c.recurrentCtxs[layer] = c.backend.NewContextSize(1).Layer(layer)
- }
-
- buf := c.recurrentCtxs[layer].Zeros(ml.DTypeF32, c.recurrentStateSize, c.maxSequences)
- c.recurrentStates[layer] = buf
- return buf
-}
-
-func (c *Recurrent) ensureWritable(ctx ml.Context) error {
- c.ensureWritableOnce(ctx)
- return c.writableError
-}
-
-func (c *Recurrent) currentSlotRows(ctx ml.Context, buf ml.Tensor, rowSize int) ml.Tensor {
- if start, ok := c.contiguousSlots(); ok {
- offset := start * buf.Stride(1)
- return buf.View(ctx, offset, rowSize, buf.Stride(1), c.NumSeqs())
- }
-
- return buf.Rows(ctx, c.SlotsTensor())
-}
-
-func (c *Recurrent) writeCurrentSlotRows(ctx ml.Context, buf ml.Tensor, rowSize int, src ml.Tensor) {
- if start, ok := c.contiguousSlots(); ok {
- offset := start * buf.Stride(1)
- view := buf.View(ctx, offset, rowSize, buf.Stride(1), c.NumSeqs())
- ctx.Forward(src.Copy(ctx, view))
- return
- }
-
- ctx.Forward(buf.SetRows(ctx, src, c.SlotsTensor()))
-}
-
-func (c *Recurrent) ensureWritableOnce(ctx ml.Context) {
- if !c.writableEnsured {
- needsWritable := false
- for _, seq := range c.curSeqs {
- slot, ok := c.slotForSeq[seq]
- if !ok {
- continue
- }
- if slot >= 0 && slot < len(c.refCount) && c.refCount[slot] > 1 {
- needsWritable = true
- break
- }
- }
-
- if needsWritable {
- if err := c.EnsureWritable(ctx); err != nil {
- c.writableError = err
- }
- }
- c.writableEnsured = true
- }
-}
-
-// ConvState returns conv state for current batch sequences as [convDim, convChannels, nSeqs].
-func (c *Recurrent) ConvState(ctx ml.Context, layer int) (ml.Tensor, error) {
- if err := c.ensureWritable(ctx); err != nil {
- return nil, err
- }
-
- buf := c.convBuffer(layer)
- cur := c.currentSlotRows(ctx, buf, c.convDim*c.convChannels)
- return cur.Reshape(ctx, c.convDim, c.convChannels, c.NumSeqs()), nil
-}
-
-// UpdateConvState writes new conv state for current batch sequences.
-func (c *Recurrent) UpdateConvState(ctx ml.Context, layer int, newState ml.Tensor) {
- buf := c.convBuffer(layer)
- src := newState.Reshape(ctx, c.convDim*c.convChannels, c.NumSeqs())
- srcF32 := src
- if src.DType() != ml.DTypeF32 {
- srcF32 = src.Cast(ctx, ml.DTypeF32)
- }
- c.writeCurrentSlotRows(ctx, buf, c.convDim*c.convChannels, srcF32)
-
- c.captureConvCheckpoint(ctx, layer, srcF32)
-}
-
-// RecurrentState returns recurrent state for current batch sequences with shape [dims..., nSeqs].
-func (c *Recurrent) RecurrentState(ctx ml.Context, layer int, dims ...int) (ml.Tensor, error) {
- if err := c.ensureWritable(ctx); err != nil {
- return nil, err
- }
- if len(dims) == 0 {
- return nil, ErrInvalidRecurrentShape
- }
-
- size := 1
- for _, d := range dims {
- if d <= 0 {
- return nil, ErrInvalidRecurrentShape
- }
- size *= d
- }
- if size != c.recurrentStateSize {
- return nil, fmt.Errorf("%w: got %v (size %d), want size %d", ErrInvalidRecurrentShape, dims, size, c.recurrentStateSize)
- }
-
- buf := c.recurrentBuffer(layer)
- cur := c.currentSlotRows(ctx, buf, c.recurrentStateSize)
- shape := make([]int, 0, len(dims)+1)
- shape = append(shape, dims...)
- shape = append(shape, c.NumSeqs())
- return cur.Reshape(ctx, shape...), nil
-}
-
-// RecurrentState4D returns recurrent state as [dim0, dim1, dim2, nSeqs].
-func (c *Recurrent) RecurrentState4D(ctx ml.Context, layer int, dim0, dim1, dim2 int) (ml.Tensor, error) {
- if err := c.ensureWritable(ctx); err != nil {
- return nil, err
- }
- if dim0 <= 0 || dim1 <= 0 || dim2 <= 0 {
- return nil, ErrInvalidRecurrentShape
- }
-
- size := dim0 * dim1 * dim2
- if size != c.recurrentStateSize {
- return nil, fmt.Errorf("%w: got [%d %d %d] (size %d), want size %d", ErrInvalidRecurrentShape, dim0, dim1, dim2, size, c.recurrentStateSize)
- }
-
- buf := c.recurrentBuffer(layer)
- cur := c.currentSlotRows(ctx, buf, c.recurrentStateSize)
- return cur.Reshape(ctx, dim0, dim1, dim2, c.NumSeqs()), nil
-}
-
-// UpdateRecurrentState writes new recurrent state for current batch sequences.
-func (c *Recurrent) UpdateRecurrentState(ctx ml.Context, layer int, newState ml.Tensor) {
- buf := c.recurrentBuffer(layer)
- src := newState.Reshape(ctx, c.recurrentStateSize, c.NumSeqs())
- srcF32 := src
- if src.DType() != ml.DTypeF32 {
- srcF32 = src.Cast(ctx, ml.DTypeF32)
- }
- c.writeCurrentSlotRows(ctx, buf, c.recurrentStateSize, srcF32)
-
- c.captureRecurrentCheckpoint(ctx, layer, srcF32)
-}
-
-// IsSupportedForBatch returns true if the current batch layout supports recurrent layers.
-func (c *Recurrent) IsSupportedForBatch() bool {
- return c.curSeqTokens > 0 && len(c.curSeqs) > 0
-}
-
-// Seqs returns the ordered unique sequences for the current forward pass.
-func (c *Recurrent) Seqs() []int {
- return slices.Clone(c.curSeqs)
-}
diff --git a/kvcache/recurrent_checkpoints.go b/kvcache/recurrent_checkpoints.go
deleted file mode 100644
index 1e029a5b3..000000000
--- a/kvcache/recurrent_checkpoints.go
+++ /dev/null
@@ -1,561 +0,0 @@
-package kvcache
-
-import (
- "log/slog"
- "math"
-
- "github.com/ollama/ollama/ml"
- "github.com/ollama/ollama/model/input"
-)
-
-// TODO(jmorganca): Add byte-serialized host-RAM checkpoints to reduce GPU
-// memory usage while preserving prefix reuse for recurrent state.
-
-type checkpointEntry struct {
- pos int32
- conv map[int]ml.Tensor
- recurrent map[int]ml.Tensor
-}
-
-type slotCheckpointStore struct {
- entries []checkpointEntry
- size int
- next int
- lastPos int32
-}
-
-type checkpointRestore struct {
- slot int
- idx int
- pos int32
-}
-
-func newSlotCheckpointStore(n int) *slotCheckpointStore {
- entries := make([]checkpointEntry, n)
- for i := range entries {
- entries[i].pos = -1
- }
- return &slotCheckpointStore{
- entries: entries,
- lastPos: -1,
- }
-}
-
-func (s *slotCheckpointStore) reset() {
- s.size = 0
- s.next = 0
- s.lastPos = -1
- for i := range s.entries {
- s.entries[i].pos = -1
- }
-}
-
-func (s *slotCheckpointStore) record(pos int32) int {
- if len(s.entries) == 0 {
- return -1
- }
- idx := s.next
- s.next = (s.next + 1) % len(s.entries)
- if s.size < len(s.entries) {
- s.size++
- }
- s.entries[idx].pos = pos
- s.lastPos = pos
- return idx
-}
-
-func (s *slotCheckpointStore) bestIndex(targetPos int32) (int, int32, bool) {
- bestIdx := -1
- bestPos := int32(-1)
- for i := range s.entries {
- pos := s.entries[i].pos
- if pos < 0 || pos >= targetPos {
- continue
- }
- if pos > bestPos {
- bestPos = pos
- bestIdx = i
- }
- }
- if bestIdx < 0 {
- return -1, -1, false
- }
- return bestIdx, bestPos, true
-}
-
-func (s *slotCheckpointStore) pruneAfter(pos int32) {
- if len(s.entries) == 0 {
- s.size = 0
- s.next = 0
- s.lastPos = -1
- return
- }
-
- size := 0
- next := -1
- minPos := int32(math.MaxInt32)
- minIdx := 0
- for i := range s.entries {
- if s.entries[i].pos > pos {
- s.entries[i].pos = -1
- }
- if s.entries[i].pos >= 0 {
- size++
- if s.entries[i].pos < minPos {
- minPos = s.entries[i].pos
- minIdx = i
- }
- } else if next == -1 {
- next = i
- }
- }
-
- s.size = size
- if size == 0 {
- s.next = 0
- s.lastPos = -1
- return
- }
- if next != -1 {
- s.next = next
- } else {
- // Full ring: overwrite the oldest checkpoint next.
- s.next = minIdx
- }
- s.lastPos = pos
-}
-
-func (s *slotCheckpointStore) shiftRange(beginIndex, endIndex int32) {
- if len(s.entries) == 0 {
- s.size = 0
- s.next = 0
- s.lastPos = -1
- return
- }
-
- offset := beginIndex - endIndex
-
- size := 0
- next := -1
- minPos := int32(math.MaxInt32)
- maxPos := int32(-1)
- minIdx := 0
-
- for i := range s.entries {
- pos := s.entries[i].pos
- if pos >= 0 {
- if pos >= beginIndex && pos < endIndex {
- s.entries[i].pos = -1
- } else if pos >= endIndex {
- s.entries[i].pos = pos + offset
- }
- }
-
- pos = s.entries[i].pos
- if pos >= 0 {
- size++
- if pos < minPos {
- minPos = pos
- minIdx = i
- }
- if pos > maxPos {
- maxPos = pos
- }
- } else if next == -1 {
- next = i
- }
- }
-
- s.size = size
- if size == 0 {
- s.next = 0
- s.lastPos = -1
- return
- }
-
- if next != -1 {
- s.next = next
- } else {
- // Full ring: overwrite the oldest checkpoint next.
- s.next = minIdx
- }
- s.lastPos = maxPos
-}
-
-func (s *slotCheckpointStore) window() (size int, minPos, maxPos, lastPos int32) {
- minPos = int32(math.MaxInt32)
- maxPos = int32(-1)
- for i := range s.entries {
- pos := s.entries[i].pos
- if pos < 0 {
- continue
- }
- size++
- if pos < minPos {
- minPos = pos
- }
- if pos > maxPos {
- maxPos = pos
- }
- }
- if size == 0 {
- minPos = -1
- maxPos = -1
- }
- return size, minPos, maxPos, s.lastPos
-}
-
-func (c *Recurrent) checkpointTag() string {
- if c.logPrefix == "" {
- return "kvcache.recurrent"
- }
- return c.logPrefix
-}
-
-func (c *Recurrent) planCheckpoints(batch input.Batch) {
- if c.checkpointCount == 0 || len(c.curSeqs) == 0 {
- c.curCheckpointPos = c.curCheckpointPos[:0]
- for k := range c.curCheckpointSlots {
- delete(c.curCheckpointSlots, k)
- }
- return
- }
-
- if cap(c.curCheckpointPos) < len(c.curSeqs) {
- c.curCheckpointPos = make([]int32, len(c.curSeqs))
- } else {
- c.curCheckpointPos = c.curCheckpointPos[:len(c.curSeqs)]
- }
- for i := range c.curCheckpointPos {
- c.curCheckpointPos[i] = -1
- }
- for k := range c.curCheckpointSlots {
- delete(c.curCheckpointSlots, k)
- }
-
- posMax := make(map[int]int32, len(c.curSeqs))
- for i, seq := range batch.Sequences {
- pos := batch.Positions[i]
- if cur, ok := posMax[seq]; !ok || pos > cur {
- posMax[seq] = pos
- }
- }
-
- for i, seq := range c.curSeqs {
- pos, ok := posMax[seq]
- if !ok {
- continue
- }
- if pos < c.checkpointMinPos {
- continue
- }
- slot := c.curSlots[i]
- store := c.checkpointStore(slot)
- lastPos := store.lastPos
- if lastPos < 0 || pos-lastPos >= c.checkpointInterval {
- c.curCheckpointPos[i] = pos
- }
- }
-}
-
-func (c *Recurrent) checkpointStore(slot int) *slotCheckpointStore {
- store, ok := c.checkpoints[slot]
- if ok {
- return store
- }
- store = newSlotCheckpointStore(c.checkpointCount)
- c.checkpoints[slot] = store
- return store
-}
-
-func (c *Recurrent) checkpointIndexForSlot(slot int, pos int32) int {
- if c.checkpointCount == 0 {
- return -1
- }
- if idx, ok := c.curCheckpointSlots[slot]; ok {
- return idx
- }
- store := c.checkpointStore(slot)
- idx := store.record(pos)
- if idx >= 0 {
- c.curCheckpointSlots[slot] = idx
- }
- return idx
-}
-
-func (c *Recurrent) hasCheckpoint(seq int, pos int32) bool {
- if pos <= 0 {
- return false
- }
- slot, ok := c.slotForSeq[seq]
- if !ok {
- return false
- }
- store, ok := c.checkpoints[slot]
- if !ok {
- return false
- }
- _, _, ok = store.bestIndex(pos)
- return ok
-}
-
-func (c *Recurrent) PrepareRestore(seq int, targetPos int32) (int32, bool) {
- if targetPos <= 0 {
- return 0, false
- }
- slot, ok := c.slotForSeq[seq]
- if !ok {
- return 0, false
- }
- store, ok := c.checkpoints[slot]
- if !ok {
- slog.Debug(c.checkpointTag()+": checkpoint miss", "seq", seq, "slot", slot, "target", targetPos, "size", 0)
- return 0, false
- }
- idx, pos, ok := store.bestIndex(targetPos)
- if !ok {
- size, minPos, maxPos, lastPos := store.window()
- slog.Debug(c.checkpointTag()+": checkpoint miss", "seq", seq, "slot", slot, "target", targetPos, "size", size,
- "min", minPos, "max", maxPos, "last", lastPos)
- return 0, false
- }
- c.pendingRestore[seq] = checkpointRestore{
- slot: slot,
- idx: idx,
- pos: pos,
- }
- return pos + 1, true
-}
-
-func (c *Recurrent) applyCheckpointRestore(restore checkpointRestore) error {
- entry, ok := c.restoreEntry(restore)
- if !ok {
- return ErrNotSupported
- }
-
- ctx := c.backend.NewContext()
- defer ctx.Close()
-
- slotIdx := ctx.Input().FromInts([]int32{int32(restore.slot)}, 1)
- for layer, src := range entry.conv {
- buf := c.convBuffer(layer)
- ctx.Forward(buf.SetRows(ctx, src, slotIdx))
- }
- for layer, src := range entry.recurrent {
- buf := c.recurrentBuffer(layer)
- ctx.Forward(buf.SetRows(ctx, src, slotIdx))
- }
-
- if len(entry.conv) > 0 || len(entry.recurrent) > 0 {
- ctx.Compute()
- }
- store := c.checkpoints[restore.slot]
- store.pruneAfter(restore.pos)
- return nil
-}
-
-func (c *Recurrent) restoreComplete(restore checkpointRestore) bool {
- _, ok := c.restoreEntry(restore)
- return ok
-}
-
-func (c *Recurrent) restoreEntry(restore checkpointRestore) (*checkpointEntry, bool) {
- store, ok := c.checkpoints[restore.slot]
- if !ok || restore.idx < 0 || restore.idx >= len(store.entries) {
- return nil, false
- }
- entry := &store.entries[restore.idx]
- if entry.pos < 0 {
- return nil, false
- }
- if !c.entryComplete(entry) {
- return nil, false
- }
- return entry, true
-}
-
-func (c *Recurrent) entryComplete(entry *checkpointEntry) bool {
- for layer := range c.convStates {
- if entry.conv == nil || entry.conv[layer] == nil {
- return false
- }
- }
- for layer := range c.recurrentStates {
- if entry.recurrent == nil || entry.recurrent[layer] == nil {
- return false
- }
- }
- return true
-}
-
-func (c *Recurrent) clearCheckpoints(slot int) {
- if store, ok := c.checkpoints[slot]; ok {
- store.reset()
- }
-}
-
-func (c *Recurrent) shiftCheckpoints(slot int, beginIndex, endIndex int32) {
- if store, ok := c.checkpoints[slot]; ok {
- store.shiftRange(beginIndex, endIndex)
- }
-}
-
-func (c *Recurrent) copyCheckpoints(ctx ml.Context, srcSlot, dstSlot int) {
- if c.checkpointCount == 0 {
- return
- }
- srcStore, ok := c.checkpoints[srcSlot]
- if !ok || srcStore.size == 0 {
- return
- }
- dstStore := c.checkpointStore(dstSlot)
- dstStore.size = srcStore.size
- dstStore.next = srcStore.next
- dstStore.lastPos = srcStore.lastPos
-
- for i := range srcStore.entries {
- srcEntry := &srcStore.entries[i]
- dstEntry := &dstStore.entries[i]
- dstEntry.pos = srcEntry.pos
- if srcEntry.conv != nil {
- if dstEntry.conv == nil {
- dstEntry.conv = make(map[int]ml.Tensor)
- }
- for layer, src := range srcEntry.conv {
- dst := c.ensureCheckpointConv(layer, dstEntry)
- ctx.Forward(src.Copy(ctx, dst))
- }
- }
- if srcEntry.recurrent != nil {
- if dstEntry.recurrent == nil {
- dstEntry.recurrent = make(map[int]ml.Tensor)
- }
- for layer, src := range srcEntry.recurrent {
- dst := c.ensureCheckpointRecurrent(layer, dstEntry)
- ctx.Forward(src.Copy(ctx, dst))
- }
- }
- }
-}
-
-func (c *Recurrent) captureConvCheckpoint(ctx ml.Context, layer int, src ml.Tensor) {
- if c.checkpointCount == 0 {
- return
- }
- if c.reserveCheckpoints {
- c.reserveCheckpointConv(layer)
- return
- }
- if len(c.curCheckpointPos) == 0 {
- return
- }
- for i, pos := range c.curCheckpointPos {
- if pos < 0 {
- continue
- }
- slot := c.curSlots[i]
- idx := c.checkpointIndexForSlot(slot, pos)
- if idx < 0 {
- continue
- }
- entry := &c.checkpoints[slot].entries[idx]
- dst := c.ensureCheckpointConv(layer, entry)
- seqSlice := src.Slice(ctx, 1, i, i+1, 1)
- ctx.Forward(seqSlice.Copy(ctx, dst))
- }
-}
-
-func (c *Recurrent) captureRecurrentCheckpoint(ctx ml.Context, layer int, src ml.Tensor) {
- if c.checkpointCount == 0 {
- return
- }
- if c.reserveCheckpoints {
- c.reserveCheckpointRecurrent(layer)
- return
- }
- if len(c.curCheckpointPos) == 0 {
- return
- }
- for i, pos := range c.curCheckpointPos {
- if pos < 0 {
- continue
- }
- slot := c.curSlots[i]
- idx := c.checkpointIndexForSlot(slot, pos)
- if idx < 0 {
- continue
- }
- entry := &c.checkpoints[slot].entries[idx]
- dst := c.ensureCheckpointRecurrent(layer, entry)
- seqSlice := src.Slice(ctx, 1, i, i+1, 1)
- ctx.Forward(seqSlice.Copy(ctx, dst))
- }
-}
-
-func (c *Recurrent) ensureCheckpointConv(layer int, entry *checkpointEntry) ml.Tensor {
- if entry.conv == nil {
- entry.conv = make(map[int]ml.Tensor)
- }
- if t, ok := entry.conv[layer]; ok {
- return t
- }
- ctx, ok := c.checkpointConvCtxs[layer]
- if !ok {
- ctx = c.backend.NewContextSize(c.checkpointCtxSize).Layer(layer)
- c.checkpointConvCtxs[layer] = ctx
- }
- t := ctx.Zeros(ml.DTypeF32, c.convDim*c.convChannels, 1)
- entry.conv[layer] = t
- return t
-}
-
-func (c *Recurrent) ensureCheckpointRecurrent(layer int, entry *checkpointEntry) ml.Tensor {
- if entry.recurrent == nil {
- entry.recurrent = make(map[int]ml.Tensor)
- }
- if t, ok := entry.recurrent[layer]; ok {
- return t
- }
- ctx, ok := c.checkpointRecurCtxs[layer]
- if !ok {
- ctx = c.backend.NewContextSize(c.checkpointCtxSize).Layer(layer)
- c.checkpointRecurCtxs[layer] = ctx
- }
- t := ctx.Zeros(ml.DTypeF32, c.recurrentStateSize, 1)
- entry.recurrent[layer] = t
- return t
-}
-
-func (c *Recurrent) reserveCheckpointConv(layer int) {
- key := checkpointReserveKey(layer, 0)
- if _, ok := c.checkpointReserved[key]; ok {
- return
- }
- for slot := range c.maxSequences {
- store := c.checkpointStore(slot)
- for i := range store.entries {
- entry := &store.entries[i]
- _ = c.ensureCheckpointConv(layer, entry)
- }
- }
- c.checkpointReserved[key] = struct{}{}
-}
-
-func (c *Recurrent) reserveCheckpointRecurrent(layer int) {
- key := checkpointReserveKey(layer, 1)
- if _, ok := c.checkpointReserved[key]; ok {
- return
- }
- for slot := range c.maxSequences {
- store := c.checkpointStore(slot)
- for i := range store.entries {
- entry := &store.entries[i]
- _ = c.ensureCheckpointRecurrent(layer, entry)
- }
- }
- c.checkpointReserved[key] = struct{}{}
-}
-
-func checkpointReserveKey(layer int, kind int) int {
- return layer*2 + kind
-}
diff --git a/kvcache/recurrent_checkpoints_test.go b/kvcache/recurrent_checkpoints_test.go
deleted file mode 100644
index cf7a7b99a..000000000
--- a/kvcache/recurrent_checkpoints_test.go
+++ /dev/null
@@ -1,288 +0,0 @@
-package kvcache
-
-import (
- "errors"
- "math"
- "slices"
- "testing"
-
- "github.com/ollama/ollama/ml"
-)
-
-func newTestCache() *Recurrent {
- return NewRecurrentCache(RecurrentConfig{ConvDim: 1, ConvChannels: 2, RecurrentStateSize: 2})
-}
-
-func TestSlotCheckpointStoreBestIndex(t *testing.T) {
- store := newSlotCheckpointStore(2)
- store.record(10)
- store.record(20)
-
- _, pos, ok := store.bestIndex(15)
- if !ok || pos != 10 {
- t.Fatalf("expected best pos 10, got pos=%d ok=%v", pos, ok)
- }
-
- store.record(30) // overwrite oldest (10)
-
- if _, _, ok := store.bestIndex(15); ok {
- t.Fatalf("expected no checkpoint for targetPos=15 after overwrite")
- }
-
- _, pos, ok = store.bestIndex(40)
- if !ok || pos != 30 {
- t.Fatalf("expected best pos 30, got pos=%d ok=%v", pos, ok)
- }
-}
-
-func TestCachePrepareRestore(t *testing.T) {
- cache := newTestCache()
- cache.checkpointCount = 3
- cache.checkpoints = make(map[int]*slotCheckpointStore)
- cache.pendingRestore = make(map[int]checkpointRestore)
-
- cache.slotForSeq[1] = 0
- store := cache.checkpointStore(0)
- store.record(5)
- store.record(9)
- store.record(15)
-
- restorePos, ok := cache.PrepareRestore(1, 12)
- if !ok {
- t.Fatalf("expected restore ok")
- }
- if restorePos != 10 {
- t.Fatalf("expected restorePos 10, got %d", restorePos)
- }
- rest, ok := cache.pendingRestore[1]
- if !ok {
- t.Fatalf("expected pending restore entry")
- }
- if rest.pos != 9 {
- t.Fatalf("expected pending restore pos 9, got %d", rest.pos)
- }
-}
-
-func TestSlotCheckpointStorePruneAfter(t *testing.T) {
- store := newSlotCheckpointStore(3)
- store.record(10)
- store.record(20)
- store.record(30)
-
- store.pruneAfter(20)
-
- if store.lastPos != 20 {
- t.Fatalf("expected lastPos 20, got %d", store.lastPos)
- }
-
- _, pos, ok := store.bestIndex(25)
- if !ok || pos != 20 {
- t.Fatalf("expected best pos 20 after prune, got pos=%d ok=%v", pos, ok)
- }
-
- _, pos, ok = store.bestIndex(35)
- if !ok || pos != 20 {
- t.Fatalf("expected pruned best pos 20 for targetPos=35, got pos=%d ok=%v", pos, ok)
- }
-}
-
-func TestCacheRestoreRejectsIncompleteCheckpoint(t *testing.T) {
- cache := newTestCache()
- cache.checkpointCount = 3
- cache.checkpoints = make(map[int]*slotCheckpointStore)
- cache.pendingRestore = make(map[int]checkpointRestore)
-
- cache.slotForSeq[1] = 0
- cache.refCount = []int{1}
- cache.freeSlots = nil
-
- // Simulate layer 0 requires both conv and recurrent checkpoints.
- cache.convStates[0] = nil
- cache.recurrentStates[0] = nil
-
- store := cache.checkpointStore(0)
- idx := store.record(9)
- entry := &store.entries[idx]
- entry.conv = map[int]ml.Tensor{0: nil}
- // entry.recurrent intentionally missing
-
- cache.pendingRestore[1] = checkpointRestore{slot: 0, idx: idx, pos: 9}
-
- err := cache.Remove(1, 10, math.MaxInt32)
- if !errors.Is(err, ErrNotSupported) {
- t.Fatalf("expected ErrNotSupported for incomplete checkpoint, got %v", err)
- }
-}
-
-func TestCacheRestoreAcceptsCompleteCheckpoint(t *testing.T) {
- cache := newTestCache()
- cache.checkpointCount = 3
- cache.checkpoints = make(map[int]*slotCheckpointStore)
- cache.pendingRestore = make(map[int]checkpointRestore)
-
- cache.slotForSeq[1] = 0
- cache.refCount = []int{1}
- cache.freeSlots = nil
-
- store := cache.checkpointStore(0)
- idx := store.record(9)
-
- cache.pendingRestore[1] = checkpointRestore{slot: 0, idx: idx, pos: 9}
-
- restore := cache.pendingRestore[1]
- if !cache.restoreComplete(restore) {
- t.Fatalf("expected restoreComplete to return true for complete checkpoint")
- }
-}
-
-func TestCacheRecurrentStateShapeValidation(t *testing.T) {
- cache := newTestCache()
- _, err := cache.RecurrentState(nil, 0, 3)
- if !errors.Is(err, ErrInvalidRecurrentShape) {
- t.Fatalf("expected ErrInvalidRecurrentShape, got %v", err)
- }
-}
-
-func TestSlotCheckpointStoreShiftRange(t *testing.T) {
- store := newSlotCheckpointStore(5)
- store.record(1)
- store.record(4)
- store.record(7)
- store.record(10)
-
- store.shiftRange(2, 6)
-
- var positions []int32
- for i := range store.entries {
- if store.entries[i].pos >= 0 {
- positions = append(positions, store.entries[i].pos)
- }
- }
- slices.Sort(positions)
-
- want := []int32{1, 3, 6}
- if !slices.Equal(positions, want) {
- t.Fatalf("unexpected shifted positions: got=%v want=%v", positions, want)
- }
- if store.lastPos != 6 {
- t.Fatalf("expected lastPos 6, got %d", store.lastPos)
- }
-}
-
-func TestCacheRemoveMiddleShiftsCheckpoints(t *testing.T) {
- cache := newTestCache()
- cache.slotForSeq[1] = 0
- cache.refCount = []int{1}
- cache.pendingRestore[1] = checkpointRestore{slot: 0, idx: 0, pos: 1}
-
- store := cache.checkpointStore(0)
- store.record(1)
- store.record(4)
- store.record(7)
- store.record(10)
-
- if err := cache.Remove(1, 2, 6); err != nil {
- t.Fatalf("expected middle remove to succeed, got %v", err)
- }
-
- if _, ok := cache.pendingRestore[1]; ok {
- t.Fatalf("expected pending restore to be cleared after middle remove")
- }
-
- var positions []int32
- for i := range store.entries {
- if store.entries[i].pos >= 0 {
- positions = append(positions, store.entries[i].pos)
- }
- }
- slices.Sort(positions)
-
- want := []int32{1, 3, 6}
- if !slices.Equal(positions, want) {
- t.Fatalf("unexpected checkpoint positions after remove: got=%v want=%v", positions, want)
- }
-}
-
-func TestSlotCheckpointStoreRingBufferWrapAround(t *testing.T) {
- store := newSlotCheckpointStore(3)
-
- store.record(10)
- store.record(20)
- store.record(30)
-
- store.entries[0].conv = make(map[int]ml.Tensor)
- store.entries[0].conv[0] = nil
- store.entries[0].recurrent = make(map[int]ml.Tensor)
- store.entries[0].recurrent[0] = nil
-
- store.record(40)
-
- if store.entries[0].conv == nil {
- t.Fatalf("expected conv map to be preserved on reuse")
- }
- if store.entries[0].recurrent == nil {
- t.Fatalf("expected recurrent map to be preserved on reuse")
- }
- if store.entries[0].pos != 40 {
- t.Fatalf("expected entry 0 pos to be 40, got %d", store.entries[0].pos)
- }
-}
-
-func TestSlotCheckpointStoreFullCapacity(t *testing.T) {
- store := newSlotCheckpointStore(2)
-
- idx1 := store.record(10)
- idx2 := store.record(20)
-
- if idx1 != 0 || idx2 != 1 {
- t.Fatalf("expected indices 0, 1, got %d, %d", idx1, idx2)
- }
- if store.size != 2 {
- t.Fatalf("expected size 2, got %d", store.size)
- }
-
- _, pos1, ok1 := store.bestIndex(15)
- _, pos2, ok2 := store.bestIndex(25)
-
- if !ok1 || pos1 != 10 {
- t.Fatalf("expected best pos 10 for target 15, got pos=%d ok=%v", pos1, ok1)
- }
- if !ok2 || pos2 != 20 {
- t.Fatalf("expected best pos 20 for target 25, got pos=%d ok=%v", pos2, ok2)
- }
-}
-
-func TestSlotCheckpointStoreEmptyBuffer(t *testing.T) {
- store := newSlotCheckpointStore(0)
-
- idx := store.record(10)
- if idx != -1 {
- t.Fatalf("expected record to return -1 for empty buffer, got %d", idx)
- }
-
- _, _, ok := store.bestIndex(15)
- if ok {
- t.Fatalf("expected no checkpoint for empty buffer")
- }
-}
-
-func TestSlotCheckpointStorePruneAfterAll(t *testing.T) {
- store := newSlotCheckpointStore(3)
- store.record(10)
- store.record(20)
- store.record(30)
-
- store.pruneAfter(5)
-
- if store.size != 0 {
- t.Fatalf("expected size 0 after pruning all, got %d", store.size)
- }
- if store.lastPos != -1 {
- t.Fatalf("expected lastPos -1 after pruning all, got %d", store.lastPos)
- }
-
- _, _, ok := store.bestIndex(100)
- if ok {
- t.Fatalf("expected no checkpoint after pruning all")
- }
-}
diff --git a/kvcache/wrapper.go b/kvcache/wrapper.go
deleted file mode 100644
index 7533d959e..000000000
--- a/kvcache/wrapper.go
+++ /dev/null
@@ -1,110 +0,0 @@
-package kvcache
-
-import (
- "math"
-
- "github.com/ollama/ollama/ml"
- "github.com/ollama/ollama/model/input"
-)
-
-// Wrapper cache is a container for multiple types of caches,
-// such as for the encoding and decoding portions of a model.
-type WrapperCache struct {
- // caches we are wrapping
- caches []Cache
-
- // cache to be used for this layer
- curType int
-}
-
-func NewWrapperCache(caches ...Cache) *WrapperCache {
- return &WrapperCache{
- caches: caches,
- }
-}
-
-func (c *WrapperCache) Init(backend ml.Backend, dtype ml.DType, maxSequences, capacity, maxBatch int) {
- for _, cache := range c.caches {
- cache.Init(backend, dtype, maxSequences, capacity, maxBatch)
- }
-}
-
-func (c *WrapperCache) SetConfig(config ml.CacheConfig) {
- for _, cache := range c.caches {
- cache.SetConfig(config)
- }
-}
-
-func (c *WrapperCache) Close() {
- for _, cache := range c.caches {
- cache.Close()
- }
-}
-
-func (c *WrapperCache) StartForward(ctx ml.Context, batch input.Batch, reserve bool) error {
- for i, cache := range c.caches {
- err := cache.StartForward(ctx, batch, reserve)
- if err != nil {
- // unwind on error - Remove with endIndex set to math.MaxInt32 does not fail
- for j := i - 1; j >= 0; j-- {
- for k := range batch.Positions {
- _ = c.caches[j].Remove(batch.Sequences[k], batch.Positions[k], math.MaxInt32)
- }
- }
- return err
- }
- }
-
- c.curType = 0
- return nil
-}
-
-func (c *WrapperCache) SetLayer(layer int) {
- for _, cache := range c.caches {
- cache.SetLayer(layer)
- }
-}
-
-func (c *WrapperCache) SetLayerType(layerType int) {
- c.curType = layerType
-}
-
-func (c *WrapperCache) UnderlyingCache() Cache {
- return c.caches[c.curType]
-}
-
-func (c *WrapperCache) Get(ctx ml.Context) (ml.Tensor, ml.Tensor, ml.Tensor) {
- return c.caches[c.curType].Get(ctx)
-}
-
-func (c *WrapperCache) Put(ctx ml.Context, key, value ml.Tensor) {
- c.caches[c.curType].Put(ctx, key, value)
-}
-
-func (c *WrapperCache) CopyPrefix(srcSeq, dstSeq int, len int32) {
- for _, cache := range c.caches {
- cache.CopyPrefix(srcSeq, dstSeq, len)
- }
-}
-
-func (c *WrapperCache) CanResume(seq int, pos int32) bool {
- for _, cache := range c.caches {
- if !cache.CanResume(seq, pos) {
- return false
- }
- }
-
- return true
-}
-
-func (c *WrapperCache) Remove(seq int, beginIndex, endIndex int32) error {
- // If the one of these fails, the caller is supposed to retry with endIndex set to math.MaxInt32, which should not fail
- for _, cache := range c.caches {
- err := cache.Remove(seq, beginIndex, endIndex)
- if err != nil {
- return err
- }
- }
-
- return nil
-}
diff --git a/ml/nn/attention.go b/ml/nn/attention.go
deleted file mode 100644
index e495e1f60..000000000
--- a/ml/nn/attention.go
+++ /dev/null
@@ -1,84 +0,0 @@
-package nn
-
-import (
- "fmt"
-
- "github.com/ollama/ollama/kvcache"
- "github.com/ollama/ollama/ml"
-)
-
-// Attention implements scaled dot-product attention for transformer models:
-// Attention(Q, K, V) = softmax(QK^T/√d_k)V
-//
-// Parameters:
-// - ctx: Context for tensor operations
-// - query: Query tensor (Q) with shape [d_k, heads, seq_len_q]
-// - key: Key tensor (K) with shape [d_k, kv_heads, seq_len_k], can be nil to read from cache only
-// - value: Value tensor (V) with shape [d_v, kv_heads, seq_len_k], can be nil to read from cache only
-// - scale: Scaling factor, typically 1/√d_k where d_k is the key dimension
-// - cache: KV cache to store key/value and get past history, can be nil to only use provided key/value
-//
-// Returns:
-//
-// Attention output with shape [d_v, heads, seq_len_q]
-func Attention(ctx ml.Context, query, key, value ml.Tensor, scale float64, cache kvcache.Cache) ml.Tensor {
- return AttentionWithVMLA(ctx, query, key, value, nil, nil, scale, cache)
-}
-
-func AttentionWithSinks(ctx ml.Context, query, key, value, sinks ml.Tensor, scale float64, cache kvcache.Cache) ml.Tensor {
- return AttentionWithVMLA(ctx, query, key, value, sinks, nil, scale, cache)
-}
-
-func AttentionWithVMLA(ctx ml.Context, query, key, value, sinks ml.Tensor, vmla ml.Tensor, scale float64, cache kvcache.Cache) ml.Tensor {
- ctx.Forward(query)
- if key != nil && value != nil {
- if query.Dim(0) != key.Dim(0) {
- panic(fmt.Errorf("d_k in attention operation does not match between query(%v) and key(%v)", query.Dim(0), key.Dim(0)))
- }
-
- if key.Dim(1) != value.Dim(1) {
- panic(fmt.Errorf("kv_heads in attention operation does not match between key(%v) and value(%v)", key.Dim(1), value.Dim(1)))
- }
-
- if key.Dim(2) != value.Dim(2) {
- panic(fmt.Errorf("seq_len_k in attention operation does not match between key(%v) and value(%v)", key.Dim(2), value.Dim(2)))
- }
-
- ctx.Forward(key, value)
- if cache != nil {
- cache.Put(ctx, key, value)
- }
- } else if cache == nil {
- panic("key & value tensors must be provided if cache is nil")
- }
-
- var mask ml.Tensor
- if cache != nil {
- key, value, mask = cache.Get(ctx)
- }
-
- if sdpa, ok := query.(ml.ScaledDotProductAttention); ok {
- cacheConfigApplied := cache != nil
- return sdpa.ScaledDotProductAttention(ctx, key, value, mask, sinks, vmla, scale, cacheConfigApplied)
- } else {
- query = query.Permute(ctx, 0, 2, 1, 3)
- key = key.Permute(ctx, 0, 2, 1, 3)
- value = value.Permute(ctx, 1, 2, 0, 3).Contiguous(ctx)
-
- kq := key.MulmatFullPrec(ctx, query)
-
- kq = kq.Scale(ctx, scale)
- if mask != nil {
- kq = kq.Add(ctx, mask)
- }
- kq = kq.Softmax(ctx)
-
- kqv := value.Mulmat(ctx, kq)
-
- if vmla != nil {
- kqv = vmla.Mulmat(ctx, kqv)
- }
-
- return kqv.Permute(ctx, 0, 2, 1, 3).Contiguous(ctx)
- }
-}
diff --git a/ml/nn/convolution.go b/ml/nn/convolution.go
deleted file mode 100644
index 2954de007..000000000
--- a/ml/nn/convolution.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package nn
-
-import "github.com/ollama/ollama/ml"
-
-type Conv2D struct {
- Weight ml.Tensor `gguf:"weight"`
- Bias ml.Tensor `gguf:"bias"`
-}
-
-func (m *Conv2D) Forward(ctx ml.Context, t ml.Tensor, s0, s1, p0, p1, d0, d1 int) ml.Tensor {
- t = m.Weight.Conv2D(ctx, t, s0, s1, p0, p1, d0, d1)
- if m.Bias != nil {
- // Bias shape is (out_channels,) while t shape is (width, height, out_channels, batch)
- t = t.Add(ctx, m.Bias.Reshape(ctx, 1, 1, -1))
- }
- return t
-}
-
-type Conv3D struct {
- Weight ml.Tensor `gguf:"weight"`
- Bias ml.Tensor `gguf:"bias"`
-}
-
-func (m *Conv3D) Forward(ctx ml.Context, t ml.Tensor, c, s0, s1, s2, p0, p1, p2, d0, d1, d2 int) ml.Tensor {
- t = m.Weight.Conv3D(ctx, t, c, s0, s1, s2, p0, p1, p2, d0, d1, d2)
- if m.Bias != nil {
- t = t.Add(ctx, m.Bias)
- }
- return t
-}
diff --git a/ml/nn/embedding.go b/ml/nn/embedding.go
deleted file mode 100644
index 621efbcce..000000000
--- a/ml/nn/embedding.go
+++ /dev/null
@@ -1,11 +0,0 @@
-package nn
-
-import "github.com/ollama/ollama/ml"
-
-type Embedding struct {
- Weight ml.Tensor `gguf:"weight"`
-}
-
-func (m *Embedding) Forward(ctx ml.Context, hiddenState ml.Tensor) ml.Tensor {
- return m.Weight.Rows(ctx, hiddenState)
-}
diff --git a/ml/nn/linear.go b/ml/nn/linear.go
deleted file mode 100644
index c1f331635..000000000
--- a/ml/nn/linear.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package nn
-
-import "github.com/ollama/ollama/ml"
-
-type Linear struct {
- Weight ml.Tensor `gguf:"weight"`
- Bias ml.Tensor `gguf:"bias"`
-}
-
-func (m *Linear) Forward(ctx ml.Context, t ml.Tensor) ml.Tensor {
- t = m.Weight.Mulmat(ctx, t)
- if m.Bias != nil {
- t = t.Add(ctx, m.Bias)
- }
-
- return t
-}
-
-type LinearBatch struct {
- Weight ml.Tensor `gguf:"weight"`
- Bias ml.Tensor `gguf:"bias"`
-}
-
-func (m *LinearBatch) Forward(ctx ml.Context, t, indices ml.Tensor) ml.Tensor {
- t = m.Weight.MulmatID(ctx, t, indices)
- if m.Bias != nil {
- t = t.AddID(ctx, m.Bias, indices)
- }
-
- return t
-}
diff --git a/ml/nn/normalization.go b/ml/nn/normalization.go
deleted file mode 100644
index 8346bf7a3..000000000
--- a/ml/nn/normalization.go
+++ /dev/null
@@ -1,22 +0,0 @@
-package nn
-
-import (
- "github.com/ollama/ollama/ml"
-)
-
-type LayerNorm struct {
- Weight ml.Tensor `gguf:"weight"`
- Bias ml.Tensor `gguf:"bias"`
-}
-
-func (m *LayerNorm) Forward(ctx ml.Context, t ml.Tensor, eps float32) ml.Tensor {
- return t.LayerNorm(ctx, m.Weight, m.Bias, eps)
-}
-
-type RMSNorm struct {
- Weight ml.Tensor `gguf:"weight"`
-}
-
-func (m *RMSNorm) Forward(ctx ml.Context, t ml.Tensor, eps float32) ml.Tensor {
- return t.RMSNorm(ctx, m.Weight, eps)
-}
diff --git a/ml/nn/pooling/pooling.go b/ml/nn/pooling/pooling.go
deleted file mode 100644
index 47af87463..000000000
--- a/ml/nn/pooling/pooling.go
+++ /dev/null
@@ -1,41 +0,0 @@
-package pooling
-
-import (
- "github.com/ollama/ollama/ml"
-)
-
-type Type uint32
-
-const (
- TypeNone Type = iota
- TypeMean
- TypeCLS
- TypeLast
-)
-
-func (t Type) String() string {
- switch t {
- case TypeMean:
- return "Mean"
- case TypeCLS:
- return "CLS"
- case TypeLast:
- return "Last"
- default:
- return "Unknown"
- }
-}
-
-func (t Type) Forward(ctx ml.Context, hiddenStates ml.Tensor) ml.Tensor {
- switch t {
- case TypeMean:
- hiddenStates = hiddenStates.Permute(ctx, 1, 0, 2, 3).Contiguous(ctx).Mean(ctx)
- return hiddenStates.Permute(ctx, 1, 0, 2, 3).Contiguous(ctx)
- case TypeCLS:
- return hiddenStates.Slice(ctx, 1, 0, 1, 1)
- case TypeLast:
- return hiddenStates.Slice(ctx, 1, hiddenStates.Dim(1)-1, hiddenStates.Dim(1), 1)
- default:
- panic("unknown pooling type")
- }
-}
diff --git a/ml/nn/rope.go b/ml/nn/rope.go
deleted file mode 100644
index 967aa94f9..000000000
--- a/ml/nn/rope.go
+++ /dev/null
@@ -1,20 +0,0 @@
-package nn
-
-import (
- "github.com/ollama/ollama/ml"
- "github.com/ollama/ollama/ml/nn/rope"
-)
-
-// fastRoPE is an interface for tensors that support fast rotary positional embedding.
-type fastRoPE interface {
- RoPE(ctx ml.Context, positions ml.Tensor, dim int, base, scale float32, options ...func(*rope.Options)) ml.Tensor
-}
-
-// RoPE applies rotary positional embedding to tensor `t`.
-func RoPE(ctx ml.Context, t, positions ml.Tensor, dim int, base, scale float32, options ...func(*rope.Options)) ml.Tensor {
- if t, ok := t.(fastRoPE); ok {
- return t.RoPE(ctx, positions, dim, base, scale, options...)
- }
-
- panic("RoPE not implemented for this tensor type")
-}
diff --git a/ml/nn/rope/options.go b/ml/nn/rope/options.go
deleted file mode 100644
index 1724128a4..000000000
--- a/ml/nn/rope/options.go
+++ /dev/null
@@ -1,92 +0,0 @@
-// Package rope provides options for RoPE
-package rope
-
-import "github.com/ollama/ollama/ml"
-
-// Options contains optional parameters for RoPE function
-type Options struct {
- Type int
- Factors ml.Tensor
-
- // YaRN options
- YaRN struct {
- OriginalContextLength int
- ExtrapolationFactor,
- AttentionFactor,
- BetaFast,
- BetaSlow float32
- }
-
- // MRoPE options
- MRoPE struct {
- Sections []int
- }
-}
-
-// WithTypeNeoX sets RoPE type to NeoX
-func WithTypeNeoX() func(*Options) {
- return func(opts *Options) {
- opts.Type = 2
- }
-}
-
-// WithFactors sets custom rope factors
-func WithFactors(factors ml.Tensor) func(*Options) {
- return func(opts *Options) {
- if factors != nil {
- opts.Factors = factors
- }
- }
-}
-
-// WithOriginalContextLength sets a custom context length
-func WithOriginalContextLength(n int) func(*Options) {
- return func(opts *Options) {
- opts.YaRN.OriginalContextLength = n
- }
-}
-
-func WithExtrapolationFactor(extrapolationFactor float32) func(*Options) {
- return func(opts *Options) {
- opts.YaRN.ExtrapolationFactor = extrapolationFactor
- }
-}
-
-func WithAttentionFactor(attentionFactor float32) func(*Options) {
- return func(opts *Options) {
- opts.YaRN.AttentionFactor = attentionFactor
- }
-}
-
-func WithBetaFast(betaFast float32) func(*Options) {
- return func(opts *Options) {
- opts.YaRN.BetaFast = betaFast
- }
-}
-
-func WithBetaSlow(betaSlow float32) func(*Options) {
- return func(opts *Options) {
- opts.YaRN.BetaSlow = betaSlow
- }
-}
-
-func WithMRoPE(sections []int) func(*Options) {
- return func(opts *Options) {
- opts.Type |= 1 << 3
- opts.MRoPE.Sections = sections
- }
-}
-
-func WithVision(sections []int) func(*Options) {
- return func(opts *Options) {
- opts.Type |= 1<<3 | 1<<4
- opts.MRoPE.Sections = sections
- }
-}
-
-func WithInterleaveMRoPE(sections []int) func(*Options) {
- return func(opts *Options) {
- opts.Type |= 1<<3 | 1<<5
- opts.MRoPE.Sections = sections
- }
-}
diff --git a/model/input/input.go b/model/input/input.go
deleted file mode 100644
index 35dc41b35..000000000
--- a/model/input/input.go
+++ /dev/null
@@ -1,72 +0,0 @@
-package input
-
-import "github.com/ollama/ollama/ml"
-
-// Multimodal is a multimodal embedding or a component of one.
-// For example, it could be a row of an image that can be processed
-// independently.
-type Multimodal struct {
- // Tensor is the embedding data. Implementations may chose what to
- // store here or it may be nil if not needed. However, any ml.Tensor
- // objects must be stored here and not in Data.
- Tensor ml.Tensor
-
- // Data is implementation-specific opaque data, such as metadata on how
- // to layout Tensor. It may be nil if not needed. It may also store larger
- // objects such as complete images if they are to be processed later.
- Data any
-}
-
-// Input represents one token in the input stream
-type Input struct {
- // Token is a single element of text.
- Token int32
-
- // Multimodal is represents a non-text element such as an
- // image (or part of one if the image can be processed in pieces).
- // It may be used either together with Token or on its own.
- Multimodal []Multimodal
-
- // MultimodalHash is a unique representation of the data
- // stored in Multimodal, used for caching and comparing
- // equality.
- MultimodalHash uint64
-
- // SameBatch forces the following number of tokens to be processed
- // in a single batch, breaking and extending batches as needed.
- // Useful for things like images that must be processed in one
- // shot.
- SameBatch int
-}
-
-// MultimodalIndex is a multimodal element (such as an image)
-// together with an index into the slice of Inputs with the
-// corresponding token. Note that the index is not the same
-// as the position - to find that use the index with the
-// Positions slice.
-type MultimodalIndex struct {
- Index int
- Multimodal []Multimodal
-}
-
-// Batch contains the inputs for a model forward pass
-type Batch struct {
- // Inputs is the input tokens, including placeholders for multimodal inputs.
- Inputs ml.Tensor
-
- // Outputs are the set of indicies into Inputs for which output data should
- // be returned.
- Outputs ml.Tensor
-
- // Positions is the position for each Input, relative to its sequence. Equal
- // in length to Inputs.
- Positions []int32
-
- // Sequences is the sequence for each Input. Equal in length to Inputs.
- Sequences []int
-
- // Multimodal is a set of multimodal embeddings previously created by
- // EncodeMultimodal, along with an index into Inputs. Unused for text-only
- // models or for batches without multimodal elements.
- Multimodal []MultimodalIndex
-}
diff --git a/model/model.go b/model/model.go
deleted file mode 100644
index 238df11bb..000000000
--- a/model/model.go
+++ /dev/null
@@ -1,353 +0,0 @@
-package model
-
-import (
- "errors"
- "fmt"
- _ "image/jpeg"
- _ "image/png"
- "log/slog"
- "os"
- "reflect"
- "strconv"
- "strings"
-
- _ "golang.org/x/image/bmp"
- _ "golang.org/x/image/tiff"
- _ "golang.org/x/image/webp"
-
- "github.com/ollama/ollama/fs"
- fsggml "github.com/ollama/ollama/fs/ggml"
- "github.com/ollama/ollama/kvcache"
- "github.com/ollama/ollama/logutil"
- "github.com/ollama/ollama/ml"
- "github.com/ollama/ollama/ml/nn/pooling"
- "github.com/ollama/ollama/model/input"
- "github.com/ollama/ollama/tokenizer"
-)
-
-var (
- ErrNoVisionModel = errors.New("this model is missing data required for image input")
- ErrUnsupportedModel = errors.New("model not supported")
- ErrUnsupportedTokenizer = errors.New("tokenizer not supported")
-)
-
-// Model implements a specific model architecture, defining the forward pass and any model-specific configuration
-type Model interface {
- Forward(ml.Context, input.Batch) (ml.Tensor, error)
-
- Backend() ml.Backend
- Config() config
-}
-
-// Validator is an optional interface that models can implement to perform
-// validation after tensors have been loaded. If validation fails, model
-// loading will fail with the returned error.
-type Validator interface {
- Validate() error
-}
-
-// PostLoader is an optional interface that models can implement to run
-// initialization steps after backend weights have been loaded.
-type PostLoader interface {
- PostLoad() error
-}
-
-// MultimodalProcessor must be implemented by multimodal models.
-type MultimodalProcessor interface {
- // EncodeMultimodal processes a single input (such as an image) and
- // generates an output (typically an embedding) that can be used by the model.
- //
- // The return value is one or more tensors, each with optional model-specific
- // opaque metadata. Typically, the tensors might be views into an embedding
- // with each view representing a chunk of data that can be processed independently
- // in different batches.
- //
- // The result may be cached by the runner.
- EncodeMultimodal(ml.Context, []byte) ([]input.Multimodal, error)
-
- // PostTokenize is called after tokenization to allow the model to edit the
- // input stream to correctly arrange multimodal elements.
- //
- // The input is a slice of tokens with the results of EncodeMultimodal interleaved
- // in the order that the user provided them. Each element of the slice will be
- // either a single token or single multimodal object.
- //
- // The model must ensure that inputs are stored according to how they will be
- // processed and stored in the cache. For example, Llava-style models should insert
- // placeholder tokens equal to the feature size of the corresponding image with
- // the image itself attached to and split across these tokens. When Forward is called
- // a partial subset of these tokens may be submitted according to the batch size.
- //
- // This function is also responsible for updating MultimodalHash for any Multimodal
- // that is modified to ensure that there is a unique hash value that accurately
- // represents the contents.
- PostTokenize([]*input.Input) ([]*input.Input, error)
-}
-
-// Base implements the common fields and methods for all models
-type Base struct {
- b ml.Backend
- config
-}
-
-type config struct {
- Cache kvcache.Cache
-}
-
-// Backend returns the underlying backend that will run the model
-func (m *Base) Backend() ml.Backend {
- return m.b
-}
-
-func (m *Base) Config() config {
- return m.config
-}
-
-var models = make(map[string]func(fs.Config) (Model, error))
-
-// Register registers a model constructor for the given architecture
-func Register(name string, f func(fs.Config) (Model, error)) {
- if _, ok := models[name]; ok {
- panic("model: model already registered")
- }
-
- models[name] = f
-}
-
-// New initializes a new model instance with the provided configuration based on the metadata in the model file
-func New(modelPath string, params ml.BackendParams) (Model, error) {
- b, err := ml.NewBackend(modelPath, params)
- if err != nil {
- return nil, err
- }
-
- m, err := modelForArch(b.Config())
- if err != nil {
- return nil, err
- }
-
- base := Base{b: b, config: m.Config()}
- v := reflect.ValueOf(m)
- v.Elem().Set(populateFields(base, v.Elem()))
-
- if validator, ok := m.(Validator); ok {
- if err := validator.Validate(); err != nil {
- return nil, err
- }
- }
-
- return m, nil
-}
-
-func NewTextProcessor(s string) (tokenizer.Tokenizer, error) {
- r, err := os.Open(s)
- if err != nil {
- return nil, err
- }
- defer r.Close()
-
- meta, err := fsggml.Decode(r, -1)
- if err != nil {
- return nil, err
- }
-
- m, err := modelForArch(meta.KV())
- if err != nil {
- return nil, err
- }
-
- tp, ok := m.(tokenizer.Tokenizer)
- if !ok {
- return nil, ErrUnsupportedTokenizer
- }
- return tp, nil
-}
-
-func modelForArch(c fs.Config) (Model, error) {
- arch := c.Architecture()
- if pooling.Type(c.Uint("pooling_type")) != pooling.TypeNone {
- arch = arch + "_embed"
- }
-
- f, ok := models[arch]
- if !ok {
- return nil, ErrUnsupportedModel
- }
-
- return f(c)
-}
-
-func populateFields(base Base, v reflect.Value, tags ...Tag) reflect.Value {
- t := v.Type()
-
- if t.Kind() == reflect.Struct {
- allNil := true
- for i := range t.NumField() {
- tt := t.Field(i).Type
- vv := v.Field(i)
- if !vv.CanSet() {
- continue
- }
-
- // make a copy
- tagsCopy := tags
- if tag := t.Field(i).Tag.Get("gguf"); tag != "" {
- tagsCopy = append(tagsCopy, parseTag(tag))
- }
-
- if tt == reflect.TypeOf((*Base)(nil)).Elem() {
- vv.Set(reflect.ValueOf(base))
- } else if tt == reflect.TypeOf((*ml.Tensor)(nil)).Elem() {
- var fn func([]Tag, string, string) [][]string
- fn = func(tags []Tag, prefix, suffix string) (fullNames [][]string) {
- if len(tags) > 0 {
- var names []string
- if tags[0].name != "" {
- for _, n := range append([]string{tags[0].name}, tags[0].alternatives...) {
- names = append(names, prefix+n+suffix)
- }
- }
- childNames := fn(tags[1:], tags[0].prefix, tags[0].suffix)
- if len(names) == 0 {
- // current tag has no name, use child names only
- fullNames = append(fullNames, childNames...)
- } else if len(childNames) == 0 {
- // current tag has names but no children, create branches for each name
- for _, name := range names {
- fullNames = append(fullNames, []string{name})
- }
- } else {
- // merge each name with each child
- for _, name := range names {
- for _, childName := range childNames {
- fullNames = append(fullNames, append([]string{name}, childName...))
- }
- }
- }
- }
-
- return fullNames
- }
-
- names := fn(tagsCopy, "", "")
- for _, name := range names {
- if tensor := base.Backend().Get(strings.Join(name, ".")); tensor != nil {
- logutil.Trace("found tensor", "", tensor)
- vv.Set(reflect.ValueOf(tensor))
- break
- }
- }
- } else if tt.Kind() == reflect.Pointer || tt.Kind() == reflect.Interface {
- setPointer(base, vv, tagsCopy)
- } else if tt.Kind() == reflect.Slice || tt.Kind() == reflect.Array {
- for i := range vv.Len() {
- vvv := vv.Index(i)
- if vvv.Kind() == reflect.Pointer || vvv.Kind() == reflect.Interface {
- setPointer(base, vvv, append(tagsCopy, Tag{name: strconv.Itoa(i)}))
- } else {
- vvv.Set(populateFields(base, vvv, append(tagsCopy, Tag{name: strconv.Itoa(i)})...))
- }
- }
- }
-
- if !canNil(tt) || !vv.IsNil() {
- allNil = false
- }
- }
-
- if allNil {
- return reflect.Zero(t)
- }
- }
-
- return v
-}
-
-func setPointer(base Base, v reflect.Value, tags []Tag) {
- vv := v
- if v.Kind() == reflect.Interface {
- if v.IsNil() {
- return
- }
-
- vv = vv.Elem()
- }
-
- vv = reflect.Indirect(vv)
- if v.IsNil() {
- vv = reflect.New(v.Type().Elem()).Elem()
- }
-
- if f := populateFields(base, vv, tags...); f.CanAddr() {
- v.Set(f.Addr())
- }
-}
-
-type Tag struct {
- name,
- // prefix and suffix are applied to child tags
- prefix,
- suffix string
- alternatives []string
-}
-
-func parseTag(s string) (tag Tag) {
- parts := strings.Split(s, ",")
- if len(parts) > 0 {
- tag.name = parts[0]
-
- for _, part := range parts[1:] {
- if value, ok := strings.CutPrefix(part, "alt:"); ok && tag.name == "" {
- // elevate alternative to primary if no primary given
- tag.name = value
- slog.Warn("gguf tag has alt: but no primary name", "tag", s)
- } else if ok {
- tag.alternatives = append(tag.alternatives, value)
- }
- if value, ok := strings.CutPrefix(part, "pre:"); ok {
- tag.prefix = value
- }
- if value, ok := strings.CutPrefix(part, "suf:"); ok {
- tag.suffix = value
- }
- }
- }
-
- return
-}
-
-func canNil(t reflect.Type) bool {
- return t.Kind() == reflect.Chan ||
- t.Kind() == reflect.Func ||
- t.Kind() == reflect.Interface ||
- t.Kind() == reflect.Map ||
- t.Kind() == reflect.Pointer ||
- t.Kind() == reflect.Slice
-}
-
-func Forward(ctx ml.Context, m Model, batch input.Batch) (ml.Tensor, error) {
- if len(batch.Positions) != len(batch.Sequences) {
- return nil, fmt.Errorf("length of positions (%v) must match length of seqs (%v)", len(batch.Positions), len(batch.Sequences))
- }
-
- if len(batch.Positions) < 1 {
- return nil, errors.New("batch size cannot be less than 1")
- }
-
- cache := m.Config().Cache
- if cache != nil {
- err := cache.StartForward(ctx, batch, false)
- if err != nil {
- return nil, err
- }
- }
-
- t, err := m.Forward(ctx, batch)
- if err != nil {
- return nil, err
- }
-
- ctx.Forward(t)
-
- return t, nil
-}
diff --git a/model/models/gemma4/model.go b/model/models/gemma4/model.go
deleted file mode 100644
index 45d986fc7..000000000
--- a/model/models/gemma4/model.go
+++ /dev/null
@@ -1,265 +0,0 @@
-package gemma4
-
-import (
- "bytes"
- "fmt"
- "image"
- "log/slog"
- "slices"
- "time"
-
- "github.com/ollama/ollama/fs"
- "github.com/ollama/ollama/kvcache"
- "github.com/ollama/ollama/ml"
- "github.com/ollama/ollama/ml/nn"
- "github.com/ollama/ollama/ml/nn/rope"
- "github.com/ollama/ollama/model"
- "github.com/ollama/ollama/model/input"
- "github.com/ollama/ollama/tokenizer"
-)
-
-type Model struct {
- model.Base
- tokenizer.Tokenizer
-
- *VisionModel `gguf:"v"`
- *TextModel
- *AudioModel `gguf:"a"`
-
- *MultiModalProjector `gguf:"mm"`
- *AudioMultimodalProjector `gguf:"mm.a"`
-
- ImageProcessor
-
- imageTokenID int32
- imageEndTokenID int32
- audioTokenID int32
- audioEndTokenID int32
-
- audioOpts *AudioModelOptions
-}
-
-var _ model.MultimodalProcessor = (*Model)(nil)
-
-type MultiModalProjector struct {
- Projection *ClippableLinear `gguf:"input_projection"`
-}
-
-func (p *MultiModalProjector) Forward(ctx ml.Context, visionOutputs ml.Tensor, eps float32) ml.Tensor {
- visionOutputs = p.Projection.Forward(ctx, visionOutputs)
- // Post-projection RMSNorm without learned weight
- visionOutputs = visionOutputs.RMSNorm(ctx, nil, eps)
- return visionOutputs
-}
-
-func New(c fs.Config) (model.Model, error) {
- vocabulary := tokenizer.Vocabulary{
- Values: c.Strings("tokenizer.ggml.tokens"),
- Scores: c.Floats("tokenizer.ggml.scores"),
- Types: c.Ints("tokenizer.ggml.token_type"),
- Merges: c.Strings("tokenizer.ggml.merges"),
- AddBOS: c.Bool("tokenizer.ggml.add_bos_token", false),
- BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
- AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
- EOS: append(
- []int32{
- int32(c.Uint("tokenizer.ggml.eos_token_id")),
- },
- c.Ints("tokenizer.ggml.eos_token_ids")...,
- ),
- }
-
- vocabulary.EOS = append(vocabulary.EOS, int32(c.Uint("tokenizer.ggml.eot_token_id", 106)))
-
- // Gemma 4 uses BPE with SentencePiece-style ▁ space markers (not GPT-2 byte-level encoding).
- // The tokenizer.json has merges and a Replace normalizer (space → ▁), with no pre-tokenizer.
- t := tokenizer.NewBytePairEncodingWithOptions(&vocabulary, []string{},
- tokenizer.WithSentencePieceNormalizer())
-
- // Look up special token IDs for vision and audio
- imageTokenID := int32(-1)
- imageEndTokenID := int32(-1)
- audioTokenID := int32(-1)
- audioEndTokenID := int32(-1)
- for i, tok := range vocabulary.Values {
- switch tok {
- case "<|image>":
- imageTokenID = int32(i)
- case "<image|>":
- imageEndTokenID = int32(i)
- case "<|audio>":
- audioTokenID = int32(i)
- case "<audio|>":
- audioEndTokenID = int32(i)
- }
- }
-
- slog.Info("gemma4: token IDs", "image", imageTokenID, "image_end", imageEndTokenID, "audio", audioTokenID, "audio_end", audioEndTokenID)
-
- m := Model{
- Tokenizer: t,
- TextModel: newTextModel(c),
- VisionModel: newVisionModel(c),
- AudioModel: newAudioModel(c),
- MultiModalProjector: &MultiModalProjector{},
- AudioMultimodalProjector: &AudioMultimodalProjector{},
- ImageProcessor: newImageProcessor(c),
- imageTokenID: imageTokenID,
- imageEndTokenID: imageEndTokenID,
- audioTokenID: audioTokenID,
- audioEndTokenID: audioEndTokenID,
- audioOpts: newAudioModelOptions(c),
- }
-
- slidingWindowLen := int32(c.Uint("attention.sliding_window"))
- m.Cache = kvcache.NewWrapperCache(
- kvcache.NewSWAMemCache(slidingWindowLen, 4096, m.Shift),
- kvcache.NewCausalCache(m.Shift),
- )
-
- return &m, nil
-}
-
-func (m *Model) EncodeMultimodal(ctx ml.Context, multimodalData []byte) ([]input.Multimodal, error) {
- // Audio input: detect WAV format and route to audio encoder.
- if isAudioData(multimodalData) {
- return m.encodeAudioMultimodal(ctx, multimodalData)
- }
-
- if len(m.VisionModel.Layers) == 0 {
- return nil, model.ErrNoVisionModel
- }
-
- t0 := time.Now()
- img, _, err := image.Decode(bytes.NewReader(multimodalData))
- if err != nil {
- return nil, err
- }
- slog.Info("vision: decode", "elapsed", time.Since(t0), "bounds", img.Bounds())
-
- t1 := time.Now()
- f32s, imgW, imgH, err := m.ImageProcessor.ProcessImage(img)
- if err != nil {
- return nil, err
- }
- slog.Info("vision: preprocess", "elapsed", time.Since(t1), "size", [2]int{imgW, imgH})
-
- pixelValues := ctx.Input().FromFloats(f32s, imgW, imgH, m.ImageProcessor.numChannels)
- slog.Info("vision: pixelValues", "shape", pixelValues.Shape(), "dim0", pixelValues.Dim(0), "dim1", pixelValues.Dim(1), "dim2", pixelValues.Dim(2))
-
- numPatchesX := imgW / m.ImageProcessor.patchSize
- numPatchesY := imgH / m.ImageProcessor.patchSize
- slog.Info("vision: patches", "patchesX", numPatchesX, "patchesY", numPatchesY, "total", numPatchesX*numPatchesY, "patchSize", m.ImageProcessor.patchSize)
-
- visionOutputs := m.VisionModel.Forward(ctx, pixelValues, numPatchesX, numPatchesY)
- visionOutputs = visionPoolAndProject(ctx, visionOutputs, numPatchesX, numPatchesY, m.VisionModel.VisionModelOptions, m.MultiModalProjector, m.VisionModel.StdBias, m.VisionModel.StdScale)
- slog.Info("vision: encoded", "elapsed", time.Since(t0), "shape", visionOutputs.Shape())
-
- return []input.Multimodal{{Tensor: visionOutputs}}, nil
-}
-
-func (m *Model) PostLoad() error {
- m.VisionModel.InitClamp(m.MultiModalProjector)
- return nil
-}
-
-func (m *Model) encodeAudioMultimodal(ctx ml.Context, data []byte) ([]input.Multimodal, error) {
- if m.AudioModel == nil || m.audioOpts == nil {
- return nil, model.ErrNoVisionModel
- }
-
- t0 := time.Now()
- samples, err := decodeWAV(data)
- if err != nil {
- return nil, err
- }
- slog.Info("audio: decode", "elapsed", time.Since(t0), "samples", len(samples), "duration_s", float64(len(samples))/audioSampleRate)
-
- // Pad waveform to next multiple of 128.
- if rem := len(samples) % 128; rem != 0 {
- samples = append(samples, make([]float32, 128-rem)...)
- }
-
- // Compute mel spectrogram.
- melData, numFrames := computeMelSpectrogram(samples)
- if numFrames == 0 {
- return nil, fmt.Errorf("audio too short to encode")
- }
- slog.Info("audio: mel", "frames", numFrames, "elapsed", time.Since(t0))
-
- // Create input tensor [melBins, numFrames] (GGML ne order). FromFloats creates F32.
- melTensor := ctx.Input().FromFloats(melData, melBins, numFrames)
-
- // Run audio encoder.
- audioOutputs := m.AudioModel.ForwardAudio(ctx, melTensor, m.AudioMultimodalProjector, m.audioOpts)
- slog.Info("audio: encoded", "elapsed", time.Since(t0), "shape", audioOutputs.Shape())
-
- return []input.Multimodal{{Tensor: audioOutputs, Data: audioTag{}}}, nil
-}
-
-// audioTag marks multimodal data as audio (vs vision) for PostTokenize.
-type audioTag struct{}
-
-func (m *Model) PostTokenize(inputs []*input.Input) ([]*input.Input, error) {
- var result []*input.Input
-
- for _, inp := range inputs {
- if len(inp.Multimodal) == 0 {
- result = append(result, inp)
- continue
- }
-
- inputMultimodal := inp.Multimodal[0].Tensor
- numTokens := inputMultimodal.Dim(1)
-
- // Determine if this is audio or vision based on the tag.
- _, isAudio := inp.Multimodal[0].Data.(audioTag)
-
- var beginToken, endToken int32
- if isAudio {
- beginToken = m.audioTokenID
- endToken = m.audioEndTokenID
- } else {
- beginToken = m.imageTokenID
- endToken = m.imageEndTokenID
- }
-
- if beginToken >= 0 {
- result = append(result, &input.Input{Token: beginToken, SameBatch: numTokens + 2})
- }
-
- result = append(result,
- &input.Input{Multimodal: []input.Multimodal{{Tensor: inputMultimodal}}, MultimodalHash: inp.MultimodalHash},
- )
- result = append(result, slices.Repeat([]*input.Input{{Token: 0}}, numTokens-1)...)
-
- if endToken >= 0 {
- result = append(result, &input.Input{Token: endToken})
- }
- }
-
- return result, nil
-}
-
-func (m *Model) Forward(ctx ml.Context, batch input.Batch) (ml.Tensor, error) {
- hiddenState := m.TextModel.Forward(ctx, batch, m.Cache)
-
- hiddenState = m.TextModel.Output.Forward(ctx, hiddenState)
-
- if m.TextModel.TextOptions.finalLogitSoftcap > 0.0 {
- hiddenState = hiddenState.Scale(ctx, 1.0/float64(m.TextModel.TextOptions.finalLogitSoftcap))
- hiddenState = hiddenState.Tanh(ctx)
- hiddenState = hiddenState.Scale(ctx, float64(m.TextModel.TextOptions.finalLogitSoftcap))
- }
-
- return hiddenState, nil
-}
-
-func (m *Model) Shift(ctx ml.Context, layer int, key, shift ml.Tensor) (ml.Tensor, error) {
- ropeBase, ropeDims := m.TextModel.ropeForLayer(layer)
- return nn.RoPE(ctx, key, shift, ropeDims, ropeBase, 1.0, rope.WithTypeNeoX()), nil
-}
-
-func init() {
- model.Register("gemma4", New)
-}
diff --git a/model/models/gemma4/model_audio.go b/model/models/gemma4/model_audio.go
deleted file mode 100644
index 2bb53fad7..000000000
--- a/model/models/gemma4/model_audio.go
+++ /dev/null
@@ -1,611 +0,0 @@
-package gemma4
-
-import (
- "math"
-
- "github.com/ollama/ollama/fs"
- "github.com/ollama/ollama/ml"
- "github.com/ollama/ollama/ml/nn"
-)
-
-// AudioModel holds the audio encoder and configuration.
-type AudioModel struct {
- // SSCP: Sub-Sample Convolution Projection.
- SSCPConv0 *AudioConvBlock `gguf:"conv1d.0"`
- SSCPConv1 *AudioConvBlock `gguf:"conv1d.1"`
-
- // SSCP output projection (linear).
- SSCPInputProj *nn.Linear `gguf:"pre_encode.out"`
-
- // Conformer blocks.
- Layers []AudioConformerBlock `gguf:"blk"`
-
- // Output projection to embedder dimension.
- OutputProj *AudioOutputProj `gguf:"output_proj"`
-
- AudioModelOptions
-}
-
-type AudioOutputProj struct {
- Weight ml.Tensor `gguf:"weight"`
- Bias ml.Tensor `gguf:"bias"`
-}
-
-// AudioModelOptions holds audio model hyperparameters.
-type AudioModelOptions struct {
- hiddenSize int
- numHeads int
- headDim int
- ffnSize int
- numLayers int
- melBins int
- chunkSize int
- maxPast int
- maxFuture int
- contextSize int
- logitCap float32
- residualWeight float32
- gradClip float32
- convKernelSize int
- eps float32
-}
-
-// AudioConvBlock is a single 2D convolution block for the SSCP.
-type AudioConvBlock struct {
- Weight ml.Tensor `gguf:"weight"`
- Norm *nn.LayerNorm `gguf:"norm"`
-}
-
-// AudioConformerBlock is a single conformer layer.
-// All tensors are flat at the block level (a.blk.N.<name>) using underscore naming.
-type AudioConformerBlock struct {
- // Block-level norm
- Norm *nn.RMSNorm `gguf:"layer_pre_norm"`
-
- // FFW start
- FFWNorm *nn.RMSNorm `gguf:"ffn_norm"`
- FFWUp *AudioClippableLinear `gguf:"ffn_up"`
- FFWDown *AudioClippableLinear `gguf:"ffn_down"`
- FFWPostNorm *nn.RMSNorm `gguf:"ffn_post_norm"`
-
- // FFW end
- FFWNorm1 *nn.RMSNorm `gguf:"ffn_norm_1"`
- FFWUp1 *AudioClippableLinear `gguf:"ffn_up_1"`
- FFWDown1 *AudioClippableLinear `gguf:"ffn_down_1"`
- FFWPostNorm1 *nn.RMSNorm `gguf:"ffn_post_norm_1"`
-
- // Attention
- AttnQ *AudioClippableLinear `gguf:"attn_q"`
- AttnK *AudioClippableLinear `gguf:"attn_k"`
- AttnV *AudioClippableLinear `gguf:"attn_v"`
- AttnOut *AudioClippableLinear `gguf:"attn_out"`
- AttnPreNorm *nn.RMSNorm `gguf:"ln1"`
- AttnPostNorm *nn.RMSNorm `gguf:"ln2"`
- LinearPos ml.Tensor `gguf:"linear_pos.weight"`
- PerDimScale ml.Tensor `gguf:"per_dim_scale.weight"`
-
- // LightConv1d
- ConvPW1 *AudioClippableLinear `gguf:"conv_pw1"`
- ConvPW2 *AudioClippableLinear `gguf:"conv_pw2"`
- ConvDW ml.Tensor `gguf:"conv_dw.weight"`
- ConvNorm *nn.RMSNorm `gguf:"conv_norm"`
- NormConv *nn.RMSNorm `gguf:"norm_conv"`
-}
-
-// AudioClippableLinear is a linear layer with optional input/output clamping.
-type AudioClippableLinear struct {
- Weight ml.Tensor `gguf:"weight"`
- Bias ml.Tensor `gguf:"bias"`
- InputMin ml.Tensor `gguf:"input_min"`
- InputMax ml.Tensor `gguf:"input_max"`
- OutputMin ml.Tensor `gguf:"output_min"`
- OutputMax ml.Tensor `gguf:"output_max"`
-
- // Cached scalar clamp values (populated on first forward).
- inMin, inMax, outMin, outMax float32
- clampsLoaded bool
-}
-
-func (l *AudioClippableLinear) loadClamps() {
- if l.clampsLoaded {
- return
- }
- l.clampsLoaded = true
- if l.InputMin != nil {
- vals := l.InputMin.BackendGet()
- if len(vals) > 0 {
- l.inMin = vals[0]
- }
- }
- if l.InputMax != nil {
- vals := l.InputMax.BackendGet()
- if len(vals) > 0 {
- l.inMax = vals[0]
- }
- }
- if l.OutputMin != nil {
- vals := l.OutputMin.BackendGet()
- if len(vals) > 0 {
- l.outMin = vals[0]
- }
- }
- if l.OutputMax != nil {
- vals := l.OutputMax.BackendGet()
- if len(vals) > 0 {
- l.outMax = vals[0]
- }
- }
-}
-
-func (l *AudioClippableLinear) Forward(ctx ml.Context, x ml.Tensor) ml.Tensor {
- l.loadClamps()
- if l.inMax != 0 {
- x = x.Clamp(ctx, l.inMin, l.inMax)
- }
- out := l.Weight.Mulmat(ctx, x)
- if l.Bias != nil {
- out = out.Add(ctx, l.Bias)
- }
- if l.outMax != 0 {
- out = out.Clamp(ctx, l.outMin, l.outMax)
- }
- return out
-}
-
-// AudioMultimodalProjector is the audio-to-text embedding projector.
-type AudioMultimodalProjector struct {
- Projection *AudioClippableLinear `gguf:"input_projection"`
- FC *AudioFC `gguf:"fc"`
-}
-
-type AudioFC struct {
- Weight ml.Tensor `gguf:"weight"`
- Bias ml.Tensor `gguf:"bias"`
-}
-
-func (p *AudioMultimodalProjector) Forward(ctx ml.Context, x ml.Tensor, eps float32) ml.Tensor {
- // FC: output projection from conformer to embedder dimension.
- x = p.FC.Weight.Mulmat(ctx, x)
- if p.FC.Bias != nil {
- x = x.Add(ctx, p.FC.Bias)
- }
- // Pre-projection RMSNorm (without learned weight) — matches Python's embedding_pre_projection_norm.
- x = x.RMSNorm(ctx, nil, eps)
- // Embedding projection to text hidden size.
- x = p.Projection.Forward(ctx, x)
- return x
-}
-
-// ForwardAudio encodes mel spectrogram features into soft tokens.
-// melFeatures: float32 tensor with ne[0]=melBins, ne[1]=numFrames.
-// Returns: [hiddenSize, numTokens] tensor.
-func (m *AudioModel) ForwardAudio(ctx ml.Context, melFeatures ml.Tensor, proj *AudioMultimodalProjector, opts *AudioModelOptions) ml.Tensor {
- // SSCP Conv2D input: ne[0]=F (freq/width), ne[1]=T (time/height), ne[2]=C_in, ne[3]=B
- // melFeatures is [melBins, numFrames], add channel and batch dims.
- x := melFeatures.Reshape(ctx, melFeatures.Dim(0), melFeatures.Dim(1), 1, 1)
-
- // SSCP Conv block 0: [F, T, 1, 1] → [F', T', C0, 1]
- x = forwardConvBlock(ctx, m.SSCPConv0, x, opts)
-
- // SSCP Conv block 1: [F', T', C0, 1] → [F'', T'', C1, 1]
- x = forwardConvBlock(ctx, m.SSCPConv1, x, opts)
-
- // After conv blocks, layout is [F'', T'', C_out, B].
- // Permute to [C_out*F'', T'', B] for linear projection (channels+freq in ne[0]).
- fOut := x.Dim(0)
- tOut := x.Dim(1)
- cOut := x.Dim(2)
- // Permute [F'', T'', C, B] → [C, F'', T'', B]
- // (1,2,0,3): old[0]→pos1, old[1]→pos2, old[2]→pos0
- x = x.Permute(ctx, 1, 2, 0, 3).Contiguous(ctx)
- x = x.Reshape(ctx, cOut*fOut, tOut)
-
- // Linear projection to hidden size.
- x = m.SSCPInputProj.Forward(ctx, x)
-
- // Build causal-valid mask for conformer attention.
- causalMask := buildCausalValidMaskF32(opts.chunkSize, opts.maxPast, opts.maxFuture)
-
- // Run conformer blocks.
- for i := range m.Layers {
- x = m.Layers[i].Forward(ctx, x, causalMask, opts, i)
- }
-
- // Output projection.
- if m.OutputProj != nil {
- x = m.OutputProj.Weight.Mulmat(ctx, x)
- if m.OutputProj.Bias != nil {
- x = x.Add(ctx, m.OutputProj.Bias)
- }
- }
-
- // Audio embedder: project to text embedding space.
- if proj != nil {
- x = proj.Forward(ctx, x, opts.eps)
- }
-
- return x
-}
-
-// forwardConvBlock runs a single SSCP Conv2D block.
-// Conv2D receiver is the kernel, argument is the input data.
-// Input: [F, T, C_in, B]. Output: [F', T', C_out, B].
-func forwardConvBlock(ctx ml.Context, block *AudioConvBlock, x ml.Tensor, opts *AudioModelOptions) ml.Tensor {
- // Conv2D: kernel.Conv2D(ctx, input, s0, s1, p0, p1, d0, d1)
- // Kernel is 3x3, stride 2x2, padding 1x1 (matching SSCP config).
- // Output layout: [F', T', C_out, B]
- // Make weight contiguous — the shape reversal in the converter creates
- // a tensor where the physical data order doesn't match ne[]/stride[].
- weight := block.Weight.Contiguous(ctx)
- x = weight.Conv2D(ctx, x, 2, 2, 1, 1, 1, 1)
-
- // LayerNorm needs channels in ne[0]. Permute [F', T', C_out, B] → [C_out, F', T', B],
- // norm, then permute back.
- // GGML permute: axis i says where old axis i goes.
- // (1,2,0,3): old[0]→pos1, old[1]→pos2, old[2]→pos0 → [C_out, F', T', B]
- x = x.Permute(ctx, 1, 2, 0, 3).Contiguous(ctx)
- x = block.Norm.Forward(ctx, x, opts.eps)
- // (2,0,1,3): old[0]→pos2, old[1]→pos0, old[2]→pos1 → [F', T', C_out, B]
- x = x.Permute(ctx, 2, 0, 1, 3).Contiguous(ctx)
-
- x = x.RELU(ctx)
- return x
-}
-
-// Forward runs a single conformer block.
-func (cb *AudioConformerBlock) Forward(ctx ml.Context, x ml.Tensor, causalMask []float32, opts *AudioModelOptions, blockIdx int) ml.Tensor {
- // FFW start (half-residual).
- x = cb.forwardFFW(ctx, cb.FFWNorm, cb.FFWUp, cb.FFWDown, cb.FFWPostNorm, x, opts)
-
- // Self-attention.
- x = cb.forwardAttention(ctx, x, causalMask, opts, blockIdx)
-
- // Lightweight Conv1d.
- x = cb.forwardLightConv(ctx, x, opts, blockIdx)
-
- // FFW end (half-residual).
- x = cb.forwardFFW(ctx, cb.FFWNorm1, cb.FFWUp1, cb.FFWDown1, cb.FFWPostNorm1, x, opts)
-
- // Gradient clipping + final norm.
- x = x.Clamp(ctx, -opts.gradClip, opts.gradClip)
- x = cb.Norm.Forward(ctx, x, opts.eps)
-
- return x
-}
-
-// forwardFFW runs a feedforward module with half-residual connection.
-func (cb *AudioConformerBlock) forwardFFW(ctx ml.Context, preNorm *nn.RMSNorm, up, down *AudioClippableLinear, postNorm *nn.RMSNorm, x ml.Tensor, opts *AudioModelOptions) ml.Tensor {
- residual := x
- x = x.Clamp(ctx, -opts.gradClip, opts.gradClip)
- x = preNorm.Forward(ctx, x, opts.eps)
- x = up.Forward(ctx, x)
- x = x.SILU(ctx)
- x = down.Forward(ctx, x)
- x = x.Clamp(ctx, -opts.gradClip, opts.gradClip)
- x = postNorm.Forward(ctx, x, opts.eps)
- x = x.Scale(ctx, float64(opts.residualWeight))
- return residual.Add(ctx, x)
-}
-
-// forwardAttention runs the conformer block-local attention with relative position embeddings.
-func (cb *AudioConformerBlock) forwardAttention(ctx ml.Context, x ml.Tensor, causalMask []float32, opts *AudioModelOptions, blockIdx int) ml.Tensor {
- residual := x
- x = x.Clamp(ctx, -opts.gradClip, opts.gradClip)
- x = cb.AttnPreNorm.Forward(ctx, x, opts.eps)
-
- hiddenSize := x.Dim(0)
- seqLen := x.Dim(1)
-
- // QKV projections: [hiddenSize, seqLen] → [headDim, numHeads, seqLen]
- q := cb.AttnQ.Forward(ctx, x).Reshape(ctx, opts.headDim, opts.numHeads, seqLen)
- k := cb.AttnK.Forward(ctx, x).Reshape(ctx, opts.headDim, opts.numHeads, seqLen)
- v := cb.AttnV.Forward(ctx, x).Reshape(ctx, opts.headDim, opts.numHeads, seqLen)
-
- // Per-dim scaling for queries: (headDim^-0.5 / log(2)) * softplus(per_dim_scale)
- // per_dim_scale is already softplus'd from the converter.
- qScale := float64(math.Pow(float64(opts.headDim), -0.5)) / math.Log(2)
- q = q.Scale(ctx, qScale)
- if cb.PerDimScale != nil {
- q = q.Mul(ctx, cb.PerDimScale)
- }
-
- // Key scaling: softplus(1) / log(2) — matches the query base scaling convention.
- kScale := math.Log(1+math.E) / math.Log(2)
- k = k.Scale(ctx, kScale)
-
- // Build sinusoidal position embeddings for the block-local context.
- maxSpan := opts.maxPast + opts.maxFuture + 1 // 13 unique relative positions
- posEmb := cb.buildPositionEmbeddings(ctx, maxSpan, opts)
- // posEmb: [headDim, numHeads, maxSpan]
-
- // Block-local attention: process chunks of size chunkSize.
- chunkSize := opts.chunkSize
- numChunks := (seqLen + chunkSize - 1) / chunkSize
- contextSize := opts.contextSize
-
- // Pad q/k/v to multiple of chunkSize on the time dimension (dim 2).
- padT := numChunks*chunkSize - seqLen
- if padT > 0 {
- q = q.Pad(ctx, 0, 0, padT, 0)
- k = k.Pad(ctx, 0, 0, padT, 0)
- v = v.Pad(ctx, 0, 0, padT, 0)
- }
- paddedLen := numChunks * chunkSize
-
- // Pad k/v for context extraction: add maxPast on left, (maxFuture+chunkSize-1) on right.
- // Use Pad (right) + PadExt (left) workaround since PadExt+Slice has issues.
- // Actually use Concat with zero tensors for reliable left-padding.
- padLeft := opts.maxPast
- padRight := opts.maxFuture + chunkSize - 1
- zeroLeft := ctx.Input().FromFloats(make([]float32, opts.headDim*opts.numHeads*padLeft), opts.headDim, opts.numHeads, padLeft)
- zeroRight := ctx.Input().FromFloats(make([]float32, opts.headDim*opts.numHeads*padRight), opts.headDim, opts.numHeads, padRight)
- kPadded := zeroLeft.Concat(ctx, k, 2).Concat(ctx, zeroRight, 2)
- vPadded := zeroLeft.Concat(ctx, v, 2).Concat(ctx, zeroRight, 2)
-
- // Reshape q into chunks: [headDim, numHeads, numChunks, chunkSize]
- qChunked := q.Reshape(ctx, opts.headDim, opts.numHeads, numChunks, chunkSize)
-
- // Process each chunk and collect results.
- chunkOutputs := make([]ml.Tensor, numChunks)
- for u := range numChunks {
- // Extract query block: [headDim, numHeads, 1, chunkSize] → [headDim, numHeads, chunkSize]
- qBlock := qChunked.Slice(ctx, 2, u, u+1, 1).Reshape(ctx, opts.headDim, opts.numHeads, chunkSize)
-
- // Extract key/value context: [headDim, numHeads, contextSize]
- cStart := u * chunkSize // offset in kPadded (padLeft already accounts for left context)
- kCtx := kPadded.Slice(ctx, 2, cStart, cStart+contextSize, 1).Contiguous(ctx)
- vCtx := vPadded.Slice(ctx, 2, cStart, cStart+contextSize, 1).Contiguous(ctx)
-
- // Content-content logits: qBlock^T @ kCtx → [chunkSize, contextSize] per head.
- // Mulmat(a, b) = a^T @ b. We want Q^T K, so: kCtx.Mulmat(qBlock) but that gives
- // [numHeads, chunkSize, contextSize] with wrong batching.
- // Instead: permute to [headDim, chunkSize, numHeads] and [headDim, contextSize, numHeads]
- // then Mulmat batches over numHeads.
- // GGML permute(0,2,1,3): old[0]→0, old[1]→2, old[2]→1
- qP := qBlock.Permute(ctx, 0, 2, 1, 3) // [headDim, chunkSize, numHeads]
- kP := kCtx.Permute(ctx, 0, 2, 1, 3) // [headDim, contextSize, numHeads]
-
- termAC := kP.MulmatFullPrec(ctx, qP) // [contextSize, chunkSize, numHeads]
-
- // Content-position logits: qBlock^T @ posEmb → [chunkSize, maxSpan] per head.
- pP := posEmb.Permute(ctx, 0, 2, 1, 3) // [headDim, maxSpan, numHeads]
- termBDRaw := pP.MulmatFullPrec(ctx, qP) // [maxSpan, chunkSize, numHeads]
-
- // Relative shift: [maxSpan, chunkSize, numHeads] → [contextSize, chunkSize, numHeads]
- termBD := cb.relativeShiftGGML(ctx, termBDRaw, maxSpan, chunkSize, contextSize, opts.numHeads)
-
- // Combined logits.
- logits := termAC.Add(ctx, termBD)
-
- // Logit softcap: tanh(logits / cap) * cap
- logits = logits.Scale(ctx, 1.0/float64(opts.logitCap))
- logits = logits.Tanh(ctx)
- logits = logits.Scale(ctx, float64(opts.logitCap))
-
- // Apply combined causal + validity mask.
- // causalMask [chunkSize * contextSize]: 1=causal-allowed, 0=masked.
- // Validity: context positions before the actual sequence start are invalid.
- // For chunk u, context position c corresponds to actual time: u*chunkSize + c - padLeft.
- // Valid if 0 <= actual_time < seqLen.
- // Mask tensor layout: [contextSize, chunkSize, 1] with ne[0]=contextSize contiguous.
- // Element at (context=j, chunk=i) is at flat index: i*contextSize + j.
- maskData := make([]float32, contextSize*chunkSize)
- for i := range chunkSize {
- for j := range contextSize {
- actualTime := u*chunkSize + j - padLeft
- causalOK := causalMask[i*contextSize+j] > 0
- validOK := actualTime >= 0 && actualTime < seqLen
- if causalOK && validOK {
- maskData[i*contextSize+j] = 0
- } else {
- maskData[i*contextSize+j] = -1e9
- }
- }
- }
- mask := ctx.Input().FromFloats(maskData, contextSize, chunkSize, 1) // 3D for broadcasting over numHeads
- logits = logits.Add(ctx, mask)
-
- // Softmax over context dimension (dim 0 = contextSize).
- logits = logits.Softmax(ctx) // softmax over ne[0]=contextSize
-
- // Weighted sum: logits^T @ vCtx.
- // logits: [contextSize, chunkSize, numHeads], vCtx: [headDim, numHeads, contextSize]
- // vCtx permuted: [headDim, contextSize, numHeads]
- vP := vCtx.Permute(ctx, 0, 2, 1, 3) // [headDim, contextSize, numHeads]
- // Weighted sum: for each head, value[headDim, contextSize] @ weights[contextSize, chunkSize]
- // = [headDim, chunkSize].
- // Mulmat(a, b) = a^T @ b. Need a=[contextSize, headDim, numHeads], b=[contextSize, chunkSize, numHeads].
- vPT := vP.Permute(ctx, 1, 0, 2, 3).Contiguous(ctx) // [contextSize, headDim, numHeads]
- chunkOut := vPT.Mulmat(ctx, logits) // [headDim, chunkSize, numHeads]
-
- // Permute back to [headDim, numHeads, chunkSize]
- chunkOut = chunkOut.Permute(ctx, 0, 2, 1, 3).Contiguous(ctx)
- chunkOutputs[u] = chunkOut
- }
-
- // Concatenate chunk outputs along time dimension.
- var attnOut ml.Tensor
- if numChunks == 1 {
- attnOut = chunkOutputs[0]
- } else {
- attnOut = chunkOutputs[0]
- for _, co := range chunkOutputs[1:] {
- attnOut = attnOut.Concat(ctx, co, 2)
- }
- }
-
- // Trim to original sequence length if we padded.
- if paddedLen > seqLen {
- attnOut = attnOut.Slice(ctx, 2, 0, seqLen, 1).Contiguous(ctx)
- }
-
- // Reshape to [hiddenSize, seqLen] and project.
- attnOut = attnOut.Reshape(ctx, hiddenSize, seqLen)
- x = cb.AttnOut.Forward(ctx, attnOut)
- x = x.Clamp(ctx, -opts.gradClip, opts.gradClip)
- x = cb.AttnPostNorm.Forward(ctx, x, opts.eps)
-
- return residual.Add(ctx, x)
-}
-
-// buildPositionEmbeddings builds sinusoidal position embeddings and projects through linear_pos.
-// Returns [headDim, numHeads, maxSpan] tensor.
-func (cb *AudioConformerBlock) buildPositionEmbeddings(ctx ml.Context, maxSpan int, opts *AudioModelOptions) ml.Tensor {
- halfDim := opts.hiddenSize / 2
- hiddenSize := opts.hiddenSize
-
- // inv_timescales: exp(-i * log(10000) / max(D/2-1, 1))
- logInc := math.Log(10000.0) / math.Max(float64(halfDim-1), 1)
-
- // Sinusoidal embeddings for relative positions [maxPast, maxPast-1, ..., -maxFuture].
- posData := make([]float32, hiddenSize*maxSpan)
- for p := range maxSpan {
- relPos := float64(opts.maxPast - p)
- for d := range halfDim {
- angle := relPos * math.Exp(float64(-d)*logInc)
- posData[p*hiddenSize+d] = float32(math.Sin(angle))
- posData[p*hiddenSize+halfDim+d] = float32(math.Cos(angle))
- }
- }
-
- // Create [hiddenSize, maxSpan] input tensor.
- posEmb := ctx.Input().FromFloats(posData, hiddenSize, maxSpan)
-
- // Project through linear_pos: [hiddenSize, maxSpan] → Mulmat → [numHeads*headDim, maxSpan]
- projPos := cb.LinearPos.Mulmat(ctx, posEmb)
-
- // Reshape to [headDim, numHeads, maxSpan].
- return projPos.Reshape(ctx, opts.headDim, opts.numHeads, maxSpan)
-}
-
-// relativeShiftGGML performs the relative shift to extract correct position logits.
-// Input: [maxSpan, chunkSize, numHeads]. Output: [contextSize, chunkSize, numHeads].
-func (cb *AudioConformerBlock) relativeShiftGGML(ctx ml.Context, x ml.Tensor, maxSpan, chunkSize, contextSize, numHeads int) ml.Tensor {
- // The shift trick: pad ne[0] to contextSize+1, reshape to flatten first two dims,
- // skip first (contextSize+1-maxSpan) elements, take contextSize*chunkSize elements, reshape back.
- padAmt := contextSize + 1 - maxSpan
- if padAmt > 0 {
- x = x.Pad(ctx, padAmt, 0, 0, 0) // [maxSpan+padAmt, chunkSize, numHeads] = [contextSize+1, chunkSize, numHeads]
- }
- // Reshape to [(contextSize+1)*chunkSize, numHeads]
- x = x.Reshape(ctx, (contextSize+1)*chunkSize, numHeads)
- // Take the first contextSize*chunkSize elements (the standard relative shift trick).
- x = x.Slice(ctx, 0, 0, contextSize*chunkSize, 1).Contiguous(ctx)
- // Reshape to [contextSize, chunkSize, numHeads]
- return x.Reshape(ctx, contextSize, chunkSize, numHeads)
-}
-
-// forwardLightConv runs the lightweight depthwise convolution module.
-func (cb *AudioConformerBlock) forwardLightConv(ctx ml.Context, x ml.Tensor, opts *AudioModelOptions, blockIdx int) ml.Tensor {
- residual := x
-
- x = cb.ConvNorm.Forward(ctx, x, opts.eps)
- x = cb.ConvPW1.Forward(ctx, x) // [2*D, T, B]
-
- // GLU: split in half along dim 0, sigmoid gate, multiply.
- d := x.Dim(0) / 2
- data := x.Slice(ctx, 0, 0, d, 1).Contiguous(ctx)
- gate := x.Slice(ctx, 0, d, d*2, 1).Contiguous(ctx).Sigmoid(ctx)
- x = data.Mul(ctx, gate) // [D, T, B]
-
- // Depthwise Conv1d: manual implementation using model weight tensor slices.
- // Kernel cb.ConvDW shape: [K=5, D=1024] (ne[0]=K, ne[1]=D) after shape reversal.
- // Actually in GGML, ne[0]=K=5 contiguous, ne[1]=D=1024.
- // We need per-tap weights [D] and shifted input copies.
- kernelSize := cb.ConvDW.Dim(0) // K=5
- seqLen := x.Dim(1)
-
- // Transpose kernel to [D, K] for per-tap slicing.
- // GGML permute(1,0,2,3): old[0]→pos1, old[1]→pos0 → swap ne[0] and ne[1]
- kernelT := cb.ConvDW.Permute(ctx, 1, 0, 2, 3).Contiguous(ctx) // [D, K]
-
- var convOut ml.Tensor
- for k := range kernelSize {
- shift := kernelSize - 1 - k
- var shifted ml.Tensor
- if shift == 0 {
- shifted = x
- } else {
- trimmed := x.Slice(ctx, 1, 0, seqLen-shift, 1).Contiguous(ctx)
- shifted = trimmed.PadExt(ctx, 0, 0, shift, 0, 0, 0, 0, 0)
- }
-
- wk := kernelT.Slice(ctx, 1, k, k+1, 1).Contiguous(ctx) // [D, 1]
- term := shifted.Mul(ctx, wk)
- if convOut == nil {
- convOut = term
- } else {
- convOut = convOut.Add(ctx, term)
- }
- }
- x = convOut
-
- x = x.Clamp(ctx, -opts.gradClip, opts.gradClip)
- x = cb.NormConv.Forward(ctx, x, opts.eps)
- x = x.SILU(ctx)
- x = cb.ConvPW2.Forward(ctx, x)
-
- return x.Add(ctx, residual)
-}
-
-func newAudioModel(c fs.Config) *AudioModel {
- numLayers := int(c.Uint("audio.block_count", 0))
- if numLayers == 0 {
- return nil
- }
- return &AudioModel{
- Layers: make([]AudioConformerBlock, numLayers),
- }
-}
-
-func newAudioModelOptions(c fs.Config) *AudioModelOptions {
- hiddenSize := int(c.Uint("audio.embedding_length", 0))
- if hiddenSize == 0 {
- return nil
- }
- numHeads := int(c.Uint("audio.attention.head_count", 8))
- headDim := hiddenSize / numHeads
- chunkSize := 12 // default conformer chunk size
- maxPast := 12 // conf_attention_context_left - 1
- maxFuture := 0 // conf_attention_context_right
- convKernel := int(c.Uint("audio.conv_kernel_size", 5))
-
- eps := c.Float("audio.attention.layer_norm_epsilon", 1e-6)
-
- return &AudioModelOptions{
- hiddenSize: hiddenSize,
- numHeads: numHeads,
- headDim: headDim,
- ffnSize: int(c.Uint("audio.feed_forward_length", uint32(hiddenSize*4))),
- numLayers: int(c.Uint("audio.block_count", 12)),
- melBins: int(c.Uint("audio.num_mel_bins", 128)),
- chunkSize: chunkSize,
- maxPast: maxPast,
- maxFuture: maxFuture,
- contextSize: chunkSize + maxPast + maxFuture,
- logitCap: 50.0,
- residualWeight: 0.5,
- gradClip: 1e10,
- convKernelSize: convKernel,
- eps: float32(eps),
- }
-}
-
-// buildCausalValidMaskF32 creates the causal-valid mask for block-local attention.
-// Returns flat [chunkSize * contextSize] float32 data (1.0 = allowed, 0.0 = masked).
-func buildCausalValidMaskF32(chunkSize, maxPast, maxFuture int) []float32 {
- contextSize := chunkSize + maxPast + maxFuture
- upperDiag := maxPast + maxFuture
-
- result := make([]float32, chunkSize*contextSize)
- for r := range chunkSize {
- for c := range contextSize {
- lower := (r <= c) // tril(contextSize, chunkSize) transposed
- upper := (c <= r+upperDiag) // tril(chunkSize, contextSize, diag=upperDiag)
- if lower && upper {
- result[r*contextSize+c] = 1.0
- }
- }
- }
- return result
-}
diff --git a/model/models/gemma4/model_text.go b/model/models/gemma4/model_text.go
deleted file mode 100644
index 86397affd..000000000
--- a/model/models/gemma4/model_text.go
+++ /dev/null
@@ -1,475 +0,0 @@
-package gemma4
-
-import (
- "math"
-
- "github.com/ollama/ollama/fs"
- "github.com/ollama/ollama/kvcache"
- "github.com/ollama/ollama/ml"
- "github.com/ollama/ollama/ml/nn"
- "github.com/ollama/ollama/ml/nn/rope"
- "github.com/ollama/ollama/model/input"
-)
-
-const (
- cacheTypeSWA = iota
- cacheTypeCausal
-)
-
-type TextOptions struct {
- hiddenSize int
- numHeads, numKVHeads int
- numGlobalKVHeads int
- headDim, globalHeadDim int
- hiddenLayers int
- hiddenSizePerLayerInput int
-
- eps float32
- ropeBase float32
- ropeLocalBase float32
- partialRotaryDims int // RoPE dims for full-attention (global) layers
-
- slidingWindowPattern []bool
- // kvDonorMap maps shared layer index -> donor layer index.
- // Donor is the last non-shared layer of the same type (sliding/full).
- kvDonorMap map[int]int
-
- finalLogitSoftcap float32
-
- numExperts int
- numExpertsUsed int
-}
-
-func (o *TextOptions) isLocal(layer int) bool {
- if layer < len(o.slidingWindowPattern) {
- return o.slidingWindowPattern[layer]
- }
- return false
-}
-
-func (o *TextOptions) ropeForLayer(layer int) (base float32, dims int) {
- if o.isLocal(layer) {
- return o.ropeLocalBase, o.headDim
- }
- return o.ropeBase, o.partialRotaryDims
-}
-
-func (o *TextOptions) kvHeadsForLayer(layer int) int {
- if o.isLocal(layer) {
- return o.numKVHeads
- }
- if o.numGlobalKVHeads > 0 {
- return o.numGlobalKVHeads
- }
- return o.numKVHeads
-}
-
-func (o *TextOptions) headDimForLayer(layer int) int {
- if o.isLocal(layer) {
- return o.headDim
- }
- return o.globalHeadDim
-}
-
-type TextModel struct {
- TokenEmbedding *nn.Embedding `gguf:"token_embd"`
- *PerLayerProjector
- Layers []TextLayer `gguf:"blk"`
- OutputNorm *nn.RMSNorm `gguf:"output_norm"`
- Output *nn.Linear `gguf:"output,alt:token_embd"`
- TextOptions
-}
-
-func newTextModel(c fs.Config) *TextModel {
- numLayers := int(c.Uint("block_count"))
-
- // Head dimensions: key_length is global head dim, key_length_swa is local (SWA) head dim.
- globalHeadDim := int(c.Uint("attention.key_length", 512))
- headDim := int(c.Uint("attention.key_length_swa", 256))
-
- // RoPE dimensions for global (full attention) layers with proportional RoPE.
- // The freq_factors tensor handles partial rotation (1.0 for rotated pairs,
- // 1e30 for non-rotated), so ropeDims equals the full global head dim.
- partialRotaryDims := int(c.Uint("rope.dimension_count", 0))
- if partialRotaryDims == 0 {
- partialFactor := c.Float("rope.partial_rotary_factor", 1.0)
- partialRotaryDims = int(float32(globalHeadDim) * partialFactor)
- }
-
- ropeBase := c.Float("rope.freq_base", 1000000.0)
- ropeLocalBase := c.Float("rope.freq_base_swa", 0)
- if ropeLocalBase == 0 {
- ropeLocalBase = c.Float("rope.local.freq_base", 10000.0)
- }
-
- numGlobalKVHeads := int(c.Uint("attention.global_head_count_kv", 0))
- slidingPattern := c.Bools("attention.sliding_window_pattern")
-
- // KV heads: try per-layer array first (MoE models), then fall back to scalar
- numKVHeads := 0
- kvHeadsArray := c.Ints("attention.head_count_kv")
- if len(kvHeadsArray) > 0 {
- numKVHeads = int(kvHeadsArray[0])
- if numGlobalKVHeads == 0 && len(slidingPattern) > 0 {
- for i, isLocal := range slidingPattern {
- if !isLocal && i < len(kvHeadsArray) {
- numGlobalKVHeads = int(kvHeadsArray[i])
- break
- }
- }
- }
- }
- if numKVHeads == 0 {
- numKVHeads = int(c.Uint("attention.head_count_kv", 0))
- }
-
- // Compute KV sharing donor map (same logic as MLX)
- sharedLayers := int(c.Uint("attention.shared_kv_layers", 0))
- kvDonorMap := make(map[int]int)
- if sharedLayers > 0 && len(slidingPattern) > 0 {
- firstShared := numLayers - sharedLayers
- for i := firstShared; i < numLayers; i++ {
- isLocal := slidingPattern[i]
- // Find last non-shared layer of same type
- for j := firstShared - 1; j >= 0; j-- {
- if slidingPattern[j] == isLocal {
- kvDonorMap[i] = j
- break
- }
- }
- }
- }
-
- return &TextModel{
- Layers: make([]TextLayer, numLayers),
- TextOptions: TextOptions{
- hiddenSize: int(c.Uint("embedding_length")),
- numHeads: int(c.Uint("attention.head_count")),
- numKVHeads: numKVHeads,
- numGlobalKVHeads: numGlobalKVHeads,
- headDim: headDim,
- globalHeadDim: globalHeadDim,
- hiddenLayers: numLayers,
- hiddenSizePerLayerInput: int(c.Uint("embedding_length_per_layer_input", 0)),
- eps: c.Float("attention.layer_norm_rms_epsilon", 1e-06),
- ropeBase: ropeBase,
- ropeLocalBase: ropeLocalBase,
- partialRotaryDims: partialRotaryDims,
- slidingWindowPattern: slidingPattern,
- kvDonorMap: kvDonorMap,
- finalLogitSoftcap: c.Float("final_logit_softcapping", 0.0),
- numExperts: int(c.Uint("expert_count", 0)),
- numExpertsUsed: int(c.Uint("expert_used_count", 0)),
- },
- }
-}
-
-func (m *TextModel) Forward(ctx ml.Context, batch input.Batch, cache kvcache.Cache) ml.Tensor {
- positions := ctx.Input().FromInts(batch.Positions, len(batch.Positions))
-
- hiddenState := m.TokenEmbedding.Forward(ctx, batch.Inputs)
- hiddenState = hiddenState.Scale(ctx, math.Sqrt(float64(m.hiddenSize)))
-
- // Inject vision embeddings into the hidden state
- var except []int
- for _, image := range batch.Multimodal {
- visionOutputs := image.Multimodal[0].Tensor
- ctx.Forward(visionOutputs.Copy(ctx, hiddenState.View(ctx, image.Index*hiddenState.Stride(1), visionOutputs.Dim(0)*visionOutputs.Dim(1))))
-
- for i := range visionOutputs.Dim(1) {
- except = append(except, image.Index+i)
- }
- }
-
- // PLE
- var perLayerInputs ml.Tensor
- if m.PerLayerProjector != nil {
- perLayerInputs = m.PerLayerProjector.Forward(ctx, batch, hiddenState, &m.TextOptions)
- }
-
- for i := range len(m.Layers) {
- layer := m.Layers[i]
- if cache != nil {
- cache.SetLayer(i)
- cacheType := cacheTypeSWA
- if !m.isLocal(i) {
- cacheType = cacheTypeCausal
- }
- wc := cache.(*kvcache.WrapperCache)
- wc.SetLayerType(cacheType)
-
- if causal, ok := wc.UnderlyingCache().(*kvcache.Causal); ok {
- causal.SetCausal(ctx, kvcache.CausalOptions{Except: except})
- }
- }
-
- var lastLayerOutputs ml.Tensor
- if i == len(m.Layers)-1 {
- lastLayerOutputs = batch.Outputs
- }
-
- var perLayerInput ml.Tensor
- if perLayerInputs != nil {
- perLayerInput = perLayerInputs.View(ctx, i*perLayerInputs.Stride(1), perLayerInputs.Dim(0), perLayerInputs.Stride(2), perLayerInputs.Dim(2))
- }
-
- // KV sharing: layers >= firstShared reuse K/V from donor layers
- isShared := false
- if donorLayer, ok := m.kvDonorMap[i]; ok {
- // Set cache layer to donor so Get() reads donor's K/V
- cache.SetLayer(donorLayer)
- isShared = true
- }
- hiddenState = layer.Forward(ctx, i, hiddenState, positions, perLayerInput, lastLayerOutputs, cache, isShared, &m.TextOptions)
- }
-
- return m.OutputNorm.Forward(ctx, hiddenState, m.eps)
-}
-
-// PerLayerProjector implements PLE.
-type PerLayerProjector struct {
- TokenEmbedding *nn.Embedding `gguf:"per_layer_token_embd"`
- Projector *nn.Linear `gguf:"per_layer_model_proj"`
- Norm *nn.RMSNorm `gguf:"per_layer_proj_norm"`
-}
-
-func (p *PerLayerProjector) Forward(ctx ml.Context, batch input.Batch, inputs ml.Tensor, opts *TextOptions) ml.Tensor {
- inputsPerLayer := p.TokenEmbedding.Forward(ctx, batch.Inputs)
- inputsPerLayer = inputsPerLayer.Scale(ctx, math.Sqrt(float64(opts.hiddenSizePerLayerInput)))
- // Reshape to [pleDim, numLayers, numTokens] — matching projection shape
- inputsPerLayer = inputsPerLayer.Reshape(ctx, opts.hiddenSizePerLayerInput, opts.hiddenLayers, inputs.Dim(1))
-
- perLayerProjection := p.Projector.Forward(ctx, inputs)
- perLayerProjection = perLayerProjection.Scale(ctx, 1.0/math.Sqrt(float64(opts.hiddenSize)))
- perLayerProjection = perLayerProjection.Reshape(ctx, opts.hiddenSizePerLayerInput, opts.hiddenLayers, inputs.Dim(1))
- perLayerProjection = p.Norm.Forward(ctx, perLayerProjection, opts.eps)
-
- if inputsPerLayer != nil {
- perLayerProjection = perLayerProjection.Add(ctx, inputsPerLayer)
- perLayerProjection = perLayerProjection.Scale(ctx, 1/math.Sqrt(2))
- }
-
- return perLayerProjection
-}
-
-type TextSelfAttention struct {
- Query *nn.Linear `gguf:"attn_q"`
- QueryNorm *nn.RMSNorm `gguf:"attn_q_norm"`
- Key *nn.Linear `gguf:"attn_k"`
- KeyNorm *nn.RMSNorm `gguf:"attn_k_norm"`
- Value *nn.Linear `gguf:"attn_v"`
- Output *nn.Linear `gguf:"attn_output"`
- RopeFactors ml.Tensor `gguf:"rope_freqs.weight"` // proportional RoPE freq_factors
-}
-
-func (sa *TextSelfAttention) Forward(ctx ml.Context, layer int, hiddenState, positions ml.Tensor, cache kvcache.Cache, sharedKV bool, opts *TextOptions) ml.Tensor {
- batchSize := hiddenState.Dim(1)
- hd := opts.headDimForLayer(layer)
- kvHeads := opts.kvHeadsForLayer(layer)
- ropeBase, ropeDims := opts.ropeForLayer(layer)
-
- q := sa.Query.Forward(ctx, hiddenState)
- q = q.Reshape(ctx, hd, opts.numHeads, batchSize)
- q = sa.QueryNorm.Forward(ctx, q, opts.eps)
-
- var k, v ml.Tensor
- if !sharedKV {
- k = sa.Key.Forward(ctx, hiddenState)
- k = k.Reshape(ctx, hd, kvHeads, batchSize)
-
- if sa.Value != nil {
- v = sa.Value.Forward(ctx, hiddenState)
- v = v.Reshape(ctx, hd, kvHeads, batchSize)
- } else {
- // K=V: use raw K projection (before K norm) as V
- v = k
- }
-
- k = sa.KeyNorm.Forward(ctx, k, opts.eps)
- v = v.RMSNorm(ctx, nil, opts.eps) // V norm: unweighted RMSNorm
- }
-
- // RoPE with proportional freq_factors on global layers
- ropeOpts := []func(*rope.Options){rope.WithTypeNeoX()}
- if sa.RopeFactors != nil && !opts.isLocal(layer) {
- ropeOpts = append(ropeOpts, rope.WithFactors(sa.RopeFactors))
- }
- q = nn.RoPE(ctx, q, positions, ropeDims, ropeBase, 1.0, ropeOpts...)
- if k != nil {
- k = nn.RoPE(ctx, k, positions, ropeDims, ropeBase, 1.0, ropeOpts...)
- }
-
- attention := nn.Attention(ctx, q, k, v, 1.0, cache)
-
- attention = attention.Reshape(ctx, hd*opts.numHeads, batchSize)
- return sa.Output.Forward(ctx, attention)
-}
-
-type TextMLP struct {
- Gate *nn.Linear `gguf:"ffn_gate"`
- Up *nn.Linear `gguf:"ffn_up"`
- Down *nn.Linear `gguf:"ffn_down"`
-}
-
-func (mlp *TextMLP) Forward(ctx ml.Context, hiddenState ml.Tensor) ml.Tensor {
- hiddenState = mlp.Gate.Forward(ctx, hiddenState).GELU(ctx, mlp.Up.Forward(ctx, hiddenState))
- return mlp.Down.Forward(ctx, hiddenState)
-}
-
-// TextRouter implements the Gemma 4 MoE router.
-type TextRouter struct {
- Proj *nn.Linear `gguf:"ffn_gate_inp"`
- Scale ml.Tensor `gguf:"ffn_gate_inp.scale"`
-}
-
-func (r *TextRouter) Forward(ctx ml.Context, hiddenState ml.Tensor, opts *TextOptions) (routingWeights, selectedExperts ml.Tensor) {
- // RMSNorm without learned weight
- x := hiddenState.RMSNorm(ctx, nil, opts.eps)
- // Scale by 1/sqrt(hidden_size)
- x = x.Scale(ctx, 1.0/math.Sqrt(float64(opts.hiddenSize)))
- // Multiply by learned scale parameter
- x = x.Mul(ctx, r.Scale)
- // Project to expert logits
- expertScores := r.Proj.Forward(ctx, x)
- // Softmax over experts
- routingWeights = expertScores.Softmax(ctx)
- // TopK expert selection
- selectedExperts = routingWeights.TopK(ctx, opts.numExpertsUsed)
- return routingWeights, selectedExperts
-}
-
-// TextMoEBlock implements the Gemma 4 sparse MoE.
-type TextMoEBlock struct {
- GateUp *nn.LinearBatch `gguf:"ffn_gate_up_exps"`
- Gate *nn.LinearBatch `gguf:"ffn_gate_exps"`
- Up *nn.LinearBatch `gguf:"ffn_up_exps"`
- Down *nn.LinearBatch `gguf:"ffn_down_exps"`
- DownScale ml.Tensor `gguf:"ffn_down_exps.scale,alt:ffn_gate_inp.per_expert_scale"`
-}
-
-func (moe *TextMoEBlock) Forward(ctx ml.Context, hiddenState, routingWeights, selectedExperts ml.Tensor, opts *TextOptions) ml.Tensor {
- // Select routing weights for chosen experts and renormalize
- routingWeights = routingWeights.Reshape(ctx, 1, opts.numExperts, hiddenState.Dim(1)).Rows(ctx, selectedExperts)
- routingWeights = routingWeights.Reshape(ctx, opts.numExpertsUsed, hiddenState.Dim(1))
- routingWeights = routingWeights.Div(ctx, routingWeights.SumRows(ctx))
- routingWeights = routingWeights.Reshape(ctx, 1, opts.numExpertsUsed, hiddenState.Dim(1))
-
- hiddenState = hiddenState.Reshape(ctx, hiddenState.Dim(0), 1, hiddenState.Dim(1))
-
- // Expert computation using LinearBatch (MulmatID selecting experts by index)
- var gateOut, upOut ml.Tensor
- if moe.GateUp != nil && moe.GateUp.Weight != nil {
- gateUp := moe.GateUp.Forward(ctx, hiddenState, selectedExperts)
- nFF := gateUp.Dim(0) / 2
- gateOut = gateUp.Slice(ctx, 0, 0, nFF, 1)
- upOut = gateUp.Slice(ctx, 0, nFF, gateUp.Dim(0), 1)
- } else {
- gateOut = moe.Gate.Forward(ctx, hiddenState, selectedExperts)
- upOut = moe.Up.Forward(ctx, hiddenState, selectedExperts)
- }
- hiddenState = gateOut.GELU(ctx, upOut)
- experts := moe.Down.Forward(ctx, hiddenState, selectedExperts)
-
- // Apply per-expert down projection scale when present.
- if moe.DownScale != nil {
- expertScales := moe.DownScale.Reshape(ctx, opts.numExperts, 1)
- expertScales = expertScales.Repeat(ctx, 1, hiddenState.Dim(2))
- expertScales = expertScales.Reshape(ctx, 1, opts.numExperts, hiddenState.Dim(2)).Rows(ctx, selectedExperts)
- expertScales = expertScales.Reshape(ctx, opts.numExpertsUsed, hiddenState.Dim(2))
- expertScales = expertScales.Reshape(ctx, 1, opts.numExpertsUsed, hiddenState.Dim(2))
- experts = experts.Mul(ctx, expertScales)
- }
-
- // Apply routing weights
- experts = experts.Mul(ctx, routingWeights)
-
- // Sum across experts
- nextStates := experts.View(ctx, 0, experts.Dim(0), experts.Stride(2), experts.Dim(2))
- for i := 1; i < opts.numExpertsUsed; i++ {
- nextStates = nextStates.Add(ctx, experts.View(ctx, i*experts.Stride(1), experts.Dim(0), experts.Stride(2), experts.Dim(2)))
- }
-
- return nextStates
-}
-
-type TextLayer struct {
- AttentionNorm *nn.RMSNorm `gguf:"attn_norm"`
- SelfAttention *TextSelfAttention
- PostAttentionNorm *nn.RMSNorm `gguf:"post_attention_norm,alt:attn_post_norm"`
- MLPNorm *nn.RMSNorm `gguf:"ffn_norm,alt:ffn_pre_norm"`
- MLP *TextMLP
- PostMLPNorm *nn.RMSNorm `gguf:"post_ffw_norm,alt:ffn_post_norm"`
-
- // MoE (present only for models with enable_moe_block=true)
- Router *TextRouter
- MoE *TextMoEBlock
- MoENorm *nn.RMSNorm `gguf:"pre_ffw_norm_2,alt:ffn_pre_norm_2"`
- PostMoENorm *nn.RMSNorm `gguf:"post_ffw_norm_2,alt:ffn_post_norm_2"`
- PostMLPNorm1 *nn.RMSNorm `gguf:"post_ffw_norm_1,alt:ffn_post_norm_1"` // used instead of PostMLPNorm when MoE is present
-
- PerLayerInputGate *nn.Linear `gguf:"inp_gate"`
- PerLayerProjection *nn.Linear `gguf:"proj"`
- PostPerLayerNorm *nn.RMSNorm `gguf:"post_norm"`
- LayerScalar ml.Tensor `gguf:"layer_scalar,alt:layer_output_scale.weight"`
-}
-
-func (l *TextLayer) Forward(ctx ml.Context, layer int, hiddenState, positions, perLayerInput, outputs ml.Tensor, cache kvcache.Cache, sharedKV bool, opts *TextOptions) ml.Tensor {
- residual := hiddenState
-
- hiddenState = l.AttentionNorm.Forward(ctx, hiddenState, opts.eps)
- hiddenState = l.SelfAttention.Forward(ctx, layer, hiddenState, positions, cache, sharedKV, opts)
- hiddenState = l.PostAttentionNorm.Forward(ctx, hiddenState, opts.eps)
-
- if outputs != nil {
- hiddenState = hiddenState.Rows(ctx, outputs)
- residual = residual.Rows(ctx, outputs)
- if perLayerInput != nil {
- perLayerInput = perLayerInput.Rows(ctx, outputs)
- }
- }
-
- hiddenState = hiddenState.Add(ctx, residual)
- residual = hiddenState
-
- // MLP (+ optional MoE in parallel)
- hasSplitExperts := l.MoE != nil && l.MoE.Gate != nil && l.MoE.Up != nil && l.MoE.Gate.Weight != nil && l.MoE.Up.Weight != nil
- hasFusedExperts := l.MoE != nil && l.MoE.GateUp != nil && l.MoE.GateUp.Weight != nil
- if l.Router != nil && l.MoE != nil && l.MoE.Down != nil && l.MoE.Down.Weight != nil && (hasSplitExperts || hasFusedExperts) {
- // MoE layers: run MLP and MoE in parallel, sum results
- mlpState := l.MLPNorm.Forward(ctx, hiddenState, opts.eps)
- mlpState = l.MLP.Forward(ctx, mlpState)
- mlpState = l.PostMLPNorm1.Forward(ctx, mlpState, opts.eps)
-
- routingWeights, selectedExperts := l.Router.Forward(ctx, hiddenState, opts)
- moeState := l.MoENorm.Forward(ctx, hiddenState, opts.eps)
- moeState = l.MoE.Forward(ctx, moeState, routingWeights, selectedExperts, opts)
- moeState = l.PostMoENorm.Forward(ctx, moeState, opts.eps)
-
- // Combine MLP + MoE, apply outer post-FFN norm, then add residual
- combined := mlpState.Add(ctx, moeState)
- combined = l.PostMLPNorm.Forward(ctx, combined, opts.eps)
- hiddenState = combined.Add(ctx, residual)
- } else {
- // Dense layers: MLP only
- hiddenState = l.MLPNorm.Forward(ctx, hiddenState, opts.eps)
- hiddenState = l.MLP.Forward(ctx, hiddenState)
- hiddenState = l.PostMLPNorm.Forward(ctx, hiddenState, opts.eps)
- hiddenState = hiddenState.Add(ctx, residual)
- }
-
- // PLE injection (after MLP residual)
- if perLayerInput != nil && l.PerLayerInputGate != nil {
- pleState := l.PerLayerInputGate.Forward(ctx, hiddenState)
- pleState = pleState.GELU(ctx, perLayerInput)
- pleState = l.PerLayerProjection.Forward(ctx, pleState)
- pleState = l.PostPerLayerNorm.Forward(ctx, pleState, opts.eps)
- hiddenState = hiddenState.Add(ctx, pleState)
- }
-
- // Layer scalar applied at end of layer (full-attention layers only)
- if l.LayerScalar != nil {
- hiddenState = hiddenState.Mul(ctx, l.LayerScalar)
- }
-
- return hiddenState
-}
diff --git a/model/models/gemma4/model_vision.go b/model/models/gemma4/model_vision.go
deleted file mode 100644
index c0ecccce3..000000000
--- a/model/models/gemma4/model_vision.go
+++ /dev/null
@@ -1,384 +0,0 @@
-package gemma4
-
-import (
- "math"
-
- "github.com/ollama/ollama/fs"
- "github.com/ollama/ollama/ml"
- "github.com/ollama/ollama/ml/nn"
- "github.com/ollama/ollama/ml/nn/rope"
-)
-
-const batchSize = 1
-
-// ClippableLinear is a linear layer with optional input/output clamping.
-// Required by Gemma4 vision encoder for numerical stability with F16 weights.
-type ClippableLinear struct {
- Weight ml.Tensor `gguf:"weight"`
-
- InputMin ml.Tensor `gguf:"input_min"`
- InputMax ml.Tensor `gguf:"input_max"`
- OutputMin ml.Tensor `gguf:"output_min"`
- OutputMax ml.Tensor `gguf:"output_max"`
-
- inMin, inMax, outMin, outMax float32
- hasClamp bool
- clampsLoaded bool
-}
-
-func scalarValue(t ml.Tensor) (float32, bool) {
- if t == nil {
- return 0, false
- }
-
- data := t.BackendGet()
- if len(data) == 0 {
- return 0, false
- }
-
- return data[0], true
-}
-
-func (l *ClippableLinear) loadClampFromScalars() {
- if l.clampsLoaded {
- return
- }
- l.clampsLoaded = true
-
- const (
- defaultMin = -math.MaxFloat32
- defaultMax = math.MaxFloat32
- )
-
- inMin, hasInMin := scalarValue(l.InputMin)
- inMax, hasInMax := scalarValue(l.InputMax)
- outMin, hasOutMin := scalarValue(l.OutputMin)
- outMax, hasOutMax := scalarValue(l.OutputMax)
-
- if !(hasInMin || hasInMax || hasOutMin || hasOutMax) {
- return
- }
-
- l.hasClamp = true
- l.inMin = defaultMin
- l.inMax = defaultMax
- l.outMin = defaultMin
- l.outMax = defaultMax
-
- if hasInMin {
- l.inMin = inMin
- }
- if hasInMax {
- l.inMax = inMax
- }
- if hasOutMin {
- l.outMin = outMin
- }
- if hasOutMax {
- l.outMax = outMax
- }
-}
-
-func (l *ClippableLinear) Forward(ctx ml.Context, x ml.Tensor) ml.Tensor {
- if l.hasClamp {
- x = x.Clamp(ctx, l.inMin, l.inMax)
- }
- out := l.Weight.Mulmat(ctx, x)
- if l.hasClamp {
- out = out.Clamp(ctx, l.outMin, l.outMax)
- }
- return out
-}
-
-// InitClamp distributes packed clamp values from v.clamp_data to ClippableLinear structs.
-// If scalar clamp tensors (input_min/max, output_min/max) are present, they are used too.
-// Layout: numLayers × 7 linears (q,k,v,out,gate,up,down) × 4 floats (inMin,inMax,outMin,outMax)
-// then 4 floats for the projector.
-func (m *VisionModel) InitClamp(proj *MultiModalProjector) {
- if m.clampInitDone {
- return
- }
- m.clampInitDone = true
-
- linears := func(l *VisionEncoderLayer) []*ClippableLinear {
- return []*ClippableLinear{
- l.SelfAttention.Query, l.SelfAttention.Key, l.SelfAttention.Value,
- l.SelfAttention.Output, l.MLP.Gate, l.MLP.Up, l.MLP.Down,
- }
- }
-
- for i := range m.Layers {
- for _, cl := range linears(&m.Layers[i]) {
- if cl != nil {
- cl.loadClampFromScalars()
- }
- }
- }
- if proj != nil && proj.Projection != nil {
- proj.Projection.loadClampFromScalars()
- }
-
- // Load packed clamp data when present (legacy Ollama format).
- if m.ClampData == nil {
- return
- }
-
- // Read all clamp values from packed F32 tensor
- data := m.ClampData.BackendGet()
- if len(data) == 0 {
- return
- }
-
- // Distribute to layer linears: 7 per layer × 4 values each
- for i := range m.Layers {
- for li, cl := range linears(&m.Layers[i]) {
- if cl == nil {
- continue
- }
- idx := (i*7 + li) * 4
- if idx+3 < len(data) {
- cl.inMin = data[idx]
- cl.inMax = data[idx+1]
- cl.outMin = data[idx+2]
- cl.outMax = data[idx+3]
- cl.hasClamp = true
- }
- }
- }
-
- // Projector clamp values (last 4 floats)
- if proj != nil && proj.Projection != nil {
- projIdx := len(m.Layers) * 7 * 4
- if projIdx+3 < len(data) {
- proj.Projection.inMin = data[projIdx]
- proj.Projection.inMax = data[projIdx+1]
- proj.Projection.outMin = data[projIdx+2]
- proj.Projection.outMax = data[projIdx+3]
- proj.Projection.hasClamp = true
- }
- }
-}
-
-type VisionSelfAttention struct {
- Query *ClippableLinear `gguf:"attn_q"`
- Key *ClippableLinear `gguf:"attn_k"`
- Value *ClippableLinear `gguf:"attn_v"`
- QueryNorm *nn.RMSNorm `gguf:"attn_q_norm"`
- KeyNorm *nn.RMSNorm `gguf:"attn_k_norm"`
- Output *ClippableLinear `gguf:"attn_out"`
-}
-
-func (sa *VisionSelfAttention) Forward(ctx ml.Context, hiddenState, posX, posY, attnMask ml.Tensor, opts *VisionModelOptions) ml.Tensor {
- numPatches := hiddenState.Dim(1)
- headDim := opts.hiddenSize / opts.numHeads
-
- query := sa.Query.Forward(ctx, hiddenState)
- key := sa.Key.Forward(ctx, hiddenState)
- value := sa.Value.Forward(ctx, hiddenState)
-
- query = query.Reshape(ctx, headDim, opts.numHeads, numPatches, batchSize)
- key = key.Reshape(ctx, headDim, opts.numHeads, numPatches, batchSize)
- value = value.Reshape(ctx, headDim, opts.numHeads, numPatches, batchSize)
-
- // Q/K norms (Gemma-style: x * (1 + weight) / rms(x))
- query = sa.QueryNorm.Forward(ctx, query, opts.eps)
- key = sa.KeyNorm.Forward(ctx, key, opts.eps)
-
- // V norm (RMSNorm without learned weights)
- value = value.RMSNorm(ctx, nil, opts.eps)
-
- // 2D RoPE: split head dim in half, apply NeoX RoPE with x positions to first half,
- // y positions to second half, then concatenate.
- halfDim := headDim / 2
- ropeOpts := rope.WithTypeNeoX()
-
- qFirst := query.View(ctx, 0, halfDim, query.Stride(1), opts.numHeads, query.Stride(2), numPatches)
- qFirst = nn.RoPE(ctx, qFirst, posX, halfDim, opts.ropeTheta, 1.0, ropeOpts)
-
- kFirst := key.View(ctx, 0, halfDim, key.Stride(1), opts.numHeads, key.Stride(2), numPatches)
- kFirst = nn.RoPE(ctx, kFirst, posX, halfDim, opts.ropeTheta, 1.0, ropeOpts)
-
- halfOffset := halfDim * query.Stride(0)
- qSecond := query.View(ctx, halfOffset, halfDim, query.Stride(1), opts.numHeads, query.Stride(2), numPatches)
- qSecond = nn.RoPE(ctx, qSecond, posY, halfDim, opts.ropeTheta, 1.0, ropeOpts)
-
- halfOffsetK := halfDim * key.Stride(0)
- kSecond := key.View(ctx, halfOffsetK, halfDim, key.Stride(1), opts.numHeads, key.Stride(2), numPatches)
- kSecond = nn.RoPE(ctx, kSecond, posY, halfDim, opts.ropeTheta, 1.0, ropeOpts)
-
- query = qFirst.Concat(ctx, qSecond, 0)
- key = kFirst.Concat(ctx, kSecond, 0)
-
- // Use flash attention for numerical stability (handles large attention scores
- // from unclamped RMSNorm weights, e.g. 26B has addOne weights up to 19.5)
- attention := nn.Attention(ctx, query, key, value, 1.0, nil)
- attention = attention.Reshape(ctx, opts.hiddenSize, attention.Dim(2), batchSize)
-
- return sa.Output.Forward(ctx, attention)
-}
-
-type VisionMLP struct {
- Gate *ClippableLinear `gguf:"ffn_gate"`
- Up *ClippableLinear `gguf:"ffn_up"`
- Down *ClippableLinear `gguf:"ffn_down"`
-}
-
-func (mlp *VisionMLP) Forward(ctx ml.Context, hiddenState ml.Tensor) ml.Tensor {
- gate := mlp.Gate.Forward(ctx, hiddenState)
- up := mlp.Up.Forward(ctx, hiddenState)
- hiddenState = gate.QuickGELU(ctx, up)
- return mlp.Down.Forward(ctx, hiddenState)
-}
-
-type VisionEncoderLayer struct {
- AttentionNorm *nn.RMSNorm `gguf:"ln1"`
- SelfAttention *VisionSelfAttention
- PostAttentionNorm *nn.RMSNorm `gguf:"attn_post_norm"`
-
- FFNNorm *nn.RMSNorm `gguf:"ln2"`
- MLP *VisionMLP
- PostFFNNorm *nn.RMSNorm `gguf:"ffn_post_norm"`
-
- LayerOutputScale ml.Tensor `gguf:"out_scale.weight"`
-}
-
-func (e *VisionEncoderLayer) Forward(ctx ml.Context, hiddenState, posX, posY, attnMask ml.Tensor, opts *VisionModelOptions) ml.Tensor {
- residual := hiddenState
-
- // Pre-attention norm -> self attention -> post-attention norm
- hiddenState = e.AttentionNorm.Forward(ctx, hiddenState, opts.eps)
- hiddenState = e.SelfAttention.Forward(ctx, hiddenState, posX, posY, attnMask, opts)
- hiddenState = e.PostAttentionNorm.Forward(ctx, hiddenState, opts.eps)
-
- // Residual connection
- hiddenState = hiddenState.Add(ctx, residual)
- residual = hiddenState
-
- // Pre-FFN norm -> FFN -> post-FFN norm
- hiddenState = e.FFNNorm.Forward(ctx, hiddenState, opts.eps)
- hiddenState = e.MLP.Forward(ctx, hiddenState)
- hiddenState = e.PostFFNNorm.Forward(ctx, hiddenState, opts.eps)
-
- // Residual connection
- hiddenState = hiddenState.Add(ctx, residual)
-
- // Per-layer output scale
- if e.LayerOutputScale != nil {
- hiddenState = hiddenState.Mul(ctx, e.LayerOutputScale)
- }
-
- return hiddenState
-}
-
-type VisionModelOptions struct {
- hiddenSize int
- numHeads int
- patchSize int
- nMerge int
- eps float32
- ropeTheta float32
-}
-
-type VisionModel struct {
- PatchEmbedding *nn.Conv2D `gguf:"patch_embd"`
- PositionEmbedding ml.Tensor `gguf:"position_embd.weight"`
- ClampData ml.Tensor `gguf:"clamp_data"`
- StdBias ml.Tensor `gguf:"std_bias"`
- StdScale ml.Tensor `gguf:"std_scale"`
-
- Layers []VisionEncoderLayer `gguf:"blk"`
-
- *VisionModelOptions
- clampInitDone bool
-}
-
-func (m *VisionModel) Forward(ctx ml.Context, pixelValues ml.Tensor, numPatchesX, numPatchesY int) ml.Tensor {
- numPatches := numPatchesX * numPatchesY
-
- // Patch embedding via Conv2D
- hiddenState := m.PatchEmbedding.Forward(ctx, pixelValues, m.patchSize, m.patchSize, 0, 0, 1, 1)
- hiddenState = hiddenState.Reshape(ctx, numPatches, m.hiddenSize)
- hiddenState = hiddenState.Permute(ctx, 1, 0, 2, 3).Contiguous(ctx)
-
- // Conv2D with F16 weights produces F16 output via im2col; cast to F32 for encoder precision
- hiddenState = hiddenState.Cast(ctx, ml.DTypeF32)
-
- // 2D positional embeddings from 3D tensor [nEmbd, maxPos, 2]
- posSize := m.PositionEmbedding.Dim(1)
- nb1 := m.PositionEmbedding.Stride(1)
- tblX := m.PositionEmbedding.View(ctx, 0, m.hiddenSize, nb1, posSize)
- tblY := m.PositionEmbedding.View(ctx, posSize*nb1, m.hiddenSize, nb1, posSize)
-
- // Position indices for patches
- posXData := make([]int32, numPatches)
- posYData := make([]int32, numPatches)
- for i := range numPatches {
- posXData[i] = int32(i % numPatchesX)
- posYData[i] = int32(i / numPatchesX)
- }
-
- posXEmb := ctx.Input().FromInts(posXData, numPatches)
- posYEmb := ctx.Input().FromInts(posYData, numPatches)
-
- hiddenState = hiddenState.Add(ctx, tblX.Rows(ctx, posXEmb))
- hiddenState = hiddenState.Add(ctx, tblY.Rows(ctx, posYEmb))
-
- // No attention mask — all positions are real patches
- var attnMask ml.Tensor
-
- // RoPE positions
- posXRope := ctx.Input().FromInts(posXData, numPatches)
- posYRope := ctx.Input().FromInts(posYData, numPatches)
-
- // Vision transformer layers
- for i := range m.Layers {
- hiddenState = m.Layers[i].Forward(ctx, hiddenState, posXRope, posYRope, attnMask, m.VisionModelOptions)
- }
-
- return hiddenState
-}
-
-func newVisionModel(c fs.Config) *VisionModel {
- return &VisionModel{
- Layers: make([]VisionEncoderLayer, c.Uint("vision.block_count")),
- VisionModelOptions: &VisionModelOptions{
- hiddenSize: int(c.Uint("vision.embedding_length")),
- numHeads: int(c.Uint("vision.attention.head_count")),
- patchSize: int(c.Uint("vision.patch_size", 16)),
- nMerge: int(c.Uint("vision.projector.scale_factor", 3)),
- eps: c.Float("vision.attention.layer_norm_epsilon", 1e-6),
- ropeTheta: 100.0,
- },
- }
-}
-
-func visionPoolAndProject(ctx ml.Context, hiddenState ml.Tensor, numPatchesX, numPatchesY int, opts *VisionModelOptions, proj *MultiModalProjector, stdBias, stdScale ml.Tensor) ml.Tensor {
- hiddenSize := opts.hiddenSize
-
- // Reshape from [hiddenSize, numPatches] to spatial layout for pooling
- hiddenState = hiddenState.Permute(ctx, 1, 0, 2, 3).Contiguous(ctx)
- hiddenState = hiddenState.Reshape(ctx, numPatchesX, numPatchesY, hiddenSize)
-
- // AvgPool2D with kernel=stride=nMerge
- hiddenState = hiddenState.AvgPool2D(ctx, opts.nMerge, opts.nMerge, 0)
-
- // Reshape back to [hiddenSize, numMergedPatches]
- mergedX := numPatchesX / opts.nMerge
- mergedY := numPatchesY / opts.nMerge
- hiddenState = hiddenState.Reshape(ctx, mergedX*mergedY, hiddenSize)
- hiddenState = hiddenState.Permute(ctx, 1, 0, 2, 3).Contiguous(ctx)
-
- hiddenState = hiddenState.Cast(ctx, ml.DTypeF32)
- hiddenState = hiddenState.Scale(ctx, math.Sqrt(float64(hiddenSize)))
-
- // Optional vision standardization before projection.
- if stdBias != nil && stdScale != nil {
- hiddenState = hiddenState.Sub(ctx, stdBias)
- hiddenState = hiddenState.Mul(ctx, stdScale)
- }
-
- // Project to text embedding dimension
- hiddenState = proj.Forward(ctx, hiddenState, opts.eps)
-
- return hiddenState
-}
diff --git a/model/models/gemma4/process_audio.go b/model/models/gemma4/process_audio.go
deleted file mode 100644
index 63fdf3512..000000000
--- a/model/models/gemma4/process_audio.go
+++ /dev/null
@@ -1,280 +0,0 @@
-package gemma4
-
-import (
- "encoding/binary"
- "fmt"
- "math"
- "math/cmplx"
-)
-
-// Audio preprocessing constants.
-const (
- audioSampleRate = 16000
- melBins = 128
- frameLengthMs = 20.0
- hopLengthMs = 10.0
- minFrequency = 0.0
- maxFrequency = 8000.0
- melFloor = 1e-3
- maxAudioSoftTokens = 750
-)
-
-// Computed from the above constants.
-var (
- frameLength = int(math.Round(audioSampleRate * frameLengthMs / 1000.0)) // 320
- hopLength = int(math.Round(audioSampleRate * hopLengthMs / 1000.0)) // 160
-)
-
-// decodeWAV extracts mono float32 PCM samples from a WAV file, resampled to 16kHz.
-func decodeWAV(data []byte) ([]float32, error) {
- if len(data) < 12 {
- return nil, fmt.Errorf("WAV file too short")
- }
- if string(data[0:4]) != "RIFF" || string(data[8:12]) != "WAVE" {
- return nil, fmt.Errorf("not a WAV file")
- }
-
- var audioFormat uint16
- var numChannels, sampleRate, bitsPerSample int
- var audioData []byte
- foundFmt := false
-
- offset := 12
- for offset+8 <= len(data) {
- chunkID := string(data[offset : offset+4])
- chunkSize := int(binary.LittleEndian.Uint32(data[offset+4 : offset+8]))
- chunkData := data[offset+8 : min(offset+8+chunkSize, len(data))]
-
- switch chunkID {
- case "fmt ":
- if len(chunkData) < 16 {
- return nil, fmt.Errorf("fmt chunk too short")
- }
- audioFormat = binary.LittleEndian.Uint16(chunkData[0:2])
- numChannels = int(binary.LittleEndian.Uint16(chunkData[2:4]))
- sampleRate = int(binary.LittleEndian.Uint32(chunkData[4:8]))
- bitsPerSample = int(binary.LittleEndian.Uint16(chunkData[14:16]))
- if audioFormat == 0xFFFE && len(chunkData) >= 26 {
- audioFormat = binary.LittleEndian.Uint16(chunkData[24:26])
- }
- foundFmt = true
- case "data":
- audioData = chunkData
- }
-
- offset += 8 + chunkSize
- if chunkSize%2 != 0 {
- offset++
- }
- }
-
- if !foundFmt {
- return nil, fmt.Errorf("no fmt chunk found in WAV file")
- }
- if audioFormat != 1 && audioFormat != 3 {
- return nil, fmt.Errorf("unsupported WAV format: %d (need PCM=1 or float=3)", audioFormat)
- }
- if audioData == nil {
- return nil, fmt.Errorf("no data chunk found in WAV file")
- }
-
- samples := decodeWAVSamples(audioData, audioFormat, bitsPerSample, numChannels)
- if sampleRate != audioSampleRate {
- samples = resampleLinear(samples, sampleRate, audioSampleRate)
- }
- return samples, nil
-}
-
-func decodeWAVSamples(data []byte, format uint16, bits, channels int) []float32 {
- bytesPerSample := bits / 8
- totalSamples := len(data) / (bytesPerSample * channels)
- mono := make([]float32, totalSamples)
-
- for i := range totalSamples {
- var sum float64
- for ch := range channels {
- off := (i*channels + ch) * bytesPerSample
- if off+bytesPerSample > len(data) {
- break
- }
- switch {
- case format == 1 && bits == 16:
- v := int16(binary.LittleEndian.Uint16(data[off : off+2]))
- sum += float64(v) / 32768.0
- case format == 1 && bits == 32:
- v := int32(binary.LittleEndian.Uint32(data[off : off+4]))
- sum += float64(v) / 2147483648.0
- case format == 1 && bits == 24:
- v := int32(data[off]) | int32(data[off+1])<<8 | int32(data[off+2])<<16
- if v&0x800000 != 0 {
- v |= ^0xFFFFFF
- }
- sum += float64(v) / 8388608.0
- case format == 3 && bits == 32:
- v := math.Float32frombits(binary.LittleEndian.Uint32(data[off : off+4]))
- sum += float64(v)
- case format == 1 && bits == 8:
- sum += (float64(data[off]) - 128.0) / 128.0
- }
- }
- mono[i] = float32(sum / float64(channels))
- }
- return mono
-}
-
-func resampleLinear(samples []float32, fromRate, toRate int) []float32 {
- n := int(float64(len(samples)) / float64(fromRate) * float64(toRate))
- out := make([]float32, n)
- for i := range n {
- pos := float64(i) * float64(len(samples)-1) / float64(n-1)
- idx := int(pos)
- frac := float32(pos - float64(idx))
- if idx+1 < len(samples) {
- out[i] = samples[idx]*(1-frac) + samples[idx+1]*frac
- } else {
- out[i] = samples[idx]
- }
- }
- return out
-}
-
-// computeMelSpectrogram computes the log mel spectrogram from PCM samples.
-// Returns shape [numFrames, melBins] as float32 slice, and numFrames.
-func computeMelSpectrogram(samples []float32) ([]float32, int) {
- fftLen := 1
- for fftLen < frameLength {
- fftLen <<= 1
- }
- fftLen *= 2 // fft_overdrive=True
-
- // Hanning-nonzero window.
- window := make([]float64, frameLength)
- arg := math.Pi * 2.0 / float64(frameLength)
- for i := range frameLength {
- window[i] = 0.5 - 0.5*math.Cos(arg*(float64(i)+0.5))
- }
-
- numFreqBins := fftLen/2 + 1
- melFilters := buildMelFilterBank(numFreqBins, melBins, minFrequency, maxFrequency, audioSampleRate)
-
- frameSizeForUnfold := frameLength + 1
- numFrames := (len(samples) - frameSizeForUnfold) / hopLength
- if numFrames <= 0 {
- return nil, 0
- }
-
- result := make([]float32, numFrames*melBins)
- fftInput := make([]complex128, fftLen)
-
- for f := range numFrames {
- start := f * hopLength
- for i := range frameLength {
- fftInput[i] = complex(float64(samples[start+i])*window[i], 0)
- }
- for i := frameLength; i < fftLen; i++ {
- fftInput[i] = 0
- }
-
- fft(fftInput)
-
- for m := range melBins {
- var melVal float64
- for k := range numFreqBins {
- mag := cmplx.Abs(fftInput[k])
- melVal += mag * float64(melFilters[k*melBins+m])
- }
- if melVal < melFloor {
- melVal = melFloor
- }
- result[f*melBins+m] = float32(math.Log(melVal))
- }
- }
-
- return result, numFrames
-}
-
-func buildMelFilterBank(numFreqBins, numMels int, fMin, fMax float64, sr int) []float32 {
- hzToMel := func(f float64) float64 {
- return 2595.0 * math.Log10(1.0+f/700.0)
- }
- melToHz := func(m float64) float64 {
- return 700.0 * (math.Pow(10.0, m/2595.0) - 1.0)
- }
-
- melMin := hzToMel(fMin)
- melMax := hzToMel(fMax)
-
- melPts := make([]float64, numMels+2)
- for i := range melPts {
- melPts[i] = melMin + float64(i)*(melMax-melMin)/float64(numMels+1)
- }
- filterFreqs := make([]float64, numMels+2)
- for i, m := range melPts {
- filterFreqs[i] = melToHz(m)
- }
-
- fftFreqs := make([]float64, numFreqBins)
- for i := range fftFreqs {
- fftFreqs[i] = float64(i) * float64(sr) / float64(2*(numFreqBins-1))
- }
-
- filters := make([]float32, numFreqBins*numMels)
- for m := range numMels {
- fLeft := filterFreqs[m]
- fCenter := filterFreqs[m+1]
- fRight := filterFreqs[m+2]
- for k := range numFreqBins {
- f := fftFreqs[k]
- var v float64
- if f >= fLeft && f <= fCenter && fCenter > fLeft {
- v = (f - fLeft) / (fCenter - fLeft)
- } else if f > fCenter && f <= fRight && fRight > fCenter {
- v = (fRight - f) / (fRight - fCenter)
- }
- if v > 0 {
- filters[k*numMels+m] = float32(v)
- }
- }
- }
- return filters
-}
-
-// fft performs an in-place Cooley-Tukey radix-2 FFT.
-func fft(x []complex128) {
- n := len(x)
- if n <= 1 {
- return
- }
-
- j := 0
- for i := 1; i < n; i++ {
- bit := n >> 1
- for j&bit != 0 {
- j ^= bit
- bit >>= 1
- }
- j ^= bit
- if i < j {
- x[i], x[j] = x[j], x[i]
- }
- }
-
- for size := 2; size <= n; size <<= 1 {
- halfSize := size / 2
- w := complex(math.Cos(2*math.Pi/float64(size)), -math.Sin(2*math.Pi/float64(size)))
- for start := 0; start < n; start += size {
- wn := complex(1, 0)
- for k := range halfSize {
- t := wn * x[start+k+halfSize]
- x[start+k+halfSize] = x[start+k] - t
- x[start+k] = x[start+k] + t
- wn *= w
- }
- }
- }
-}
-
-// isAudioData checks if the data starts with WAV magic bytes.
-func isAudioData(data []byte) bool {
- return len(data) >= 12 && string(data[0:4]) == "RIFF" && string(data[8:12]) == "WAVE"
-}
diff --git a/model/models/gemma4/process_image.go b/model/models/gemma4/process_image.go
deleted file mode 100644
index 0404ffb7b..000000000
--- a/model/models/gemma4/process_image.go
+++ /dev/null
@@ -1,103 +0,0 @@
-package gemma4
-
-import (
- "image"
- "math"
-
- "golang.org/x/image/draw"
-
- "github.com/ollama/ollama/fs"
-)
-
-type ImageProcessor struct {
- patchSize int
- numChannels int
- nMerge int
- minPixels int
- maxPixels int
-}
-
-func newImageProcessor(c fs.Config) ImageProcessor {
- patchSize := int(c.Uint("vision.patch_size", 16))
- nMerge := int(c.Uint("vision.projector.scale_factor", 3))
- numChannels := int(c.Uint("vision.num_channels", 3))
-
- // Token limits from reference: min=40, max=280 output tokens after pooling.
- // Convert to pixel counts: tokens * nMerge^2 * patchSize^2
- minTokens := 40
- maxTokens := 280
- patchArea := patchSize * patchSize * nMerge * nMerge
- minPixels := minTokens * patchArea
- maxPixels := maxTokens * patchArea
-
- return ImageProcessor{
- patchSize: patchSize,
- numChannels: numChannels,
- nMerge: nMerge,
- minPixels: minPixels,
- maxPixels: maxPixels,
- }
-}
-
-// ProcessImage resizes an image preserving aspect ratio, aligning dimensions
-// to (patchSize * nMerge) boundaries, and normalizes pixels to [-1, 1].
-// Returns the float32 pixel data and the actual output dimensions.
-func (p *ImageProcessor) ProcessImage(img image.Image) ([]float32, int, int, error) {
- // Compute target size preserving aspect ratio
- alignSize := p.patchSize * p.nMerge
- targetW, targetH := p.smartResize(img.Bounds().Dx(), img.Bounds().Dy(), alignSize)
-
- // Resize directly without alpha compositing, matching MLX reference.
- dst := image.NewRGBA(image.Rect(0, 0, targetW, targetH))
- draw.BiLinear.Scale(dst, dst.Bounds(), img, img.Bounds(), draw.Over, nil)
-
- // Normalize to [-1, 1] using mean=0.5, std=0.5: (pixel/255 - 0.5) / 0.5 = 2*pixel/255 - 1
- data := p.pack(dst)
- return data, targetW, targetH, nil
-}
-
-// smartResize computes target dimensions that preserve aspect ratio and
-// align to alignSize boundaries. It scales the image to fill the maximum
-// patch budget (maxPixels), matching the MLX reference.
-func (p *ImageProcessor) smartResize(origW, origH, alignSize int) (int, int) {
- totalPx := origW * origH
-
- var targetW, targetH int
- if p.maxPixels > 0 && totalPx > 0 {
- factor := math.Sqrt(float64(p.maxPixels) / float64(totalPx))
- targetH = max(alignSize, int(math.Floor(factor*float64(origH)/float64(alignSize)))*alignSize)
- targetW = max(alignSize, int(math.Floor(factor*float64(origW)/float64(alignSize)))*alignSize)
- } else {
- targetH = max(alignSize, (origH/alignSize)*alignSize)
- targetW = max(alignSize, (origW/alignSize)*alignSize)
- }
-
- return targetW, targetH
-}
-
-// pack extracts RGB values from an image and normalizes to [-1, 1].
-// Returns channel-first layout: [R..., G..., B...].
-func (p *ImageProcessor) pack(img image.Image) []float32 {
- bounds := img.Bounds()
- w := bounds.Dx()
- h := bounds.Dy()
- size := w * h
-
- pixelVals := make([]float32, 3*size)
- rOff, gOff, bOff := 0, size, 2*size
-
- for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
- for x := bounds.Min.X; x < bounds.Max.X; x++ {
- c := img.At(x, y)
- r, g, b, _ := c.RGBA()
- idx := (y-bounds.Min.Y)*w + (x - bounds.Min.X)
-
- // Normalize [0, 255] -> [-1, 1]: 2 * (val/255) - 1
- pixelVals[rOff+idx] = float32(r>>8)/255.0*2.0 - 1.0
- pixelVals[gOff+idx] = float32(g>>8)/255.0*2.0 - 1.0
- pixelVals[bOff+idx] = float32(b>>8)/255.0*2.0 - 1.0
- }
- }
-
- return pixelVals
-}
diff --git a/model/models/laguna/model.go b/model/models/laguna/model.go
deleted file mode 100644
index 82a913e58..000000000
--- a/model/models/laguna/model.go
+++ /dev/null
@@ -1,444 +0,0 @@
-package laguna
-
-import (
- "fmt"
- "math"
-
- "github.com/ollama/ollama/fs"
- "github.com/ollama/ollama/kvcache"
- "github.com/ollama/ollama/ml"
- "github.com/ollama/ollama/ml/nn"
- "github.com/ollama/ollama/ml/nn/rope"
- "github.com/ollama/ollama/model"
- "github.com/ollama/ollama/model/input"
- "github.com/ollama/ollama/tokenizer"
-)
-
-const (
- cacheTypeSWA = iota
- cacheTypeCausal
-)
-
-type Options struct {
- hiddenSize int
- headDim int
-
- numHeads []int
- numKVHeads int
-
- eps float32
-
- slidingWindow int
- slidingWindowPattern []bool
-
- fullRopeDim int
- fullRopeBase, fullRopeScale float32
- fullRopeOriginalContextLength int
- fullRopeAttentionFactor float32
- fullRopeBetaFast float32
- fullRopeBetaSlow float32
-
- swaRopeDim int
- swaRopeBase, swaRopeScale float32
- numExperts, numExpertsUsed int
- normTopKProb bool
- routedScalingFactor float32
- decoderSparseStep int
- denseLayers map[int]bool
-}
-
-func (o *Options) numHeadsForLayer(layer int) int {
- if layer < len(o.numHeads) && o.numHeads[layer] > 0 {
- return o.numHeads[layer]
- }
- if len(o.numHeads) > 0 && o.numHeads[0] > 0 {
- return o.numHeads[0]
- }
- return 1
-}
-
-func (o *Options) layerIsSliding(layer int) bool {
- return layer < len(o.slidingWindowPattern) && o.slidingWindowPattern[layer]
-}
-
-func (o *Options) layerUsesMoE(layer int) bool {
- if o.numExperts == 0 || o.denseLayers[layer] {
- return false
- }
- step := o.decoderSparseStep
- if step <= 0 {
- step = 1
- }
- return (layer+1)%step == 0
-}
-
-func (o *Options) applyRotaryPositionEmbeddings(ctx ml.Context, layer int, states, positions ml.Tensor) ml.Tensor {
- opts := []func(*rope.Options){rope.WithTypeNeoX()}
- if o.layerIsSliding(layer) {
- return nn.RoPE(ctx, states, positions, o.swaRopeDim, o.swaRopeBase, 1./o.swaRopeScale, opts...)
- }
-
- opts = append(opts,
- rope.WithOriginalContextLength(o.fullRopeOriginalContextLength),
- rope.WithExtrapolationFactor(1),
- rope.WithAttentionFactor(o.fullRopeAttentionFactor),
- rope.WithBetaFast(o.fullRopeBetaFast),
- rope.WithBetaSlow(o.fullRopeBetaSlow),
- )
- return nn.RoPE(ctx, states, positions, o.fullRopeDim, o.fullRopeBase, 1./o.fullRopeScale, opts...)
-}
-
-type Attention struct {
- Query *nn.Linear `gguf:"attn_q"`
- QueryNorm *nn.RMSNorm `gguf:"attn_q_norm"`
- Key *nn.Linear `gguf:"attn_k"`
- KeyNorm *nn.RMSNorm `gguf:"attn_k_norm"`
- Value *nn.Linear `gguf:"attn_v"`
- Gate *nn.Linear `gguf:"attn_g"`
- Output *nn.Linear `gguf:"attn_output"`
-}
-
-func (sa *Attention) Forward(ctx ml.Context, layer int, hiddenStates, positions ml.Tensor, cache kvcache.Cache, opts *Options) ml.Tensor {
- batchSize := hiddenStates.Dim(1)
- numHeads := opts.numHeadsForLayer(layer)
-
- query := sa.Query.Forward(ctx, hiddenStates)
- key := sa.Key.Forward(ctx, hiddenStates)
- value := sa.Value.Forward(ctx, hiddenStates)
- gate := sa.Gate.Forward(ctx, hiddenStates)
-
- query = query.Reshape(ctx, opts.headDim, numHeads, batchSize)
- key = key.Reshape(ctx, opts.headDim, opts.numKVHeads, batchSize)
- value = value.Reshape(ctx, opts.headDim, opts.numKVHeads, batchSize)
-
- query = sa.QueryNorm.Forward(ctx, query, opts.eps)
- key = sa.KeyNorm.Forward(ctx, key, opts.eps)
-
- query = opts.applyRotaryPositionEmbeddings(ctx, layer, query, positions)
- key = opts.applyRotaryPositionEmbeddings(ctx, layer, key, positions)
-
- attention := nn.Attention(ctx, query, key, value, 1./math.Sqrt(float64(opts.headDim)), cache)
- // Laguna applies the per-head gate softplus in float32, then casts back.
- gate = gate.Cast(ctx, ml.DTypeF32).Softplus(ctx).Cast(ctx, attention.DType())
- attention = attention.Mul(ctx, gate.Reshape(ctx, 1, numHeads, batchSize))
- attention = attention.Reshape(ctx, opts.headDim*numHeads, batchSize)
- return sa.Output.Forward(ctx, attention)
-}
-
-type MLP interface {
- Forward(ml.Context, ml.Tensor, *Options) ml.Tensor
-}
-
-type dense struct {
- Gate *nn.Linear `gguf:"ffn_gate"`
- Up *nn.Linear `gguf:"ffn_up"`
- Down *nn.Linear `gguf:"ffn_down"`
-}
-
-func (mlp *dense) Forward(ctx ml.Context, hiddenStates ml.Tensor, _ *Options) ml.Tensor {
- hiddenStates = mlp.Gate.Forward(ctx, hiddenStates).SILU(ctx, mlp.Up.Forward(ctx, hiddenStates))
- return mlp.Down.Forward(ctx, hiddenStates)
-}
-
-type sparse struct {
- Router *nn.Linear `gguf:"ffn_gate_inp"`
- Gate *nn.LinearBatch `gguf:"ffn_gate_exps"`
- Up *nn.LinearBatch `gguf:"ffn_up_exps"`
- Down *nn.LinearBatch `gguf:"ffn_down_exps"`
- SharedExpert *dense `gguf:",suf:_shexp"`
- ExpProbsBias ml.Tensor `gguf:"exp_probs_b.bias,alt:exp_probs_b"`
-}
-
-func (moe *sparse) topKIndices(ctx ml.Context, scores ml.Tensor, opts *Options) ml.Tensor {
- if moe.ExpProbsBias != nil {
- scores = scores.Add(ctx, moe.ExpProbsBias)
- }
- return scores.TopK(ctx, opts.numExpertsUsed)
-}
-
-func (moe *sparse) Forward(ctx ml.Context, hiddenStates ml.Tensor, opts *Options) ml.Tensor {
- residual := hiddenStates
-
- scores := moe.Router.Forward(ctx, hiddenStates).Cast(ctx, ml.DTypeF32).Sigmoid(ctx)
- selectedExperts := moe.topKIndices(ctx, scores, opts)
- routingWeights := scores.Reshape(ctx, 1, opts.numExperts, hiddenStates.Dim(1)).Rows(ctx, selectedExperts)
- if opts.normTopKProb {
- routingWeights = routingWeights.Reshape(ctx, opts.numExpertsUsed, hiddenStates.Dim(1))
- routingWeights = routingWeights.Div(ctx, routingWeights.SumRows(ctx))
- routingWeights = routingWeights.Reshape(ctx, 1, opts.numExpertsUsed, hiddenStates.Dim(1))
- }
- routingWeights = routingWeights.Scale(ctx, float64(opts.routedScalingFactor))
-
- hiddenStates = hiddenStates.Reshape(ctx, hiddenStates.Dim(0), 1, hiddenStates.Dim(1))
- upStates := moe.Up.Forward(ctx, hiddenStates, selectedExperts)
- hiddenStates = moe.Gate.Forward(ctx, hiddenStates, selectedExperts).SILU(ctx, upStates)
-
- experts := moe.Down.Forward(ctx, hiddenStates, selectedExperts)
- experts = experts.Mul(ctx, routingWeights)
-
- nextStates := experts.View(ctx, 0, experts.Dim(0), experts.Stride(2), experts.Dim(2))
- for i := 1; i < opts.numExpertsUsed; i++ {
- nextStates = nextStates.Add(ctx, experts.View(ctx, i*experts.Stride(1), experts.Dim(0), experts.Stride(2), experts.Dim(2)))
- }
-
- return nextStates.Add(ctx, moe.SharedExpert.Forward(ctx, residual, opts))
-}
-
-type Layer struct {
- AttentionNorm *nn.RMSNorm `gguf:"attn_norm"`
- *Attention
-
- MLPNorm *nn.RMSNorm `gguf:"ffn_norm"`
- MLP
-}
-
-func (l *Layer) Forward(ctx ml.Context, layer int, hiddenStates, positions, outputs ml.Tensor, cache kvcache.Cache, opts *Options) ml.Tensor {
- residual := hiddenStates
- hiddenStates = l.AttentionNorm.Forward(ctx, hiddenStates, opts.eps)
- hiddenStates = l.Attention.Forward(ctx, layer, hiddenStates, positions, cache, opts)
-
- if outputs != nil {
- hiddenStates = hiddenStates.Rows(ctx, outputs)
- residual = residual.Rows(ctx, outputs)
- }
-
- hiddenStates = hiddenStates.Add(ctx, residual)
- residual = hiddenStates
-
- hiddenStates = l.MLPNorm.Forward(ctx, hiddenStates, opts.eps)
- hiddenStates = l.MLP.Forward(ctx, hiddenStates, opts)
- return hiddenStates.Add(ctx, residual)
-}
-
-type Model struct {
- model.Base
- tokenizer.Tokenizer
-
- TokenEmbedding *nn.Embedding `gguf:"token_embd"`
- Layers []Layer `gguf:"blk"`
- OutputNorm *nn.RMSNorm `gguf:"output_norm"`
- Output *nn.Linear `gguf:"output,alt:token_embd"`
-
- *Options
-}
-
-func New(c fs.Config) (model.Model, error) {
- if c.Bool("attention.sink_enabled") {
- return nil, fmt.Errorf("laguna: SWA attention sinks are not supported")
- }
- if c.Uint("attention.gating_type") != 1 {
- return nil, fmt.Errorf("laguna: unsupported attention gating type %d", c.Uint("attention.gating_type"))
- }
- if !c.Bool("attention.qk_norm") {
- return nil, fmt.Errorf("laguna: Q/K RMSNorm is required")
- }
- if gating := c.Uint("expert_gating_func"); gating != 2 {
- return nil, fmt.Errorf("laguna: unsupported expert gating function %d", gating)
- }
-
- numLayers := int(c.Uint("block_count"))
- opts := newOptions(c, numLayers)
- layers := make([]Layer, numLayers)
- for i := range layers {
- if opts.layerUsesMoE(i) {
- layers[i].MLP = &sparse{}
- } else {
- layers[i].MLP = &dense{}
- }
- }
-
- var pre []string
- switch c.String("tokenizer.ggml.pre") {
- case "laguna":
- pre = []string{
- `(?:\r?\n)+(?!\r?\n)`,
- `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`,
- }
- default:
- return nil, model.ErrUnsupportedTokenizer
- }
-
- m := Model{
- Tokenizer: tokenizer.NewBytePairEncoding(
- &tokenizer.Vocabulary{
- Values: c.Strings("tokenizer.ggml.tokens"),
- Types: c.Ints("tokenizer.ggml.token_type"),
- Merges: c.Strings("tokenizer.ggml.merges"),
- AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
- BOS: []int32{int32(c.Uint("tokenizer.ggml.bos_token_id"))},
- AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
- EOS: append(
- []int32{int32(c.Uint("tokenizer.ggml.eos_token_id"))},
- c.Ints("tokenizer.ggml.eos_token_ids")...,
- ),
- },
- pre...,
- ),
- Layers: layers,
- Options: opts,
- }
-
- m.Cache = kvcache.NewWrapperCache(
- kvcache.NewSWACache(int32(opts.slidingWindow), m.Shift),
- kvcache.NewCausalCache(m.Shift),
- )
- return &m, nil
-}
-
-func newOptions(c fs.Config, numLayers int) *Options {
- denseLayers := make(map[int]bool)
- for _, layer := range configUints(c, "dense_layers") {
- denseLayers[int(layer)] = true
- }
- for i := range c.Uint("leading_dense_block_count") {
- denseLayers[int(i)] = true
- }
-
- fullRopeScale := c.Float("rope.scaling.factor", 1)
- if fullRopeScale == 0 {
- fullRopeScale = 1
- }
- swaRopeScale := c.Float("rope.swa.scaling.factor", 1)
- if swaRopeScale == 0 {
- swaRopeScale = 1
- }
- fullRopeType := c.String("rope.scaling.type")
- fullRopeAttentionFactor := lagunaAttentionFactor(fullRopeType, fullRopeScale, c.Float("rope.scaling.attn_factor"))
-
- return &Options{
- hiddenSize: int(c.Uint("embedding_length")),
- headDim: int(c.Uint("attention.key_length")),
- numHeads: expandIntArray(configUints(c, "attention.head_count"), numLayers, c.Uint("attention.head_count", 1)),
- numKVHeads: int(c.Uint("attention.head_count_kv")),
- eps: c.Float("attention.layer_norm_rms_epsilon", 1e-6),
- slidingWindow: int(c.Uint("attention.sliding_window", 512)),
- slidingWindowPattern: slidingWindowPattern(c, numLayers),
- fullRopeDim: int(c.Uint("rope.dimension_count", c.Uint("attention.key_length"))),
- fullRopeBase: c.Float("rope.freq_base", 500000),
- fullRopeScale: fullRopeScale,
- fullRopeOriginalContextLength: int(c.Uint("rope.scaling.original_context_length", 4096)),
- fullRopeAttentionFactor: fullRopeAttentionFactor,
- fullRopeBetaFast: c.Float("rope.scaling.beta_fast", 64),
- fullRopeBetaSlow: c.Float("rope.scaling.beta_slow", 1),
- swaRopeDim: int(c.Uint("rope.swa.dimension_count", c.Uint("attention.key_length"))),
- swaRopeBase: c.Float("rope.swa.freq_base", 10000),
- swaRopeScale: swaRopeScale,
- numExperts: int(c.Uint("expert_count")),
- numExpertsUsed: int(c.Uint("expert_used_count")),
- normTopKProb: c.Bool("expert_weights_norm", true),
- routedScalingFactor: c.Float("expert_weights_scale", 1),
- decoderSparseStep: int(c.Uint("decoder_sparse_step", 1)),
- denseLayers: denseLayers,
- }
-}
-
-func lagunaAttentionFactor(ropeType string, scaleFactor, attentionFactor float32) float32 {
- if attentionFactor != 0 {
- return attentionFactor
- }
- if ropeType == "yarn" && scaleFactor > 1 {
- return float32(0.1*math.Log(float64(scaleFactor)) + 1)
- }
- return 1
-}
-
-func slidingWindowPattern(c fs.Config, numLayers int) []bool {
- pattern := c.Bools("attention.sliding_window_pattern")
- if len(pattern) == numLayers {
- return pattern
- }
-
- layerTypes := configUints(c, "attention.layer_types")
- if len(layerTypes) == numLayers {
- pattern = make([]bool, numLayers)
- for i, layerType := range layerTypes {
- pattern[i] = layerType == 1
- }
- return pattern
- }
-
- return make([]bool, numLayers)
-}
-
-func configUints(c fs.Config, key string) []uint32 {
- keyExists := c.Value(c.Architecture()+"."+key) != nil || c.Value(key) != nil
- if cc, ok := c.(interface {
- Uints(string, ...[]uint32) []uint32
- }); ok {
- if values := cc.Uints(key); len(values) > 0 && (keyExists || !(len(values) == 1 && values[0] == 0)) {
- return values
- }
- }
-
- ints := c.Ints(key)
- if len(ints) > 0 && (keyExists || !(len(ints) == 1 && ints[0] == 0)) {
- values := make([]uint32, len(ints))
- for i, v := range ints {
- values[i] = uint32(v)
- }
- return values
- }
-
- if scalar := c.Uint(key); scalar != 0 {
- return []uint32{scalar}
- }
- return nil
-}
-
-func expandIntArray(values []uint32, n int, fallback uint32) []int {
- if len(values) == 0 {
- values = []uint32{fallback}
- }
- defaultValue := values[0]
- if len(values) == 1 {
- defaultValue = values[0]
- }
-
- out := make([]int, n)
- for i := range out {
- if i < len(values) {
- out[i] = int(values[i])
- } else {
- out[i] = int(defaultValue)
- }
- }
- return out
-}
-
-func (m *Model) Shift(ctx ml.Context, layer int, key, shift ml.Tensor) (ml.Tensor, error) {
- return m.Options.applyRotaryPositionEmbeddings(ctx, layer, key, shift), nil
-}
-
-func (m *Model) Forward(ctx ml.Context, batch input.Batch) (ml.Tensor, error) {
- positions := ctx.Input().FromInts(batch.Positions, len(batch.Positions))
- hiddenStates := m.TokenEmbedding.Forward(ctx, batch.Inputs)
-
- for i, layer := range m.Layers {
- if m.Cache != nil {
- m.Cache.SetLayer(i)
- if wrapper, ok := m.Cache.(*kvcache.WrapperCache); ok {
- cacheType := cacheTypeCausal
- if m.Options.layerIsSliding(i) {
- cacheType = cacheTypeSWA
- }
- wrapper.SetLayerType(cacheType)
- }
- }
-
- var outputs ml.Tensor
- if i == len(m.Layers)-1 {
- outputs = batch.Outputs
- }
-
- hiddenStates = layer.Forward(ctx, i, hiddenStates, positions, outputs, m.Cache, m.Options)
- }
-
- hiddenStates = m.OutputNorm.Forward(ctx, hiddenStates, m.eps)
- return m.Output.Forward(ctx, hiddenStates), nil
-}
-
-func init() {
- model.Register("laguna", New)
-}
-
-var _ model.Model = (*Model)(nil)
diff --git a/model/models/laguna/model_test.go b/model/models/laguna/model_test.go
deleted file mode 100644
index ac7b336b2..000000000
--- a/model/models/laguna/model_test.go
+++ /dev/null
@@ -1,237 +0,0 @@
-package laguna
-
-import (
- "iter"
- "math"
- "testing"
-)
-
-type testConfig map[string]any
-
-func (c testConfig) Architecture() string { return "laguna" }
-
-func (c testConfig) key(key string) string {
- switch {
- case len(key) >= len("tokenizer.") && key[:len("tokenizer.")] == "tokenizer.":
- return key
- case len(key) >= len("general.") && key[:len("general.")] == "general.":
- return key
- default:
- return "laguna." + key
- }
-}
-
-func (c testConfig) String(key string, defaultValue ...string) string {
- if v, ok := c[c.key(key)].(string); ok {
- return v
- }
- if len(defaultValue) > 0 {
- return defaultValue[0]
- }
- return ""
-}
-
-func (c testConfig) Uint(key string, defaultValue ...uint32) uint32 {
- switch v := c[c.key(key)].(type) {
- case uint32:
- return v
- case int:
- return uint32(v)
- }
- if len(defaultValue) > 0 {
- return defaultValue[0]
- }
- return 0
-}
-
-func (c testConfig) Float(key string, defaultValue ...float32) float32 {
- if v, ok := c[c.key(key)].(float32); ok {
- return v
- }
- if len(defaultValue) > 0 {
- return defaultValue[0]
- }
- return 0
-}
-
-func (c testConfig) Bool(key string, defaultValue ...bool) bool {
- if v, ok := c[c.key(key)].(bool); ok {
- return v
- }
- if len(defaultValue) > 0 {
- return defaultValue[0]
- }
- return false
-}
-
-func (c testConfig) Strings(key string, defaultValue ...[]string) []string {
- if v, ok := c[c.key(key)].([]string); ok {
- return v
- }
- if len(defaultValue) > 0 {
- return defaultValue[0]
- }
- return nil
-}
-
-func (c testConfig) Ints(key string, defaultValue ...[]int32) []int32 {
- if v, ok := c[c.key(key)].([]int32); ok {
- return v
- }
- if len(defaultValue) > 0 {
- return defaultValue[0]
- }
- return nil
-}
-
-func (c testConfig) Uints(key string, defaultValue ...[]uint32) []uint32 {
- if v, ok := c[c.key(key)].([]uint32); ok {
- return v
- }
- if len(defaultValue) > 0 {
- return defaultValue[0]
- }
- return nil
-}
-
-func (c testConfig) Floats(key string, defaultValue ...[]float32) []float32 {
- if v, ok := c[c.key(key)].([]float32); ok {
- return v
- }
- if len(defaultValue) > 0 {
- return defaultValue[0]
- }
- return nil
-}
-
-func (c testConfig) Bools(key string, defaultValue ...[]bool) []bool {
- if v, ok := c[c.key(key)].([]bool); ok {
- return v
- }
- if len(defaultValue) > 0 {
- return defaultValue[0]
- }
- return nil
-}
-
-func (c testConfig) Len() int { return len(c) }
-
-func (c testConfig) Keys() iter.Seq[string] {
- return func(yield func(string) bool) {
- for key := range c {
- if !yield(key) {
- return
- }
- }
- }
-}
-
-func (c testConfig) Value(key string) any { return c[key] }
-
-func TestNewOptionsLayerConfig(t *testing.T) {
- cfg := testConfig{
- "laguna.block_count": uint32(4),
- "laguna.embedding_length": uint32(128),
- "laguna.attention.key_length": uint32(16),
- "laguna.attention.head_count": []uint32{8, 16, 16, 16},
- "laguna.attention.head_count_kv": uint32(4),
- "laguna.attention.layer_norm_rms_epsilon": float32(1e-6),
- "laguna.attention.sliding_window": uint32(512),
- "laguna.attention.sliding_window_pattern": []bool{false, true, true, true},
- "laguna.rope.dimension_count": uint32(8),
- "laguna.rope.freq_base": float32(500000),
- "laguna.rope.scaling.factor": float32(32),
- "laguna.rope.scaling.original_context_length": uint32(4096),
- "laguna.rope.swa.dimension_count": uint32(16),
- "laguna.rope.swa.freq_base": float32(10000),
- "laguna.expert_count": uint32(32),
- "laguna.expert_used_count": uint32(4),
- "laguna.expert_weights_norm": true,
- "laguna.expert_weights_scale": float32(2.5),
- "laguna.decoder_sparse_step": uint32(1),
- "laguna.dense_layers": []uint32{0},
- }
-
- opts := newOptions(cfg, 4)
- if got := opts.numHeadsForLayer(0); got != 8 {
- t.Fatalf("layer 0 heads = %d, want 8", got)
- }
- if got := opts.numHeadsForLayer(1); got != 16 {
- t.Fatalf("layer 1 heads = %d, want 16", got)
- }
- if opts.layerIsSliding(0) {
- t.Fatal("layer 0 should be full attention")
- }
- if !opts.layerIsSliding(1) {
- t.Fatal("layer 1 should be sliding attention")
- }
- if opts.layerUsesMoE(0) {
- t.Fatal("layer 0 should be dense")
- }
- if !opts.layerUsesMoE(1) {
- t.Fatal("layer 1 should use MoE")
- }
- if opts.fullRopeDim != 8 || opts.swaRopeDim != 16 {
- t.Fatalf("rope dims = full %d swa %d, want 8/16", opts.fullRopeDim, opts.swaRopeDim)
- }
-}
-
-func TestNewOptionsYarnAttentionFactorFallback(t *testing.T) {
- cfg := testConfig{
- "laguna.block_count": uint32(1),
- "laguna.embedding_length": uint32(128),
- "laguna.attention.key_length": uint32(16),
- "laguna.attention.head_count": uint32(8),
- "laguna.attention.head_count_kv": uint32(4),
- "laguna.rope.scaling.type": "yarn",
- "laguna.rope.scaling.factor": float32(32),
- }
-
- opts := newOptions(cfg, 1)
- want := float32(0.1*math.Log(32) + 1)
- if got := opts.fullRopeAttentionFactor; math.Abs(float64(got-want)) > 1e-6 {
- t.Fatalf("fullRopeAttentionFactor = %v, want %v", got, want)
- }
-}
-
-func TestNewRejectsUnsupportedLagunaVariants(t *testing.T) {
- tests := []struct {
- name string
- cfg testConfig
- }{
- {
- name: "attention sinks",
- cfg: testConfig{
- "laguna.attention.sink_enabled": true,
- },
- },
- {
- name: "non per-head gate",
- cfg: testConfig{
- "laguna.attention.gating_type": uint32(0),
- },
- },
- {
- name: "missing qk norm",
- cfg: testConfig{
- "laguna.attention.gating_type": uint32(1),
- },
- },
- {
- name: "non sigmoid experts",
- cfg: testConfig{
- "laguna.attention.gating_type": uint32(1),
- "laguna.attention.qk_norm": true,
- "laguna.expert_gating_func": uint32(1),
- },
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- if _, err := New(tt.cfg); err == nil {
- t.Fatal("expected unsupported variant error")
- }
- })
- }
-}