model_text.go 8.7 KB

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