"""Kill the same training run many times and compare it with the run that never stopped.

    python kill_resume.py --kills 40 --out ./kill-resume

Ravex's tests already hold a resume to the strong form (same losses step by
step, same final weights); this script is the same claim made visible, at a
size a reader can rerun on a laptop, and next to what a typical hand-written
resume does. It trains one small character GPT three ways:

* ``reference``: never interrupted.
* ``ravex``: under ``@ravex.train_loop``, killed ``--kills`` times at random
  steps, alternating SIGKILL (a host that vanishes: nothing runs) and SIGTERM
  (a spot reclaim: Ravex saves and exits), and started again with the same
  command each time until it reaches the last step.
* ``naive``: the resume most scripts write by hand: every ``--every`` steps it
  saves the model, the optimizer and the step number with ``torch.save``, and
  on a restart loads them and goes on. It does not save the LR scheduler or
  the RNG, which is the usual omission, so after a restart the warm-up starts
  again and the batches are other batches. It is killed at the same steps.

Every arm writes each step's loss to a log as it trains. A step trained twice
(the ones after the last checkpoint, redone after a kill) keeps its last
value, which is the one the finished run actually went through. The script
then prints, per arm, how many steps carry exactly the reference's loss, the
largest difference, how many steps were trained more than once, and whether
the final weights are bit-for-bit the reference's. With ``--out`` it also
writes the losses as CSV and, if matplotlib is installed, the curves as PNG.

It needs Linux or macOS: on Windows both signals are the same hard stop.
"""

from __future__ import annotations

import argparse
import csv
import hashlib
import math
import os
import random
import signal
import subprocess
import sys
import time
from pathlib import Path

CONTEXT = 32


def build(steps: int):
    """The model, data, optimizer and schedule, the same for every arm."""
    import torch
    import torch.nn as nn

    words = ["checkpoint", "resume", "step", "loss", "model", "train", "save", "node", "gpu", "run"]
    generator = torch.Generator().manual_seed(1)
    picks = torch.randint(len(words), (1500,), generator=generator).tolist()
    text = " ".join(words[i] for i in picks) + "."
    vocab = sorted(set(text))
    data = torch.tensor([vocab.index(c) for c in text])

    class GPT(nn.Module):
        def __init__(self) -> None:
            super().__init__()
            width = 64
            self.tokens = nn.Embedding(len(vocab), width)
            self.positions = nn.Embedding(CONTEXT, width)
            block = nn.TransformerEncoderLayer(width, 4, 4 * width, dropout=0.0, batch_first=True, norm_first=True)
            self.blocks = nn.TransformerEncoder(block, 2, enable_nested_tensor=False)
            self.norm = nn.LayerNorm(width)
            self.head = nn.Linear(width, len(vocab), bias=False)

        def forward(self, idx):
            length = idx.shape[1]
            h = self.tokens(idx) + self.positions(torch.arange(length))
            mask = nn.Transformer.generate_square_subsequent_mask(length)
            return self.head(self.norm(self.blocks(h, mask=mask, is_causal=True)))

    torch.manual_seed(0)
    model = GPT()
    optimizer = torch.optim.AdamW(model.parameters(), lr=3e-3, weight_decay=0.1)
    warmup = steps // 10

    def rate(step: int) -> float:
        if step < warmup:
            return (step + 1) / warmup
        return 0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * (step - warmup) / (steps - warmup)))

    scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, rate)
    return data, model, optimizer, scheduler


def train_step(data, model, optimizer, scheduler) -> float:
    import torch
    import torch.nn as nn

    starts = torch.randint(len(data) - CONTEXT - 1, (16,))
    x = torch.stack([data[i : i + CONTEXT] for i in starts])
    y = torch.stack([data[i + 1 : i + CONTEXT + 1] for i in starts])
    loss = nn.functional.cross_entropy(model(x).flatten(0, 1), y.flatten())
    optimizer.zero_grad(set_to_none=True)
    loss.backward()
    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
    optimizer.step()
    scheduler.step()
    return loss.item()


def digest(model) -> str:
    h = hashlib.sha256()
    for name, tensor in sorted(model.state_dict().items()):
        h.update(name.encode())
        h.update(tensor.detach().cpu().contiguous().numpy().tobytes())
    return h.hexdigest()


def worker(arm: str, steps: int, every: int, log: Path, store: Path) -> None:
    """One process of one arm: train from wherever its store says, log every step."""
    with log.open("a") as out:

        def record(step: int, loss: float) -> None:
            out.write(f"{step} {loss!r}\n")
            out.flush()

        if arm == "ravex":
            import ravex

            # The process runs in the arm's own folder, so Ravex's default ./checkpoints is the arm's store.
            @ravex.train_loop(max_steps=steps, checkpoint_every=every, announce=False)
            def train():
                data, model, optimizer, scheduler = build(steps)
                while ravex.step() < steps:
                    loss = train_step(data, model, optimizer, scheduler)
                    record(ravex.step(), loss)
                out.write(f"final {digest(model)}\n")

            train()
            return

        import torch

        data, model, optimizer, scheduler = build(steps)
        step = 0
        if arm == "naive" and (store / "last.pt").exists():
            state = torch.load(store / "last.pt")
            model.load_state_dict(state["model"])
            optimizer.load_state_dict(state["optimizer"])
            step = state["step"]
        while step < steps:
            loss = train_step(data, model, optimizer, scheduler)
            step += 1
            record(step, loss)
            if arm == "naive" and step % every == 0:
                store.mkdir(parents=True, exist_ok=True)
                torch.save({"model": model.state_dict(), "optimizer": optimizer.state_dict(), "step": step}, store / "tmp.pt")
                os.replace(store / "tmp.pt", store / "last.pt")
        out.write(f"final {digest(model)}\n")


def last_step(log: Path) -> int:
    try:
        lines = log.read_text().splitlines()
    except FileNotFoundError:
        return 0
    for line in reversed(lines):
        head = line.split(" ", 1)[0]
        if head.isdigit():
            return int(head)
    return 0


def run(arm: str, targets: list[int], args, work: Path) -> tuple[Path, int]:
    """Start the arm, kill it at each target step, start it again until it finishes."""
    log, store = (work / f"{arm}.log").resolve(), (work / f"{arm}-store").resolve()
    store.mkdir(parents=True, exist_ok=True)
    command = [sys.executable, os.path.abspath(__file__), "--worker", arm, "--steps", str(args.steps), "--every", str(args.every),
               "--log", str(log), "--store", str(store)]
    pending, restarts = list(targets), 0
    while True:
        process = subprocess.Popen(command, cwd=store)
        if pending:
            target = pending[0]
            while process.poll() is None and last_step(log) < target:
                time.sleep(0.01)
            if process.poll() is None:
                pending.pop(0)
                kind = signal.SIGKILL if (len(targets) - len(pending)) % 2 else signal.SIGTERM
                process.send_signal(kind)
                process.wait()
                restarts += 1
                continue
        if process.wait() != 0:
            raise SystemExit(f"{arm} exited with {process.returncode} after its last restart")
        if log.read_text().rstrip().splitlines()[-1].startswith("final"):
            return log, restarts


def read(log: Path) -> tuple[dict[int, float], str, int]:
    losses, final, repeated = {}, "", 0
    for line in log.read_text().splitlines():
        head, value = line.split(" ", 1)
        if head == "final":
            final = value
        else:
            step = int(head)
            repeated += step in losses
            losses[step] = float(value)
    return losses, final, repeated


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--kills", type=int, default=40)
    parser.add_argument("--steps", type=int, default=2000)
    parser.add_argument("--every", type=int, default=50, help="steps between checkpoints (Ravex may save more often in between)")
    parser.add_argument("--seed", type=int, default=0, help="seed of the kill steps, so a rerun kills at the same steps")
    parser.add_argument("--out", type=Path, help="folder for losses.csv and losses.png")
    parser.add_argument("--worker", help=argparse.SUPPRESS)
    parser.add_argument("--log", type=Path, help=argparse.SUPPRESS)
    parser.add_argument("--store", type=Path, help=argparse.SUPPRESS)
    args = parser.parse_args()

    if args.worker:
        worker(args.worker, args.steps, args.every, args.log, args.store)
        return
    if os.name == "nt":
        raise SystemExit("needs Linux or macOS: on Windows SIGTERM and SIGKILL are the same hard stop")

    work = args.out or Path("kill-resume-work")
    work.mkdir(parents=True, exist_ok=True)
    for stale in work.glob("*.log"):
        stale.unlink()
    for stale in work.glob("*-store"):
        subprocess.run(["rm", "-rf", str(stale)], check=True)
    targets = sorted(random.Random(args.seed).sample(range(10, args.steps - 10), args.kills))

    reference, _ = run("reference", [], args, work)
    ref_losses, ref_final, _ = read(reference)
    curves = {"reference": ref_losses}
    print(f"{args.steps} steps, {args.kills} kills (alternating SIGKILL and SIGTERM), checkpoint every {args.every}")
    print(f"{'arm':<8} {'restarts':>8} {'exact steps':>12} {'max |diff|':>11} {'retrained':>10}  final weights")
    for arm in ("ravex", "naive"):
        log, restarts = run(arm, targets, args, work)
        losses, final, repeated = read(log)
        curves[arm] = losses
        exact = sum(losses.get(s) == v for s, v in ref_losses.items())
        worst = max(abs(losses[s] - v) for s, v in ref_losses.items())
        same = "identical" if final == ref_final else "different"
        print(f"{arm:<8} {restarts:>8} {exact:>7}/{len(ref_losses):<4} {worst:>11.3g} {repeated:>10}  {same}")

    if args.out:
        with (args.out / "losses.csv").open("w", newline="") as f:
            w = csv.writer(f)
            w.writerow(["step", *curves])
            for step in sorted(ref_losses):
                w.writerow([step, *(curves[arm][step] for arm in curves)])
        try:
            import matplotlib

            matplotlib.use("Agg")
            import matplotlib.pyplot as plt
        except ImportError:
            print("matplotlib not installed: no losses.png")
            return
        fig, ax = plt.subplots(figsize=(9, 4.5))
        for arm, style in (("naive", "-"), ("reference", "-"), ("ravex", "--")):
            steps = sorted(curves[arm])
            ax.plot(steps, [curves[arm][s] for s in steps], style, label=arm, linewidth=1)
        for target in targets:
            ax.axvline(target, color="grey", alpha=0.15, linewidth=0.8)
        ax.set_xlabel("step")
        ax.set_ylabel("training loss")
        ax.set_title(f"The same run killed {args.kills} times (grey lines)")
        ax.legend()
        fig.tight_layout()
        fig.savefig(args.out / "losses.png", dpi=150)
        print(f"wrote {args.out / 'losses.csv'} and {args.out / 'losses.png'}")


if __name__ == "__main__":
    main()
