Datasets:
Upload folder using huggingface_hub
Browse files- .gitattributes +3 -0
- exp2/README.md +30 -0
- exp2/code.jsonl +3 -0
- exp2/code_cut.jsonl +0 -0
- exp2/gen_data.py +292 -0
- exp2/math.jsonl +3 -0
- exp2/math_cut.jsonl +0 -0
- exp2/math_hard_val.jsonl +0 -0
- exp2/problems/code.jsonl +3 -0
- exp2/problems/math.jsonl +0 -0
- exp2/stats.json +20 -0
.gitattributes
CHANGED
|
@@ -58,3 +58,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
exp2/code.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 62 |
+
exp2/math.jsonl filter=lfs diff=lfs merge=lfs -text
|
| 63 |
+
exp2/problems/code.jsonl filter=lfs diff=lfs merge=lfs -text
|
exp2/README.md
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Experiment 2 training data (built 25 Oct 2026 with `gen_data.py`)
|
| 2 |
+
|
| 3 |
+
Same row format as experiment 1 (`$J/data/`): one JSON object per line with token ids (Qwen2.5 vocabulary) of
|
| 4 |
+
`prompt` (teacher chat template + system prompt), `response` (the teacher's own answer, greedy) and `gold` (reference
|
| 5 |
+
answer), each answer ending in `<|im_end|>`. Training takes all but the last 200 rows; the last 200 are validation.
|
| 6 |
+
|
| 7 |
+
| File | Rows | Content |
|
| 8 |
+
|---|---|---|
|
| 9 |
+
| `math.jsonl` | 14,559 | 7,241 GSM8K train rows from experiment 1 (unchanged) + 7,118 MATH train rows (new) + experiment 1's 200 GSM8K validation rows (last) |
|
| 10 |
+
| `code.jsonl` | 14,956 | 7,269 KodCode-Light-RL rows from experiment 1 (unchanged) + 7,487 KodCode-V1 rows (new) + experiment 1's 200 validation rows (last) |
|
| 11 |
+
| `math_hard_val.jsonl` | 200 | MATH problems held out as an extra validation set, never trained on |
|
| 12 |
+
| `math_cut.jsonl` / `code_cut.jsonl` | 173 / 14 | new answers that hit the length limit without ending (dropped, like experiment 1's cut rows) |
|
| 13 |
+
| `stats.json` | | the counts above |
|
| 14 |
+
| `problems/` | 7,491 / 7,501 | the chosen new problems (text), input of `generate` |
|
| 15 |
+
|
| 16 |
+
**Sources.** MATH: `EleutherAI/hendrycks_math`, original train split (7 subjects), deduplicated against MATH-500 and
|
| 17 |
+
the GSM8K test set; reference = MATH's own solution. KodCode: `KodCode/KodCode-V1`, instruct style, with a function
|
| 18 |
+
declaration and a verified solution (`gpt_pass_percentage` > 0), no `filter_reason`, `benchmark_similarity` <= 0.6, no
|
| 19 |
+
13-gram overlap with HumanEval+ / MBPP+, none of KodCode-Light-RL-10K's problems, sampled in Light-RL's subset
|
| 20 |
+
proportions (seed 0); reference = KodCode's solution in a python code block.
|
| 21 |
+
|
| 22 |
+
**Teacher answers.** Qwen2.5-Math-7B-Instruct (math) and Qwen2.5-Coder-7B-Instruct (code), vLLM 0.11, greedy,
|
| 23 |
+
repetition penalty 1.0, max 2,048 new tokens (MATH) / 1,600 (code), unfiltered for correctness (the math teacher is
|
| 24 |
+
right on 82.8% of the new MATH rows; experiment 1: 96% on GSM8K). Checks: experiment 1's prompts and references rebuild
|
| 25 |
+
token for token with this code; vLLM reproduces 39/50 of experiment 1's math answers exactly (the rest diverge
|
| 26 |
+
mid-answer from GPU arithmetic). Answers are cached per problem id in `cache/` (NAS only), so generation resumes and the
|
| 27 |
+
same answers can be reused for sequential KD.
|
| 28 |
+
|
| 29 |
+
**Rebuild.** `python gen_data.py prepare`, then `generate <math|code> <shard> <n>` on GPUs with `$J/.venv-vllm`
|
| 30 |
+
(transformers 4.57.1), then `assemble`, `upload` (hub: `pmangesh/FML_project`, dataset repo, `exp2/`).
|
exp2/code.jsonl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f2ac7283ec65ae1cfc978e5bfad33e490b8c3d62f46a448f94e812b566e3454c
|
| 3 |
+
size 56327242
|
exp2/code_cut.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
exp2/gen_data.py
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# builds the experiment 2 training data: experiment 1's rows (GSM8K train, KodCode-Light-RL) plus MATH train and more
|
| 2 |
+
# KodCode-V1 problems, with answers written once by the teachers and cached. same row format as experiment 1:
|
| 3 |
+
# token ids of prompt (teacher chat template + system prompt), response (teacher answer) and gold (reference answer)
|
| 4 |
+
#
|
| 5 |
+
# python gen_data.py prepare pick the new problems -> problems/{math,code}.jsonl (any venv)
|
| 6 |
+
# CUDA_VISIBLE_DEVICES=g $J/.venv-vllm/bin/python gen_data.py generate <math|code> <shard> <n_shards>
|
| 7 |
+
# teacher answers with vllm -> cache/<domain>_gen.<shard>.jsonl
|
| 8 |
+
# $J/.venv-vllm/bin/python gen_data.py exp1check <n> regenerate experiment 1's first n math answers (same recipe?)
|
| 9 |
+
# python gen_data.py hfgen <math|code> <n> the same for the first n problems with hf generate (cross-check)
|
| 10 |
+
# python gen_data.py compare <math|code> <n> vllm vs hf answers, and vllm vs experiment 1's stored answers
|
| 11 |
+
# python gen_data.py assemble cache -> math.jsonl, code.jsonl, math_hard_val.jsonl, *_cut.jsonl
|
| 12 |
+
# python gen_data.py upload to the experiment 2 hub dataset repo under exp2/
|
| 13 |
+
# run in $J/data_exp2 after `source $J/env.sh`. generation resumes: answered problem ids are skipped
|
| 14 |
+
|
| 15 |
+
import ast
|
| 16 |
+
import glob
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import random
|
| 20 |
+
import re
|
| 21 |
+
import sys
|
| 22 |
+
|
| 23 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 24 |
+
PROJECT = os.path.dirname(HERE)
|
| 25 |
+
EXP1 = f"{PROJECT}/data"
|
| 26 |
+
VAL_SIZE = 200 # experiment 1's validation rows: the last 200 of each file, kept as the validation rows here too
|
| 27 |
+
SEED = 0
|
| 28 |
+
|
| 29 |
+
TEACHERS = {"math": "Qwen/Qwen2.5-Math-7B-Instruct", "code": "Qwen/Qwen2.5-Coder-7B-Instruct"}
|
| 30 |
+
SYSTEM = {"math": "Please reason step by step, and put your final answer within \\boxed{}.",
|
| 31 |
+
"code": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."}
|
| 32 |
+
MAX_NEW = {"math": 2048, "code": 1600} # MATH solutions run longer than GSM8K ones; experiment 1's longest answer: 1264
|
| 33 |
+
N_NEW = {"math": None, "code": 7500} # MATH train is taken whole (~7.5k); KodCode-V1 sampled to match it
|
| 34 |
+
HUB_REPO = "pmangesh/FML_project" # experiment 2 dataset repo (private), files under exp2/
|
| 35 |
+
|
| 36 |
+
PROBLEMS, CACHE = f"{HERE}/problems", f"{HERE}/cache"
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def norm(text):
|
| 40 |
+
# for duplicate and overlap checks: lowercase, letters and digits only
|
| 41 |
+
return re.sub(r"[^a-z0-9]+", " ", text.lower()).strip()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def ngrams(text, n=13):
|
| 45 |
+
words = norm(text).split()
|
| 46 |
+
return {" ".join(words[i:i + n]) for i in range(len(words) - n + 1)}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def code_user(question, decl):
|
| 50 |
+
# experiment 1's code prompt, checked token by token against data/code.jsonl
|
| 51 |
+
return (f"Please solve the programming task below in Python. \n\n{question.strip()}\n\n"
|
| 52 |
+
f"Note that the function declaration is {decl}. Your code should be wrapped in a markdown code block.")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def tokenizer(domain):
|
| 56 |
+
from transformers import AutoTokenizer
|
| 57 |
+
return AutoTokenizer.from_pretrained(TEACHERS[domain])
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def prompt_ids(tok, domain, user):
|
| 61 |
+
# render the chat template to text, then tokenize: reproduces experiment 1's stored prompt ids exactly
|
| 62 |
+
msgs = [{"role": "system", "content": SYSTEM[domain]}, {"role": "user", "content": user}]
|
| 63 |
+
text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
|
| 64 |
+
return tok(text, add_special_tokens=False).input_ids
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def read_jsonl(path):
|
| 68 |
+
return [json.loads(line) for line in open(path)] if os.path.exists(path) else []
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# ---- prepare: choose the new problems ----
|
| 72 |
+
|
| 73 |
+
def prepare():
|
| 74 |
+
import pyarrow.parquet as pq
|
| 75 |
+
from datasets import load_dataset
|
| 76 |
+
from huggingface_hub import HfApi, HfFileSystem
|
| 77 |
+
|
| 78 |
+
os.makedirs(PROBLEMS, exist_ok=True)
|
| 79 |
+
rng = random.Random(SEED)
|
| 80 |
+
|
| 81 |
+
# MATH train (original split), minus anything in MATH-500 or the GSM8K test set
|
| 82 |
+
taken = {norm(r["problem"]) for r in load_dataset("HuggingFaceH4/MATH-500", split="test")}
|
| 83 |
+
taken |= {norm(r["question"]) for r in load_dataset("openai/gsm8k", "main", split="test")}
|
| 84 |
+
math = []
|
| 85 |
+
for cfg in ["algebra", "counting_and_probability", "geometry", "intermediate_algebra", "number_theory",
|
| 86 |
+
"prealgebra", "precalculus"]:
|
| 87 |
+
for i, r in enumerate(load_dataset("EleutherAI/hendrycks_math", cfg, split="train")):
|
| 88 |
+
if norm(r["problem"]) in taken:
|
| 89 |
+
continue
|
| 90 |
+
taken.add(norm(r["problem"]))
|
| 91 |
+
math.append({"id": f"math_{cfg}_{i}", "user": r["problem"], "gold": r["solution"],
|
| 92 |
+
"level": r["level"], "type": r["type"]})
|
| 93 |
+
rng.shuffle(math)
|
| 94 |
+
print(f"math: {len(math)} MATH train problems kept")
|
| 95 |
+
|
| 96 |
+
# KodCode-V1: same style as Light-RL (instruct, with a function declaration and a verified solution), the same mix of
|
| 97 |
+
# sources (subset proportions), none of Light-RL's 10k problems, nothing close to HumanEval / MBPP
|
| 98 |
+
light = load_dataset("KodCode/KodCode-Light-RL-10K", split="train")
|
| 99 |
+
light_ids, light_q = set(light["question_id"]), {norm(q) for q in light["question"]}
|
| 100 |
+
share = {s: light["subset"].count(s) / len(light) for s in set(light["subset"])}
|
| 101 |
+
from evalplus.data import get_human_eval_plus, get_mbpp_plus
|
| 102 |
+
bench = set()
|
| 103 |
+
for p in list(get_human_eval_plus().values()) + list(get_mbpp_plus().values()):
|
| 104 |
+
bench |= ngrams(p["prompt"])
|
| 105 |
+
cols = ["style", "subset", "question_id", "question", "solution", "test_info", "gpt_pass_percentage",
|
| 106 |
+
"benchmark_similarity", "filter_reason"]
|
| 107 |
+
fs = HfFileSystem()
|
| 108 |
+
pool = {}
|
| 109 |
+
for f in sorted(HfApi().list_repo_tree("KodCode/KodCode-V1", repo_type="dataset", path_in_repo="data"),
|
| 110 |
+
key=lambda f: f.path):
|
| 111 |
+
with fs.open(f"datasets/KodCode/KodCode-V1/{f.path}") as fh:
|
| 112 |
+
for r in pq.read_table(fh, columns=cols).to_pylist():
|
| 113 |
+
info = ast.literal_eval(r["test_info"]) if isinstance(r["test_info"], str) else r["test_info"]
|
| 114 |
+
if (r["style"] != "instruct" or r["subset"] not in share or r["question_id"] in light_ids
|
| 115 |
+
or norm(r["question"]) in light_q or not info or not info[0].get("function_declaration")
|
| 116 |
+
or not r["solution"] or float(r["gpt_pass_percentage"] or 0) <= 0 or r["filter_reason"]
|
| 117 |
+
or (r["benchmark_similarity"] is not None and float(r["benchmark_similarity"]) > 0.6)
|
| 118 |
+
or ngrams(r["question"]) & bench):
|
| 119 |
+
continue
|
| 120 |
+
pool.setdefault(r["subset"], []).append(
|
| 121 |
+
{"id": f"kodcode_{r['question_id']}", "user": code_user(r["question"], info[0]["function_declaration"]),
|
| 122 |
+
"gold": f"```python\n{r['solution'].strip()}\n```", "subset": r["subset"], "qnorm": norm(r["question"])})
|
| 123 |
+
print(f" {f.path}: pool {sum(len(v) for v in pool.values())}")
|
| 124 |
+
code, seen = [], set()
|
| 125 |
+
for s, frac in sorted(share.items()):
|
| 126 |
+
cands = pool.get(s, [])
|
| 127 |
+
rng.shuffle(cands)
|
| 128 |
+
want = round(frac * N_NEW["code"])
|
| 129 |
+
for c in cands:
|
| 130 |
+
if len([x for x in code if x["subset"] == s]) >= want:
|
| 131 |
+
break
|
| 132 |
+
if c["qnorm"] not in seen:
|
| 133 |
+
seen.add(c["qnorm"])
|
| 134 |
+
code.append({k: v for k, v in c.items() if k != "qnorm"})
|
| 135 |
+
rng.shuffle(code)
|
| 136 |
+
print(f"code: {len(code)} KodCode-V1 problems, by subset {({s: sum(c['subset'] == s for c in code) for s in share})}")
|
| 137 |
+
|
| 138 |
+
for domain, rows in (("math", math), ("code", code)):
|
| 139 |
+
with open(f"{PROBLEMS}/{domain}.jsonl", "w") as f:
|
| 140 |
+
for r in rows:
|
| 141 |
+
f.write(json.dumps(r) + "\n")
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
# ---- generate: teacher answers, cached per problem id ----
|
| 145 |
+
|
| 146 |
+
def generate(domain, shard, n_shards):
|
| 147 |
+
from vllm import LLM, SamplingParams
|
| 148 |
+
|
| 149 |
+
os.makedirs(CACHE, exist_ok=True)
|
| 150 |
+
out = f"{CACHE}/{domain}_gen.{shard}.jsonl"
|
| 151 |
+
done = {r["id"] for path in glob.glob(f"{CACHE}/{domain}_gen.*.jsonl") for r in read_jsonl(path)}
|
| 152 |
+
todo = [r for i, r in enumerate(read_jsonl(f"{PROBLEMS}/{domain}.jsonl")) if i % n_shards == shard and r["id"] not in done]
|
| 153 |
+
print(f"{domain} shard {shard}/{n_shards}: {len(todo)} to answer, {len(done)} already cached")
|
| 154 |
+
if not todo:
|
| 155 |
+
return
|
| 156 |
+
tok = tokenizer(domain)
|
| 157 |
+
llm = LLM(TEACHERS[domain], dtype="bfloat16", max_model_len=4096, gpu_memory_utilization=0.85, seed=SEED)
|
| 158 |
+
# greedy, like experiment 1's answers (checked by `compare`), repetition penalty off like the benchmarks
|
| 159 |
+
params = SamplingParams(temperature=0, max_tokens=MAX_NEW[domain], repetition_penalty=1.0)
|
| 160 |
+
for start in range(0, len(todo), 256):
|
| 161 |
+
chunk = todo[start:start + 256]
|
| 162 |
+
prompts = [{"prompt_token_ids": prompt_ids(tok, domain, r["user"])} for r in chunk]
|
| 163 |
+
results = llm.generate(prompts, params)
|
| 164 |
+
with open(out, "a") as f:
|
| 165 |
+
for r, res in zip(chunk, results):
|
| 166 |
+
o = res.outputs[0]
|
| 167 |
+
ids = list(o.token_ids)
|
| 168 |
+
f.write(json.dumps({"id": r["id"], "response": ids, "finish": o.finish_reason}) + "\n")
|
| 169 |
+
f.flush()
|
| 170 |
+
print(f" {domain} shard {shard}: {start + len(chunk)}/{len(todo)}")
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def exp1check(n):
|
| 174 |
+
# regenerates experiment 1's first n stored math answers with vllm: if they match, experiment 1's answers were greedy
|
| 175 |
+
# with these settings and the new answers are made the same way
|
| 176 |
+
from vllm import LLM, SamplingParams
|
| 177 |
+
|
| 178 |
+
rows = read_jsonl(f"{EXP1}/math.jsonl")[:n]
|
| 179 |
+
llm = LLM(TEACHERS["math"], dtype="bfloat16", max_model_len=4096, gpu_memory_utilization=0.85, seed=SEED)
|
| 180 |
+
res = llm.generate([{"prompt_token_ids": r["prompt"]} for r in rows],
|
| 181 |
+
SamplingParams(temperature=0, max_tokens=MAX_NEW["math"], repetition_penalty=1.0))
|
| 182 |
+
same = sum(list(o.outputs[0].token_ids) == r["response"] for o, r in zip(res, rows))
|
| 183 |
+
print(f"experiment 1 math answers reproduced token for token: {same}/{len(rows)}")
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def hfgen(domain, n):
|
| 187 |
+
# reference answers with hf generate (what experiment 1's benchmarks use) for the vllm cross-check
|
| 188 |
+
import torch
|
| 189 |
+
from transformers import AutoModelForCausalLM
|
| 190 |
+
|
| 191 |
+
tok = tokenizer(domain)
|
| 192 |
+
model = AutoModelForCausalLM.from_pretrained(TEACHERS[domain], dtype=torch.bfloat16).to("cuda:0").eval()
|
| 193 |
+
rows = read_jsonl(f"{PROBLEMS}/{domain}.jsonl")[:n]
|
| 194 |
+
out = []
|
| 195 |
+
for r in rows:
|
| 196 |
+
ids = torch.tensor([prompt_ids(tok, domain, r["user"])], device="cuda:0")
|
| 197 |
+
with torch.no_grad():
|
| 198 |
+
g = model.generate(ids, max_new_tokens=MAX_NEW[domain], do_sample=False, repetition_penalty=1.0)
|
| 199 |
+
out.append({"id": r["id"], "response": g[0, ids.shape[1]:].tolist()})
|
| 200 |
+
with open(f"{CACHE}/{domain}_hf_check.jsonl", "w") as f:
|
| 201 |
+
for r in out:
|
| 202 |
+
f.write(json.dumps(r) + "\n")
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def compare(domain, n):
|
| 206 |
+
# how often vllm and hf greedy answers agree, token for token and on the final answer text
|
| 207 |
+
tok = tokenizer(domain)
|
| 208 |
+
vllm = {r["id"]: r["response"] for p in glob.glob(f"{CACHE}/{domain}_gen.*.jsonl") for r in read_jsonl(p)}
|
| 209 |
+
hf = read_jsonl(f"{CACHE}/{domain}_hf_check.jsonl")[:n]
|
| 210 |
+
same, prefix = 0, []
|
| 211 |
+
for r in hf:
|
| 212 |
+
v = vllm.get(r["id"])
|
| 213 |
+
if v is None:
|
| 214 |
+
continue
|
| 215 |
+
h = [t for t in r["response"] if t != tok.pad_token_id]
|
| 216 |
+
same += v == h
|
| 217 |
+
k = next((i for i, (a, b) in enumerate(zip(v, h)) if a != b), min(len(v), len(h)))
|
| 218 |
+
prefix.append(k / max(len(h), 1))
|
| 219 |
+
print(f"{domain}: identical answers {same}/{len(prefix)}, mean shared prefix {100 * sum(prefix) / max(len(prefix), 1):.0f}%")
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
# ---- assemble: experiment 1 rows + new rows -> the experiment 2 files ----
|
| 223 |
+
|
| 224 |
+
def assemble():
|
| 225 |
+
stats = {}
|
| 226 |
+
for domain in ("math", "code"):
|
| 227 |
+
tok = tokenizer(domain)
|
| 228 |
+
end = tok.convert_tokens_to_ids("<|im_end|>")
|
| 229 |
+
old = read_jsonl(f"{EXP1}/{domain}.jsonl")
|
| 230 |
+
old_train, old_val = old[:-VAL_SIZE], old[-VAL_SIZE:]
|
| 231 |
+
answers = {r["id"]: r for p in glob.glob(f"{CACHE}/{domain}_gen.*.jsonl") for r in read_jsonl(p)}
|
| 232 |
+
new, cut, missing = [], [], 0
|
| 233 |
+
for r in read_jsonl(f"{PROBLEMS}/{domain}.jsonl"):
|
| 234 |
+
a = answers.get(r["id"])
|
| 235 |
+
if a is None:
|
| 236 |
+
missing += 1
|
| 237 |
+
continue
|
| 238 |
+
row = {"prompt": prompt_ids(tok, domain, r["user"]), "response": a["response"],
|
| 239 |
+
"gold": tok(r["gold"] + "<|im_end|>", add_special_tokens=False).input_ids}
|
| 240 |
+
# an answer that never ends within the token limit is the degenerate kind experiment 1 also cut
|
| 241 |
+
if a["finish"] != "stop" or row["response"][-1:] != [end]:
|
| 242 |
+
cut.append(row)
|
| 243 |
+
else:
|
| 244 |
+
new.append(row)
|
| 245 |
+
hard_val = []
|
| 246 |
+
if domain == "math":
|
| 247 |
+
# 200 MATH problems as an extra validation set, never trained on
|
| 248 |
+
hard_val, new = new[:VAL_SIZE], new[VAL_SIZE:]
|
| 249 |
+
with open(f"{HERE}/math_hard_val.jsonl", "w") as f:
|
| 250 |
+
for row in hard_val:
|
| 251 |
+
f.write(json.dumps(row) + "\n")
|
| 252 |
+
# experiment 1 train rows, new rows, then experiment 1's validation rows last (joint.py takes the last 200)
|
| 253 |
+
with open(f"{HERE}/{domain}.jsonl", "w") as f:
|
| 254 |
+
for row in old_train + new + old_val:
|
| 255 |
+
f.write(json.dumps(row) + "\n")
|
| 256 |
+
with open(f"{HERE}/{domain}_cut.jsonl", "w") as f:
|
| 257 |
+
for row in cut:
|
| 258 |
+
f.write(json.dumps(row) + "\n")
|
| 259 |
+
lens = sorted(len(r["response"]) for r in new)
|
| 260 |
+
stats[domain] = {"experiment_1_train": len(old_train), "new_train": len(new), "validation": len(old_val),
|
| 261 |
+
"hard_validation": len(hard_val), "cut": len(cut), "missing": missing,
|
| 262 |
+
"new_answer_tokens_median": lens[len(lens) // 2] if lens else None}
|
| 263 |
+
print(domain, stats[domain])
|
| 264 |
+
json.dump(stats, open(f"{HERE}/stats.json", "w"), indent=1)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def upload():
|
| 268 |
+
from huggingface_hub import create_repo, upload_folder
|
| 269 |
+
|
| 270 |
+
create_repo(HUB_REPO, repo_type="dataset", private=True, exist_ok=True)
|
| 271 |
+
upload_folder(repo_id=HUB_REPO, repo_type="dataset", folder_path=HERE, path_in_repo="exp2",
|
| 272 |
+
allow_patterns=["*.jsonl", "*.json", "*.md", "gen_data.py", "problems/*"], ignore_patterns=["cache/*"])
|
| 273 |
+
print("uploaded to", HUB_REPO, "exp2/")
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
if __name__ == "__main__":
|
| 277 |
+
a = sys.argv[1:]
|
| 278 |
+
if a == ["prepare"]:
|
| 279 |
+
prepare()
|
| 280 |
+
elif len(a) == 4 and a[0] == "generate":
|
| 281 |
+
generate(a[1], int(a[2]), int(a[3]))
|
| 282 |
+
elif len(a) == 2 and a[0] == "exp1check":
|
| 283 |
+
exp1check(int(a[1]))
|
| 284 |
+
elif len(a) == 3 and a[0] in ("hfgen", "compare"):
|
| 285 |
+
(hfgen if a[0] == "hfgen" else compare)(a[1], int(a[2]))
|
| 286 |
+
elif a == ["assemble"]:
|
| 287 |
+
assemble()
|
| 288 |
+
elif a == ["upload"]:
|
| 289 |
+
upload()
|
| 290 |
+
else:
|
| 291 |
+
sys.exit("usage: gen_data.py prepare | generate <math|code> <shard> <n_shards> | exp1check <n> "
|
| 292 |
+
"| hfgen|compare <math|code> <n> | assemble | upload")
|
exp2/math.jsonl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e9b894eda7d28486852f6c6571106027ce0111139b196105ec522a538abb312d
|
| 3 |
+
size 53742134
|
exp2/math_cut.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
exp2/math_hard_val.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
exp2/problems/code.jsonl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1ab808029a86fbf36076077814cce4efe2747329b9ef22e3720b510de69223e5
|
| 3 |
+
size 15701217
|
exp2/problems/math.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
exp2/stats.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"math": {
|
| 3 |
+
"experiment_1_train": 7241,
|
| 4 |
+
"new_train": 7118,
|
| 5 |
+
"validation": 200,
|
| 6 |
+
"hard_validation": 200,
|
| 7 |
+
"cut": 173,
|
| 8 |
+
"missing": 0,
|
| 9 |
+
"new_answer_tokens_median": 496
|
| 10 |
+
},
|
| 11 |
+
"code": {
|
| 12 |
+
"experiment_1_train": 7269,
|
| 13 |
+
"new_train": 7487,
|
| 14 |
+
"validation": 200,
|
| 15 |
+
"hard_validation": 0,
|
| 16 |
+
"cut": 14,
|
| 17 |
+
"missing": 0,
|
| 18 |
+
"new_answer_tokens_median": 231
|
| 19 |
+
}
|
| 20 |
+
}
|