Files
ModelHub XC c1ce9811bb 初始化项目,由ModelHub XC社区提供模型
Model: Xirui1208/selective-readtwice-7b-early-evaluated-20260928
Source: Original Platform
2026-11-17 05:18:17 +08:00

359 lines
12 KiB
Python

"""ReadTwice 的统一提示词与有界记忆校验。
本模块只定义纯 ReadTwice 流程:先为每个分块建立导航提要,再逐块
重写完整记忆,最后基于记忆作答。持久记忆的内容上限固定为 1024
tokens;运行时不得把 evidence delta 当成完整记忆追加到旧状态。
"""
from __future__ import annotations
from dataclasses import dataclass
import re
from typing import Literal
NO_MEMORY = "No previous memory"
KEEP_MEMORY = "<KEEP_MEMORY>"
MEMORY_TOKEN_LIMIT = 1024
# 生成预算必须大于正文上限,为 EOS 和 tokenizer 边界预留空间。
MEMORY_GENERATION_MAX_TOKENS = 1088
ABILITY_LONG_CONTEXT_QA = "long_context_qa"
ABILITY_MULTIPLE_CHOICE = "multiple_choice"
ABILITY_QUERY_FOCUSED_SUMMARY = "query_focused_summary"
SUPPORTED_ABILITIES = frozenset(
{
ABILITY_LONG_CONTEXT_QA,
ABILITY_MULTIPLE_CHOICE,
ABILITY_QUERY_FOCUSED_SUMMARY,
}
)
TEMPLATE_SKIM = """<section>
{chunk}
</section>
[Task: NAVIGATION-ONLY CHUNK OUTLINE]
Identify every distinct major content unit in THIS section and give each unit one short topic label. This outline is only a map for a later reader; it is not a replacement for the source.
Use the shortest label that identifies each unit. Preserve a source title or heading when one is available; otherwise infer a 2-6 word topic label. A structural marker such as Document 12, Section 3, or Chapter 4 is not an informative label by itself; replace it with the unit's actual title or topic. Keep the units in source order and cover all of them, including topics that may appear unimportant without a future question.
Output one compact paragraph beginning with OUTLINE: and separate labels with |. Include labels only. Do not copy body facts, dates, descriptions, relationships, answers, relevance judgments, or missing-information statements. Do not use a question.
Output:
"""
TEMPLATE_UPDATE_READTWICE = """<section>
{chunk}
</section>
[Task: OUTLINE-GUIDED COMPLETE MEMORY REWRITE]
[Contract: 完整记忆; 不是 evidence delta]
The section above is the current section.
<problem>
{prompt}
</problem>
<memory>
{memory}
</memory>
<current_section_id>
{section_id}
</current_section_id>
<outline>
{outline}
</outline>
Read the current section carefully and produce the next complete memory state.
The output is not an evidence delta and must not mechanically copy the old memory
and append a suffix. You may reorganize, rewrite, merge, deduplicate, and compress
facts while preserving every useful answer fact, entity identity, alias, number,
date, relation, and unresolved bridge.
Use the outline only for navigation; it is never evidence. Old facts may come only
from the previous memory, and new facts may come only from the current section.
Never fill a missing relation from the problem wording, the outline, or general
knowledge.
Follow exactly one branch:
1. If the current section adds no useful new fact, output only <KEEP_MEMORY>.
2. Otherwise output only the rewritten complete memory body, with no heading,
label, code fence, analysis, or explanation.
The complete memory body is limited to 1024 tokens. Near the limit, compress
repetition and low-value detail first. Never truncate a sentence or delete an
answer fact or required bridge merely to fit.
Output:
"""
# QMSum used this source-specific complete-rewrite prompt in the admitted
# ReadAll/Selective Stage-B SFT rows. RL selects it from the validated
# ``ability`` field so continuation does not silently change the policy input.
TEMPLATE_UPDATE_SUMMARY = """<section>
{chunk}
</section>
[Task: INCREMENTAL COMPLETE SUMMARY MEMORY REWRITE]
Maintain a complete compact summary of the target document while reading it in
sections. The output is the complete next memory, not a delta. Preserve every
important fact already in memory and add important facts from the current
section. Ignore explicitly marked background/distractor material. Do not add
facts absent from the old memory or current section.
<summary_request>
{question}
</summary_request>
<memory>
{memory}
</memory>
<current_section_id>{section_id}</current_section_id>
<outline>
{outline}
</outline>
If the section adds nothing, output only <KEEP_MEMORY>. Otherwise output only
the rewritten complete memory body, at most 1024 tokens. No heading or notes.
Output:
"""
def update_template_for_ability(ability: object) -> str:
"""Return the exact admitted SFT UPDATE template for one task ability."""
if not isinstance(ability, str) or ability not in SUPPORTED_ABILITIES:
raise ValueError(f"unsupported recurrent ability: {ability!r}")
if ability == ABILITY_QUERY_FOCUSED_SUMMARY:
return TEMPLATE_UPDATE_SUMMARY
return TEMPLATE_UPDATE_READTWICE
TEMPLATE_FINAL = """You are presented with a problem and a previous memory. Please answer the problem based on the previous memory and put the answer in \\boxed{{}}.
<problem>
{prompt}
</problem>
<memory>
{memory}
</memory>
Output only the boxed answer. Do not add notes, assumptions, or explanations.
Your answer:
"""
# KEEP 只能作为完整响应单独出现,混在正文中属于格式错误。
_KEEP_MARKER_RE = re.compile(r"<\s*KEEP_MEMORY\s*>", flags=re.IGNORECASE)
# 这些包装意味着模型没有遵守“只输出记忆正文”的协议。
_FORBIDDEN_WRAPPER_RE = re.compile(
r"(?:```|</?(?:section|problem|memory|outline|current_section_id)>|"
r"^\s*(?:updated\s+memory|memory|完整记忆|更新后的记忆)\s*:)",
flags=re.IGNORECASE | re.MULTILINE,
)
# 缺失信息和过程性措辞不是可持久化事实,也常见于失败/截断输出。
# Absence verbs are scoped to self-references to the model input. Scientific
# source text legitimately says things such as "a node does not contain the
# subtree" and must remain representable as grounded memory.
_META_OR_ABSENCE_RE = re.compile(
r"\b(?:current section|section above|provided documents?|given documents?|"
r"provided context|given context|context above|provided passages?|given passages?|"
r"current memory)\b.{0,80}\b(?:does not contain|do not contain|contains? no|"
r"has no|no relevant information|no useful information|cannot answer|"
r"can not answer|not mentioned)\b|"
r"\b(?:cannot answer|can not answer)\b|"
r"\b(?:the answer|requested information|required information)\b.{0,48}\b"
r"(?:not mentioned|not provided|not available|missing|cannot be determined)\b|"
r"\b(?:according to the outline|based on the outline|the problem asks)\b|"
r"(?:当前分块|上述分块|所给文档).{0,16}(?:没有|未提及|无法|不能)|"
r"(?:根据|基于)(?:该|上述)?(?:提要|问题)",
flags=re.IGNORECASE,
)
@dataclass(frozen=True)
class MemoryUpdateDecision:
"""一次记忆输出的确定性解析结果。"""
action: Literal["replace", "keep", "reject"]
text: str
token_count: int
reason: str
@property
def should_replace(self) -> bool:
"""仅合法的完整重写可以替换持久记忆。"""
return self.action == "replace"
@property
def is_valid(self) -> bool:
"""KEEP 和合法重写都属于协议内输出。"""
return self.action != "reject"
def clean_gist(text: str) -> str:
"""去重 pipe 标签,并把单个 section 的提要规范为一行。"""
raw = text or ""
prefix = re.match(r"^\s*(?:gist|outline)\s*:\s*", raw, flags=re.IGNORECASE)
cleaned = re.sub(
r"^\s*(?:gist|outline)\s*:\s*", "OUTLINE: ", raw, flags=re.IGNORECASE
).strip()
normalized = " ".join(cleaned.split())
if prefix is None or "|" not in raw[prefix.end() :]:
return normalized
labels: list[str] = []
seen: set[str] = set()
for value in raw[prefix.end() :].split("|"):
label = " ".join(value.split())
if not label:
continue
key = label.casefold()
if key in seen:
continue
seen.add(key)
labels.append(label)
return ("OUTLINE: " + " | ".join(labels)).strip()
def build_outline(gists) -> str:
"""按分块顺序构造全局导航提要。"""
return "\n".join(
f"[Section {section_id}] {str(gist).strip()}"
for section_id, gist in enumerate(gists, 1)
)
def is_keep_memory(text: str) -> bool:
"""判断响应是否为严格的 KEEP 控制符。"""
return str(text or "").strip().upper() == KEEP_MEMORY
def _parse_memory_update(
raw_text: str,
tokenizer,
*,
token_limit: int = MEMORY_TOKEN_LIMIT,
reject_meta_or_absence: bool,
) -> MemoryUpdateDecision:
if token_limit != MEMORY_TOKEN_LIMIT:
return MemoryUpdateDecision("reject", "", 0, "unexpected_token_limit")
if not isinstance(raw_text, str):
return MemoryUpdateDecision("reject", "", 0, "non_text_output")
text = raw_text.strip()
if not text:
return MemoryUpdateDecision("reject", "", 0, "empty_output")
if is_keep_memory(text):
return MemoryUpdateDecision("keep", KEEP_MEMORY, 0, "keep_memory")
if _KEEP_MARKER_RE.search(text):
return MemoryUpdateDecision("reject", "", 0, "mixed_keep_marker")
if text == NO_MEMORY or NO_MEMORY.lower() in text.lower():
return MemoryUpdateDecision("reject", "", 0, "memory_placeholder")
if _FORBIDDEN_WRAPPER_RE.search(text):
return MemoryUpdateDecision("reject", "", 0, "invalid_wrapper")
if reject_meta_or_absence and _META_OR_ABSENCE_RE.search(text):
return MemoryUpdateDecision("reject", "", 0, "meta_or_absence_claim")
try:
token_ids = tokenizer.encode(text, add_special_tokens=False)
except Exception:
return MemoryUpdateDecision("reject", "", 0, "tokenization_failed")
token_count = len(token_ids)
if token_count == 0:
return MemoryUpdateDecision("reject", "", 0, "empty_tokenization")
if token_count > MEMORY_TOKEN_LIMIT:
return MemoryUpdateDecision("reject", "", token_count, "memory_too_long")
return MemoryUpdateDecision("replace", text, token_count, "rewritten_memory")
def parse_memory_update(
raw_text: str,
tokenizer,
*,
token_limit: int = MEMORY_TOKEN_LIMIT,
) -> MemoryUpdateDecision:
"""Parse a free-form model UPDATE under the strict protocol contract.
tokenizer only needs ``encode(text, add_special_tokens=False)``. Besides
structure and token budget, teacher/model output is rejected when it tries
to persist a self-referential missing-information claim instead of KEEP.
"""
return _parse_memory_update(
raw_text,
tokenizer,
token_limit=token_limit,
reject_meta_or_absence=True,
)
def parse_grounded_memory_update(
raw_text: str,
tokenizer,
*,
token_limit: int = MEMORY_TOKEN_LIMIT,
) -> MemoryUpdateDecision:
"""Validate exact source-grounded memory without teacher-output heuristics.
Exact evidence has already been proven to occur in an admitted support
section. It still must obey control-marker, wrapper, non-empty, and 1,024
token contracts, but legitimate scientific negative relations must not be
mistaken for a model's missing-information refusal.
"""
return _parse_memory_update(
raw_text,
tokenizer,
token_limit=token_limit,
reject_meta_or_absence=False,
)
def canonical_final(answer: str) -> str:
"""把监督答案统一成严格 boxed 格式。"""
return f"\\boxed{{{str(answer).strip()}}}"
__all__ = [
"ABILITY_LONG_CONTEXT_QA",
"ABILITY_MULTIPLE_CHOICE",
"ABILITY_QUERY_FOCUSED_SUMMARY",
"KEEP_MEMORY",
"MEMORY_GENERATION_MAX_TOKENS",
"MEMORY_TOKEN_LIMIT",
"MemoryUpdateDecision",
"NO_MEMORY",
"TEMPLATE_FINAL",
"TEMPLATE_SKIM",
"TEMPLATE_UPDATE_READTWICE",
"TEMPLATE_UPDATE_SUMMARY",
"SUPPORTED_ABILITIES",
"build_outline",
"canonical_final",
"clean_gist",
"is_keep_memory",
"parse_memory_update",
"parse_grounded_memory_update",
"update_template_for_ability",
]