model.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. package gemma3
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "hash/fnv"
  6. "image"
  7. "math"
  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. tokensPerImage int
  27. }
  28. func (p *MultiModalProjector) Forward(ctx ml.Context, visionOutputs ml.Tensor, imageSize, patchSize int, eps float32) ml.Tensor {
  29. l := visionOutputs.Dim(0)
  30. visionOutputs = visionOutputs.Permute(ctx, 1, 0, 2, 3).Contiguous(ctx)
  31. patchesPerImage := imageSize / patchSize
  32. visionOutputs = visionOutputs.Reshape(ctx, patchesPerImage, patchesPerImage, l)
  33. kernelSize := patchesPerImage / int(math.Sqrt(float64(p.tokensPerImage)))
  34. visionOutputs = visionOutputs.AvgPool2D(ctx, kernelSize, kernelSize, 0)
  35. visionOutputs = visionOutputs.Reshape(ctx, visionOutputs.Dim(0)*visionOutputs.Dim(1), l)
  36. visionOutputs = visionOutputs.Permute(ctx, 1, 0, 2, 3).Contiguous(ctx)
  37. visionOutputs = p.SoftEmbNorm.Forward(ctx, visionOutputs, eps)
  38. // TODO: inputProjection must be transposed since they're incompatible with visionOutputs
  39. visionOutputs = p.InputProjection.Weight.Permute(ctx, 1, 0, 2, 3).Contiguous(ctx).Mulmat(ctx, visionOutputs)
  40. return visionOutputs
  41. }
  42. func New(c ml.Config) (model.Model, error) {
  43. m := Model{
  44. SentencePieceModel: model.NewSentencePieceModel(
  45. 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+`),
  46. &model.Vocabulary{
  47. Values: c.Strings("tokenizer.ggml.tokens"),
  48. Scores: c.Floats("tokenizer.ggml.scores"),
  49. Types: c.Uints("tokenizer.ggml.token_type"),
  50. BOS: int32(c.Uint("tokenizer.ggml.bos_token_id")),
  51. AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
  52. EOS: int32(1),
  53. AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
  54. EOT: int32(106),
  55. AddEOT: c.Bool("tokenizer.ggml.add_eot_token", false),
  56. },
  57. ),
  58. ImageProcessor: newImageProcessor(c),
  59. VisionModel: newVisionModel(c),
  60. TextModel: newTextModel(c),
  61. MultiModalProjector: &MultiModalProjector{
  62. tokensPerImage: int(c.Uint("mm_tokens_per_image", 256)),
  63. },
  64. }
  65. slidingWindowLen := int32(c.Uint("attention.sliding_window"))
  66. m.Cache = kvcache.NewWrapperCache(kvcache.NewSWACache(slidingWindowLen, m.Shift), kvcache.NewCausalCache(m.Shift))
  67. return &m, nil
  68. }
  69. func (m *Model) EncodeMultimodal(ctx ml.Context, multimodalData []byte) (any, error) {
  70. if len(m.VisionModel.Layers) == 0 {
  71. return nil, model.ErrNoVisionModel
  72. }
  73. image, _, err := image.Decode(bytes.NewReader(multimodalData))
  74. if err != nil {
  75. return nil, err
  76. }
  77. f32s, err := m.ImageProcessor.ProcessImage(image)
  78. if err != nil {
  79. return nil, err
  80. }
  81. pixelValues, err := ctx.Input().FromFloatSlice(f32s,
  82. m.ImageProcessor.imageSize,
  83. m.ImageProcessor.imageSize,
  84. m.ImageProcessor.numChannels,
  85. )
  86. if err != nil {
  87. return nil, err
  88. }
  89. visionOutputs := m.VisionModel.Forward(ctx, pixelValues)
  90. visionOutputs = m.MultiModalProjector.Forward(ctx, visionOutputs, m.imageSize, m.patchSize, m.VisionModel.eps)
  91. return visionOutputs, nil
  92. }
  93. type imageToken struct {
  94. embedding ml.Tensor
  95. index int
  96. }
  97. func (m *Model) PostTokenize(ctx ml.Context, inputs []input.Input) ([]input.Input, error) {
  98. var result []input.Input
  99. fnvHash := fnv.New64a()
  100. for _, inp := range inputs {
  101. if inp.Multimodal == nil {
  102. result = append(result, inp)
  103. } else {
  104. imageInputs := []input.Input{
  105. {Token: 108}, // "\n\n"
  106. {Token: 255999}, // "<start_of_image>""
  107. }
  108. result = append(result, imageInputs...)
  109. // add image embeddings
  110. inputMultimodal := inp.Multimodal.(ml.Tensor)
  111. for i := range inputMultimodal.Dim(1) {
  112. fnvHash.Reset()
  113. binary.Write(fnvHash, binary.NativeEndian, inp.MultimodalHash)
  114. fnvHash.Write([]byte{byte(i)})
  115. imageToken := imageToken{embedding: inputMultimodal, index: i}
  116. result = append(result, input.Input{Multimodal: imageToken, MultimodalHash: fnvHash.Sum64()})
  117. }
  118. result = append(result,
  119. input.Input{Token: 256000}, // <end_of_image>
  120. input.Input{Token: 108}, // "\n\n"
  121. )
  122. }
  123. }
  124. return result, nil
  125. }
  126. func (m *Model) Forward(ctx ml.Context, opts input.Options) (ml.Tensor, error) {
  127. inputs, err := ctx.Input().FromIntSlice(opts.Inputs, len(opts.Inputs))
  128. if err != nil {
  129. return nil, err
  130. }
  131. positions, err := ctx.Input().FromIntSlice(opts.Positions, len(opts.Positions))
  132. if err != nil {
  133. return nil, err
  134. }
  135. outputs, err := ctx.Output().FromIntSlice(opts.Outputs, len(opts.Outputs))
  136. if err != nil {
  137. return nil, err
  138. }
  139. return m.TextModel.Forward(ctx, inputs, positions, outputs, opts, m.Cache), nil
  140. }
  141. func init() {
  142. model.Register("gemma3", New)
  143. }