model_text.go 9.1 KB

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