Skip to content
Merged
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
421 changes: 421 additions & 0 deletions gemma/configs.cc

Large diffs are not rendered by default.

21 changes: 19 additions & 2 deletions gemma/configs.h
Original file line number Diff line number Diff line change
Expand Up @@ -478,7 +478,9 @@ struct LayerConfig : public IFields {
}

// Width of one cached latent row (c_kv + decoupled RoPE key).
size_t KVLatentDim() const { return kv_lora_rank + rope_head_dim; }
size_t KVLatentDim() const {
return static_cast<size_t>(kv_lora_rank) + rope_head_dim;
}

// V4 compressor: ratio-4 layers use overlapping windows (doubled dims).
size_t CompressorCoff() const { return kv_compression_rate == 4 ? 2 : 1; }
Expand Down Expand Up @@ -517,7 +519,7 @@ struct LayerConfig : public IFields {
}
return size;
}
return kv_heads * qkv_dim * 2;
return static_cast<size_t>(kv_heads) * qkv_dim * 2;
}

// f32 elements of per-query incremental compressor state for this layer:
Expand Down Expand Up @@ -760,10 +762,18 @@ struct ModelConfig : public IFields {
// The third ctor also expects a string returned by this.
std::string Specifier() const;

// Maximum `max_seq_len` that can be rounded by `KVCache` (`kMaxBF16PerVector`
// and `kTileSize = 32`) or added to `prefill_tbatch_size` (<= kMaxBatchSize)
// without 32-bit `size_t` / `uint32_t` wraparound.
static constexpr size_t kMaxSeqLen =
UINT32_MAX - HWY_MAX(kMaxBF16PerVector, kMaxBatchSize);

// Overwrites `max_seq_len` with `new_max_seq_len` and updates all global
// layers' attention window sizes to `new_max_seq_len`. This function must be
// called before instantiating the KVCache object.
void SetMaxSeqLen(size_t new_max_seq_len) {
HWY_ASSERT(new_max_seq_len > 0);
HWY_ASSERT(new_max_seq_len <= kMaxSeqLen);
for (size_t i = 0; i < attention_window_sizes.size(); ++i) {
if (attention_window_sizes[i] == max_seq_len) {
attention_window_sizes[i] = new_max_seq_len;
Expand Down Expand Up @@ -854,6 +864,13 @@ struct ModelConfig : public IFields {
}
return num_layers;
}
// Validates a layer sharing another layer's KV cache (`!HasOwnKVCache()`),
// returning the validated source layer index `< layer_idx`.
static size_t ValidateKVShareLayer(const std::vector<LayerConfig>& layers,
const std::vector<uint32_t>& window_sizes,
size_t layer_idx,
const char* stack_name = "kv");
void Validate() const;

bool IsEOS(int id) const { return (id == eos_id || id == secondary_eos_id); }

Expand Down
67 changes: 67 additions & 0 deletions gemma/configs_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,73 @@ TEST(ConfigsTest, T5GemmaKVCacheUsesDecoderLayers) {
EXPECT_EQ(config.KVCacheCols(), expected_cols);
}

TEST(ConfigsTest, ValidateAcceptsAllCanonicalModels) {
ForEachModel([](Model m) {
ModelConfig(m, Type::kBF16, ChooseWrapping(m)).Validate();
});
}

TEST(ConfigsTest, ValidateRejectsMalformedUntrustedConfigs) {
#ifdef GTEST_HAS_DEATH_TEST
using M = Model;
const auto chk = [](const char* re, auto fn, M m = M::GEMMA2_2B) {
ModelConfig c(m, Type::kBF16, ChooseWrapping(m));
fn(c, c.layer_configs);
EXPECT_DEATH(c.Validate(), re);
};
const auto ds = M::DEEPSEEK4_FLASH, m4 = M::GEMMA4_26B_MOE;
const auto v4 = M::GEMMA4_2B, pg = M::PALIGEMMA2_3B_224;
chk("main layer 0: ff_hidden_dim 0",
[](auto&, auto& l) { l[0].ff_hidden_dim = 0; });
chk("main layer 1: heads 4194305 \\* qkv_dim .* > kMaxMatMulK",
[](auto&, auto& l) { l[1].heads = 0x400001; });
chk("main layer 1: model_dim .* != expected",
[](auto&, auto& l) { l[1].model_dim += 64; });
chk("main layer 0: window_size 0",
[](auto& c, auto&) { c.attention_window_sizes[0] = 0; });
chk("main layer 1: ple_dim 256 != model ple_dim 0",
[](auto&, auto& l) { l[1].ple_dim = 256; });
chk("vocab_size <= kMaxMatCols",
[](auto& c, auto&) { c.vocab_size = 0xFFFFFFFFu; });
chk("max_seq_len <= kMaxSeqLen",
[](auto& c, auto&) { c.max_seq_len = UINT32_MAX; });
chk("hc_sinkhorn_iters <= kMaxSinkhornIters",
[](auto& c, auto&) { c.hc_sinkhorn_iters = 999; });
chk("main layer 0: window_size .* must be in",
[](auto& c, auto&) { c.attention_window_sizes[0] = c.max_seq_len + 1; });
chk("main layer 1: heads .* != layer 0 heads",
[](auto&, auto& l) { l[1].heads *= 2; });
chk("main layer 0: non-zero indexer fields",
[](auto&, auto& l) { l[0].indexer_heads = 16; });
chk("Invalid decoder stack: window_sizes\\.size\\(\\) 0 != 8",
[](auto& c, auto&) { c.decoder_attention_window_sizes.clear(); },
M::T5GEMMA_S_S);
chk("total_mtp_layers <= kMaxLayers",
[](auto& c, auto&) { c.num_mtp_layers = 100000; }, ds);
chk("main layer 0: inconsistent MLA config",
[](auto&, auto& l) { l[0].kv_lora_rank = 0; }, ds);
chk("main layer 2: indexer requires compressor",
[](auto&, auto& l) { l[2].kv_compression_rate = 1; }, ds);
chk("main layer 0: num_experts 256 > max_experts 128",
[](auto&, auto& l) { l[0].num_experts = 256; }, m4);
chk("vit_config\\.seq_len <= kMaxBatchSize",
[](auto& c, auto&) { c.vit_config.seq_len = 8192; }, v4);
chk("vit_config\\.pool_dim == kGemma4VitPoolDim",
[](auto& c, auto&) { c.vit_config.pool_dim = 6; }, v4);
chk("main layer 15: kv_heads 4 > layer 0 kv_heads",
[](auto&, auto& l) { l[15].kv_heads = 4; }, M::GEMMA4_2B_LM);
chk("main layer 15: qkv_dim .* != share source",
[](auto&, auto& l) { l[15].qkv_dim += 64; }, M::GEMMA4_2B_LM);
chk("vit_config\\.seq_len == kGemmaVlmSeqLen",
[](auto& c, auto&) { c.vit_config.seq_len = 16; }, M::GEMMA3_4B);
chk("patches_per_side \\* patches_per_side == vit_config\\.seq_len",
[](auto& c, auto&) { c.vit_config.image_size = 14; }, pg);
ModelConfig bad(M::GEMMA2_2B, Type::kBF16, PromptWrapping::GEMMA_IT);
EXPECT_DEATH(bad.SetMaxSeqLen(0), "new_max_seq_len > 0");
EXPECT_DEATH(bad.SetMaxSeqLen(UINT32_MAX), "new_max_seq_len <= kMaxSeqLen");
#endif // GTEST_HAS_DEATH_TEST
}

TEST(ConfigsTest, DeduceT5GemmaSS) {
EXPECT_EQ(DeduceModel(Path("t5gemma-s-s.sbs"), 8, kDeducedT5Gemma),
Model::T5GEMMA_S_S);
Expand Down
22 changes: 4 additions & 18 deletions gemma/kv_cache.cc
Original file line number Diff line number Diff line change
Expand Up @@ -158,15 +158,8 @@ KVCache::KVCache(const ModelConfig& config, const InferenceArgs& inference_args,

for (size_t i = 0; i < num_layers; ++i) {
if (!kv_layer_configs[i].HasOwnKVCache()) {
const size_t src =
static_cast<size_t>(kv_layer_configs[i].kv_share_layer_idx);
HWY_ASSERT(src < i);
HWY_ASSERT(kv_layer_configs[src].HasOwnKVCache());
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]);
const size_t src = ModelConfig::ValidateKVShareLayer(
kv_layer_configs, kv_attention_window_sizes, i);
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];
Expand Down Expand Up @@ -242,15 +235,8 @@ KVCache::KVCache(const ModelConfig& config, const InferenceArgs& inference_args,
max_kv_heads = HWY_MAX(max_kv_heads, kv_layer_configs[i].kv_heads);

if (!kv_layer_configs[i].HasOwnKVCache()) {
const size_t src =
static_cast<size_t>(kv_layer_configs[i].kv_share_layer_idx);
HWY_ASSERT(src < i); // sources must precede, so their offsets are set
HWY_ASSERT(kv_layer_configs[src].HasOwnKVCache());
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]);
const size_t src = ModelConfig::ValidateKVShareLayer(
kv_layer_configs, kv_attention_window_sizes, i);
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];
Expand Down
19 changes: 6 additions & 13 deletions gemma/model_store.cc
Original file line number Diff line number Diff line change
Expand Up @@ -329,14 +329,14 @@ static ModelConfig ReadOrDeduceConfig(BlobReader& reader,
deduced_model = DeduceModel(reader.blob_path(), layers, layer_types);
}
if (has_config) {
HWY_ASSERT(config.wrapping != PromptWrapping::kSentinel);
HWY_ASSERT(config.weight != Type::kUnknown);
for (const LayerConfig& layer_config : config.layer_configs) {
if (static_cast<size_t>(layer_config.qkv_dim) > kMaxQKVDim) {
HWY_ABORT("Increase kMaxQKVDim to at least %u.", layer_config.qkv_dim);
for (const std::string& key : reader.Keys()) {
if (key.find("mtp_main_proj") != std::string::npos ||
key.find("mtp.0.main_proj") != std::string::npos) {
config.num_mtp_layers = 3;
break;
}
}

config.Validate();
// We trust the deserialized config, but checking helps to validate the
// deduction, which we rely on below for pre-2025 files.
if (deduced_model.has_value() && config.model != *deduced_model) {
Expand All @@ -345,13 +345,6 @@ static ModelConfig ReadOrDeduceConfig(BlobReader& reader,
(std::string(ModelPrefix(*deduced_model)) + suffix).c_str(),
(std::string(ModelPrefix(config.model)) + suffix).c_str());
}
for (const std::string& key : reader.Keys()) {
if (key.find("mtp_main_proj") != std::string::npos ||
key.find("mtp.0.main_proj") != std::string::npos) {
config.num_mtp_layers = 3;
break;
}
}
return config;
}

Expand Down
2 changes: 1 addition & 1 deletion ops/matmul.h
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ class MMEntireA {
public:
// Compile-time bounds on matrix columns to enable pre-allocating storage
// and reusing it across `MatMul` calls. Sufficient for Gemma 2 27B.
static constexpr size_t kMaxK = 36 * 1024;
static constexpr size_t kMaxK = kMaxMatMulK;

explicit MMEntireA(const Allocator& allocator)
// 288 MiB. Must be padded, see `DoDecompressA`.
Expand Down
4 changes: 4 additions & 0 deletions util/basics.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ namespace gcpp {
// For hwy::BitSet4096. Note that KVs are extremely large for such batches.
HWY_INLINE_VAR constexpr size_t kMaxBatchSize = 4096;

// Maximum MatMul inner dimension K (matches MMEntireA::kMaxK; sufficient for
// Gemma 2 27B ff_hidden_dim = 36864).
HWY_INLINE_VAR constexpr size_t kMaxMatMulK = 36 * 1024;

// Multiplier so a u64 occupies an entire cache line; avoids false sharing.
HWY_INLINE_VAR constexpr size_t kU64PerLine = HWY_ALIGNMENT / sizeof(uint64_t);

Expand Down
Loading