model_text.go 6.5 KB

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