backend.go 16.1 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"
Jesse Gross's avatar
Jesse Gross committed
8
	"hash/maphash"
9
	"log/slog"
10
	"math"
Michael Yang's avatar
Michael Yang committed
11
	"slices"
Michael Yang's avatar
Michael Yang committed
12
13
14
	"strconv"
	"strings"

Jesse Gross's avatar
Jesse Gross committed
15
	"github.com/ollama/ollama/format"
16
17
	"github.com/ollama/ollama/fs"
)
Michael Yang's avatar
Michael Yang committed
18
19

type Backend interface {
Jesse Gross's avatar
Jesse Gross committed
20
21
22
	// Close frees all memory associated with this backend
	Close()

23
	Load(ctx context.Context, progress func(float32)) error
24
25
26
27

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

28
	Config() fs.Config
Michael Yang's avatar
Michael Yang committed
29
30
	Get(name string) Tensor
	NewContext() Context
31
	NewContextSize(size int) Context
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
57
58
59
60

	// 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
61
62
}

Jesse Gross's avatar
Jesse Gross committed
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
// GPULayers is a set of layers to be allocated on a single GPU
type GPULayers struct {
	// ID is the identifier of the GPU, as reported in DeviceMemory
	ID string

	// Layers is a set of layer indicies to load
	Layers []int
}

func (g GPULayers) String() string {
	if len(g.Layers) == 0 {
		return ""
	}

	slices.Sort(g.Layers)

	contiguous := true
	base := g.Layers[0]
	for i := range g.Layers {
		if g.Layers[i] != base+i {
			contiguous = false
			break
		}
	}

	if contiguous {
		return fmt.Sprintf("ID:%v Layers:%v(%v..%v)", g.ID, len(g.Layers), g.Layers[0], g.Layers[len(g.Layers)-1])
	} else {
		return fmt.Sprintf("ID:%v Layers:%v%v", g.ID, len(g.Layers), g.Layers)
	}
}

// GPULayersList is a set of layer allocations across multiple GPUs
type GPULayersList []GPULayers

func (l GPULayersList) String() string {
	if l.Sum() > 0 {
		return fmt.Sprintf("%v%v", l.Sum(), []GPULayers(l))
	} else {
		return fmt.Sprintf("%v", []GPULayers(l))
	}
}

// Sum is the total number of layers assigned across all GPUs
func (l GPULayersList) Sum() int {
	var sum int

	for _, g := range l {
		sum += len(g.Layers)
	}

	return sum
}

var h maphash.Hash

// Hash is an identifier of this layer assignment
func (l GPULayersList) Hash() uint64 {
	h.Reset()
	for _, g := range l {
		if len(g.Layers) > 0 {
			h.WriteString(g.ID)
			for _, l := range g.Layers {
				binary.Write(&h, binary.NativeEndian, int64(l))
			}
		}
	}

	return h.Sum64()
}

134
135
// BackendParams controls how the backend loads and executes models
type BackendParams struct {
Jesse Gross's avatar
Jesse Gross committed
136
137
138
139
140
	// 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

141
142
	// NumThreads sets the number of threads to use if running on the CPU
	NumThreads int
Michael Yang's avatar
Michael Yang committed
143

Jesse Gross's avatar
Jesse Gross committed
144
145
	// GPULayers is the set of layers to offload to GPUs
	GPULayers GPULayersList
146
147
148

	// FlashAttention indicates that we should use a fused flash attention kernel
	FlashAttention bool
149
150
}

151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
// ErrNoMem is returned when panicing due to insufficient memory. It includes
// the attempted memory allocation.
type ErrNoMem struct {
	BackendMemory
}

func (e ErrNoMem) Error() string {
	return fmt.Sprintf("insufficient memory - required allocations: %+v", e.BackendMemory)
}

type AllocationStatus int

const (
	// Unallocated memory - have not yet attempted to allocate
	Unallocated AllocationStatus = iota

	// Failed memory - tried to allocate the memory and did not succeed
	Failed

	// Allocated memory = tried and succeeded to allocate memory
	Allocated
)

// Memory is the size of an allocation and whether it was successful.
type Memory struct {
	Size   uint64
	Status AllocationStatus
}

func (m Memory) String() string {
	s := fmt.Sprint(m.Size)

	switch m.Status {
	case Unallocated:
		s += "U"
	case Failed:
		s += "F"
	case Allocated:
		s += "A"
	}

	return s
}

// DeviceMemory provides a breakdown of the memory needed
// per device, such as a CPU or GPU.
type DeviceMemory struct {
	// Name is the name of the device as labeled by the backend. It
	// may not be persistent across instances of the runner.
	Name string

202
203
204
	// ID is an identifier for the device for matching with system
	// management libraries.
	ID string
205

206
207
208
209
210
211
212
213
214
215
	// Weights is the per-layer memory needed for the model weights.
	Weights []Memory

	// Cache is the per-layer memory needed for the KV cache.
	Cache []Memory

	// Graph is the size of the compute graph. It is not per-layer.
	Graph Memory
}

Jesse Gross's avatar
Jesse Gross committed
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
// Allocated returns the total size of the memory that has been successfully
// allocated on this device
func (m DeviceMemory) Allocated() uint64 {
	var mem uint64

	for _, w := range m.Weights {
		if w.Status == Allocated {
			mem += w.Size
		}
	}
	for _, c := range m.Cache {
		if c.Status == Allocated {
			mem += c.Size
		}
	}
	if m.Graph.Status == Allocated {
		mem += m.Graph.Size
	}

	return mem
}

238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
func memoryPresent(mem []Memory) bool {
	return slices.ContainsFunc(mem, func(m Memory) bool { return m.Size != 0 })
}

func (m DeviceMemory) LogValue() slog.Value {
	var attrs []slog.Attr
	if memoryPresent(m.Weights) {
		attrs = append(attrs, slog.Any("Weights", m.Weights))
	}

	if memoryPresent(m.Cache) {
		attrs = append(attrs, slog.Any("Cache", m.Cache))
	}

	if m.Graph.Size != 0 {
		attrs = append(attrs, slog.Any("Graph", m.Graph))
	}

256
257
	if len(attrs) > 0 && m.ID != "" {
		attrs = append([]slog.Attr{slog.String("ID", m.ID)}, attrs...)
258
259
	}

260
261
262
	return slog.GroupValue(attrs...)
}

263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
// BackendMemory provides the amount of memory required to load the model
// per device based on the BackendParams. In some cases, not all required
// allocations will be known at this point. However, the size of the most recent
// allocation is guaranteed to be provided so that if it failed, the caller can
// accommodate that to make forward progress.
type BackendMemory struct {
	// InputsWeights are always located on the CPU and cannot be moved
	InputWeights Memory

	// CPU model components are located in system memory. This does not
	// include unified memory allocated through the GPU.
	CPU DeviceMemory

	// GPU model components are located on one or more GPUs.
	GPUs []DeviceMemory
}

280
281
282
283
284
285
286
287
288
289
290
291
292
293
func (m BackendMemory) LogValue() slog.Value {
	var attrs []slog.Attr
	if m.InputWeights.Size != 0 {
		attrs = append(attrs, slog.Any("InputWeights", m.InputWeights))
	}

	attrs = append(attrs, slog.Any(m.CPU.Name, m.CPU))
	for _, g := range m.GPUs {
		attrs = append(attrs, slog.Any(g.Name, g))
	}

	return slog.GroupValue(attrs...)
}

Jesse Gross's avatar
Jesse Gross committed
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
func sumMemory(mem []Memory) uint64 {
	var sum uint64

	for _, m := range mem {
		sum += m.Size
	}

	return sum
}

// Log prints a high level summary of the memory (allocated or not)
func (m BackendMemory) Log(level slog.Level) {
	var total uint64

	for _, gpu := range m.GPUs {
		if sum := sumMemory(gpu.Weights); sum > 0 {
			slog.Log(context.TODO(), level, "model weights", "device", gpu.Name, "size", format.HumanBytes2(sum))
			total += sum
		}
	}
	if sum := m.InputWeights.Size + sumMemory(m.CPU.Weights); sum > 0 {
		slog.Log(context.TODO(), level, "model weights", "device", m.CPU.Name, "size", format.HumanBytes2(sum))
		total += sum
	}

	for _, gpu := range m.GPUs {
		if sum := sumMemory(gpu.Cache); sum > 0 {
			slog.Log(context.TODO(), level, "kv cache", "device", gpu.Name, "size", format.HumanBytes2(sum))
			total += sum
		}
	}
	if sum := sumMemory(m.CPU.Cache); sum > 0 {
		slog.Log(context.TODO(), level, "kv cache", "device", m.CPU.Name, "size", format.HumanBytes2(sum))
		total += sum
	}

	for _, gpu := range m.GPUs {
		if sum := gpu.Graph.Size; sum > 0 {
			slog.Log(context.TODO(), level, "compute graph", "device", gpu.Name, "size", format.HumanBytes2(sum))
			total += sum
		}
	}
	if sum := m.CPU.Graph.Size; sum > 0 {
		slog.Log(context.TODO(), level, "compute graph", "device", m.CPU.Name, "size", format.HumanBytes2(sum))
		total += sum
	}

	if total > 0 {
		slog.Log(context.TODO(), level, "total memory", "size", format.HumanBytes2(total))
	}
}

346
var backends = make(map[string]func(string, BackendParams) (Backend, error))
347

348
func RegisterBackend(name string, f func(string, BackendParams) (Backend, error)) {
Michael Yang's avatar
Michael Yang committed
349
350
351
352
353
354
355
	if _, ok := backends[name]; ok {
		panic("backend: backend already registered")
	}

	backends[name] = f
}

356
func NewBackend(modelPath string, params BackendParams) (Backend, error) {
Michael Yang's avatar
Michael Yang committed
357
	if backend, ok := backends["ggml"]; ok {
358
		return backend(modelPath, params)
Michael Yang's avatar
Michael Yang committed
359
360
361
362
363
364
	}

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

type Context interface {
365
	Empty(dtype DType, shape ...int) Tensor
Michael Yang's avatar
Michael Yang committed
366
	Zeros(dtype DType, shape ...int) Tensor
367
368
	FromFloatSlice(s []float32, shape ...int) Tensor
	FromIntSlice(s []int32, shape ...int) Tensor
Michael Yang's avatar
Michael Yang committed
369

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

373
	Forward(...Tensor) Context
374
	Compute(...Tensor)
375
	ComputeWithNotify(func(), ...Tensor) // notify callback once compute has begun
376
377
378
379
380

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

383
	MaxGraphNodes() int
384
	Close()
385

386
387
	// Input returns a context appropriate for creating tensors that are
	// inputs to the model (which includes things like output locations)
388
389
390
391
	Input() Context

	// Layer returns a context appropriate for creating intermediate tensors
	Layer(int) Context
Michael Yang's avatar
Michael Yang committed
392
393
394
}

type Tensor interface {
395
396
	Dim(n int) int
	Stride(n int) int
Michael Yang's avatar
Michael Yang committed
397

398
	Shape() []int
Michael Yang's avatar
Michael Yang committed
399
	DType() DType
400
	Cast(ctx Context, dtype DType) Tensor
Michael Yang's avatar
Michael Yang committed
401
402
403
404

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

405
406
	SetValueFromIntSlice(s []int32)

407
	Neg(ctx Context) Tensor
Michael Yang's avatar
Michael Yang committed
408
	Add(ctx Context, t2 Tensor) Tensor
Michael Yang's avatar
Michael Yang committed
409
	Sub(ctx Context, t2 Tensor) Tensor
Michael Yang's avatar
Michael Yang committed
410
	Mul(ctx Context, t2 Tensor) Tensor
411
412
	Div(ctx Context, t2 Tensor) Tensor

Michael Yang's avatar
Michael Yang committed
413
	Mulmat(ctx Context, t2 Tensor) Tensor
414
	MulmatFullPrec(ctx Context, t2 Tensor) Tensor
Michael Yang's avatar
llama4  
Michael Yang committed
415
	MulmatID(ctx Context, t2, ids Tensor) Tensor
416
	AddID(ctx Context, t2, ids Tensor) Tensor
Michael Yang's avatar
Michael Yang committed
417
418
419
420
421

	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
422
	SumRows(ctx Context) Tensor
Michael Yang's avatar
Michael Yang committed
423

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

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

429
430
	Sin(ctx Context) Tensor
	Cos(ctx Context) Tensor
Michael Yang's avatar
Michael Yang committed
431
432
	Tanh(ctx Context) Tensor
	GELU(ctx Context) Tensor
Michael Yang's avatar
Michael Yang committed
433
	QuickGELU(ctx Context) Tensor
Michael Yang's avatar
Michael Yang committed
434
	SILU(ctx Context) Tensor
Michael Yang's avatar
Michael Yang committed
435
	RELU(ctx Context) Tensor
Michael Yang's avatar
llama4  
Michael Yang committed
436
	Sigmoid(ctx Context) Tensor
437
	SwiGLU(ctx Context, up Tensor, alpha, limit float32) Tensor
Michael Yang's avatar
Michael Yang committed
438

439
	Reshape(ctx Context, shape ...int) Tensor
Michael Yang's avatar
Michael Yang committed
440
441
	View(ctx Context, offset int, shape ...int) Tensor
	Permute(ctx Context, shape ...int) Tensor
Michael Yang's avatar
Michael Yang committed
442
	Contiguous(ctx Context, shape ...int) Tensor
Michael Yang's avatar
Michael Yang committed
443
	Set(ctx Context, t2 Tensor, offset int, strides ...int) Tensor
Michael Yang's avatar
Michael Yang committed
444

445
	Pad(ctx Context, shape ...int) Tensor
Michael Yang's avatar
Michael Yang committed
446
447

	Stack(ctx Context, dim int, s ...Tensor) Tensor
448
449
450

	// Repeat repeats the tensor n times along dimension dim
	Repeat(ctx Context, dim, n int) Tensor
Michael Yang's avatar
Michael Yang committed
451
452
453
	Concat(ctx Context, t2 Tensor, dim int) Tensor
	Rows(ctx Context, t2 Tensor) Tensor
	Copy(ctx Context, t2 Tensor) Tensor
454
	Duplicate(ctx Context) Tensor
Michael Yang's avatar
llama4  
Michael Yang committed
455
456

	TopK(ctx Context, k int) Tensor
457
	Argsort(ctx Context) Tensor
Michael Yang's avatar
Michael Yang committed
458
459
460
461
462
463
	Mean(ctx Context) Tensor
	Variance(ctx Context) Tensor
	Stddev(ctx Context) Tensor
	Sqr(ctx Context) Tensor
	Sqrt(ctx Context) Tensor
	Clamp(ctx Context, min, max float32) Tensor
Michael Yang's avatar
Michael Yang committed
464
465
}

466
467
468
469
// ScaledDotProductAttention implements a fused attention
// operation equivalent to following code on a tensor named
// query:
//
470
471
472
473
// 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)
//
474
475
476
477
478
479
480
481
482
483
484
485
486
// 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 {
487
	ScaledDotProductAttention(ctx Context, key, value, mask, sinks Tensor, scale float64) Tensor
488
489
}

Michael Yang's avatar
Michael Yang committed
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
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
}

506
type DumpOptions func(*dumpOptions)
Michael Yang's avatar
Michael Yang committed
507

508
509
510
511
512
// 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
513
514
}

515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
// 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
543
544
545
546
	}

	switch t.DType() {
	case DTypeF32:
547
548
		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
549
		})
550
	case DTypeF16, DTypeQ80, DTypeQ40:
551
		f32 := ctx.Input().Empty(DTypeF32, t.Shape()...)
Jesse Gross's avatar
Jesse Gross committed
552
		f32 = t.Copy(ctx, f32)
553
554
		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
555
556
		})
	case DTypeI32:
557
		return dump[[]int32](ctx, t, opts.EdgeItems, func(i int32) string {
Michael Yang's avatar
Michael Yang committed
558
559
560
561
562
563
564
			return strconv.FormatInt(int64(i), 10)
		})
	default:
		return "<unsupported>"
	}
}

Jesse Gross's avatar
Jesse Gross committed
565
566
func dump[S ~[]E, E number](ctx Context, t Tensor, items int, fn func(E) string) string {
	if t.Bytes() == nil {
567
		ctx.Forward(t).Compute(t)
Michael Yang's avatar
Michael Yang committed
568
569
570
571
572
573
574
575
	}

	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
576
	slices.Reverse(shape)
Michael Yang's avatar
Michael Yang committed
577
578

	var sb strings.Builder
579
580
	var f func([]int, int)
	f = func(dims []int, stride int) {
Michael Yang's avatar
Michael Yang committed
581
		prefix := strings.Repeat(" ", len(shape)-len(dims)+1)
Michael Yang's avatar
Michael Yang committed
582
583
		sb.WriteString("[")
		defer func() { sb.WriteString("]") }()
584
		for i := 0; i < dims[0]; i++ {
Michael Yang's avatar
Michael Yang committed
585
			if i >= items && i < dims[0]-items {
Michael Yang's avatar
Michael Yang committed
586
				sb.WriteString("..., ")
Michael Yang's avatar
Michael Yang committed
587
588
589
590
591
592
593
594
595
596
597
598
599
600
				// 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
601
602
603
604
605
606
				text := fn(s[stride+i])
				if len(text) > 0 && text[0] != '-' {
					sb.WriteString(" ")
				}

				sb.WriteString(text)
Michael Yang's avatar
Michael Yang committed
607
				if i < dims[0]-1 {
Michael Yang's avatar
Michael Yang committed
608
					sb.WriteString(", ")
Michael Yang's avatar
Michael Yang committed
609
610
611
612
613
614
615
616
617
618
619
620
				}
			}
		}
	}
	f(shape, 0)

	return sb.String()
}

type DType int

const (
Jesse Gross's avatar
Jesse Gross committed
621
622
623
	DTypeOther DType = iota
	DTypeF32
	DTypeF16
624
625
	DTypeQ80
	DTypeQ40
Michael Yang's avatar
Michael Yang committed
626
	DTypeI32
Michael Yang's avatar
Michael Yang committed
627
	DTypeMXFP4
Michael Yang's avatar
Michael Yang committed
628
)