data_mem / step_train /src /model /tokenizer_utils.py
dudulu66666's picture
Add files using upload-large-folder tool
4968ea3 verified
Raw
History Blame Contribute Delete
12.5 kB
"""Pseudo-token span utilities (NO vocab extension).
Control signals ([MS:*] [ACT:*] [EOQ] [ANS] [RETRIEVED]) are plain text strings
fed through the original Qwen3-8B tokenizer's subword splitting. We never call
add_special_tokens / resize embeddings / touch lm_head. This is the Search-R1 /
R1 route: the framework parses control strings deterministically and masks token
spans by *segmented* tokenization + length-based concatenation (NOT substring β†’
token-boundary guessing, which is ambiguous).
This module provides three pure helpers:
- tokenize_with_spans: split a target into [MS:*] / [ACT:*]..[EOQ] / rest segments,
encode each with add_special_tokens=False, concatenate, and return target_ids
plus two token-level bool masks (ms_mask, act_query_mask).
- find_marker_token_span: locate a marker's token span inside an id list
(used on the rollout side to cut the [EOQ] boundary and locate the [MS:*] span).
- extract_control_strings: regex out [MS:X], [ACT:Y], <rewrite_query> from text;
malformed output returns a fallback flag. reward/parse use strings, not ids.
"""
import re
from typing import List, Optional, Tuple
from src.utils.special_tokens import (
ACT_TOKENS,
EOQ_TOKEN,
MS_TOKENS,
)
# Regex anchors over the pseudo-token strings. We allow optional surrounding
# whitespace; the strings themselves are literal "[MS:SM]" etc.
_MS_RE = re.compile(r"\[MS:(SM|PM|VM|NM)\]")
_ACT_RE = re.compile(r"\[ACT:(DIRECT|REWRITE|CLUE|RETRIEVE)\]")
_EOQ_RE = re.compile(re.escape(EOQ_TOKEN))
_VALID_MS = set(MS_TOKENS.keys())
_VALID_ACT = set(ACT_TOKENS.keys())
def tokenize_with_spans(
tok,
prompt_str: str,
target_str: str,
) -> dict:
"""Tokenize prompt + target and return target spans for loss weighting.
The target string is expected to look like:
"[MS:PM] [ACT:REWRITE] <rewrite query text> [EOQ]"
or for SM/DIRECT:
"[MS:SM] [ACT:DIRECT] [EOQ]" (empty rewrite span)
We segment the target into three pieces so we can label spans precisely:
seg_ms : the "[MS:*]" marker (+ trailing space)
seg_act_q: "[ACT:*] <query> [EOQ]" (the act marker through and including EOQ)
(there is no "rest" after EOQ in SFT targets; everything is covered)
Each segment is encoded with add_special_tokens=False and concatenated. The
masks are built from segment token lengths (no substring search), which is the
robust Search-R1 alignment trick.
Returns dict with:
prompt_ids: List[int]
target_ids: List[int]
ms_mask: List[bool] len == len(target_ids); True over [MS:*] subwords
act_query_mask: List[bool] len == len(target_ids); True over [ACT:*]..[EOQ]
ms_str: the matched "[MS:*]" string (or None)
act_str: the matched "[ACT:*]" string (or None)
"""
prompt_ids = tok.encode(prompt_str, add_special_tokens=False)
ms_match = _MS_RE.search(target_str)
act_match = _ACT_RE.search(target_str)
eoq_idx = target_str.find(EOQ_TOKEN)
target_ids: List[int] = []
ms_mask: List[bool] = []
act_query_mask: List[bool] = []
def _append(segment: str, is_ms: bool, is_act_q: bool):
if segment == "":
return
seg_ids = tok.encode(segment, add_special_tokens=False)
target_ids.extend(seg_ids)
ms_mask.extend([is_ms] * len(seg_ids))
act_query_mask.extend([is_act_q] * len(seg_ids))
if ms_match is None or act_match is None or eoq_idx == -1:
# Malformed target (should not happen for SFT-built targets). Encode whole
# thing as a generic (unmasked) span so training still proceeds.
_append(target_str, is_ms=False, is_act_q=False)
return {
"prompt_ids": prompt_ids,
"target_ids": target_ids,
"ms_mask": ms_mask,
"act_query_mask": act_query_mask,
"ms_str": ms_match.group(0) if ms_match else None,
"act_str": act_match.group(0) if act_match else None,
}
# Segment boundaries (character offsets in target_str):
# [0, ms_start) : any leading text (usually empty) -> generic
# [ms_start, ms_end) : [MS:*] -> ms span
# [ms_end, act_start) : between MS and ACT (whitespace) -> generic
# [act_start, eoq_end) : [ACT:*] .. [EOQ] (inclusive) -> act_query span
# [eoq_end, end) : trailing (should be empty) -> generic
ms_start, ms_end = ms_match.start(), ms_match.end()
act_start = act_match.start()
eoq_end = eoq_idx + len(EOQ_TOKEN)
_append(target_str[:ms_start], is_ms=False, is_act_q=False)
_append(target_str[ms_start:ms_end], is_ms=True, is_act_q=False)
_append(target_str[ms_end:act_start], is_ms=False, is_act_q=False)
_append(target_str[act_start:eoq_end], is_ms=False, is_act_q=True)
_append(target_str[eoq_end:], is_ms=False, is_act_q=False)
assert len(ms_mask) == len(act_query_mask) == len(target_ids)
return {
"prompt_ids": prompt_ids,
"target_ids": target_ids,
"ms_mask": ms_mask,
"act_query_mask": act_query_mask,
"ms_str": ms_match.group(0),
"act_str": act_match.group(0),
}
def tokenize_with_answer(
tok,
prompt_str: str,
decision_segments: List[Tuple[str, str]],
rag_block: str,
answer_suffix: str,
answer_str: str,
eos_id: Optional[int],
model_max: Optional[int] = None,
) -> dict:
"""Phase-C SFT tokenization: prompt + decision + retrieved block + answer cue + answer.
πŸ”΄ This MUST be byte-identical (token-id level) to the rollout's teacher-forcing prefix
(src/train/rl/rollout.py). The rollout encodes each segment SEPARATELY with
add_special_tokens=False (Qwen BPE merges across segment boundaries if concatenated
first), so we replicate the SAME per-segment encode order. The decision segment encode
differs PER forced branch, so 08c pre-splits it into `decision_segments` (a list of
(seg_str, role) where role ∈ {"dec", "query_fixed", "query_content"}); we just encode
each seg_str in order β€” NOT reuse tokenize_with_spans (whose [MS]/space/[ACT]..[EOQ]
split produces different ids). See plan critique #2.
Segment order (mirrors rollout):
prompt_str β†’ label -100, answer_mask False
*decision_segments β†’ label real, answer_mask False (teacher-forced context)
rag_block ("" for SM β†’ skip)β†’ label -100, answer_mask False
answer_suffix (ends [ANS]) β†’ label -100, answer_mask False
answer_str β†’ label real, answer_mask True
eos β†’ label real, answer_mask True πŸ”΄ eos ONLY here
πŸ”΄ eos is appended ONLY after the final answer, NEVER after the decision segment
(the existing tokenize_with_spans path appends eos after the decision target; doing
that here would make the Phase-C prefix diverge from the rollout β€” critique #4).
Phase C trains ONLY the answer span (weighted_ce_loss active = labels!=-100 &
answer_mask), so decision labels being "real" is harmless β€” they never enter the loss.
Returns dict: input_ids / labels / answer_mask (equal-length List[int]/List[int]/List[bool]).
"""
input_ids: List[int] = []
labels: List[int] = []
answer_mask: List[bool] = []
def _append(segment: str, is_label: bool, is_answer: bool):
if segment == "":
return
seg_ids = tok.encode(segment, add_special_tokens=False)
input_ids.extend(seg_ids)
labels.extend(seg_ids if is_label else [-100] * len(seg_ids))
answer_mask.extend([is_answer] * len(seg_ids))
_append(prompt_str, is_label=False, is_answer=False)
for seg_str, _role in decision_segments:
_append(seg_str, is_label=True, is_answer=False)
_append(rag_block, is_label=False, is_answer=False) # "" for SM/DIRECT β†’ skipped
_append(answer_suffix, is_label=False, is_answer=False)
_append(answer_str, is_label=True, is_answer=True)
if eos_id is not None:
input_ids.append(eos_id)
labels.append(eos_id)
answer_mask.append(True)
if model_max is not None and len(input_ids) > model_max:
cut = len(input_ids) - model_max
input_ids = input_ids[cut:]
labels = labels[cut:]
answer_mask = answer_mask[cut:]
assert len(input_ids) == len(labels) == len(answer_mask)
return {"input_ids": input_ids, "labels": labels, "answer_mask": answer_mask}
def find_marker_token_span(
ids: List[int],
tok,
marker_str: str,
start: int = 0,
) -> Optional[Tuple[int, int]]:
"""Find the first token span in ids whose decoded text contains marker_str.
Decode-based (NOT exact id-subsequence): a marker's subword tokenization differs
by what precedes it (e.g. "[EOQ]" -> [58,6760,48,60] standalone vs [508,6760,48,60]
when glued to a preceding space). So we incrementally decode and locate the marker
string. Returns (begin, end) β€” token indices such that ids[:end] is the smallest
prefix whose tail contains marker_str, and ids[begin:end] is the tightest window
still containing it. Returns None if not found.
Used on the rollout side to cut the decision segment right after the first [EOQ]
(keep ids[:end]) and to locate the [MS:*] span. O(n^2) decodes but n is tiny
(<=64 here). [ANS] is NOT searched β€” it is concatenated as a known-length suffix.
"""
n = len(ids)
for end in range(start + 1, n + 1):
if marker_str in tok.decode(ids[start:end]):
# tighten the begin: largest begin < end still containing the marker
begin = start
for b in range(start, end):
if marker_str in tok.decode(ids[b:end]):
begin = b
else:
break
return (begin, end)
return None
# control pseudo-tokens that must NEVER appear in a final answer string. They are plain
# text (not registered special tokens), so tokenizer.decode(skip_special_tokens=True)
# does NOT remove them β€” the model, trained to emit [EOQ] in the decision stage, often
# tails the answer with "... [EOQ]". We truncate at the first such marker and strip any
# leftovers, so eval EM/F1 and DAPO reward (both read traj.answer) are not polluted.
_ANSWER_STOP_MARKERS = ("[EOQ]", "[ANS]", "[RETRIEVED]", "[/RETRIEVED]")
_CONTROL_TOKEN_RE = re.compile(r"\[(?:MS|ACT):[A-Z]+\]|\[/?(?:EOQ|ANS|RETRIEVED|QUERY)\]")
def clean_answer_text(text: str) -> str:
"""Strip control pseudo-tokens from a generated answer.
Truncate at the FIRST answer-stop marker ([EOQ]/[ANS]/[RETRIEVED]/[/RETRIEVED]) β€”
anything the model emits after it is control garbage, not answer content β€” then
remove any stray [MS:*]/[ACT:*]/[EOQ]/... tokens that slipped in earlier, and strip
whitespace. Idempotent; a clean answer passes through unchanged.
"""
cut = len(text)
for m in _ANSWER_STOP_MARKERS:
i = text.find(m)
if i != -1:
cut = min(cut, i)
text = text[:cut]
text = _CONTROL_TOKEN_RE.sub("", text)
return text.strip()
def extract_control_strings(text: str) -> dict:
"""Parse [MS:X], [ACT:Y], and the rewrite_query span from generated text.
The rewrite_query is the text between [ACT:*] and [EOQ] (stripped). For
DIRECT the span is typically empty.
Returns dict:
ms: one of SM/PM/VM/NM or None
act: one of DIRECT/REWRITE/CLUE/RETRIEVE or None
query_text: str (may be "")
valid: bool β€” True iff both [MS:*] and [ACT:*] were found
has_eoq: bool β€” whether an [EOQ] terminator was present
"""
ms_match = _MS_RE.search(text)
act_match = _ACT_RE.search(text)
ms = ms_match.group(1) if ms_match else None
act = act_match.group(1) if act_match else None
query_text = ""
has_eoq = False
if act_match is not None:
after_act = text[act_match.end():]
eoq_pos = after_act.find(EOQ_TOKEN)
if eoq_pos != -1:
has_eoq = True
query_text = after_act[:eoq_pos].strip()
else:
query_text = after_act.strip()
return {
"ms": ms,
"act": act,
"query_text": query_text,
"valid": (ms is not None and act is not None),
"has_eoq": has_eoq,
}