model.go 4.8 KB

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