model.go 7.4 KB

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