model.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. package gemma3
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "hash/fnv"
  6. "image"
  7. "slices"
  8. "github.com/ollama/ollama/kvcache"
  9. "github.com/ollama/ollama/ml"
  10. "github.com/ollama/ollama/ml/nn"
  11. "github.com/ollama/ollama/model"
  12. "github.com/ollama/ollama/model/input"
  13. )
  14. type Model struct {
  15. model.Base
  16. model.SentencePieceModel
  17. *VisionModel `gguf:"v,vision"`
  18. *TextModel
  19. *MultiModalProjector `gguf:"mm"`
  20. ImageProcessor
  21. }
  22. var _ model.MultimodalProcessor = (*Model)(nil)
  23. type MultiModalProjector struct {
  24. SoftEmbNorm *nn.RMSNorm `gguf:"mm_soft_emb_norm"`
  25. InputProjection *nn.Linear `gguf:"mm_input_projection"`
  26. }
  27. func (p *MultiModalProjector) Forward(ctx ml.Context, visionOutputs ml.Tensor, eps float32) ml.Tensor {
  28. visionOutputs = p.SoftEmbNorm.Forward(ctx, visionOutputs, eps)
  29. // TODO: inputProjection must be transposed since they're incompatible with visionOutputs
  30. visionOutputs = p.InputProjection.Weight.Permute(ctx, 1, 0, 2, 3).Contiguous(ctx).Mulmat(ctx, visionOutputs)
  31. return visionOutputs
  32. }
  33. func New(c ml.Config) (model.Model, error) {
  34. m := Model{
  35. SentencePieceModel: model.NewSentencePieceModel(
  36. 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+`),
  37. &model.Vocabulary{
  38. Values: c.Strings("tokenizer.ggml.tokens"),
  39. Scores: c.Floats("tokenizer.ggml.scores"),
  40. Types: c.Uints("tokenizer.ggml.token_type"),
  41. BOS: int32(c.Uint("tokenizer.ggml.bos_token_id")),
  42. AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
  43. EOS: int32(1),
  44. AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
  45. EOT: int32(106),
  46. AddEOT: c.Bool("tokenizer.ggml.add_eot_token", false),
  47. },
  48. ),
  49. ImageProcessor: newImageProcessor(c),
  50. VisionModel: newVisionModel(c),
  51. TextModel: newTextModel(c),
  52. }
  53. slidingWindowLen := int32(c.Uint("text.attention.sliding_window"))
  54. m.Cache = kvcache.NewWrapperCache(kvcache.NewSWACache(slidingWindowLen, m.Shift), kvcache.NewCausalCache(m.Shift))
  55. return &m, nil
  56. }
  57. func (m *Model) EncodeMultimodal(ctx ml.Context, multimodalData []byte) (any, error) {
  58. image, _, err := image.Decode(bytes.NewReader(multimodalData))
  59. if err != nil {
  60. return nil, err
  61. }
  62. f32s, err := m.ImageProcessor.ProcessImage(image)
  63. if err != nil {
  64. return nil, err
  65. }
  66. pixelValues, err := ctx.Input().FromFloatSlice(f32s,
  67. m.ImageProcessor.imageSize,
  68. m.ImageProcessor.imageSize,
  69. m.ImageProcessor.numChannels,
  70. )
  71. if err != nil {
  72. return nil, err
  73. }
  74. positionIDs, err := ctx.FromIntSlice([]int32{0}, 1)
  75. if err != nil {
  76. return nil, err
  77. }
  78. visionOutputs := m.VisionModel.Forward(ctx, pixelValues, positionIDs)
  79. visionOutputs = visionOutputs.Permute(ctx, 1, 0, 2, 3).Contiguous(ctx)
  80. patchesPerImage := m.ImageProcessor.imageSize / m.ImageProcessor.patchSize
  81. kernelSize := patchesPerImage * patchesPerImage / 256
  82. visionOutputs = visionOutputs.AvgPool1D(ctx, kernelSize, kernelSize, 0)
  83. visionOutputs = visionOutputs.Permute(ctx, 1, 0, 2, 3).Contiguous(ctx)
  84. visionOutputs = m.MultiModalProjector.Forward(ctx, visionOutputs, m.VisionModel.eps)
  85. return visionOutputs, 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. for j := range images {
  93. if j == 0 {
  94. inputs[i].Multimodal = images[j].Multimodal
  95. inputs[i].MultimodalHash = images[j].MultimodalHash
  96. } else {
  97. inputs[i].Multimodal = inputs[i].Multimodal.(ml.Tensor).Concat(ctx, images[j].Multimodal.(ml.Tensor), 3)
  98. fnvHash.Reset()
  99. binary.Write(fnvHash, binary.NativeEndian, inputs[i].MultimodalHash)
  100. binary.Write(fnvHash, binary.NativeEndian, images[j].MultimodalHash)
  101. inputs[i].MultimodalHash = fnvHash.Sum64()
  102. }
  103. }
  104. images = nil
  105. } else {
  106. images = append(images, inputs[i])
  107. inputs[i].Token = -1
  108. }
  109. }
  110. for i := range inputs {
  111. if inputs[i].Token == -1 {
  112. imageInputs := []input.Input{
  113. {Token: 108}, // "\n\n"
  114. {Token: 255999}, // "<start_of_image>""
  115. }
  116. // <image_soft_token>
  117. imageInputs = append(imageInputs, slices.Repeat([]input.Input{{Token: 262144}}, 256)...)
  118. // <end_of_image>
  119. imageInputs = append(imageInputs, input.Input{Token: 256000})
  120. inputs = append(inputs[:i], append(imageInputs, inputs[i+1:]...)...)
  121. }
  122. }
  123. return inputs, nil
  124. }
  125. func (m *Model) Forward(ctx ml.Context, opts input.Options) (ml.Tensor, error) {
  126. inputs, err := ctx.Input().FromIntSlice(opts.Inputs, len(opts.Inputs))
  127. if err != nil {
  128. return nil, err
  129. }
  130. positions, err := ctx.Input().FromIntSlice(opts.Positions, len(opts.Positions))
  131. if err != nil {
  132. return nil, err
  133. }
  134. outputs, err := ctx.Output().FromIntSlice(opts.Outputs, len(opts.Outputs))
  135. if err != nil {
  136. return nil, err
  137. }
  138. return m.TextModel.Forward(ctx, inputs, positions, outputs, opts.Multimodal, m.Cache), nil
  139. }
  140. func init() {
  141. model.Register("gemma3", New)
  142. }