"""Fill IRM/SWA fuse stream caches for causal_moe_fuse.py.

Uses CUDA if available for frozen forward only. Does NOT acquire gpu.lock.
Safe to rerun; skips existing cache files.
"""
import os
import time

import torch

# Prefer GPU for this cache-fill helper; scoring stays in causal_moe_fuse.py
os.environ.pop("CUDA_VISIBLE_DEVICES", None)

import ensemble_clf_nested as N
import ensemble_clf_transformer_v2 as V
import ensemble_clf_transformer_v4 as V4
import stem_ms96_irm_swa_fuse as F
import causal_moe_fuse as M
from common import DS_KEYS


def main():
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    torch.set_num_threads(8)
    M.log_line(f"[cachefill] device {device}")
    if device.type == "cuda":
        torch.backends.cuda.matmul.allow_tf32 = True
        torch.backends.cudnn.allow_tf32 = True
    N.load_all()
    feat_all = V.build_features()["ms"]
    for held in DS_KEYS:
        M.ensure_fuse_cache(held, feat_all, device)
        if device.type == "cuda":
            torch.cuda.empty_cache()
    M.ensure_all5_corpus_fuse(feat_all, device)
    if device.type == "cuda":
        torch.cuda.empty_cache()
    ext_logits, _ = F.load_external()
    ext_feat = V4.build_features_from(ext_logits)["ms"]
    M.ensure_all5_ext_fuse(ext_feat, device)
    M.log_line("[cachefill] done")


if __name__ == "__main__":
    # append to same log
    os.makedirs(os.path.dirname(M.LOG), exist_ok=True)
    main()
