model.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. package llama
  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. )
  9. type Options struct {
  10. RopeFactors ml.Tensor `gguf:"rope_freqs.weight"`
  11. ctxLen, hiddenSize, numHeads, numKVHeads int
  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. m := Model{
  26. BytePairEncoding: model.NewBytePairEncoding(
  27. 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. &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: int32(c.Uint("tokenizer.ggml.bos_token_id")),
  33. EOS: int32(c.Uint("tokenizer.ggml.eos_token_id")),
  34. },
  35. ),
  36. Layers: make([]Layer, c.Uint("block_count")),
  37. Options: &Options{
  38. hiddenSize: int(c.Uint("embedding_length")),
  39. numHeads: int(c.Uint("attention.head_count")),
  40. numKVHeads: int(c.Uint("attention.head_count_kv")),
  41. eps: c.Float("attention.layer_norm_rms_epsilon"),
  42. ctxLen: int(c.Uint("context_length")),
  43. ropeBase: c.Float("rope.freq_base"),
  44. ropeScale: c.Float("rope.freq_scale", 1),
  45. ropeDim: c.Uint("rope.dimension_count"),
  46. },
  47. }
  48. m.Cache = kvcache.NewCausalCache(m.Shift)
  49. return &m, nil
  50. }
  51. type SelfAttention struct {
  52. Query *nn.Linear `gguf:"attn_q"`
  53. Key *nn.Linear `gguf:"attn_k"`
  54. Value *nn.Linear `gguf:"attn_v"`
  55. Output *nn.Linear `gguf:"attn_output"`
  56. }
  57. func (sa *SelfAttention) Forward(ctx ml.Context, hiddenState, positionIDs ml.Tensor, cache kvcache.Cache, opts *Options) ml.Tensor {
  58. batchSize := hiddenState.Dim(1)
  59. headDim := opts.hiddenSize / opts.numHeads
  60. rc := ml.RopeConfig{
  61. PositionIDs: positionIDs,
  62. RopeFactors: opts.RopeFactors,
  63. RopeDim: opts.ropeDim,
  64. RopeType: ml.RopeTypeStandard,
  65. OrigCtxLen: opts.ctxLen,
  66. RopeBase: opts.ropeBase,
  67. RopeScale: opts.ropeScale,
  68. }
  69. q := sa.Query.Forward(ctx, hiddenState)
  70. q = q.Reshape(ctx, headDim, opts.numHeads, batchSize)
  71. q = q.RoPE(ctx, rc)
  72. k := sa.Key.Forward(ctx, hiddenState)
  73. k = k.Reshape(ctx, headDim, opts.numKVHeads, batchSize)
  74. k = k.RoPE(ctx, rc)
  75. v := sa.Value.Forward(ctx, hiddenState)
  76. v = v.Reshape(ctx, headDim, opts.numKVHeads, batchSize)
  77. cache.Put(ctx, k, v)
  78. k, v, mask := cache.Get(ctx)
  79. q = q.Permute(ctx, 0, 2, 1, 3).Contiguous(ctx)
  80. k = k.Permute(ctx, 0, 2, 1, 3).Contiguous(ctx)
  81. v = v.Permute(ctx, 1, 2, 0, 3).Contiguous(ctx)
  82. kq := k.MulmatFullPrec(ctx, q)
  83. kq = kq.Scale(ctx, 1.0/math.Sqrt(float64(headDim)))
  84. kq = kq.Add(ctx, mask)
  85. kq = kq.Softmax(ctx)
  86. kqv := v.Mulmat(ctx, kq)
  87. kqv = kqv.Permute(ctx, 0, 2, 1, 3).Contiguous(ctx)
  88. kqv = kqv.Reshape(ctx, opts.hiddenSize, batchSize)
  89. return sa.Output.Forward(ctx, kqv)
  90. }
  91. func (m *Model) Shift(ctx ml.Context, layer int, key, shift ml.Tensor) (ml.Tensor, error) {
  92. return key.RoPE(
  93. ctx,
  94. ml.RopeConfig{
  95. PositionIDs: shift,
  96. RopeFactors: m.Options.RopeFactors,
  97. RopeDim: m.Options.ropeDim,
  98. RopeType: ml.RopeTypeStandard,
  99. OrigCtxLen: m.Options.ctxLen,
  100. RopeBase: m.Options.ropeBase,
  101. RopeScale: m.Options.ropeScale,
  102. },
  103. ), nil
  104. }
  105. type MLP struct {
  106. Up *nn.Linear `gguf:"ffn_up"`
  107. Down *nn.Linear `gguf:"ffn_down"`
  108. Gate *nn.Linear `gguf:"ffn_gate"`
  109. }
  110. func (mlp *MLP) Forward(ctx ml.Context, hiddenState ml.Tensor, opts *Options) ml.Tensor {
  111. hiddenState = mlp.Gate.Forward(ctx, hiddenState).SILU(ctx).Mul(ctx, mlp.Up.Forward(ctx, hiddenState))
  112. return mlp.Down.Forward(ctx, hiddenState)
  113. }
  114. type Layer struct {
  115. AttentionNorm *nn.RMSNorm `gguf:"attn_norm"`
  116. SelfAttention *SelfAttention
  117. MLPNorm *nn.RMSNorm `gguf:"ffn_norm"`
  118. MLP *MLP
  119. }
  120. func (l *Layer) Forward(ctx ml.Context, hiddenState, positionIDs 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 = hiddenState.Add(ctx, residual)
  125. residual = hiddenState
  126. hiddenState = l.MLPNorm.Forward(ctx, hiddenState, opts.eps)
  127. hiddenState = l.MLP.Forward(ctx, hiddenState, opts)
  128. return hiddenState.Add(ctx, residual)
  129. }
  130. func (m *Model) Forward(ctx ml.Context, opts model.Options) (ml.Tensor, error) {
  131. inputs, err := ctx.FromIntSlice(opts.Inputs, len(opts.Inputs))
  132. if err != nil {
  133. return nil, err
  134. }
  135. positions, err := ctx.FromIntSlice(opts.Positions, len(opts.Positions))
  136. if err != nil {
  137. return nil, err
  138. }
  139. hiddenState := m.TokenEmbedding.Forward(ctx, inputs)
  140. for i, layer := range m.Layers {
  141. m.Cache.SetLayer(i)
  142. hiddenState = layer.Forward(ctx, hiddenState, positions, m.Cache, m.Options)
  143. }
  144. hiddenState = m.OutputNorm.Forward(ctx, hiddenState, m.eps)
  145. hiddenState = m.Output.Forward(ctx, hiddenState)
  146. outputs, err := ctx.FromIntSlice(opts.Outputs, len(opts.Outputs))
  147. if err != nil {
  148. return nil, err
  149. }
  150. return hiddenState.Rows(ctx, outputs), nil
  151. }
  152. func init() {
  153. model.Register("llama", New)
  154. }