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

313 lines
12 KiB
Python

"""ReadAll v6 数据生成与评测共用的协议、模板和确定性校验函数。
第一遍为每个 section 生成问题无关的导航 outline;第二遍逐节读取全部内容,
用当前 section 的证据增量确定性追加 memory,最后仅依据累计 memory 作答。
本文件只保留数据代码与 ReadAll 评测真实引用的符号。
"""
import re
NO_MEMORY = "No previous memory"
KEEP_MEMORY = "<KEEP_MEMORY>"
TEACHER_EMPTY_MEMORY = "<EMPTY_MEMORY>"
SKIM_TARGET_MIN_TOKENS = 4
SKIM_HARD_MAX_TOKENS = 480
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 = """<section>
{chunk}
</section>
[Task: OUTLINE-GUIDED MEMORY UPDATE]
The section above is the current selected section.
<problem>
{prompt}
</problem>
<memory>
{memory}
</memory>
<current_section_id>
{section_id}
</current_section_id>
<outline>
{outline}
</outline>
Please read the selected section carefully and update the memory with new information that helps answer the problem. Use the outline only to notice which locally stated facts may connect to later topics. The outline is never evidence.
A partial bridge fact is useful even when this section cannot answer the problem by itself. Preserve names, roles, relationships, dates, numbers, and enough local context for the evidence chain. Every new sentence must closely follow one local passage in the selected section. Never join an entity from one content unit to an attribute from another unless the selected section explicitly states that relationship.
If useful evidence exists and there is previous memory, copy the previous memory verbatim at the beginning, then append only the new supported sentences. Do not rewrite, shorten, reinterpret, or correct previous memory. Write direct factual memory only: do not cite Document or Section numbers, mention the outline or problem, explain why evidence is useful, or add conclusions such as "as evidenced by", "therefore", or "this confirms".
If the selected section adds no useful information, output exactly <KEEP_MEMORY>. Otherwise output only the complete append-only updated memory.
Updated memory:
"""
TEMPLATE_UPDATE_READALL = TEMPLATE_UPDATE
TEMPLATE_UPDATE_DELTA_TEACHER = """[Task: EXTRACT CURRENT-SECTION EVIDENCE DELTA]
<problem>
{prompt}
</problem>
<previous_memory>
{memory}
</previous_memory>
<current_section_id>
{section_id}
</current_section_id>
<outline>
{outline}
</outline>
<section>
{chunk}
</section>
Extract only NEW facts from the current section that help answer the problem. The result is an evidence delta, not the complete updated memory. Use previous_memory only to avoid repeating facts already stored. Never copy, rewrite, summarize, or output previous_memory. Never output the literal <EMPTY_MEMORY>.
The outline is only a navigation map. It may help you notice a partial bridge to a later topic, but it is never evidence. Do not use the problem wording, the outline, or general knowledge to fill a missing relation. A partial bridge fact is useful even if this section cannot answer the problem by itself.
Select the smallest sufficient evidence delta. A fact being true in the source does not by itself make it useful: omit a sentence if removing it would not affect an answer candidate, an entity identity, or a required bridge relation. For a bridge-only section, retain only the minimal relation needed to identify or connect the bridge entity.
Use extractive wording: copy the shortest complete source sentence or source clause that states each useful fact. You may delete irrelevant clauses, but do not freely paraphrase. Keep names, aliases, roles, relationships, dates, numbers, and enough local context for the chain. Stop as soon as each useful entity or relation is preserved: do not copy neighboring plot details, biography, examples, or background merely because they are adjacent. When two source sentences are needed, output both separately; never fuse facts from separate passages into a new inferred claim. Normally use one or two sentences and no more than 80 words.
Write facts only. Do not cite Document or Section numbers, mention the outline or problem, explain relevance, make guesses, state missing information, or write reasoning such as "as evidenced by", "therefore", "this confirms", "suggests", or "can be inferred".
Follow exactly one branch:
1. If at least one new useful source-grounded fact exists, output only those new evidence sentences. Do not add a label or the previous memory. The output must not contain KEEP_MEMORY.
2. If no new useful source-grounded fact exists, output exactly <KEEP_MEMORY> and nothing else.
Output:
"""
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:
"""
NEGATIVE_CLAIM_RE = re.compile(
r"\b(?:"
r"no (?:specific |direct |relevant |useful |additional )?(?:information|answer|evidence|mention|connection)|"
r"no (?:explicit |clear |established )?(?:connection|link|relationship)|"
r"does not (?:contain|mention|provide|state|match|establish|identify|indicate|show|support)|"
r"do not (?:contain|mention|provide|state|match|establish|identify|indicate|show|support)|"
r"not (?:mentioned|provided|stated|found|available|directly answered|relevant)|"
r"not (?:directly |explicitly )?(?:identified|established|indicated|shown|supported)|"
r"cannot (?:answer|determine|be determined|be established|be confirmed|be verified)|"
r"unable to (?:answer|determine)|insufficient (?:information|evidence|context)|"
r"lack(?:s|ing)? (?:of )?(?:information|evidence|context)|"
r"none of the documents|no previous memory"
r")\b",
flags=re.IGNORECASE,
)
KEEP_MARKER_RE = re.compile(r"<?\s*KEEP[_ ]MEMORY\s*>?", flags=re.IGNORECASE)
EVIDENCE_WORD_RE = re.compile(r"[a-z0-9]+", flags=re.IGNORECASE)
EVIDENCE_SENTENCE_RE = re.compile(r"(?<=[.!?])\s+|\n+")
META_REASONING_RE = re.compile(
r"\b(?:document|section)\s*\d+\b|"
r"\b(?:mentioned in|according to) (?:the )?outline\b|"
r"\b(?:problem statement|provided documents?|provided section|current section)\b|"
r"\b(?:as evidenced by|further establishing|can be inferred|directly answers?)\b|"
r"\b(?:this (?:information|evidence) (?:aligns|confirms|indicates|shows|supports)|"
r"therefore|thus|which suggests|providing a connection)\b",
flags=re.IGNORECASE,
)
EVIDENCE_STOPWORDS = frozenset(
"""
a an the and or but if then than to of in on at for from with by as is are was
were be been being it its this that these those who which what when where how
has have had do does did into over under about also additionally further
their his her they he she we you i our your through during after before
between among while only
""".split()
)
LOCAL_EVIDENCE_WINDOW_WORDS = 160
LOCAL_EVIDENCE_WINDOW_STRIDE = 40
MIN_LOCAL_SENTENCE_SUPPORT = 0.85
MAX_EVIDENCE_DELTA_WORDS = 100
MIN_NOVEL_CHUNK_SUPPORT = 0.80
MIN_PREVIOUS_MEMORY_PRESERVATION = 1.00
def build_outline(gists):
"""把章节 gist 依次格式化为带编号的纲要。"""
return "\n".join(f"[Section {i + 1}] {gist.strip()}" for i, gist in enumerate(gists))
def has_negative_claim(text):
"""检测文本是否包含否定性证据声明。"""
return bool(NEGATIVE_CLAIM_RE.search(text or ""))
def clean_gist(text):
"""移除可选 GIST 前缀并清理首尾空白。"""
return re.sub(r"^\s*gist\s*:\s*", "", text or "", flags=re.IGNORECASE).strip()
def clean_memory(text):
"""移除可选 UPDATED MEMORY 前缀并清理空白。"""
text = (text or "").strip()
text = re.sub(r"^\s*updated memory\s*:\s*", "", text, flags=re.IGNORECASE).strip()
return text
def is_keep_memory(text):
"""判断清理后的输出是否为保持记忆标记。"""
return clean_memory(text).upper() == KEEP_MEMORY
def has_keep_marker(text):
"""检测文本中是否出现保持记忆标记。"""
return bool(KEEP_MARKER_RE.search(text or ""))
def evidence_word_list(text):
"""提取小写证据词并过滤停用词,同时保留词频。"""
return [
token
for token in EVIDENCE_WORD_RE.findall(str(text).lower())
if token not in EVIDENCE_STOPWORDS
]
def evidence_words(text):
"""提取去重后的证据词集合。"""
return set(evidence_word_list(text))
def has_meta_reasoning(text):
"""检测文本是否混入元推理措辞。"""
return bool(META_REASONING_RE.search(text or ""))
def appended_evidence(candidate, previous_memory):
"""从候选记忆中分离相对旧记忆新增的证据文本。"""
candidate = str(candidate).strip()
if previous_memory == NO_MEMORY:
return candidate
previous_memory = str(previous_memory).strip()
if not candidate.startswith(previous_memory):
return None
return candidate[len(previous_memory):].strip()
def local_evidence_scores(new_text, chunk):
"""计算新增文本词窗与当前章节的局部证据重合分数。"""
chunk_words = evidence_word_list(chunk)
if not chunk_words:
return []
windows = []
for start in range(0, max(1, len(chunk_words)), LOCAL_EVIDENCE_WINDOW_STRIDE):
windows.append(
set(chunk_words[start:start + LOCAL_EVIDENCE_WINDOW_WORDS])
)
if start + LOCAL_EVIDENCE_WINDOW_WORDS >= len(chunk_words):
break
scores = []
for sentence in EVIDENCE_SENTENCE_RE.split(str(new_text)):
sentence_words = evidence_words(sentence)
if not sentence_words:
continue
scores.append(
max(
len(sentence_words & window) / len(sentence_words)
for window in windows
)
)
return scores
def update_lexical_grounding(candidate, previous_memory, chunk):
"""评估候选记忆更新相对旧记忆和章节的词汇落地程度。"""
candidate_words = evidence_words(candidate)
previous_words = (
set() if previous_memory == NO_MEMORY else evidence_words(previous_memory)
)
chunk_words = evidence_words(chunk)
novel_words = candidate_words - previous_words
new_text = appended_evidence(candidate, previous_memory)
local_scores = (
local_evidence_scores(new_text, chunk)
if new_text is not None
else []
)
return {
"append_only": new_text is not None,
"meta_reasoning": has_meta_reasoning(new_text or ""),
"novel_word_count": len(novel_words),
"novel_chunk_support": (
len(novel_words & chunk_words) / len(novel_words)
if novel_words
else 0.0
),
"local_sentence_count": len(local_scores),
"local_sentence_support_min": (
min(local_scores) if local_scores else 0.0
),
"previous_word_count": len(previous_words),
"previous_memory_preservation": (
len(previous_words & candidate_words) / len(previous_words)
if previous_words
else 1.0
),
}
def compose_updated_memory(previous_memory, evidence_delta):
"""在不改写旧记忆的前提下,将 teacher 的证据增量追加到记忆末尾。"""
evidence_delta = str(evidence_delta).strip()
if previous_memory == NO_MEMORY:
return evidence_delta
return f"{str(previous_memory).strip()}\n{evidence_delta}"
def canonical_final(answer):
"""把最终答案规范为 boxed 形式。"""
return f"\\boxed{{{str(answer).strip()}}}"