model.go 4.7 KB

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