LingweiGu's picture
Publish audited v17 Astra rollouts, verified rotation and training handoff
3bd542a verified
Raw History Blame Contribute Delete
6.05 kB
"""Loss-preserving MiniCPM preprocessing using its pinned native chat template.
Records are data, never executable instructions. Nothing here invokes a tool.
"""
import copy
import hashlib
import json
import re
IGNORE = -100
def normalize_record(record):
messages = copy.deepcopy(record["messages"])
if not isinstance(messages, list) or not messages:
raise ValueError("messages must be a nonempty list")
for message in messages:
if message.get("role") not in {"system", "user", "assistant", "tool"}:
raise ValueError(f"Unsupported role {message.get('role')}")
if "loss" in message and not isinstance(message["loss"], bool):
raise ValueError("loss must be boolean when present")
content = message.get("content")
if content is None:
message["content"] = ""
elif not isinstance(content, str) and message["role"] != "tool":
raise ValueError("Non-text message needs explicit conversion; refusing silent dropping")
for call in message.get("tool_calls") or []:
function = call.get("function", call)
arguments = function.get("arguments")
if isinstance(arguments, str):
function["arguments"] = json.loads(arguments)
if function.get("arguments") is not None and not isinstance(function["arguments"], dict):
raise ValueError("Tool arguments must be an object")
# The native template's loop-local content assembly cannot preserve
# interleaved placeholders reliably. Fail rather than lose prose.
if "<tool_sep>" in message.get("content", ""):
raise ValueError("Interleaved <tool_sep> needs audited normalization")
tools = copy.deepcopy(record.get("tools"))
if isinstance(tools, str):
tools = json.loads(tools)
if tools is not None and not isinstance(tools, list):
raise ValueError("tools must be a list")
return messages, tools
def training_template(native):
"""Add HF generation spans without changing any rendered byte."""
begin = '{%- elif message.role == "assistant" %}'
end = '{%- elif message.role == "tool" %}'
if native.count(begin) != 1 or native.count(end) != 1:
raise ValueError("Pinned template changed; review before preprocessing")
before, rest = native.split(begin)
body, after = rest.split(end)
guarded = ("{%- if message.get('loss', true) %}{%- generation %}" + body +
"{%- endgeneration %}{%- else %}" + body + "{%- endif %}")
return before + begin + guarded + end + after
def group_key(messages):
prompt = next((m["content"] for m in messages if m["role"] == "user"), None)
if not isinstance(prompt, str) or not prompt.strip():
raise ValueError("Missing initial user request")
normalized = re.sub(r"\s+", " ", prompt).strip()
return hashlib.sha256(normalized.encode()).hexdigest()
def encode_record(record, tokenizer, template):
messages, tools = normalize_record(record)
key = group_key(messages)
encoded = tokenizer.apply_chat_template(
messages, tools=tools, chat_template=template,
tokenize=True, add_generation_prompt=False, return_dict=True,
return_assistant_tokens_mask=True,
)
ids = encoded["input_ids"]
mask = encoded["assistant_masks"]
labels = [token if supervise else IGNORE for token, supervise in zip(ids, mask)]
# Generation spans include the assistant role header. It belongs to the
# prompt; model outputs begin after it. Mask it at each span boundary.
header = tokenizer.encode("<|im_start|>assistant\n", add_special_tokens=False)
for index, value in enumerate(mask):
if value and (index == 0 or not mask[index - 1]):
if ids[index:index + len(header)] != header:
raise ValueError("Assistant span does not begin with the expected role header")
labels[index:index + len(header)] = [IGNORE] * len(header)
if len(ids) != len(labels):
raise AssertionError("Token/mask length mismatch")
return {"input_ids": ids, "labels": labels}, key
def split_windows(encoded, maximum=131072, overlap=16384):
"""Keep all eligible target tokens exactly once, including overflow tails."""
if maximum <= overlap or overlap < 1:
raise ValueError("Require 0 < overlap < maximum")
n = len(encoded["input_ids"])
start = 0
supervised_until = 0
while start < n:
end = min(start + maximum, n)
ids = encoded["input_ids"][start:end]
labels = encoded["labels"][start:end].copy()
for index in range(min(len(labels), max(0, supervised_until - start))):
labels[index] = IGNORE
# A causal sequence cannot predict its first token. The first token of
# later windows is always in the masked overlap.
if labels and labels[0] != IGNORE:
raise ValueError("Unpredictable first-token target")
if any(value != IGNORE for value in labels):
yield {"input_ids": ids, "labels": labels}
supervised_until = end
if end == n:
break
start = end - overlap
def pack_items(items, target=32768):
"""Pack adjacent samples with independent attention/position boundaries."""
pack = {key: [] for key in ["input_ids", "labels", "attention_mask", "position_ids"]}
segment = 0
for item in items:
length = len(item["input_ids"])
if pack["input_ids"] and len(pack["input_ids"]) + length > target:
yield pack
pack = {key: [] for key in pack}
segment = 0
segment += 1
pack["input_ids"].extend(item["input_ids"])
pack["labels"].extend(item["labels"])
pack["attention_mask"].extend([segment] * length)
pack["position_ids"].extend(range(length))
if len(pack["input_ids"]) >= target:
yield pack
pack = {key: [] for key in pack}
segment = 0
if pack["input_ids"]:
yield pack