"""MR112 M1: interpolated Kneser-Ney n-gram (exact counts, orders 1..N<=4) on the task's 499,646,464 training targets,
scored with the official val stream (40 x 32 x 2048) and the held-out rows; optional doc-cache interpolation.
Tokens are 14-bit (8192 = row-start sentinel); n-grams never cross rows (each row = BOS-aligned packed row from the loader).
Usage: python tools/kn_placement.py OUT.json [N=4] [TRAIN_ROWS (default all: 953*4*64)]"""
import os, sys, json, math, time
W = os.path.dirname(os.path.dirname(os.path.abspath(__file__))); os.chdir(W)
os.environ.setdefault("PRETRAIN_DATA_ROOT", "/mnt/stephen/research_data/general_pretraining/cache")
sys.path.insert(0, "code/oe_write"); sys.path.insert(0, "code")
import torch
from prepare import Tokenizer, make_dataloader, get_token_bytes, EVAL_TOKENS, MAX_SEQ_LEN
import heldout
OUT = sys.argv[1]; N = int(sys.argv[2]) if len(sys.argv) > 2 else 4; NROWS = int(sys.argv[3]) if len(sys.argv) > 3 else 953 * 4 * 64
S = 8192; BITS = 14; dev = "cuda"
tok = Tokenizer.from_directory(); tb = get_token_bytes(device=dev); BOS = int(tok.get_bos_token_id())
cache_f = f"data_heldout/train_rows_{NROWS}.pt"; full_f = "data_heldout/train_rows_243968.pt"
t0 = time.time()
if os.path.exists(cache_f): R = torch.load(cache_f)
elif os.path.exists(full_f): R = torch.load(full_f)[:NROWS]   # prefix of the same stream
else:   # the exact training stream: 64-row micro-batches, rows = concat(x[:,0:1], y) (2049 tokens)
    dl = make_dataloader(tok, 64, MAX_SEQ_LEN, "train"); chunks = []; n = 0
    while n < NROWS:
        x, y, _ = next(dl); r = torch.cat([x[:, :1], y], 1).to(torch.int16).cpu(); chunks.append(r); n += r.shape[0]
    R = torch.cat(chunks)[:NROWS]; torch.save(R, cache_f)
print(f"train rows {tuple(R.shape)} targets {R.shape[0]*(R.shape[1]-1):,} ({time.time()-t0:.0f}s)", flush=True)
def keys_of(rows, n):
    """n-gram keys (ctx then w, w in the low bits) for every target position (cols 1..2048) of rows (B, 2049)."""
    B = rows.shape[0]; p = torch.cat([torch.full((B, N - 1), S, dtype=torch.long, device=rows.device), rows.long()], 1)
    k = torch.zeros(B, rows.shape[1] - 1, dtype=torch.long, device=rows.device)
    for i in range(n):   # token at offset (n-1-i) before target
        k = (k << BITS) | p[:, N - 1 - (n - 1 - i) + 1: N - 1 - (n - 1 - i) + 1 + rows.shape[1] - 1]
    return k
def count(n, chunk=32768):
    U = None; C = None
    for i in range(0, R.shape[0], chunk):
        k = keys_of(R[i:i + chunk].to(dev), n).reshape(-1); u, c = torch.unique(k, return_counts=True)
        if U is None: U, C = u, c
        else:
            u2, inv = torch.unique(torch.cat([U, u]), return_inverse=True); c2 = torch.zeros_like(u2); c2.scatter_add_(0, inv, torch.cat([C, c])); U, C = u2, c2
        del k
    return U, C
tables = {}
U, C = count(N); tables[N] = (U.cpu(), C.cpu()); del U, C; torch.cuda.empty_cache()
print(f"order {N}: {tables[N][0].numel():,} distinct ({time.time()-t0:.0f}s)", flush=True)
for n in range(N - 1, 0, -1):   # continuation counts N1+(. h w) from the order-(n+1) key set
    suf = tables[n + 1][0] & ((1 << (BITS * n)) - 1); u, c = torch.unique(suf, return_counts=True); tables[n] = (u, c); del suf
    print(f"order {n}: {u.numel():,} distinct (continuation)", flush=True)
meta = {}
for n, (U, C) in tables.items():
    ctx = U >> BITS; cu, inv, n1 = torch.unique_consecutive(ctx, return_inverse=True, return_counts=True)   # on CPU
    den = torch.zeros(cu.numel(), dtype=torch.long); den.scatter_add_(0, inv, C)
    c1 = int((C == 1).sum()); c2 = int((C == 2).sum()); D = c1 / (c1 + 2 * c2); del ctx, inv
    meta[n] = dict(ctx=cu.to(dev), den=den.float().to(dev), n1=n1.float().to(dev), D=D); print(f"order {n}: D={D:.4f} contexts {cu.numel():,}", flush=True)
    tables[n] = (U.to(dev), C.int().to(dev))
def lookup(sorted_keys, q):
    i = torch.searchsorted(sorted_keys, q).clamp(max=sorted_keys.numel() - 1); return i, sorted_keys[i] == q
@torch.no_grad()
def kn_prob(rows, order=N):
    """p(target) for rows (B, 2049) under interpolated KN up to `order`."""
    U1, C1 = tables[1]; m1 = meta[1]; w = rows[:, 1:].long()
    i, ok = lookup(U1, w); c = torch.where(ok, C1[i].long(), torch.zeros_like(w)).double()
    d0, n0 = float(m1["den"][0]), float(m1["n1"][0]); p = (c - m1["D"]).clamp(min=0) / d0 + m1["D"] * n0 / d0 / 8192
    for n in range(2, order + 1):
        U, Cn = tables[n]; m = meta[n]; k = keys_of(rows, n); ctx = k >> BITS
        i, ok = lookup(U, k); c = torch.where(ok, Cn[i].long(), torch.zeros_like(k)).double()
        j, okc = lookup(m["ctx"], ctx); den = torch.where(okc, m["den"][j].double(), torch.zeros_like(c)); n1 = torch.where(okc, m["n1"][j].double(), torch.zeros_like(c))
        pn = ((c - m["D"]).clamp(min=0) + m["D"] * n1 * p) / den.clamp(min=1)
        p = torch.where(den > 0, pn, p)
    return p
@torch.no_grad()
def cache_prob(rows):
    """doc-cache p_c(target) = count of target in x[doc_start..t] / (t - doc_start + 1); x = rows[:, :-1]."""
    x = rows[:, :-1].long(); y = rows[:, 1:].long(); B, T = x.shape
    pos = torch.arange(T, device=dev).expand(B, T); st = torch.where(x == BOS, pos, torch.zeros_like(pos)).cummax(1).values
    out = torch.zeros(B, T, dtype=torch.double, device=dev)
    for b in range(B):
        oh = torch.zeros(T, 8192, device=dev); oh[torch.arange(T), x[b]] = 1; cum = oh.cumsum(0)
        prev = (st[b] - 1).clamp(min=0); base = cum[prev] * (st[b] > 0).unsqueeze(-1).float()
        cnt = (cum - base).gather(1, y[b].unsqueeze(-1)).squeeze(-1); out[b] = cnt.double() / (pos[b] - st[b] + 1).double()
    return out
# normalisation check: full distribution for 4 positions
def full_dist_check():
    r = val_rows[0][:1].clone(); tot = []
    for t in (5, 100, 1000, 2000):
        rr = r.repeat(8192, 1); rr[:, t + 1] = torch.arange(8192, device=dev).to(rr.dtype)
        tot.append(float(kn_prob(rr)[:, t].sum()))
    return tot
# official val stream (identical to evaluate_bpb with batch 32) and held-out rows
vl = make_dataloader(tok, 32, MAX_SEQ_LEN, "val"); val_rows = []
for _ in range(EVAL_TOKENS // (32 * MAX_SEQ_LEN)):
    x, y, _ = next(vl); val_rows.append(torch.cat([x[:, :1], y], 1).to(dev))
HX, HY = heldout.get_rows(tok, "heldout"); ho_rows = [torch.cat([HX[i][:, :1].long(), HY[i].long()], 1).to(dev) for i in range(HX.shape[0])]
res = {"N": N, "train_rows": int(R.shape[0]), "norm_check_sums": full_dist_check(), "discounts": {n: meta[n]["D"] for n in meta}}
print("norm check", res["norm_check_sums"], flush=True)
lams = [0.0, 0.02, 0.05, 0.1, 0.15, 0.2, 0.3]
orders = list(range(2, N + 1))
def per_batch(rows_list):
    out = []   # per batch: {(o,l): nats}, bytes
    for rows in rows_list:
        y = rows[:, 1:].long(); nb = tb[y]; mk = nb > 0; pc = cache_prob(rows); d = {}
        for o in orders:
            pk = kn_prob(rows, o)
            for l in lams: d[(o, l)] = float((-torch.log(((1 - l) * pk + l * pc).clamp(min=1e-30)) * mk).sum())
        out.append((d, int(nb.sum())))
    return out
def agg(pb):
    tot = sum(b for _, b in pb); return {f"order{o}_lam{l}": sum(d[(o, l)] for d, _ in pb) / (math.log(2) * tot) for o in orders for l in lams}
NV = int(os.environ.get('KN_NVAL', len(val_rows))); PV = per_batch(val_rows[:NV]); h = len(PV) // 2
v1, v2, vall = agg(PV[:h]), agg(PV[h:]), agg(PV)
ho = agg(per_batch(ho_rows[:int(os.environ.get('KN_NHO', 40))]))
res.update(n_val_batches=len(PV), val_first_half=v1, val_second_half=v2, val_all=vall, heldout_40x32=ho)
best = {o: min(lams, key=lambda l: v1[f"order{o}_lam{l}"]) for o in orders}
res["lambda_tuned_on_first_half"] = best
res["summary"] = {f"order{o}": dict(no_cache_val=vall[f"order{o}_lam0.0"], cache_lam=best[o], cache_val_second_half=v2[f"order{o}_lam{best[o]}"],
                  no_cache_val_second_half=v2[f"order{o}_lam0.0"], cache_val_all=vall[f"order{o}_lam{best[o]}"],
                  cache_heldout=ho[f"order{o}_lam{best[o]}"], no_cache_heldout=ho[f"order{o}_lam0.0"]) for o in orders}
json.dump(res, open(OUT, "w"), indent=1); print(json.dumps(res["summary"], indent=1), f"({time.time()-t0:.0f}s)")
