Download train.py from datavorous/ohev: direct link, hf CLI and curl.
- Browser
- Download file 6.29 kB
-
https://huggingface.co/datavorous/ohev/resolve/main/train.py
- Command line
-
hf download hf://datavorous/ohev/train.py
-
curl -L -o train.py https://huggingface.co/datavorous/ohev/resolve/main/train.py
6.29 kB
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import math | |
| import os | |
| from collections import Counter | |
| from pathlib import Path | |
| from schema import BASE_MODEL, BASE_REVISION, LABELS, QUESTION | |
| SEED = 3407 | |
| os.environ.setdefault("UNSLOTH_COMPILE_LOCATION", str(Path.home() / ".cache/unsloth/ohev")) | |
| def read_rows(path: Path) -> list[dict]: | |
| rows = [] | |
| for line_number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): | |
| if not line.strip(): | |
| continue | |
| row = json.loads(line) | |
| if (not isinstance(row, dict) or set(row) != {"state", "questions", "gold"} | |
| or row["questions"] != QUESTION or not isinstance(row["gold"], dict) | |
| or set(row["gold"]) != {"interest"} or row["gold"]["interest"] not in LABELS | |
| or not isinstance(row["state"], str) | |
| or not row["state"].startswith("Context: A is an adult man and B is an adult woman") | |
| or row["state"].count("\n\nA: ") != 1 or row["state"].count("\n\nB: ") != 1): | |
| raise ValueError(f"invalid decision row at {path}:{line_number}") | |
| rows.append(row) | |
| if not rows or len({row["state"] for row in rows}) != len(rows): | |
| raise ValueError(f"empty or duplicate-state dataset: {path}") | |
| return rows | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--train", type=Path, required=True, help="reviewed training JSONL") | |
| parser.add_argument("--validation", type=Path, help="optional separate validation JSONL") | |
| parser.add_argument("--output-dir", type=Path) | |
| parser.add_argument("--epochs", type=int, default=10) | |
| parser.add_argument("--seed", type=int, default=SEED) | |
| parser.add_argument("--check-data", action="store_true", help="validate files without loading Unsloth") | |
| args = parser.parse_args() | |
| if args.epochs < 1: | |
| parser.error("--epochs must be positive") | |
| train_path = args.train.resolve() | |
| validation_path = args.validation.resolve() if args.validation else None | |
| if validation_path == train_path: | |
| parser.error("training and validation must be separate files") | |
| train_rows = read_rows(train_path) | |
| validation_rows = read_rows(validation_path) if validation_path else [] | |
| if {row["state"] for row in train_rows} & {row["state"] for row in validation_rows}: | |
| raise ValueError("training and validation contain the same state") | |
| evaluation_path = Path(__file__).resolve().parent / "evaluation.jsonl" | |
| evaluation_states = {json.loads(line)["state"] for line in evaluation_path.read_text(encoding="utf-8").splitlines()} | |
| if evaluation_states & {row["state"] for row in (*train_rows, *validation_rows)}: | |
| raise ValueError("training or validation contains a held-out evaluation case") | |
| manifest = { | |
| "base_model": BASE_MODEL, "base_revision": BASE_REVISION, | |
| "train_sha256": hashlib.sha256(train_path.read_bytes()).hexdigest(), | |
| "train_rows": len(train_rows), "train_labels": dict(Counter(r["gold"]["interest"] for r in train_rows)), | |
| "validation_sha256": hashlib.sha256(validation_path.read_bytes()).hexdigest() if validation_path else None, | |
| "validation_rows": len(validation_rows), "epochs": args.epochs, | |
| "seed": args.seed, "question": QUESTION, | |
| } | |
| print(json.dumps(manifest, indent=2), flush=True) | |
| if args.check_data: | |
| return | |
| if args.output_dir is None: | |
| parser.error("--output-dir is required for training") | |
| output = args.output_dir.resolve() | |
| if (output / "final_adapter").exists(): | |
| raise ValueError(f"adapter already exists at {output}") | |
| output.mkdir(parents=True, exist_ok=True) | |
| manifest_path = output / "run_manifest.json" | |
| if manifest_path.exists() and json.loads(manifest_path.read_text(encoding="utf-8")) != manifest: | |
| raise ValueError("output directory belongs to another run") | |
| manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8") | |
| from datasets import Dataset | |
| from transformers import TrainingArguments | |
| from unsloth import DecisionTrainer, FastDecisionModel, is_bfloat16_supported | |
| model, tokenizer = FastDecisionModel.from_pretrained( | |
| model_name=BASE_MODEL, revision=BASE_REVISION, max_seq_length=2048, load_in_4bit=True) | |
| model = FastDecisionModel.get_peft_model( | |
| model, r=16, lora_alpha=16, lora_dropout=0, | |
| use_gradient_checkpointing="unsloth", random_state=args.seed) | |
| def build(rows: list[dict], name: str): | |
| items, report = FastDecisionModel.build_dataset(Dataset.from_list(rows), tokenizer, model) | |
| if report["skipped"] or report["total"] != len(rows): | |
| raise ValueError(f"Unsloth skipped {name} rows: {report}") | |
| return items | |
| train_items = build(train_rows, "training") | |
| validation_items = build(validation_rows, "validation") if validation_rows else None | |
| steps = math.ceil(len(train_rows) / 8) * args.epochs | |
| trainer = DecisionTrainer( | |
| model=model, processing_class=tokenizer, | |
| train_dataset=train_items, eval_dataset=validation_items, | |
| args=TrainingArguments( | |
| output_dir=str(output), per_device_train_batch_size=2, | |
| gradient_accumulation_steps=4, warmup_steps=max(1, round(steps * .05)), | |
| max_steps=steps, learning_rate=2e-4, lr_scheduler_type="cosine", | |
| weight_decay=.01, bf16=is_bfloat16_supported(), fp16=not is_bfloat16_supported(), | |
| eval_strategy="epoch" if validation_items is not None else "no", | |
| save_strategy="epoch", save_total_limit=2, | |
| logging_steps=5, report_to="none", seed=args.seed, | |
| ), | |
| ) | |
| stats = trainer.train() | |
| metrics = {"train_loss": stats.training_loss, "steps": stats.global_step} | |
| if validation_items is not None: | |
| metrics["validation"] = FastDecisionModel.evaluate(model, tokenizer, validation_items) | |
| (output / "training_metrics.json").write_text(json.dumps(metrics, indent=2) + "\n", encoding="utf-8") | |
| model.save_pretrained(str(output / "final_adapter")) | |
| tokenizer.save_pretrained(str(output / "final_adapter")) | |
| print(f"Saved adapter to {output / 'final_adapter'}", flush=True) | |
| if __name__ == "__main__": | |
| main() | |