model_text.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. package gemma3
  2. import (
  3. "math"
  4. "github.com/ollama/ollama/kvcache"
  5. "github.com/ollama/ollama/ml"
  6. "github.com/ollama/ollama/ml/nn"
  7. "github.com/ollama/ollama/model"
  8. "github.com/ollama/ollama/model/input"
  9. )
  10. type TextOptions struct {
  11. hiddenSize, numHeads, numKVHeads int
  12. attnKeyLen, attnValLen int
  13. eps, ropeScale float32
  14. ropeLocalBase, ropeGlobalBase float32
  15. finalLogitSoftcap float32
  16. largeModelScaling bool
  17. }
  18. type TextModel struct {
  19. model.Base
  20. model.SentencePieceModel
  21. TokenEmbedding *nn.Embedding `gguf:"token_embd"`
  22. Layers []TextLayer `gguf:"blk"`
  23. OutputNorm *nn.RMSNorm `gguf:"output_norm"`
  24. Output *nn.Linear `gguf:"output,alt:token_embd"`
  25. *TextOptions
  26. }
  27. const (
  28. gemma27BLayerCount = 46
  29. )
  30. const (
  31. cacheTypeSWA = iota
  32. cacheTypeCausal
  33. )
  34. func newTextModel(c ml.Config) *TextModel {
  35. m := TextModel{
  36. SentencePieceModel: model.NewSentencePieceModel(
  37. 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+`),
  38. &model.Vocabulary{
  39. Values: c.Strings("tokenizer.ggml.tokens"),
  40. Scores: c.Floats("tokenizer.ggml.scores"),
  41. Types: c.Uints("tokenizer.ggml.token_type"),
  42. BOS: int32(c.Uint("tokenizer.ggml.bos_token_id")),
  43. EOS: int32(c.Uint("tokenizer.ggml.eos_token_id")),
  44. },
  45. ),
  46. Layers: make([]TextLayer, c.Uint("block_count")),
  47. TextOptions: &TextOptions{
  48. hiddenSize: int(c.Uint("embedding_length")),
  49. numHeads: int(c.Uint("attention.head_count")),
  50. numKVHeads: int(c.Uint("attention.head_count_kv")),
  51. attnKeyLen: int(c.Uint("attention.key_length")),
  52. attnValLen: int(c.Uint("attention.value_length")),
  53. eps: c.Float("text.attention.layer_norm_rms_epsilon"),
  54. ropeLocalBase: c.Float("text.rope.local.freq_base", 10000.0),
  55. ropeGlobalBase: c.Float("text.rope.global.freq_base", 1000000.0),
  56. ropeScale: c.Float("text.rope.freq_scale", 1.0),
  57. finalLogitSoftcap: c.Float("text.final_logit_softcapping"),
  58. },
  59. }
  60. return &m
  61. }
  62. type TextSelfAttention struct {
  63. Query *nn.Linear `gguf:"attn_q"`
  64. QueryNorm *nn.RMSNorm `gguf:"attn_q_norm"`
  65. Key *nn.Linear `gguf:"attn_k"`
  66. KeyNorm *nn.RMSNorm `gguf:"attn_k_norm"`
  67. Value *nn.Linear `gguf:"attn_v"`
  68. Output *nn.Linear `gguf:"attn_output"`
  69. }
  70. func (sa *TextSelfAttention) Forward(ctx ml.Context, layer int, hiddenState, positionIDs ml.Tensor, cache kvcache.Cache, opts *TextOptions) ml.Tensor {
  71. batchSize := hiddenState.Dim(1)
  72. ropeType := uint32(2)
  73. ropeBase := opts.ropeLocalBase
  74. if (layer+1)%6 == 0 {
  75. ropeBase = opts.ropeGlobalBase
  76. }
  77. q := sa.Query.Forward(ctx, hiddenState)
  78. q = q.Reshape(ctx, opts.attnKeyLen, opts.numHeads, batchSize)
  79. q = sa.QueryNorm.Forward(ctx, q, opts.eps)
  80. q = q.RoPE(ctx, positionIDs, nil, uint32(opts.attnKeyLen), ropeType, ropeBase, opts.ropeScale)
  81. if opts.largeModelScaling {
  82. q = q.Scale(ctx, 1.0/math.Sqrt(float64(opts.hiddenSize/opts.numHeads)))
  83. } else {
  84. q = q.Scale(ctx, 1.0/math.Sqrt(float64(opts.attnKeyLen)))
  85. }
  86. k := sa.Key.Forward(ctx, hiddenState)
  87. k = k.Reshape(ctx, opts.attnKeyLen, opts.numKVHeads, batchSize)
  88. k = sa.KeyNorm.Forward(ctx, k, opts.eps)
  89. k = k.RoPE(ctx, positionIDs, nil, uint32(opts.attnKeyLen), ropeType, ropeBase, opts.ropeScale)
  90. v := sa.Value.Forward(ctx, hiddenState)
  91. v = v.Reshape(ctx, opts.attnValLen, opts.numKVHeads, batchSize)
  92. scaleFactor := 1.0
  93. kqv := nn.Attention(ctx, q, k, v, scaleFactor, cache)
  94. kqv = kqv.Reshape(ctx, opts.attnValLen*opts.numHeads, batchSize)
  95. return sa.Output.Forward(ctx, kqv)
  96. }
  97. func (m *TextModel) Shift(ctx ml.Context, layer int, key, shift ml.Tensor) (ml.Tensor, error) {
  98. ropeBase := m.TextOptions.ropeLocalBase
  99. if (layer+1)%6 == 0 {
  100. ropeBase = m.TextOptions.ropeGlobalBase
  101. }
  102. return key.RoPE(ctx, shift, nil, uint32(m.TextOptions.attnKeyLen), uint32(2), ropeBase, m.TextOptions.ropeScale), nil
  103. }
  104. type TextMLP struct {
  105. Up *nn.Linear `gguf:"ffn_up"`
  106. Down *nn.Linear `gguf:"ffn_down"`
  107. Gate *nn.Linear `gguf:"ffn_gate"`
  108. }
  109. func (mlp *TextMLP) Forward(ctx ml.Context, hiddenState ml.Tensor, opts *TextOptions) ml.Tensor {
  110. hiddenState = mlp.Gate.Forward(ctx, hiddenState).GELU(ctx).Mul(ctx, mlp.Up.Forward(ctx, hiddenState))
  111. return mlp.Down.Forward(ctx, hiddenState)
  112. }
  113. type TextLayer struct {
  114. AttentionNorm *nn.RMSNorm `gguf:"attn_norm"`
  115. SelfAttention *TextSelfAttention
  116. PostAttentionNorm *nn.RMSNorm `gguf:"post_attention_norm"`
  117. MLPNorm *nn.RMSNorm `gguf:"ffn_norm"`
  118. MLP *TextMLP
  119. PostMLPNorm *nn.RMSNorm `gguf:"post_ffw_norm"`
  120. }
  121. func (l *TextLayer) Forward(ctx ml.Context, layer int, hiddenState, positionIDs, outputs ml.Tensor, cache kvcache.Cache, opts *TextOptions) ml.Tensor {
  122. residual := hiddenState
  123. hiddenState = l.AttentionNorm.Forward(ctx, hiddenState, opts.eps)
  124. hiddenState = l.SelfAttention.Forward(ctx, layer, hiddenState, positionIDs, cache, opts)
  125. hiddenState = l.PostAttentionNorm.Forward(ctx, hiddenState, opts.eps)
  126. // In the final layer (outputs != nil), optimize by pruning to just the token positions
  127. // we need logits for.
  128. if outputs != nil {
  129. hiddenState = hiddenState.Rows(ctx, outputs)
  130. residual = residual.Rows(ctx, outputs)
  131. }
  132. hiddenState = hiddenState.Add(ctx, residual)
  133. residual = hiddenState
  134. hiddenState = l.MLPNorm.Forward(ctx, hiddenState, opts.eps)
  135. hiddenState = l.MLP.Forward(ctx, hiddenState, opts)
  136. hiddenState = l.PostMLPNorm.Forward(ctx, hiddenState, opts.eps)
  137. return hiddenState.Add(ctx, residual)
  138. }
  139. func (m *TextModel) Forward(ctx ml.Context, inputs, positions, outputs ml.Tensor, multimodal []input.MultimodalIndex, cache kvcache.Cache) ml.Tensor {
  140. hiddenState := m.TokenEmbedding.Forward(ctx, inputs)
  141. if multimodal != nil {
  142. visionOutputs := multimodal[0].Multimodal.(ml.Tensor)
  143. offset := multimodal[0].Index - 1 - visionOutputs.Dim(1)
  144. hiddenState = hiddenState.Set(ctx, visionOutputs, offset*hiddenState.Stride(0))
  145. }
  146. hiddenState = hiddenState.Scale(ctx, math.Sqrt(float64(m.TextOptions.hiddenSize)))
  147. if len(m.Layers) == gemma27BLayerCount {
  148. m.TextOptions.largeModelScaling = true
  149. }
  150. for i, layer := range m.Layers {
  151. // gemma alternates between the sliding window (local) and causal (global)
  152. // kv cache every 6 layers
  153. cacheType := cacheTypeSWA
  154. if (i+1)%6 == 0 {
  155. cacheType = cacheTypeCausal
  156. }
  157. cache.SetLayer(i)
  158. wc := cache.(*kvcache.WrapperCache)
  159. wc.SetLayerType(cacheType)
  160. var lastLayerOutputs ml.Tensor
  161. if i == len(m.Layers)-1 {
  162. lastLayerOutputs = outputs
  163. }
  164. hiddenState = layer.Forward(ctx, i, hiddenState, positions, lastLayerOutputs, cache, m.TextOptions)
  165. }
  166. hiddenState = m.OutputNorm.Forward(ctx, hiddenState, m.eps)
  167. hiddenState = m.Output.Forward(ctx, hiddenState)
  168. // final logit softcap
  169. hiddenState = hiddenState.Scale(ctx, 1.0/float64(m.TextOptions.finalLogitSoftcap))
  170. hiddenState = hiddenState.Tanh(ctx)
  171. return hiddenState.Scale(ctx, float64(m.TextOptions.finalLogitSoftcap))
  172. }