backend.go 10.5 KB
Newer Older
Michael Yang's avatar
Michael Yang committed
1
2
3
4
package ml

import (
	"bytes"
5
	"context"
Michael Yang's avatar
Michael Yang committed
6
7
	"encoding/binary"
	"fmt"
8
	"math"
Michael Yang's avatar
Michael Yang committed
9
	"slices"
Michael Yang's avatar
Michael Yang committed
10
11
12
	"strconv"
	"strings"

13
14
	"github.com/ollama/ollama/fs"
)
Michael Yang's avatar
Michael Yang committed
15
16

type Backend interface {
Jesse Gross's avatar
Jesse Gross committed
17
18
19
	// Close frees all memory associated with this backend
	Close()

20
	Load(ctx context.Context, progress func(float32)) error
21
22
23
24

	// BackendMemory returns the memory allocations that were made for this model
	BackendMemory() BackendMemory

25
	Config() fs.Config
Michael Yang's avatar
Michael Yang committed
26
27
	Get(name string) Tensor
	NewContext() Context
28
	NewContextSize(size int) Context
29
30
31

	// Enumerate the devices available for inference via this backend
	BackendDevices() []DeviceInfo
Michael Yang's avatar
Michael Yang committed
32
33
}

34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// BackendCacheConfig should be implemented by backends that need special output
// from the cache to meet specific requirements. It is frequently implemented in
// conjunction with ScaledDotProductAttention.
type BackendCacheConfig interface {
	CacheConfig() CacheConfig
}

// CacheConfig controls optimizations (mostly backend-specific) that may transform
// the output the cache to work better with specific kernels.
type CacheConfig struct {
	// CachePadding specifies the multiple for the number of tokens of cache history
	// that will be returned from cache Get for k, v and mask. The capacity of the
	// cache itself will also be increased to a multiple of this size if needed.
	CachePadding int

	// PermutedV performs Permute(ctx, 1, 2, 0, 3) on v tensors stored via Put
	// and return the permuted version via Get. This uses the cache copy operation
	// to avoid a Contiguous call on the permuted tensor.
	PermutedV bool
53
54
55
56

	// MaskDType specifies the data type for generating the mask. If unset it will
	// default to DTypeF32.
	MaskDType DType
57
58
}

59
60
// BackendParams controls how the backend loads and executes models
type BackendParams struct {
Jesse Gross's avatar
Jesse Gross committed
61
62
63
64
65
	// AllocMemory causes the backend to allocate memory for the model. If
	// false, this is only being used for discovering the required amount of
	// memory and cannot load the model for running.
	AllocMemory bool

66
67
	// NumThreads sets the number of threads to use if running on the CPU
	NumThreads int
Michael Yang's avatar
Michael Yang committed
68

Jesse Gross's avatar
Jesse Gross committed
69
70
	// GPULayers is the set of layers to offload to GPUs
	GPULayers GPULayersList
71
72

	// FlashAttention indicates that we should use a fused flash attention kernel
73
	FlashAttention FlashAttentionType
74
75
}

76
var backends = make(map[string]func(string, BackendParams) (Backend, error))
77

78
func RegisterBackend(name string, f func(string, BackendParams) (Backend, error)) {
Michael Yang's avatar
Michael Yang committed
79
80
81
82
83
84
85
	if _, ok := backends[name]; ok {
		panic("backend: backend already registered")
	}

	backends[name] = f
}

86
func NewBackend(modelPath string, params BackendParams) (Backend, error) {
Michael Yang's avatar
Michael Yang committed
87
	if backend, ok := backends["ggml"]; ok {
88
		return backend(modelPath, params)
Michael Yang's avatar
Michael Yang committed
89
90
91
92
93
94
	}

	return nil, fmt.Errorf("unsupported backend")
}

type Context interface {
95
	Empty(dtype DType, shape ...int) Tensor
Michael Yang's avatar
Michael Yang committed
96
	Zeros(dtype DType, shape ...int) Tensor
Michael Yang's avatar
Michael Yang committed
97
98
99
	FromBytes(dtype DType, s []byte, shape ...int) Tensor
	FromFloats(s []float32, shape ...int) Tensor
	FromInts(s []int32, shape ...int) Tensor
Michael Yang's avatar
Michael Yang committed
100

Michael Yang's avatar
arange  
Michael Yang committed
101
102
103
	// Arange creates a 1D tensor with values within an interval (start, stop] increased by step.
	Arange(start, stop, step float32, dtype DType) Tensor

104
	Forward(...Tensor) Context
105
106
107
108
109

	// SetBatchSize provides a hint on the batch size to optimize processing
	// Uses heuristics if not set
	SetBatchSize(int)

110
	Compute(...Tensor)
111
	ComputeWithNotify(func(), ...Tensor) // notify callback once compute has begun
112
113
114
115
116

	// Reserve is analogous to Compute but rather than executing a
	// graph, simply preallocates memory. Typically called with a
	// worst case graph to ensure all resources are available for
	// for future inference.
117
	Reserve()
118

119
	MaxGraphNodes() int
120
	Close()
121

122
123
	// Input returns a context appropriate for creating tensors that are
	// inputs to the model (which includes things like output locations)
124
125
126
127
	Input() Context

	// Layer returns a context appropriate for creating intermediate tensors
	Layer(int) Context
Michael Yang's avatar
Michael Yang committed
128
129
130
}

type Tensor interface {
131
132
	Dim(n int) int
	Stride(n int) int
Michael Yang's avatar
Michael Yang committed
133

134
	Shape() []int
Michael Yang's avatar
Michael Yang committed
135
	DType() DType
136
	Cast(ctx Context, dtype DType) Tensor
Michael Yang's avatar
Michael Yang committed
137
138
139
140

	Bytes() []byte
	Floats() []float32

Michael Yang's avatar
Michael Yang committed
141
142
143
	FromBytes([]byte)
	FromFloats([]float32)
	FromInts([]int32)
144

Michael Yang's avatar
Michael Yang committed
145
	Add(ctx Context, t2 Tensor) Tensor
Michael Yang's avatar
Michael Yang committed
146
	Sub(ctx Context, t2 Tensor) Tensor
Michael Yang's avatar
Michael Yang committed
147
	Mul(ctx Context, t2 Tensor) Tensor
148
149
	Div(ctx Context, t2 Tensor) Tensor

Michael Yang's avatar
Michael Yang committed
150
	Mulmat(ctx Context, t2 Tensor) Tensor
151
	MulmatFullPrec(ctx Context, t2 Tensor) Tensor
Michael Yang's avatar
llama4  
Michael Yang committed
152
	MulmatID(ctx Context, t2, ids Tensor) Tensor
153
	AddID(ctx Context, t2, ids Tensor) Tensor
Michael Yang's avatar
Michael Yang committed
154
155

	Softmax(ctx Context) Tensor
156
	L2Norm(ctx Context, eps float32) Tensor
Michael Yang's avatar
Michael Yang committed
157
158
159
	LayerNorm(ctx Context, weight, bias Tensor, eps float32) Tensor
	RMSNorm(ctx Context, weight Tensor, eps float32) Tensor
	Scale(ctx Context, s float64) Tensor
160
	SumRows(ctx Context) Tensor
Michael Yang's avatar
Michael Yang committed
161

Michael Yang's avatar
Michael Yang committed
162
	AvgPool2D(ctx Context, k, s int, p float32) Tensor
Michael Yang's avatar
Michael Yang committed
163
	Conv2D(ctx Context, weight Tensor, s0, s1, p0, p1, d0, d1 int) Tensor
164
	Conv3D(ctx Context, weight Tensor, c, s0, s1, s2, p0, p1, p2, d0, d1, d2 int) Tensor
Michael Yang's avatar
Michael Yang committed
165

166
	IM2Col(ctx Context, weight Tensor, s0, s1, p0, p1, d0, d1 int) Tensor
Michael Yang's avatar
Michael Yang committed
167

168
169
	Sin(ctx Context) Tensor
	Cos(ctx Context) Tensor
Michael Yang's avatar
Michael Yang committed
170
	Tanh(ctx Context) Tensor
171
	GELU(ctx Context, up ...Tensor) Tensor
Michael Yang's avatar
Michael Yang committed
172
	QuickGELU(ctx Context, up ...Tensor) Tensor
173
174
	SILU(ctx Context, up ...Tensor) Tensor
	RELU(ctx Context, up ...Tensor) Tensor
Michael Yang's avatar
llama4  
Michael Yang committed
175
	Sigmoid(ctx Context) Tensor
176
177
178

	// AlphaLimitSILU is a variant of SILU that clamps the input to the range [-limit, limit]
	SILUAlphaLimit(ctx Context, up Tensor, alpha, limit float32) Tensor
Michael Yang's avatar
Michael Yang committed
179

180
	Reshape(ctx Context, shape ...int) Tensor
Michael Yang's avatar
Michael Yang committed
181
182
	View(ctx Context, offset int, shape ...int) Tensor
	Permute(ctx Context, shape ...int) Tensor
Michael Yang's avatar
Michael Yang committed
183
	Contiguous(ctx Context, shape ...int) Tensor
Michael Yang's avatar
Michael Yang committed
184

185
	Pad(ctx Context, shape ...int) Tensor
Michael Yang's avatar
Michael Yang committed
186
187

	Stack(ctx Context, dim int, s ...Tensor) Tensor
188
189
190

	// Repeat repeats the tensor n times along dimension dim
	Repeat(ctx Context, dim, n int) Tensor
Michael Yang's avatar
Michael Yang committed
191
192
	Concat(ctx Context, t2 Tensor, dim int) Tensor
	Rows(ctx Context, t2 Tensor) Tensor
193
	SetRows(ctx Context, src Tensor, idxs Tensor) Tensor
Michael Yang's avatar
Michael Yang committed
194
	Copy(ctx Context, t2 Tensor) Tensor
195
	Duplicate(ctx Context) Tensor
Michael Yang's avatar
llama4  
Michael Yang committed
196

197
198
199
200
	Slice(ctx Context, dim, low, high, step int) Tensor
	Chunk(ctx Context, dim int, size int) []Tensor
	ChunkSections(ctx Context, dim int, sections ...int) []Tensor

Michael Yang's avatar
llama4  
Michael Yang committed
201
	TopK(ctx Context, k int) Tensor
202
	Argsort(ctx Context) Tensor
Michael Yang's avatar
Michael Yang committed
203
204
205
206
207
	Mean(ctx Context) Tensor
	Variance(ctx Context) Tensor
	Stddev(ctx Context) Tensor
	Sqr(ctx Context) Tensor
	Sqrt(ctx Context) Tensor
Michael Yang's avatar
Michael Yang committed
208
209

	Interpolate(ctx Context, dims [4]int, samplingMode SamplingMode) Tensor
Michael Yang's avatar
Michael Yang committed
210
211
}

212
213
214
215
// ScaledDotProductAttention implements a fused attention
// operation equivalent to following code on a tensor named
// query:
//
216
217
218
219
// 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)
//
220
221
222
223
224
225
226
227
228
229
230
231
// 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)
// return kqv.Permute(ctx, 0, 2, 1, 3).Contiguous(ctx)
232
233
//
// cacheConfigApplied indicates whether the optimizations requested through CacheConfig have been performed
234
type ScaledDotProductAttention interface {
235
	ScaledDotProductAttention(ctx Context, key, value, mask, sinks Tensor, vmla Tensor, scale float64, cacheConfigApplied bool) Tensor
236
237
}

Michael Yang's avatar
Michael Yang committed
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
type number interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
		~float32 | ~float64 |
		~complex64 | ~complex128
}

func mul[T number](s ...T) T {
	p := T(1)
	for _, v := range s {
		p *= v
	}

	return p
}

254
type DumpOptions func(*dumpOptions)
Michael Yang's avatar
Michael Yang committed
255

256
257
258
259
260
// DumpWithPrecision sets the number of decimal places to print. Applies to float32 and float64.
func DumpWithPrecision(n int) DumpOptions {
	return func(opts *dumpOptions) {
		opts.Precision = n
	}
Michael Yang's avatar
Michael Yang committed
261
262
}

263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
// DumpWithThreshold sets the threshold for printing the entire tensor. If the number of elements
// is less than or equal to this value, the entire tensor will be printed. Otherwise, only the
// beginning and end of each dimension will be printed.
func DumpWithThreshold(n int) DumpOptions {
	return func(opts *dumpOptions) {
		opts.Threshold = n
	}
}

// DumpWithEdgeItems sets the number of elements to print at the beginning and end of each dimension.
func DumpWithEdgeItems(n int) DumpOptions {
	return func(opts *dumpOptions) {
		opts.EdgeItems = n
	}
}

type dumpOptions struct {
	Precision, Threshold, EdgeItems int
}

func Dump(ctx Context, t Tensor, optsFuncs ...DumpOptions) string {
	opts := dumpOptions{Precision: 4, Threshold: 1000, EdgeItems: 3}
	for _, optsFunc := range optsFuncs {
		optsFunc(&opts)
	}

	if mul(t.Shape()...) <= opts.Threshold {
		opts.EdgeItems = math.MaxInt
Michael Yang's avatar
Michael Yang committed
291
292
293
294
	}

	switch t.DType() {
	case DTypeF32:
295
296
		return dump[[]float32](ctx, t, opts.EdgeItems, func(f float32) string {
			return strconv.FormatFloat(float64(f), 'f', opts.Precision, 32)
Jesse Gross's avatar
Jesse Gross committed
297
		})
298
	case DTypeF16, DTypeQ80, DTypeQ40:
299
		f32 := ctx.Input().Empty(DTypeF32, t.Shape()...)
Jesse Gross's avatar
Jesse Gross committed
300
		f32 = t.Copy(ctx, f32)
301
302
		return dump[[]float32](ctx, f32, opts.EdgeItems, func(f float32) string {
			return strconv.FormatFloat(float64(f), 'f', opts.Precision, 32)
Michael Yang's avatar
Michael Yang committed
303
304
		})
	case DTypeI32:
305
		return dump[[]int32](ctx, t, opts.EdgeItems, func(i int32) string {
Michael Yang's avatar
Michael Yang committed
306
307
308
309
310
311
312
			return strconv.FormatInt(int64(i), 10)
		})
	default:
		return "<unsupported>"
	}
}

Jesse Gross's avatar
Jesse Gross committed
313
314
func dump[S ~[]E, E number](ctx Context, t Tensor, items int, fn func(E) string) string {
	if t.Bytes() == nil {
315
		ctx.Forward(t).Compute(t)
Michael Yang's avatar
Michael Yang committed
316
317
318
319
320
321
322
323
	}

	s := make(S, mul(t.Shape()...))
	if err := binary.Read(bytes.NewBuffer(t.Bytes()), binary.LittleEndian, &s); err != nil {
		panic(err)
	}

	shape := t.Shape()
Michael Yang's avatar
Michael Yang committed
324
	slices.Reverse(shape)
Michael Yang's avatar
Michael Yang committed
325
326

	var sb strings.Builder
327
328
	var f func([]int, int)
	f = func(dims []int, stride int) {
Michael Yang's avatar
Michael Yang committed
329
		prefix := strings.Repeat(" ", len(shape)-len(dims)+1)
Michael Yang's avatar
Michael Yang committed
330
331
		sb.WriteString("[")
		defer func() { sb.WriteString("]") }()
332
		for i := 0; i < dims[0]; i++ {
Michael Yang's avatar
Michael Yang committed
333
			if i >= items && i < dims[0]-items {
Michael Yang's avatar
Michael Yang committed
334
				sb.WriteString("..., ")
Michael Yang's avatar
Michael Yang committed
335
336
337
338
339
340
341
342
343
344
345
346
347
348
				// skip to next printable element
				skip := dims[0] - 2*items
				if len(dims) > 1 {
					stride += mul(append(dims[1:], skip)...)
					fmt.Fprint(&sb, strings.Repeat("\n", len(dims)-1), prefix)
				}
				i += skip - 1
			} else if len(dims) > 1 {
				f(dims[1:], stride)
				stride += mul(dims[1:]...)
				if i < dims[0]-1 {
					fmt.Fprint(&sb, ",", strings.Repeat("\n", len(dims)-1), prefix)
				}
			} else {
Michael Yang's avatar
Michael Yang committed
349
350
351
352
353
354
				text := fn(s[stride+i])
				if len(text) > 0 && text[0] != '-' {
					sb.WriteString(" ")
				}

				sb.WriteString(text)
Michael Yang's avatar
Michael Yang committed
355
				if i < dims[0]-1 {
Michael Yang's avatar
Michael Yang committed
356
					sb.WriteString(", ")
Michael Yang's avatar
Michael Yang committed
357
358
359
360
361
362
363
364
365
366
367
368
				}
			}
		}
	}
	f(shape, 0)

	return sb.String()
}

type DType int

const (
Jesse Gross's avatar
Jesse Gross committed
369
370
371
	DTypeOther DType = iota
	DTypeF32
	DTypeF16
372
373
	DTypeQ80
	DTypeQ40
Michael Yang's avatar
Michael Yang committed
374
	DTypeI32
Michael Yang's avatar
Michael Yang committed
375
	DTypeMXFP4
Michael Yang's avatar
Michael Yang committed
376
)
Michael Yang's avatar
Michael Yang committed
377
378
379
380
381
382
383

type SamplingMode int

const (
	SamplingModeNearest SamplingMode = iota
	SamplingModeBilinear
)