Download code/pocket_math/sft_data.py from Palaestra/pocket-math-ops: direct link, hf CLI and curl.
- Browser
- Download file 2.66 kB
-
https://huggingface.co/datasets/Palaestra/pocket-math-ops/resolve/main/code/pocket_math/sft_data.py
- Command line
-
hf download hf://datasets/Palaestra/pocket-math-ops/code/pocket_math/sft_data.py
-
curl -L -o sft_data.py https://huggingface.co/datasets/Palaestra/pocket-math-ops/resolve/main/code/pocket_math/sft_data.py
2.66 kB
| """SFT examples (warm-up, Python-tool and usability traces) turned into token rows. | |
| Accepted rows: {"messages": [..., {"role": "assistant", "content": ...}]} or | |
| {"problem": ..., "response": ...}. Tool output blocks (```output ... ```) inside a response | |
| get loss_mask 0: the model never wrote them, so it must not learn to predict them. | |
| """ | |
| from __future__ import annotations | |
| import os | |
| import re | |
| from pathlib import Path | |
| from typing import Any | |
| from .io import read_jsonl | |
| OUTPUT_BLOCK = re.compile(r"```output\n.*?```\n?", re.S) | |
| def _source_rows(source: str) -> list[dict[str, Any]]: | |
| if Path(source).exists(): | |
| return list(read_jsonl(source)) | |
| from huggingface_hub import hf_hub_download | |
| repo, _, path = source.partition(":") | |
| return list(read_jsonl(hf_hub_download(repo, path, repo_type="dataset", token=os.environ.get("HF_TOKEN") or None))) | |
| def response_mask(tokenizer, response: str) -> tuple[list[int], list[int]]: | |
| enc = tokenizer(response, add_special_tokens=False, return_offsets_mapping=True) | |
| spans = [(m.start(), m.end()) for m in OUTPUT_BLOCK.finditer(response)] | |
| mask = [0 if any(a <= start < b for a, b in spans) else 1 for start, _ in enc["offset_mapping"]] | |
| return list(enc["input_ids"]), mask | |
| def sft_rows(ctx, source: str, tokenizer, prof: dict[str, Any], max_len: int) -> list[dict[str, Any]]: | |
| end_id = tokenizer.convert_tokens_to_ids("<|im_end|>") | |
| if end_id is None or end_id == tokenizer.unk_token_id: | |
| end_id = tokenizer.eos_token_id | |
| rows, dropped = [], 0 | |
| for r in _source_rows(source): | |
| if "messages" in r: | |
| messages, response = r["messages"][:-1], r["messages"][-1]["content"] | |
| else: | |
| user = prof["user_template"].format(problem=r["problem"]) | |
| messages, response = [{"role": "user", "content": user}], r["response"] | |
| if prof.get("system") and messages[0]["role"] != "system": | |
| messages = [{"role": "system", "content": prof["system"]}, *messages] | |
| text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) | |
| prompt = tokenizer(text, add_special_tokens=False).input_ids | |
| ids, mask = response_mask(tokenizer, response) | |
| ids, mask = ids + [end_id], mask + [1] | |
| if len(prompt) + len(ids) > max_len: | |
| dropped += 1 | |
| continue | |
| rows.append({"prompt_ids": prompt, "response_ids": ids, "loss_mask": mask if 0 in mask else None}) | |
| if ctx is not None: | |
| ctx.log(f"SFT rows: {len(rows)} kept, {dropped} longer than {max_len} tokens dropped") | |
| return rows | |