model.go 6.9 KB

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