{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.12.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat_minor":4,"nbformat":4,"cells":[{"id":"342c8c53","cell_type":"markdown","source":"# RSNA Knee — Notebook 02: Conservative Fine-Tuning (FT-A)\n\nThis is the first actual continuation-training stage after Notebook 01.\n\nNotebook 01 established:\n\n- 4,407 training studies;\n- only 58 studies have complete 12-target expert labels;\n- the existing package contains 20 DINOv2 members (4 per original fold);\n- the checkpoints contain model weights and epoch metadata but no optimizer/scheduler state;\n- no original `StudyInstanceUID -> fold` artifact was verified.\n\nBecause the historical fold map is unavailable, this notebook **does not claim strict historical OOF**. Instead it creates a new deterministic 5-fold split only inside the 58 expert-labelled studies and uses it as a conservative promotion gate for fine-tuning.\n\n### FT-A policy\n\n- keep the original 0.891 package untouched;\n- default: fine-tune only the best-holdout member from each original fold (5 new members);\n- train the head + final 2 DINO transformer blocks;\n- very small backbone learning rate;\n- random overlapping 3-slice training windows;\n- target-balanced masked BCE;\n- early stopping / rollback: a fine-tuned state is promoted only if it improves validation BCE over its own base checkpoint;\n- save new checkpoint fingerprints and an inference-compatible `manifest.json`.\n\n### Required Kaggle inputs\n\n1. RSNA Knee competition data.\n2. The original `rsna-knee-weights` package used by the 0.89 notebook.\n3. The same local DINOv2-small Hugging Face model input used by the old inference notebook.\n4. Notebook 01 output (`rsna_stage1_bundle/` or `rsna_stage1_bundle.zip`).\n\nThe final output folder is `/kaggle/working/rsna_stage2_fta/`. Add this notebook's output as an input to Notebook 03.","metadata":{}},{"id":"b1cee1ff","cell_type":"code","source":"from __future__ import annotations\n\nimport os\nfor _v in (\"OMP_NUM_THREADS\", \"OPENBLAS_NUM_THREADS\", \"MKL_NUM_THREADS\"):\n    os.environ.setdefault(_v, \"4\")\n\nimport gc\nimport hashlib\nimport json\nimport math\nimport re\nimport shutil\nimport time\nimport traceback\nimport zipfile\nfrom concurrent.futures import ThreadPoolExecutor\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\nimport pydicom\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom IPython.display import display\nfrom sklearn.metrics import roc_auc_score\n\nT0 = time.time()\nSEED = int(os.environ.get(\"FT_SEED\", \"2026\"))\nnp.random.seed(SEED)\ntorch.manual_seed(SEED)\nif torch.cuda.is_available():\n    torch.cuda.manual_seed_all(SEED)\n\nTARGETS = [\n    \"ACL\", \"MCL\", \"Medial Meniscus\", \"Lateral Meniscus\", \"Medial OA\",\n    \"Lateral OA\", \"PF OA\", \"Effusion\", \"Synovitis\", \"Baker's\",\n    \"Contusion\", \"Fracture\",\n]\n\n# Conservative FT defaults.\nFT_MEMBER_MODE = os.environ.get(\"FT_MEMBER_MODE\", \"champions\").lower()\n# champions = best checkpoint per original fold (recommended)\n# top2      = best 2 per original fold\n# all20     = every member\nFT_UNFREEZE_LAST = int(os.environ.get(\"FT_UNFREEZE_LAST\", \"2\"))\nFT_MAX_EPOCHS = int(os.environ.get(\"FT_MAX_EPOCHS\", \"4\"))\nFT_PATIENCE = int(os.environ.get(\"FT_PATIENCE\", \"2\"))\nFT_HEAD_LR = float(os.environ.get(\"FT_HEAD_LR\", \"2e-4\"))\nFT_BACKBONE_LR = float(os.environ.get(\"FT_BACKBONE_LR\", \"1e-5\"))\nFT_WEIGHT_DECAY = float(os.environ.get(\"FT_WEIGHT_DECAY\", \"0.01\"))\nFT_BATCH = int(os.environ.get(\"FT_BATCH\", \"2\"))\nFT_GRAD_ACCUM = int(os.environ.get(\"FT_GRAD_ACCUM\", \"2\"))\nFT_MIN_DELTA = float(os.environ.get(\"FT_MIN_DELTA\", \"0.0005\"))\nFT_N_FOLDS = 5\nEVAL_BATCH = int(os.environ.get(\"FT_EVAL_BATCH\", \"4\"))\nTIME_BUDGET = float(os.environ.get(\"FT_TIME_BUDGET_HOURS\", \"8\")) * 3600\n\n# Checkpoint-compatible pixel defaults. Manifest config overwrites these.\nCROP_MM = 130.0\nCACHE_IMG = 336\nIMG = CACHE_IMG\nGROUP = 3\nCACHE_SLICES = 12\nN_GROUP = max(CACHE_SLICES // GROUP, 1)\nSLICE_BAND = (0.20, 0.80)\n\nHDR_THREADS = int(os.environ.get(\"HDR_THREADS\", \"16\"))\nPIX_THREADS = int(os.environ.get(\"PIX_THREADS\", \"12\"))\nORDER_THREADS = int(os.environ.get(\"ORDER_THREADS\", \"32\"))\nORDER_BUDGET_S = 5400\nLAT_MIN_OFFSET_MM = 20.0\nLEGACY_LAT_OFFSET_MM = 5.0\n\nRULES_NATIVE = {\n    \"order\": \"normal\",\n    \"lat\": \"centre\",\n    \"slot_fallback\": False,\n    \"decode_fill\": \"nearest\",\n}\nRULES_LEGACY = {\n    \"order\": \"dominant_axis\",\n    \"lat\": \"corner_x\",\n    \"slot_fallback\": True,\n    \"decode_fill\": \"zero\",\n}\nRULES = dict(RULES_NATIVE)\n\nSLOTS_RECOVERED = [\n    (\"SAG_FLUID_FS\", \"Sagittal\", True, True),\n    (\"COR_FLUID_FS\", \"Coronal\", True, True),\n    (\"AX_FLUID_FS\", \"Axial\", True, True),\n    (\"SAG_FLUID_NOFS\", \"Sagittal\", True, False),\n    (\"COR_T1\", \"Coronal\", False, False),\n    (\"SAG_T1\", \"Sagittal\", False, False),\n]\nSLOTS_PUBLIC = [\n    (\"SAG_FLUID\", \"Sagittal\", None, True),\n    (\"COR_FLUID\", \"Coronal\", None, True),\n    (\"AX_FLUID\", \"Axial\", None, True),\n    (\"SAG_STRUCT\", \"Sagittal\", None, False),\n    (\"COR_STRUCT\", \"Coronal\", None, False),\n    (\"AX_STRUCT\", \"Axial\", None, False),\n]\nSLOTS = SLOTS_RECOVERED\nN_SLOT = len(SLOTS)\n\nPOOL_PARTS = {\"cls_mean\": 2, \"cls_mean_focal\": 3}\nSLOT_PRIOR_TABLE = {\n    \"ACL\": (0, 3, 5), \"MCL\": (1, 4),\n    \"Medial Meniscus\": (0, 1, 3, 4), \"Lateral Meniscus\": (0, 1, 3, 4),\n    \"Medial OA\": (1, 4, 5), \"Lateral OA\": (1, 4, 5),\n    \"PF OA\": (0, 2, 5), \"Effusion\": (0, 2), \"Synovitis\": (0, 2),\n    \"Baker's\": (0,), \"Contusion\": (0, 1, 2), \"Fracture\": (0, 1, 2, 4, 5),\n}\nSLOT_PRIOR_STRENGTH = 0.55\n\nFATSAT_OPTS = {\"FS\", \"FATSAT\", \"FAT_SAT\", \"FSAT\"}\n_SEP = re.compile(r\"[_\\-.]\")\n_FATSAT_RX = re.compile(\n    r\"\\bfs\\b|fatsat|fat sat|\\bstir\\b|\\bspair\\b|\\bspir\\b|\\bwe\\b|\"\n    r\"water excit|\\btirm\\b|\\bsting\\b|\\bfatsup\\b\"\n)\n_T1_RX = re.compile(r\"\\bt1\\b|\\bt1w\\b\")\n_T2_RX = re.compile(r\"\\bt2\\b|\\bt2w\\b\")\n_PD_RX = re.compile(r\"\\bpd\\b|\\bpdw\\b|proton|\\bdp\\b|dens\")\n\nFRONTIER_TARGET_POOL = {\n    \"Fracture\": \"max\",\n    \"Contusion\": \"max\",\n    \"Medial Meniscus\": \"max\",\n    \"Lateral Meniscus\": \"max\",\n    \"ACL\": \"top2\",\n    \"MCL\": \"top2\",\n    \"Baker's\": \"max\",\n}\n\nOUT = Path(\"/kaggle/working/rsna_stage2_fta\")\nOUT.mkdir(parents=True, exist_ok=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-11T20:01:40.065559Z","iopub.execute_input":"2026-08-11T20:01:40.066352Z","iopub.status.idle":"2026-08-11T20:01:40.084741Z","shell.execute_reply.started":"2026-08-11T20:01:40.066324Z","shell.execute_reply":"2026-08-11T20:01:40.084009Z"}},"outputs":[],"execution_count":null},{"id":"93377b4c","cell_type":"code","source":"def log(msg):\n    print(f\"[{time.time() - T0:7.1f}s] {msg}\", flush=True)\n\n\nclass WeightsError(RuntimeError):\n    pass\n\n\ndef find_train_root():\n    explicit = os.environ.get(\"KNEE_INPUT_DIR\", \"\").strip()\n    candidates = [Path(explicit)] if explicit else []\n    candidates += [\n        Path(\"/kaggle/input/competitions/rsna-knee-abnormality-detection\"),\n        Path(\"/kaggle/input/rsna-knee-abnormality-detection\"),\n    ]\n    for c in candidates:\n        if (c / \"train.csv\").is_file() and (c / \"train_series\").is_dir():\n            return c\n\n    base = Path(\"/kaggle/input\")\n    if base.is_dir():\n        for root, dirs, files in os.walk(base):\n            dirs[:] = [d for d in dirs if d not in (\"train_series\", \"test_series\")]\n            root = Path(root)\n            if (root / \"train.csv\").is_file() and (root / \"train_series\").is_dir():\n                return root\n    raise FileNotFoundError(\"RSNA Knee competition training mount not found\")\n\n\ndef _valid_weight_package(root: Path):\n    root = Path(root)\n    p = root / \"manifest.json\"\n    if not p.is_file():\n        return False\n    try:\n        man = json.loads(p.read_text())\n    except Exception:\n        return False\n    members = man.get(\"members\")\n    if not isinstance(members, list) or not members:\n        return False\n    return all((root / str(m.get(\"file\"))).is_file() for m in members)\n\n\ndef find_weights():\n    explicit = os.environ.get(\"KNEE_WEIGHTS_DIR\", \"\").strip()\n    candidates = [Path(explicit)] if explicit else []\n    candidates += [\n        Path(\"/kaggle/input/rsna-knee-weights\"),\n        Path(\"/kaggle/input/datasets/pilkwang/rsna-knee-weights\"),\n    ]\n    for p in candidates:\n        if p and _valid_weight_package(p):\n            return p\n\n    base = Path(\"/kaggle/input\")\n    if base.is_dir():\n        for root, dirs, files in os.walk(base):\n            dirs[:] = [d for d in dirs if d not in (\"train_series\", \"test_series\")]\n            if \"manifest.json\" in files and _valid_weight_package(Path(root)):\n                # Avoid accidentally picking Stage 2 output from a prior run.\n                man = json.loads((Path(root) / \"manifest.json\").read_text())\n                if not any(\"ft_stage\" in m for m in man.get(\"members\", [])):\n                    return Path(root)\n    raise FileNotFoundError(\"Original rsna-knee-weights package not found\")\n\n\ndef _looks_like_dinov2_config(config_path: Path):\n    try:\n        cfg = json.loads(config_path.read_text())\n    except Exception:\n        return False\n    text = json.dumps(cfg).lower()\n    return (\n        cfg.get(\"model_type\", \"\").lower() == \"dinov2\"\n        or \"dinov2\" in text\n        or any(\"dinov2\" in str(x).lower() for x in cfg.get(\"architectures\", []) or [])\n    )\n\n\ndef find_dinov2(variant=\"small\"):\n    explicit = os.environ.get(\"KNEE_DINOV2_DIR\", \"\").strip()\n    if explicit:\n        p = Path(explicit)\n        if (p / \"config.json\").is_file():\n            return p\n        raise FileNotFoundError(f\"KNEE_DINOV2_DIR={explicit!r} has no config.json\")\n\n    base = Path(\"/kaggle/input\")\n    strong, weak = [], []\n    if base.is_dir():\n        for root, dirs, files in os.walk(base):\n            dirs[:] = [d for d in dirs if d not in (\"train_series\", \"test_series\")]\n            if \"config.json\" not in files:\n                continue\n            p = Path(root)\n            if _looks_like_dinov2_config(p / \"config.json\"):\n                strong.append(p)\n            elif \"dinov2\" in str(p).lower():\n                weak.append(p)\n\n    hits = strong or weak\n    if not hits:\n        return None\n\n    target_hidden = {\"small\": 384, \"base\": 768, \"large\": 1024, \"giant\": 1536}.get(str(variant).lower())\n    if target_hidden is not None:\n        for p in hits:\n            try:\n                cfg = json.loads((p / \"config.json\").read_text())\n                if int(cfg.get(\"hidden_size\", -1)) == target_hidden:\n                    return p\n            except Exception:\n                pass\n    return hits[0]\n\n\ndef find_stage1():\n    explicit = os.environ.get(\"STAGE1_DIR\", \"\").strip()\n    if explicit:\n        p = Path(explicit)\n        if (p / \"stage1_status.json\").is_file():\n            return p\n\n    # Prefer already-unpacked Notebook 01 output.\n    base = Path(\"/kaggle/input\")\n    if base.is_dir():\n        for root, dirs, files in os.walk(base):\n            dirs[:] = [d for d in dirs if d not in (\"train_series\", \"test_series\")]\n            if \"stage1_status.json\" in files and \"expert_complete_12.csv\" in files:\n                return Path(root)\n\n    # Or extract the compact ZIP produced by Notebook 01.\n    if base.is_dir():\n        for root, dirs, files in os.walk(base):\n            dirs[:] = [d for d in dirs if d not in (\"train_series\", \"test_series\")]\n            if \"rsna_stage1_bundle.zip\" in files:\n                z = Path(root) / \"rsna_stage1_bundle.zip\"\n                dest = Path(\"/kaggle/working/stage1_input\")\n                dest.mkdir(parents=True, exist_ok=True)\n                with zipfile.ZipFile(z) as fh:\n                    fh.extractall(dest)\n                if (dest / \"stage1_status.json\").is_file():\n                    return dest\n\n    raise FileNotFoundError(\n        \"Notebook 01 output not found. Add Notebook 01 output as a Kaggle input \"\n        \"or set STAGE1_DIR.\"\n    )\n\n\nROOT = find_train_root()\nWEIGHTS = find_weights()\nSTAGE1 = find_stage1()\nDINO = find_dinov2(\"small\")\n\nlog(f\"competition root: {ROOT}\")\nlog(f\"base weights: {WEIGHTS}\")\nlog(f\"stage1 input: {STAGE1}\")\nlog(f\"DINOv2: {DINO}\")\n\nif DINO is None:\n    raise FileNotFoundError(\n        \"DINOv2-small Hugging Face model directory not found. \"\n        \"Attach the same DINO input used by the old notebook.\"\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-11T20:01:40.086312Z","iopub.execute_input":"2026-08-11T20:01:40.08667Z","iopub.status.idle":"2026-08-11T20:01:40.372042Z","shell.execute_reply.started":"2026-08-11T20:01:40.086648Z","shell.execute_reply":"2026-08-11T20:01:40.371216Z"}},"outputs":[],"execution_count":null},{"id":"49564b29","cell_type":"markdown","source":"## 1. Validate Notebook 01 handoff\n\nNo historical fold map was found in your actual Notebook 01 run. Therefore this stage creates a **new expert-CV split** and records that fact in every checkpoint. It does not relabel this split as the original folds.","metadata":{}},{"id":"85c53bca","cell_type":"code","source":"stage1_status = json.loads((STAGE1 / \"stage1_status.json\").read_text())\nresume_manifest = json.loads((STAGE1 / \"resume_manifest.json\").read_text())\nexpert = pd.read_csv(STAGE1 / \"expert_complete_12.csv\", dtype={\"StudyInstanceUID\": str})\n\nif not stage1_status.get(\"stage1_ok\", False):\n    raise RuntimeError(\"Stage 1 did not report stage1_ok=True\")\n\nif len(expert) < 20:\n    raise RuntimeError(f\"Expected the expert-labelled subset; found only {len(expert)} rows\")\n\nmissing = [t for t in TARGETS if t not in expert.columns]\nif missing:\n    raise KeyError(f\"expert_complete_12.csv missing targets: {missing}\")\n\nif expert[TARGETS].isna().any().any():\n    raise RuntimeError(\"Notebook 02 expects complete expert labels in expert_complete_12.csv\")\n\nprint(\"Stage 1 historical fold map verified:\", stage1_status.get(\"has_verified_original_fold_map\"))\nprint(\"Expert studies:\", len(expert))\nprint(\"Fine-tuning validation mode: NEW_EXPERT_CV (not historical OOF)\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-11T20:01:40.373458Z","iopub.execute_input":"2026-08-11T20:01:40.373774Z","iopub.status.idle":"2026-08-11T20:01:40.38756Z","shell.execute_reply.started":"2026-08-11T20:01:40.373751Z","shell.execute_reply":"2026-08-11T20:01:40.38674Z"}},"outputs":[],"execution_count":null},{"id":"2b4b12e6","cell_type":"markdown","source":"## 2. Load manifest, select FT-A starting members, and auto-match the slot scheme","metadata":{}},{"id":"750d8de3","cell_type":"code","source":"base_manifest = json.loads((WEIGHTS / \"manifest.json\").read_text())\nmembers = base_manifest[\"members\"]\n\ndef choose_members(members, mode):\n    frame = pd.DataFrame([\n        {\n            \"idx\": i,\n            \"id\": m.get(\"id\"),\n            \"fold\": int(m.get(\"fold\")),\n            \"holdout\": float(m.get(\"holdout\") or -1),\n        }\n        for i, m in enumerate(members)\n    ])\n    frame = frame.sort_values([\"fold\", \"holdout\"], ascending=[True, False])\n\n    if mode == \"champions\":\n        keep = frame.groupby(\"fold\", as_index=False).head(1)\n    elif mode == \"top2\":\n        keep = frame.groupby(\"fold\", as_index=False).head(2)\n    elif mode == \"all20\":\n        keep = frame\n    else:\n        raise ValueError(\"FT_MEMBER_MODE must be champions, top2, or all20\")\n\n    return [members[int(i)] for i in keep[\"idx\"].tolist()]\n\n\nselected_members = choose_members(members, FT_MEMBER_MODE)\nprint(\"FT_MEMBER_MODE:\", FT_MEMBER_MODE)\nprint(\"selected members:\", len(selected_members))\n\ndisplay(pd.DataFrame([\n    {\"id\": m[\"id\"], \"base_fold\": m.get(\"fold\"), \"holdout\": m.get(\"holdout\"), \"file\": m[\"file\"]}\n    for m in selected_members\n]).sort_values([\"base_fold\", \"holdout\"], ascending=[True, False]))\n\n\ndef slot_scheme_for_names(names):\n    names = list(names)\n    rec = [x[0] for x in SLOTS_RECOVERED]\n    pub = [x[0] for x in SLOTS_PUBLIC]\n    if names == rec:\n        return SLOTS_RECOVERED\n    if names == pub:\n        return SLOTS_PUBLIC\n    raise WeightsError(f\"Unknown checkpoint slot scheme: {names}\")\n\n\ndef adopt_config_globals(cfg):\n    global IMG, CACHE_IMG, GROUP, CACHE_SLICES, N_GROUP, CROP_MM\n    global SLICE_BAND, RULES, SLOTS, N_SLOT\n\n    CACHE_IMG = IMG = int(cfg[\"img\"])\n    GROUP = int(cfg[\"group\"])\n    CACHE_SLICES = int(cfg[\"slices\"])\n    N_GROUP = max(CACHE_SLICES // GROUP, 1)\n    CROP_MM = float(cfg[\"crop_mm\"])\n    SLICE_BAND = tuple(float(x) for x in cfg[\"band\"])\n\n    rules = cfg.get(\"rules\") or RULES_NATIVE\n    unknown = {\n        k: v for k, v in rules.items()\n        if k not in RULES_NATIVE or v not in (RULES_NATIVE[k], RULES_LEGACY[k])\n    }\n    if unknown:\n        raise WeightsError(f\"unsupported pixel rules in manifest: {unknown}\")\n    RULES = {**RULES_NATIVE, **rules}\n\n    SLOTS = slot_scheme_for_names(cfg[\"slots\"])\n    N_SLOT = len(SLOTS)\n\n\npixel_groups = {}\nfor m in selected_members:\n    pixel_groups.setdefault(m[\"pixel_group\"], []).append(m)\n\nprint(\"selected pixel groups:\", len(pixel_groups))\nfor k, gm in pixel_groups.items():\n    cfg = json.loads(k)\n    print(\n        f\"- {cfg['img']}px, slices={cfg['slices']}, group={cfg['group']}, \"\n        f\"crop={cfg['crop_mm']}mm -> {len(gm)} selected member(s)\"\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-11T20:01:40.38892Z","iopub.execute_input":"2026-08-11T20:01:40.389317Z","iopub.status.idle":"2026-08-11T20:01:40.414651Z","shell.execute_reply.started":"2026-08-11T20:01:40.389282Z","shell.execute_reply":"2026-08-11T20:01:40.414113Z"}},"outputs":[],"execution_count":null},{"id":"11791aa5","cell_type":"markdown","source":"## 3. Reuse the checkpoint-compatible MRI preprocessing\n\nThe following functions come from the old inference pipeline so FT-A sees the same sequence selection, slice ordering, crop, intensity normalization, and laterality convention as the checkpoint it starts from.","metadata":{}},{"id":"3ef7c59e","cell_type":"code","source":"HDR_TAGS = [\"SeriesDescription\", \"SequenceName\", \"ScanOptions\", \"ScanningSequence\",\n            \"RepetitionTime\", \"EchoTime\", \"Laterality\", \"PixelSpacing\", \"Rows\",\n            \"Columns\", \"RescaleSlope\", \"RescaleIntercept\",\n            # Position and orientation are read from the same header probe() already\n            # opens, so they cost nothing, and they are what recovers the side when the\n            # Laterality tag is absent - which it is for half the studies here.\n            \"ImagePositionPatient\", \"ImageOrientationPatient\"]\n\n\ndef _hdr_vec(s, n):\n    \"\"\"Parse a DICOM multi-value string as stored by probe(): floats joined by `|`.\"\"\"\n    if not isinstance(s, str):\n        return None\n    try:\n        v = [float(x) for x in s.split(\"|\")]\n    except ValueError:\n        return None\n    return np.array(v) if len(v) >= n else None\n\n\ndef side_from_geometry(h):\n    \"\"\"Study -> 'L' / 'R' / None, from where the image sits in the patient.\n\n    `Laterality` (0020,0060) is Type 2C and may legitimately be absent; in this corpus it\n    is missing on exactly half the studies, and the vendors it is missing from are whole\n    vendors rather than scattered series. A study with no tag is not a left knee, but the\n    normalisation upstream treats it as one, so half the corpus was never normalised and\n    the five side-defined targets - the two menisci, the two tibiofemoral compartments\n    and the medial collateral ligament - saw that axis reversed on a large minority of it.\n\n    The patient coordinate system fixes this without the tag: +x is the patient's left, so\n    the centre of a right knee sits at negative x. The centre is used rather than\n    `ImagePositionPatient` itself because that is the corner of the image, which is offset\n    by half a field of view - enough to change the sign on a knee near the midline.\n\n    The median over a study's series is what is thresholded, not a single series: probe()\n    reads one arbitrary slice per series, which on a sagittal stack can sit anywhere\n    across the joint. Studies whose centre falls near the midline are left unresolved\n    rather than guessed - measured against the tagged half, the rule is right 97% of the\n    time overall and no better than chance inside 20 mm.\n    \"\"\"\n    cx = {}\n    for r in h.itertuples(index=False):\n        ipp = _hdr_vec(getattr(r, \"ImagePositionPatient\", None), 3)\n        iop = _hdr_vec(getattr(r, \"ImageOrientationPatient\", None), 6)\n        ps = _hdr_vec(getattr(r, \"PixelSpacing\", None), 2)\n        rows, cols = getattr(r, \"Rows\", None), getattr(r, \"Columns\", None)\n        if ipp is None or iop is None or ps is None or not rows or not cols:\n            continue\n        try:\n            c = ipp[:3] + iop[:3] * ps[1] * float(cols) / 2 + iop[3:6] * ps[0] * float(rows) / 2\n        except (TypeError, ValueError):\n            continue\n        cx.setdefault(r.StudyInstanceUID, []).append(float(c[0]))\n    out = {}\n    for st, xs in cx.items():\n        m = float(np.median(xs))\n        out[st] = None if abs(m) < LAT_MIN_OFFSET_MM else (\"R\" if m < 0 else \"L\")\n    return out\n\n\ndef side_from_corner_x(h):\n    \"\"\"The laterality an imported member was fitted under.\n\n    It thresholds the median raw `ImagePositionPatient` x over a study's series. That is\n    the x of the image *corner*, not of its centre, so it differs from the rule above by\n    up to half a field of view - which is enough to reverse the sign on a knee scanned\n    near the midline. The dead zone is 5 mm rather than 20 mm, so it also commits on\n    studies the rule above leaves unresolved.\n\n    Neither difference changes a shape. Each one decides whether a study is mirrored, and\n    a study mirrored one way at training and the other at inference presents the five\n    side-defined targets with their axis reversed.\n    \"\"\"\n    out = {}\n    for st, g in h.groupby(\"StudyInstanceUID\"):\n        xs = []\n        for r in g.itertuples(index=False):\n            ipp = _hdr_vec(getattr(r, \"ImagePositionPatient\", None), 3)\n            if ipp is not None and np.isfinite(ipp).all():\n                xs.append(float(ipp[0]))\n        if not xs:\n            out[st] = None\n            continue\n        x = float(np.median(xs))\n        # DICOM patient coordinates are LPS: +x is the patient's left.\n        out[st] = None if abs(x) < LEGACY_LAT_OFFSET_MM else (\"R\" if x < 0 else \"L\")\n    return out\n\n\ndef lat_of(h, tag=\"\"):\n    \"\"\"Study -> 'L' / 'R' / None: the tag where it exists, geometry where it does not.\n\n    The tag is present on exactly half the studies here and is sometimes an empty\n    string rather than absent, which is not the same as NaN. Treating the other half\n    as left-sided is what `normalise_laterality` did by omission, so the geometry\n    fallback is not a refinement - it is the difference between normalising half the\n    corpus and normalising all of it.\n    \"\"\"\n    geo = side_from_corner_x(h) if RULES[\"lat\"] == \"corner_x\" else side_from_geometry(h)\n    d, n_tag, n_geo, n_none, n_disagree = {}, 0, 0, 0, 0\n    for st, g in h.groupby(\"StudyInstanceUID\"):\n        v = [str(x).strip().upper() for x in g[\"Laterality\"].dropna()]\n        if RULES[\"lat\"] == \"corner_x\" and \"ImageLaterality\" in g.columns:\n            # The legacy rule reads the second tag too, so a study tagged only there is\n            # resolved from the tag rather than from geometry.\n            v += [str(x).strip().upper() for x in g[\"ImageLaterality\"].dropna()]\n        v = [x[0] for x in v if x and x[0] in (\"L\", \"R\")]\n        side = v[0] if v else None\n        if side is not None:\n            n_tag += 1\n            if geo.get(st) is not None and geo[st] != side:\n                n_disagree += 1\n        else:\n            side = geo.get(st)\n            n_geo += side is not None\n            n_none += side is None\n        d[st] = side\n    log(f\"{tag}laterality: {n_tag} from the tag, {n_geo} from geometry, \"\n        f\"{n_none} unresolved; tag and geometry disagree on {n_disagree} \"\n        f\"({n_disagree / max(n_tag, 1):.1%} of the tagged)\")\n    return d\n\n\n\ndef probe(item):\n    split, study, series, path = item\n    row = {\"split\": split, \"StudyInstanceUID\": study, \"SeriesInstanceUID\": series,\n           \"dir\": path}\n    try:\n        files = sorted(e.name for e in os.scandir(path) if e.name.endswith(\".dcm\"))\n        row[\"files\"] = files\n        row[\"n_slices\"] = len(files)\n        if not files:\n            return row\n        ds = pydicom.dcmread(os.path.join(path, files[len(files) // 2]),\n                             stop_before_pixels=True, force=True)\n        for t in HDR_TAGS:\n            v = getattr(ds, t, None)\n            if v is None:\n                row[t] = None\n            elif isinstance(v, (list, tuple)) or type(v).__name__ == \"MultiValue\":\n                row[t] = \"|\".join(str(x) for x in v)\n            else:\n                row[t] = str(v)\n    except Exception as exc:\n        row[\"err\"] = str(exc)[:120]\n    return row\n\n\ndef walk(split):\n    \"\"\"Every series directory of a split, with one header read per series.\n\n    An absent split returns an empty frame *with the columns annotate expects*. Returning\n    a bare DataFrame looks like the same thing and is not: the next call indexes\n    `SeriesDescription` and raises KeyError, so the branch that exists to survive a\n    missing split is what turns it into a crash.\n    \"\"\"\n    base = ROOT / split\n    items = []\n    if not base.is_dir():\n        return pd.DataFrame(columns=[\"split\", \"StudyInstanceUID\", \"SeriesInstanceUID\",\n                                     \"dir\", \"files\", \"n_slices\"] + HDR_TAGS)\n    for study in os.scandir(base):\n        if study.is_dir():\n            for series in os.scandir(study.path):\n                if series.is_dir():\n                    items.append((split, study.name, series.name, series.path))\n    with ThreadPoolExecutor(max_workers=HDR_THREADS) as pool:\n        rows = list(pool.map(probe, items))\n    return pd.DataFrame(rows)\n\n\ndef annotate(df):\n    \"\"\"Recover fat suppression and pulse-sequence weighting from the header.\"\"\"\n    desc = (df[\"SeriesDescription\"].fillna(\"\") + \" \" + df[\"SequenceName\"].fillna(\"\"))\n    desc = desc.str.lower().str.replace(_SEP, \" \", regex=True)\n\n    opts = df[\"ScanOptions\"].fillna(\"\").str.upper().str.split(\"|\")\n    # GE writes SAT_GEMS for spatial saturation, so ScanOptions must be matched as\n    # exact tokens; a substring test on \"SAT\" fires on non-fat-sat series.\n    opts_fs = opts.apply(lambda ts: any(t.strip() in FATSAT_OPTS for t in ts))\n    df[\"fatsat\"] = desc.str.contains(_FATSAT_RX) | opts_fs\n\n    tr = pd.to_numeric(df[\"RepetitionTime\"], errors=\"coerce\")\n    te = pd.to_numeric(df[\"EchoTime\"], errors=\"coerce\")\n    gre = df[\"ScanningSequence\"].fillna(\"\").str.upper().str.contains(\"GR\")\n    t1, t2, pdw = desc.str.contains(_T1_RX), desc.str.contains(_T2_RX), desc.str.contains(_PD_RX)\n\n    df[\"weight\"] = np.where(t1 & ~t2 & ~pdw, \"T1\",\n                     np.where(t2 & ~pdw, \"T2\",\n                       np.where(pdw, \"PD\",\n                         np.where(gre, \"GRE\",\n                           np.where(tr < 800, \"T1\",\n                             np.where(te > 60, \"T2\",\n                               np.where(tr >= 800, \"PD\", \"UNK\")))))))\n    df[\"fluid\"] = np.isin(df[\"weight\"], [\"PD\", \"T2\"])\n    df[\"px\"] = pd.to_numeric(\n        df[\"PixelSpacing\"].fillna(\"\").str.split(\"|\").str[0].replace(\"\", np.nan),\n        errors=\"coerce\")\n    return df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-11T20:01:40.416211Z","iopub.execute_input":"2026-08-11T20:01:40.416424Z","iopub.status.idle":"2026-08-11T20:01:40.439032Z","shell.execute_reply.started":"2026-08-11T20:01:40.416402Z","shell.execute_reply":"2026-08-11T20:01:40.438225Z"}},"outputs":[],"execution_count":null},{"id":"affce9c1","cell_type":"code","source":"def walk_selected(split, study_ids):\n    study_ids = {str(x) for x in study_ids}\n    base = ROOT / split\n    items = []\n\n    if not base.is_dir():\n        raise FileNotFoundError(base)\n\n    for study_id in sorted(study_ids):\n        study_dir = base / study_id\n        if not study_dir.is_dir():\n            continue\n        for series in os.scandir(study_dir):\n            if series.is_dir():\n                items.append((split, study_id, series.name, series.path))\n\n    with ThreadPoolExecutor(max_workers=HDR_THREADS) as pool:\n        rows = list(pool.map(probe, items))\n\n    out = pd.DataFrame(rows)\n    if out.empty:\n        raise RuntimeError(f\"No DICOM series found for {len(study_ids)} selected studies\")\n    return out","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-11T20:01:40.439914Z","iopub.execute_input":"2026-08-11T20:01:40.440218Z","iopub.status.idle":"2026-08-11T20:01:40.456772Z","shell.execute_reply.started":"2026-08-11T20:01:40.440197Z","shell.execute_reply":"2026-08-11T20:01:40.455899Z"}},"outputs":[],"execution_count":null},{"id":"ab755544","cell_type":"code","source":"def _as_bool(v):\n    if pd.isna(v):\n        return None\n    s = str(v).strip().upper()\n    if s in {\"1\", \"TRUE\", \"T\", \"YES\", \"Y\"}:\n        return True\n    if s in {\"0\", \"FALSE\", \"F\", \"NO\", \"N\"}:\n        return False\n    try:\n        f = float(s)\n        return True if f == 1 else False if f == 0 else None\n    except Exception:\n        return None\n\n\ndef audit_official_sequence_metadata(inferred, official):\n    \"\"\"Audit only. Do not change imported checkpoint pixels from this table.\"\"\"\n    need = {\"SeriesInstanceUID\", \"Fluid_Sensitive\", \"Fat_Suppression\"}\n    if inferred.empty or official.empty or not need.issubset(official.columns):\n        return\n    a = inferred[[\"SeriesInstanceUID\", \"fluid\", \"fatsat\"]].copy()\n    b = official[[\"SeriesInstanceUID\", \"Fluid_Sensitive\", \"Fat_Suppression\"]].copy()\n    b[\"official_fluid\"] = b[\"Fluid_Sensitive\"].map(_as_bool)\n    b[\"official_fatsat\"] = b[\"Fat_Suppression\"].map(_as_bool)\n    m = a.merge(b[[\"SeriesInstanceUID\", \"official_fluid\", \"official_fatsat\"]],\n                on=\"SeriesInstanceUID\", how=\"inner\")\n    for inferred_col, official_col, name in [\n        (\"fluid\", \"official_fluid\", \"Fluid_Sensitive\"),\n        (\"fatsat\", \"official_fatsat\", \"Fat_Suppression\"),\n    ]:\n        valid = m[official_col].notna() & m[inferred_col].notna()\n        if valid.any():\n            agree = (m.loc[valid, inferred_col].astype(bool).values ==\n                     m.loc[valid, official_col].astype(bool).values).mean()\n            log(f\"metadata audit {name}: {agree:.1%} agreement on {int(valid.sum())} series\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-11T20:01:40.457734Z","iopub.execute_input":"2026-08-11T20:01:40.458096Z","iopub.status.idle":"2026-08-11T20:01:40.470864Z","shell.execute_reply.started":"2026-08-11T20:01:40.458064Z","shell.execute_reply":"2026-08-11T20:01:40.470025Z"}},"outputs":[],"execution_count":null},{"id":"49cdc87f","cell_type":"code","source":"def pick_slots(series_df, plane_map):\n    \"\"\"One series per slot per study.\n\n    Ties are broken toward the stack with the most slices: a thicker stack samples the\n    joint more densely, and the three-slice sampler below benefits from the margin.\n    \"\"\"\n    series_df = series_df.copy()\n    series_df[\"plane\"] = series_df[\"SeriesInstanceUID\"].map(plane_map)\n    out = {}\n    for study, g in series_df.groupby(\"StudyInstanceUID\"):\n        chosen = {}\n        for name, plane, fluid, fs in SLOTS:\n            sel = (g[\"plane\"] == plane) & (g[\"fatsat\"] == fs)\n            # fluid=None means \"do not condition on weighting\" - the public scheme,\n            # where the single provided flag stands in for both axes at once.\n            if fluid is not None:\n                sel &= (g[\"fluid\"] == fluid)\n            cand = g[sel]\n            # A slot with no series matching its predicate stays empty, and no substitute\n            # is admitted from a neighbouring predicate. Relaxing the weighting to fill a\n            # T1 slot would draw from the pool `SAG_FLUID_NOFS` selects from, since that\n            # pool is what remains once the weighting is dropped: over the training corpus\n            # it would put one series in two slots for 2383 of 4407 studies and leave 56%\n            # of the T1 slot holding PD or T2. The presence mask would then assert a\n            # sequence that was never acquired, and the per-diagnosis softmax of §6 would\n            # divide its attention across two identical slots, giving one acquisition\n            # about twice the weight it carries in a study that holds both. The mask is\n            # there to say a slot is absent, which is what an absent slot is.\n            if len(cand) == 0 and RULES[\"slot_fallback\"] and fluid is False:\n                # The relaxation the paragraph above rejects, reproduced because an\n                # imported member was fitted with its T1 slots filled this way: over half\n                # of that member's training studies had a T1 slot holding a series that\n                # is not T1. Leaving those slots empty would present it with a presence\n                # mask it never saw.\n                cand = g[(g[\"plane\"] == plane) & (~g[\"fatsat\"])]\n            if len(cand):\n                chosen[name] = cand.sort_values(\"n_slices\", ascending=False).iloc[0]\n        out[study] = chosen\n    return out","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-11T20:01:40.471767Z","iopub.execute_input":"2026-08-11T20:01:40.47219Z","iopub.status.idle":"2026-08-11T20:01:40.487318Z","shell.execute_reply.started":"2026-08-11T20:01:40.472161Z","shell.execute_reply":"2026-08-11T20:01:40.48674Z"}},"outputs":[],"execution_count":null},{"id":"54b5e785","cell_type":"code","source":"ORDER_TAGS = [(0x0020, 0x0032), (0x0020, 0x0037), (0x0020, 0x0013)]\n\n# Series in which at least one sampled slice would not decode. A list rather than a\n# counter because appending is atomic under the reader threads, and reported rather than\n# swallowed: unreported, a decode failure is indistinguishable from a black knee.\nDECODE_FAILED = []\n\n\ndef cache_tag(rules=None):\n    \"\"\"The name a decoded cache is stored under.\n\n    It has to name everything that decides the pixels, not only their dimensions. Two\n    configurations that agree on resolution, slice count, crop and band but disagree on\n    how a slice is chosen produce different arrays of identical shape - so a tag built\n    from the dimensions alone lets the second attach to the first one's file and train\n    against pixels it never asked for, with nothing anywhere reporting a mismatch.\n\n    A native reading keeps the plain name, so caches decoded before the rules existed\n    stay valid; anything else earns a suffix.\n    \"\"\"\n    r = dict(RULES if rules is None else rules)\n    t = (f\"{CACHE_IMG}px_{CACHE_SLICES}sl_{int(CROP_MM)}mm_\"\n         f\"{SLICE_BAND[0]:.2f}-{SLICE_BAND[1]:.2f}\")\n    if {k: r.get(k, v) for k, v in RULES_NATIVE.items()} != RULES_NATIVE:\n        t += \"_\" + hashlib.md5(json.dumps(r, sort_keys=True).encode()).hexdigest()[:6]\n    return t\n\n\ndef _natural_key(name):\n    return tuple(int(x) if x.isdigit() else x.lower()\n                 for x in re.split(r\"(\\d+)\", str(name)))\n\n\ndef _order_dominant_axis(rec):\n    \"\"\"The slice order an imported member was fitted under.\n\n    It sorts on the raw patient coordinate along whichever axis varies most across the\n    stack, rather than on the projection onto the slice normal. The two differ by a sign,\n    not by a formula: measured over this corpus every sagittal series has a slice normal\n    with n_x in [-1.00, -0.98], so p.n is the negative of the raw x this sorts on and the\n    two stacks come out exactly reversed. Because the band sampler truncates rather than\n    rounds, its nine indices are not symmetric about the middle, so nine slices drawn from\n    a twenty-six slice stack under one order share two with the other.\n\n    Missing geometry falls back to `InstanceNumber` and then to a natural sort of the file\n    name, both at the same 80% threshold the imported pipeline used.\n    \"\"\"\n    files, d = rec[\"files\"], rec[\"dir\"]\n    rows = []\n    for pos, f in enumerate(files):\n        ipp = inst = None\n        try:\n            ds = pydicom.dcmread(os.path.join(d, f), force=True, stop_before_pixels=True,\n                                 specific_tags=[\"ImagePositionPatient\", \"InstanceNumber\"])\n            raw = getattr(ds, \"ImagePositionPatient\", None)\n            if raw is not None and len(raw) >= 3:\n                c = np.asarray(raw[:3], dtype=np.float64)\n                if np.isfinite(c).all():\n                    ipp = c\n            n = getattr(ds, \"InstanceNumber\", None)\n            if n is not None:\n                inst = float(n)\n        except Exception:\n            pass\n        rows.append((f, ipp, inst, pos))\n\n    placed = [r for r in rows if r[1] is not None]\n    need = max(2, int(0.8 * len(rows)))\n    if len(placed) >= need:\n        xyz = np.stack([r[1] for r in placed])\n        axis = int(np.argmax(np.ptp(xyz, axis=0)))\n        spare = float(np.nanmedian(xyz[:, axis]))\n        rows.sort(key=lambda r: (float(r[1][axis]) if r[1] is not None else spare,\n                                 r[2] if r[2] is not None else float(\"inf\"), r[3]))\n    elif sum(r[2] is not None for r in rows) >= need:\n        rows.sort(key=lambda r: (r[2] if r[2] is not None else float(\"inf\"), r[3]))\n    else:\n        rows.sort(key=lambda r: _natural_key(r[0]))\n    return [r[0] for r in rows], True\n\n\ndef order_slices(rec):\n    \"\"\"Return the series' files sorted along the through-plane axis.\n\n    A DICOM file name here is a SOP Instance UID, which is assigned arbitrarily. Sorting\n    by it therefore produces an order uncorrelated with anatomy - measured over one\n    series, Spearman between file-name rank and physical position is 0.009, i.e. none.\n    Anything that assumes the file order means something is then operating on noise: the\n    three channels of a \"2.5D\" input are three unrelated views rather than neighbouring\n    slices, \"the middle of the stack\" is a random subset, and reversing slice order to\n    normalise laterality reverses nothing meaningful.\n\n    The physical order is recoverable exactly. Each slice carries its position in patient\n    coordinates and the in-plane axes; projecting the position onto the slice normal\n    gives a signed through-plane coordinate, monotonic along the stack:\n\n        n = r_x  x  r_y ,      k = p . n\n\n    `InstanceNumber` is the fallback. It usually tracks the projection up to sign, but\n    interleaved and multi-echo acquisitions need not number slices in the order they\n    occupy in space - but the projection is signed in patient\n    coordinates, which is what laterality normalisation needs.\n    \"\"\"\n    if RULES[\"order\"] == \"dominant_axis\":\n        return _order_dominant_axis(rec)\n    files, d = rec[\"files\"], rec[\"dir\"]\n    keyed = []\n    for f in files:\n        k = None\n        try:\n            ds = pydicom.dcmread(os.path.join(d, f), force=True, stop_before_pixels=True,\n                                 specific_tags=ORDER_TAGS)\n            iop = np.asarray(ds.ImageOrientationPatient, dtype=float)\n            ipp = np.asarray(ds.ImagePositionPatient, dtype=float)\n            k = float(np.dot(ipp, np.cross(iop[:3], iop[3:])))\n        except Exception:\n            try:\n                k = float(ds.InstanceNumber)\n            except Exception:\n                k = None\n        keyed.append((k, f))\n    if any(k is None for k, _ in keyed):\n        # A series with no usable geometry keeps its arbitrary order; that is worse than\n        # sorting but better than dropping the series, and it is logged as a count.\n        return files, False\n    return [f for _, f in sorted(keyed, key=lambda t: t[0])], True\n\n\ndef read_slot(rec, n_slice=None, out_size=None):\n    \"\"\"`n_slice` physically spread slices from one series, at `out_size` pixels.\n\n    Returns uint8 [n_slice, out, out] normalised per-series to its 1st-99th\n    percentile. Percentiles rather than min/max because MR intensity has no absolute\n    scale and a single bright vessel would otherwise compress the whole dynamic range.\n\n    Reading is the expensive half of this pipeline, so the caller reads once at the\n    largest configuration it needs and derives the smaller ones from the returned buffer\n    rather than re-reading.\n    \"\"\"\n    n_slice = GROUP if n_slice is None else n_slice\n    out_size = IMG if out_size is None else out_size\n    files, d, px = rec.get(\"ordered\") or rec[\"files\"], rec[\"dir\"], rec[\"px\"]\n    n = len(files)\n    if n == 0:\n        return None\n    # Spread the samples over a central band of the stack: the outermost slices of a knee\n    # series are mostly soft tissue outside the joint. The band is a constant rather than\n    # a literal because how much of the stack is worth reading depends on how many slices\n    # are being taken - at three the middle is all that fits, while at sixteen the ends\n    # are worth having, and a Baker cyst sits at the posteromedial end of a sagittal one.\n    lo, hi = int(SLICE_BAND[0] * (n - 1)), int(SLICE_BAND[1] * (n - 1))\n    idx = np.unique(np.linspace(lo, hi, n_slice).astype(int)) if hi > lo else np.array([n // 2])\n    while len(idx) < n_slice:\n        idx = np.append(idx, idx[-1])\n\n    planes = []\n    for i in idx[:n_slice]:\n        try:\n            ds = pydicom.dcmread(os.path.join(d, files[int(i)]), force=True)\n            a = ds.pixel_array.astype(np.float32)\n            sl = float(getattr(ds, \"RescaleSlope\", 1) or 1)\n            ic = float(getattr(ds, \"RescaleIntercept\", 0) or 0)\n            a = a * sl + ic\n        except Exception:\n            a = None                      # no shape is known here; see below\n        planes.append(a)\n\n    # A slice that would not decode has no shape of its own, and inventing one is how a\n    # single unreadable file erases a whole series: a substitute allocated at the resize\n    # target while the decoded slices are still native makes the shape check below take\n    # the substitute as the authority and zero the good slices with it, leaving a black\n    # slot that the presence mask still reports as acquired.\n    #\n    # A failure is instead filled from the nearest slice that did decode - the same\n    # convention the sampler already uses when the band holds fewer distinct slices than\n    # were asked for - and a series where nothing decodes is reported absent, which the\n    # mask can express, rather than black, which it cannot.\n    got = [k for k, p in enumerate(planes) if p is not None]\n    if RULES[\"decode_fill\"] == \"zero\":\n        # What an imported member was fitted with: a failure becomes a zero plane at the\n        # resize target, which the shape check below then propagates to the whole slot.\n        # It is the behaviour the paragraph above describes and rejects, kept here only\n        # because that member's weights were learned against slots blacked out this way.\n        if not got:\n            DECODE_FAILED.append(rec.get(\"SeriesInstanceUID\", d))\n        planes = [np.zeros((out_size, out_size), np.float32) if p is None else p\n                  for p in planes]\n        got = list(range(len(planes)))\n    if not got:\n        DECODE_FAILED.append(rec.get(\"SeriesInstanceUID\", d))\n        return None\n    if len(got) < len(planes):\n        DECODE_FAILED.append(rec.get(\"SeriesInstanceUID\", d))\n        for k, p in enumerate(planes):\n            if p is None:\n                planes[k] = planes[min(got, key=lambda j: abs(j - k))]\n\n    # Slices of one series can still differ in matrix size - multi-echo and some\n    # reformats do - and those are genuinely not stackable.\n    shp = planes[0].shape\n    planes = [p if p.shape == shp else np.zeros(shp, np.float32) for p in planes]\n    vol = np.stack(planes)\n\n    # constant physical extent, then resize: PixelSpacing varies 3.4x across the corpus\n    if px and np.isfinite(px) and px > 0:\n        want = int(round(CROP_MM / px))\n        h, w = shp\n        if 16 < want < min(h, w):\n            cy, cx = h // 2, w // 2\n            half = want // 2\n            vol = vol[:, max(0, cy - half):cy + half, max(0, cx - half):cx + half]\n\n    lo_v, hi_v = np.percentile(vol, [1, 99])\n    vol = np.clip((vol - lo_v) / max(hi_v - lo_v, 1e-6), 0, 1)\n\n    t = torch.from_numpy(np.ascontiguousarray(vol)).unsqueeze(0)\n    t = F.interpolate(t, size=(out_size, out_size), mode=\"bilinear\", align_corners=False)\n    # uint8, not float32. These buffers queue up between the reader threads and the\n    # encoder, and at this size a float32 slot-series is several megabytes. Intensity is\n    # already normalised into [0, 1] here, so eight bits cost nothing that a bilinear\n    # resize has not already cost, and the queue is a quarter the size.\n    return (t.squeeze(0) * 255).round().clamp(0, 255).to(torch.uint8)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-11T20:01:40.489036Z","iopub.execute_input":"2026-08-11T20:01:40.489543Z","iopub.status.idle":"2026-08-11T20:01:40.516534Z","shell.execute_reply.started":"2026-08-11T20:01:40.489521Z","shell.execute_reply":"2026-08-11T20:01:40.515549Z"}},"outputs":[],"execution_count":null},{"id":"967fa64c","cell_type":"code","source":"def normalise_laterality(img, plane, lat):\n    \"\"\"Map every knee onto a left-knee convention.\n\n    Coronal and axial views mirror under a horizontal flip. Sagittal stacks are not\n    mirror images of each other - the slice order runs medial-to-lateral in opposite\n    directions - so the channel order is reversed instead.\n    \"\"\"\n    if lat != \"R\":\n        return img\n    if plane in (\"Coronal\", \"Axial\"):\n        return torch.flip(img, dims=[-1])\n    return torch.flip(img, dims=[0])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-11T20:01:40.517372Z","iopub.execute_input":"2026-08-11T20:01:40.517954Z","iopub.status.idle":"2026-08-11T20:01:40.532477Z","shell.execute_reply.started":"2026-08-11T20:01:40.517918Z","shell.execute_reply":"2026-08-11T20:01:40.531894Z"}},"outputs":[],"execution_count":null},{"id":"494a60e0","cell_type":"code","source":"# Where the geometric slice order may be remembered between runs. Unset on the platform,\n# because each run gets a fresh machine and there is nothing to remember; set off it,\n# where the same corpus is cached again at every resolution and slice count and the order\n# is a function of neither. It is opt-in so that the scored run's behaviour is decided by\n# the code rather than by whether a file happens to be lying about.\nORDER_CACHE = os.environ.get(\"RSNA_ORDER_CACHE\") or None\n\n\ndef build_cache(slot_map, plane_map, lat_map, tag):\n    \"\"\"Decode every (study, slot) once into an in-memory uint8 array.\n\n    Fine-tuning revisits the same pixels every epoch. Reading them from the mount each\n    time would make the epoch count a function of I/O rather than of learning, so they\n    are decoded once and held as bytes: intensity has already been normalised into\n    [0, 1], and eight bits cost nothing a bilinear resize has not already cost.\n\n    CACHE_SLICES positions are kept per slot, which the training loop reads as N_GROUP\n    groups of GROUP consecutive channels.\n    \"\"\"\n    studies = sorted(slot_map)\n    sidx = {s: i for i, s in enumerate(studies)}\n    cache = np.zeros((len(studies), N_SLOT, CACHE_SLICES, IMG, IMG), np.uint8)\n    mask = np.zeros((len(studies), N_SLOT), np.float32)\n    log(f\"{tag}: cache {cache.shape} = {cache.nbytes / 1024 ** 3:.1f} GB\")\n\n    jobs = [(st, k, plane, slot_map[st][name])\n            for st in studies\n            for k, (name, plane, _, _) in enumerate(SLOTS)\n            if name in slot_map[st]]\n    n_job = len(jobs)\n\n    # Ordering first, and as its own pass. It reads one header per slice of every chosen\n    # series - far more file opens than the decode that follows - and on a network mount\n    # that is latency, not work, so it gets its own wider pool.\n    t_ord = time.time()\n    n_slice_total = sum(len(j[3][\"files\"]) for j in jobs)\n    log(f\"{tag}: ordering {len(jobs)} slot-series ({n_slice_total} slice headers)\")\n    ok = done = 0\n    CHUNK_O = 1024\n\n    # A remembered order, when one is offered. The projection depends on the DICOM\n    # geometry alone, so it is the same at every resolution and every slice count, and\n    # it costs one header read per slice - the largest single cost in this pass. An entry\n    # is validated by the number of files present, so a tree that has changed under it is\n    # recomputed rather than trusted: order is derived data, and a stale entry would be\n    # invisible in the way that matters most.\n    seen = {}\n    if ORDER_CACHE and Path(ORDER_CACHE).is_file():\n        try:\n            import json as _json\n            seen = _json.loads(Path(ORDER_CACHE).read_text())\n        except (OSError, ValueError):\n            seen = {}\n        hit = 0\n        for _, _, _, rec in jobs:\n            e = seen.get(rec[\"SeriesInstanceUID\"])\n            if e and len(e[\"files\"]) == len(rec[\"files\"]):\n                rec[\"ordered\"] = e[\"files\"]\n                ok += int(e[\"good\"])\n                hit += 1\n        jobs = [j for j in jobs if \"ordered\" not in j[3]]\n        log(f\"{tag}: {hit} slot-series ordered from {ORDER_CACHE}, {len(jobs)} to read\")\n\n    with ThreadPoolExecutor(max_workers=ORDER_THREADS) as pool:\n        for c0 in range(0, len(jobs), CHUNK_O):\n            block = jobs[c0:c0 + CHUNK_O]\n            for (_, _, _, rec), (files, good) in zip(\n                    block, pool.map(lambda j: order_slices(j[3]), block)):\n                rec[\"ordered\"] = files\n                ok += int(good)\n                done += 1\n                if ORDER_CACHE:\n                    seen[rec[\"SeriesInstanceUID\"]] = {\"files\": files, \"good\": bool(good)}\n            # The ceiling is whichever comes first: the pass's own budget, or the share\n            # of what is left of the run that it may take. The second is what makes the\n            # first safe to set generously - a mount slow enough to matter cannot spend\n            # the training time, because the budget shrinks as the run does.\n            budget = min(ORDER_BUDGET_S, max(60.0, (TIME_BUDGET - (time.time() - T0)) * 0.35))\n            if time.time() - t_ord > budget:\n                log(f\"{tag}: ordering budget spent at {done}/{len(jobs)}; \"\n                    f\"the rest keep file order\")\n                break\n    if ORDER_CACHE and done:\n        import json as _json\n        _t = Path(ORDER_CACHE).with_suffix(\".tmp\")\n        _t.write_text(_json.dumps(seen))\n        _t.replace(Path(ORDER_CACHE))\n    log(f\"{tag}: ordered {ok}/{n_job} by geometry \"\n        f\"({n_job - ok} kept arbitrary) in {time.time() - t_ord:.0f}s\")\n\n    jobs = [(st, k, plane, slot_map[st][name])\n            for st in studies\n            for k, (name, plane, _, _) in enumerate(SLOTS)\n            if name in slot_map[st]]\n    log(f\"{tag}: decoding {len(jobs)} slot-series\")\n    n_failed_before = len(DECODE_FAILED)\n\n    CHUNK = 512\n    done = 0\n    with ThreadPoolExecutor(max_workers=PIX_THREADS) as pool:\n        for c0 in range(0, len(jobs), CHUNK):\n            block = jobs[c0:c0 + CHUNK]\n            for (st, k, plane, _), img in zip(\n                    block, pool.map(lambda j: read_slot(j[3], CACHE_SLICES, IMG), block)):\n                done += 1\n                if img is None:\n                    continue\n                cache[sidx[st], k] = normalise_laterality(img, plane,\n                                                          lat_map.get(st)).numpy()\n                mask[sidx[st], k] = 1.0\n            if done % 4096 < CHUNK:\n                log(f\"  {tag} {done}/{len(jobs)}\")\n            if time.time() - T0 > TIME_BUDGET:\n                log(f\"  {tag}: time budget reached during decode\")\n                break\n    n_failed = len(DECODE_FAILED) - n_failed_before\n    log(f\"{tag}: {int(mask.sum())}/{len(jobs)} slots filled\"\n        + (f\"; {n_failed} series had a slice that would not decode\" if n_failed else \"\"))\n    gc.collect()\n    return studies, cache, mask","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-11T20:01:40.5346Z","iopub.execute_input":"2026-08-11T20:01:40.534933Z","iopub.status.idle":"2026-08-11T20:01:40.552153Z","shell.execute_reply.started":"2026-08-11T20:01:40.534912Z","shell.execute_reply":"2026-08-11T20:01:40.551436Z"}},"outputs":[],"execution_count":null},{"id":"af366781","cell_type":"markdown","source":"## 4. Checkpoint-compatible DINOv2 model","metadata":{}},{"id":"fd36bec2","cell_type":"code","source":"class SlotHead(nn.Module):\n    \"\"\"Per-diagnosis attention over the slot embeddings of one study.\n\n    Each finding is read on particular sequences - cruciates sagittally, collateral\n    ligaments and the meniscal body coronally, patellar cartilage axially - so pooling\n    the slots identically would dilute the one that carries the evidence with the rest.\n\n    The aggregation is deliberately this simple. With a study-level label there is no\n    signal telling the model which part of a study matters, so extra attention\n    parameters below the slot level would have nothing to learn from and would spend\n    their capacity fitting noise.\n    \"\"\"\n\n    def __init__(self, dim, n_slot, n_out, hidden=256, p=0.2, prior=False):\n        super().__init__()\n        self.proj = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, hidden), nn.GELU())\n        self.slot_emb = nn.Parameter(torch.randn(n_slot, hidden) * 0.02)\n        self.query = nn.Parameter(torch.randn(n_out, hidden) * 0.02)\n        self.drop = nn.Dropout(p)\n        self.out = nn.Linear(hidden, n_out)\n        self.hidden = hidden\n        # An imported member carries a fixed per-(diagnosis, slot) tilt on the attention\n        # logits, set from the anatomy table below rather than learned. It is a buffer, so\n        # it travels in the state dict and must exist for that member to load; exp(0.55)\n        # gives a preferred slot about 1.73x the weight of an unpreferred one, which\n        # biases the softmax without ever excluding a slot.\n        p_ = torch.zeros(n_out, n_slot)\n        if prior and n_slot == len(SLOTS) and n_out == len(TARGETS):\n            for t, slots in SLOT_PRIOR_TABLE.items():\n                if t in TARGETS:\n                    p_[TARGETS.index(t), list(slots)] = SLOT_PRIOR_STRENGTH\n        self.prior = prior\n        if prior:\n            self.register_buffer(\"slot_prior\", p_)\n\n    def forward(self, x, mask):\n        h = self.proj(x) + self.slot_emb\n        att = torch.einsum(\"bsh,oh->bos\", h, self.query) / self.hidden ** 0.5\n        if self.prior:\n            att = att + self.slot_prior.unsqueeze(0)\n        att = att.masked_fill(mask.unsqueeze(1) < 0.5, -1e4).softmax(-1)\n        ctx = self.drop(torch.einsum(\"bos,bsh->boh\", att, h))\n        return (ctx * self.out.weight.unsqueeze(0)).sum(-1) + self.out.bias","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-11T20:01:40.552991Z","iopub.execute_input":"2026-08-11T20:01:40.553343Z","iopub.status.idle":"2026-08-11T20:01:40.569246Z","shell.execute_reply.started":"2026-08-11T20:01:40.553302Z","shell.execute_reply":"2026-08-11T20:01:40.568357Z"}},"outputs":[],"execution_count":null},{"id":"acc1c31b","cell_type":"code","source":"class Model(nn.Module):\n    \"\"\"Encoder plus head, trained end to end.\n\n    A study arrives as a bag of slot images. The bag is flattened for the encoder and\n    folded back before the head, so the encoder never sees the study structure and the\n    head never sees pixels.\n    \"\"\"\n\n    def __init__(self, backbone, dim, pool=\"cls_mean\", prior=False):\n        super().__init__()\n        self.backbone = backbone\n        self.pool = pool\n        self.head = SlotHead(dim * POOL_PARTS[pool], N_SLOT, len(TARGETS), prior=prior)\n        self.register_buffer(\"mean\", torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1))\n        self.register_buffer(\"std\", torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1))\n\n    def forward(self, imgs, mask, img_size=None):\n        B, S = imgs.shape[:2]\n        x = imgs.reshape(B * S, *imgs.shape[2:]).float().div_(255.0)\n        if img_size is not None and img_size != x.shape[-1]:\n            # The cache is held at the highest resolution any configuration needs; the\n            # rest downsample from it, so every configuration sees the same pixels\n            # through a different sampling grid rather than a different crop.\n            x = F.interpolate(x, size=(img_size, img_size), mode=\"bilinear\",\n                              align_corners=False)\n        x = (x - self.mean) / self.std\n        out = self.backbone(pixel_values=x).last_hidden_state\n        patch = out[:, 1:]\n        parts = [out[:, 0], patch.mean(1)]\n        if self.pool == \"cls_mean_focal\":\n            # The upper tail of each channel over the patch grid, taken per channel\n            # rather than by selecting whole patches: a finding occupies a small part of\n            # the field, so a plain mean over 256 patches dilutes it by two orders of\n            # magnitude, and this keeps the top eighth of each channel's responses.\n            k = max(1, patch.shape[1] // 8)\n            parts.append(patch.topk(k, dim=1).values.mean(1))\n        feat = torch.cat(parts, dim=1).reshape(B, S, -1)\n        return self.head(feat, mask)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-11T20:01:40.570253Z","iopub.execute_input":"2026-08-11T20:01:40.570616Z","iopub.status.idle":"2026-08-11T20:01:40.585773Z","shell.execute_reply.started":"2026-08-11T20:01:40.570568Z","shell.execute_reply":"2026-08-11T20:01:40.584914Z"}},"outputs":[],"execution_count":null},{"id":"5e6824ec","cell_type":"code","source":"def build_model(unfreeze_last, source=None, variant=\"small\", pool=\"cls_mean\", prior=False):\n    from transformers import AutoModel\n\n    p = Path(source) if source is not None else DINO\n    if p is None:\n        raise FileNotFoundError(\"DINOv2 weights not attached\")\n\n    bb = AutoModel.from_pretrained(str(p))\n    n_layer = len(bb.encoder.layer)\n\n    for prm in bb.parameters():\n        prm.requires_grad = False\n    for blk in bb.encoder.layer[max(0, n_layer - int(unfreeze_last)):]:\n        for prm in blk.parameters():\n            prm.requires_grad = True\n    for prm in bb.layernorm.parameters():\n        prm.requires_grad = True\n\n    dim = bb.config.hidden_size\n    trainable = sum(p.numel() for p in bb.parameters() if p.requires_grad)\n    log(\n        f\"backbone: {n_layer} blocks, last {unfreeze_last} trainable \"\n        f\"({trainable / 1e6:.1f}M backbone params)\"\n    )\n    return Model(bb, dim, pool=pool, prior=prior)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-11T20:01:40.586673Z","iopub.execute_input":"2026-08-11T20:01:40.586988Z","iopub.status.idle":"2026-08-11T20:01:40.602309Z","shell.execute_reply.started":"2026-08-11T20:01:40.586962Z","shell.execute_reply":"2026-08-11T20:01:40.601476Z"}},"outputs":[],"execution_count":null},{"id":"b7449b8a","cell_type":"markdown","source":"## 5. Fingerprint contract + frontier validation prediction","metadata":{}},{"id":"313f0b9c","cell_type":"code","source":"FINGERPRINT_TOL = 2e-3\n\ndef fingerprint(model, dev, img_size, n_slot=None, group=None, seed=None):\n    n_slot = N_SLOT if n_slot is None else n_slot\n    group = GROUP if group is None else group\n    seed = SEED if seed is None else seed\n\n    g = torch.Generator().manual_seed(seed)\n    imgs = torch.randint(\n        0, 256, (2, n_slot, group, img_size, img_size),\n        generator=g, dtype=torch.uint8\n    ).to(dev)\n    mask = torch.ones(2, n_slot, device=dev)\n    mask[1, -1] = 0.0\n\n    was_training = model.training\n    model.eval()\n    with torch.no_grad():\n        out = model(imgs, mask, img_size).float().cpu().numpy()\n    if was_training:\n        model.train()\n    return out\n\n\ndef check_fingerprint(model, dev, img_size, expected, tol=FINGERPRINT_TOL, tag=\"\"):\n    got = fingerprint(model, dev, img_size)\n    exp = np.asarray(expected, np.float32)\n    if got.shape != exp.shape:\n        raise WeightsError(f\"{tag}fingerprint shape {got.shape} != stored {exp.shape}\")\n    d = float(np.abs(got - exp).max())\n    if d > tol:\n        raise WeightsError(\n            f\"{tag}fingerprint differs by {d:.4g} > {tol:g}; \"\n            \"architecture/preprocessing contract moved\"\n        )\n    log(f\"{tag}base fingerprint matches within {d:.2g}\")\n    return d\n\n\ndef window_starts(n_slice, group):\n    if n_slice >= group:\n        return list(range(n_slice - group + 1))\n    return [0]\n\n\ndef _apply_frontier_pool(probs):\n    v = probs.mean(dim=0)\n    target_idx = {t: j for j, t in enumerate(TARGETS)}\n    for target, mode in FRONTIER_TARGET_POOL.items():\n        j = target_idx[target]\n        x = probs[:, :, j]\n        if mode == \"max\":\n            v[:, j] = x.max(dim=0).values\n        elif mode.startswith(\"top\"):\n            k = min(int(mode[3:]), x.shape[0])\n            v[:, j] = x.topk(k, dim=0).values.mean(dim=0)\n        elif mode == \"mean\":\n            v[:, j] = x.mean(dim=0)\n        else:\n            raise ValueError(mode)\n    return v\n\n\n@torch.no_grad()\ndef predict_member_frontier(model, cache, mask, idx, dev, img_size):\n    starts = window_starts(cache.shape[2], GROUP)\n    model.eval()\n    pred = np.empty((len(idx), len(TARGETS)), np.float32)\n\n    for b0 in range(0, len(idx), EVAL_BATCH):\n        sel = np.asarray(idx[b0:b0 + EVAL_BATCH], dtype=int)\n        b1 = b0 + len(sel)\n        m = torch.from_numpy(mask[sel]).to(dev)\n        win = []\n\n        for st in starts:\n            rows = torch.from_numpy(\n                np.ascontiguousarray(cache[sel, :, st:st + GROUP])\n            ).to(dev)\n            with torch.autocast(device_type=dev.type, enabled=dev.type == \"cuda\"):\n                logits = model(rows, m, img_size).float()\n            win.append(torch.sigmoid(logits))\n\n        probs = torch.stack(win, dim=0)\n        pred[b0:b1] = _apply_frontier_pool(probs).cpu().numpy()\n\n    return pred","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-11T20:01:40.603282Z","iopub.execute_input":"2026-08-11T20:01:40.603601Z","iopub.status.idle":"2026-08-11T20:01:40.619742Z","shell.execute_reply.started":"2026-08-11T20:01:40.60358Z","shell.execute_reply":"2026-08-11T20:01:40.61903Z"}},"outputs":[],"execution_count":null},{"id":"fc30acb0","cell_type":"markdown","source":"## 6. Build a new deterministic 5-fold split inside the 58 expert labels\n\nThis is **FT-stage CV**, not the original model's historical CV. The split is greedily balanced across the 12 positive labels so rare findings are spread as evenly as possible.","metadata":{}},{"id":"8ae7f1f9","cell_type":"code","source":"Y_expert = expert[TARGETS].to_numpy(np.float32)\n\ndef make_balanced_multilabel_folds(y, n_folds=5, seed=2026):\n    y = np.asarray(y, np.float32)\n    n, t = y.shape\n    rng = np.random.default_rng(seed)\n\n    total_pos = y.sum(axis=0)\n    rarity = 1.0 / np.maximum(total_pos, 1.0)\n    priority = (y * rarity).sum(axis=1) + 0.01 * y.sum(axis=1)\n    priority += rng.uniform(0, 1e-6, size=n)\n    order = np.argsort(-priority)\n\n    target_pos = total_pos / n_folds\n    target_size = n / n_folds\n    fold_pos = np.zeros((n_folds, t), np.float64)\n    fold_size = np.zeros(n_folds, np.int64)\n    assignment = np.full(n, -1, np.int64)\n\n    max_size = int(math.ceil(n / n_folds))\n\n    for i in order:\n        scores = []\n        for f in range(n_folds):\n            if fold_size[f] >= max_size:\n                scores.append(float(\"inf\"))\n                continue\n            new_pos = fold_pos[f] + y[i]\n            pos_err = np.sum(\n                ((new_pos - target_pos) ** 2) / np.maximum(target_pos, 0.5)\n            )\n            size_err = ((fold_size[f] + 1 - target_size) ** 2) / max(target_size, 1)\n            # Slight deterministic jitter prevents pathological repeated ties.\n            scores.append(pos_err + 0.15 * size_err + 1e-7 * f)\n\n        f = int(np.argmin(scores))\n        assignment[i] = f\n        fold_pos[f] += y[i]\n        fold_size[f] += 1\n\n    return assignment\n\n\nexpert = expert.copy()\nexpert[\"ft_fold\"] = make_balanced_multilabel_folds(\n    expert[TARGETS].to_numpy(np.float32),\n    n_folds=FT_N_FOLDS,\n    seed=SEED,\n)\n\nexpert.to_csv(OUT / \"expert_ft_fold_map.csv\", index=False)\n\nprint(\"FT fold sizes:\")\ndisplay(expert.groupby(\"ft_fold\").size().rename(\"n\").to_frame())\n\nfold_pos = expert.groupby(\"ft_fold\")[TARGETS].sum().T\nfold_pos[\"TOTAL\"] = expert[TARGETS].sum()\ndisplay(fold_pos)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-11T20:01:40.620672Z","iopub.execute_input":"2026-08-11T20:01:40.620952Z","iopub.status.idle":"2026-08-11T20:01:40.661346Z","shell.execute_reply.started":"2026-08-11T20:01:40.62092Z","shell.execute_reply":"2026-08-11T20:01:40.660798Z"}},"outputs":[],"execution_count":null},{"id":"2b39a487","cell_type":"markdown","source":"## 7. Decode only the 58 expert studies, once per checkpoint pixel group","metadata":{}},{"id":"23dd6790","cell_type":"code","source":"train_series = pd.read_csv(\n    ROOT / \"train_series.csv\",\n    dtype={\"StudyInstanceUID\": str, \"SeriesInstanceUID\": str},\n)\nplane_map = dict(zip(\n    train_series[\"SeriesInstanceUID\"].astype(str),\n    train_series[\"Anatomical_Plane\"],\n))\n\nexpert_ids = expert[\"StudyInstanceUID\"].astype(str).tolist()\nhtr = annotate(walk_selected(\"train_series\", expert_ids))\nlog(f\"expert header pass: {len(htr)} series across {htr['StudyInstanceUID'].nunique()} studies\")\n\ngroup_cache = {}\n\nfor gi, (pixel_key, gm) in enumerate(pixel_groups.items(), 1):\n    cfg = json.loads(pixel_key)\n    adopt_config_globals(cfg)\n    log(\n        f\"decode group {gi}/{len(pixel_groups)}: \"\n        f\"{IMG}px, {CACHE_SLICES} slices, group={GROUP}, crop={CROP_MM}mm\"\n    )\n\n    slot_map = pick_slots(htr, plane_map)\n    studies, cache, slot_mask = build_cache(\n        slot_map,\n        plane_map,\n        lat_of(htr, f\"expert g{gi} \"),\n        f\"expert g{gi}\",\n    )\n\n    group_cache[pixel_key] = {\n        \"studies\": studies,\n        \"cache\": cache,\n        \"slot_mask\": slot_mask,\n        \"cfg\": cfg,\n    }\n\n    log(\n        f\"g{gi}: cache {cache.shape}, slot coverage \"\n        f\"{slot_mask.sum():.0f}/{slot_mask.size}\"\n    )\n\nprint(\"cached pixel groups:\", len(group_cache))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-11T20:01:40.662152Z","iopub.execute_input":"2026-08-11T20:01:40.662434Z","iopub.status.idle":"2026-08-11T20:02:16.042595Z","shell.execute_reply.started":"2026-08-11T20:01:40.662403Z","shell.execute_reply":"2026-08-11T20:02:16.04201Z"}},"outputs":[],"execution_count":null},{"id":"66df3265","cell_type":"markdown","source":"## 8. Training utilities: masked balanced BCE, tiny LR, rollback gate","metadata":{}},{"id":"933ee51a","cell_type":"code","source":"def align_labels(studies):\n    e = expert.set_index(\"StudyInstanceUID\").loc[list(studies)]\n    y = e[TARGETS].to_numpy(np.float32)\n    mask = np.isfinite(y).astype(np.float32)\n    y = np.nan_to_num(y, nan=0.0)\n    folds = e[\"ft_fold\"].to_numpy(np.int64)\n    return y, mask, folds\n\n\ndef make_pos_weight(y, label_mask, idx):\n    yy = y[idx]\n    mm = label_mask[idx]\n    pos = (yy * mm).sum(axis=0)\n    known = mm.sum(axis=0)\n    neg = known - pos\n\n    # Conservative balancing: sqrt ratio, clipped to avoid huge gradients on rare targets.\n    ratio = np.sqrt((neg + 0.5) / (pos + 0.5))\n    ratio = np.clip(ratio, 1.0, 3.0)\n    return torch.tensor(ratio, dtype=torch.float32)\n\n\ndef masked_bce_logits(logits, y, mask, pos_weight):\n    per = F.binary_cross_entropy_with_logits(\n        logits, y, reduction=\"none\", pos_weight=pos_weight\n    )\n    return (per * mask).sum() / mask.sum().clamp_min(1.0)\n\n\ndef prob_bce(pred, y, mask):\n    p = np.clip(np.asarray(pred, np.float64), 1e-6, 1 - 1e-6)\n    y = np.asarray(y, np.float64)\n    m = np.asarray(mask, np.float64)\n    per = -(y * np.log(p) + (1 - y) * np.log(1 - p))\n    return float((per * m).sum() / max(m.sum(), 1.0))\n\n\ndef macro_auc(pred, y, mask):\n    vals = []\n    per_target = {}\n    for j, t in enumerate(TARGETS):\n        valid = mask[:, j] > 0.5\n        yy = y[valid, j]\n        pp = pred[valid, j]\n        if len(np.unique(yy)) < 2:\n            per_target[t] = np.nan\n            continue\n        a = float(roc_auc_score(yy, pp))\n        per_target[t] = a\n        vals.append(a)\n    return (float(np.mean(vals)) if vals else np.nan), per_target\n\n\ndef optimizer_for(model):\n    head = [p for p in model.head.parameters() if p.requires_grad]\n    backbone = [p for p in model.backbone.parameters() if p.requires_grad]\n\n    return torch.optim.AdamW(\n        [\n            {\"params\": head, \"lr\": FT_HEAD_LR},\n            {\"params\": backbone, \"lr\": FT_BACKBONE_LR},\n        ],\n        weight_decay=FT_WEIGHT_DECAY,\n    )\n\n\ndef train_one_epoch(model, cache, slot_mask, y, label_mask, train_idx, dev, optimizer, scaler, pos_weight, epoch_seed):\n    model.train()\n    rng = np.random.default_rng(epoch_seed)\n    order = np.asarray(train_idx, dtype=int).copy()\n    rng.shuffle(order)\n\n    optimizer.zero_grad(set_to_none=True)\n    losses = []\n    n_steps = math.ceil(len(order) / FT_BATCH)\n\n    for step, b0 in enumerate(range(0, len(order), FT_BATCH), 1):\n        sel = order[b0:b0 + FT_BATCH]\n        starts = rng.integers(\n            0,\n            max(cache.shape[2] - GROUP + 1, 1),\n            size=len(sel),\n        )\n\n        x_np = np.stack(\n            [cache[i, :, int(st):int(st) + GROUP] for i, st in zip(sel, starts)],\n            axis=0,\n        )\n        x = torch.from_numpy(np.ascontiguousarray(x_np)).to(dev)\n        sm = torch.from_numpy(slot_mask[sel]).to(dev)\n        yy = torch.from_numpy(y[sel]).to(dev)\n        lm = torch.from_numpy(label_mask[sel]).to(dev)\n\n        with torch.autocast(device_type=dev.type, enabled=dev.type == \"cuda\"):\n            logits = model(x, sm, IMG)\n            loss = masked_bce_logits(logits, yy, lm, pos_weight.to(dev))\n            loss = loss / FT_GRAD_ACCUM\n\n        scaler.scale(loss).backward()\n        losses.append(float(loss.detach().cpu()) * FT_GRAD_ACCUM)\n\n        if step % FT_GRAD_ACCUM == 0 or step == n_steps:\n            scaler.unscale_(optimizer)\n            torch.nn.utils.clip_grad_norm_(\n                [p for p in model.parameters() if p.requires_grad],\n                max_norm=1.0,\n            )\n            scaler.step(optimizer)\n            scaler.update()\n            optimizer.zero_grad(set_to_none=True)\n\n    return float(np.mean(losses)) if losses else np.nan\n\n\ndef cpu_state_dict(model):\n    return {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-11T20:02:16.043644Z","iopub.execute_input":"2026-08-11T20:02:16.044181Z","iopub.status.idle":"2026-08-11T20:02:16.060667Z","shell.execute_reply.started":"2026-08-11T20:02:16.044157Z","shell.execute_reply":"2026-08-11T20:02:16.059973Z"}},"outputs":[],"execution_count":null},{"id":"b771597c","cell_type":"markdown","source":"## 9. Conservative FT-A loop\n\nDefault behavior creates 5 new checkpoints: the best-holdout starting member from each original fold. A base member's fold number is used only to choose which **new expert fold** is held out during its FT-A stage.\n\nThe promotion rule starts from the original checkpoint as the best state. If fine-tuning never beats the base validation BCE, the saved FT-A checkpoint rolls back to the original weights.","metadata":{}},{"id":"5c99025f","cell_type":"code","source":"dev = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nlog(f\"device: {dev}\")\n\nmetrics_rows = []\nnew_members = []\n\n# For stage-level cross-validated diagnostics.\nexpert_uid_order = expert[\"StudyInstanceUID\"].astype(str).tolist()\nuid_to_global = {u: i for i, u in enumerate(expert_uid_order)}\noof_base_sum = np.zeros((len(expert), len(TARGETS)), np.float64)\noof_ft_sum = np.zeros_like(oof_base_sum)\noof_count = np.zeros(len(expert), np.int64)\n\nfor mi, m in enumerate(selected_members, 1):\n    if time.time() - T0 > TIME_BUDGET:\n        log(\"time budget reached before all selected members were processed\")\n        break\n\n    pixel_key = m[\"pixel_group\"]\n    pack = group_cache[pixel_key]\n    pixel_cfg = pack[\"cfg\"]\n    member_cfg = m.get(\"config\") or {}\n    adopt_config_globals(pixel_cfg)\n\n    studies = pack[\"studies\"]\n    cache = pack[\"cache\"]\n    slot_mask = pack[\"slot_mask\"]\n    y, label_mask, ft_folds = align_labels(studies)\n\n    # Historical fold ID is not a study mapping. We only use its 0..4 identity\n    # to choose a distinct new expert-CV validation partition.\n    val_fold = int(m.get(\"fold\")) % FT_N_FOLDS\n    train_idx = np.where(ft_folds != val_fold)[0]\n    val_idx = np.where(ft_folds == val_fold)[0]\n\n    if len(train_idx) == 0 or len(val_idx) == 0:\n        raise RuntimeError(f\"Empty train/val split for FT fold {val_fold}\")\n\n    log(\n        f\"[{mi}/{len(selected_members)}] {m['id']} base-fold={m.get('fold')} \"\n        f\"-> FT-val-fold={val_fold}; train={len(train_idx)}, val={len(val_idx)}\"\n    )\n\n    ck_path = WEIGHTS / m[\"file\"]\n    ck = torch.load(ck_path, map_location=\"cpu\", weights_only=False)\n\n    model = build_model(\n        FT_UNFREEZE_LAST,\n        source=DINO,\n        variant=member_cfg.get(\"variant\", \"small\"),\n        pool=member_cfg.get(\"pool\", \"cls_mean\"),\n        prior=bool(member_cfg.get(\"prior\", False)),\n    ).to(dev)\n\n    model.load_state_dict(ck[\"model\"], strict=True)\n\n    if \"fingerprint\" in ck:\n        check_fingerprint(model, dev, IMG, ck[\"fingerprint\"], tag=f\"{m['id']}: \")\n\n    base_pred = predict_member_frontier(model, cache, slot_mask, val_idx, dev, IMG)\n    base_loss = prob_bce(base_pred, y[val_idx], label_mask[val_idx])\n    base_auc, _ = macro_auc(base_pred, y[val_idx], label_mask[val_idx])\n\n    best_loss = base_loss\n    best_auc = base_auc\n    best_epoch = 0\n    best_state = None\n    best_pred = base_pred.copy()\n\n    pos_weight = make_pos_weight(y, label_mask, train_idx)\n    optimizer = optimizer_for(model)\n    def lr_factor(ep):\n        if FT_MAX_EPOCHS <= 1:\n            return 1.0\n        x = min(max(ep, 0), FT_MAX_EPOCHS)\n        return max(0.10, 0.5 * (1.0 + math.cos(math.pi * x / FT_MAX_EPOCHS)))\n\n    scheduler = torch.optim.lr_scheduler.LambdaLR(\n        optimizer, lr_lambda=[lr_factor, lr_factor]\n    )\n    scaler = torch.amp.GradScaler(\"cuda\", enabled=dev.type == \"cuda\")\n\n    stale = 0\n    history = []\n\n    for epoch in range(1, FT_MAX_EPOCHS + 1):\n        train_loss = train_one_epoch(\n            model,\n            cache,\n            slot_mask,\n            y,\n            label_mask,\n            train_idx,\n            dev,\n            optimizer,\n            scaler,\n            pos_weight,\n            epoch_seed=SEED + 1000 * mi + epoch,\n        )\n\n        val_pred = predict_member_frontier(\n            model, cache, slot_mask, val_idx, dev, IMG\n        )\n        val_loss = prob_bce(val_pred, y[val_idx], label_mask[val_idx])\n        val_auc, _ = macro_auc(val_pred, y[val_idx], label_mask[val_idx])\n\n        history.append({\n            \"epoch\": epoch,\n            \"train_loss\": train_loss,\n            \"val_bce\": val_loss,\n            \"val_macro_auc\": val_auc,\n            \"head_lr\": optimizer.param_groups[0][\"lr\"],\n            \"backbone_lr\": optimizer.param_groups[1][\"lr\"],\n        })\n\n        log(\n            f\"  epoch {epoch}: train={train_loss:.5f}, \"\n            f\"val_bce={val_loss:.5f}, val_auc={val_auc:.4f}\"\n        )\n\n        if val_loss < best_loss - FT_MIN_DELTA:\n            best_loss = val_loss\n            best_auc = val_auc\n            best_epoch = epoch\n            best_state = cpu_state_dict(model)\n            best_pred = val_pred.copy()\n            stale = 0\n        else:\n            stale += 1\n\n        scheduler.step()\n\n        if stale >= FT_PATIENCE:\n            log(f\"  early stop after epoch {epoch}; no promotion for {stale} epoch(s)\")\n            break\n\n    promoted = best_epoch > 0\n\n    if promoted:\n        model.load_state_dict(best_state, strict=True)\n    else:\n        model.load_state_dict(ck[\"model\"], strict=True)\n        best_loss = base_loss\n        best_auc = base_auc\n        best_pred = base_pred.copy()\n\n    # Recompute a fingerprint for the exact state that will be handed to the next notebook.\n    new_fp = fingerprint(model, dev, IMG).tolist()\n    final_state = cpu_state_dict(model)\n\n    new_id = f\"{m['id']}_fta\"\n    new_file = f\"fta_{m['id']}.pt\"\n\n    new_ck = dict(ck)\n    new_ck[\"model\"] = final_state\n    new_ck[\"fingerprint\"] = new_fp\n    new_ck[\"ft_stage\"] = \"FT-A_CONSERVATIVE\"\n    new_ck[\"parent_id\"] = m[\"id\"]\n    new_ck[\"parent_file\"] = m[\"file\"]\n    new_ck[\"ft_validation_mode\"] = \"NEW_EXPERT_CV_NOT_HISTORICAL_OOF\"\n    new_ck[\"ft_val_fold\"] = val_fold\n    new_ck[\"ft_train_n\"] = int(len(train_idx))\n    new_ck[\"ft_val_n\"] = int(len(val_idx))\n    new_ck[\"ft_unfreeze_last\"] = FT_UNFREEZE_LAST\n    new_ck[\"ft_best_epoch\"] = int(best_epoch)\n    new_ck[\"ft_promoted\"] = bool(promoted)\n    new_ck[\"ft_base_val_bce\"] = float(base_loss)\n    new_ck[\"ft_best_val_bce\"] = float(best_loss)\n    new_ck[\"ft_base_val_macro_auc\"] = float(base_auc) if np.isfinite(base_auc) else None\n    new_ck[\"ft_best_val_macro_auc\"] = float(best_auc) if np.isfinite(best_auc) else None\n    new_ck[\"ft_history\"] = history\n\n    torch.save(new_ck, OUT / new_file)\n\n    nm = dict(m)\n    nm[\"id\"] = new_id\n    nm[\"file\"] = new_file\n    nm[\"ft_stage\"] = \"FT-A_CONSERVATIVE\"\n    nm[\"parent_id\"] = m[\"id\"]\n    nm[\"parent_file\"] = m[\"file\"]\n    nm[\"ft_val_fold\"] = val_fold\n    nm[\"ft_promoted\"] = bool(promoted)\n    nm[\"ft_best_epoch\"] = int(best_epoch)\n    nm[\"ft_base_val_bce\"] = float(base_loss)\n    nm[\"ft_best_val_bce\"] = float(best_loss)\n    nm[\"ft_best_val_macro_auc\"] = float(best_auc) if np.isfinite(best_auc) else None\n    new_members.append(nm)\n\n    # Aggregate new expert-CV predictions. With champions mode count=1 per study;\n    # with top2/all20 the same validation fold gets multiple diverse member votes.\n    for local_pos, cache_idx in enumerate(val_idx):\n        uid = studies[int(cache_idx)]\n        g = uid_to_global[uid]\n        oof_base_sum[g] += base_pred[local_pos]\n        oof_ft_sum[g] += best_pred[local_pos]\n        oof_count[g] += 1\n\n    metrics_rows.append({\n        \"parent_id\": m[\"id\"],\n        \"new_id\": new_id,\n        \"base_fold\": int(m.get(\"fold\")),\n        \"ft_val_fold\": val_fold,\n        \"base_holdout\": float(m.get(\"holdout\") or np.nan),\n        \"train_n\": len(train_idx),\n        \"val_n\": len(val_idx),\n        \"base_val_bce\": base_loss,\n        \"best_val_bce\": best_loss,\n        \"delta_bce\": best_loss - base_loss,\n        \"base_val_macro_auc\": base_auc,\n        \"best_val_macro_auc\": best_auc,\n        \"best_epoch\": best_epoch,\n        \"promoted\": promoted,\n    })\n\n    del model, ck, final_state, best_state\n    gc.collect()\n    if dev.type == \"cuda\":\n        torch.cuda.empty_cache()\n\nmetrics = pd.DataFrame(metrics_rows)\nmetrics.to_csv(OUT / \"ft_a_member_metrics.csv\", index=False)\ndisplay(metrics)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-11T20:02:16.061654Z","iopub.execute_input":"2026-08-11T20:02:16.062488Z","iopub.status.idle":"2026-08-11T20:03:52.93044Z","shell.execute_reply.started":"2026-08-11T20:02:16.062455Z","shell.execute_reply":"2026-08-11T20:03:52.929701Z"}},"outputs":[],"execution_count":null},{"id":"70d5ef4f","cell_type":"markdown","source":"## 10. Stage-level expert-CV diagnostic and handoff manifest","metadata":{}},{"id":"cae765b0","cell_type":"code","source":"valid = oof_count > 0\nif not valid.all():\n    missing_uids = expert.loc[~valid, \"StudyInstanceUID\"].tolist()\n    print(\"WARNING: some expert studies received no validation prediction:\", len(missing_uids))\n\nbase_oof = np.full_like(oof_base_sum, np.nan)\nft_oof = np.full_like(oof_ft_sum, np.nan)\nbase_oof[valid] = oof_base_sum[valid] / oof_count[valid, None]\nft_oof[valid] = oof_ft_sum[valid] / oof_count[valid, None]\n\noof_frame = expert[[\"StudyInstanceUID\", \"ft_fold\", *TARGETS]].copy()\noof_frame[\"n_member_votes\"] = oof_count\n\nfor j, t in enumerate(TARGETS):\n    oof_frame[f\"base__{t}\"] = base_oof[:, j]\n    oof_frame[f\"fta__{t}\"] = ft_oof[:, j]\n\noof_frame.to_csv(OUT / \"expert_cv_predictions.csv\", index=False)\n\nif valid.any():\n    y_all = expert.loc[valid, TARGETS].to_numpy(np.float32)\n    mask_all = np.ones_like(y_all, np.float32)\n\n    base_cv_bce = prob_bce(base_oof[valid], y_all, mask_all)\n    ft_cv_bce = prob_bce(ft_oof[valid], y_all, mask_all)\n\n    base_cv_auc, base_per = macro_auc(base_oof[valid], y_all, mask_all)\n    ft_cv_auc, ft_per = macro_auc(ft_oof[valid], y_all, mask_all)\n\n    target_diag = pd.DataFrame({\n        \"target\": TARGETS,\n        \"base_auc\": [base_per[t] for t in TARGETS],\n        \"fta_auc\": [ft_per[t] for t in TARGETS],\n    })\n    target_diag[\"delta_auc\"] = target_diag[\"fta_auc\"] - target_diag[\"base_auc\"]\n    target_diag.to_csv(OUT / \"expert_cv_target_auc.csv\", index=False)\n\n    print(f\"Expert-CV base BCE: {base_cv_bce:.6f}\")\n    print(f\"Expert-CV FT-A BCE: {ft_cv_bce:.6f}\")\n    print(f\"Expert-CV base macro AUC: {base_cv_auc:.6f}\")\n    print(f\"Expert-CV FT-A macro AUC: {ft_cv_auc:.6f}\")\n    display(target_diag)\nelse:\n    base_cv_bce = ft_cv_bce = base_cv_auc = ft_cv_auc = np.nan\n\nhistory = base_manifest.get(\"history\")\nif not isinstance(history, list):\n    history = [] if history is None else [history]\n\nstage2_history = history + [{\n    \"stage\": \"FT-A_CONSERVATIVE\",\n    \"seed\": SEED,\n    \"member_mode\": FT_MEMBER_MODE,\n    \"n_output_members\": len(new_members),\n    \"expert_n\": len(expert),\n    \"validation_mode\": \"NEW_EXPERT_CV_NOT_HISTORICAL_OOF\",\n    \"ft_unfreeze_last\": FT_UNFREEZE_LAST,\n    \"max_epochs\": FT_MAX_EPOCHS,\n    \"patience\": FT_PATIENCE,\n    \"head_lr\": FT_HEAD_LR,\n    \"backbone_lr\": FT_BACKBONE_LR,\n    \"expert_cv_base_bce\": None if not np.isfinite(base_cv_bce) else float(base_cv_bce),\n    \"expert_cv_fta_bce\": None if not np.isfinite(ft_cv_bce) else float(ft_cv_bce),\n    \"expert_cv_base_macro_auc\": None if not np.isfinite(base_cv_auc) else float(base_cv_auc),\n    \"expert_cv_fta_macro_auc\": None if not np.isfinite(ft_cv_auc) else float(ft_cv_auc),\n}]\n\nnew_manifest = {\n    \"format\": base_manifest.get(\"format\"),\n    \"targets\": TARGETS,\n    \"history\": stage2_history,\n    \"members\": new_members,\n}\n\n(OUT / \"manifest.json\").write_text(json.dumps(new_manifest, indent=2))\n\nstatus2 = {\n    \"stage2_ok\": len(new_members) > 0,\n    \"stage\": \"FT-A_CONSERVATIVE\",\n    \"member_mode\": FT_MEMBER_MODE,\n    \"n_output_members\": len(new_members),\n    \"n_promoted\": int(metrics[\"promoted\"].sum()) if len(metrics) else 0,\n    \"n_rolled_back_to_base\": int((~metrics[\"promoted\"]).sum()) if len(metrics) else 0,\n    \"validation_mode\": \"NEW_EXPERT_CV_NOT_HISTORICAL_OOF\",\n    \"strict_historical_oof_available\": False,\n    \"expert_cv_base_bce\": None if not np.isfinite(base_cv_bce) else float(base_cv_bce),\n    \"expert_cv_fta_bce\": None if not np.isfinite(ft_cv_bce) else float(ft_cv_bce),\n    \"expert_cv_base_macro_auc\": None if not np.isfinite(base_cv_auc) else float(base_cv_auc),\n    \"expert_cv_fta_macro_auc\": None if not np.isfinite(ft_cv_auc) else float(ft_cv_auc),\n    \"next_notebook\": \"03_hard_example_finetune.ipynb\",\n}\n(OUT / \"stage2_status.json\").write_text(json.dumps(status2, indent=2))\n\nprint(json.dumps(status2, indent=2))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-11T20:03:52.931592Z","iopub.execute_input":"2026-08-11T20:03:52.931972Z","iopub.status.idle":"2026-08-11T20:03:53.001386Z","shell.execute_reply.started":"2026-08-11T20:03:52.931931Z","shell.execute_reply":"2026-08-11T20:03:53.00047Z"}},"outputs":[],"execution_count":null},{"id":"fba347bb","cell_type":"markdown","source":"## 11. Output inventory\n\nDo **not** submit anything from this notebook to the competition yet. This stage produces new model weights, not the final submission.\n\nFor Notebook 03, add this notebook's Kaggle output as an input. The important files are:\n\n- `rsna_stage2_fta/manifest.json`\n- `rsna_stage2_fta/fta_*.pt`\n- `rsna_stage2_fta/ft_a_member_metrics.csv`\n- `rsna_stage2_fta/expert_cv_predictions.csv`\n- `rsna_stage2_fta/expert_cv_target_auc.csv`\n- `rsna_stage2_fta/expert_ft_fold_map.csv`\n- `rsna_stage2_fta/stage2_status.json`\n\nThe original 20 checkpoints remain untouched and will return in the final ensemble.","metadata":{}},{"id":"627ba402","cell_type":"code","source":"print(\"Stage 2 output:\")\ntotal_bytes = 0\nfor p in sorted(OUT.iterdir()):\n    if p.is_file():\n        total_bytes += p.stat().st_size\n        print(f\" - {p.name:40s} {p.stat().st_size / (1024**2):9.2f} MB\")\n\nprint(f\"Total output size: {total_bytes / (1024**3):.3f} GB\")\nprint(\"Next: add this notebook output as a Kaggle input to Notebook 03.\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-08-11T20:03:53.002531Z","iopub.execute_input":"2026-08-11T20:03:53.002909Z","iopub.status.idle":"2026-08-11T20:03:53.048279Z","shell.execute_reply.started":"2026-08-11T20:03:53.002871Z","shell.execute_reply":"2026-08-11T20:03:53.04751Z"}},"outputs":[],"execution_count":null},{"id":"988bcb2a-3ae1-4fcb-b61a-7c241d4f3b9d","cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}