From 5bd0becd28c9da87688a478ca9edcc9acdbd4534 Mon Sep 17 00:00:00 2001 From: Jan Wassenberg Date: Wed, 11 Nov 2026 04:17:38 -0800 Subject: [PATCH] Compute RoPE inverse timescales and query scales per layer. PiperOrigin-RevId: 1019066959 --- deepseek/deepseek.cc | 3 +- gemma/activations.h | 91 ++++++++++++++++++++++++++--------- gemma/attention.cc | 5 +- gemma/attention_test.cc | 76 +++++++++++++++++++++++++++++ gemma/flash_attention.cc | 2 +- gemma/flash_attention_test.cc | 2 +- gemma/gemma.cc | 32 +++++++----- gemma/tiled_attention.cc | 6 ++- ops/ops.h | 6 ++- 9 files changed, 181 insertions(+), 42 deletions(-) diff --git a/deepseek/deepseek.cc b/deepseek/deepseek.cc index 6024b3cc..8a10934a 100644 --- a/deepseek/deepseek.cc +++ b/deepseek/deepseek.cc @@ -997,7 +997,8 @@ static HWY_NOINLINE void DeepSeekAttention(size_t num_tokens, size_t layer_idx, // ---- Per (token, head): scores over window + compressed entries, online // softmax with sink, inverse-RoPE of the output. - const float query_scale = att.query_scale; + const float query_scale = + ChooseQueryScale(activations.attention.config, layer.layer_config); ParallelFor( Parallelism::kFlat, num_interleaved * heads, env.ctx, /*cluster_idx=*/0, Callers::kAttComputeQKV, [&](size_t task, size_t worker) HWY_ATTR { diff --git a/gemma/activations.h b/gemma/activations.h index ba36628f..8a1a7e0e 100644 --- a/gemma/activations.h +++ b/gemma/activations.h @@ -41,8 +41,18 @@ namespace gcpp { typedef std::vector> AlignedFloatVector; 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& config) { + return config.is_encoder_decoder ? config.decoder_layer_configs + : config.layer_configs; +} + +static inline const LayerConfig& FirstLayerConfig( + const std::vector& layers) { + HWY_ASSERT(!layers.empty()); + return layers[0]; +} + static inline size_t MaxQkvDim(const ModelConfig& config) { size_t max_dim = 0; for (const auto& lc : config.layer_configs) { @@ -61,18 +71,25 @@ static inline size_t MaxFFHiddenDim(const ModelConfig& config) { return max_dim; } - -static inline float ChooseQueryScale(const ModelConfig& config) { - const LayerConfig& layer_config = config.layer_configs[0]; - if (config.query_scale == QueryScaleType::SqrtModelDimDivNumHeads) - return 1.0f / - sqrtf(static_cast(config.model_dim / layer_config.heads)); +// Returns the scale value to use for the query in the attention computation. +static inline float ChooseQueryScale(const ModelConfig& config, + const LayerConfig& layer_config) { + HWY_ASSERT(layer_config.heads != 0 && layer_config.qkv_dim != 0); + if (config.query_scale == QueryScaleType::SqrtModelDimDivNumHeads) { + return 1.0f / sqrtf(static_cast(config.model_dim) / + static_cast(layer_config.heads)); + } if (config.query_scale == QueryScaleType::One) return 1.0f; // QueryScaleType::SqrtKeySize return 1.0f / sqrtf(static_cast(layer_config.qkv_dim)); } +// Also called by ops_test. +static inline float ChooseQueryScale(const ModelConfig& config) { + return ChooseQueryScale(config, FirstLayerConfig(ActiveLayerConfigs(config))); +} + struct AttentionActivations { AttentionActivations( const ModelConfig& config, const LayerConfig& layer_config, @@ -129,8 +146,7 @@ struct AttentionActivations { allocator, layer_config.qkv_dim, layer_config.post_qk == PostQKType::HalfRope, config.rope_theta)), inv_timescale_global(CreateInvTimescale( - allocator, max_qkv_dim, - layer_config.post_qk == PostQKType::HalfRope, + allocator, max_qkv_dim, /*half_rope=*/false, config.global_rope_theta, config.partial_rotary_factor)), s_att_q(config.is_encoder_decoder ? config.decoder_num_layers : config.num_layers, @@ -144,6 +160,17 @@ struct AttentionActivations { s_att_out(config.is_encoder_decoder ? config.decoder_num_layers : config.num_layers, max_workers) { + const std::vector& active_layers = ActiveLayerConfigs(config); + layer_inv_timescales.reserve(active_layers.size()); + layer_inv_timescales_global.reserve(active_layers.size()); + for (const LayerConfig& lc : active_layers) { + const bool half_rope = lc.post_qk == PostQKType::HalfRope; + layer_inv_timescales.push_back(CreateInvTimescale( + allocator, lc.qkv_dim, half_rope, config.rope_theta)); + layer_inv_timescales_global.push_back(CreateInvTimescale( + allocator, lc.qkv_dim, half_rope, config.global_rope_theta, + config.partial_rotary_factor)); + } // Batch size can be 0 in experimental code so do not assert. if (batch_size == 0) { static std::atomic_flag warned = ATOMIC_FLAG_INIT; @@ -258,6 +285,8 @@ struct AttentionActivations { // Rope MatStorageT inv_timescale; MatStorageT inv_timescale_global; + std::vector> layer_inv_timescales; + std::vector> layer_inv_timescales_global; // Only active when GCPP_TENSOR_STATS. TensorStats s_att_q; @@ -288,7 +317,8 @@ 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( + FirstLayerConfig(ActiveLayerConfigs(config)).heads)), query_scale(ChooseQueryScale(config)) {} AttentionActivationsPtrs(const ModelConfig& config, size_t seq_len, @@ -308,6 +338,8 @@ struct AttentionActivationsPtrs { att_sums = activations.att_sums; inv_timescale = activations.inv_timescale; inv_timescale_global = activations.inv_timescale_global; + layer_inv_timescales = &activations.layer_inv_timescales; + layer_inv_timescales_global = &activations.layer_inv_timescales_global; k_tile_vec = activations.k_tile_vec; v_tile_vec = activations.v_tile_vec; sub_task_att_out = &activations.sub_task_att_out; @@ -400,11 +432,27 @@ struct AttentionActivationsPtrs { MatPtrT inv_timescale; // Inverse timescales for global RoPE computation. MatPtrT inv_timescale_global; + const std::vector>* layer_inv_timescales = nullptr; + const std::vector>* layer_inv_timescales_global = nullptr; + + const float* InvTimescale(size_t layer_idx) const { + if (layer_inv_timescales == nullptr) return inv_timescale.PackedScale1(); + HWY_ASSERT(layer_idx < layer_inv_timescales->size()); + return (*layer_inv_timescales)[layer_idx].PackedScale1(); + } + const float* InvTimescaleGlobal(size_t layer_idx) const { + if (layer_inv_timescales_global == nullptr) { + return inv_timescale_global.PackedScale1(); + } + HWY_ASSERT(layer_idx < layer_inv_timescales_global->size()); + return (*layer_inv_timescales_global)[layer_idx].PackedScale1(); + } + // Divisor for faster division by sequence length. hwy::Divisor div_seq_len; // Divisor for faster division by number of heads. hwy::Divisor div_heads; - // Query scaling factor for attention computation. + // Query scaling factor for attention computation (layer 0 default). float query_scale; // Only active when GCPP_TENSOR_STATS. @@ -445,8 +493,7 @@ struct Activations { Activations(const RuntimeConfig& runtime_config, const ModelConfig& config, size_t batch_size, size_t seq_len, ThreadingContext& ctx, std::vector>& row_ptrs) - : layer_config(config.is_encoder_decoder ? config.decoder_layer_configs[0] - : config.layer_configs[0]), + : layer_config(FirstLayerConfig(ActiveLayerConfigs(config))), moe_layer_config(MoELayerConfig(config)), mla_dims(config), num_layers(config.is_encoder_decoder ? config.decoder_num_layers @@ -516,14 +563,6 @@ struct Activations { t5_encoder_ffw_out(MatFactory( "t5_e_ffw_out", encoder_seq_len, config.is_encoder_decoder ? config.model_dim : 0, ctx.allocator)), - t5_encoder_inv_timescale( - config.is_encoder_decoder - ? CreateInvTimescale(ctx.allocator, - config.encoder_layer_configs[0].qkv_dim, - config.encoder_layer_configs[0].post_qk == - PostQKType::HalfRope, - config.rope_theta) - : MatStorageT()), max_workers(ctx.pools.MaxWorkers()), s_ffw_in(num_layers, max_workers), @@ -644,6 +683,12 @@ struct Activations { } if (config.is_encoder_decoder) { + t5_encoder_inv_timescales.reserve(config.encoder_layer_configs.size()); + for (const LayerConfig& lc : config.encoder_layer_configs) { + t5_encoder_inv_timescales.push_back(CreateInvTimescale( + ctx.allocator, lc.qkv_dim, lc.post_qk == PostQKType::HalfRope, + config.rope_theta)); + } t5_encoder_q.AllocateAndAttachRowPtrs(row_ptrs); t5_encoder_kv.AllocateAndAttachRowPtrs(row_ptrs); t5_encoder_att_out.AllocateAndAttachRowPtrs(row_ptrs); @@ -801,7 +846,7 @@ struct Activations { MatStorageT t5_encoder_c1; MatStorageT t5_encoder_c2; MatStorageT t5_encoder_ffw_out; - MatStorageT t5_encoder_inv_timescale; + std::vector> t5_encoder_inv_timescales; const size_t max_workers; TensorStats s_ffw_in; diff --git a/gemma/attention.cc b/gemma/attention.cc index 6aa409e8..ab67fab0 100644 --- a/gemma/attention.cc +++ b/gemma/attention.cc @@ -151,10 +151,10 @@ void PositionalEncodingQK(float* qk, const size_t layer_idx, const size_t qkv_dim = layer_config.qkv_dim; const PostQKType& post_qk = layer_config.post_qk; // qk is either q or k, so qkv_dim is the length we operate on. - const float* inv_timescale = activations.inv_timescale.PackedScale1(); + const float* inv_timescale = activations.InvTimescale(layer_idx); const bool is_global_layer = activations.config.IsGlobalLayer(layer_idx); if (is_global_layer && activations.config.use_global_timescale) { - inv_timescale = activations.inv_timescale_global.PackedScale1(); + inv_timescale = activations.InvTimescaleGlobal(layer_idx); } // PostQKType::Rope if (post_qk == PostQKType::HalfRope) { @@ -216,6 +216,7 @@ static HWY_INLINE void ComputeQKV(size_t num_tokens, const size_t layer_idx, // Set up MatMul row pointers for `kv_heads` pairs of (k, v) vectors. MatPtrT kv_rows("kv", Extents2D(activations.pre_att_rms_out.Rows(), layer.qkv_einsum_w2.Rows())); + HWY_ASSERT(num_interleaved <= kMaxBatchSize); for (size_t interleaved_idx = 0; interleaved_idx < num_interleaved; ++interleaved_idx) { // Index into qbatch, within [0, qbatch.Size()] diff --git a/gemma/attention_test.cc b/gemma/attention_test.cc index 6484fc0d..6f74e12a 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,79 @@ void TestGemmaAttentionFlash() { RunAttentionTest(AttentionImpl::kFlash, true); } +void TestHeterogeneousLayerRopeAndScale() { + ModelConfig config(Model::GEMMA3_1B, Type::kF32, PromptWrapping::GEMMA_PT); + config.model_dim = config.vocab_size = config.max_seq_len = 64; + config.num_layers = 2; + config.attention_window_sizes = {16, 64}; + LayerConfig lc0 = config.layer_configs[0]; + lc0.model_dim = lc0.ff_hidden_dim = lc0.qkv_dim = 64; + lc0.post_qk = PostQKType::HalfRope; + lc0.post_norm = PostNormType::None; + lc0.use_qk_norm = false; + LayerConfig lc1 = lc0; // Wider full-RoPE global layer (b/583882314). + lc1.qkv_dim = 128; + lc1.post_qk = PostQKType::Rope; + config.layer_configs = {lc0, lc1}; + ModelConfig ref_cfg = config; + ref_cfg.num_layers = 1; + ref_cfg.layer_configs = {lc1}; + ref_cfg.attention_window_sizes = {64}; + + constexpr size_t kBatch = 4; + InferenceArgs inf_args; + inf_args.seq_len = 64; + std::vector tokens = {1, 2, 3, 4}; + const PromptTokens prompt(tokens.data(), kBatch); + const Extents2D x_extents(kBatch, config.model_dim); + + for (AttentionImpl impl : + {AttentionImpl::kFlash, AttentionImpl::kFlashTransposedQsBF16}) { + RuntimeConfig rt_cfg{.attention_impl = impl}; + ThreadingContext io_ctx({}); + MatStorageT x_in1("in1", x_extents, io_ctx.allocator, + MatPadding::kOdd); + auto run = [&](const ModelConfig& cfg, const MatPtrT* x_init) { + TestState s; + TensorInfoRegistry reg(cfg); + std::vector kv; + kv.emplace_back(cfg, inf_args, rt_cfg, s.ctx.allocator); + Activations act(rt_cfg, cfg, kBatch, kv[0].SeqLen(), s.ctx, + s.env.row_ptrs); + FillRandom(act.x, 301); + if (x_init != nullptr) CopyMat(*x_init, act.x); + AllQueries queries(prompt, /*pos=*/0, /*prefix_end=*/0, + hwy::Span(kv.data(), kv.size())); + QBatch qbatch(/*start=*/0, /*max_size=*/1, queries); + for (size_t l = 0; l < cfg.num_layers; ++l) { + if (l == 1) CopyMat(act.x, x_in1); + LayerWeightsPtrs layer(l, cfg.layer_configs[l], reg); + uint64_t seed = (x_init != nullptr || l == 1) ? 200 : 100; + for (MatPtr* m : {&layer.pre_attention_norm_scale, &layer.qkv_einsum_w, + &layer.attn_vec_einsum_w, &layer.pre_ffw_norm_scale, + &layer.gating_einsum_w, &layer.linear_w}) { + AllocateAndFillRandom(*m, s.ctx.allocator, s.mat_owners, seed++); + } + layer.Fixup(cfg.model, s.mat_owners, s.ctx); + TransformerLayer(kBatch, l, layer, act, qbatch, s.env); + } + MatStorageT out("out", x_extents, io_ctx.allocator, + MatPadding::kOdd); + CopyMat(act.x, out); + return out; + }; + + const MatStorageT out = run(config, nullptr); + const MatStorageT ref = run(ref_cfg, &x_in1); + for (size_t r = 0; r < kBatch; ++r) { + for (size_t c = 0; c < config.model_dim; ++c) { + ASSERT_TRUE(std::isfinite(out.Row(r)[c])); + EXPECT_NEAR(out.Row(r)[c], ref.Row(r)[c], 1e-5f); + } + } + } +} + } // namespace HWY_NAMESPACE } // namespace gcpp HWY_AFTER_NAMESPACE(); @@ -589,6 +664,7 @@ HWY_AFTER_NAMESPACE(); namespace gcpp { HWY_BEFORE_TEST(AttentionTest); HWY_EXPORT_AND_TEST_P(AttentionTest, TestGemmaAttentionFlash); +HWY_EXPORT_AND_TEST_P(AttentionTest, TestHeterogeneousLayerRopeAndScale); HWY_AFTER_TEST(); } // namespace gcpp diff --git a/gemma/flash_attention.cc b/gemma/flash_attention.cc index 5092f514..5ecd5c28 100644 --- a/gemma/flash_attention.cc +++ b/gemma/flash_attention.cc @@ -72,7 +72,7 @@ void RMSNormAndPositionalEncoding(const size_t num_tokens, const QBatch& qbatch, const AttentionActivationsPtrs& activations, ThreadingContext& ctx) { const LayerConfig& layer_config = activations.config.layer_configs[layer_idx]; - const float query_scale = activations.query_scale; + const float query_scale = ChooseQueryScale(activations.config, layer_config); const hwy::Divisor div_qbatch(qbatch.Size()); const auto func = [&](const size_t task, size_t worker) HWY_ATTR { diff --git a/gemma/flash_attention_test.cc b/gemma/flash_attention_test.cc index 88649b74..39488dcf 100644 --- a/gemma/flash_attention_test.cc +++ b/gemma/flash_attention_test.cc @@ -124,10 +124,10 @@ void SingleDotSoftmaxWeightedSum( float* HWY_RESTRICT att_out, const SMOptions& sm_options, ThreadingContext& ctx, const size_t worker) { const float att_cap = activations.config.att_cap; - const float query_scale = activations.query_scale; // --seq_len must be large enough to avoid wraparound. HWY_DASSERT(kv_last_pos < activations.SeqLen()); const LayerConfig& layer_config = activations.config.layer_configs[layer_idx]; + const float query_scale = ChooseQueryScale(activations.config, layer_config); // Apply rope and scaling to Q. if (query_norm_scale.HasPtr()) { diff --git a/gemma/gemma.cc b/gemma/gemma.cc index 02c3356d..37f59f68 100644 --- a/gemma/gemma.cc +++ b/gemma/gemma.cc @@ -94,6 +94,10 @@ void Attention(LayerAttentionType type, const size_t num_tokens, const size_t layer_idx, const LayerWeightsPtrs& layer, Activations& activations, QBatch& qbatch, MatMulEnv& env) { const int kFlags = 0; + const size_t active_qkv_dim = + layer.layer_config.heads * layer.layer_config.qkv_dim; + activations.attention.q.OverrideCols(active_qkv_dim); + activations.attention.att_out.OverrideCols(active_qkv_dim); if (IsTiledAttention(activations.attention_impl)) { TiledAttention(activations.attention_impl, num_tokens, layer_idx, layer, activations.attention, qbatch, env, kFlags); @@ -386,8 +390,7 @@ static void T5GemmaEncoderAttentionReference( 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, - /*scale=*/1.0f / sqrtf(static_cast(qkv_dim)), q, kv, - env.ctx); + ChooseQueryScale(config, layer_config), q, kv, env.ctx); for (size_t query_pos = 0; query_pos < source_len; ++query_pos) { for (size_t head = 0; head < heads; ++head) { @@ -516,6 +519,7 @@ static void T5GemmaEncode(const ModelConfig& config, const WeightsPtrs& weights, for (size_t layer_idx = 0; layer_idx < weights.t5gemma_encoder_layers.size(); ++layer_idx) { + HWY_ASSERT(layer_idx < activations.t5_encoder_inv_timescales.size()); T5GemmaEncoderLayerReference( config, layer_idx, weights.t5gemma_encoder_layers[layer_idx], encoder_cache, activations.t5_encoder_pre_att_rms_out, @@ -523,7 +527,7 @@ static void T5GemmaEncode(const ModelConfig& config, const WeightsPtrs& weights, activations.t5_encoder_att_out, activations.t5_encoder_att_sums, activations.t5_encoder_pre_ffw_rms_out, activations.t5_encoder_c1, activations.t5_encoder_c2, activations.t5_encoder_ffw_out, - activations.t5_encoder_inv_timescale, env); + activations.t5_encoder_inv_timescales[layer_idx], env); } RMSNormInplaceBatched(weights.t5gemma_encoder_final_norm_scale, encoder_cache.hidden_states, env.ctx); @@ -673,7 +677,7 @@ static void T5GemmaDecoderSelfAttentionReference( CallMatMul(activations.attention.pre_att_rms_out, layer.self_qkv_einsum_w2, /*add=*/nullptr, env, kv); T5GemmaApplyDecoderRope(layer_config, inv_timescale, - /*scale=*/1.0f / sqrtf(static_cast(qkv_dim)), + ChooseQueryScale(config, layer_config), activations.attention.q, kv, qbatch, env.ctx); T5GemmaWriteDecoderKV(layer, layer_idx, kv, qbatch); @@ -885,15 +889,17 @@ static void T5GemmaDecoderTransformer(const ModelConfig& config, const WeightsPtrs& weights, Activations& activations, MatStorageT& decoder_kv, - const MatPtrT& inv_timescale, + const std::vector>& + inv_timescales, QBatch& qbatch, MatMulEnv& env) { for (size_t layer_idx = 0; layer_idx < weights.t5gemma_decoder_layers.size(); ++layer_idx) { + HWY_ASSERT(layer_idx < inv_timescales.size()); const T5GemmaDecoderLayerWeightsPtrs& layer = weights.t5gemma_decoder_layers[layer_idx]; T5GemmaDecoderSelfAttentionReference(config, layer_idx, layer, activations, - decoder_kv, inv_timescale, qbatch, - env); + decoder_kv, inv_timescales[layer_idx], + qbatch, env); T5GemmaDecoderCrossAttentionReference(config, layer_idx, layer, activations, qbatch, env); T5GemmaDecoderFFW(layer, activations, env); @@ -986,9 +992,13 @@ static void T5GemmaGenerateT(const ModelConfig& config, "t5_d_kv", qbatch.Size(), 2 * layer_config.kv_heads * layer_config.qkv_dim, env.ctx.allocator)); decoder_kv.AllocateAndAttachRowPtrs(env.row_ptrs); - MatStorageT inv_timescale = CreateInvTimescale( - env.ctx.allocator, layer_config.qkv_dim, - layer_config.post_qk == PostQKType::HalfRope, config.rope_theta); + std::vector> inv_timescales; + inv_timescales.reserve(config.decoder_layer_configs.size()); + for (const LayerConfig& lc : config.decoder_layer_configs) { + inv_timescales.push_back(CreateInvTimescale( + env.ctx.allocator, lc.qkv_dim, lc.post_qk == PostQKType::HalfRope, + config.rope_theta)); + } auto logits_chunk_row_ptrs = hwy::AllocateAligned(qbatch.Size()); std::vector greedy_tokens(qbatch.Size()); std::vector greedy_logits(qbatch.Size()); @@ -996,7 +1006,7 @@ static void T5GemmaGenerateT(const ModelConfig& config, for (size_t gen = 0; gen < max_gen_steps && non_eos.Any(); ++gen) { T5GemmaEmbedDecoderTokens(config, weights, activations, qbatch, env); T5GemmaDecoderTransformer(config, weights, activations, decoder_kv, - inv_timescale, qbatch, env); + inv_timescales, qbatch, env); T5GemmaSampleAndStream(config, runtime_config, weights, sample_token, activations, qbatch, env, logits_chunk_row_ptrs.get(), greedy_tokens, diff --git a/gemma/tiled_attention.cc b/gemma/tiled_attention.cc index a84131b2..aae96622 100644 --- a/gemma/tiled_attention.cc +++ b/gemma/tiled_attention.cc @@ -1638,8 +1638,12 @@ void TiledAttention(AttentionImpl attention_impl, size_t num_tokens, "Unsupported KV cache type: %d", static_cast(qbatch.KV(0).cache->compact_kv_cache_ptr.GetType())); } + const size_t q_layer_idx = + layer.layer_idx < activations.config.layer_configs.size() + ? layer.layer_idx + : layer_idx; RMSNormAndPositionalEncoding(num_tokens, qbatch, activations.q, - layer.query_norm_scale, layer_idx, activations, + layer.query_norm_scale, q_layer_idx, activations, env.ctx); if (activations.s_att_q) { activations.s_att_q->Notify(layer.layer_idx, activations.q, env.ctx); diff --git a/ops/ops.h b/ops/ops.h index 9dd3b917..76f578c8 100644 --- a/ops/ops.h +++ b/ops/ops.h @@ -28,10 +28,12 @@ namespace gcpp { static inline HWY_MAYBE_UNUSED MatStorageT CreateInvTimescale( const Allocator& allocator, size_t qkv_dim, bool half_rope, double base_frequency, float partial_rotary_factor = 1.0f) { + HWY_ASSERT(partial_rotary_factor >= 0.0f && partial_rotary_factor <= 1.0f); const size_t rope_dim = half_rope ? qkv_dim / 2 : qkv_dim; const size_t total_entries = rope_dim / 2; const size_t active_entries = - static_cast(total_entries * partial_rotary_factor); + HWY_MIN(total_entries, + static_cast(total_entries * partial_rotary_factor)); MatStorageT inv_timescale("inv_timescale", total_entries, allocator); float* data = inv_timescale.Row(0); for (size_t dim = 0; dim < active_entries; ++dim) { @@ -42,7 +44,7 @@ static inline HWY_MAYBE_UNUSED MatStorageT CreateInvTimescale( data[dim] = static_cast(1.0 / std::pow(base_frequency, freq_exponents)); } - // Zero out NoPE dimensions — cos(0)=1, sin(0)=0 gives identity. + // Zero out NoPE dimensions: cos(0)=1, sin(0)=0 gives identity. for (size_t dim = active_entries; dim < total_entries; ++dim) { data[dim] = 0.0f; }