diff --git a/gemma/activations.h b/gemma/activations.h index ba36628f..2a0ef7e2 100644 --- a/gemma/activations.h +++ b/gemma/activations.h @@ -43,13 +43,37 @@ typedef std::vector> AlignedBF16Vector; // Returns the scale value to use for the query in the attention computation. // Also called by ops_test. +static inline const std::vector& ActiveLayerConfigs( + const ModelConfig& c) { + return c.is_encoder_decoder ? c.decoder_layer_configs : c.layer_configs; +} static inline size_t MaxQkvDim(const ModelConfig& config) { size_t max_dim = 0; - for (const auto& lc : config.layer_configs) { - max_dim = HWY_MAX(max_dim, lc.qkv_dim); - } + for (const auto& lc : config.layer_configs) + max_dim = HWY_MAX(max_dim, static_cast(lc.qkv_dim)); + for (const auto& lc : config.decoder_layer_configs) + max_dim = HWY_MAX(max_dim, static_cast(lc.qkv_dim)); return max_dim; } +static inline size_t MaxHeads(const std::vector& layers, + size_t fallback = 0) { + for (const auto& lc : layers) + fallback = HWY_MAX(fallback, static_cast(lc.heads)); + return fallback; +} +static inline size_t MinHeads(const std::vector& layers, + size_t fallback = 0) { + size_t m = fallback ? fallback : ~size_t{0}; + for (const auto& lc : layers) + if (lc.heads) m = HWY_MIN(m, static_cast(lc.heads)); + return m == ~size_t{0} ? size_t{1} : m; +} +static inline size_t MaxKVHeads(const std::vector& layers, + size_t fallback = 0) { + for (const auto& lc : layers) + fallback = HWY_MAX(fallback, static_cast(lc.kv_heads)); + return fallback; +} static inline size_t MaxFFHiddenDim(const ModelConfig& config) { size_t max_dim = config.model_dim; if (config.num_mtp_layers > 1) { @@ -79,50 +103,53 @@ struct AttentionActivations { size_t batch_size, size_t seq_len, const RuntimeConfig& runtime_config, size_t max_workers, const Allocator& allocator, std::vector>& row_ptrs) - : heads(layer_config.heads), + : heads(MaxHeads(ActiveLayerConfigs(config), layer_config.heads)), + kv_heads(MaxKVHeads(ActiveLayerConfigs(config), layer_config.kv_heads)), qkv_dim(layer_config.qkv_dim), - max_qkv_dim(MaxQkvDim(config)), + max_qkv_dim(HWY_MAX(MaxQkvDim(config), + static_cast(layer_config.qkv_dim))), rep_factor(max_workers * AttentionActivations::kThreadReplicationFactor / - layer_config.heads), + MinHeads(ActiveLayerConfigs(config), layer_config.heads)), // `vocab_size == 0` means it is for Vit part, VitAttention // is still MHA and does not use an external KV cache. q(MatFactory("q", batch_size, config.vocab_size == 0 - ? layer_config.heads * 3 * max_qkv_dim - : layer_config.heads * max_qkv_dim, + ? (heads + 2 * HWY_MAX(heads, kv_heads)) * max_qkv_dim + : heads * max_qkv_dim, allocator)), q_bf(MatFactory("q_bf", batch_size, config.vocab_size == 0 - ? layer_config.heads * 3 * max_qkv_dim - : layer_config.heads * max_qkv_dim, + ? HWY_MAX(heads * 3, heads + 2 * kv_heads) * + max_qkv_dim + : heads * max_qkv_dim, allocator)), vit_Q(MatFactory("Q2", batch_size, max_qkv_dim, allocator)), vit_K_T(MatFactory( "K2_T", hwy::RoundUpTo(seq_len, kMaxBF16PerVector), - layer_config.heads * hwy::RoundUpTo(max_qkv_dim, kMaxBF16PerVector), + heads * hwy::RoundUpTo(max_qkv_dim, kMaxBF16PerVector), allocator, MatPadding::kPacked)), vit_V_T(MatFactory( "V2_T", hwy::RoundUpTo(seq_len, kMaxBF16PerVector), - layer_config.heads * hwy::RoundUpTo(max_qkv_dim, kMaxBF16PerVector), + heads * hwy::RoundUpTo(max_qkv_dim, kMaxBF16PerVector), allocator, MatPadding::kPacked)), pre_att_rms_out(MatFactory("pre_att_rms_out", batch_size, config.model_dim, allocator)), att_out(MatFactory("att_out", batch_size, - layer_config.heads * max_qkv_dim, allocator)), + heads * max_qkv_dim, allocator)), att_out_reps(MatFactory("att_out", batch_size * rep_factor, - layer_config.heads * max_qkv_dim, allocator)), - softmax_max(MatFactory("softmax_max", batch_size, layer_config.heads, + heads * max_qkv_dim, allocator)), + softmax_max(MatFactory("softmax_max", batch_size, heads, allocator)), softmax_d( - MatFactory("softmax_d", batch_size, layer_config.heads, allocator)), + MatFactory("softmax_d", batch_size, heads, allocator)), att_sums( MatFactory("att_sums", batch_size, config.model_dim, allocator)), - k_tile_vec(MatFactory("k_tile_vec", batch_size * layer_config.kv_heads, + k_tile_vec(MatFactory("k_tile_vec", batch_size * kv_heads, KVCache::kTileSize * max_qkv_dim, allocator)), - v_tile_vec(MatFactory("v_tile_vec", batch_size * layer_config.kv_heads, + v_tile_vec(MatFactory("v_tile_vec", batch_size * kv_heads, KVCache::kTileSize * max_qkv_dim, allocator)), inv_timescale(CreateInvTimescale( @@ -155,13 +182,12 @@ struct AttentionActivations { // This is a guess at the maximum number of params we might need to avoid // reallocations. The actual number of params is determined by the number of // query tiles, which is not known here. - flash_params.reserve(batch_size * layer_config.heads); - split_flash_params.reserve(batch_size * layer_config.heads); + flash_params.reserve(batch_size * heads); + split_flash_params.reserve(batch_size * heads); - const size_t kv_out_elems = - batch_size * layer_config.kv_heads * 2 * max_qkv_dim; + const size_t kv_out_elems = batch_size * kv_heads * 2 * max_qkv_dim; kv_out_mem.resize(kv_out_elems, 0.0f); - const size_t total_queries = batch_size * layer_config.heads; + const size_t total_queries = batch_size * heads; const size_t query_elems = total_queries * max_qkv_dim; float_queries.resize(query_elems, 0.0f); bf16_queries.resize(query_elems); @@ -211,6 +237,7 @@ struct AttentionActivations { } size_t heads; + size_t kv_heads; size_t qkv_dim; size_t max_qkv_dim; AlignedBF16Vector bf16_queries; @@ -288,13 +315,15 @@ struct AttentionActivationsPtrs { float_queries(nullptr), q_scales(nullptr), div_seq_len(static_cast(seq_len)), - div_heads(static_cast(config.layer_configs[0].heads)), + div_heads(static_cast( + HWY_MAX(size_t{1}, MaxHeads(ActiveLayerConfigs(config))))), query_scale(ChooseQueryScale(config)) {} AttentionActivationsPtrs(const ModelConfig& config, size_t seq_len, AttentionActivations& activations) : AttentionActivationsPtrs(config, seq_len, activations.flash_params, activations.split_flash_params) { + rep_factor = activations.rep_factor; q = activations.q; q_bf = activations.q_bf; vit_Q = activations.vit_Q; @@ -335,6 +364,7 @@ struct AttentionActivationsPtrs { pre_att_rms_out.OverrideRows(batch_size); att_out.OverrideRows(batch_size); + if (rep_factor != 0) att_out_reps.OverrideRows(batch_size * rep_factor); softmax_max.OverrideRows(batch_size); softmax_d.OverrideRows(batch_size); att_sums.OverrideRows(batch_size); @@ -406,6 +436,8 @@ struct AttentionActivationsPtrs { hwy::Divisor div_heads; // Query scaling factor for attention computation. float query_scale; + size_t rep_factor = 0; + bool vit_kv_reshaped = false; // Only active when GCPP_TENSOR_STATS. TensorStats* s_att_q = nullptr; diff --git a/gemma/attention_test.cc b/gemma/attention_test.cc index 6484fc0d..8423aaf1 100644 --- a/gemma/attention_test.cc +++ b/gemma/attention_test.cc @@ -1,3 +1,4 @@ +#include #include #include #include // strcmp @@ -36,6 +37,7 @@ #include "compression/compress-inl.h" #include "gemma/attention.h" #include "gemma/configs.h" +#include "gemma/generate_internal.h" #include "util/test_util.h" #include "hwy/tests/test_util-inl.h" @@ -580,6 +582,52 @@ void TestGemmaAttentionFlash() { RunAttentionTest(AttentionImpl::kFlash, true); } +void TestHeterogeneousLayerActivations() { + TestState s; + ModelConfig cfg(Model::GEMMA2_2B, Type::kF32, PromptWrapping::GEMMA_PT); + cfg.vocab_size = cfg.max_seq_len = 64; + cfg.num_layers = 3; + cfg.attention_window_sizes = {16, 64, 16}; + cfg.layer_configs.resize(3); + cfg.layer_configs[0].heads = cfg.layer_configs[2].heads = 2; + cfg.layer_configs[0].kv_heads = cfg.layer_configs[2].kv_heads = 1; + TensorInfoRegistry reg(cfg); + std::vector layers; + layers.reserve(3); + for (size_t i = 0; i < 3; ++i) { + auto& l = layers.emplace_back(i, cfg.layer_configs[i], reg); + for (MatPtr* m : {&l.pre_attention_norm_scale, &l.post_attention_norm_scale, + &l.qkv_einsum_w, &l.attn_vec_einsum_w, + &l.pre_ffw_norm_scale, &l.post_ffw_norm_scale, + &l.gating_einsum_w, &l.linear_w}) + AllocateAndFillRandom(*m, s.ctx.allocator, s.mat_owners, 100 + i); + l.Fixup(cfg.model, s.mat_owners, s.ctx); + } + InferenceArgs inf; + inf.seq_len = 64; + int toks[4] = {1, 2, 3, 4}; + RuntimeConfig rt; + for (auto impl : + {AttentionImpl::kFlash, AttentionImpl::kFlashTransposedQsBF16}) { + rt.attention_impl = impl; + KVCache kv(cfg, inf, rt, s.ctx.allocator); + Activations act(rt, cfg, 4, kv.SeqLen(), s.ctx, s.env.row_ptrs); + act.SetBatchSize(4); + EXPECT_GE(act.attention.q.Stride(), 8u * 256u); + EXPECT_GE(act.attention.k_tile_vec.Rows(), 16u); + FillRandom(act.x, 301); + AllQueries aq(PromptTokens(toks, 4), 0, 0, hwy::Span(&kv, 1)); + QBatch qb(0, 1, aq); + for (size_t i = 0; i < 3; ++i) + TransformerLayer(4, i, layers[i], act, qb, s.env); + ASSERT_TRUE(std::isfinite(act.x.Row(3)[0])); + } + ModelConfig t5(Model::T5GEMMA_S_S, Type::kF32, PromptWrapping::GEMMA_PT); + t5.max_seq_len = 64; + t5.decoder_attention_window_sizes.clear(); + EXPECT_EQ(KVCache(t5, inf, rt, s.ctx.allocator).SeqLen(), 64u); +} + } // namespace HWY_NAMESPACE } // namespace gcpp HWY_AFTER_NAMESPACE(); @@ -589,6 +637,7 @@ HWY_AFTER_NAMESPACE(); namespace gcpp { HWY_BEFORE_TEST(AttentionTest); HWY_EXPORT_AND_TEST_P(AttentionTest, TestGemmaAttentionFlash); +HWY_EXPORT_AND_TEST_P(AttentionTest, TestHeterogeneousLayerActivations); HWY_AFTER_TEST(); } // namespace gcpp diff --git a/gemma/flash_attention.cc b/gemma/flash_attention.cc index 5092f514..07399430 100644 --- a/gemma/flash_attention.cc +++ b/gemma/flash_attention.cc @@ -2190,8 +2190,8 @@ void ComputeFlashParams(size_t num_tokens, const size_t target_parallelism, const size_t total_tasks = token_batch * layer_config.heads; size_t kVTileSize = GetVTileSize(kNF, kHeadGroups, num_tokens, total_tasks, target_parallelism); - // All layers should have the same number of heads. - HWY_DASSERT(activations.div_heads.GetDivisor() == layer_config.heads); + HWY_DASSERT(layer_config.heads != 0 && + layer_config.heads <= activations.div_heads.GetDivisor()); // To maximize adjacent tasks with the same kv matrices, task index is encoded // thus: [qi][kv_head][batch_idx][head_group]. Note that the head index is // split into kv_head and head_group, since the head_group does not affect @@ -2272,7 +2272,7 @@ size_t GetMaxTiles(const std::vector& params, // split_params is cleared and filled with the split tasks. void SplitTasksByKPos(std::vector& params, const size_t kHTileSize, const size_t num_tiles_per_task, - const size_t out_stride, + const size_t out_stride, const size_t att_out_reps_rows, std::vector& split_params) { split_params.clear(); for (auto& param : params) { @@ -2302,6 +2302,7 @@ void SplitTasksByKPos(std::vector& params, for (size_t i = 0; i < split_param.v_tile_size; ++i) { split_param.tq_idx[i] = param.tq_idx[i] * split_param.n_of_n + split_param.i_of_n - 1; + HWY_ASSERT(split_param.tq_idx[i] < att_out_reps_rows); split_param.out_offsets[i] = param.out_offsets[i] + (split_param.tq_idx[i] - param.tq_idx[i]) * out_stride; @@ -2328,7 +2329,10 @@ uint32_t ComputeAndSplitFlashParams(const size_t kNF, const size_t num_tokens, ComputeFlashParams(num_tokens, target_parallelism, layer_idx, activations, qbatch, attention_impl, activations.flash_params); size_t target_workers = std::min(ctx.pools.MaxWorkers(), target_parallelism); - if (activations.flash_params.size() < target_workers) { + const size_t token_batch = num_tokens * qbatch.Size(); + const size_t max_splits = + token_batch != 0 ? activations.att_out_reps.Rows() / token_batch : 0; + if (max_splits >= 2 && activations.flash_params.size() < target_workers) { // Insufficient parallelism for this processor type. Try splitting along the // k positions. size_t max_tiles = GetMaxTiles(activations.flash_params, 2 * kNF); @@ -2343,11 +2347,15 @@ uint32_t ComputeAndSplitFlashParams(const size_t kNF, const size_t num_tokens, activations.flash_params.size() / k4xNFVTileSize, layer_idx, activations, qbatch, attention_impl, activations.flash_params); + max_tiles = GetMaxTiles(activations.flash_params, 2 * kNF); desired_tiles_per_task = hwy::DivCeil(desired_tiles_per_task, k4xNFVTileSize); + desired_tiles_per_task = HWY_MAX(desired_tiles_per_task, + hwy::DivCeil(max_tiles, max_splits)); SplitTasksByKPos( activations.flash_params, 2 * kNF, desired_tiles_per_task, - activations.att_out_reps.Stride(), activations.split_flash_params); + activations.att_out_reps.Stride(), activations.att_out_reps.Rows(), + activations.split_flash_params); return k4xNFVTileSize; } } diff --git a/gemma/flash_attention_test.cc b/gemma/flash_attention_test.cc index 88649b74..b174ae8b 100644 --- a/gemma/flash_attention_test.cc +++ b/gemma/flash_attention_test.cc @@ -169,13 +169,12 @@ void DotSoftmaxWeightedSum(const size_t num_tokens, const size_t layer_idx, const size_t cache_layer_size = layer_config.CacheLayerSize(); const size_t seq_len = activations.SeqLen(); - // All layers should have the same number of heads. - HWY_DASSERT(activations.div_heads.GetDivisor() == layer_config.heads); + const hwy::Divisor div_heads(layer_config.heads); // For each head/token/query, compute Q.K, softmax, and weighted V. const auto func = [&](const size_t task, size_t worker) HWY_ATTR { - const size_t tq_idx = activations.div_heads.Divide(task); - const size_t head = activations.div_heads.Remainder(task); + const size_t tq_idx = div_heads.Divide(task); + const size_t head = div_heads.Remainder(task); GCPP_ZONE(ctx, worker, Zones::kGenAttentionDotSoftmaxWeightedSumPar); const size_t qi = div_qbatch.Remainder(tq_idx); diff --git a/gemma/gemma.cc b/gemma/gemma.cc index 02c3356d..93666ef2 100644 --- a/gemma/gemma.cc +++ b/gemma/gemma.cc @@ -383,6 +383,9 @@ static void T5GemmaEncoderAttentionReference( const size_t kv_heads = layer_config.kv_heads; const size_t heads_per_kv = heads / kv_heads; + q.OverrideCols(heads * qkv_dim); + kv.OverrideCols(2 * kv_heads * qkv_dim); + att_out.OverrideCols(heads * qkv_dim); CallMatMul(pre_att_rms_out, layer.qkv_einsum_w1, /*add=*/nullptr, env, q); CallMatMul(pre_att_rms_out, layer.qkv_einsum_w2, /*add=*/nullptr, env, kv); T5GemmaApplyRope(layer_config, inv_timescale, @@ -646,7 +649,10 @@ static void T5GemmaWriteDecoderKV(const T5GemmaDecoderLayerWeightsPtrs& layer, } const size_t pos = qbatch.Pos(qi); HWY_ASSERT(pos < qbatch.KV(qi).SeqLen()); - KV_t* dst = qbatch.KV(qi).kv_cache.Row(pos) + layer_idx * cache_layer_size; + const size_t layer_offset = + qbatch.KV(qi).cache ? qbatch.KV(qi).cache->layer_flat_offsets[layer_idx] + : layer_idx * cache_layer_size; + KV_t* dst = qbatch.KV(qi).kv_cache.Row(pos) + layer_offset; const float* src = kv.Row(qi); for (size_t i = 0; i < cache_layer_size; ++i) { dst[i] = hwy::ConvertScalarTo(src[i]); @@ -666,6 +672,9 @@ static void T5GemmaDecoderSelfAttentionReference( const size_t heads_per_kv = heads / kv_heads; const size_t cache_layer_size = layer_config.CacheLayerSize(); + activations.attention.q.OverrideCols(heads * qkv_dim); + kv.OverrideCols(2 * kv_heads * qkv_dim); + activations.attention.att_out.OverrideCols(heads * qkv_dim); RMSNormBatched(activations.x, layer.pre_self_attention_norm_scale, activations.attention.pre_att_rms_out, env.ctx); CallMatMul(activations.attention.pre_att_rms_out, layer.self_qkv_einsum_w1, @@ -681,14 +690,17 @@ static void T5GemmaDecoderSelfAttentionReference( const size_t query_pos = qbatch.Pos(qi); const size_t start_pos = T5GemmaDecoderStartPos(config, layer_idx, query_pos); + const size_t layer_offset = + qbatch.KV(qi).cache ? qbatch.KV(qi).cache->layer_flat_offsets[layer_idx] + : layer_idx * cache_layer_size; for (size_t head = 0; head < heads; ++head) { const size_t kv_head = head / heads_per_kv; const float* query = activations.attention.q.Row(qi) + head * qkv_dim; float max_score = -std::numeric_limits::infinity(); for (size_t key_pos = start_pos; key_pos <= query_pos; ++key_pos) { - const KV_t* key = qbatch.KV(qi).kv_cache.Row(key_pos) + - layer_idx * cache_layer_size + kv_head * 2 * qkv_dim; + const KV_t* key = qbatch.KV(qi).kv_cache.Row(key_pos) + layer_offset + + kv_head * 2 * qkv_dim; float score = 0.0f; for (size_t dim = 0; dim < qkv_dim; ++dim) { score += query[dim] * hwy::ConvertScalarTo(key[dim]); @@ -701,8 +713,8 @@ static void T5GemmaDecoderSelfAttentionReference( float* out = activations.attention.att_out.Row(qi) + head * qkv_dim; std::fill(out, out + qkv_dim, 0.0f); for (size_t key_pos = start_pos; key_pos <= query_pos; ++key_pos) { - const KV_t* key = qbatch.KV(qi).kv_cache.Row(key_pos) + - layer_idx * cache_layer_size + kv_head * 2 * qkv_dim; + const KV_t* key = qbatch.KV(qi).kv_cache.Row(key_pos) + layer_offset + + kv_head * 2 * qkv_dim; const KV_t* value = key + qkv_dim; float score = 0.0f; for (size_t dim = 0; dim < qkv_dim; ++dim) { @@ -737,6 +749,8 @@ static void T5GemmaDecoderCrossAttentionReference( const size_t kv_heads = layer_config.kv_heads; const size_t heads_per_kv = heads / kv_heads; + activations.attention.q.OverrideCols(heads * qkv_dim); + activations.attention.att_out.OverrideCols(heads * qkv_dim); RMSNormBatched(activations.x, layer.pre_cross_attention_norm_scale, activations.attention.pre_att_rms_out, env.ctx); CallMatMul(activations.attention.pre_att_rms_out, layer.cross_q_einsum_w, diff --git a/gemma/kv_cache.cc b/gemma/kv_cache.cc index e83f9ed4..4aef65b4 100644 --- a/gemma/kv_cache.cc +++ b/gemma/kv_cache.cc @@ -54,6 +54,12 @@ static const std::vector& KVAttentionWindowSizes( : config.attention_window_sizes; } +static uint32_t KVLayerWindowSize(const ModelConfig& config, + const std::vector& windows, + size_t i) { + return i < windows.size() ? windows[i] : config.max_seq_len; +} + KVCache::KVCache(const Extents2D& kv_extents, size_t num_layers, size_t kv_heads, size_t qkv_dim, const Allocator& allocator) : num_layers(num_layers), @@ -165,8 +171,8 @@ KVCache::KVCache(const ModelConfig& config, const InferenceArgs& inference_args, HWY_ASSERT(kv_layer_configs[i].kv_heads == kv_layer_configs[src].kv_heads); HWY_ASSERT(kv_layer_configs[i].qkv_dim == kv_layer_configs[src].qkv_dim); - HWY_ASSERT(kv_attention_window_sizes[i] == - kv_attention_window_sizes[src]); + HWY_ASSERT(KVLayerWindowSize(config, kv_attention_window_sizes, i) == + KVLayerWindowSize(config, kv_attention_window_sizes, src)); layer_flat_offsets[i] = layer_flat_offsets[src]; layer_k_v_offsets[i] = layer_k_v_offsets[src]; layer_kv_head_offsets[i] = layer_kv_head_offsets[src]; @@ -184,7 +190,7 @@ KVCache::KVCache(const ModelConfig& config, const InferenceArgs& inference_args, k_v_accum += kv_layer_configs[i].kv_heads * rounded_dim; layer_kv_head_offsets[i] = static_cast(kv_head_accum); - kv_head_accum += config.layer_configs[i].kv_heads; + kv_head_accum += kv_layer_configs[i].kv_heads; } k_v_cols = static_cast(k_v_accum); @@ -249,8 +255,8 @@ KVCache::KVCache(const ModelConfig& config, const InferenceArgs& inference_args, HWY_ASSERT(kv_layer_configs[i].kv_heads == kv_layer_configs[src].kv_heads); HWY_ASSERT(kv_layer_configs[i].qkv_dim == kv_layer_configs[src].qkv_dim); - HWY_ASSERT(kv_attention_window_sizes[i] == - kv_attention_window_sizes[src]); + HWY_ASSERT(KVLayerWindowSize(config, kv_attention_window_sizes, i) == + KVLayerWindowSize(config, kv_attention_window_sizes, src)); layer_flat_offsets[i] = layer_flat_offsets[src]; layer_k_v_offsets[i] = layer_k_v_offsets[src]; layer_kv_head_offsets[i] = layer_kv_head_offsets[src]; @@ -268,7 +274,7 @@ KVCache::KVCache(const ModelConfig& config, const InferenceArgs& inference_args, k_v_accum += kv_layer_configs[i].kv_heads * rounded_dim; layer_kv_head_offsets[i] = static_cast(kv_head_accum); - kv_head_accum += config.layer_configs[i].kv_heads; + kv_head_accum += kv_layer_configs[i].kv_heads; } k_v_cols = static_cast(k_v_accum); @@ -351,7 +357,9 @@ KVCache::KVCache(const ModelConfig& config, const InferenceArgs& inference_args, const size_t capped_seq_len = CappedSeqLen(config, inference_args); for (size_t i = 0; i < num_layers; ++i) { if (!kv_layer_configs[i].HasOwnKVCache()) continue; - size_t num_tiles = num_tiles_per_head(kv_attention_window_sizes[i], + const uint32_t window_size = + KVLayerWindowSize(config, kv_attention_window_sizes, i); + size_t num_tiles = num_tiles_per_head(window_size, runtime_config.prefill_tbatch_size, capped_seq_len) * kv_layer_configs[i].kv_heads; @@ -365,12 +373,12 @@ KVCache::KVCache(const ModelConfig& config, const InferenceArgs& inference_args, } } - if (kv_attention_window_sizes[i] == config.max_seq_len) { + if (window_size == config.max_seq_len) { total_global_num_tiles += num_tiles; - global_tile_length = tile_len; + global_tile_length = HWY_MAX(global_tile_length, tile_len); } else { total_local_num_tiles += num_tiles; - local_tile_length = tile_len; + local_tile_length = HWY_MAX(local_tile_length, tile_len); } } @@ -431,10 +439,12 @@ KVCache::KVCache(const ModelConfig& config, const InferenceArgs& inference_args, layer_tile_length += sizeof(int32_t) * kTileSize; } } - bool is_global = kv_attention_window_sizes[i] == config.max_seq_len; + const uint32_t window_size = + KVLayerWindowSize(config, kv_attention_window_sizes, i); + bool is_global = window_size == config.max_seq_len; for (size_t kv = 0; kv < kv_layer_configs[i].kv_heads; ++kv) { size_t num_tiles_per_kv_head = num_tiles_per_head( - kv_attention_window_sizes[i], runtime_config.prefill_tbatch_size, + window_size, runtime_config.prefill_tbatch_size, CappedSeqLen(config, inference_args)); MatPtr kv_ptr("kv_ptr", kv_cache_type, Extents2D(num_tiles_per_kv_head, layer_tile_length)); diff --git a/gemma/vit.cc b/gemma/vit.cc index 35bd4179..e838a44c 100644 --- a/gemma/vit.cc +++ b/gemma/vit.cc @@ -66,7 +66,7 @@ class VitAttention { PROFILER_ZONE("Gen.VitAttention.QKV"); auto& qkv = activations_.attention.q; HWY_ASSERT(qkv.Rows() == num_tokens_); - HWY_ASSERT(qkv.Cols() == layer_config_.heads * 3 * layer_config_.qkv_dim); + qkv.OverrideCols(layer_config_.heads * 3 * layer_config_.qkv_dim); CallMatMul(activations_.attention.pre_att_rms_out, layer_.vit.qkv_einsum_w, layer_.vit.qkv_einsum_b.PackedScale1(), env_, qkv); } @@ -111,9 +111,12 @@ class VitAttention { for (size_t token_h = 0; token_h < kNumTokensH; ++token_h) { KVType* HWY_RESTRICT dst_k = k_output.Row(token_h); KVType* HWY_RESTRICT dst_v = v_output.Row(token_h); + const size_t valid_tokens_l = + std::min(2 * kNF, num_tokens - token_h * 2 * kNF); + const KVType kZero = hwy::ConvertScalarTo(0.0f); size_t dst_k_index = k_or_v_offset; for (size_t q = 0; q < qkv_dim; q += 2) { - for (size_t token_l = 0; token_l < 2 * kNF; + for (size_t token_l = 0; token_l < valid_tokens_l; ++token_l, dst_k_index += 2) { const QKVType* HWY_RESTRICT src_k = qkv.Row(token_h * 2 * kNF + token_l) + qkv_offset + qkv_dim; @@ -121,25 +124,25 @@ class VitAttention { dst_k[dst_k_index + 1] = hwy::ConvertScalarTo(src_k[q + 1]); } + const size_t pad_k = (2 * kNF - valid_tokens_l) * 2; + std::fill_n(dst_k + dst_k_index, pad_k, kZero); + dst_k_index += pad_k; } size_t dst_v_index = k_or_v_offset; for (size_t q = 0; q < qkv_dim; q += 2 * kNF) { - for (size_t token_l = 0; token_l < 2 * kNF; ++token_l) { + const size_t q_count = std::min(2 * kNF, qkv_dim - q); + for (size_t token_l = 0; token_l < valid_tokens_l; ++token_l) { const QKVType* HWY_RESTRICT src_v = qkv.Row(token_h * 2 * kNF + token_l) + qkv_offset + qkv_dim * 2; - if (q + 2 * kNF <= qkv_dim) { - for (size_t q_l = 0; q_l < 2 * kNF; ++q_l) { - dst_v[dst_v_index++] = - hwy::ConvertScalarTo(src_v[q + q_l]); - } - } else { - for (size_t q_l = 0; q_l < qkv_dim - q; ++q_l) { - dst_v[dst_v_index++] = - hwy::ConvertScalarTo(src_v[q + q_l]); - } + for (size_t q_l = 0; q_l < q_count; ++q_l) { + dst_v[dst_v_index++] = + hwy::ConvertScalarTo(src_v[q + q_l]); } } + const size_t pad_v = (2 * kNF - valid_tokens_l) * q_count; + std::fill_n(dst_v + dst_v_index, pad_v, kZero); + dst_v_index += pad_v; } // Zero out the padding area. // In the loops above, the dst_k loop has written 2kNF x 2 @@ -217,10 +220,13 @@ class VitAttention { const size_t kNF = hn::Lanes(hn::ScalableTag()); const size_t kRoundedKVDim = hwy::RoundUpTo(qkv_dim, 2 * kNF); auto& attn = activations_.attention; + attn.q_bf.OverrideCols(heads * qkv_dim); + attn.att_out.OverrideCols(heads * qkv_dim); const size_t seq_len = static_cast(attn.div_seq_len.GetDivisor()); - if (attn.vit_K_T.Rows() >= seq_len) { + if (!attn.vit_kv_reshaped) { attn.vit_K_T.ReshapePackedRowsToCols(2 * kNF); attn.vit_V_T.ReshapePackedRowsToCols(2 * kNF); + attn.vit_kv_reshaped = true; } const float query_scale = 1.0f / sqrtf(static_cast(qkv_dim)); ScaleQuery(attn.q, num_tokens_, heads, qkv_dim, query_scale, attn.q_bf); @@ -424,6 +430,7 @@ void PrefillVit(const ModelConfig& model_config, const WeightsPtrs& weights, weights.vit_encoder_norm_bias, activations.x); if (model_config.wrapping == PromptWrapping::GEMMA_VLM) { + HWY_ASSERT(activations.x.Rows() == 4096); activations.x = AvgPool4x4(activations.x, env.ctx.allocator); // Apply soft embedding norm before input projection. diff --git a/gemma/vit_gemma4.cc b/gemma/vit_gemma4.cc index e59c8d36..586ebd46 100644 --- a/gemma/vit_gemma4.cc +++ b/gemma/vit_gemma4.cc @@ -193,6 +193,7 @@ class VitGemma4Attention { const size_t heads = layer_config_.heads; const size_t kv_heads = layer_config_.kv_heads; const size_t qkv_dim = layer_config_.qkv_dim; + HWY_ASSERT(qkv_dim >= 64); auto& qkv = activations_.attention.q; float inv_timescale[16]; @@ -294,7 +295,7 @@ class VitGemma4Attention { const size_t qkv_dim = layer_config_.qkv_dim; HWY_ASSERT(qkv.Rows() == num_tokens_); - HWY_ASSERT(qkv.Cols() == (heads + 2 * kv_heads) * qkv_dim); + qkv.OverrideCols((heads + 2 * kv_heads) * qkv_dim); // Q part: MatPtrT q_part("q_part", Extents2D(num_tokens_, heads * qkv_dim)); @@ -479,10 +480,13 @@ class VitGemma4Attention { const size_t kNF = hn::Lanes(hn::ScalableTag()); const size_t kRoundedKVDim = hwy::RoundUpTo(qkv_dim, 2 * kNF); auto& attn = activations_.attention; + attn.q_bf.OverrideCols(heads * qkv_dim); + attn.att_out.OverrideCols(heads * qkv_dim); const size_t seq_len = static_cast(attn.div_seq_len.GetDivisor()); - if (attn.vit_K_T.Rows() >= seq_len) { + if (!attn.vit_kv_reshaped) { attn.vit_K_T.ReshapePackedRowsToCols(2 * kNF); attn.vit_V_T.ReshapePackedRowsToCols(2 * kNF); + attn.vit_kv_reshaped = true; } const float query_scale = 1.0f; ScaleQuery(attn.q, num_tokens_, heads, qkv_dim, query_scale, attn.q_bf);