backend.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. package ml
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "fmt"
  6. "os"
  7. "strings"
  8. )
  9. type Config interface {
  10. Architecture() string
  11. String(string, ...string) string
  12. Uint(string, ...uint32) uint32
  13. Float(string, ...float32) float32
  14. Strings(string, ...[]string) []string
  15. Uints(string, ...[]uint32) []uint32
  16. }
  17. type Backend interface {
  18. Config() Config
  19. Get(name string) Tensor
  20. NewContext() Context
  21. }
  22. var backends = make(map[string]func(*os.File) (Backend, error))
  23. func RegisterBackend(name string, f func(*os.File) (Backend, error)) {
  24. if _, ok := backends[name]; ok {
  25. panic("backend: backend already registered")
  26. }
  27. backends[name] = f
  28. }
  29. func NewBackend(f *os.File) (Backend, error) {
  30. if backend, ok := backends["mlx"]; ok {
  31. return backend(f)
  32. }
  33. return nil, fmt.Errorf("unsupported backend")
  34. }
  35. type Context interface {
  36. Zeros(dtype DType, shape ...int) Tensor
  37. FromFloatSlice(s []float32, shape ...int) (Tensor, error)
  38. FromIntSlice(s []int32, shape ...int) (Tensor, error)
  39. Forward(Tensor)
  40. Compute(Tensor) Tensor
  41. Close() error
  42. }
  43. type Tensor interface {
  44. Dim(n int) int64
  45. Stride(n int) int64
  46. Shape() []int64
  47. DType() DType
  48. Bytes() []byte
  49. Floats() []float32
  50. Add(ctx Context, t2 Tensor) Tensor
  51. Mul(ctx Context, t2 Tensor) Tensor
  52. Mulmat(ctx Context, t2 Tensor) Tensor
  53. Softmax(ctx Context) Tensor
  54. LayerNorm(ctx Context, weight, bias Tensor, eps float32) Tensor
  55. RMSNorm(ctx Context, weight, bias Tensor, eps float32) Tensor
  56. Scale(ctx Context, s float64) Tensor
  57. Conv2D(ctx Context, weight Tensor, s0, s1, p0, p1, d0, d1 int) Tensor
  58. Rope(ctx Context, positionIDs, ropeFactors Tensor, dim uint32, base, scale float32) Tensor
  59. Tanh(ctx Context) Tensor
  60. GELU(ctx Context) Tensor
  61. SILU(ctx Context) Tensor
  62. Reshape(ctx Context, shape ...int64) Tensor
  63. View(ctx Context, offset int, shape ...int) Tensor
  64. Permute(ctx Context, shape ...int) Tensor
  65. Contiguous(ctx Context) Tensor
  66. Pad(ctx Context, shape ...int64) Tensor
  67. Unpad(ctx Context, shape ...int64) Tensor
  68. Stack(ctx Context, dim int, s ...Tensor) Tensor
  69. Concat(ctx Context, t2 Tensor, dim int) Tensor
  70. Rows(ctx Context, t2 Tensor) Tensor
  71. Copy(ctx Context, t2 Tensor) Tensor
  72. }
  73. type number interface {
  74. ~int | ~int8 | ~int16 | ~int32 | ~int64 |
  75. ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
  76. ~float32 | ~float64 |
  77. ~complex64 | ~complex128
  78. }
  79. func mul[T number](s ...T) T {
  80. p := T(1)
  81. for _, v := range s {
  82. p *= v
  83. }
  84. return p
  85. }
  86. type DumpOptions struct {
  87. // Items is the number of elements to print at the beginning and end of each dimension.
  88. Items int64
  89. // Precision is the number of decimal places to print. Applies to float32 and float64.
  90. Precision int
  91. }
  92. func Dump(t Tensor, opts ...DumpOptions) string {
  93. if len(opts) < 1 {
  94. opts = append(opts, DumpOptions{
  95. Items: 3,
  96. Precision: 4,
  97. })
  98. }
  99. switch t.DType() {
  100. case DTypeF32:
  101. return dump[[]float32](t, opts[0])
  102. case DTypeI32:
  103. return dump[[]int32](t, opts[0])
  104. default:
  105. return "<unsupported>"
  106. }
  107. }
  108. func dump[S ~[]E, E number](t Tensor, opts DumpOptions) string {
  109. bts := t.Bytes()
  110. if bts == nil {
  111. return "<nil>"
  112. }
  113. s := make(S, mul(t.Shape()...))
  114. if err := binary.Read(bytes.NewBuffer(t.Bytes()), binary.LittleEndian, &s); err != nil {
  115. panic(err)
  116. }
  117. shape := t.Shape()
  118. var sb strings.Builder
  119. var f func([]int64, int64)
  120. f = func(dims []int64, stride int64) {
  121. prefix := strings.Repeat(" ", len(shape)-len(dims)+1)
  122. fmt.Fprint(&sb, "[")
  123. defer func() { fmt.Fprint(&sb, "]") }()
  124. for i := int64(0); i < dims[0]; i++ {
  125. if i >= opts.Items && i < dims[0]-opts.Items {
  126. fmt.Fprint(&sb, "..., ")
  127. // skip to next printable element
  128. skip := dims[0] - 2*opts.Items
  129. if len(dims) > 1 {
  130. stride += mul(append(dims[1:], skip)...)
  131. fmt.Fprint(&sb, strings.Repeat("\n", len(dims)-1), prefix)
  132. }
  133. i += skip - 1
  134. } else if len(dims) > 1 {
  135. f(dims[1:], stride)
  136. stride += mul(dims[1:]...)
  137. if i < dims[0]-1 {
  138. fmt.Fprint(&sb, ",", strings.Repeat("\n", len(dims)-1), prefix)
  139. }
  140. } else {
  141. fmt.Fprint(&sb, s[stride+i])
  142. if i < dims[0]-1 {
  143. fmt.Fprint(&sb, ", ")
  144. }
  145. }
  146. }
  147. }
  148. f(shape, 0)
  149. return sb.String()
  150. }
  151. type DType int
  152. const (
  153. DTypeF32 DType = iota
  154. DTypeI32
  155. DTypeOther
  156. )