Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 56 additions & 24 deletions gemma/activations.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,37 @@ typedef std::vector<BF16, hwy::AlignedAllocator<BF16>> AlignedBF16Vector;

// Returns the scale value to use for the query in the attention computation.
// Also called by ops_test.
static inline const std::vector<LayerConfig>& 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<size_t>(lc.qkv_dim));
for (const auto& lc : config.decoder_layer_configs)
max_dim = HWY_MAX(max_dim, static_cast<size_t>(lc.qkv_dim));
return max_dim;
}
static inline size_t MaxHeads(const std::vector<LayerConfig>& layers,
size_t fallback = 0) {
for (const auto& lc : layers)
fallback = HWY_MAX(fallback, static_cast<size_t>(lc.heads));
return fallback;
}
static inline size_t MinHeads(const std::vector<LayerConfig>& 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<size_t>(lc.heads));
return m == ~size_t{0} ? size_t{1} : m;
}
static inline size_t MaxKVHeads(const std::vector<LayerConfig>& layers,
size_t fallback = 0) {
for (const auto& lc : layers)
fallback = HWY_MAX(fallback, static_cast<size_t>(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) {
Expand Down Expand Up @@ -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<hwy::AlignedFreeUniquePtr<uint8_t*[]>>& 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<size_t>(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(
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -288,13 +315,15 @@ struct AttentionActivationsPtrs {
float_queries(nullptr),
q_scales(nullptr),
div_seq_len(static_cast<uint32_t>(seq_len)),
div_heads(static_cast<uint32_t>(config.layer_configs[0].heads)),
div_heads(static_cast<uint32_t>(
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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;
Expand Down
49 changes: 49 additions & 0 deletions gemma/attention_test.cc
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#include <cmath>
#include <cstddef>
#include <cstdlib>
#include <cstring> // strcmp
Expand Down Expand Up @@ -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"

Expand Down Expand Up @@ -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<LayerWeightsPtrs> 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<KVCache>(&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();
Expand All @@ -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
Expand Down
18 changes: 13 additions & 5 deletions gemma/flash_attention.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -2272,7 +2272,7 @@ size_t GetMaxTiles(const std::vector<Tile148Params>& params,
// split_params is cleared and filled with the split tasks.
void SplitTasksByKPos(std::vector<Tile148Params>& 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<Tile148Params>& split_params) {
split_params.clear();
for (auto& param : params) {
Expand Down Expand Up @@ -2302,6 +2302,7 @@ void SplitTasksByKPos(std::vector<Tile148Params>& 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;
Expand All @@ -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);
Expand All @@ -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;
}
}
Expand Down
7 changes: 3 additions & 4 deletions gemma/flash_attention_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
24 changes: 19 additions & 5 deletions gemma/gemma.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<KV_t>(src[i]);
Expand All @@ -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,
Expand All @@ -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<float>::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<float>(key[dim]);
Expand All @@ -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) {
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading