4141#include " hwy/highway.h"
4242// After highway.h
4343#include " compression/compress-inl.h"
44+ #include " gemma/flash_attention.h"
4445#include " ops/ops-inl.h"
4546
4647HWY_BEFORE_NAMESPACE ();
4748namespace gcpp {
4849namespace HWY_NAMESPACE {
4950
51+ constexpr int kFlagReserved = 1 ; // LINTER: unused, reserved for future use.
52+ constexpr int kUseOldAttention = 2 ;
53+
5054// Computes Q.K scores, which are "logits" (or scores) stored to att.
5155// `k` is a strided view of the kv cache with dimensions [seq_len, qkv_dim].
5256static HWY_INLINE void QDotK (const size_t start_pos, const size_t last_pos,
@@ -71,11 +75,11 @@ static HWY_INLINE void QDotK(const size_t start_pos, const size_t last_pos,
7175 }
7276}
7377
74- static void PositionalEncodingQK (float * qk, const size_t layer_idx,
75- const LayerWeightsPtrs& layer,
76- const AttentionActivations& activations,
77- hwy::Profiler& p, const size_t worker,
78- const size_t pos, const float mul = 1 . 0f ) {
78+ void PositionalEncodingQK (float * qk, const size_t layer_idx,
79+ const LayerWeightsPtrs& layer,
80+ const AttentionActivations& activations,
81+ hwy::Profiler& p, const size_t worker,
82+ const size_t pos, const float mul) {
7983 const size_t qkv_dim = layer.layer_config .qkv_dim ;
8084 const PostQKType& post_qk = layer.layer_config .post_qk ;
8185 // qk is either q or k, so qkv_dim is the length we operate on.
@@ -165,8 +169,7 @@ void SingleDotSoftmaxWeightedSum(
165169
166170// The attention window usually starts at 0 unless `pos` is larger than
167171// the attention window size, then it is `pos` - window_size + 1.
168- static HWY_INLINE size_t StartPos (size_t pos, const ModelConfig& config,
169- size_t layer_idx) {
172+ size_t StartPos (size_t pos, const ModelConfig& config, size_t layer_idx) {
170173 const size_t att_window_size = config.attention_window_sizes [layer_idx];
171174 return pos - HWY_MIN (att_window_size - 1 , pos);
172175}
@@ -314,7 +317,7 @@ static HWY_INLINE void ComputeQKV(size_t num_tokens, const size_t layer_idx,
314317 }
315318
316319 PositionalEncodingQK (kv_f32, layer_idx, layer, activations,
317- env.ctx .profiler , worker, pos);
320+ env.ctx .profiler , worker, pos, /* mul= */ 1 . 0f );
318321 CompressPerThread tls;
319322 Compress (kv_f32, 2 * qkv_dim, tls, MakeSpan (kv, 2 * qkv_dim), 0 );
320323 });
@@ -354,8 +357,12 @@ void GemmaAttention(size_t num_tokens, const size_t layer_idx,
354357 (void )layer_config; // only used in HWY_DASSERT
355358
356359 ComputeQKV (num_tokens, layer_idx, layer, activations, qbatch, flags, env);
357- DotSoftmaxWeightedSum (num_tokens, layer_idx, layer, activations, qbatch,
358- env.ctx );
360+ if (flags & kUseOldAttention ) {
361+ DotSoftmaxWeightedSum (num_tokens, layer_idx, layer, activations, qbatch,
362+ env.ctx );
363+ } else {
364+ FlashAttention (num_tokens, layer_idx, layer, activations, qbatch, env.ctx );
365+ }
359366 SumHeads (layer, activations, env);
360367}
361368
0 commit comments