model.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. package gemma2
  2. import (
  3. "fmt"
  4. "math"
  5. "github.com/ollama/ollama/cache"
  6. "github.com/ollama/ollama/cache/causal"
  7. "github.com/ollama/ollama/ml"
  8. "github.com/ollama/ollama/ml/nn"
  9. "github.com/ollama/ollama/model"
  10. )
  11. type Options struct {
  12. RopeFactors ml.Tensor `gguf:"rope_freqs.weight"`
  13. hiddenSize, numHeads, numKVHeads int
  14. attnKeyLen, attnValLen int
  15. eps, ropeBase, ropeScale float32
  16. ropeDim uint32
  17. }
  18. type Model struct {
  19. model.Base
  20. model.BytePairEncoding
  21. TokenEmbedding *nn.Embedding `gguf:"token_embd"`
  22. Layers []Layer `gguf:"blk"`
  23. OutputNorm *nn.RMSNorm `gguf:"output_norm"` // is this supposed to be root means square?
  24. Output *nn.Linear `gguf:"output,alt:token_embd"` // just set to token_embd?
  25. *Options
  26. }
  27. func New(c ml.Config) (model.Model, error) {
  28. m := Model{
  29. BytePairEncoding: model.NewBytePairEncoding(
  30. 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+`),
  31. &model.Vocabulary{
  32. Values: c.Strings("tokenizer.ggml.tokens"),
  33. Types: c.Uints("tokenizer.ggml.token_type"),
  34. BOS: int32(c.Uint("tokenizer.ggml.bos_token_id")),
  35. EOS: int32(c.Uint("tokenizer.ggml.eos_token_id")),
  36. },
  37. ),
  38. Layers: make([]Layer, c.Uint("block_count")),
  39. Options: &Options{
  40. hiddenSize: int(c.Uint("embedding_length")),
  41. numHeads: int(c.Uint("attention.head_count")),
  42. numKVHeads: int(c.Uint("attention.head_count_kv")),
  43. attnKeyLen: int(c.Uint("attention.key_length")),
  44. attnValLen: int(c.Uint("attention.value_length")),
  45. eps: c.Float("attention.layer_norm_rms_epsilon"),
  46. ropeBase: c.Float("rope.freq_base", 10000.0),
  47. ropeScale: c.Float("rope.freq_scale", 1.0),
  48. },
  49. }
  50. m.Cache = causal.NewCausalCache(m.Shift)
  51. return &m, nil
  52. }
  53. type SelfAttention struct {
  54. Query *nn.Linear `gguf:"attn_q"`
  55. Key *nn.Linear `gguf:"attn_k"`
  56. Value *nn.Linear `gguf:"attn_v"`
  57. Output *nn.Linear `gguf:"attn_output"`
  58. }
  59. func (sa *SelfAttention) Forward(ctx ml.Context, hiddenState, positionIDs ml.Tensor, cache cache.Cache, opts *Options) ml.Tensor {
  60. batchSize := hiddenState.Dim(1)
  61. headDim := opts.hiddenSize / opts.numHeads
  62. q := sa.Query.Forward(ctx, hiddenState)
  63. q = q.Reshape(ctx, opts.attnKeyLen, opts.numHeads, batchSize)
  64. q = q.RoPE(ctx, positionIDs, opts.RopeFactors, uint32(headDim), opts.ropeBase, opts.ropeScale)
  65. // todo: this should be 1.0/math.Sqrt(float64(headDim)) for 27B models
  66. q = q.Scale(ctx, 1.0/math.Sqrt(float64(opts.attnKeyLen)))
  67. k := sa.Key.Forward(ctx, hiddenState)
  68. k = k.Reshape(ctx, opts.attnKeyLen, opts.numKVHeads, batchSize)
  69. k = k.RoPE(ctx, positionIDs, opts.RopeFactors, opts.ropeDim, opts.ropeBase, opts.ropeScale)
  70. v := sa.Value.Forward(ctx, hiddenState)
  71. v = v.Reshape(ctx, opts.attnValLen, opts.numKVHeads, batchSize)
  72. cache.Put(ctx, k, v)
  73. k, v, mask := cache.Get(ctx)
  74. q = q.Permute(ctx, 0, 2, 1, 3).Contiguous(ctx)
  75. k = k.Permute(ctx, 0, 2, 1, 3).Contiguous(ctx)
  76. v = v.Permute(ctx, 1, 2, 0, 3).Contiguous(ctx)
  77. kq := k.Mulmat(ctx, q)
  78. kq = kq.Scale(ctx, 1.0/math.Sqrt(float64(headDim)))
  79. kq = kq.Add(ctx, mask)
  80. kq = kq.Softmax(ctx)
  81. kqv := v.Mulmat(ctx, kq)
  82. kqv = kqv.Permute(ctx, 0, 2, 1, 3).Contiguous(ctx)
  83. kqv = kqv.Reshape(ctx, opts.attnValLen*opts.numHeads, batchSize)
  84. return sa.Output.Forward(ctx, kqv)
  85. }
  86. func (m *Model) Shift(ctx ml.Context, layer int, key, shift ml.Tensor) (ml.Tensor, error) {
  87. return key.RoPE(ctx, shift, m.Options.RopeFactors, m.Options.ropeDim, m.Options.ropeBase, m.Options.ropeScale), nil
  88. }
  89. type MLP struct {
  90. Up *nn.Linear `gguf:"ffn_up"`
  91. Down *nn.Linear `gguf:"ffn_down"`
  92. Gate *nn.Linear `gguf:"ffn_gate"`
  93. }
  94. func (mlp *MLP) Forward(ctx ml.Context, hiddenState ml.Tensor, opts *Options) ml.Tensor {
  95. hiddenState = mlp.Gate.Forward(ctx, hiddenState).Tanh(ctx).Mul(ctx, mlp.Up.Forward(ctx, hiddenState))
  96. return mlp.Down.Forward(ctx, hiddenState)
  97. }
  98. type Layer struct {
  99. AttentionNorm *nn.RMSNorm `gguf:"attn_norm"`
  100. SelfAttention *SelfAttention
  101. MLPNorm *nn.RMSNorm `gguf:"ffn_norm"`
  102. MLP *MLP
  103. }
  104. func (l *Layer) Forward(ctx ml.Context, hiddenState, positionIDs ml.Tensor, cache cache.Cache, opts *Options) ml.Tensor {
  105. residual := hiddenState
  106. hiddenState = l.AttentionNorm.Forward(ctx, hiddenState, opts.eps)
  107. hiddenState = l.SelfAttention.Forward(ctx, hiddenState, positionIDs, cache, opts)
  108. hiddenState = hiddenState.Add(ctx, residual)
  109. residual = hiddenState
  110. hiddenState = l.MLPNorm.Forward(ctx, hiddenState, opts.eps)
  111. hiddenState = l.MLP.Forward(ctx, hiddenState, opts)
  112. return hiddenState.Add(ctx, residual)
  113. }
  114. func (m *Model) Forward(ctx ml.Context, opts model.Options) (ml.Tensor, error) {
  115. fmt.Printf("HELLO THERE!!\n")
  116. inputs, err := ctx.FromIntSlice(opts.Inputs, len(opts.Inputs))
  117. if err != nil {
  118. return nil, err
  119. }
  120. inputs = inputs.Scale(ctx, math.Sqrt(float64(m.Options.hiddenSize)))
  121. positions, err := ctx.FromIntSlice(opts.Positions, len(opts.Positions))
  122. if err != nil {
  123. return nil, err
  124. }
  125. hiddenState := m.TokenEmbedding.Forward(ctx, inputs)
  126. ctx.Forward(hiddenState)
  127. fmt.Printf("hidden state = %s\n", ml.Dump(hiddenState))
  128. for i, layer := range m.Layers {
  129. m.Cache.SetLayer(i)
  130. hiddenState = layer.Forward(ctx, hiddenState, positions, m.Cache, m.Options)
  131. }
  132. hiddenState = m.OutputNorm.Forward(ctx, hiddenState, m.eps)
  133. hiddenState = m.Output.Forward(ctx, hiddenState)
  134. outputs, err := ctx.FromIntSlice(opts.Outputs, len(opts.Outputs))
  135. if err != nil {
  136. return nil, err
  137. }
  138. return hiddenState.Rows(ctx, outputs), nil
  139. }
  140. func init() {
  141. model.Register("gemma2", New)
  142. }