model.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. package model
  2. import (
  3. "fmt"
  4. "image"
  5. _ "image/jpeg"
  6. _ "image/png"
  7. "log/slog"
  8. "os"
  9. "reflect"
  10. "strconv"
  11. "strings"
  12. _ "golang.org/x/image/bmp"
  13. _ "golang.org/x/image/tiff"
  14. _ "golang.org/x/image/webp"
  15. "github.com/ollama/ollama/cache"
  16. "github.com/ollama/ollama/ml"
  17. _ "github.com/ollama/ollama/ml/backend"
  18. )
  19. type Cache struct {
  20. cache.Cache
  21. cache.Options
  22. }
  23. func (c Cache) Sub(i int) Cache {
  24. if c.Cache != nil {
  25. return Cache{
  26. Cache: c.Cache.Sub(i),
  27. Options: c.Options,
  28. }
  29. }
  30. return c
  31. }
  32. func (c Cache) Put(ctx ml.Context, key, value ml.Tensor, opts cache.Options) (ml.Tensor, ml.Tensor) {
  33. if c.Cache != nil {
  34. return c.Cache.Put(ctx, key, value, opts)
  35. }
  36. return key, value
  37. }
  38. type Options struct {
  39. inputs []int32
  40. Offset int
  41. Images []image.Image
  42. Cache
  43. }
  44. func (opts Options) Inputs() []int32 {
  45. return opts.inputs[opts.Offset:]
  46. }
  47. func (opts Options) Positions() []int32 {
  48. positions := make([]int32, len(opts.inputs)-opts.Offset)
  49. for i := range positions {
  50. positions[i] = int32(opts.Offset + i)
  51. }
  52. return positions
  53. }
  54. type OptionsFunc func(Model, *Options)
  55. func WithInputIDs(ids []int32) OptionsFunc {
  56. return func(m Model, opts *Options) {
  57. opts.inputs = ids
  58. }
  59. }
  60. func WithOffset(offset int) OptionsFunc {
  61. return func(m Model, opts *Options) {
  62. opts.Offset = offset
  63. opts.Cache.Position = offset
  64. }
  65. }
  66. func WithImage(img image.Image) OptionsFunc {
  67. return func(m Model, opts *Options) {
  68. opts.Images = append(opts.Images, img)
  69. }
  70. }
  71. func WithCache(c cache.Cache) OptionsFunc {
  72. return func(m Model, opts *Options) {
  73. opts.Cache = Cache{
  74. Cache: c,
  75. Options: cache.Options{
  76. Position: opts.Offset,
  77. },
  78. }
  79. }
  80. }
  81. type Base struct {
  82. b ml.Backend
  83. }
  84. func (m *Base) Backend() ml.Backend {
  85. return m.b
  86. }
  87. func (m *Base) SetBackend(b ml.Backend) {
  88. m.b = b
  89. }
  90. type Model interface {
  91. Forward(ml.Context, Options) (ml.Tensor, error)
  92. Backend() ml.Backend
  93. SetBackend(ml.Backend)
  94. }
  95. var models = make(map[string]func(ml.Config) (Model, error))
  96. func Register(name string, f func(ml.Config) (Model, error)) {
  97. if _, ok := models[name]; ok {
  98. panic("model: model already registered")
  99. }
  100. models[name] = f
  101. }
  102. func New(s string) (Model, error) {
  103. r, err := os.Open(s)
  104. if err != nil {
  105. return nil, err
  106. }
  107. defer r.Close()
  108. b, err := ml.NewBackend(r)
  109. if err != nil {
  110. return nil, err
  111. }
  112. arch := b.Config().Architecture()
  113. f, ok := models[arch]
  114. if !ok {
  115. return nil, fmt.Errorf("unsupported model architecture %q", arch)
  116. }
  117. m, err := f(b.Config())
  118. if err != nil {
  119. return nil, err
  120. }
  121. if err := loadTensors(b, m); err != nil {
  122. return nil, err
  123. }
  124. m.SetBackend(b)
  125. return m, nil
  126. }
  127. var mlTensorType = reflect.TypeOf((*ml.Tensor)(nil)).Elem()
  128. func loadTensors(b ml.Backend, m any, tensorPath ...string) error {
  129. t := reflect.TypeOf(m)
  130. v := reflect.ValueOf(m)
  131. if t.Kind() == reflect.Pointer {
  132. t = t.Elem()
  133. v = v.Elem()
  134. }
  135. if t.Kind() == reflect.Interface {
  136. return loadTensors(b, v.Interface(), tensorPath...)
  137. }
  138. for i := range t.NumField() {
  139. f := v.Field(i)
  140. fullTensorPath := tensorPath
  141. if tag := t.Field(i).Tag.Get("ggml"); tag != "" {
  142. tensorName, _, _ := strings.Cut(tag, ",")
  143. fullTensorPath = append(tensorPath, tensorName)
  144. }
  145. if !f.CanSet() {
  146. continue
  147. }
  148. if f.Kind() == reflect.Ptr && f.IsNil() {
  149. f.Set(reflect.New(f.Type().Elem()))
  150. } else if f.Kind() == reflect.Interface && f.IsNil() && f.Type().Implements(mlTensorType) {
  151. if tensor := b.Get(strings.Join(fullTensorPath, ".")); tensor != nil {
  152. f.Set(reflect.ValueOf(tensor))
  153. slog.Debug("loaded tensor", "kind", f.Elem().Type(), "", f.Interface())
  154. }
  155. }
  156. if r := reflect.Indirect(f); r.Kind() == reflect.Struct {
  157. if err := loadTensors(b, f.Interface(), fullTensorPath...); err != nil {
  158. return err
  159. }
  160. } else if r.Kind() == reflect.Slice {
  161. for i := range r.Len() {
  162. if err := loadTensors(b, f.Index(i).Addr().Interface(), append(fullTensorPath, strconv.Itoa(i))...); err != nil {
  163. return err
  164. }
  165. }
  166. }
  167. }
  168. return nil
  169. }
  170. func Forward(m Model, optsFuncs ...OptionsFunc) (ml.Tensor, error) {
  171. var opts Options
  172. for _, optsFunc := range optsFuncs {
  173. optsFunc(m, &opts)
  174. }
  175. ctx := m.Backend().NewContext()
  176. t, err := m.Forward(ctx, opts)
  177. if err != nil {
  178. return nil, err
  179. }
  180. defer ctx.Close()
  181. return ctx.Compute(t), nil
  182. }