File size: 8,263 Bytes
3bbd5dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
"""Train MTP heads and an NTP control for one condition, then evaluate held out.

One condition per invocation so the caller can pin it to a single physical
GPU with CUDA_VISIBLE_DEVICES; these are independent single-GPU jobs, no
DDP and no model parallelism. Writes per-condition CSV rows plus a run log
recording command, git hash, wall time, peak GPU memory and tokens seen.
"""

import argparse
import csv
import json
import logging
import os
import subprocess
import time

os.environ.setdefault("CUDA_DEVICE_ORDER", "PCI_BUS_ID")

import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

import torch
import yaml
from transformers import AutoModelForCausalLM, AutoTokenizer

from src.train.data import iter_batches, load_heldout_texts, load_train_ids
from src.train.evaluate import evaluate_stack, speculative_decode
from src.train.model import MTPStack
from src.train.trainer import train

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("huggingface_hub").setLevel(logging.WARNING)
logger = logging.getLogger("phase3")

DEVICE = "cuda:0"  # the process is already restricted to one physical GPU by the caller


def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--config", default="configs/phase3.yaml")
    p.add_argument("--condition", required=True, choices=["L2", "L4", "E1"])
    p.add_argument("--out", required=True, help="per-condition output CSV path")
    p.add_argument("--max-steps", type=int, default=None, help="override; otherwise derived from the token budget")
    p.add_argument("--seed", type=int, default=None)
    p.add_argument("--no-shared-trunk", action="store_true", help="ablate the shared trunk; D is then zero by construction")
    p.add_argument("--tag", default="", help="suffix distinguishing this run's checkpoints and logs")
    return p.parse_args()


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


def build_stacks(backbone, cfg: dict, use_shared_trunk: bool) -> tuple:
    """Return (mtp, ntp) stacks sharing the backbone's frozen unembedding.

    The control gets its own trunk and head so the two stacks share no
    trainable parameter; only the frozen unembedding and the frozen hidden
    states are common to both.
    """
    hidden_size = backbone.config.hidden_size
    mtp = MTPStack(hidden_size, backbone.lm_head, cfg["n_heads"], use_shared_trunk).to(DEVICE)
    ntp = MTPStack(hidden_size, backbone.lm_head, 1, use_shared_trunk).to(DEVICE)
    return mtp, ntp


def main() -> None:
    args = parse_args()
    with open(args.config, encoding="utf-8") as f:
        cfg = yaml.safe_load(f)
    seed = args.seed if args.seed is not None else cfg["seed"]
    use_shared_trunk = cfg["use_shared_trunk"] and not args.no_shared_trunk
    logger.info("config: %s", cfg)
    logger.info("condition=%s seed=%d use_shared_trunk=%s", args.condition, seed, use_shared_trunk)

    torch.manual_seed(seed)
    started = time.perf_counter()

    tokenizer = AutoTokenizer.from_pretrained(cfg["backbone"]["hf_id"])
    backbone = AutoModelForCausalLM.from_pretrained(cfg["backbone"]["hf_id"], dtype=torch.float32).to(DEVICE)
    backbone.eval()
    for param in backbone.parameters():
        param.requires_grad = False

    mtp, ntp = build_stacks(backbone, cfg, use_shared_trunk)
    logger.info(
        "trainable params: mtp=%d ntp=%d",
        sum(p.numel() for p in mtp.trainable_parameters()),
        sum(p.numel() for p in ntp.trainable_parameters()),
    )

    data_dir = Path(cfg["data_dir"])
    train_ids = load_train_ids(str(data_dir / f"{args.condition}_train_ids.npy"))
    heldout = load_heldout_texts(str(data_dir / f"{args.condition}_heldout.jsonl"))
    logger.info("loaded %d train tokens, %d held-out docs", len(train_ids), len(heldout))

    tokens_per_step = cfg["batch_size"] * cfg["seq_len"]
    max_steps = args.max_steps if args.max_steps is not None else len(train_ids) // tokens_per_step
    batches = iter_batches(train_ids, cfg["batch_size"], cfg["seq_len"], seed, max_steps=max_steps)

    torch.cuda.reset_peak_memory_stats(DEVICE)
    metrics = train(backbone, mtp, ntp, batches, DEVICE, cfg["learning_rate"], max_steps)
    logger.info(
        "training done: %d steps, %d tokens, %.1f tok/s, mtp_h1 %.4f ntp %.4f",
        metrics.steps, metrics.tokens, metrics.tokens_per_second, metrics.mtp_head_losses[0], metrics.ntp_loss,
    )

    mtp.eval()
    ntp.eval()
    mtp_stats = evaluate_stack(backbone, mtp, tokenizer, heldout, DEVICE, cfg["eval_max_tokens_per_doc"])
    ntp_stats = evaluate_stack(backbone, ntp, tokenizer, heldout, DEVICE, cfg["eval_max_tokens_per_doc"])
    d_value = mtp_stats.bpb - ntp_stats.bpb
    logger.info("BPB mtp=%.6f ntp=%.6f D=%.6f", mtp_stats.bpb, ntp_stats.bpb, d_value)

    spec = speculative_decode(
        backbone, mtp, tokenizer, heldout[: cfg["spec_docs"]], DEVICE, cfg["spec_prompt_tokens"], cfg["spec_completion_tokens"]
    )
    logger.info(
        "speculative: %.4f accepted/forward, boundary completion %.4f over %d spans",
        spec.mean_accepted_per_forward, spec.boundary_completion_rate, spec.n_spans_scored,
    )

    peak_mem_mib = torch.cuda.max_memory_allocated(DEVICE) / (1024**2)
    wall = time.perf_counter() - started

    tag = args.tag or f"seed{seed}"
    ckpt_dir = Path(cfg["checkpoint_dir"]) / f"{args.condition}_{tag}"
    ckpt_dir.mkdir(parents=True, exist_ok=True)
    torch.save(mtp.state_dict(), ckpt_dir / "mtp.pt")
    torch.save(ntp.state_dict(), ckpt_dir / "ntp.pt")

    rows = [["condition", "metric", "value", "n"]]
    c = args.condition

    def add(metric: str, value, n) -> None:
        rows.append([c, metric, value, n])

    add("seed", seed, 1)
    add("use_shared_trunk", int(use_shared_trunk), 1)
    add("train_tokens", metrics.tokens, 1)
    add("train_steps", metrics.steps, 1)
    add("tokens_per_second", f"{metrics.tokens_per_second:.3f}", 1)
    add("train_loss_ntp_nats", f"{metrics.ntp_loss:.6f}", metrics.steps)
    for k, loss in enumerate(metrics.mtp_head_losses):
        add(f"train_loss_mtp_head{k + 1}_nats", f"{loss:.6f}", metrics.steps)
    add("bpb_mtp", f"{mtp_stats.bpb:.6f}", mtp_stats.n_bytes)
    add("bpb_ntp", f"{ntp_stats.bpb:.6f}", ntp_stats.n_bytes)
    add("d_bpb_mtp_minus_ntp", f"{d_value:.6f}", mtp_stats.n_bytes)
    for k in range(len(mtp_stats.head_accuracy)):
        add(f"head{k + 1}_accuracy", f"{mtp_stats.head_accuracy[k]:.6f}", mtp_stats.n_tokens)
        add(f"head{k + 1}_accuracy_intraword", f"{mtp_stats.head_accuracy_intraword[k]:.6f}", mtp_stats.n_tokens)
        add(f"head{k + 1}_accuracy_boundary", f"{mtp_stats.head_accuracy_boundary[k]:.6f}", mtp_stats.n_tokens)
    add("ntp_head_accuracy", f"{ntp_stats.head_accuracy[0]:.6f}", ntp_stats.n_tokens)
    add("mean_accepted_per_forward", f"{spec.mean_accepted_per_forward:.6f}", spec.n_rounds)
    add("boundary_completion_rate", f"{spec.boundary_completion_rate:.6f}", spec.n_spans_scored)
    add("peak_gpu_mib", f"{peak_mem_mib:.1f}", 1)
    add("wall_seconds", f"{wall:.1f}", 1)

    Path(args.out).parent.mkdir(parents=True, exist_ok=True)
    with open(args.out, "w", newline="", encoding="utf-8") as f:
        csv.writer(f).writerows(rows)

    log_dir = Path(cfg["run_log_dir"])
    log_dir.mkdir(parents=True, exist_ok=True)
    with (log_dir / f"{c}_{tag}.json").open("w", encoding="utf-8") as f:
        json.dump(
            {
                "command": " ".join(sys.argv),
                "git_hash": git_hash(),
                "condition": c,
                "seed": seed,
                "use_shared_trunk": use_shared_trunk,
                "wall_seconds": round(wall, 1),
                "peak_gpu_mib": round(peak_mem_mib, 1),
                "tokens_processed": metrics.tokens,
                "tokens_per_second": round(metrics.tokens_per_second, 3),
            },
            f,
            indent=2,
        )
    logger.info("wrote %s and run log", args.out)


if __name__ == "__main__":
    main()