backend.go 4.1 KB

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