model_text.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. package mistral3
  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 TextOptions struct {
  13. hiddenSize, numHeads, numKVHeads, headDim int
  14. eps, ropeBase, ropeScale float32
  15. ropeDim uint32
  16. }
  17. type TextModel 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. *TextOptions
  25. }
  26. type SelfAttention struct {
  27. Query *nn.Linear `gguf:"attn_q"`
  28. Key *nn.Linear `gguf:"attn_k"`
  29. Value *nn.Linear `gguf:"attn_v"`
  30. Output *nn.Linear `gguf:"attn_output"`
  31. RopeFactors ml.Tensor `gguf:"rope_freqs.weight"`
  32. }
  33. func (sa *SelfAttention) Forward(ctx ml.Context, hiddenState, positionIDs ml.Tensor, cache kvcache.Cache, opts *TextOptions) ml.Tensor {
  34. batchSize := hiddenState.Dim(1)
  35. ropeType := uint32(0)
  36. // Get head dimension - use explicit value if available, otherwise calculate
  37. headDim := opts.headDim
  38. if headDim == 0 {
  39. headDim = opts.hiddenSize / opts.numHeads
  40. }
  41. // Query projection and reshape
  42. q := sa.Query.Forward(ctx, hiddenState)
  43. q = q.Reshape(ctx, headDim, opts.numHeads, batchSize)
  44. q = q.RoPE(ctx, positionIDs, sa.RopeFactors, opts.ropeDim, ropeType, opts.ropeBase, opts.ropeScale)
  45. // Key projection and reshape
  46. k := sa.Key.Forward(ctx, hiddenState)
  47. k = k.Reshape(ctx, headDim, opts.numKVHeads, batchSize)
  48. k = k.RoPE(ctx, positionIDs, sa.RopeFactors, opts.ropeDim, ropeType, opts.ropeBase, opts.ropeScale)
  49. // Value projection and reshape
  50. v := sa.Value.Forward(ctx, hiddenState)
  51. v = v.Reshape(ctx, headDim, opts.numKVHeads, batchSize)
  52. // Attention computation
  53. scaleFactor := 1.0 / math.Sqrt(float64(headDim))
  54. kqv := nn.Attention(ctx, q, k, v, scaleFactor, cache)
  55. // Reshape attention output for final projection
  56. outputDim := headDim * opts.numHeads
  57. kqv = kqv.Reshape(ctx, outputDim, batchSize)
  58. // Apply output projection
  59. return sa.Output.Forward(ctx, kqv)
  60. }
  61. func (m *TextModel) Shift(ctx ml.Context, layer int, key, shift ml.Tensor) (ml.Tensor, error) {
  62. return key.RoPE(ctx, shift, m.Layers[layer].SelfAttention.RopeFactors, uint32(0), m.ropeDim, m.ropeBase, m.ropeScale), nil
  63. }
  64. type MLP struct {
  65. Up *nn.Linear `gguf:"ffn_up"`
  66. Down *nn.Linear `gguf:"ffn_down"`
  67. Gate *nn.Linear `gguf:"ffn_gate"`
  68. }
  69. func (mlp *MLP) Forward(ctx ml.Context, hiddenState ml.Tensor, opts *TextOptions) ml.Tensor {
  70. hiddenState = mlp.Gate.Forward(ctx, hiddenState).SILU(ctx).Mul(ctx, mlp.Up.Forward(ctx, hiddenState))
  71. return mlp.Down.Forward(ctx, hiddenState)
  72. }
  73. type Layer struct {
  74. AttentionNorm *nn.RMSNorm `gguf:"attn_norm"`
  75. SelfAttention *SelfAttention
  76. MLPNorm *nn.RMSNorm `gguf:"ffn_norm"`
  77. MLP *MLP
  78. }
  79. func (l *Layer) Forward(ctx ml.Context, hiddenState, positionIDs, outputs ml.Tensor, cache kvcache.Cache, opts *TextOptions) ml.Tensor {
  80. residual := hiddenState
  81. hiddenState = l.AttentionNorm.Forward(ctx, hiddenState, opts.eps)
  82. hiddenState = l.SelfAttention.Forward(ctx, hiddenState, positionIDs, cache, opts)
  83. // In the final layer (outputs != nil), optimize by pruning to just the token positions
  84. // we need logits for.
  85. if outputs != nil {
  86. hiddenState = hiddenState.Rows(ctx, outputs)
  87. residual = residual.Rows(ctx, outputs)
  88. }
  89. hiddenState = hiddenState.Add(ctx, residual)
  90. residual = hiddenState
  91. hiddenState = l.MLPNorm.Forward(ctx, hiddenState, opts.eps)
  92. hiddenState = l.MLP.Forward(ctx, hiddenState, opts)
  93. return hiddenState.Add(ctx, residual)
  94. }
  95. func (m *TextModel) Forward(ctx ml.Context, inputs, positions, outputs ml.Tensor, batch input.Batch, cache kvcache.Cache) ml.Tensor {
  96. // Process text inputs
  97. hiddenState := m.TokenEmbedding.Forward(ctx, inputs)
  98. // Process through text transformer layers
  99. for i, layer := range m.Layers {
  100. cache.SetLayer(i)
  101. var lastLayerOutputs ml.Tensor
  102. if i == len(m.Layers)-1 {
  103. lastLayerOutputs = outputs
  104. }
  105. hiddenState = layer.Forward(ctx, hiddenState, positions, lastLayerOutputs, cache, m.TextOptions)
  106. }
  107. hiddenState = m.OutputNorm.Forward(ctx, hiddenState, m.eps)
  108. return m.Output.Forward(ctx, hiddenState)
  109. }
  110. func NewTextModel(c ml.Config) (*TextModel, error) {
  111. if !strings.EqualFold(c.String("tokenizer.ggml.model"), "gpt2") {
  112. return nil, fmt.Errorf("tokenizer %s not yet supported", c.String("tokenizer.ggml.model"))
  113. }
  114. textModel := &TextModel{
  115. BytePairEncoding: model.NewBytePairEncoding(
  116. c.String("tokenizer.ggml.pretokenizer", `[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+`),
  117. &model.Vocabulary{
  118. Values: c.Strings("tokenizer.ggml.tokens"),
  119. Types: c.Uints("tokenizer.ggml.token_type"),
  120. Merges: c.Strings("tokenizer.ggml.merges"),
  121. BOS: int32(c.Uint("tokenizer.ggml.bos_token_id", 1)),
  122. AddBOS: c.Bool("tokenizer.ggml.add_bos_token", true),
  123. EOS: int32(c.Uint("tokenizer.ggml.eos_token_id", 2)),
  124. AddEOS: c.Bool("tokenizer.ggml.add_eos_token", false),
  125. },
  126. ),
  127. Layers: make([]Layer, c.Uint("block_count")),
  128. TextOptions: &TextOptions{
  129. hiddenSize: int(c.Uint("embedding_length")),
  130. numHeads: int(c.Uint("attention.head_count")),
  131. numKVHeads: int(c.Uint("attention.head_count_kv")),
  132. headDim: int(c.Uint("attention.key_length")),
  133. eps: c.Float("attention.layer_norm_rms_epsilon"),
  134. ropeBase: c.Float("rope.freq_base"),
  135. ropeScale: c.Float("rope.freq_scale", 1),
  136. ropeDim: c.Uint("rope.dimension_count"),
  137. },
  138. }
  139. return textModel, nil
  140. }