model.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. image, _, err := image.Decode(bytes.NewReader(multimodalData))
  71. if err != nil {
  72. return nil, err
  73. }
  74. f32s, err := m.ImageProcessor.ProcessImage(image)
  75. if err != nil {
  76. return nil, err
  77. }
  78. pixelValues, err := ctx.Input().FromFloatSlice(f32s,
  79. m.ImageProcessor.imageSize,
  80. m.ImageProcessor.imageSize,
  81. m.ImageProcessor.numChannels,
  82. )
  83. if err != nil {
  84. return nil, err
  85. }
  86. visionOutputs := m.VisionModel.Forward(ctx, pixelValues)
  87. visionOutputs = m.MultiModalProjector.Forward(ctx, visionOutputs, m.imageSize, m.patchSize, m.VisionModel.eps)
  88. return visionOutputs, nil
  89. }
  90. type imageToken struct {
  91. embedding ml.Tensor
  92. index int
  93. }
  94. func (m *Model) PostTokenize(ctx ml.Context, inputs []input.Input) ([]input.Input, error) {
  95. var result []input.Input
  96. fnvHash := fnv.New64a()
  97. for _, inp := range inputs {
  98. if inp.Multimodal == nil {
  99. result = append(result, inp)
  100. } else {
  101. imageInputs := []input.Input{
  102. {Token: 108}, // "\n\n"
  103. {Token: 255999}, // "<start_of_image>""
  104. }
  105. result = append(result, imageInputs...)
  106. // add image embeddings
  107. inputMultimodal := inp.Multimodal.(ml.Tensor)
  108. for i := range inputMultimodal.Dim(1) {
  109. fnvHash.Reset()
  110. binary.Write(fnvHash, binary.NativeEndian, inp.MultimodalHash)
  111. fnvHash.Write([]byte{byte(i)})
  112. imageToken := imageToken{embedding: inputMultimodal, index: i}
  113. result = append(result, input.Input{Multimodal: imageToken, MultimodalHash: fnvHash.Sum64()})
  114. }
  115. result = append(result,
  116. input.Input{Token: 256000}, // <end_of_image>
  117. input.Input{Token: 108}, // "\n\n"
  118. )
  119. }
  120. }
  121. return result, nil
  122. }
  123. func (m *Model) Forward(ctx ml.Context, opts input.Options) (ml.Tensor, error) {
  124. inputs, err := ctx.Input().FromIntSlice(opts.Inputs, len(opts.Inputs))
  125. if err != nil {
  126. return nil, err
  127. }
  128. positions, err := ctx.Input().FromIntSlice(opts.Positions, len(opts.Positions))
  129. if err != nil {
  130. return nil, err
  131. }
  132. outputs, err := ctx.Output().FromIntSlice(opts.Outputs, len(opts.Outputs))
  133. if err != nil {
  134. return nil, err
  135. }
  136. return m.TextModel.Forward(ctx, inputs, positions, outputs, opts, m.Cache), nil
  137. }
  138. func init() {
  139. model.Register("gemma3", New)
  140. }