"""Gated cosine EEG–envelope match on top of stem_ms96.

The published stem is loaded from models/logit_tf_v2/stem_ms96__held-*.pt.
A causal projection of the EEG and a shared causal projection of each speaker
envelope are compared by time-wise cosine similarity. The antisymmetric
difference (speaker A minus speaker B) is added to the stem logit through a
scalar gate that starts at 0, so step 0 matches the unmodified stem.

Prep stays eaP_n5_t60. The four sw2 classifier logits are the stem input and
are not retrained. Corpus envelopes are column-swapped with the same synthetic
schedule the classifier folds used. AASD and Carta keep their real envelopes.

usage:
  python stem_envelope_match.py --check-only
  python stem_envelope_match.py
"""
import argparse
import copy
import json
import math
import os
import pickle
import time

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

import ensemble_clf_nested as N
import ensemble_clf_transformer_v2 as V
import ensemble_clf_transformer_v4 as V4
import eval_external as E
from common import DS_KEYS, SEED
from common_exp import EXP, FS, load_trial, rows_of
from e1_switch import draw_switch_times

HOP = 8
WINDOW = 96
PREP = "eaP_n5_t60"
P_STAY = 0.994
SCALE = 0.8
STEPS = int(os.environ.get("STEPS", "1000"))
BATCH = int(os.environ.get("BATCH", "512"))
CKPT_DIR = os.path.join(EXP, "models", "stem_envelope_match")
STEM_DIR = os.path.join(EXP, "models", "logit_tf_v2")
LOG = os.path.join(EXP, "experiments", "stem_envelope_match.log")
OUT = os.path.join(EXP, "results", "research", "stem_envelope_match.json")
EVID = "/root/disk_3tb/EEG-sAAD-Grand-Challenge-Training-Dataset/experiments/decoder_lodo/results/research"
TEST_NAMES = ("AASD", "Carta2026")
MATCH_D = 16
MATCH_K = 17


def log_line(text):
    print(text, flush=True)
    os.makedirs(os.path.dirname(LOG), exist_ok=True)
    with open(LOG, "a") as fh:
        fh.write(text + "\n")


class CausalMap(nn.Module):
    def __init__(self, c_in, d, k):
        super().__init__()
        self.k = k
        self.conv = nn.Conv1d(c_in, d, k, bias=False)

    def forward(self, x):
        h = self.conv(F.pad(x.transpose(1, 2), (self.k - 1, 0)))
        return h.transpose(1, 2)


def _cosine(a, b):
    a = F.normalize(a, dim=-1, eps=1e-6)
    b = F.normalize(b, dim=-1, eps=1e-6)
    return (a * b).sum(-1)


class EnvelopeMatch(nn.Module):
    """Causal maps into one space, cosine at each decision sample, A minus B.

    No bias: a zero EEG produces a zero query, so the cosine difference is zero.
    Both speakers share the envelope map, so swapping the columns negates the scalar.
    """

    def __init__(self, d=MATCH_D, k=MATCH_K, hop=HOP):
        super().__init__()
        self.hop = hop
        self.eeg = CausalMap(58, d, k)
        self.env = CausalMap(1, d, k)

    def forward(self, eeg, env):
        q = self.eeg(eeg)
        k0 = self.env(env[..., 0:1])
        k1 = self.env(env[..., 1:2])
        sl = slice(self.hop - 1, None, self.hop)
        return _cosine(q[:, sl], k0[:, sl]) - _cosine(q[:, sl], k1[:, sl])


class GatedStem(nn.Module):
    def __init__(self, stem):
        super().__init__()
        self.stem = stem
        self.match = EnvelopeMatch()
        self.gate = nn.Parameter(torch.zeros(()))

    def forward(self, x, eeg, env):
        return self.stem(x) + self.gate * self.match(eeg, env)


def load_stem(path, device):
    blob = torch.load(path, map_location="cpu", weights_only=False)
    name, family, window, d_model, nlayers, stem, _lr = blob["cfg"]
    if name != "stem_ms96" or not stem or window != WINDOW:
        raise RuntimeError(f"unexpected stem cfg {blob['cfg']}")
    c_in = int(np.asarray(blob["mu"]).shape[0])
    net = V.LogitTransformer(c_in, window, d_model=d_model, nlayers=nlayers, stem=True)
    net.load_state_dict(blob["state"])
    model = GatedStem(net).to(device)
    mu = np.asarray(blob["mu"], np.float32)
    sd = np.asarray(blob["sd"], np.float32)
    return model, mu, sd, list(blob["train"])


def pack_neural(eeg, env, a, w, hop=HOP):
    """Window of w decision frames starting at frame a (a may be negative)."""
    length = w * hop
    idx = (a * hop - (hop - 1)) + np.arange(length)
    eeg_o = np.zeros((length, eeg.shape[1]), np.float32)
    env_o = np.zeros((length, env.shape[1]), np.float32)
    ok = (idx >= 0) & (idx < len(eeg))
    if np.any(ok):
        eeg_o[ok] = eeg[idx[ok]]
        env_o[ok] = env[idx[ok]]
    return eeg_o, env_o


def switch_envelopes(ds, eeg_len, t0, n128):
    """Boolean mask at 32 Hz, same consumption order as direct_classifier.run_fold."""
    srng = np.random.default_rng(SEED + DS_KEYS.index(ds))
    masks = {}
    for _, r in rows_of(ds).iterrows():
        times = draw_switch_times(srng, int(r["n"]) / 128.0)
        srng.integers(0, 2)
        if r["key"] not in eeg_len:
            continue
        T128 = int(r["n"])
        st128 = np.zeros(T128, dtype=bool)
        cur, prev = False, 0
        for tt in np.atleast_1d(times):
            s0 = min(T128 - 1, int(round(float(tt) * 128)))
            st128[prev:s0] = cur
            cur, prev = (not cur), s0
        st128[prev:] = cur
        n = eeg_len[r["key"]]
        idx = np.minimum(T128 - 1, np.round((np.arange(n) / FS + t0[r["key"]]) * 128).astype(int))
        masks[r["key"]] = st128[idx]
    return masks


def load_corpus_neural():
    """EEG and speaker envelopes. Envelopes follow the fold switch schedule."""
    raw = {}
    meta_n, meta_t0 = {}, {}
    for ds in DS_KEYS:
        for _, r in rows_of(ds).iterrows():
            tr = load_trial(PREP, r["key"])
            eeg = np.asarray(tr["eeg"], np.float32)
            env = np.asarray(tr["env"], np.float32)
            raw[(ds, r["key"])] = (eeg, env)
            meta_n.setdefault(ds, {})[r["key"]] = len(eeg)
            meta_t0.setdefault(ds, {})[r["key"]] = float(tr["t0"])
    out = {}
    for ds in DS_KEYS:
        masks = switch_envelopes(ds, meta_n[ds], meta_t0[ds], None)
        for key, (eeg, env) in list(raw.items()):
            if key[0] != ds:
                continue
            env = np.array(env, copy=True)
            st = masks[key[1]]
            env[st] = env[st, ::-1]
            out[key] = (eeg, env)
    return out


def build_groups(feat, att, neural, datasets):
    groups = []
    ys = []
    for ds in datasets:
        trials = []
        for key, X in feat[ds].items():
            y = (np.asarray(att[ds][key]) == 0).astype(np.float32)
            eeg, env = neural[(ds, key)]
            n_frames = int(np.ceil(len(eeg) / float(HOP)))
            if len(X) != len(y) or n_frames != len(X):
                raise RuntimeError(
                    f"alignment {ds}/{key}: feat {len(X)} att {len(y)} eeg {len(eeg)} frames {n_frames}")
            trials.append((np.asarray(X, np.float32), y, eeg, env))
            ys.append(y)
        lengths = np.array([len(t[1]) for t in trials], np.int64)
        groups.append(dict(trials=trials, lengths=lengths, total=int(lengths.sum()), ends=np.cumsum(lengths)))
    return groups, np.concatenate(ys)


def sample_batch(rng, groups, batch, mu, sd):
    C = groups[0]["trials"][0][0].shape[1]
    Tn = WINDOW * HOP
    Xo = np.zeros((batch, WINDOW, C), np.float32)
    yo = np.zeros((batch, WINDOW), np.float32)
    mo = np.zeros((batch, WINDOW), np.float32)
    Eo = np.zeros((batch, Tn, 58), np.float32)
    Vo = np.zeros((batch, Tn, 2), np.float32)
    ds_of = np.arange(batch) % len(groups)
    for g_i, g in enumerate(groups):
        rows = np.flatnonzero(ds_of == g_i)
        if len(rows) == 0:
            continue
        pick = rng.integers(0, g["total"], size=len(rows))
        which = np.searchsorted(g["ends"], pick, side="right")
        local = pick - (g["ends"] - g["lengths"])[which]
        trials = g["trials"]
        for row, ti, t in zip(rows, which, local):
            x, y, eeg, env = trials[int(ti)]
            t = int(t)
            a = t - WINDOW + 1
            if a >= 0:
                Xo[row] = x[a:t + 1]
                yo[row] = y[a:t + 1]
                mo[row] = 1.0
            else:
                n = t + 1
                Xo[row, -n:] = x[:n]
                yo[row, -n:] = y[:n]
                mo[row, -n:] = 1.0
            Eo[row], Vo[row] = pack_neural(eeg, env, a, WINDOW)
    Xo -= mu
    Xo /= sd
    return Xo, yo, mo, Eo, Vo


def batch_loss(logit, y, m, pos_weight):
    sw = V.switch_weights(y, m)
    bce = F.binary_cross_entropy_with_logits(logit, y, pos_weight=pos_weight, reduction="none")
    denom = (sw * m).sum().clamp_min(1.0)
    loss = (bce * sw * m).sum() / denom
    dv = (logit[:, 1:] - logit[:, :-1]).abs()
    m2 = m[:, 1:] * m[:, :-1]
    loss = loss + 0.05 * (dv * m2).sum() / m2.sum().clamp_min(1.0)
    return loss


def set_lrs(opt, step, total, bases):
    warm = 10
    if step < warm:
        scale = (step + 1) / float(warm)
    else:
        p = (step - warm) / float(max(total - warm, 1))
        scale = 0.1 + 0.5 * 0.9 * (1.0 + math.cos(math.pi * p))
    for group, base in zip(opt.param_groups, bases):
        group["lr"] = base * scale


def make_opt(model):
    bases = (2e-5, 1e-3, 1e-2)
    opt = torch.optim.AdamW([
        {"params": list(model.stem.parameters()), "lr": bases[0], "weight_decay": 0.0},
        {"params": list(model.match.parameters()), "lr": bases[1], "weight_decay": 1e-4},
        {"params": [model.gate], "lr": bases[2], "weight_decay": 0.0},
    ])
    return opt, bases


def to_device(batch, device):
    xb, yb, mb, eb, vb = batch
    return (
        torch.from_numpy(xb).to(device, non_blocking=True),
        torch.from_numpy(yb).to(device, non_blocking=True),
        torch.from_numpy(mb).to(device, non_blocking=True),
        torch.from_numpy(eb).to(device, non_blocking=True),
        torch.from_numpy(vb).to(device, non_blocking=True),
    )


def fresh_loss(model, frozen, rng, groups, batch, mu, sd, pos_weight, device, n=4):
    model.eval()
    frozen.eval()
    live, base = [], []
    with torch.no_grad():
        for _ in range(n):
            x, y, m, eeg, env = to_device(sample_batch(rng, groups, batch, mu, sd), device)
            x = V.augment(x)
            live.append(float(batch_loss(model(x, eeg, env), y, m, pos_weight)))
            base.append(float(batch_loss(frozen(x), y, m, pos_weight)))
    model.train()
    return float(np.mean(live)), float(np.mean(base))


def train_one(model, groups, y_all, mu, sd, device, steps, batch, tag, check_gate):
    pos = float(y_all.mean())
    pos_weight = torch.tensor([(1.0 - pos) / max(pos, 1e-3)], device=device)
    frozen = copy.deepcopy(model.stem).eval()
    for p in frozen.parameters():
        p.requires_grad_(False)
    ema = copy.deepcopy(model).eval()
    opt, bases = make_opt(model)
    rng = np.random.default_rng(V.TRAIN_SEED)
    model.train()
    t0 = time.time()
    last = None
    gate50 = None
    for step in range(steps):
        if check_gate and step == 50:
            live, base = fresh_loss(model, frozen, rng, groups, batch, mu, sd, pos_weight, device)
            gate50 = float(model.gate.detach().cpu())
            log_line(f"  {tag} step 50 train-batch loss {live:.4f} frozen-stem {base:.4f} gate {gate50:.4f}")
            if live > 0.689 or live >= base - 1e-4:
                log_line(f"  ABORT {tag}: loss {live:.4f} vs frozen {base:.4f}")
                raise SystemExit(3)
        set_lrs(opt, step, steps, bases)
        x, y, m, eeg, env = to_device(sample_batch(rng, groups, batch, mu, sd), device)
        x = V.augment(x)
        opt.zero_grad(set_to_none=True)
        loss = batch_loss(model(x, eeg, env), y, m, pos_weight)
        if not torch.isfinite(loss):
            raise RuntimeError(f"non-finite loss at step {step} for {tag}")
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        opt.step()
        V.ema_update(model, ema, 0.995)
        last = float(loss.item())
        if step == 0 or (step + 1) % 200 == 0:
            log_line(f"    {tag} step {step + 1}/{steps} loss {last:.4f} gate {float(model.gate.detach().cpu()):.4f}")
    ema.eval()
    log_line(f"  trained {tag} loss {last:.4f} gate {float(ema.gate.detach().cpu()):.4f} ({time.time() - t0:.0f}s)")
    return ema


@torch.no_grad()
def infer_table(model, table, neural, mu, sd, device, batch, ds_of_neural):
    model.eval()
    mu_t = torch.from_numpy(mu.reshape(1, 1, -1))
    sd_t = torch.from_numpy(sd.reshape(1, 1, -1))
    out = {}
    for key, X in table.items():
        eeg, env = neural[(ds_of_neural, key)] if ds_of_neural is not None else neural[key]
        T = len(X)
        pieces = []
        for i in range(0, T, batch):
            ends = np.arange(i, min(T, i + batch))
            xb = np.zeros((len(ends), WINDOW, X.shape[1]), np.float32)
            eb = np.zeros((len(ends), WINDOW * HOP, 58), np.float32)
            vb = np.zeros((len(ends), WINDOW * HOP, 2), np.float32)
            for row, t in enumerate(ends):
                a = int(t) - WINDOW + 1
                if a >= 0:
                    xb[row] = X[a:int(t) + 1]
                else:
                    n = int(t) + 1
                    xb[row, -n:] = X[:n]
                eb[row], vb[row] = pack_neural(eeg, env, a, WINDOW)
            xb -= mu
            xb /= sd
            logit = model(
                torch.from_numpy(xb).to(device),
                torch.from_numpy(eb).to(device),
                torch.from_numpy(vb).to(device),
            )
            pieces.append(logit[:, -1].cpu().numpy())
        pred = np.concatenate(pieces).astype(np.float64)
        if len(pred) != T:
            raise RuntimeError(f"infer length {len(pred)} != {T} for {key}")
        out[key] = pred
    return out


def forward_check(device):
    """Gate 0 matches the stem. Gate 1 must move when the EEG is zeroed."""
    path = os.path.join(STEM_DIR, "stem_ms96__held-AVGC.pt")
    model, mu, sd, train_ds = load_stem(path, device)
    model.eval()
    log_line(f"forward check from {path} train {train_ds}")
    torch.manual_seed(0)
    x = torch.randn(4, WINDOW, mu.shape[0], device=device)
    # one real trial, packed as four identical windows ending mid-trial
    tr = load_trial(PREP, rows_of("KUL").iloc[0]["key"])
    eeg = np.asarray(tr["eeg"], np.float32)
    env = np.asarray(tr["env"], np.float32)
    a = 200
    e1, v1 = pack_neural(eeg, env, a, WINDOW)
    # decision sample of the last frame is eeg[(a+WINDOW-1)*HOP]
    last = (a + WINDOW - 1) * HOP
    if not np.allclose(e1[-1], eeg[last]):
        raise RuntimeError("pack does not land on the decision sample")
    eb = torch.from_numpy(np.stack([e1] * 4)).to(device)
    vb = torch.from_numpy(np.stack([v1] * 4)).to(device)
    with torch.no_grad():
        same = model(x, eb, vb)
        stem = model.stem(x)
        gap = float((same - stem).abs().max())
        model.gate.fill_(1)
        full = model(x, eb, vb)
        zero = model(x, torch.zeros_like(eb), vb)
        delta = float((full - zero).abs().mean())
        match = model.match(eb, vb)
        swapped = model.match(eb, vb.flip(-1))
        swap_gap = float((swapped + match).abs().max())
        # corrupt the last hop; earlier decision frames must stay put
        late = eb.clone()
        late[:, -HOP:] = torch.randn_like(late[:, -HOP:])
        past = model.match(eb, vb)
        fut = model.match(late, vb)
        future_gap = float((past[:, :-1] - fut[:, :-1]).abs().max())
        model.gate.zero_()
    log_line(f"  gate0 max abs logit diff {gap:.3e}")
    log_line(f"  gate1 zero-EEG mean abs logit change {delta:.4f}")
    log_line(f"  speaker-swap residual {swap_gap:.3e}  future residual {future_gap:.3e}")
    if gap > 1e-4:
        raise RuntimeError(f"gate 0 does not match the stem ({gap})")
    if delta < 0.05:
        raise RuntimeError(f"zeroing EEG changes the logit by only {delta}")
    if swap_gap > 1e-4 or future_gap > 1e-4:
        raise RuntimeError("match is not antisymmetric or not causal")
    return dict(gate0_max_abs=gap, zero_eeg_mean_abs=delta, swap_residual=swap_gap, future_residual=future_gap)


def score_lodo(model, feat, neural, mu, sd, held, device):
    streams = {}
    for ds in DS_KEYS:
        streams[ds] = infer_table(model, feat[ds], neural, mu, sd, device, batch=128, ds_of_neural=ds)
    ev = N.to_ev(streams)
    off = N.official(held, ev, P_STAY, SCALE)
    log_line(f"LODO {held} p {P_STAY} sc {SCALE}  H {off['H']:.4f} Acc {off['Acc']:.2f} "
             f"L {off['L']:.3f} SDT {off['SDT']:.2f}")
    return off


def load_external():
    E.CONF.update(prep=PREP, targets=["env", "onset", "dom"])
    logits, meta, neural = {}, {}, {}
    for ds in TEST_NAMES:
        evs = []
        for i in range(4):
            path = os.path.join(EVID, f"ext_clf_{ds}_w10b3sw2P_evidence_s{i}.pkl")
            with open(path, "rb") as fh:
                evs.append(pickle.load(fh))
        logits[ds], meta[ds] = {}, {}
        by_key = {tr["key"]: tr for tr in E.ext_trials(ds)}
        for key in evs[0]:
            cols = [(ev[key]["r0"] - ev[key]["r1"]).astype(np.float32) for ev in evs]
            e0 = evs[0][key]
            logits[ds][key] = np.stack(cols, 1)
            meta[ds][key] = dict(
                att=np.asarray(e0["att"]), t_end=np.asarray(e0["t_end"], np.float64),
                att128=np.asarray(e0["att128"]), n128=int(e0["n128"]), subject=int(e0["subject"]))
            tr = by_key[key]
            eeg = np.asarray(tr["eeg"], np.float32)
            env = np.asarray(tr["env"], np.float32)
            n_frames = int(np.ceil(len(eeg) / float(HOP)))
            if n_frames != len(e0["att"]) or len(logits[ds][key]) != n_frames:
                raise RuntimeError(f"external alignment {ds}/{key}: eeg {len(eeg)} frames {n_frames} att {len(e0['att'])}")
            neural[(ds, key)] = (eeg, env)
        log_line(f"  external {ds}: {len(logits[ds])} trials")
    return logits, meta, neural


def score_external(model, feat, neural, meta, mu_in, sd_in, corpus_streams, corpus_att, device):
    """Emissions from this model's five corpus streams. No test-label tuning."""
    parts = []
    for ds, table in corpus_streams.items():
        labels = corpus_att[ds]
        for key, d in table.items():
            parts.append(np.asarray(d, np.float64) * np.where(labels[key] == 0, 1.0, -1.0))
    mu_e, sd_e = float(np.concatenate(parts).mean()), float(np.concatenate(parts).std())
    log_line(f"  external emissions mu {mu_e:.4f} sd {sd_e:.4f} scale {SCALE}")
    rows = {}
    for ds in TEST_NAMES:
        stream = infer_table(model, feat[ds], neural, mu_in, sd_in, device, batch=128, ds_of_neural=ds)
        ev = {}
        for key, d in stream.items():
            m = meta[ds][key]
            d = np.asarray(d, np.float64)
            ev[key] = dict(r0=d, r1=np.zeros(len(d)), att=m["att"], t_end=m["t_end"],
                           att128=m["att128"], n128=m["n128"], subject=m["subject"])
        r = E.score(ev, mu_e, sd_e * SCALE, P_STAY, 0.75)
        rows[ds] = r
        log_line(f"EXT {ds} p {P_STAY} sc {SCALE}  H {r['H']:.4f} Acc {r['Acc']:.2f} "
                 f"L {r['L']:.3f} SDT {r['SDT']:.2f}")
    return rows


def fit_with_oom(stem_path, groups, y_all, mu, sd, device, steps, batch, tag, check_gate, halved=False):
    model, mu_ck, sd_ck, _train = load_stem(stem_path, device)
    # keep the checkpoint normalisation so step 0 is that stem
    del mu, sd
    try:
        ema = train_one(model, groups, y_all, mu_ck, sd_ck, device, steps, batch, tag, check_gate)
        return ema, mu_ck, sd_ck, batch
    except torch.cuda.OutOfMemoryError:
        if halved:
            raise
        log_line(f"  OOM on {tag} at batch {batch}; halving once")
        del model
        torch.cuda.empty_cache()
        return fit_with_oom(stem_path, groups, y_all, mu_ck, sd_ck, device, steps, batch // 2, tag, check_gate, halved=True)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--check-only", action="store_true")
    args = ap.parse_args()
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    log_line(f"device {device} steps {STEPS} batch {BATCH}")
    torch.backends.cuda.matmul.allow_tf32 = True
    torch.backends.cudnn.allow_tf32 = True
    check = forward_check(device)
    if args.check_only:
        log_line("check only, no training")
        return
    log_line("loading corpus logits and eaP_n5_t60 trials")
    N.load_all()
    feat = V.build_features()["ms"]
    neural = load_corpus_neural()
    os.makedirs(CKPT_DIR, exist_ok=True)
    per = {}
    for i, held in enumerate(DS_KEYS):
        path = os.path.join(STEM_DIR, f"stem_ms96__held-{held}.pt")
        train_ds = [d for d in DS_KEYS if d != held]
        groups, y_all = build_groups(feat, N.G["att"], neural, train_ds)
        log_line(f"fold held-out={held} from {path} batch {BATCH}")
        ema, mu, sd, used = fit_with_oom(
            path, groups, y_all, None, None, device, STEPS, BATCH, f"held-{held}", check_gate=(i == 0))
        torch.save({"state": ema.state_dict(), "mu": mu, "sd": sd, "stem": path,
                    "train": train_ds, "steps": STEPS, "batch": used},
                   os.path.join(CKPT_DIR, f"held-{held}.pt"))
        per[held] = score_lodo(ema, feat, neural, mu, sd, held, device)
        del ema
        if device.type == "cuda":
            torch.cuda.empty_cache()
    log_line("all-5 fine-tune for AASD and Carta, init stem_ms96__held-AVGC.pt")
    groups, y_all = build_groups(feat, N.G["att"], neural, list(DS_KEYS))
    all_path = os.path.join(STEM_DIR, "stem_ms96__held-AVGC.pt")
    ema, mu, sd, used = fit_with_oom(
        all_path, groups, y_all, None, None, device, STEPS, BATCH, "all5", check_gate=False)
    torch.save({"state": ema.state_dict(), "mu": mu, "sd": sd, "stem": all_path,
                "train": list(DS_KEYS), "steps": STEPS, "batch": used},
               os.path.join(CKPT_DIR, "all5.pt"))
    corpus_streams = {ds: infer_table(ema, feat[ds], neural, mu, sd, device, batch=128, ds_of_neural=ds)
                      for ds in DS_KEYS}
    ext_logits, ext_meta, ext_neural = load_external()
    ext_feat = V4.build_features_from(ext_logits)["ms"]
    ext = score_external(ema, ext_feat, ext_neural, ext_meta, mu, sd, corpus_streams, N.G["att"], device)
    out = dict(check=check, p_stay=P_STAY, scale=SCALE, steps=STEPS, lodo=per, external=ext)
    os.makedirs(os.path.dirname(OUT), exist_ok=True)
    with open(OUT, "w") as fh:
        json.dump(out, fh, indent=1, default=float)
    log_line(f"wrote {OUT}")


if __name__ == "__main__":
    main()
