"""Technical audit of a rendered SFT set before training (what the model will actually be trained on).
Per component (sample of rows):
mask targets = assistant turns only: every target span ends with <|im_end|>, contains no role header, no tool output
no_target rows with zero target tokens (useless)
calls tool-call JSON in targets parses, has name + object arguments
repeat identical tool call twice in one conversation (teaches loops)
abstain tool list present but no call (teaches when NOT to call)
lang PL / EN share of target text
Global: exact duplicate rows, length distribution, padding efficiency of train.py's microbatch plan.
python audit_sft.py data/i1 ckpt/tokenizer.json [--per-comp 200]
"""
import argparse
import hashlib
import json
import random
import re
import sys
from collections import Counter, defaultdict
import numpy as np
import pyarrow.parquet as pq
from tokenizers import Tokenizer
CALL = re.compile(r"\s*(.*?)\s*", re.S)
PL = re.compile(r"[ąćęłńśźż]", re.I)
def spans(ids, m):
out, cur = [], []
for x, y in zip(ids, m):
if y:
cur.append(x)
elif cur:
out.append(cur)
cur = []
if cur:
out.append(cur)
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("data")
ap.add_argument("tokenizer")
ap.add_argument("--per-comp", type=int, default=200)
a = ap.parse_args()
tok = Tokenizer.from_file(a.tokenizer)
t = pq.read_table(f"{a.data}/train.parquet", columns=["id", "input_ids", "loss_mask", "n_tokens", "comp", "is_tool", "n_target"])
comp = t.column("comp").to_pylist()
n_tok = np.array(t.column("n_tokens").to_pylist())
n_tgt = np.array(t.column("n_target").to_pylist())
by = defaultdict(list)
for i, c in enumerate(comp):
by[c.split("+")[0]].append(i)
rnd = random.Random(0)
rep = {}
ids_col, m_col = t.column("input_ids"), t.column("loss_mask")
for c, idx in sorted(by.items(), key=lambda x: -len(x[1])):
smp = rnd.sample(idx, min(a.per_comp, len(idx)))
st = Counter()
for i in smp:
ids = np.frombuffer(ids_col[i].as_py(), dtype=np.uint16).tolist()
m = np.frombuffer(m_col[i].as_py(), dtype=np.uint8).tolist()
sp = [tok.decode(s, skip_special_tokens=False) for s in spans(ids, m)]
full = tok.decode(ids, skip_special_tokens=False)
st["rows"] += 1
if not sp:
st["no_target"] += 1
continue
if not all(s.endswith("<|im_end|>") and "<|im_start|>" not in s and "" not in s for s in sp):
st["mask_bad"] += 1
if len(sp) > full.count("<|im_start|>assistant\n"):
st["mask_bad_count"] += 1
calls = [c_ for s in sp for c_ in CALL.findall(s)]
keys = []
for c_ in calls:
st["calls"] += 1
try:
o = json.loads(c_)
assert isinstance(o, dict) and "name" in o and isinstance(o.get("arguments", {}), dict)
keys.append(json.dumps(o, sort_keys=True))
except Exception:
st["call_bad_json"] += 1
if len(keys) != len(set(keys)):
st["repeat_call_rows"] += 1
has_tools = "" in full
st["tools_offered"] += has_tools
st["abstain"] += has_tools and not calls
txt = " ".join(sp)
st["pl"] += bool(PL.search(txt))
if re.search(r"(?![\s\S]*)", txt):
st["unclosed_call"] += 1
tg = int(n_tgt[idx].sum())
rep[c] = {"rows": len(idx), "target_M": round(tg / 1e6, 2), "sample": dict(st)}
tot = int(n_tgt.sum())
for c in rep:
rep[c]["target_share_%"] = round(100 * rep[c]["target_M"] * 1e6 / tot, 2)
# duplicates (exact rows; intended repeats carry '#r' ids)
ids_list = t.column("id").to_pylist()
h = Counter(hashlib.sha1(ids_col[i].as_py()).hexdigest() for i in range(len(ids_list)) if "#r" not in ids_list[i])
dup = sum(v - 1 for v in h.values() if v > 1)
# padding efficiency of the train.py plan
sys.path.insert(0, ".")
from train import microbatches
ex = [{"n": int(n), "tool": bool(x)} for n, x in zip(n_tok, t.column("is_tool").to_pylist())]
mbs = microbatches(ex, 8192, "slayer1b-sft-1", 0, 1)
padded = sum(max(ex[i]["n"] for i in b) * len(b) for b in mbs)
out = {"rows": len(ids_list), "tokens_M": round(n_tok.sum() / 1e6, 1), "target_M": round(tot / 1e6, 1),
"target_fraction": round(tot / n_tok.sum(), 3), "len_p50_p90_p99_max": [int(np.percentile(n_tok, q)) for q in (50, 90, 99)] + [int(n_tok.max())],
"exact_duplicates_unintended": dup, "padding_efficiency": round(n_tok.sum() / padded, 4), "microbatches": len(mbs), "components": rep}
print(json.dumps(out, ensure_ascii=False, indent=1))
if __name__ == "__main__":
main()