model.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. package model
  2. import (
  3. "errors"
  4. "fmt"
  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. fs "github.com/ollama/ollama/fs/ggml"
  16. "github.com/ollama/ollama/kvcache"
  17. "github.com/ollama/ollama/ml"
  18. _ "github.com/ollama/ollama/ml/backend"
  19. "github.com/ollama/ollama/model/input"
  20. )
  21. // Model implements a specific model architecture, defining the forward pass and any model-specific configuration
  22. type Model interface {
  23. Forward(ml.Context, input.Options) (ml.Tensor, error)
  24. Backend() ml.Backend
  25. Config() config
  26. }
  27. // MultimodalProcessor must be implemented by multimodal models.
  28. type MultimodalProcessor interface {
  29. // EncodeMultimodal processes a single input (such as an image) and
  30. // generates an output (typically an embedding) that can be used by the model.
  31. //
  32. // The return value is most typically an ml.Tensor, however, different
  33. // type are possible, such as an object containing a tensor plus
  34. // additional metadata, a slice of tensors or even just the original input.
  35. //
  36. // The result may be cached by the runner.
  37. EncodeMultimodal(ml.Context, []byte) (any, error)
  38. // PostTokenize is called after tokenization to allow the model to edit the
  39. // input stream to correctly arrange multimodal elements.
  40. //
  41. // The input is a slice of tokens with the results of EncodeMultimodal interleaved
  42. // in the order that the user provided them. Each element of the slice will be
  43. // either a single token or single multimodal object.
  44. //
  45. // The model must ensure that inputs are stored according to how they will be
  46. // processed and stored in the cache. For example, Llava-style models should insert
  47. // placeholder tokens equal to the feature size of the corresponding image with
  48. // the image itself attached to and split across these tokens. When Forward is called
  49. // a partial subset of these tokens may be submitted according to the batch size.
  50. //
  51. // This function is also responsible for updating MultimodalHash for any Multimodal
  52. // that is modified to ensure that there is a unique hash value that accurately
  53. // represents the contents.
  54. PostTokenize(ml.Context, []input.Input) ([]input.Input, error)
  55. }
  56. // Base implements the common fields and methods for all models
  57. type Base struct {
  58. b ml.Backend
  59. config
  60. }
  61. type config struct {
  62. Cache kvcache.Cache
  63. }
  64. // Backend returns the underlying backend that will run the model
  65. func (m *Base) Backend() ml.Backend {
  66. return m.b
  67. }
  68. func (m *Base) Config() config {
  69. return m.config
  70. }
  71. var models = make(map[string]func(ml.Config) (Model, error))
  72. // Register registers a model constructor for the given architecture
  73. func Register(name string, f func(ml.Config) (Model, error)) {
  74. if _, ok := models[name]; ok {
  75. panic("model: model already registered")
  76. }
  77. models[name] = f
  78. }
  79. // New initializes a new model instance with the provided configuration based on the metadata in the model file
  80. func New(modelPath string, params ml.BackendParams) (Model, error) {
  81. r, err := os.Open(modelPath)
  82. if err != nil {
  83. return nil, err
  84. }
  85. defer r.Close()
  86. b, err := ml.NewBackend(r, params)
  87. if err != nil {
  88. return nil, err
  89. }
  90. arch := b.Config().Architecture()
  91. f, ok := models[arch]
  92. if !ok {
  93. return nil, fmt.Errorf("unsupported model architecture %q", arch)
  94. }
  95. m, err := f(b.Config())
  96. if err != nil {
  97. return nil, err
  98. }
  99. base := Base{b: b, config: m.Config()}
  100. v := reflect.ValueOf(m)
  101. v.Elem().Set(populateFields(base, v.Elem()))
  102. return m, nil
  103. }
  104. func NewTextProcessor(s string) (TextProcessor, error) {
  105. r, err := os.Open(s)
  106. if err != nil {
  107. return nil, err
  108. }
  109. defer r.Close()
  110. meta, _, err := fs.Decode(r, -1)
  111. if err != nil {
  112. return nil, err
  113. }
  114. return getTextProcessor(meta.KV())
  115. }
  116. func getTextProcessor(kv fs.KV) (TextProcessor, error) {
  117. arch := kv.Architecture()
  118. f, ok := models[arch]
  119. if !ok {
  120. return nil, fmt.Errorf("unsupported model architecture %q", arch)
  121. }
  122. m, err := f(kv)
  123. if err != nil {
  124. return nil, err
  125. }
  126. tp, ok := m.(TextProcessor)
  127. if !ok {
  128. return nil, fmt.Errorf("%v is not a TextProcessor", m)
  129. }
  130. return tp, nil
  131. }
  132. func populateFields(base Base, v reflect.Value, tags ...Tag) reflect.Value {
  133. t := v.Type()
  134. if t.Kind() == reflect.Struct {
  135. allNil := true
  136. for i := range t.NumField() {
  137. tt := t.Field(i).Type
  138. vv := v.Field(i)
  139. if !vv.CanSet() {
  140. continue
  141. }
  142. // make a copy
  143. tagsCopy := tags
  144. if tag := t.Field(i).Tag.Get("gguf"); tag != "" {
  145. tagsCopy = append(tagsCopy, ParseTags(tag))
  146. }
  147. if tt == reflect.TypeOf((*Base)(nil)).Elem() {
  148. vv.Set(reflect.ValueOf(base))
  149. } else if tt == reflect.TypeOf((*ml.Tensor)(nil)).Elem() {
  150. var fn func([]Tag) [][]string
  151. fn = func(tags []Tag) (values [][]string) {
  152. if len(tags) < 1 {
  153. return nil
  154. }
  155. values = [][]string{{tags[0].Name}}
  156. for _, alt := range tags[0].Alternate {
  157. values = append(values, []string{alt})
  158. }
  159. for i, value := range values {
  160. for _, rest := range fn(tags[1:]) {
  161. value = append(value, rest...)
  162. }
  163. values[i] = value
  164. }
  165. return values
  166. }
  167. names := fn(tagsCopy)
  168. for _, name := range names {
  169. if tensor := base.Backend().Get(strings.Join(name, ".")); tensor != nil {
  170. slog.Debug("found tensor", "", tensor)
  171. vv.Set(reflect.ValueOf(tensor))
  172. break
  173. }
  174. }
  175. } else if tt.Kind() == reflect.Pointer || tt.Kind() == reflect.Interface {
  176. setPointer(base, vv, tagsCopy)
  177. } else if tt.Kind() == reflect.Slice || tt.Kind() == reflect.Array {
  178. for i := range vv.Len() {
  179. vvv := vv.Index(i)
  180. if vvv.Kind() == reflect.Pointer || vvv.Kind() == reflect.Interface {
  181. setPointer(base, vvv, append(tagsCopy, Tag{Name: strconv.Itoa(i)}))
  182. } else {
  183. vvv.Set(populateFields(base, vvv, append(tagsCopy, Tag{Name: strconv.Itoa(i)})...))
  184. }
  185. }
  186. }
  187. if !canNil(tt) || !vv.IsNil() {
  188. allNil = false
  189. }
  190. }
  191. if allNil {
  192. return reflect.Zero(t)
  193. }
  194. }
  195. return v
  196. }
  197. func setPointer(base Base, v reflect.Value, tags []Tag) {
  198. vv := v
  199. if v.Kind() == reflect.Interface {
  200. if v.IsNil() {
  201. return
  202. }
  203. vv = vv.Elem()
  204. }
  205. vv = vv.Elem()
  206. if v.IsNil() {
  207. vv = reflect.New(v.Type().Elem()).Elem()
  208. }
  209. if f := populateFields(base, vv, tags...); f.CanAddr() {
  210. v.Set(f.Addr())
  211. }
  212. }
  213. type Tag struct {
  214. Name string
  215. Alternate []string
  216. }
  217. func ParseTags(s string) (tag Tag) {
  218. parts := strings.Split(s, ",")
  219. if len(parts) > 0 {
  220. tag.Name = parts[0]
  221. for _, part := range parts[1:] {
  222. if value, ok := strings.CutPrefix(part, "alt:"); ok {
  223. tag.Alternate = append(tag.Alternate, value)
  224. }
  225. }
  226. }
  227. return
  228. }
  229. func canNil(t reflect.Type) bool {
  230. return t.Kind() == reflect.Chan ||
  231. t.Kind() == reflect.Func ||
  232. t.Kind() == reflect.Interface ||
  233. t.Kind() == reflect.Map ||
  234. t.Kind() == reflect.Pointer ||
  235. t.Kind() == reflect.Slice
  236. }
  237. func Forward(ctx ml.Context, m Model, opts input.Options) (ml.Tensor, error) {
  238. if len(opts.Positions) != len(opts.Sequences) {
  239. return nil, fmt.Errorf("length of positions (%v) must match length of seqs (%v)", len(opts.Positions), len(opts.Sequences))
  240. }
  241. if len(opts.Positions) < 1 {
  242. return nil, errors.New("batch size cannot be less than 1")
  243. }
  244. cache := m.Config().Cache
  245. if cache != nil {
  246. err := cache.StartForward(ctx, opts)
  247. if err != nil {
  248. return nil, err
  249. }
  250. }
  251. t, err := m.Forward(ctx, opts)
  252. if err != nil {
  253. return nil, err
  254. }
  255. ctx.Forward(t).Compute(t)
  256. return t, nil
  257. }