model.go 4.4 KB

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