model.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. package mllama
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "fmt"
  6. "hash/fnv"
  7. "image"
  8. "slices"
  9. "github.com/ollama/ollama/kvcache"
  10. "github.com/ollama/ollama/ml"
  11. "github.com/ollama/ollama/ml/nn"
  12. "github.com/ollama/ollama/model"
  13. "github.com/ollama/ollama/model/input"
  14. )
  15. type Model struct {
  16. model.Base
  17. model.BytePairEncoding
  18. *VisionModel `gguf:"v,vision"`
  19. *TextModel
  20. Projector *nn.Linear `gguf:"mm.0"`
  21. ImageProcessor
  22. }
  23. const (
  24. crossAttentionLayer = iota
  25. selfAttentionLayer
  26. )
  27. func New(c ml.Config) (model.Model, error) {
  28. // Verify unified config
  29. if c.Uint("vision.block_count") == 0 {
  30. return nil, fmt.Errorf("non-unified vision model not supported")
  31. }
  32. m := Model{
  33. BytePairEncoding: model.NewBytePairEncoding(
  34. c.String("tokenizer.ggml.pretokenizer", `(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
  35. &model.Vocabulary{
  36. Values: c.Strings("tokenizer.ggml.tokens"),
  37. Types: c.Uints("tokenizer.ggml.token_type"),
  38. Merges: c.Strings("tokenizer.ggml.merges"),
  39. BOS: int32(c.Uint("tokenizer.ggml.bos_token_id")),
  40. AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
  41. EOS: int32(c.Uint("tokenizer.ggml.eos_token_id")),
  42. AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
  43. },
  44. ),
  45. ImageProcessor: newImageProcessor(c),
  46. VisionModel: newVisionModel(c),
  47. TextModel: newTextModel(c),
  48. }
  49. encoderCache := kvcache.NewEncoderCache()
  50. encoderCache.SetConfig(ml.CacheConfig{})
  51. m.Cache = kvcache.NewWrapperCache(encoderCache, kvcache.NewCausalCache(m.TextModel.Shift))
  52. return &m, nil
  53. }
  54. func (m *Model) EncodeMultimodal(ctx ml.Context, multimodalData []byte) (any, error) {
  55. image, _, err := image.Decode(bytes.NewReader(multimodalData))
  56. if err != nil {
  57. return nil, err
  58. }
  59. f32s, aspectRatioID, err := m.ImageProcessor.ProcessImage(image)
  60. if err != nil {
  61. return nil, err
  62. }
  63. pixelValues, err := ctx.Input().FromFloatSlice(f32s,
  64. m.ImageProcessor.imageSize,
  65. m.ImageProcessor.imageSize,
  66. m.ImageProcessor.numChannels,
  67. m.ImageProcessor.maxNumTiles,
  68. )
  69. if err != nil {
  70. return nil, err
  71. }
  72. aspectRatio, err := ctx.Input().FromIntSlice([]int32{int32(aspectRatioID)}, 1)
  73. if err != nil {
  74. return nil, err
  75. }
  76. positions := make([]int32, 1601)
  77. for i := range positions {
  78. positions[i] = int32(i)
  79. }
  80. positionIDs, err := ctx.Input().FromIntSlice(positions, len(positions))
  81. if err != nil {
  82. return nil, err
  83. }
  84. crossAttentionStates := m.VisionModel.Forward(ctx, pixelValues, positionIDs, aspectRatio)
  85. return m.Projector.Forward(ctx, crossAttentionStates), nil
  86. }
  87. func (m *Model) PostTokenize(ctx ml.Context, inputs []input.Input) ([]input.Input, error) {
  88. var images []input.Input
  89. fnvHash := fnv.New64a()
  90. for i := range inputs {
  91. if inputs[i].Multimodal == nil {
  92. if len(images) > 0 {
  93. inputs[i].Multimodal = images[0].Multimodal
  94. inputs[i].MultimodalHash = images[0].MultimodalHash
  95. for j := 1; j < len(images); j++ {
  96. inputs[i].Multimodal = inputs[i].Multimodal.(ml.Tensor).Concat(ctx, images[j].Multimodal.(ml.Tensor), 3)
  97. fnvHash.Reset()
  98. binary.Write(fnvHash, binary.NativeEndian, inputs[i].MultimodalHash)
  99. binary.Write(fnvHash, binary.NativeEndian, inputs[j].MultimodalHash)
  100. inputs[i].MultimodalHash = fnvHash.Sum64()
  101. }
  102. images = nil
  103. }
  104. } else {
  105. images = append(images, inputs[i])
  106. inputs[i].Token = -1
  107. }
  108. }
  109. inputs = slices.DeleteFunc(inputs, func(input input.Input) bool { return input.Token == -1 })
  110. return inputs, nil
  111. }
  112. func (m *Model) Forward(ctx ml.Context, opts input.Options) (ml.Tensor, error) {
  113. var crossAttentionStates ml.Tensor
  114. if len(opts.Multimodal) > 0 {
  115. crossAttentionStates = opts.Multimodal[len(opts.Multimodal)-1].Multimodal.(ml.Tensor)
  116. }
  117. inputs, err := ctx.Input().FromIntSlice(opts.Inputs, len(opts.Inputs))
  118. if err != nil {
  119. return nil, err
  120. }
  121. positions, err := ctx.Input().FromIntSlice(opts.Positions, len(opts.Positions))
  122. if err != nil {
  123. return nil, err
  124. }
  125. outputs, err := ctx.Output().FromIntSlice(opts.Outputs, len(opts.Outputs))
  126. if err != nil {
  127. return nil, err
  128. }
  129. // TODO: attention mask, cross attention mask
  130. return m.TextModel.Forward(ctx, inputs, positions, outputs, nil, crossAttentionStates, nil, m.Cache.(*kvcache.WrapperCache)), nil
  131. }
  132. func init() {
  133. model.Register("mllama", New)
  134. }