"""Shared context-budget / truncation helpers (baseline-identical numbers). 🔴 RL rollout AND eval must use the SAME budget (plan §4.3 / §4.4 / eval): - model_max = 32000, gen_length(answer) = 800 - max_retrieval_tokens = 32000 - 800 - 1000 = 30200 - retrieved-session text exceeding 30200 → char-ratio crop (baseline build_prompt_rag) - final full_ids exceeding 32000 → LEFT-truncate (truncation_side="left"): drop the earliest retrieved text first, keep recent decision/answer markers. - answer max_new_tokens = 800 (RL and eval IDENTICAL — never 200 here / 800 there) - decision segment max_new_tokens = 64 (only [MS:*][ACT:*][EOQ]) estimate_tokens uses len//4 (baseline). The char-ratio crop mirrors baseline exactly. """ from typing import List, Tuple MODEL_MAX = 32000 GEN_LENGTH = 800 RESERVE = 1000 MAX_RETRIEVAL_TOKENS = MODEL_MAX - GEN_LENGTH - RESERVE # 30200 DECISION_MAX_NEW_TOKENS = 64 ANSWER_MAX_NEW_TOKENS = GEN_LENGTH # 800 def estimate_tokens(text: str) -> int: return len(text) // 4 def crop_retrieval_text(history_string: str, max_tokens: int = MAX_RETRIEVAL_TOKENS) -> str: """Char-ratio crop of the assembled retrieved-session string (baseline口径).""" est = estimate_tokens(history_string) if est > max_tokens: ratio = max_tokens / est char_limit = int(len(history_string) * ratio) return history_string[:char_limit] return history_string def left_truncate_ids(full_ids: List[int], mask: List[bool], max_length: int = MODEL_MAX, *extra_masks: List[bool]): """LEFT-truncate full_ids (+ aligned mask and any extra aligned masks) to max_length. Drops the earliest tokens (retrieved text sits at the front of the post-decision region; the decision prompt itself also sits at the very front). This matches baseline tokenizer(truncation=True, truncation_side='left', max_length=32000): the most recent answer marker / decision survive, the oldest text is dropped. Returns (ids, mask) when no extra masks, else (ids, mask, *extra_masks). """ if len(full_ids) <= max_length: return (full_ids, mask) if not extra_masks else (full_ids, mask, *extra_masks) cut = len(full_ids) - max_length if not extra_masks: return full_ids[cut:], mask[cut:] return (full_ids[cut:], mask[cut:], *(em[cut:] for em in extra_masks))