model.go 5.4 KB

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