"""Rocky Tested AirLLM bench. One mode per process so peak-memory numbers don't mix.
mode=split    : split checkpoint into per-layer shards (CPU/disk only)
mode=airllm   : AirLLM layer streaming with torch GPU allocator capped at --cap-gb
mode=baseline : plain transformers, whole model on the GPU (needs enough free GPU memory for the whole model)
Writes one JSON line to --out. Greedy decoding so outputs can be compared token for token."""
import argparse, json, time, resource, os, sys, threading
import torch
p = argparse.ArgumentParser()
p.add_argument("--mode", required=True); p.add_argument("--model", required=True)
p.add_argument("--label", required=True); p.add_argument("--out", required=True)
p.add_argument("--cap-gb", type=float); p.add_argument("--new", type=int, default=24)
p.add_argument("--shards", default="/shards")
a = p.parse_args()
PROMPT = "Question: What is the capital of France, and what river runs through it? Answer:"
rec = {"label": a.label, "mode": a.mode, "model": a.model, "cap_gb": a.cap_gb, "max_new_tokens": a.new, "prompt": PROMPT}
# sample unified-memory use of this process (GB10 shares RAM between CPU and GPU)
peak_rss = [0]
def sampler():
    while True:
        try:
            for l in open("/proc/self/status"):
                if l.startswith("VmRSS"): peak_rss[0] = max(peak_rss[0], int(l.split()[1]))
        except Exception: pass
        time.sleep(0.2)
threading.Thread(target=sampler, daemon=True).start()
def emit(**kw):
    rec.update(kw)
    rec["peak_rss_gb"] = round(peak_rss[0] / 1048576, 2)
    rec["ru_maxrss_gb"] = round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1048576, 2)
    if torch.cuda.is_available():
        rec["torch_peak_allocated_gb"] = round(torch.cuda.max_memory_allocated() / 2**30, 3)
        rec["torch_peak_reserved_gb"] = round(torch.cuda.max_memory_reserved() / 2**30, 3)
    open(a.out, "a").write(json.dumps(rec) + "\n"); print(json.dumps(rec), flush=True)
try:
    if a.mode == "split":
        import importlib
        from airllm import AutoModel
        from airllm.utils import find_or_create_local_splitted_path
        mod, cls_name = AutoModel.get_module_class(a.model)
        cls = getattr(importlib.import_module(mod), cls_name); o = cls.__new__(cls); o.set_layer_names_dict()
        rec["airllm_class"] = cls_name
        t0 = time.time(); r = find_or_create_local_splitted_path(a.model, layer_shards_saving_path=a.shards, layer_names=o.layer_names_dict)
        emit(ok=True, split_seconds=round(time.time() - t0, 1), split_path=str(r[0])); sys.exit(0)
    if a.cap_gb:
        tot = torch.cuda.get_device_properties(0).total_memory
        torch.cuda.set_per_process_memory_fraction(a.cap_gb * 2**30 / tot, 0)
        rec["device_total_gb"] = round(tot / 2**30, 1)
    t0 = time.time()
    if a.mode == "airllm":
        from airllm import AutoModel
        m = AutoModel.from_pretrained(a.model, layer_shards_saving_path=a.shards)
        tok = m.tokenizer
    else:
        from transformers import AutoModelForCausalLM, AutoTokenizer
        tok = AutoTokenizer.from_pretrained(a.model)
        m = AutoModelForCausalLM.from_pretrained(a.model, dtype=torch.bfloat16, device_map="cuda:0")
    load_s = time.time() - t0
    ids = tok([PROMPT], return_tensors="pt", return_attention_mask=False)["input_ids"].cuda()
    torch.cuda.synchronize(); t1 = time.time()
    out = m.generate(ids, max_new_tokens=a.new, use_cache=True, do_sample=False, return_dict_in_generate=True)
    torch.cuda.synchronize(); gen_s = time.time() - t1
    seq = out.sequences[0][ids.shape[1]:]
    n = int(seq.shape[0])
    emit(ok=True, load_seconds=round(load_s, 1), gen_seconds=round(gen_s, 2), new_tokens=n,
         tokens_per_sec=round(n / gen_s, 4), seconds_per_token=round(gen_s / n, 3),
         output_ids=seq.tolist(), output_text=tok.decode(seq, skip_special_tokens=True))
except SystemExit: raise
except BaseException as ex:
    import traceback; traceback.print_exc()
    emit(ok=False, error=f"{type(ex).__name__}: {str(ex)[:600]}")
    sys.exit(1)
