on_the_way / context_utils.py
RANITBAG's picture
Upload 33 files
d12a5da verified
Raw History Blame Contribute Delete
3.79 kB
"""Context-length utilities for MiniMindOmni text-only chat.
WHY THIS FILE EXISTS (the 32768 myth):
config.json advertises max_position_embeddings=32768, but MiniMindConfig only
reaches that ceiling *through* YaRN rope_scaling (inference_rope_scaling=true,
factor=16 over an original_max_position_embeddings=2048 base). With scaling off
(the shipped default), the model runs UNSCALED RoPE it was never trained on
beyond ~2048 positions. So the honest pre-YaRN context budget is ~2048, and the
honest post-training budget is whatever your fine-tune actually saw (likely
512-768 in the Omni SFT stages). Treat 32768 as a hardware limit, not a
capability.
"""
def count_and_truncate_context(tokenizer, messages, max_tokens=1400):
"""Trim a chat history to a token budget, dropping OLDEST turns first.
Rules:
- The system prompt (if present) is never dropped.
- The CURRENT (last) user turn is never dropped.
- Oldest droppable turns are removed one at a time until the rendered
conversation (template overhead included) fits max_tokens.
- If only system + current turn remain and it still exceeds the budget,
we return it as-is with truncated=True (caller must decide: raise, or
hard-truncate the system/current content themselves).
Returns: (trimmed_messages, truncated_flag)
"""
msgs = [dict(m) for m in messages]
def n_tokens(ms):
ids = tokenizer.apply_chat_template(
ms, tokenize=True, add_generation_prompt=True)
return len(ids)
truncated = False
while n_tokens(msgs) > max_tokens:
# oldest turn that is NOT system and NOT the final message
idx = next((i for i, m in enumerate(msgs[:-1])
if m.get("role") != "system"), None)
if idx is None:
break # nothing left we are allowed to drop
del msgs[idx]
truncated = True
if n_tokens(msgs) > max_tokens:
truncated = True # even system+current alone exceed the budget
return msgs, truncated
# --------------------------------------------------------------------------
# YaRN (Yet another RoPE extensioN) — what it changes and why:
#
# Plain RoPE assigns each position p a rotation with frequencies
# f_i = theta^(-2i/d) (theta = rope_theta = 1e6 here)
# For positions p > ~2048 the rotation angles land in a regime the model never
# saw during training, so attention scores become extrapolations the weights
# cannot interpret -> "it stops understanding context".
#
# YaRN *modifies the frequency table itself* (see precompute_freqs_cis in
# model_minimind.py): every f_i is rescaled by 1/factor (factor=16), so position
# p rotates like position p/16 — i.e. long positions reuse rotation patterns the
# model WAS trained on. The ramp between beta_slow/beta_fast bands interpolates
# so low-frequency (long-wavelength) dims get the full 1/16 rescale while
# high-frequency dims stay closer to original, and attention_factor rescales
# attention logits to keep softmax statistics stable after interpolation.
#
# 2048 * 16 = 32768 <- exactly the advertised ceiling. That is the tell.
#
# Why it can HELP: positions 2049..32768 become interpolations of trained
# positions instead of raw extrapolation.
# Why it can FAIL: the model still never *trained* on dependencies that long, so
# it may attend locally fine yet simply not exploit long-range structure; and on
# a heavily fine-tuned small model the YaRN frequency shift itself can cost a
# little short-context quality. Always A/B (which is what eval_context_length.py
# does) before enabling it in production.
# --------------------------------------------------------------------------