"vscode:/vscode.git/clone" did not exist on "5bb0accbcffa0e47ab7987062d3895c330aa1f00"
backend.go 8.15 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
8
	"encoding/binary"
	"fmt"
	"os"
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 {
17
	Config() fs.Config
Michael Yang's avatar
Michael Yang committed
18
19
	Get(name string) Tensor
	NewContext() Context
20
	NewContextSize(size int) Context
Michael Yang's avatar
Michael Yang committed
21
22
}

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// 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
42
43
44
45
46
47
48
49

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

	// MaskBatchPadding specifies the multiple for the batch size dimension in the mask.
	// Any position that does not correspond to an actual token will be filled with -Inf.
	MaskBatchPadding int
50
51
}

52
53
// BackendParams controls how the backend loads and executes models
type BackendParams struct {
54
55
56
57
	// Progress is a callback function that allows reporting percentage completion
	// of model loading
	Progress func(float32)

58
59
	// NumThreads sets the number of threads to use if running on the CPU
	NumThreads int
Michael Yang's avatar
Michael Yang committed
60

61
62
63
64
65
66
67
68
	// MainGPU is the index of the primary GPU to use
	MainGPU int

	// NumGPULayers is the number of layers to offload to GPUs
	NumGPULayers int

	// TensorSplit is the fraction of the model to offload to each GPU
	TensorSplit []float32
69
70
71

	// FlashAttention indicates that we should use a fused flash attention kernel
	FlashAttention bool
72
73
}

74
var backends = make(map[string]func(context.Context, *os.File, BackendParams) (Backend, error))
75

76
func RegisterBackend(name string, f func(context.Context, *os.File, BackendParams) (Backend, error)) {
Michael Yang's avatar
Michael Yang committed
77
78
79
80
81
82
83
	if _, ok := backends[name]; ok {
		panic("backend: backend already registered")
	}

	backends[name] = f
}

84
func NewBackend(ctx context.Context, f *os.File, params BackendParams) (Backend, error) {
Michael Yang's avatar
Michael Yang committed
85
	if backend, ok := backends["ggml"]; ok {
86
		return backend(ctx, f, params)
Michael Yang's avatar
Michael Yang committed
87
88
89
90
91
92
	}

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

type Context interface {
93
	Empty(dtype DType, shape ...int) Tensor
Michael Yang's avatar
Michael Yang committed
94
95
96
97
	Zeros(dtype DType, shape ...int) Tensor
	FromFloatSlice(s []float32, shape ...int) (Tensor, error)
	FromIntSlice(s []int32, shape ...int) (Tensor, error)

98
	Forward(...Tensor) Context
99
	Compute(...Tensor)
100
101
102
103
104
105
106

	// 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.
	Reserve() error

107
	MaxGraphNodes() int
108
	Close()
109

110
111
	// Input returns a context appropriate for creating tensors that are
	// inputs to the model (which includes things like output locations)
112
113
114
115
	Input() Context

	// Layer returns a context appropriate for creating intermediate tensors
	Layer(int) Context
Michael Yang's avatar
Michael Yang committed
116
117
118
}

type Tensor interface {
119
120
	Dim(n int) int
	Stride(n int) int
Michael Yang's avatar
Michael Yang committed
121

122
	Shape() []int
Michael Yang's avatar
Michael Yang committed
123
124
125
126
127
	DType() DType

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

128
	Neg(ctx Context) Tensor
Michael Yang's avatar
Michael Yang committed
129
130
131
	Add(ctx Context, t2 Tensor) Tensor
	Mul(ctx Context, t2 Tensor) Tensor
	Mulmat(ctx Context, t2 Tensor) Tensor
132
	MulmatFullPrec(ctx Context, t2 Tensor) Tensor
Michael Yang's avatar
Michael Yang committed
133
134
135
136
137
138

	Softmax(ctx Context) Tensor
	LayerNorm(ctx Context, weight, bias Tensor, eps float32) Tensor
	RMSNorm(ctx Context, weight Tensor, eps float32) Tensor
	Scale(ctx Context, s float64) Tensor

Michael Yang's avatar
Michael Yang committed
139
	AvgPool2D(ctx Context, k, s int, p float32) Tensor
Michael Yang's avatar
Michael Yang committed
140
	Conv2D(ctx Context, weight Tensor, s0, s1, p0, p1, d0, d1 int) Tensor
Michael Yang's avatar
Michael Yang committed
141

Patrick Devine's avatar
Patrick Devine committed
142
	RoPE(ctx Context, positionIDs, ropeFactors Tensor, dim, ropeType uint32, base, scale float32) Tensor
143
	IM2Col(ctx Context, weight Tensor, s0, s1, p0, p1, d0, d1 int) Tensor
Michael Yang's avatar
Michael Yang committed
144

145
146
	Sin(ctx Context) Tensor
	Cos(ctx Context) Tensor
Michael Yang's avatar
Michael Yang committed
147
148
149
150
	Tanh(ctx Context) Tensor
	GELU(ctx Context) Tensor
	SILU(ctx Context) Tensor

151
	Reshape(ctx Context, shape ...int) Tensor
Michael Yang's avatar
Michael Yang committed
152
153
154
	View(ctx Context, offset int, shape ...int) Tensor
	Permute(ctx Context, shape ...int) Tensor
	Contiguous(ctx Context) Tensor
Michael Yang's avatar
Michael Yang committed
155
	Set(ctx Context, t2 Tensor, offset int, strides ...int) Tensor
Michael Yang's avatar
Michael Yang committed
156

157
158
	Pad(ctx Context, shape ...int) Tensor
	Unpad(ctx Context, shape ...int) Tensor
Michael Yang's avatar
Michael Yang committed
159
160

	Stack(ctx Context, dim int, s ...Tensor) Tensor
161
162
163

	// Repeat repeats the tensor n times along dimension dim
	Repeat(ctx Context, dim, n int) Tensor
Michael Yang's avatar
Michael Yang committed
164
165
166
	Concat(ctx Context, t2 Tensor, dim int) Tensor
	Rows(ctx Context, t2 Tensor) Tensor
	Copy(ctx Context, t2 Tensor) Tensor
167
	Duplicate(ctx Context) Tensor
Michael Yang's avatar
Michael Yang committed
168
169
}

170
171
172
173
// ScaledDotProductAttention implements a fused attention
// operation equivalent to following code on a tensor named
// query:
//
174
175
176
177
// 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)
//
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
// 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)
type ScaledDotProductAttention interface {
	ScaledDotProductAttention(ctx Context, key, value, mask Tensor, scale float64) Tensor
}

Michael Yang's avatar
Michael Yang committed
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
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
}

type DumpOptions struct {
	// Items is the number of elements to print at the beginning and end of each dimension.
212
	Items int
Michael Yang's avatar
Michael Yang committed
213
214
215
216
217

	// Precision is the number of decimal places to print. Applies to float32 and float64.
	Precision int
}

Jesse Gross's avatar
Jesse Gross committed
218
func Dump(ctx Context, t Tensor, opts ...DumpOptions) string {
Michael Yang's avatar
Michael Yang committed
219
220
221
222
223
224
225
226
227
	if len(opts) < 1 {
		opts = append(opts, DumpOptions{
			Items:     3,
			Precision: 4,
		})
	}

	switch t.DType() {
	case DTypeF32:
Jesse Gross's avatar
Jesse Gross committed
228
229
230
		return dump[[]float32](ctx, t, opts[0].Items, func(f float32) string {
			return strconv.FormatFloat(float64(f), 'f', opts[0].Precision, 32)
		})
231
	case DTypeF16, DTypeQ80, DTypeQ40:
232
		f32 := ctx.Input().Empty(DTypeF32, t.Shape()...)
Jesse Gross's avatar
Jesse Gross committed
233
234
		f32 = t.Copy(ctx, f32)
		return dump[[]float32](ctx, f32, opts[0].Items, func(f float32) string {
Michael Yang's avatar
Michael Yang committed
235
236
237
			return strconv.FormatFloat(float64(f), 'f', opts[0].Precision, 32)
		})
	case DTypeI32:
Jesse Gross's avatar
Jesse Gross committed
238
		return dump[[]int32](ctx, t, opts[0].Items, func(i int32) string {
Michael Yang's avatar
Michael Yang committed
239
240
241
242
243
244
245
			return strconv.FormatInt(int64(i), 10)
		})
	default:
		return "<unsupported>"
	}
}

Jesse Gross's avatar
Jesse Gross committed
246
247
func dump[S ~[]E, E number](ctx Context, t Tensor, items int, fn func(E) string) string {
	if t.Bytes() == nil {
248
		ctx.Forward(t).Compute(t)
Michael Yang's avatar
Michael Yang committed
249
250
251
252
253
254
255
256
	}

	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
257
	slices.Reverse(shape)
Michael Yang's avatar
Michael Yang committed
258
259

	var sb strings.Builder
260
261
	var f func([]int, int)
	f = func(dims []int, stride int) {
Michael Yang's avatar
Michael Yang committed
262
		prefix := strings.Repeat(" ", len(shape)-len(dims)+1)
Michael Yang's avatar
Michael Yang committed
263
264
		sb.WriteString("[")
		defer func() { sb.WriteString("]") }()
265
		for i := 0; i < dims[0]; i++ {
Michael Yang's avatar
Michael Yang committed
266
			if i >= items && i < dims[0]-items {
Michael Yang's avatar
Michael Yang committed
267
				sb.WriteString("..., ")
Michael Yang's avatar
Michael Yang committed
268
269
270
271
272
273
274
275
276
277
278
279
280
281
				// 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
282
283
284
285
286
287
				text := fn(s[stride+i])
				if len(text) > 0 && text[0] != '-' {
					sb.WriteString(" ")
				}

				sb.WriteString(text)
Michael Yang's avatar
Michael Yang committed
288
				if i < dims[0]-1 {
Michael Yang's avatar
Michael Yang committed
289
					sb.WriteString(", ")
Michael Yang's avatar
Michael Yang committed
290
291
292
293
294
295
296
297
298
299
300
301
				}
			}
		}
	}
	f(shape, 0)

	return sb.String()
}

type DType int

const (
Jesse Gross's avatar
Jesse Gross committed
302
303
304
	DTypeOther DType = iota
	DTypeF32
	DTypeF16
305
306
	DTypeQ80
	DTypeQ40
Michael Yang's avatar
Michael Yang committed
307
308
	DTypeI32
)