File size: 5,892 Bytes
bc3f388
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
"""Fine-tune ByT5-Sanskrit for segmentation (DECISIONS.md D01, D02, D03).

Input format follows the authors' released inference code exactly: the literal
task prefix "S " prepended to the sandhied IAST sentence, max_length 512.

A leakage audit runs as a GATE before training starts: if the pool is dirty the
run aborts rather than producing a number nobody can trust.

Usage:
  python -I src/splitter/train.py --config configs/train_1pct.yaml --seed 13
"""
from __future__ import annotations

import argparse
import json
import os
import subprocess
import sys

sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

import numpy as np  # noqa: E402
import torch  # noqa: E402
import yaml  # noqa: E402
from torch.utils.data import Dataset  # noqa: E402
from transformers import (  # noqa: E402
    AutoTokenizer,
    DataCollatorForSeq2Seq,
    Seq2SeqTrainer,
    Seq2SeqTrainingArguments,
    T5ForConditionalGeneration,
    set_seed,
)

PREFIX = "S "          # the authors' segmentation task prefix


class SegDataset(Dataset):
    def __init__(self, path, tok, max_len, limit=None):
        self.rows = []
        with open(path, encoding="utf-8") as fh:
            for line in fh:
                self.rows.append(json.loads(line))
                if limit and len(self.rows) >= limit:
                    break
        self.tok = tok
        self.max_len = max_len

    def __len__(self):
        return len(self.rows)

    def __getitem__(self, i):
        r = self.rows[i]
        x = self.tok(PREFIX + r["sanskrit_raw"], truncation=True,
                     max_length=self.max_len)
        y = self.tok(text_target=r["sanskrit_gold"], truncation=True,
                     max_length=self.max_len)
        x["labels"] = y["input_ids"]
        return x


def make_contiguous(model) -> int:
    """Pack every parameter so safetensors can save it.

    ByT5 checkpoints load with non-contiguous attention weights
    (`encoder.block.*.SelfAttention.q.weight`); safetensors refuses to
    serialise those and the run dies AFTER training, at the first save. Packing
    once up front costs nothing and removes the failure for every later save.
    """
    n = 0
    for param in model.parameters():
        if not param.data.is_contiguous():
            param.data = param.data.contiguous()
            n += 1
    return n


def git_commit() -> str:
    try:
        return subprocess.check_output(
            ["git", "rev-parse", "--short", "HEAD"], text=True).strip()
    except Exception:
        return "unknown"


def leakage_gate(cfg) -> None:
    """Abort before training if the pool is contaminated."""
    audit = cfg.get("leakage_audit_config")
    if not audit:
        raise SystemExit("config must set leakage_audit_config (no silent skip)")
    r = subprocess.run(
        [sys.executable, "-I", "src/data/assert_no_leakage.py",
         "--config", audit, "--seed", "0"],
        capture_output=True, text=True)
    print(r.stdout)
    if r.returncode != 0:
        print(r.stderr)
        raise SystemExit("LEAKAGE GATE FAILED - refusing to train")
    print("leakage gate: PASS")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--config", required=True)
    ap.add_argument("--seed", type=int, required=True)
    a = ap.parse_args()
    cfg = yaml.safe_load(open(a.config, encoding="utf-8"))

    leakage_gate(cfg)
    set_seed(a.seed)

    run = f"{cfg['run_name']}_seed{a.seed}"
    out = os.path.join(cfg["paths"]["outputs"], run)
    os.makedirs(out, exist_ok=True)

    tok = AutoTokenizer.from_pretrained(cfg["model"]["name"])
    model = T5ForConditionalGeneration.from_pretrained(cfg["model"]["name"])
    n_fixed = make_contiguous(model)
    print(f"made {n_fixed} parameter tensors contiguous for safetensors")

    max_len = int(cfg["model"]["max_length"])
    train_ds = SegDataset(cfg["paths"]["train"], tok, max_len,
                          cfg.get("limit_train"))
    eval_ds = SegDataset(cfg["paths"]["eval"], tok, max_len,
                         cfg.get("limit_eval"))
    print(f"train {len(train_ds)}  eval {len(eval_ds)}")

    args = Seq2SeqTrainingArguments(
        output_dir=out,
        seed=a.seed,
        per_device_train_batch_size=int(cfg["train"]["batch_size"]),
        per_device_eval_batch_size=int(cfg["train"]["eval_batch_size"]),
        gradient_accumulation_steps=int(cfg["train"].get("grad_accum", 1)),
        learning_rate=float(cfg["train"]["lr"]),
        warmup_ratio=float(cfg["train"].get("warmup_ratio", 0.0)),
        max_steps=int(cfg["train"]["max_steps"]),
        logging_steps=int(cfg["train"].get("logging_steps", 50)),
        eval_strategy="no",
        save_strategy="steps",
        save_steps=int(cfg["train"]["max_steps"]),
        save_total_limit=1,          # disk is tight; keep only the final model
        bf16=torch.cuda.is_available(),
        dataloader_num_workers=int(cfg["train"].get("workers", 4)),
        report_to=[],
        predict_with_generate=False,
    )

    trainer = Seq2SeqTrainer(
        model=model, args=args,
        train_dataset=train_ds, eval_dataset=eval_ds,
        data_collator=DataCollatorForSeq2Seq(tok, model=model),
        tokenizer=tok,
    )
    res = trainer.train()
    make_contiguous(trainer.model)
    trainer.save_model(os.path.join(out, "final"))
    tok.save_pretrained(os.path.join(out, "final"))

    meta = {
        "run": run, "seed": a.seed, "config": a.config,
        "git_commit": git_commit(),
        "model": cfg["model"]["name"],
        "train_records": len(train_ds),
        "train_loss": res.metrics.get("train_loss"),
        "steps": res.metrics.get("step", args.max_steps),
    }
    with open(os.path.join(out, "meta.json"), "w", encoding="utf-8") as fh:
        json.dump(meta, fh, indent=2, ensure_ascii=False)
    print(json.dumps(meta, indent=2))


if __name__ == "__main__":
    main()