model_text.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. package mllama
  2. import (
  3. "math"
  4. "slices"
  5. "github.com/ollama/ollama/kvcache"
  6. "github.com/ollama/ollama/ml"
  7. "github.com/ollama/ollama/ml/nn"
  8. )
  9. type TextSelfAttention struct {
  10. Query *nn.Linear `gguf:"attn_q"`
  11. Key *nn.Linear `gguf:"attn_k"`
  12. Value *nn.Linear `gguf:"attn_v"`
  13. Output *nn.Linear `gguf:"attn_output"`
  14. }
  15. func (sa *TextSelfAttention) Forward(ctx ml.Context, hiddenState, positions, _ ml.Tensor, cache *kvcache.WrapperCache, opts *TextModelOptions) ml.Tensor {
  16. batchSize := hiddenState.Dim(1)
  17. headDim := opts.hiddenSize / opts.numHeads
  18. query := sa.Query.Forward(ctx, hiddenState)
  19. query = query.Reshape(ctx, headDim, opts.numHeads, batchSize)
  20. query = query.RoPE(ctx, positions, opts.RopeFactors, opts.ropeDim, opts.ropeBase, opts.ropeScale)
  21. key := sa.Key.Forward(ctx, hiddenState)
  22. key = key.Reshape(ctx, headDim, opts.numKVHeads, batchSize)
  23. key = key.RoPE(ctx, positions, opts.RopeFactors, opts.ropeDim, opts.ropeBase, opts.ropeScale)
  24. value := sa.Value.Forward(ctx, hiddenState)
  25. value = value.Reshape(ctx, headDim, opts.numKVHeads, batchSize)
  26. scaleFactor := 1.0 / math.Sqrt(float64(headDim))
  27. attention := nn.Attention(ctx, query, key, value, scaleFactor, cache)
  28. attention = attention.Reshape(ctx, opts.hiddenSize, batchSize)
  29. return sa.Output.Forward(ctx, attention)
  30. }
  31. func (m *TextModel) Shift(ctx ml.Context, layer int, key, shift ml.Tensor) (ml.Tensor, error) {
  32. // This will only get called for layers in the causal cache, which are just the self attention layers
  33. return key.RoPE(ctx, shift, m.RopeFactors, m.ropeDim, m.ropeBase, m.ropeScale), nil
  34. }
  35. type TextMLP struct {
  36. Up *nn.Linear `gguf:"ffn_up"`
  37. Down *nn.Linear `gguf:"ffn_down"`
  38. Gate *nn.Linear `gguf:"ffn_gate"`
  39. }
  40. func (mlp *TextMLP) Forward(ctx ml.Context, hiddenState ml.Tensor, opts *TextModelOptions) ml.Tensor {
  41. hiddenState = mlp.Gate.Forward(ctx, hiddenState).SILU(ctx).Mul(ctx, mlp.Up.Forward(ctx, hiddenState))
  42. return mlp.Down.Forward(ctx, hiddenState)
  43. }
  44. type TextSelfAttentionDecoderLayer struct {
  45. AttentionNorm *nn.RMSNorm `gguf:"attn_norm"`
  46. SelfAttention *TextSelfAttention
  47. MLPNorm *nn.RMSNorm `gguf:"ffn_norm"`
  48. MLP *TextMLP
  49. }
  50. func (d *TextSelfAttentionDecoderLayer) Forward(ctx ml.Context, hiddenState, positions, outputs, mask, _, _ ml.Tensor, cache *kvcache.WrapperCache, opts *TextModelOptions) ml.Tensor {
  51. residual := hiddenState
  52. hiddenState = d.AttentionNorm.Forward(ctx, hiddenState, opts.eps)
  53. hiddenState = d.SelfAttention.Forward(ctx, hiddenState, positions, mask, cache, opts)
  54. // In the final layer (outputs != nil), optimize by pruning to just the token positions
  55. // we need logits for.
  56. if outputs != nil {
  57. hiddenState = hiddenState.Rows(ctx, outputs)
  58. residual = residual.Rows(ctx, outputs)
  59. }
  60. hiddenState = hiddenState.Add(ctx, residual)
  61. residual = hiddenState
  62. hiddenState = d.MLPNorm.Forward(ctx, hiddenState, opts.eps)
  63. hiddenState = d.MLP.Forward(ctx, hiddenState, opts)
  64. return hiddenState.Add(ctx, residual)
  65. }
  66. type TextCrossAttention struct {
  67. QueryNorm *nn.RMSNorm `gguf:"cross_attn_q_norm"`
  68. Query *nn.Linear `gguf:"cross_attn_q_proj"`
  69. KeyNorm *nn.RMSNorm `gguf:"cross_attn_k_norm"`
  70. Key *nn.Linear `gguf:"cross_attn_k_proj"`
  71. Value *nn.Linear `gguf:"cross_attn_v_proj"`
  72. Output *nn.Linear `gguf:"cross_attn_o_proj"`
  73. }
  74. func (ca *TextCrossAttention) Forward(ctx ml.Context, hiddenState, crossAttentionStates ml.Tensor, cache *kvcache.WrapperCache, opts *TextModelOptions) ml.Tensor {
  75. batchSize := hiddenState.Dim(1)
  76. headDim := opts.hiddenSize / opts.numHeads
  77. query := ca.Query.Forward(ctx, hiddenState)
  78. query = query.Reshape(ctx, headDim, opts.numHeads, batchSize)
  79. query = ca.QueryNorm.Forward(ctx, query, opts.eps)
  80. var key, value ml.Tensor
  81. if crossAttentionStates != nil {
  82. numVisionTokens, numTiles := crossAttentionStates.Dim(1), crossAttentionStates.Dim(2)
  83. key = ca.Key.Forward(ctx, crossAttentionStates)
  84. key = key.Reshape(ctx, headDim, opts.numKVHeads, numVisionTokens*numTiles)
  85. key = ca.KeyNorm.Forward(ctx, key, opts.eps)
  86. value = ca.Value.Forward(ctx, crossAttentionStates)
  87. value = value.Reshape(ctx, headDim, opts.numKVHeads, numVisionTokens*numTiles)
  88. cache.Put(ctx, key, value)
  89. }
  90. key, value, _ = cache.Get(ctx)
  91. scaleFactor := 1.0 / math.Sqrt(float64(headDim))
  92. query = query.Permute(ctx, 0, 2, 1, 3)
  93. key = key.Permute(ctx, 0, 2, 1, 3)
  94. value = value.Permute(ctx, 1, 2, 0, 3).Contiguous(ctx)
  95. kq := key.MulmatFullPrec(ctx, query)
  96. kq = kq.Scale(ctx, scaleFactor)
  97. kq = kq.Softmax(ctx)
  98. kqv := value.Mulmat(ctx, kq)
  99. attention := kqv.Permute(ctx, 0, 2, 1, 3).Contiguous(ctx)
  100. attention = attention.Reshape(ctx, opts.hiddenSize, batchSize)
  101. return ca.Output.Forward(ctx, attention)
  102. }
  103. type TextCrossAttentionDecoderLayer struct {
  104. AttentionNorm *nn.RMSNorm `gguf:"attn_norm"`
  105. CrossAttention *TextCrossAttention
  106. AttentionGate ml.Tensor `gguf:"cross_attn_attn_gate"`
  107. MLPNorm *nn.RMSNorm `gguf:"ffn_norm"`
  108. MLP *TextMLP
  109. MLPGate ml.Tensor `gguf:"cross_attn_mlp_gate"`
  110. }
  111. func (d *TextCrossAttentionDecoderLayer) Forward(ctx ml.Context, hiddenState, _, _, _, crossAttentionStates, crossAttentionMask ml.Tensor, cache *kvcache.WrapperCache, opts *TextModelOptions) ml.Tensor {
  112. residual := hiddenState
  113. hiddenState = d.AttentionNorm.Forward(ctx, hiddenState, opts.eps)
  114. hiddenState = d.CrossAttention.Forward(ctx, hiddenState, crossAttentionStates, cache, opts)
  115. hiddenState = hiddenState.Mul(ctx, d.AttentionGate.Tanh(ctx))
  116. hiddenState = hiddenState.Add(ctx, residual)
  117. residual = hiddenState
  118. hiddenState = d.MLPNorm.Forward(ctx, hiddenState, opts.eps)
  119. hiddenState = d.MLP.Forward(ctx, hiddenState, opts)
  120. hiddenState = hiddenState.Mul(ctx, d.MLPGate.Tanh(ctx))
  121. return hiddenState.Add(ctx, residual)
  122. }
  123. type TextDecoderLayer interface {
  124. Forward(ctx ml.Context, hiddenState, positionIDs, outputs, mask, crossAttentionStates, crossAttentionMask ml.Tensor, cache *kvcache.WrapperCache, opts *TextModelOptions) ml.Tensor
  125. }
  126. type TextDecoder struct {
  127. Layers []TextDecoderLayer
  128. }
  129. func (d *TextDecoder) Forward(ctx ml.Context, hiddenState, positionIDs, outputs, mask, crossAttentionStates, crossAttentionMask ml.Tensor, cache *kvcache.WrapperCache, opts *TextModelOptions) ml.Tensor {
  130. for i, layer := range d.Layers {
  131. layerType := selfAttentionLayer
  132. if slices.Contains(opts.crossAttentionLayers, uint32(i)) {
  133. layerType = crossAttentionLayer
  134. }
  135. cache.SetLayer(i)
  136. cache.SetLayerType(layerType)
  137. if layerType == selfAttentionLayer || crossAttentionStates != nil || cache.UnderlyingCache().(*kvcache.EncoderCache).EncoderCached() {
  138. var lastLayerOutputs ml.Tensor
  139. if i == len(d.Layers)-1 {
  140. lastLayerOutputs = outputs
  141. }
  142. hiddenState = layer.Forward(ctx, hiddenState, positionIDs, lastLayerOutputs, mask, crossAttentionStates, crossAttentionMask, cache, opts)
  143. }
  144. }
  145. return hiddenState
  146. }
  147. type TextModelOptions struct {
  148. RopeFactors ml.Tensor `gguf:"rope_freqs.weight"`
  149. hiddenSize, numHeads, numKVHeads int
  150. eps, ropeBase, ropeScale float32
  151. ropeDim uint32
  152. crossAttentionLayers []uint32
  153. }
  154. type TextModel struct {
  155. TokenEmbedding *nn.Embedding `gguf:"token_embd"`
  156. Transformer *TextDecoder `gguf:"blk"`
  157. OutputNorm *nn.RMSNorm `gguf:"output_norm"`
  158. Output *nn.Linear `gguf:"output"`
  159. *TextModelOptions
  160. }
  161. func (m *TextModel) Forward(ctx ml.Context, inputIDs, positionIDs, outputs, mask, crossAttentionStates, crossAttentionMask ml.Tensor, cache *kvcache.WrapperCache) ml.Tensor {
  162. hiddenState := m.TokenEmbedding.Forward(ctx, inputIDs)
  163. hiddenState = m.Transformer.Forward(ctx, hiddenState, positionIDs, outputs, mask, crossAttentionStates, crossAttentionMask, cache, m.TextModelOptions)
  164. hiddenState = m.OutputNorm.Forward(ctx, hiddenState, m.eps)
  165. return m.Output.Forward(ctx, hiddenState)
  166. }
  167. func newTextModel(c ml.Config) *TextModel {
  168. var decoderLayers []TextDecoderLayer
  169. for i := range c.Uint("block_count") {
  170. var textDecoderLayer TextDecoderLayer
  171. if slices.Contains(c.Uints("attention.cross_attention_layers"), i) {
  172. textDecoderLayer = &TextCrossAttentionDecoderLayer{}
  173. } else {
  174. textDecoderLayer = &TextSelfAttentionDecoderLayer{}
  175. }
  176. decoderLayers = append(decoderLayers, textDecoderLayer)
  177. }
  178. return &TextModel{
  179. Transformer: &TextDecoder{Layers: decoderLayers},
  180. TextModelOptions: &TextModelOptions{
  181. hiddenSize: int(c.Uint("embedding_length")),
  182. numHeads: int(c.Uint("attention.head_count")),
  183. numKVHeads: int(c.Uint("attention.head_count_kv")),
  184. eps: c.Float("attention.layer_norm_rms_epsilon"),
  185. ropeBase: c.Float("rope.freq_base"),
  186. ropeScale: c.Float("rope.freq_scale", 1),
  187. ropeDim: c.Uint("rope.dimension_count"),
  188. crossAttentionLayers: c.Uints("attention.cross_attention_layers"),
  189. },
  190. }
  191. }