"""Fine-tuning example on gridline/hf-finetune-2.5@r4: LoRA (bf16) and QLoRA (4-bit) on SmolLM2-135M.

Gridline stages the base model at models/base (declared under `models:` in gridline-models.yaml)
and the dataset arrives with the source (data/*.jsonl). Every step writes its outcome into
outputs/metrics.json as it goes; a failed step is recorded, never a crash, and the script exits 0
(metrics.json says whether every step passed). A heartbeat thread rewrites metrics.json every
30 s. Your code has no network, and the Hugging Face offline switches are set before any import.

FT_DRY_RUN=cpu (local proof only, never in gridline.yaml): CPU, float32, 2 steps per variant,
the model from FT_MODEL_DIR without the pin check, and QLoRA recorded as skipped (bitsandbytes'
4-bit kernels need CUDA).
"""
import getpass
import hashlib
import json
import os
import shutil
import socket
import sys
import tempfile
import threading
import time
import traceback

for name in ("HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE", "HF_DATASETS_OFFLINE"):
    os.environ.setdefault(name, "1")
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")

OUT = "outputs"
DRY = os.environ.get("FT_DRY_RUN") == "cpu"
# models: (gridline-models.yaml, v2.7) stages the base at models/base; gridline.yaml ships it as inputs.
MODEL = (os.environ.get("FT_MODEL_DIR", "inputs/model") if DRY
         else "models/base" if os.path.isdir("models/base") else "inputs/model")
PROMPTS = ("Add 12 and 30.", "Subtract 7 from 64.", "Reverse the word cedar.",
           "Sort these words: onyx, amber, river.", "Add 45 and 45.")
os.makedirs(OUT, exist_ok=True)
metrics = {"schema": "finetune-accept/v1", "dry_run": DRY, "started": time.time(), "steps": {},
           "heartbeats": []}
lock = threading.Lock()


def save():
    with lock:
        tmp = os.path.join(OUT, ".metrics.tmp")
        with open(tmp, "w") as f:
            json.dump(metrics, f, indent=1, sort_keys=True, default=str)
            f.flush()
            os.fsync(f.fileno())
        os.replace(tmp, os.path.join(OUT, "metrics.json"))


def step(name, fn):
    started = time.time()
    metrics["phase"] = name
    try:
        metrics["steps"][name] = {"ok": True, "value": fn()}
    except BaseException as e:  # recorded, not raised
        metrics["steps"][name] = {"ok": False, "error": type(e).__name__, "detail": str(e)[:400],
                                  "where": where(e)}
    metrics["steps"][name]["seconds"] = round(time.time() - started, 2)
    save()
    return metrics["steps"][name]


def where(error):
    """The failing frame and the last train.py frame above it (file:line function), so a remote
    failure names its call site without a traceback in the logs."""
    frames = traceback.extract_tb(error.__traceback__)
    ours = [f for f in frames if os.path.basename(f.filename) == "train.py"]
    return ["%s:%d %s" % (os.path.basename(f.filename), f.lineno, f.name) for f in (ours[-1:] + frames[-1:])]


def heartbeat(stop):
    while not stop.wait(30):
        metrics["heartbeats"].append({"t": time.time(), "phase": metrics.get("phase")})
        save()


def identity():
    return {"uid": os.getuid(), "gid": os.getgid(), "python": sys.version.split()[0], "cwd": os.getcwd(),
            "getuser": _try(getpass.getuser), "tmpdir": tempfile.gettempdir()}


def _try(fn):
    try:
        return fn()
    except Exception as e:
        return "error:" + type(e).__name__


def network():
    """The payload has no network: creating a TCP socket or connecting it must fail (the error is
    the evidence). The sandbox may refuse the socket itself (EPERM) before any connect, so both
    calls sit inside the try."""
    stage = "socket"
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            stage = "connect"
            s.settimeout(5)
            s.connect(("1.1.1.1", 443))
            return {"connected": True}
        finally:
            s.close()
    except OSError as e:
        return {"connected": False, "stage": stage, "error": type(e).__name__, "errno": e.errno}


def cuda():
    import torch
    if DRY:
        return {"torch": torch.__version__, "cuda_available": torch.cuda.is_available(), "skipped": "dry_run"}
    assert torch.cuda.is_available(), "cuda unavailable"
    return {"torch": torch.__version__, "cuda": torch.version.cuda, "device": torch.cuda.get_device_name(0),
            "capability": list(torch.cuda.get_device_capability(0)), "bf16": torch.cuda.is_bf16_supported(),
            "total_bytes": torch.cuda.get_device_properties(0).total_memory}


def model_pins():
    """The model directory holds every pinned file at its pinned size (and the weights' sha256);
    inputs/model must hold nothing else, models/base may (the platform's staging is recorded)."""
    with open("model-pins.json") as f:
        pins = json.load(f)
    if DRY:
        return {"skipped": "dry_run", "revision": pins["revision"]}
    present = sorted(os.listdir(MODEL))
    missing = sorted(set(pins["files"]) - set(present))
    extra = sorted(set(present) - set(pins["files"]))
    assert not missing, "model files missing %s" % missing
    assert MODEL != "inputs/model" or not extra, "model inputs %s" % present
    seen = {}
    for name, pin in pins["files"].items():
        path = os.path.join(MODEL, name)
        size = os.path.getsize(path)
        assert size == pin["bytes"], "%s is %d bytes" % (name, size)
        digest = hashlib.sha256()
        with open(path, "rb") as f:
            for chunk in iter(lambda: f.read(1 << 20), b""):
                digest.update(chunk)
        seen[name] = digest.hexdigest()
        assert pin.get("sha256", seen[name]) == seen[name], "%s sha256 differs" % name
    return {"revision": pins["revision"], "sha256": seen, "from": MODEL, "extra": extra}


def load_rows(name):
    with open(os.path.join("data", name)) as f:
        return [json.loads(line) for line in f]


def versions():
    import importlib.metadata as md
    return {name: _try(lambda name=name: md.version(name)) for name in
            ("torch", "transformers", "peft", "trl", "accelerate", "datasets", "bitsandbytes", "evaluate")}


def amp(device, dtype):
    """Autocast at the compute dtype outside the trainer. trl's SFTTrainer casts a 4-bit model's
    LoRA layers and embeddings (tied lm_head) to bf16 and keeps the norms in float32; the trainer
    runs under autocast, but eval and generate did not, and the mixed dtypes failed ("expected
    scalar type BFloat16 but found Float" with QLoRA). float32 (the CPU dry run) needs none."""
    import torch
    return torch.autocast(device_type=device, dtype=dtype, enabled=dtype != torch.float32)


def eval_loss(model, tokenizer, rows, device, dtype):
    import torch
    model.eval()
    total, count = 0.0, 0
    with torch.no_grad(), amp(device, dtype):
        for start in range(0, len(rows), 8):
            batch = tokenizer([r["text"] for r in rows[start:start + 8]], return_tensors="pt", padding=True,
                              truncation=True, max_length=256, return_token_type_ids=False).to(device)
            labels = batch["input_ids"].masked_fill(batch["attention_mask"] == 0, -100)
            total += float(model(**batch, labels=labels).loss) * len(rows[start:start + 8])
            count += len(rows[start:start + 8])
    return total / count


def generate(model, tokenizer, device, dtype):
    import torch
    model.eval()
    answers = []
    for prompt in PROMPTS:
        text = "### Instruction:\n%s\n### Response:\n" % prompt
        batch = tokenizer(text, return_tensors="pt", return_token_type_ids=False).to(device)
        with torch.no_grad(), amp(device, dtype):
            out = model.generate(**batch, max_new_tokens=24, do_sample=False,
                                 pad_token_id=tokenizer.pad_token_id)
        answers.append({"prompt": prompt, "completion": tokenizer.decode(out[0][batch["input_ids"].shape[1]:],
                                                                          skip_special_tokens=True)})
    return answers


def finetune(kind):
    """One variant: base eval loss, SFT with LoRA (kind lora) or QLoRA 4-bit (kind qlora), eval loss
    after, five greedy completions, and the adapter's two files copied to outputs/<kind>/."""
    import torch
    from datasets import Dataset
    from peft import LoraConfig
    from transformers import AutoModelForCausalLM, AutoTokenizer
    from trl import SFTConfig, SFTTrainer
    torch.manual_seed(0)
    device = "cpu" if DRY else "cuda"
    bf16 = (not DRY) and torch.cuda.is_bf16_supported()
    dtype = torch.float32 if DRY else (torch.bfloat16 if bf16 else torch.float16)
    tokenizer = AutoTokenizer.from_pretrained(MODEL, local_files_only=True)
    if tokenizer.pad_token is None:
        tokenizer.pad_token = tokenizer.eos_token
    if kind == "qlora":
        from peft import prepare_model_for_kbit_training
        from transformers import BitsAndBytesConfig
        quant = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True,
                                   bnb_4bit_compute_dtype=dtype)
        model = AutoModelForCausalLM.from_pretrained(MODEL, local_files_only=True, quantization_config=quant,
                                                     torch_dtype=dtype, device_map={"": 0})
        model = prepare_model_for_kbit_training(model)
    else:
        model = AutoModelForCausalLM.from_pretrained(MODEL, local_files_only=True, torch_dtype=dtype).to(device)
    evaluation = load_rows("eval.jsonl")
    before = eval_loss(model, tokenizer, evaluation, device, dtype)
    if not DRY:
        torch.cuda.reset_peak_memory_stats()
    work = tempfile.mkdtemp(prefix="ft-%s-" % kind)
    config = SFTConfig(output_dir=work, dataset_text_field="text", max_seq_length=256, packing=False,
                       per_device_train_batch_size=8, num_train_epochs=1, learning_rate=2e-4,
                       lr_scheduler_type="cosine", warmup_ratio=0.03, logging_steps=10, seed=0,
                       max_steps=2 if DRY else (-1 if kind == "lora" else 60), save_strategy="no",
                       report_to=[], bf16=bf16, fp16=(not DRY) and not bf16, use_cpu=DRY,
                       gradient_checkpointing=kind == "qlora", dataloader_num_workers=0)
    lora = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM",
                      target_modules=["q_proj", "k_proj", "v_proj", "o_proj"])
    trainer = SFTTrainer(model=model, args=config, train_dataset=Dataset.from_list(load_rows("train.jsonl")),
                         processing_class=tokenizer, peft_config=lora)
    started = time.time()
    result = trainer.train()
    seconds = time.time() - started
    tuned = trainer.model
    after = eval_loss(tuned, tokenizer, evaluation, device, dtype)
    answers = generate(tuned, tokenizer, device, dtype)
    tuned.save_pretrained(os.path.join(work, "adapter"))
    target = os.path.join(OUT, kind)
    os.makedirs(target, exist_ok=True)
    files = {}
    for name in ("adapter_model.safetensors", "adapter_config.json"):
        shutil.copyfile(os.path.join(work, "adapter", name), os.path.join(target, name))
        data = open(os.path.join(target, name), "rb").read()
        files[name] = {"bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()}
    trainable = sum(p.numel() for p in tuned.parameters() if p.requires_grad)
    shutil.rmtree(work, ignore_errors=True)
    history = [{k: v for k, v in entry.items() if k in ("step", "loss", "learning_rate")}
               for entry in trainer.state.log_history if "loss" in entry]
    return {"steps": int(result.global_step), "train_loss": float(result.training_loss), "train_seconds": round(seconds, 2),
            "eval_loss_before": before, "eval_loss_after": after, "improved": after < before,
            "trainable_parameters": int(trainable), "peak_gpu_bytes": None if DRY else int(torch.cuda.max_memory_allocated()),
            "log": history, "completions": answers, "adapter": files}


if __name__ == "__main__":
    stop = threading.Event()
    threading.Thread(target=heartbeat, args=(stop,), daemon=True).start()
    step("identity", identity)
    step("network", network)
    step("versions", versions)
    step("cuda", cuda)
    step("model_pins", model_pins)
    step("lora", lambda: finetune("lora"))
    if DRY:
        metrics["steps"]["qlora"] = {"ok": True, "value": {"skipped": "dry_run_cpu"}}
    else:
        step("qlora", lambda: finetune("qlora"))
    stop.set()
    steps = metrics["steps"]
    metrics["finished"] = time.time()
    metrics["pass"] = (all(s["ok"] for s in steps.values()) and not steps["network"]["value"]["connected"]
                       and (DRY or all(steps[k]["value"]["improved"] for k in ("lora", "qlora"))))
    metrics["phase"] = "done"
    save()
    sys.exit(0)
