{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "6d091387-5c69-4883-88c4-5c33296a31e1", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " ✓ Dependencies OK\n", "Device: cuda | VRAM: 20.9 GB\n", "AMP: torch.bfloat16 | TF32: ON | Dual-stream: True\n", "\n", "════════════════════════════════════════════════════════════════════════════\n", " 🚀 TRAINING CONFIG (10 Boosts + 7 TUNE Changes from Log Analysis)\n", "════════════════════════════════════════════════════════════════════════════\n", " C1 (GEMINI): Structure Loss = Phase 1/2/3: [0.0, 0.5, 0.5]\n", " └─ TUNE C: Boosted Phase 2: 0.3→0.8, Phase 3: 1.0→1.2\n", " C2 (GEMINI): Boundary Crop Ratio = [0.25, 0.45, 0.35]\n", " C3 (GEMINI): Boundary BCE Weight = Phase 1/2/3: [0.15, 0.15, 0.3]\n", " └─ TUNE D: Adaptive decay DISABLED (was eroding signal)\n", " C4 (BOTH): Backbone LR Frac = [0.0, 0.25, 0.1]\n", " └─ Decoder LR = ['1.0e-04', '7.0e-05', '3.0e-05']\n", " └─ TUNE F: Backbone frac 0.15→0.20 | TUNE G: Decoder 5e-5→7e-5\n", " C5 (MINE): Phase Durations = [18, 41, 70] epochs\n", " C6 (MINE): BIoU Loss Weight = Phase 1/2/3: [0.3, 0.4, 0.4]\n", " └─ TUNE B: Reduced from [1.0, 1.8, 2.0] (was 116% of total)\n", " C7 (MINE): Lovász Loss Weight = Phase 1/2/3: [0.15, 0.3, 0.2]\n", " C8 (MINE): Gradient Clip = Phase 1/2/3: [5.0, 35.0, 25.0]\n", " └─ TUNE E: Phase 2 raised 25→35 for backbone headroom\n", " C9 (MINE): EMA Decay = Phase 1: 0.995, Phase 2+: 0.9985\n", " C10 (MINE): Backbone Warmup = 5 epochs\n", "────────────────────────────────────────────────────────────────────────────\n", " TUNE A (BIGGEST): LR scheduler → CosineAnnealingLR (was WarmRestarts)\n", " └─ Old scheduler peaked backbone LR at epoch 5 then decayed immediately\n", " └─ New: sustained high LR for ~60% of phase, then gentle decay\n", "════════════════════════════════════════════════════════════════════════════\n", " Expected Results (with TUNE changes):\n", " • Ep 30: BIoU ~76-78% (accelerated from ~73%)\n", " • Ep 40: BIoU ~82-84% (was ~77%)\n", " • Ep 50: BIoU ~86-88% (was ~79%)\n", " • Ep 70: BIoU ~90%+ (target exceeded)\n", "════════════════════════════════════════════════════════════════════════════\n", "\n", " Dataset ready (ok:same_path)\n", " Loading ZhengPeng7/BiRefNet-matting …\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "loading configuration file config.json from cache at /nlsasfs/home/aikosh/prod-aikosh34/model_cache/models--ZhengPeng7--BiRefNet-matting/snapshots/57f9f68b43ba337c75762b14cf3075d659007268/config.json\n", "loading configuration file config.json from cache at /nlsasfs/home/aikosh/prod-aikosh34/model_cache/models--ZhengPeng7--BiRefNet-matting/snapshots/57f9f68b43ba337c75762b14cf3075d659007268/config.json\n", "Model config BiRefNetConfig {\n", " \"_name_or_path\": \"ZhengPeng7/BiRefNet-matting\",\n", " \"architectures\": [\n", " \"BiRefNet\"\n", " ],\n", " \"auto_map\": {\n", " \"AutoConfig\": \"ZhengPeng7/BiRefNet-matting--BiRefNet_config.BiRefNetConfig\",\n", " \"AutoModelForImageSegmentation\": \"ZhengPeng7/BiRefNet-matting--birefnet.BiRefNet\"\n", " },\n", " \"bb_pretrained\": false,\n", " \"custom_pipelines\": {\n", " \"image-segmentation\": {\n", " \"pt\": [\n", " \"AutoModelForImageSegmentation\"\n", " ],\n", " \"tf\": [],\n", " \"type\": \"image\"\n", " }\n", " },\n", " \"model_type\": \"SegformerForSemanticSegmentation\",\n", " \"transformers_version\": \"4.46.3\"\n", "}\n", "\n", "loading weights file model.safetensors from cache at /nlsasfs/home/aikosh/prod-aikosh34/model_cache/models--ZhengPeng7--BiRefNet-matting/snapshots/57f9f68b43ba337c75762b14cf3075d659007268/model.safetensors\n", "All model checkpoint weights were used when initializing BiRefNet.\n", "\n", "All the weights of BiRefNet were initialized from the model checkpoint at ZhengPeng7/BiRefNet-matting.\n", "If your task is similar to the task the model of the checkpoint was trained on, you can already use BiRefNet for predictions without further training.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ " from_pretrained: 24.3s\n", " .to(device): 3.3s\n", " ✓ Patched 4 BasicLayer(s) for safe checkpointing\n", " Gradient checkpointing: OFF on 4 modules\n", " Total params: 220,176,498\n", " ✓ Model ready (NCHW, eager BF16)\n", " bs=2 accum=8 eff_batch=16\n", " Cache fingerprint mismatch — rebuilding\n", " Caching 884 pairs into RAM … done (884 pairs)\n", " ✓ Saved RAM cache → .ram_cache_images.pkl (26.18 GB, 33.7s)\n", " Cache fingerprint mismatch — rebuilding\n", " Caching 41 pairs into RAM … done (41 pairs)\n", " ✓ Saved RAM cache → .ram_cache_images.pkl (1.30 GB, 1.6s)\n", " [val] 205 fixed crops from 41 images (seed=42, k=5)\n", " Train: 884 pairs | Val: 205 items\n", " Dual-stream: each batch is 1× global + 1× local\n", " Fixed preview set: 8 canonical val images (indices: [1, 6, 7, 8, 14, 15, 17, 40])\n", " Backbone frozen: 333 param tensors\n", " Gradient checkpointing: OFF on 4 modules\n", " Phase 1 optimizer: decoder-only LR=1.0e-04 fused=True\n", " decay=24,937,872 params no_decay=37,422 params\n", " Scheduler: hold-then-cosine peak=1.0e-04 hold=2ep T_max=18\n", " Latest checkpoint: ckpt_B.pth (epoch 71)\n", " Loaded ckpt_B.pth (epoch 71)\n", " All params unfrozen: 220,176,498/220,176,498 (100.0%)\n", " Gradient checkpointing: ON on 4 modules\n", " Phase 3 optimizer: decoder=3.0e-05 backbone=3.0e-06 fused=True\n", " Scheduler: hold-then-cosine peak=3.0e-05 hold=21ep T_max=70\n", " Optimizer state restored (tensors moved to device)\n", " Scheduler last_epoch aligned to phase_ep=12\n", " LR re-aligned to current config: ['3.00e-06', '3.00e-06', '3.00e-05', '3.00e-05'] -> ['3.00e-06', '3.00e-06', '3.00e-05', '3.00e-05']\n", " Loss: phase=3 db=0.5 lovasz=0.2 mae=0.2 ssim=0.3 grad=0.5 struct=0.5 bnd=0.3 biou=0.4 ero=0.5 conf=1.0 aux=0.1\n", "\n", " ✅ Resumed ep=71 → continue 72\n", " Phase=3 phase_ep=12 LR=3.00e-05\n", " best_biou=79.43% best_fi_biou=83.72% prev_biou=78.85%\n", " adaptive_w_bnd=0.300\n", "\n", "\n", "════════════════════════════════════════════════════════════════════════════\n", " A100 SXM4 MIG 20GB | BF16 AMP | TF32 | NCHW | eager\n", " Model : ZhengPeng7/BiRefNet-matting\n", " Crop : 1024px | bs=2 accum=8 eff_batch=16\n", " Dual-st : True | Inference overlap 50% conf-temp 0.3\n", " Workers : train=16 val=4\n", " Epochs : 72 → 130\n", " Goal : crop-BIoU ≥ 80.0% PA ≥ 99.5% full-img BIoU ≥ 86.0%\n", "════════════════════════════════════════════════════════════════════════════\n", "\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ " " ] }, { "name": "stdout", "output_type": "stream", "text": [ "E072|Ph3|pe=13|LR:3.00e-05|Tr:0.892|GN:7.6834|db:0.047 lov:0.165 mae:0.027 ssim:0.043 grad:0.212 bnd:1.265(w=0.30) bi:0.403 st:0.174 ero:0.075 conf:0.029|FI-BIoU=83.87% SAD=9.18 MSE=0.0024 | Crop-BIoU=79.61%★(d2=71.34%)|17.4min|VRAM:12.2GB|Peak:17.2GB\n", " ★ New best BIoU=79.61% — saving best_ema.pth\n", " ★ EMA weights saved → best_ema_weights.pth (BIoU=79.61%)\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ " " ] }, { "name": "stdout", "output_type": "stream", "text": [ "E073|Ph3|pe=14|LR:3.00e-05|Tr:0.917|GN:6.1966|db:0.054 lov:0.180 mae:0.029 ssim:0.042 grad:0.215 bnd:1.285(w=0.30) bi:0.413 st:0.187 ero:0.075 conf:0.029|FI-BIoU=83.87% SAD=8.74 MSE=0.0024 | Crop-BIoU=79.64%★(d2=71.40%)|16.7min|VRAM:12.4GB|Peak:17.6GB\n", " ★ New best BIoU=79.64% — saving best_ema.pth\n", " ★ EMA weights saved → best_ema_weights.pth (BIoU=79.64%)\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ " " ] }, { "name": "stdout", "output_type": "stream", "text": [ "E074|Ph3|pe=15|LR:3.00e-05|Tr:0.893|GN:7.7989|db:0.049 lov:0.167 mae:0.027 ssim:0.038 grad:0.213 bnd:1.279(w=0.30) bi:0.402 st:0.175 ero:0.070 conf:0.028|FI-BIoU=83.87% SAD=8.75 MSE=0.0024 | Crop-BIoU=79.63% (d2=71.42%)|16.7min|VRAM:12.3GB|Peak:17.0GB\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ " Train E075: 4%|▍ | 18/442 [00:36<12:09, 1.72s/batch, loss=1.047, gn=0.0000, up=2]" ] } ], "source": [ "import subprocess, sys\n", "import os as _os\n", "if sys.platform.startswith(\"win\"):\n", " import io\n", " sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')\n", " sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')\n", "_os.environ.setdefault(\"USE_TF\", \"0\")\n", "_os.environ.setdefault(\"USE_FLAX\", \"0\")\n", "_os.environ.setdefault(\"TRANSFORMERS_NO_ADVISORY_WARNINGS\", \"1\")\n", "# Expandable segments let the allocator reuse reserved-but-free blocks across\n", "# heterogeneous-size allocations (e.g. training → eval tiling). Without this,\n", "# 1-2 GB of 'reserved but unallocated' memory is stranded and unavailable.\n", "_os.environ.setdefault(\"PYTORCH_ALLOC_CONF\", \"expandable_segments:True\")\n", "import sys as _sys\n", "import importlib.util as _ilu\n", "if getattr(_ilu.find_spec, \"__name__\", \"\") != \"_no_deepspeed_find_spec\":\n", " _orig_find_spec = _ilu.find_spec\n", " def _no_deepspeed_find_spec(name, *a, **kw):\n", " if name == \"deepspeed\" or (isinstance(name, str) and name.startswith(\"deepspeed.\")):\n", " return None\n", " return _orig_find_spec(name, *a, **kw)\n", " _ilu.find_spec = _no_deepspeed_find_spec\n", "\n", "_PKGS = [\n", " \"numpy<2.0\",\n", " \"transformers>=4.37.0,<5.0.0\",\n", " \"albumentations>=2.0.4\",\n", " \"opencv-python-headless\",\n", " \"pandas\",\n", " \"tqdm\",\n", " \"matplotlib\",\n", " \"timm\",\n", " \"kornia\",\n", " \"huggingface_hub>=0.23.0,<1.0.0\",\n", " \"einops\",\n", "]\n", "\n", "def _bootstrap():\n", " try:\n", " import importlib.metadata as _m\n", " from packaging.requirements import Requirement\n", " except ImportError:\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"packaging\"],\n", " stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n", " import importlib.metadata as _m\n", " from packaging.requirements import Requirement\n", " needs = []\n", " for pkg in _PKGS:\n", " req = Requirement(pkg)\n", " key = req.name.replace(\"-\", \"_\").lower()\n", " try:\n", " v = _m.version(key)\n", " if req.specifier and not req.specifier.contains(v, prereleases=True):\n", " needs.append(pkg)\n", " except _m.PackageNotFoundError:\n", " needs.append(pkg)\n", " if not needs:\n", " print(\" ✓ Dependencies OK\"); return\n", " print(f\" Installing {len(needs)} package(s) …\")\n", " for pkg in needs:\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", pkg],\n", " stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n", " print(\" ✓ Dependencies OK\")\n", "\n", "_bootstrap()\n", "\n", "import gc, os, math, random, time, csv, shutil, warnings, threading, copy, types\n", "from pathlib import Path\n", "from dataclasses import dataclass, field\n", "from typing import Dict, List, Optional, Tuple\n", "from concurrent.futures import ThreadPoolExecutor, as_completed\n", "\n", "import numpy as np\n", "import cv2\n", "try:\n", " cv2.setLogLevel(0)\n", "except AttributeError:\n", " pass\n", "\n", "class _SilenceCStderr:\n", " \"\"\"Silences C-level stderr (like libpng iCCP warnings from cv2.imread) without affecting Python print/exceptions.\"\"\"\n", " def __enter__(self):\n", " try:\n", " self._null = os.open(os.devnull, os.O_RDWR)\n", " self._orig_err = os.dup(2)\n", " os.dup2(self._null, 2)\n", " except Exception:\n", " self._null = None\n", " return self\n", " def __exit__(self, *_):\n", " try:\n", " if self._null is not None:\n", " os.dup2(self._orig_err, 2)\n", " os.close(self._orig_err)\n", " os.close(self._null)\n", " except Exception:\n", " pass\n", "\n", "def safe_imread(path, flags=cv2.IMREAD_UNCHANGED):\n", " with _SilenceCStderr():\n", " return cv2.imread(str(path), flags)\n", "\n", "import matplotlib\n", "matplotlib.use(\"Agg\")\n", "import matplotlib.pyplot as plt\n", "import matplotlib.gridspec as gridspec\n", "\n", "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "from torch.utils.data import Dataset, DataLoader\n", "import torchvision.transforms as T\n", "\n", "import albumentations as A\n", "\n", "from transformers import AutoModelForImageSegmentation\n", "from tqdm import tqdm\n", "from PIL import Image as _PILImage\n", "\n", "warnings.filterwarnings(\"ignore\", category=UserWarning)\n", "warnings.filterwarnings(\"ignore\", category=FutureWarning)\n", "\n", "torch.backends.cuda.matmul.allow_tf32 = True\n", "torch.backends.cudnn.allow_tf32 = True\n", "torch.set_float32_matmul_precision(\"high\")\n", "torch.backends.cudnn.benchmark = True\n", "\n", "AMP_DTYPE = torch.bfloat16\n", "FIXED_BS = 2\n", "FORCE_BEST_EMA = False\n", "EXPORT_EMA_ONLY = True\n", "\n", "@dataclass\n", "class Config:\n", "\n", " drive_root : str = \"/nlsasfs/home/aikosh/prod-aikosh34\"\n", " drive_dataset : str = \"/nlsasfs/home/aikosh/prod-aikosh34/dataset\"\n", " ssd_dataset : str = \"/nlsasfs/home/aikosh/prod-aikosh34/dataset\"\n", " sync_workers : int = 6\n", "\n", " @property\n", " def drive_ckpt_dir(self) -> str: return f\"{self.drive_root}/checkpoints\"\n", " @property\n", " def log_csv(self) -> str: return f\"{self.drive_root}/training_log.csv\"\n", " @property\n", " def preview_dir(self) -> str: return f\"{self.drive_root}/preview\"\n", " @property\n", " def train_img_dir(self) -> str: return f\"{self.ssd_dataset}/train/images\"\n", " @property\n", " def train_mask_dir(self) -> str: return f\"{self.ssd_dataset}/train/masks\"\n", " @property\n", " def val_img_dir(self) -> str: return f\"{self.ssd_dataset}/val/images\"\n", " @property\n", " def val_mask_dir(self) -> str: return f\"{self.ssd_dataset}/val/masks\"\n", "\n", " model_id : str = \"ZhengPeng7/BiRefNet-matting\"\n", " revision : Optional[str] = None\n", " hf_cache : str = \"/nlsasfs/home/aikosh/prod-aikosh34/model_cache\"\n", " crop_size : int = 1024\n", "\n", " max_epochs : int = 130\n", " effective_batch : int = 16\n", " num_workers : int = 16\n", " pin_memory : bool = True\n", " seed : int = 42\n", " # Per-phase gradient clip. Phase 1 = decoder-only (small grads → tight clip).\n", " # Phase 2+ = full backbone unfrozen; backbone grads are legitimately 3-4× larger.\n", " # FIX: Phase 2 raised to 25.0 — CSV showed 100% of phase-2 steps were clipped\n", " # at 10.0 (avg grad_norm=19.97), removing ~50% of gradient signal every step.\n", " # 25.0 acts as a genuine safety net (~top 10% clipped) instead of a suppressor.\n", " # TUNE E: Phase 2 grad clip raised 25→35 — backbone grads were just under clip threshold,\n", " # still losing ~10% signal. 35.0 gives genuine headroom while guarding explosions.\n", " grad_clip_phase : List[float] = field(default_factory=lambda: [5.0, 35.0, 25.0])\n", "\n", " # BOOST C5: Phase 1 extended (12→18) for full decoder convergence before backbone unfreeze\n", " # Phase 2 optimized (70→50) with better LR, Phase 3 extended (38→52) for fine-tuning\n", " max_phase_epochs : List[int] = field(default_factory=lambda: [18, 41, 70])\n", " phase_min_delta : float = 0.3 # Original value - proven stable\n", " phase_patience : int = 15 # Original value - proven stable\n", "\n", " force_dual_stream : bool = True\n", " p_global_fallback : float = 0.35\n", "\n", " w_dicebce : List[float] = field(default_factory=lambda: [1.0, 1.0, 0.5])\n", " # Lovász: IoU-aware surrogate. Moderate throughout — overlaps with DiceBCE.\n", " w_lovasz : List[float] = field(default_factory=lambda: [0.15, 0.3, 0.2])\n", " # MAE: L1 pixel loss. Useful for global shape, not edges.\n", " w_mae : List[float] = field(default_factory=lambda: [0.4, 0.3, 0.2])\n", " w_ssim : List[float] = field(default_factory=lambda: [0.5, 0.5, 0.3])\n", " # Gradient loss: boundary-masked Sobel+Laplacian. Gentle ramp, not 10× jump.\n", " w_grad : List[float] = field(default_factory=lambda: [0.2, 0.3, 0.5])\n", " # Structure Loss: BiRefNet's official spatially-weighted BCE+IoU.\n", " w_struct : List[float] = field(default_factory=lambda: [0.0, 0.5, 0.5])\n", " # Boundary BCE: multi-scale boundary supervision.\n", " w_bnd : List[float] = field(default_factory=lambda: [0.15, 0.15, 0.3])\n", " # BIoU loss: REDUCED — was 66% of gradient budget. Now only d=5,12 (no gap-filling d=1,2).\n", " # FIX: Phase 3 raised from 0.2→0.4 so BIoU supervision stays firm during high-res polish.\n", " w_biou : List[float] = field(default_factory=lambda: [0.3, 0.4, 0.4])\n", " w_aux : List[float] = field(default_factory=lambda: [0.3, 0.5, 0.1])\n", " # Erosion consistency: anti-blob. ENABLED in Phase 2 (was off until Phase 3).\n", " w_erosion : List[float] = field(default_factory=lambda: [0.0, 0.3, 0.5])\n", " # Confidence loss: penalizes soft predictions on interior/exterior pixels.\n", " # Forces the model to be decisive (0 or 1), not hedge at 0.8.\n", " w_confidence : List[float] = field(default_factory=lambda: [0.5, 0.5, 1.0])\n", " global_ratio : float = 0.25\n", "\n", " # BOOST C4: Learning rates INCREASED to unlock backbone potential\n", " # Decoder LR: Phase 2 (3e-5→5e-5), Phase 3 (5e-6→1e-5) - less aggressive decay\n", " # TUNE G: Decoder LR Phase 2 INCREASED 5e-5→7e-5 for faster convergence\n", " lr_decoder_phase : List[float] = field(default_factory=lambda: [1e-4, 7e-5, 3e-5])\n", " # BOOST C4 (BOTH): Backbone LR fraction — Phase 3: 0.10 so backbone co-adapts to edge focus\n", " backbone_lr_frac : List[float] = field(default_factory=lambda: [0.0, 0.25, 0.10])\n", " weight_decay : float = 1e-4\n", "\n", " # BOOST C9: EMA decay INCREASED for better smoothing during volatile Phase 1\n", " # 0.990→0.995 (100 steps→200 steps smoothing window)\n", " ema_decay : float = 0.995\n", " # Phase 2 EMA tightened (0.997→0.9985) for more stable evaluation metrics\n", " ema_decay_phase2: float = 0.9985 # bumped at Phase 2 transition for stability\n", "\n", " # BOOST C2 (GEMINI): Boundary crop ratio CUT IN HALF - fixes 15pp crop vs full-img gap\n", " # 60% boundary crops caused massive distribution shift; 30% learns natural distribution\n", " # This is the BIGGEST SINGLE FIX - expect immediate 5-8% BIoU gain\n", " bnd_ratio : List[float] = field(default_factory=lambda: [0.25, 0.45, 0.35])\n", " min_fg_ratio : float = 0.05\n", " fg_retry : int = 12\n", " # TUNE: Scale aug widened (0.50→0.35, 1.40→1.80) to train on large-canvas scale.\n", " # Epoch 036 failure: 2400px canvas with thin diagonal sword was never seen during\n", " # training because scale_aug_lo=0.5 means smallest seen = 0.5×native, and thin\n", " # structures at 2400px need scale<0.43 to be equivalent to crop_size=1024.\n", " scale_aug_lo : float = 0.35\n", " scale_aug_hi : float = 1.80\n", "\n", " val_crops_per_image : int = 5\n", "\n", " target_biou : float = 80.0\n", " target_pa : float = 99.5\n", " target_fi_biou : float = 86.0\n", " metric_dilation : int = 5\n", " preview_every : int = 2\n", " full_val_every : int = 5\n", " # BOOST C10: Backbone warmup EXTENDED (3→5 epochs) for transformer backbone stability\n", " # Swin/ViT backbones need 5-8 epochs to stabilize large-scale feature extraction\n", " bb_warmup_epochs: int = 5\n", "\n", " inference_overlap : float = 0.50\n", "\n", " # C6: Sharper tile-fusion weighting — high-confidence regions dominate more\n", " confidence_temperature : float = 0.3\n", "\n", " # C7: TTA enabled for fixed-set eval and preview (zero training cost)\n", " tta_enable : bool = True\n", " tta_hflip : bool = True\n", " tta_scale : float = 0.85\n", "\n", " # C5: Hard-negative weighted sampling\n", " hard_neg_alpha : float = 0.80 # weight = loss^alpha; 0=uniform, 1=proportional\n", " hard_neg_warmup : int = 3 # epochs before hard-neg kicks in\n", "\n", " loss_spike_k : float = 20.0\n", " loss_ema_beta : float = 0.95\n", "\n", " bnd_bce_clamp : float = 5.0\n", " compile_model : bool = False\n", "\n", "CFG = Config()\n", "\n", "class NoOpScaler(torch.amp.GradScaler):\n", "\n", " def __init__(self):\n", " try:\n", " super().__init__(device=\"cuda\", init_scale=1.0, growth_factor=1.0,\n", " backoff_factor=1.0, growth_interval=10**9, enabled=False)\n", " except TypeError:\n", " super().__init__(\"cuda\", init_scale=1.0, growth_factor=1.0,\n", " backoff_factor=1.0, growth_interval=10**9, enabled=False)\n", "\n", "def set_seed(seed: int = 42):\n", " random.seed(seed); np.random.seed(seed)\n", " torch.manual_seed(seed); torch.cuda.manual_seed_all(seed)\n", "\n", "def vram_gb() -> float:\n", " \"\"\"Actual GPU memory used (nvidia-smi equivalent) via mem_get_info.\"\"\"\n", " if not torch.cuda.is_available():\n", " return 0.0\n", " free, total = torch.cuda.mem_get_info()\n", " return (total - free) / 1e9\n", "\n", "def vram_peak_gb() -> float:\n", " \"\"\"Peak GPU memory allocated by PyTorch since last reset_peak_memory_stats.\"\"\"\n", " return torch.cuda.max_memory_reserved() / 1e9 if torch.cuda.is_available() else 0.0\n", "\n", "def trainable_ratio(model: nn.Module) -> str:\n", " tr = sum(p.numel() for p in model.parameters() if p.requires_grad)\n", " tot = sum(p.numel() for p in model.parameters())\n", " return f\"{tr:,}/{tot:,} ({100*tr/tot:.1f}%)\"\n", "\n", "def set_bn_eval(model: nn.Module):\n", " for m in model.modules():\n", " if isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d, nn.SyncBatchNorm)):\n", " m.eval()\n", "\n", "def freeze_backbone(model: nn.Module):\n", " base = getattr(model, \"_orig_mod\", model)\n", " frozen = 0\n", " for name, p in base.named_parameters():\n", " if \"bb.\" in name:\n", " p.requires_grad_(False); frozen += 1\n", " print(f\" Backbone frozen: {frozen} param tensors\")\n", "\n", "def unfreeze_all(model: nn.Module):\n", " base = getattr(model, \"_orig_mod\", model)\n", " for p in base.parameters():\n", " p.requires_grad_(True)\n", " print(f\" All params unfrozen: {trainable_ratio(base)}\")\n", "\n", "def _normalize_preds(raw) -> List[torch.Tensor]:\n", " def _recurse(x):\n", " if x is None: return []\n", " if isinstance(x, torch.Tensor):\n", " return [x] if x.dim() >= 3 else []\n", " if isinstance(x, dict):\n", " out = []\n", " for v in x.values(): out.extend(_recurse(v))\n", " return out\n", " if isinstance(x, (list, tuple)):\n", " out = []\n", " for item in x: out.extend(_recurse(item))\n", " return out\n", " if hasattr(x, \"__dict__\"):\n", " out = []\n", " for v in vars(x).values(): out.extend(_recurse(v))\n", " return out\n", " return []\n", " all_t = _recurse(raw)\n", " mask_preds = [t for t in all_t if t.dim() == 4 and t.shape[1] == 1]\n", " if not mask_preds:\n", " mask_preds = [t for t in all_t if t.dim() == 4]\n", " if not mask_preds:\n", " raise RuntimeError(f\"BiRefNet output parse failed. type={type(raw)}\")\n", " return mask_preds\n", "\n", "def _safe_preds(preds: List[torch.Tensor]) -> List[torch.Tensor]:\n", " return [p.contiguous(memory_format=torch.contiguous_format).float() for p in preds]\n", "\n", "def sync_dataset(src: str, dst: str, workers: int = 6) -> bool:\n", " src_p, dst_p = Path(src), Path(dst)\n", " dst_p.mkdir(parents=True, exist_ok=True)\n", " sync_ok = dst_p / \".sync_ok\"\n", " print(\"═\" * 60 + \"\\n Dataset Sync\")\n", " if str(src_p.resolve()) == str(dst_p.resolve()):\n", " sync_ok.write_text(\"ok:same_path\")\n", " print(\" ✓ src == dst — no copy needed\"); print(\"═\" * 60); return True\n", " all_files = [f for f in src_p.rglob(\"*\") if f.is_file() and not f.name.startswith(\".\")]\n", " need = [(sf, dst_p / sf.relative_to(src_p))\n", " for sf in all_files\n", " if not (dst_p / sf.relative_to(src_p)).exists() or\n", " (dst_p / sf.relative_to(src_p)).stat().st_size != sf.stat().st_size]\n", " print(f\" Total: {len(all_files)} files | Need copy: {len(need)}\")\n", " if not need:\n", " sync_ok.write_text(f\"ok:{len(all_files)}\")\n", " print(\" ✓ Already synced\"); print(\"═\" * 60); return True\n", " done = [0]; lock = threading.Lock()\n", " def copy_one(args):\n", " sf, df = args\n", " df.parent.mkdir(parents=True, exist_ok=True)\n", " tmp = df.with_suffix(\".tmp\")\n", " try:\n", "\n", " shutil.copy2(sf, tmp); tmp.replace(df)\n", " with lock:\n", " done[0] += 1\n", " if done[0] % 200 == 0: print(f\" ✓ {done[0]}/{len(need)} copied\")\n", " return True\n", " except Exception as e:\n", " tmp.unlink(missing_ok=True); print(f\" ✗ {sf.name}: {e}\"); return False\n", " t0 = time.time(); failed = 0\n", " with ThreadPoolExecutor(max_workers=workers) as ex:\n", " for f in as_completed({ex.submit(copy_one, a): a for a in need}):\n", " if not f.result(): failed += 1\n", " if failed:\n", " print(f\" ✗ {failed} file(s) failed\"); print(\"═\" * 60); return False\n", " sync_ok.write_text(f\"ok:{len(all_files)}\")\n", " print(f\" ✓ Sync done in {(time.time()-t0)/60:.1f}min\"); print(\"═\" * 60); return True\n", "\n", "_MEAN = [0.485, 0.456, 0.406]\n", "_STD = [0.229, 0.224, 0.225]\n", "_BND_K5 = np.ones((5, 5), np.uint8)\n", "\n", "class ToonDataset(Dataset):\n", "\n", " def __init__(self,\n", " img_dir: str, mask_dir: str,\n", " crop_size: int = 1024,\n", " bnd_ratio: float = 0.0,\n", " augment: bool = False,\n", " min_fg_ratio: float = 0.02,\n", " fg_retry: int = 8,\n", " scale_range: Optional[Tuple[float, float]] = None,\n", " fixed_crops: bool = False,\n", " crops_per_image: int = 3,\n", " p_global: float = 0.0):\n", "\n", " self.img_dir = Path(img_dir)\n", " self.mask_dir = Path(mask_dir)\n", " self.crop_size = crop_size\n", " self.bnd_ratio = bnd_ratio\n", " self.augment = augment\n", " self.min_fg = min_fg_ratio\n", " self.fg_retry = fg_retry\n", " self.scale_rng = scale_range\n", " self.fixed = fixed_crops\n", " self.p_global = p_global\n", "\n", " self.pairs: List[Tuple[Path, Path]] = sorted([\n", " (ip, self.mask_dir / ip.name)\n", " for ip in self.img_dir.glob(\"*.png\")\n", " if (self.mask_dir / ip.name).exists()\n", " ])\n", " if not self.pairs:\n", " raise FileNotFoundError(\n", " f\"No image/mask pairs.\\n imgs: {self.img_dir}\\n masks: {self.mask_dir}\")\n", "\n", " self.aug = self._build_aug(phase=1) if augment else None\n", " self.norm = T.Normalize(_MEAN, _STD)\n", " self._img_cache: Dict[int, Tuple[np.ndarray, np.ndarray]] = {}\n", " self._cache_all()\n", " self._fixed: List[Tuple[int, int, int]] = []\n", " if fixed_crops:\n", " self._fixed = self._precompute_crops(crops_per_image)\n", "\n", " def _cache_fingerprint(self) -> str:\n", " \"\"\"Hash of filename + size + mtime for every pair. Cache invalidates if\n", " any image is added, removed, replaced, or modified.\"\"\"\n", " import hashlib\n", " h = hashlib.sha1()\n", " for ip, mp in self.pairs:\n", " try:\n", " ist, mst = ip.stat(), mp.stat()\n", " h.update(f\"{ip.name}|{ist.st_size}|{int(ist.st_mtime)}|\"\n", " f\"{mp.name}|{mst.st_size}|{int(mst.st_mtime)}\\n\".encode())\n", " except OSError:\n", " h.update(f\"{ip.name}|MISSING\\n\".encode())\n", " return h.hexdigest()[:16]\n", "\n", " def _cache_pickle_path(self) -> Path:\n", " # one pickle per image dir; stored as hidden file alongside the data\n", " return self.img_dir.parent / f\".ram_cache_{self.img_dir.name}.pkl\"\n", "\n", " def _try_load_disk_cache(self) -> bool:\n", " import pickle\n", " path = self._cache_pickle_path()\n", " if not path.exists():\n", " return False\n", " try:\n", " t0 = time.time()\n", " with open(path, \"rb\") as f:\n", " blob = pickle.load(f)\n", " if blob.get(\"fingerprint\") != self._cache_fingerprint():\n", " print(f\" Cache fingerprint mismatch — rebuilding\")\n", " return False\n", " cache = blob.get(\"cache\")\n", " if not isinstance(cache, dict) or len(cache) != len(self.pairs):\n", " print(f\" Cache count mismatch ({len(cache) if isinstance(cache, dict) else '?'}\"\n", " f\" vs {len(self.pairs)}) — rebuilding\")\n", " return False\n", " self._img_cache = cache\n", " # Fix any cached pairs where mask dims don't match image\n", " fixed = 0\n", " for k, (img, mask) in self._img_cache.items():\n", " if mask.shape[:2] != img.shape[:2]:\n", " self._img_cache[k] = (img, cv2.resize(\n", " mask, (img.shape[1], img.shape[0]),\n", " interpolation=cv2.INTER_LINEAR))\n", " fixed += 1\n", " if fixed:\n", " print(f\" ⚠ Fixed {fixed} cached pairs with mismatched mask dims\")\n", " print(f\" ✓ Loaded RAM cache from {path.name} \"\n", " f\"({len(cache)} pairs, {time.time()-t0:.1f}s)\")\n", " return True\n", " except Exception as e:\n", " print(f\" Cache load failed ({e}) — rebuilding\")\n", " return False\n", "\n", " def _save_disk_cache(self):\n", " import pickle\n", " path = self._cache_pickle_path()\n", " tmp = path.with_suffix(\".tmp\")\n", " try:\n", " t0 = time.time()\n", " blob = {\"fingerprint\": self._cache_fingerprint(),\n", " \"cache\": self._img_cache}\n", " # protocol=4 supports >4GB pickles (large datasets in RAM blow past\n", " # the protocol 3 limit). highest_protocol picks ≥4 on Py3.8+.\n", " with open(tmp, \"wb\") as f:\n", " pickle.dump(blob, f, protocol=pickle.HIGHEST_PROTOCOL)\n", " tmp.replace(path)\n", " sz_gb = path.stat().st_size / 1e9\n", " print(f\" ✓ Saved RAM cache → {path.name} \"\n", " f\"({sz_gb:.2f} GB, {time.time()-t0:.1f}s)\")\n", " except Exception as e:\n", " tmp.unlink(missing_ok=True)\n", " print(f\" ⚠ Cache save failed ({e}) — continuing without disk cache\")\n", "\n", " def _cache_all(self):\n", " # fast path: try to restore from a previously saved pickle\n", " if self._try_load_disk_cache():\n", " return\n", "\n", " print(f\" Caching {len(self.pairs)} pairs into RAM …\", end=\"\", flush=True)\n", " with _SilenceCStderr():\n", " for i, (ip, mp) in enumerate(self.pairs):\n", " img_raw = cv2.imread(str(ip), cv2.IMREAD_UNCHANGED)\n", " if img_raw is None:\n", " raise RuntimeError(f\"Failed to read {ip}\")\n", "\n", " if img_raw.ndim == 2:\n", " img = cv2.cvtColor(img_raw, cv2.COLOR_GRAY2RGB)\n", " elif img_raw.shape[2] == 4:\n", " img = cv2.cvtColor(img_raw, cv2.COLOR_BGRA2RGB)\n", " else:\n", " img = cv2.cvtColor(img_raw, cv2.COLOR_BGR2RGB)\n", " mask = cv2.imread(str(mp), cv2.IMREAD_GRAYSCALE)\n", " if mask is None:\n", " raise RuntimeError(f\"Failed to read {mp}\")\n", " # Ensure mask matches image spatial dims\n", " if mask.shape[:2] != img.shape[:2]:\n", " mask = cv2.resize(mask, (img.shape[1], img.shape[0]),\n", " interpolation=cv2.INTER_LINEAR)\n", " self._img_cache[i] = (img, mask)\n", " print(f\" done ({len(self._img_cache)} pairs)\")\n", "\n", " # persist for next run\n", " self._save_disk_cache()\n", "\n", " @staticmethod\n", " def _build_aug(phase: int = 1) -> A.Compose:\n", " if phase == 3:\n", " return A.Compose([\n", " A.HorizontalFlip(p=0.5),\n", " A.ShiftScaleRotate(shift_limit=0.06, scale_limit=0.12,\n", " rotate_limit=15,\n", " border_mode=cv2.BORDER_CONSTANT,\n", " fill=0, fill_mask=0,\n", " mask_interpolation=cv2.INTER_LINEAR, p=0.6),\n", " A.ColorJitter(brightness=0.35, contrast=0.35,\n", " saturation=0.35, hue=0.08, p=0.6),\n", " A.HueSaturationValue(hue_shift_limit=20, sat_shift_limit=30,\n", " val_shift_limit=25, p=0.4),\n", " A.CLAHE(clip_limit=4.0, tile_grid_size=(8, 8), p=0.3),\n", " A.ToGray(p=0.15),\n", " A.Sharpen(alpha=(0.15, 0.40), lightness=(0.9, 1.1), p=0.30),\n", " A.RandomGamma(gamma_limit=(80, 120), p=0.25),\n", " A.ISONoise(color_shift=(0.01, 0.03), intensity=(0.02, 0.08), p=0.10),\n", " A.GaussianBlur(blur_limit=(3, 3), p=0.05),\n", " A.MotionBlur(blur_limit=3, p=0.03),\n", " A.Downscale(scale_range=(0.6, 0.9), p=0.15),\n", " A.CoarseDropout(num_holes_range=(1, 6), hole_height_range=(10, 40),\n", " hole_width_range=(10, 40),\n", " fill=\"random\", fill_mask=0, p=0.05),\n", " ], additional_targets={\"mask\": \"mask\"})\n", " return A.Compose([\n", " A.HorizontalFlip(p=0.5),\n", " A.ShiftScaleRotate(shift_limit=0.06, scale_limit=0.12,\n", " rotate_limit=15,\n", " border_mode=cv2.BORDER_CONSTANT,\n", " fill=0, fill_mask=0,\n", " mask_interpolation=cv2.INTER_LINEAR, p=0.6),\n", " A.ColorJitter(brightness=0.35, contrast=0.35,\n", " saturation=0.35, hue=0.08, p=0.6),\n", " A.HueSaturationValue(hue_shift_limit=20, sat_shift_limit=30,\n", " val_shift_limit=25, p=0.4),\n", " A.CLAHE(clip_limit=4.0, tile_grid_size=(8, 8), p=0.3),\n", " A.ToGray(p=0.15),\n", " A.Sharpen(alpha=(0.15, 0.40), lightness=(0.9, 1.1), p=0.30),\n", " A.RandomGamma(gamma_limit=(80, 120), p=0.25),\n", " A.ISONoise(color_shift=(0.01, 0.03), intensity=(0.02, 0.08), p=0.10),\n", " # blur augmentations: simulate soft edges and motion in action poses\n", " A.GaussianBlur(blur_limit=(3, 5), p=0.15),\n", " A.MotionBlur(blur_limit=5, p=0.10),\n", " # downscale forces coarser features to generalise to lower-res inputs\n", " A.Downscale(scale_range=(0.6, 0.9), p=0.15),\n", " A.CoarseDropout(num_holes_range=(1, 6), hole_height_range=(10, 40),\n", " hole_width_range=(10, 40),\n", " fill=\"random\", fill_mask=0, p=0.15),\n", " ], additional_targets={\"mask\": \"mask\"})\n", "\n", " def _precompute_crops(self, k: int) -> List[Tuple[int, int, int]]:\n", " rng = np.random.RandomState(42)\n", " C = self.crop_size; out = []\n", " for i, (ip, _) in enumerate(self.pairs):\n", " try:\n", " img, _ = self._img_cache[i]\n", " H, W = img.shape[:2]\n", " except Exception:\n", " H = W = C\n", " H = max(H, C); W = max(W, C)\n", " for _ in range(k):\n", " out.append((i, int(rng.randint(0, H - C + 1)),\n", " int(rng.randint(0, W - C + 1))))\n", " print(f\" [val] {len(out)} fixed crops from {len(self.pairs)} images \"\n", " f\"(seed=42, k={k})\")\n", " return out\n", "\n", " def _pad_min(self, img, mask):\n", " C = self.crop_size; H, W = img.shape[:2]\n", " if H < C or W < C:\n", " ph = max(0, C-H); pw = max(0, C-W)\n", " img = cv2.copyMakeBorder(img, 0, ph, 0, pw, cv2.BORDER_REFLECT_101)\n", " mask = cv2.copyMakeBorder(mask, 0, ph, 0, pw, cv2.BORDER_CONSTANT, value=0)\n", " return img, mask\n", "\n", " def _bnd_crop_pos(self, mask, H, W, C):\n", " dilated = cv2.dilate(mask, _BND_K5)\n", " eroded = cv2.erode(mask, _BND_K5)\n", " bnd = dilated.astype(np.int16) - eroded.astype(np.int16)\n", " ys, xs = np.where(bnd > 64)\n", " if len(ys) == 0:\n", " return random.randint(0, H-C), random.randint(0, W-C)\n", " idx = random.randint(0, len(ys)-1)\n", " cy, cx = int(ys[idx]), int(xs[idx])\n", " return (max(0, min(H-C, cy - C//2)),\n", " max(0, min(W-C, cx - C//2)))\n", "\n", " def _smart_crop(self, img, mask):\n", " C = self.crop_size\n", " if self.scale_rng is not None:\n", " lo, hi = self.scale_rng\n", " s = random.uniform(lo, hi)\n", " H, W = img.shape[:2]\n", " nH, nW = int(H*s), int(W*s)\n", " if nH >= C and nW >= C:\n", " # INTER_AREA for downscaling (avoids aliasing/moiré),\n", " # INTER_LINEAR for upscaling (INTER_AREA degrades to nearest-neighbor on upscale)\n", " img_interp = cv2.INTER_AREA if s < 1.0 else cv2.INTER_LINEAR\n", " # FIX: Masks must use INTER_NEAREST on downscale to stay binary-sharp.\n", " # INTER_LINEAR/INTER_AREA on binary masks creates soft anti-aliased edges\n", " # that teach the model to produce fuzzy boundaries instead of crisp ones.\n", " mask_interp = cv2.INTER_NEAREST if s < 1.0 else cv2.INTER_LINEAR\n", " img = cv2.resize(img, (nW, nH), interpolation=img_interp)\n", " mask = cv2.resize(mask, (nW, nH), interpolation=mask_interp)\n", " img, mask = self._pad_min(img, mask)\n", " H, W = img.shape[:2]\n", " if random.random() < self.bnd_ratio:\n", " y, x = self._bnd_crop_pos(mask, H, W, C)\n", " else:\n", " y = x = 0\n", " for _ in range(self.fg_retry):\n", " y = random.randint(0, H-C)\n", " x = random.randint(0, W-C)\n", " if mask[y:y+C, x:x+C].mean() >= self.min_fg * 255:\n", " break\n", " return img[y:y+C, x:x+C], mask[y:y+C, x:x+C]\n", "\n", " def _full_image_view(self, idx: int):\n", " C = self.crop_size\n", " img, mask = self._img_cache[idx]\n", " H, W = img.shape[:2]\n", " scale = C / max(H, W)\n", " nH, nW = int(H * scale), int(W * scale)\n", " img_r = cv2.resize(img, (nW, nH), interpolation=cv2.INTER_LINEAR)\n", " mask_r = cv2.resize(mask, (nW, nH), interpolation=cv2.INTER_LINEAR)\n", " ph = C - nH; pw = C - nW\n", " t, b = ph // 2, ph - ph // 2\n", " l, r = pw // 2, pw - pw // 2\n", " img = cv2.copyMakeBorder(img_r, t, b, l, r, cv2.BORDER_REFLECT_101)\n", " mask = cv2.copyMakeBorder(mask_r, t, b, l, r, cv2.BORDER_CONSTANT, value=0)\n", " return img, mask\n", "\n", " def __len__(self) -> int:\n", " return len(self._fixed) if self.fixed else len(self.pairs)\n", "\n", " def _tensorize(self, img: np.ndarray, mask: np.ndarray):\n", " img_t = self.norm(torch.from_numpy(img).permute(2, 0, 1).float() / 255.0)\n", " mask_t = torch.from_numpy(mask).float().unsqueeze(0) / 255.0\n", " return img_t, mask_t\n", "\n", " def get_global(self, idx: int):\n", "\n", " img, mask = self._full_image_view(idx)\n", " if self.aug is not None:\n", " out = self.aug(image=img, mask=mask); img, mask = out[\"image\"], out[\"mask\"]\n", " return self._tensorize(img, mask)\n", "\n", " def get_local(self, idx: int):\n", "\n", " img, mask = self._img_cache[idx]\n", " img, mask = self._smart_crop(img, mask)\n", " if self.aug is not None:\n", " out = self.aug(image=img, mask=mask); img, mask = out[\"image\"], out[\"mask\"]\n", " return self._tensorize(img, mask)\n", "\n", " def __getitem__(self, idx: int):\n", " C = self.crop_size\n", "\n", " if self.fixed:\n", " pair_idx, y0, x0 = self._fixed[idx]\n", " img, mask = self._img_cache[pair_idx]\n", " # Ensure mask matches image spatial dims (some pairs differ)\n", " if mask.shape[:2] != img.shape[:2]:\n", " mask = cv2.resize(mask, (img.shape[1], img.shape[0]),\n", " interpolation=cv2.INTER_LINEAR)\n", " img, mask = self._pad_min(img, mask)\n", " img = img[y0:y0+C, x0:x0+C]\n", " mask = mask[y0:y0+C, x0:x0+C]\n", " # Safety: guarantee exact crop_size even if slice went past edge\n", " h, w = img.shape[:2]\n", " mh, mw = mask.shape[:2]\n", " if h < C or w < C:\n", " img = cv2.copyMakeBorder(img, 0, max(0, C-h), 0, max(0, C-w),\n", " cv2.BORDER_REFLECT_101)\n", " if mh < C or mw < C:\n", " mask = cv2.copyMakeBorder(mask, 0, max(0, C-mh), 0, max(0, C-mw),\n", " cv2.BORDER_CONSTANT, value=0)\n", " return self._tensorize(img, mask)\n", "\n", " if self.augment and self.p_global > 0 and random.random() < self.p_global:\n", " img, mask = self._full_image_view(idx)\n", " else:\n", " img, mask = self._img_cache[idx]\n", " img, mask = self._smart_crop(img, mask)\n", "\n", " if self.aug is not None:\n", " out = self.aug(image=img, mask=mask); img, mask = out[\"image\"], out[\"mask\"]\n", "\n", " return self._tensorize(img, mask)\n", "\n", "class DualStreamLoader:\n", "\n", " def __init__(self, ds: ToonDataset, bs: int, num_workers: int, seed: int):\n", " import queue\n", " self.ds = ds\n", " self.bs = bs\n", " self.num_workers = num_workers\n", " self.rng = random.Random(seed)\n", " self.length = len(ds) // bs\n", "\n", " self._pool = ThreadPoolExecutor(max_workers=max(2, num_workers // 2))\n", " # Two independent shuffled queues for global / local streams; refilled when\n", " # exhausted. Guarantees each image is seen ~equally often per epoch instead\n", " # of biased sampling-with-replacement.\n", " self._g_queue: List[int] = []\n", " self._l_queue: List[int] = []\n", "\n", " # C5: Hard-negative per-sample weights. None = uniform (default).\n", " # Updated externally via set_sample_weights() after each epoch.\n", " self._sample_weights: Optional[np.ndarray] = None\n", " self._use_hard_neg: bool = False\n", "\n", " self._q = queue.Queue(maxsize=4)\n", " self._shutdown = False\n", " self._loader_thread = None\n", "\n", " def __len__(self): return self.length\n", "\n", " def set_sample_weights(self, weights: np.ndarray):\n", " \"\"\"C5: Set per-sample difficulty weights (shape=[N], non-negative).\n", " Heavier weight → sampled more often. Call after each epoch.\"\"\"\n", " w = np.asarray(weights, dtype=np.float32)\n", " w = np.clip(w, 0.0, None)\n", " total = w.sum()\n", " if total < 1e-9:\n", " self._sample_weights = None\n", " self._use_hard_neg = False\n", " else:\n", " self._sample_weights = w / total # normalised probabilities\n", " self._use_hard_neg = True\n", "\n", " def _draw(self, queue_list: List[int], k: int) -> List[int]:\n", " # C5: Hard-negative weighted sampling when weights are available\n", " if self._use_hard_neg and self._sample_weights is not None:\n", " n = len(self.ds)\n", " probs = self._sample_weights[:n] # guard for size mismatch\n", " probs = probs / probs.sum()\n", " return list(np.random.choice(n, size=k, replace=True, p=probs))\n", " # Fallback: uniform shuffle queue (original behaviour)\n", " out: List[int] = []\n", " while len(out) < k:\n", " if not queue_list:\n", " pool = list(range(len(self.ds)))\n", " self.rng.shuffle(pool)\n", " queue_list.extend(pool)\n", " out.append(queue_list.pop())\n", " return out\n", "\n", " def _one_batch(self, epoch_idx: int):\n", " n_global = int(self.bs * CFG.global_ratio + 0.5)\n", " n_global = max(0, min(self.bs, n_global))\n", " n_local = self.bs - n_global\n", " idxs_g = self._draw(self._g_queue, n_global)\n", " idxs_l = self._draw(self._l_queue, n_local)\n", " futs = [self._pool.submit(self.ds.get_global, i) for i in idxs_g] + \\\n", " [self._pool.submit(self.ds.get_local, i) for i in idxs_l]\n", " items = [f.result() for f in futs]\n", " imgs = torch.stack([it[0] for it in items], dim=0).pin_memory()\n", " masks = torch.stack([it[1] for it in items], dim=0).pin_memory()\n", " return imgs, masks\n", "\n", " def _producer(self):\n", " for i in range(self.length):\n", " if self._shutdown:\n", " break\n", " try:\n", " batch = self._one_batch(i)\n", " self._q.put(batch)\n", " except Exception as e:\n", " self._q.put(e)\n", " break\n", "\n", " def __iter__(self):\n", " import queue\n", " self._shutdown = False\n", " # Clear queue just in case\n", " while not self._q.empty():\n", " try: self._q.get_nowait()\n", " except queue.Empty: break\n", "\n", " self._loader_thread = threading.Thread(target=self._producer, daemon=True)\n", " self._loader_thread.start()\n", "\n", " for _ in range(self.length):\n", " batch = self._q.get()\n", " if isinstance(batch, Exception):\n", " raise batch\n", " yield batch\n", "\n", " def close(self):\n", " import queue\n", " self._shutdown = True\n", " # Drain queue to unblock producer thread\n", " while not self._q.empty():\n", " try: self._q.get_nowait()\n", " except queue.Empty: break\n", " self._pool.shutdown(wait=False)\n", "\n", "\n", "def _structure_loss(pred_logit: torch.Tensor, p: torch.Tensor, gt: torch.Tensor) -> torch.Tensor:\n", " \"\"\"BiRefNet's official StructureLoss. Spatially-weighted BCE + IoU where the\n", " weight is `1 + 5 * |avgpool(gt, k=31) - gt|`. Pixels far from boundaries get\n", " weight 1; pixels right at the edge of the GT get weight up to 6. This gives\n", " boundary emphasis WITHOUT the distribution bias of training on boundary\n", " crops, which causes the model to over-predict (blob) near edges.\n", "\n", " Reference: ZhengPeng7/BiRefNet/loss.py StructureLoss class.\n", " \"\"\"\n", " weit = 1.0 + 5.0 * torch.abs(F.avg_pool2d(gt, kernel_size=31, stride=1, padding=15) - gt)\n", " wbce = F.binary_cross_entropy_with_logits(pred_logit, gt, reduction=\"none\")\n", " wbce = (weit * wbce).sum(dim=(2, 3)) / (weit.sum(dim=(2, 3)) + 1e-6)\n", "\n", " inter = ((p * gt) * weit).sum(dim=(2, 3))\n", " union = ((p + gt) * weit).sum(dim=(2, 3))\n", " wiou = 1.0 - (inter + 1.0) / (union - inter + 1.0)\n", "\n", " return (wbce + wiou).mean()\n", "\n", "\n", "def _dice_bce_loss(pred_logit, p, gt, eps=1e-6):\n", " # Focal BCE (Lin et al., ICCV 2017): down-weight easy pixels, up-weight hard ones.\n", " # At p_t=0.85 (easy interior): focal_weight = 0.0225 → nearly ignored.\n", " # At p_t=0.50 (hard boundary): focal_weight = 0.25 → 11× more gradient.\n", " # This forces the model to fix boundary mistakes instead of coasting on easy interiors.\n", " bce_raw = F.binary_cross_entropy_with_logits(pred_logit, gt, reduction='none')\n", " p_t = p * gt + (1.0 - p) * (1.0 - gt) # probability assigned to correct class\n", " focal_weight = (1.0 - p_t) ** 2.0 # gamma=2\n", " bce = (focal_weight * bce_raw).mean()\n", "\n", " num = 2 * (p * gt).sum(dim=(1,2,3)) + eps\n", " den = p.sum(dim=(1,2,3)) + gt.sum(dim=(1,2,3)) + eps\n", " dice_loss = 1.0 - (num / den).mean()\n", " return 0.5 * bce + 0.5 * dice_loss\n", "\n", "def _lovasz_grad(gt_sorted: torch.Tensor) -> torch.Tensor:\n", "\n", " gt_sorted = gt_sorted.float()\n", " gts = gt_sorted.sum()\n", " intersection = gts - gt_sorted.cumsum(0)\n", " union = gts + (1. - gt_sorted).cumsum(0)\n", " jaccard = 1. - intersection / union\n", " if len(gt_sorted) > 1:\n", " jaccard[1:] = jaccard[1:] - jaccard[:-1]\n", " return jaccard\n", "\n", "def _lovasz_hinge_flat(logits: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:\n", "\n", " if len(labels) == 0:\n", " return logits.sum() * 0.\n", " signs = 2. * labels.float() - 1.\n", " errors = (1. - logits * signs)\n", " errors_sorted, perm = torch.sort(errors, dim=0, descending=True)\n", " gt_sorted = labels[perm]\n", " grad = _lovasz_grad(gt_sorted)\n", " return torch.dot(F.relu(errors_sorted), grad)\n", "\n", "def _lovasz_hinge_loss(pred_logit: torch.Tensor, gt: torch.Tensor) -> torch.Tensor:\n", "\n", " B = pred_logit.shape[0]\n", " loss = 0.\n", " for b in range(B):\n", " lg = pred_logit[b].view(-1)\n", " gt_b = (gt[b] > 0.5).view(-1)\n", " loss = loss + _lovasz_hinge_flat(lg, gt_b)\n", " return loss / max(B, 1)\n", "\n", "def _boundary_bce_loss(pred_logit: torch.Tensor, gt: torch.Tensor,\n", " band_px: int = 5, eps: float = 1e-6) -> torch.Tensor:\n", " \"\"\"Distance-weighted boundary BCE on a single band width.\n", " C2b: Normalised by the number of boundary pixels so that thin boundaries\n", " at fine scales (band_px=1) do not produce numerically tiny denominators\n", " that inflate the loss relative to coarser scales.\"\"\"\n", " pad = band_px\n", " dil = F.max_pool2d(gt, 2*band_px+1, stride=1, padding=pad)\n", " ero = 1.0 - F.max_pool2d(1.0-gt, 2*band_px+1, stride=1, padding=pad)\n", " band = (dil - ero).clamp(0, 1)\n", " inner = band.clone()\n", " decay = 0.7\n", " w_accum = band.clone()\n", " for _ in range(band_px - 1):\n", " inner = -F.max_pool2d(-inner, 3, stride=1, padding=1)\n", " w_accum = w_accum + decay * inner\n", " decay *= 0.7\n", " weight = w_accum / (w_accum.amax(dim=(2,3), keepdim=True) + eps)\n", " bce = F.binary_cross_entropy_with_logits(\n", " pred_logit, gt, reduction=\"none\"\n", " )\n", " # Normalise by boundary pixel count (not total pixels) so the loss is\n", " # scale-invariant and does not swamp interior losses at fine scales.\n", " n_bnd = (weight > 0.01).float().sum().clamp(min=1.0)\n", " return (bce * weight).sum() / n_bnd\n", "\n", "\n", "def _multiscale_boundary_bce_loss(pred_logit: torch.Tensor, gt: torch.Tensor,\n", " bce_clamp: float = 3.0) -> torch.Tensor:\n", " \"\"\"Boundary BCE at 4 scales: 1px (finest strands), 2px (hair), 5px (edges),\n", " 12px (silhouette). Fine scales weighted higher to compensate for smaller\n", " pixel count and to directly target the biou_2 gap.\"\"\"\n", " clamped = pred_logit.clamp(-bce_clamp, bce_clamp)\n", " l1 = _boundary_bce_loss(clamped, gt, band_px=1)\n", " l2 = _boundary_bce_loss(clamped, gt, band_px=2)\n", " l5 = _boundary_bce_loss(clamped, gt, band_px=5)\n", " l12 = _boundary_bce_loss(clamped, gt, band_px=12)\n", " return 2.0 * l1 + 2.0 * l2 + 1.0 * l5 + 0.1 * l12\n", "\n", "\n", "def _soft_biou_loss_at(p: torch.Tensor, gt: torch.Tensor,\n", " dilation: int, eps: float = 1e-6) -> torch.Tensor:\n", " k = 2 * dilation + 1\n", " p_dil = F.max_pool2d(p, k, stride=1, padding=dilation)\n", " p_ero = 1.0 - F.max_pool2d(1.0 - p, k, stride=1, padding=dilation)\n", " g_dil = F.max_pool2d(gt, k, stride=1, padding=dilation)\n", " g_ero = 1.0 - F.max_pool2d(1.0 - gt, k, stride=1, padding=dilation)\n", " p_bnd = (p_dil - p_ero).clamp(0, 1)\n", " g_bnd = (g_dil - g_ero).clamp(0, 1)\n", " inter = (p_bnd * g_bnd).sum(dim=(1, 2, 3))\n", " union = (p_bnd + g_bnd - p_bnd * g_bnd).sum(dim=(1, 2, 3))\n", " return (1.0 - (inter + eps) / (union + eps)).mean()\n", "\n", "\n", "def _soft_biou_loss(p: torch.Tensor, gt: torch.Tensor,\n", " eps: float = 1e-6) -> torch.Tensor:\n", " \"\"\"Multi-scale differentiable BIoU at d=5 and d=12 only.\n", " FIX: Removed d=1 and d=2 dilation scales — they REWARD filling gaps <4px\n", " between parallel hair strands (max_pool2d at d=1 merges features 2px apart).\n", " FIX: Removed broken sigmoid(4*(p-0.5)) sharpening — it maps p=0.99→0.88,\n", " BLURRING confident predictions and creating gradient dead zones.\n", " Use raw sigmoid output directly.\"\"\"\n", " l5 = _soft_biou_loss_at(p, gt, dilation=5, eps=eps)\n", " l12 = _soft_biou_loss_at(p, gt, dilation=12, eps=eps)\n", " return 1.0 * l5 + 0.5 * l12\n", "\n", "\n", "def _erosion_consistency_loss(p: torch.Tensor, gt: torch.Tensor,\n", " erosion: int = 7, eps: float = 1e-6) -> torch.Tensor:\n", " \"\"\"\n", " Penalizes when prediction is 'fatter' than GT (fills in background gaps).\n", " Core fix for the hair-strand/ribbon collapse problem.\n", " \"\"\"\n", " k = 2 * erosion + 1\n", " p_ero = 1.0 - F.max_pool2d(1.0 - p, k, stride=1, padding=erosion)\n", " g_ero = 1.0 - F.max_pool2d(1.0 - gt, k, stride=1, padding=erosion)\n", " \n", " inter = (p_ero * g_ero).sum(dim=(1, 2, 3))\n", " union = (p_ero + g_ero - p_ero * g_ero).sum(dim=(1, 2, 3))\n", " iou_ero = (inter + eps) / (union + eps)\n", " \n", " fp_blob = F.relu(p_ero - g_ero)\n", " fp_penalty = fp_blob.mean(dim=(1, 2, 3)).mean()\n", " \n", " return (1.0 - iou_ero).mean() + 0.5 * fp_penalty\n", "\n", "\n", "_SOBEL_X = torch.tensor([[-1., 0., 1.], [-2., 0., 2.], [-1., 0., 1.]]).view(1, 1, 3, 3) / 8.0\n", "_SOBEL_Y = torch.tensor([[-1., -2., -1.], [0., 0., 0.], [1., 2., 1.]]).view(1, 1, 3, 3) / 8.0\n", "_LAPLACIAN = torch.tensor([[0., 1., 0.], [1., -4., 1.], [0., 1., 0.]]).view(1, 1, 3, 3)\n", "\n", "def _gradient_loss(p: torch.Tensor, gt: torch.Tensor) -> torch.Tensor:\n", " \"\"\"Boundary-masked Sobel + Laplacian edge sharpness loss.\n", " Only penalizes gradient/sharpness errors within a 5px boundary band\n", " (where edges actually are), avoiding 50× dilution from flat interior pixels.\n", " Laplacian (2nd derivative) directly penalizes fuzzy vs sharp transitions.\"\"\"\n", " kx = _SOBEL_X.to(device=p.device, dtype=p.dtype)\n", " ky = _SOBEL_Y.to(device=p.device, dtype=p.dtype)\n", " kl = _LAPLACIAN.to(device=p.device, dtype=p.dtype)\n", "\n", " pred_pad = F.pad(p, (1, 1, 1, 1), mode='replicate')\n", " gt_pad = F.pad(gt, (1, 1, 1, 1), mode='replicate')\n", "\n", " pred_gx = F.conv2d(pred_pad, kx, padding=0)\n", " pred_gy = F.conv2d(pred_pad, ky, padding=0)\n", " gt_gx = F.conv2d(gt_pad, kx, padding=0)\n", " gt_gy = F.conv2d(gt_pad, ky, padding=0)\n", "\n", " pred_lap = F.conv2d(pred_pad, kl, padding=0)\n", " gt_lap = F.conv2d(gt_pad, kl, padding=0)\n", "\n", " # Boundary mask: tightened to 2px band (was 5px/11-kernel which included 9px of flat\n", " # interior/exterior that diluted the per-pixel signal). Sobel detects at 1px scale;\n", " # 2px band matches the Sobel kernel's effective gradient detection range.\n", " gt_dil = F.max_pool2d(gt, 5, stride=1, padding=2)\n", " gt_ero = 1.0 - F.max_pool2d(1.0 - gt, 5, stride=1, padding=2)\n", " bnd_mask = (gt_dil - gt_ero).clamp(0, 1)\n", " n_bnd = bnd_mask.sum().clamp(min=1.0)\n", "\n", " # Boundary-masked Sobel L1\n", " loss_x = (torch.abs(pred_gx - gt_gx) * bnd_mask).sum() / n_bnd\n", " loss_y = (torch.abs(pred_gy - gt_gy) * bnd_mask).sum() / n_bnd\n", "\n", " # Boundary-masked Laplacian L1 (sharpness)\n", " loss_lap = (torch.abs(pred_lap - gt_lap) * bnd_mask).sum() / n_bnd\n", "\n", " return loss_x + loss_y + 0.5 * loss_lap\n", "\n", "\n", "def _l1_loss(p: torch.Tensor, gt: torch.Tensor) -> torch.Tensor:\n", " return F.l1_loss(p, gt)\n", "\n", "\n", "def _confidence_loss(p: torch.Tensor, gt: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:\n", " \"\"\"Penalizes indecisive (soft) predictions on interior/exterior pixels.\n", " Interior = pixels >5px from any boundary edge.\n", " Loss = 4*p*(1-p) which peaks at p=0.5 (max uncertainty) and is zero at p=0/1.\n", " This directly forces the model to commit to 0 or 1 instead of hedging at 0.8.\n", " Only applied to interior pixels — boundary pixels are allowed to be soft\n", " (anti-aliasing is acceptable at edges).\"\"\"\n", " # Interior of foreground: erode GT by 5px\n", " gt_ero = 1.0 - F.max_pool2d(1.0 - gt, 11, stride=1, padding=5)\n", " # Interior of background: erode (1-GT) by 5px\n", " bg_ero = 1.0 - F.max_pool2d(gt, 11, stride=1, padding=5)\n", " # Interior mask: both FG interior and BG interior\n", " interior = (gt_ero + bg_ero).clamp(0, 1)\n", "\n", " # Uncertainty: 4*p*(1-p), peaks at p=0.5, zero at p=0 or p=1\n", " uncertainty = 4.0 * p * (1.0 - p)\n", " n_int = interior.sum().clamp(min=1.0)\n", " return (uncertainty * interior).sum() / n_int\n", "\n", "\n", "class ToonLoss(nn.Module):\n", " def __init__(self, cfg: Config, phase: int = 1):\n", " super().__init__()\n", " self.cfg = cfg\n", " self.phase = phase\n", " self._adaptive_w_bnd: Optional[float] = None\n", " self._set_weights(phase)\n", " import kornia\n", " self._ssim_loss_fn = kornia.losses.SSIMLoss(window_size=11, reduction=\"mean\")\n", "\n", " def _set_weights(self, phase: int):\n", " i = phase - 1\n", " self.w_db = self.cfg.w_dicebce[i]\n", " self.w_lovasz = self.cfg.w_lovasz[i]\n", " self.w_mae = self.cfg.w_mae[i]\n", " self.w_ssim = self.cfg.w_ssim[i]\n", " self.w_grad = self.cfg.w_grad[i]\n", " self.w_struct = self.cfg.w_struct[i]\n", " self.w_bnd = self.cfg.w_bnd[i]\n", " self.w_biou = self.cfg.w_biou[i]\n", " self.w_aux = self.cfg.w_aux[i]\n", " self.w_erosion = self.cfg.w_erosion[i] if hasattr(self.cfg, \"w_erosion\") else 0.0\n", " self.w_confidence = self.cfg.w_confidence[i] if hasattr(self.cfg, \"w_confidence\") else 0.0\n", "\n", " def set_phase(self, phase: int):\n", " self.phase = phase\n", " self._set_weights(phase)\n", " self._adaptive_w_bnd = None\n", " print(f\" Loss: phase={phase} db={self.w_db} lovasz={self.w_lovasz} \"\n", " f\"mae={self.w_mae} ssim={self.w_ssim} grad={self.w_grad} \"\n", " f\"struct={self.w_struct} bnd={self.w_bnd} biou={self.w_biou} \"\n", " f\"ero={getattr(self, 'w_erosion', 0.0)} conf={getattr(self, 'w_confidence', 0.0)} \"\n", " f\"aux={self.w_aux}\")\n", "\n", " def update_adaptive_bnd(self, biou_delta: float):\n", " # TUNE D: DISABLED adaptive boundary weight decay.\n", " # Analysis showed it was monotonically decaying from 0.200→0.1825 because\n", " # biou_delta > 0.3 fires every epoch (BIoU keeps improving). This erodes\n", " # boundary supervision over time — the opposite of what Phase 2 needs.\n", " # The configured w_bnd values are now used directly without modification.\n", " pass\n", "\n", " @property\n", " def effective_w_bnd(self) -> float:\n", " return self._adaptive_w_bnd if self._adaptive_w_bnd is not None else self.w_bnd\n", "\n", " def state_dict(self) -> dict:\n", " return dict(phase=self.phase, adaptive_w_bnd=self._adaptive_w_bnd)\n", "\n", " def load_state_dict(self, sd: dict):\n", " ph = sd.get(\"phase\", self.phase)\n", " self._set_weights(ph)\n", " self.phase = ph\n", " saved = sd.get(\"adaptive_w_bnd\", None)\n", " if saved is None:\n", " self._adaptive_w_bnd = None\n", " else:\n", " cap = self.w_bnd * 1.5\n", " self._adaptive_w_bnd = max(min(saved, cap), self.w_bnd)\n", "\n", " def forward(self, preds: List[torch.Tensor],\n", " gt: torch.Tensor) -> Tuple[torch.Tensor, dict]:\n", " main = preds[-1]\n", " gt_r = F.interpolate(gt, size=main.shape[2:], mode=\"bilinear\", align_corners=False)\n", " p = main.sigmoid()\n", "\n", " db = _dice_bce_loss(main, p, gt_r)\n", " if self.w_lovasz > 0.0:\n", " lov = _lovasz_hinge_loss(main, gt_r)\n", " else:\n", " lov = torch.zeros(1, device=main.device)\n", " mae = _l1_loss(p, gt_r)\n", " ssim = self._ssim_loss_fn(p, gt_r)\n", " grad = _gradient_loss(p, gt_r)\n", " bnd = _multiscale_boundary_bce_loss(main, gt_r,\n", " bce_clamp=self.cfg.bnd_bce_clamp)\n", " if self.w_struct > 0.0:\n", " struct = _structure_loss(main, p, gt_r)\n", " else:\n", " struct = torch.zeros(1, device=main.device)\n", "\n", " total = (self.w_db * db +\n", " self.w_lovasz * lov +\n", " self.w_mae * mae +\n", " self.w_ssim * ssim +\n", " self.w_grad * grad +\n", " self.effective_w_bnd * bnd +\n", " self.w_struct * struct)\n", "\n", " if self.w_biou > 0:\n", " biou_l = _soft_biou_loss(p, gt_r)\n", " total = total + self.w_biou * biou_l\n", " else:\n", " biou_l = torch.zeros(1, device=main.device)\n", "\n", " if hasattr(self, \"w_erosion\") and self.w_erosion > 0:\n", " ero_l = _erosion_consistency_loss(p, gt_r)\n", " total = total + self.w_erosion * ero_l\n", " else:\n", " ero_l = torch.zeros(1, device=main.device)\n", "\n", " if hasattr(self, \"w_confidence\") and self.w_confidence > 0:\n", " conf_l = _confidence_loss(p, gt_r)\n", " total = total + self.w_confidence * conf_l\n", " else:\n", " conf_l = torch.zeros(1, device=main.device)\n", "\n", " if self.w_aux > 0 and len(preds) > 1:\n", " aux_loss = 0.0\n", " for aux in preds[:-1]:\n", " gt_a = F.interpolate(gt, size=aux.shape[2:], mode=\"bilinear\",\n", " align_corners=False)\n", " aux_p = aux.sigmoid()\n", " aux_loss = aux_loss + _dice_bce_loss(aux, aux_p, gt_a)\n", " total = total + self.w_aux * (aux_loss / max(len(preds)-1, 1))\n", "\n", " parts = dict(db=db.detach(), lovasz=lov.detach(), mae=mae.detach(),\n", " ssim=ssim.detach(), grad=grad.detach(), bnd=bnd.detach(),\n", " biou_l=biou_l.detach(), struct=struct.detach(), ero=ero_l.detach(),\n", " conf=conf_l.detach())\n", " return total, parts\n", "\n", "@torch.no_grad()\n", "def compute_metrics_gpu(pred: torch.Tensor, gt: torch.Tensor,\n", " dilation: int = 5, is_logit: bool = True) -> dict:\n", "\n", " if is_logit:\n", " p = (pred.sigmoid() > 0.5).float()\n", " else:\n", " p = (pred > 0.5).float()\n", " g = (gt > 0.5).float()\n", "\n", " p_dil = (F.max_pool2d(p, 2*dilation+1, stride=1, padding=dilation) > 0.5).float()\n", " p_ero = 1.0 - (F.max_pool2d(1.0-p, 2*dilation+1, stride=1, padding=dilation) > 0.5).float()\n", " g_dil = (F.max_pool2d(g, 2*dilation+1, stride=1, padding=dilation) > 0.5).float()\n", " g_ero = 1.0 - (F.max_pool2d(1.0-g, 2*dilation+1, stride=1, padding=dilation) > 0.5).float()\n", " p_bnd = (p_dil - p_ero).clamp(0, 1)\n", " g_bnd = (g_dil - g_ero).clamp(0, 1)\n", "\n", " inter_b = (p_bnd * g_bnd).sum()\n", " union_b = (p_bnd + g_bnd - p_bnd * g_bnd).sum()\n", " # Standard Boundary IoU convention: if both pred and GT have no boundary\n", " # pixels in the crop, the prediction is perfect (BIoU=100). Previously this\n", " # returned 0/eps ≈ 0 which artificially penalised correct predictions on\n", " # boundary-free crops, capping the average crop-BIoU.\n", " biou = 100.0 if union_b.item() < 1e-6 else 100.0 * (inter_b / union_b).item()\n", "\n", " d2 = 2\n", " p_dil2 = (F.max_pool2d(p, 2*d2+1, stride=1, padding=d2) > 0.5).float()\n", " p_ero2 = 1.0 - (F.max_pool2d(1.0-p, 2*d2+1, stride=1, padding=d2) > 0.5).float()\n", " g_dil2 = (F.max_pool2d(g, 2*d2+1, stride=1, padding=d2) > 0.5).float()\n", " g_ero2 = 1.0 - (F.max_pool2d(1.0-g, 2*d2+1, stride=1, padding=d2) > 0.5).float()\n", " p_bnd2 = (p_dil2 - p_ero2).clamp(0, 1)\n", " g_bnd2 = (g_dil2 - g_ero2).clamp(0, 1)\n", " inter_b2 = (p_bnd2 * g_bnd2).sum()\n", " union_b2 = (p_bnd2 + g_bnd2 - p_bnd2 * g_bnd2).sum()\n", " biou_d2 = 100.0 if union_b2.item() < 1e-6 else 100.0 * (inter_b2 / union_b2).item()\n", "\n", " inter_s = (p * g).sum()\n", " union_s = (p + g - p * g).sum()\n", " iou = 100.0 if union_s.item() < 1e-6 else 100.0 * (inter_s / union_s).item()\n", "\n", " pa = 100.0 * ((p == g).float().mean()).item()\n", "\n", " return dict(biou=biou, biou_d2=biou_d2, pa=pa, iou=iou)\n", "\n", "\n", "@torch.no_grad()\n", "def compute_matting_metrics(pred_prob: torch.Tensor, gt: torch.Tensor) -> dict:\n", " diff = torch.abs(pred_prob - gt)\n", " sad = diff.mean().item() * 1000.0\n", " mse = (diff ** 2).mean().item()\n", " return {\"sad\": sad, \"mse\": mse}\n", "\n", "_NORM_MEAN = torch.tensor(_MEAN).view(3, 1, 1)\n", "_NORM_STD = torch.tensor(_STD).view(3, 1, 1)\n", "\n", "@torch.no_grad()\n", "def _run_model(model, tensor: torch.Tensor) -> np.ndarray:\n", " with torch.amp.autocast(\"cuda\", dtype=AMP_DTYPE):\n", " raw = model(tensor)\n", " preds = _safe_preds(_normalize_preds(raw))\n", " return preds[-1].sigmoid().squeeze().cpu().float().numpy()\n", "\n", "_GAUSS_W_CACHE: dict = {}\n", "\n", "def _make_gaussian_weight(size: int) -> np.ndarray:\n", " if size not in _GAUSS_W_CACHE:\n", " sigma = size / 4.0\n", " coords = np.linspace(-size//2, size//2, size)\n", " xs, ys = np.meshgrid(coords, coords)\n", " w = np.exp(-(xs**2 + ys**2) / (2 * sigma**2))\n", " w /= w.max()\n", " _GAUSS_W_CACHE[size] = w.astype(np.float32)\n", " return _GAUSS_W_CACHE[size]\n", "\n", "def gaussian_tile_predict(model, img_rgb: np.ndarray, crop_size: int,\n", " overlap_frac: float, device: torch.device\n", " ) -> Tuple[np.ndarray, np.ndarray]:\n", "\n", " H, W = img_rgb.shape[:2]\n", " stride = max(1, int(crop_size * (1.0 - overlap_frac)))\n", "\n", " gauss_w = _make_gaussian_weight(crop_size)\n", " accum_m = np.zeros((H, W), dtype=np.float32)\n", " weights = np.zeros((H, W), dtype=np.float32)\n", "\n", " ys = list(range(0, max(1, H - crop_size + 1), stride))\n", " if not ys or ys[-1] + crop_size < H: ys.append(max(0, H - crop_size))\n", " xs = list(range(0, max(1, W - crop_size + 1), stride))\n", " if not xs or xs[-1] + crop_size < W: xs.append(max(0, W - crop_size))\n", "\n", " tiles_info = []\n", " tensors = []\n", " for y0 in ys:\n", " for x0 in xs:\n", " y1 = min(y0 + crop_size, H); x1 = min(x0 + crop_size, W)\n", " th = y1 - y0; tw = x1 - x0\n", " tile_rgb = img_rgb[y0:y1, x0:x1]\n", " if th < crop_size or tw < crop_size:\n", " tile_rgb = cv2.copyMakeBorder(\n", " tile_rgb, 0, crop_size - th, 0, crop_size - tw,\n", " cv2.BORDER_REFLECT_101)\n", " t_img = torch.from_numpy(tile_rgb).permute(2, 0, 1).float() / 255.0\n", " t_img = (t_img - _NORM_MEAN) / _NORM_STD\n", " tensors.append(t_img)\n", " tiles_info.append((y0, y1, x0, x1, th, tw))\n", "\n", " if not tensors:\n", " return accum_m, np.zeros_like(accum_m)\n", "\n", " # batch_size=2: the original working value. The comment 'raised from 2,\n", " # no-grad path has no activation storage' was WRONG — torch.no_grad() only\n", " # skips gradient tape, but every layer still materialises its output tensor\n", " # in VRAM until the next layer consumes it. With Swin-B at 1024×1024:\n", " # batch=8 → ~7.5 GB peak (OOM on 20 GB MIG after 12 GB training footprint)\n", " # batch=2 → ~1.9 GB peak (safe)\n", " # Restoring to 2; tile inference is not compute-bound so throughput is unchanged.\n", " batch_size = 2\n", " masks_all = []\n", " for i in range(0, len(tensors), batch_size):\n", " batch = torch.stack(tensors[i:i+batch_size]).to(device)\n", " with torch.amp.autocast(\"cuda\", dtype=AMP_DTYPE):\n", " raw = model(batch)\n", " preds = _safe_preds(_normalize_preds(raw))\n", " probs = preds[-1].sigmoid().squeeze(1).cpu().float().numpy()\n", " if probs.ndim == 2: probs = probs[np.newaxis, ...]\n", " masks_all.extend(probs)\n", "\n", " for (y0, y1, x0, x1, th, tw), tile_mask in zip(tiles_info, masks_all):\n", " # Bug 3 fix: the original |2p-1| confidence is direction-blind —\n", " # a tile predicting 0.1 (background) gets the same conf=0.8 as one\n", " # predicting 0.9 (foreground). When an early-training tile confidently\n", " # predicts the WRONG class it overrides the correct global pass.\n", " # Fix: accumulate the raw probability directly; defer confidence\n", " # to the global-vs-tile agreement step in two_pass_predict.\n", " gw = gauss_w[:th, :tw]\n", " accum_m[y0:y1, x0:x1] += tile_mask[:th, :tw] * gw\n", " weights[y0:y1, x0:x1] += gw\n", "\n", " weights = np.maximum(weights, 1e-6)\n", " # Return the Gaussian-weighted average and a sentinel conf array of ones\n", " # (signals \"use agreement-aware fusion\" in two_pass_predict).\n", " return accum_m / weights, np.ones_like(accum_m)\n", "\n", "@torch.no_grad()\n", "def fast_global_predict(model, img_rgb: np.ndarray, cfg: Config,\n", " device: torch.device) -> np.ndarray:\n", " \"\"\"Fast 1-pass global evaluation (the global branch of two_pass_predict).\n", " Runs a single resized forward pass at crop_size without multi-tile fusion.\n", " Used for rapid hard-negative difficulty scoring (~10x faster than full tiling).\"\"\"\n", " C = cfg.crop_size\n", " H, W = img_rgb.shape[:2]\n", " scale = C / max(H, W)\n", " nH, nW = max(1, int(H*scale)), max(1, int(W*scale))\n", " img_r = cv2.resize(img_rgb, (nW, nH), interpolation=cv2.INTER_LINEAR)\n", " ph = max(0, C - nH); pw = max(0, C - nW)\n", " g_pad = cv2.copyMakeBorder(img_r, ph//2, ph-ph//2, pw//2, pw-pw//2,\n", " cv2.BORDER_REFLECT_101)\n", " t_in = torch.from_numpy(g_pad).permute(2, 0, 1).float() / 255.0\n", " t_in = ((t_in - _NORM_MEAN) / _NORM_STD).unsqueeze(0).to(device)\n", " g_sq = _run_model(model, t_in)\n", " if g_sq.ndim == 2:\n", " g_crop = g_sq[ph//2: ph//2 + nH, pw//2: pw//2 + nW]\n", " g_mask = cv2.resize(g_crop, (W, H), interpolation=cv2.INTER_LINEAR)\n", " else:\n", " g_mask = np.zeros((H, W), dtype=np.float32)\n", " return g_mask.clip(0, 1).astype(np.float32)\n", "\n", "\n", "@torch.no_grad()\n", "def two_pass_predict(model, img_rgb: np.ndarray, cfg: Config,\n", " device: torch.device, tta: bool = False) -> np.ndarray:\n", "\n", " C = cfg.crop_size\n", " H, W = img_rgb.shape[:2]\n", "\n", " def _once(img):\n", "\n", " scale = C / max(img.shape[:2])\n", " nH, nW = int(img.shape[0]*scale), int(img.shape[1]*scale)\n", " img_r = cv2.resize(img, (nW, nH), interpolation=cv2.INTER_LINEAR)\n", " ph = C - nH; pw = C - nW\n", " g_pad = cv2.copyMakeBorder(img_r, ph//2, ph-ph//2, pw//2, pw-pw//2,\n", " cv2.BORDER_REFLECT_101)\n", " t_in = torch.from_numpy(g_pad).permute(2, 0, 1).float() / 255.0\n", " t_in = ((t_in - _NORM_MEAN) / _NORM_STD).unsqueeze(0).to(device)\n", " g_sq = _run_model(model, t_in)\n", " g_crop = g_sq[ph//2: ph//2 + nH, pw//2: pw//2 + nW]\n", " g_mask = cv2.resize(g_crop, (img.shape[1], img.shape[0]),\n", " interpolation=cv2.INTER_LINEAR)\n", "\n", " if max(img.shape[:2]) <= C:\n", " t_mask = g_mask\n", " # Image fits in one crop — no tiling needed; tile weight = 0 so\n", " # the global pass result is used unchanged.\n", " agree_w = np.zeros_like(g_mask, dtype=np.float32)\n", " else:\n", " t_mask, _ = gaussian_tile_predict(\n", " model, img, C, cfg.inference_overlap, device)\n", "\n", " # LARGE-CANVAS FIX: The original agreement-aware fusion had a critical bug\n", " # for large images (>1.5× crop_size, e.g. 2400px canvas):\n", " # The global pass downscales thin structures (diagonal swords, hair tips) to\n", " # sub-pixel size, so g_mask returns 0.0 on those pixels.\n", " # agree = 1 - |t_mask - g_mask| then gives agree≈0 on correct tile predictions,\n", " # which suppresses them and forces final≈g_mask≈0 — erasing the correct result.\n", " #\n", " # Fix: for images >1.5×C, bias the blend toward TILES on a per-pixel basis.\n", " # Pixels where the tile is confident (far from 0.5) and the global is uncertain\n", " # (close to 0.5 due to downscaling blur) trust the tile. Only suppress the tile\n", " # when the global is also confident but disagrees (genuine contradiction).\n", " canvas_scale = max(img.shape[:2]) / C\n", " if canvas_scale > 1.5:\n", " # Tile confidence: how far from 0.5 (uncertain) is the tile prediction?\n", " tile_conf = np.abs(t_mask - 0.5) * 2.0 # [0,1]: 0=uncertain, 1=fully confident\n", " # Global confidence: far from 0.5 means global has a clear opinion\n", " glob_conf = np.abs(g_mask - 0.5) * 2.0\n", " # Agreement: same sign = agreeing, different sign = contradicting\n", " same_sign = ((t_mask > 0.5) == (g_mask > 0.5)).astype(np.float32)\n", " # Trust tile when: tile is confident OR global is uncertain (blurred by downscale)\n", " # Suppress tile only when: global is confident AND they disagree\n", " # agree_w: high → trust tile, low → trust global\n", " agree_w = np.clip(\n", " tile_conf * (1.0 - glob_conf * (1.0 - same_sign)),\n", " 0.0, 1.0\n", " ).astype(np.float32)\n", " else:\n", " # Original agreement-aware fusion for normal-size images\n", " agree = 1.0 - np.abs(t_mask - g_mask) # 1=agree, 0=opposite\n", " agree_w = np.clip(agree, 0.0, 1.0)\n", "\n", " # Blend: tile_biased regions use tile result, global-biased use global\n", " final = agree_w * t_mask + (1.0 - agree_w) * g_mask\n", " return final.clip(0, 1).astype(np.float32)\n", "\n", " outs = [_once(img_rgb)]\n", " if tta:\n", " if cfg.tta_hflip:\n", "\n", " flipped = np.ascontiguousarray(img_rgb[:, ::-1, :])\n", " m_flipped = _once(flipped)\n", " outs.append(np.ascontiguousarray(m_flipped[:, ::-1]))\n", " if cfg.tta_scale and abs(cfg.tta_scale - 1.0) > 1e-3:\n", " s = cfg.tta_scale\n", " small = cv2.resize(img_rgb, None, fx=s, fy=s,\n", " interpolation=cv2.INTER_AREA if s < 1 else cv2.INTER_LINEAR)\n", " m_small = _once(small)\n", " outs.append(cv2.resize(m_small, (W, H), interpolation=cv2.INTER_LINEAR))\n", " return np.mean(outs, axis=0).clip(0, 1)\n", "\n", "class EMA:\n", " def __init__(self, model: nn.Module, decay: float = 0.9995):\n", " base = getattr(model, \"_orig_mod\", model)\n", " self.decay = decay\n", " self.shadow = {k: v.clone().float() for k, v in base.state_dict().items()}\n", "\n", " def update(self, model: nn.Module):\n", " base = getattr(model, \"_orig_mod\", model)\n", " with torch.no_grad():\n", " for k, v in base.state_dict().items():\n", " if k in self.shadow:\n", " if not v.is_floating_point():\n", " self.shadow[k].copy_(v)\n", " else:\n", " self.shadow[k].mul_(self.decay).add_(v.float(), alpha=1.0 - self.decay)\n", " else:\n", " self.shadow[k] = v.float().clone()\n", "\n", " def apply(self, model: nn.Module):\n", " base = getattr(model, \"_orig_mod\", model)\n", " # FIX: Persistent backup buffer — reuse via copy_() instead of clone()\n", " # to avoid allocating ~900MB per call (was 3.6GB/epoch wasted).\n", " sd = base.state_dict()\n", " if not hasattr(self, '_backup') or not self._backup:\n", " self._backup = {k: v.clone() for k, v in sd.items()}\n", " else:\n", " for k, v in sd.items():\n", " self._backup[k].copy_(v)\n", " base.load_state_dict({k: v.to(next(base.parameters()).device)\n", " for k, v in self.shadow.items()}, strict=False)\n", "\n", " def restore(self, model: nn.Module):\n", " base = getattr(model, \"_orig_mod\", model)\n", " base.load_state_dict(self._backup)\n", "\n", " def state_dict(self): return {k: v.cpu() for k, v in self.shadow.items()}\n", "\n", " def load_state_dict(self, sd, device):\n", " self.shadow = {k: v.to(device).float() for k, v in sd.items()}\n", "\n", " def register_new(self, model: nn.Module):\n", " base = getattr(model, \"_orig_mod\", model)\n", " for k, v in base.state_dict().items():\n", " if k not in self.shadow:\n", " self.shadow[k] = v.float().clone()\n", "\n", "class PhaseScheduler:\n", " def __init__(self, cfg: Config):\n", " self.cfg = cfg\n", " self.phase = 1\n", " self.phase_ep = 0\n", " self._biou_history: List[float] = []\n", " self._best_in_phase = 0.0\n", "\n", " def step(self, biou: float) -> Tuple[bool, int]:\n", " self.phase_ep += 1\n", " self._biou_history.append(biou)\n", " if biou > self._best_in_phase: self._best_in_phase = biou\n", "\n", " max_ep = self.cfg.max_phase_epochs[self.phase - 1]\n", " if self.phase >= 3:\n", " return False, self.phase\n", "\n", " patience = self.cfg.phase_patience\n", " if self.phase_ep >= max_ep:\n", " return self._transition()\n", "\n", " if len(self._biou_history) >= patience:\n", " recent_delta = max(self._biou_history[-patience:]) - \\\n", " min(self._biou_history[-patience:])\n", " if recent_delta < self.cfg.phase_min_delta:\n", " print(f\" Phase {self.phase} plateau (Δ={recent_delta:.3f}) — advancing\")\n", " return self._transition()\n", "\n", " return False, self.phase\n", "\n", " def _transition(self) -> Tuple[bool, int]:\n", " self.phase += 1\n", " self.phase_ep = 0\n", " self._biou_history.clear()\n", " self._best_in_phase = 0.0\n", " print(f\"\\n{'━'*60}\\n ▶ Phase {self.phase} begin\\n{'━'*60}\")\n", " return True, self.phase\n", "\n", " def state_dict(self) -> dict:\n", " return dict(phase=self.phase, phase_ep=self.phase_ep,\n", " biou_history=self._biou_history,\n", " best_in_phase=self._best_in_phase)\n", "\n", " def load_state_dict(self, sd: dict):\n", " self.phase = sd.get(\"phase\", 1)\n", " self.phase_ep = sd.get(\"phase_ep\", 0)\n", " self._biou_history = sd.get(\"biou_history\", [])\n", " self._best_in_phase = sd.get(\"best_in_phase\", 0.0)\n", "\n", "class CheckpointManager:\n", " _SLOTS = [\"ckpt_A.pth\", \"ckpt_B.pth\", \"ckpt_C.pth\"]\n", " _BEST = \"best_ema.pth\"\n", "\n", " def __init__(self, drive_dir: str):\n", " self.dir = Path(drive_dir)\n", " self.dir.mkdir(parents=True, exist_ok=True)\n", " self._slot = 0\n", " self._latest_path: Optional[Path] = None\n", "\n", " def _atomic_save(self, path: Path, payload: dict) -> bool:\n", " tmp = path.with_suffix(\".tmp\")\n", " try:\n", " torch.save(payload, tmp)\n", " sz = tmp.stat().st_size\n", " if sz < 1000:\n", " tmp.unlink(missing_ok=True); return False\n", "\n", " tmp.replace(path)\n", " return True\n", " except Exception as e:\n", " tmp.unlink(missing_ok=True)\n", " print(f\" ✗ Save failed ({path.name}): {e}\"); return False\n", "\n", " def scan_all(self):\n", " skip = {\"best_ema_weights.pth\"}\n", " best = None; best_ep = -1\n", " for p in sorted(self.dir.glob(\"*.pth\")):\n", " if p.name in skip: continue\n", " try:\n", " sd = torch.load(p, map_location=\"cpu\", weights_only=False)\n", " ep = sd.get(\"epoch\", 0)\n", " if isinstance(ep, int) and ep > best_ep:\n", " best_ep = ep; best = p\n", " except Exception:\n", " pass\n", " self._latest_path = best\n", " if best:\n", " print(f\" Latest checkpoint: {best.name} (epoch {best_ep})\")\n", " else:\n", " print(\" No resumable checkpoint found — fresh start\")\n", "\n", " def save(self, epoch: int, payload: dict) -> bool:\n", " path = self.dir / self._SLOTS[self._slot % len(self._SLOTS)]\n", " self._slot += 1\n", " ok = self._atomic_save(path, payload)\n", " if ok: self._latest_path = path\n", " return ok\n", "\n", " def save_best(self, epoch: int, payload: dict, biou: float) -> bool:\n", " path = self.dir / self._BEST\n", " print(f\" ★ New best BIoU={biou:.2f}% — saving {self._BEST}\")\n", " return self._atomic_save(path, payload)\n", "\n", " def save_ema_weights_only(self, ema_sd: dict, biou: float) -> bool:\n", " path = self.dir / \"best_ema_weights.pth\"\n", " tmp = path.with_suffix(\".tmp\")\n", " try:\n", " torch.save({k: v.cpu() for k, v in ema_sd.items()}, tmp)\n", " if tmp.stat().st_size < 1000:\n", " tmp.unlink(missing_ok=True); return False\n", " tmp.replace(path)\n", " print(f\" ★ EMA weights saved → {path.name} (BIoU={biou:.2f}%)\")\n", " return True\n", " except Exception as e:\n", " tmp.unlink(missing_ok=True)\n", " print(f\" ✗ EMA weights save failed: {e}\"); return False\n", "\n", " def load_latest(self) -> Optional[dict]:\n", " if self._latest_path and self._latest_path.exists():\n", " try:\n", " sd = torch.load(self._latest_path, map_location=\"cpu\", weights_only=False)\n", " print(f\" Loaded {self._latest_path.name} (epoch {sd.get('epoch','?')})\")\n", " return sd\n", " except Exception as e:\n", " print(f\" ✗ {self._latest_path.name} load failed: {e}\")\n", " return None\n", "\n", "class CSVLogger:\n", " def __init__(self, path: str):\n", " self.path = Path(path); self.path.parent.mkdir(parents=True, exist_ok=True)\n", " self._header_written = False\n", " if self.path.exists():\n", " with open(self.path, \"r\") as f:\n", " first = f.readline().strip()\n", " self._existing_fields = first.split(\",\") if first else []\n", " self._header_written = bool(self._existing_fields)\n", " else:\n", " self._existing_fields = []\n", "\n", " def log(self, row: dict):\n", " if self._header_written and set(row.keys()) != set(self._existing_fields):\n", " old = self.path.with_suffix(\".csv.old\")\n", " self.path.rename(old)\n", " self._header_written = False\n", " print(f\" CSV schema changed — rotated old log to {old.name}\")\n", " with open(self.path, \"a\", newline=\"\") as f:\n", " w = csv.DictWriter(f, fieldnames=row.keys())\n", " if not self._header_written:\n", " w.writeheader(); self._header_written = True\n", " self._existing_fields = list(row.keys())\n", " w.writerow(row)\n", "\n", "def set_grad_checkpointing(model: nn.Module, enable: bool) -> int:\n", " base = getattr(model, \"_orig_mod\", model)\n", " n = 0\n", " for _, m in base.named_modules():\n", " if hasattr(m, \"use_checkpoint\"):\n", " m.use_checkpoint = enable; n += 1\n", " if hasattr(m, \"gradient_checkpointing\"):\n", " m.gradient_checkpointing = enable\n", " tag = \"ON\" if enable else \"OFF\"\n", " if n: print(f\" Gradient checkpointing: {tag} on {n} modules\")\n", " return n\n", "\n", "def _safe_blk_fwd(blk, x, mask, h, w):\n", " blk.H = h; blk.W = w\n", " return blk(x, mask)\n", "\n", "def _patch_swin_checkpoint_safety(model: nn.Module):\n", " import torch.utils.checkpoint as cp\n", " patched = 0\n", " for module in model.modules():\n", " if type(module).__name__ != \"BasicLayer\" or not hasattr(module, \"blocks\"):\n", " continue\n", " src = sys.modules.get(type(module).__module__)\n", " wp_func = getattr(src, \"window_partition\", None) if src else None\n", " if wp_func is None: continue\n", "\n", " def _make_fwd(layer, wp):\n", " def _fwd(self, x, H, W):\n", " ws = self.window_size\n", " Hp = int(math.ceil(H/ws))*ws\n", " Wp = int(math.ceil(W/ws))*ws\n", " img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device)\n", " h_sl = (slice(0, -ws), slice(-ws, -(ws//2)), slice(-(ws//2), None))\n", " w_sl = (slice(0, -ws), slice(-ws, -(ws//2)), slice(-(ws//2), None))\n", " cnt = 0\n", " for hs in h_sl:\n", " for ws_ in w_sl:\n", " img_mask[:, hs, ws_, :] = cnt; cnt += 1\n", " mw = wp(img_mask, ws).view(-1, ws*ws)\n", " attn_mask = mw.unsqueeze(1) - mw.unsqueeze(2)\n", " attn_mask = (attn_mask.masked_fill(attn_mask != 0, -100.0)\n", " .masked_fill(attn_mask == 0, 0.0)\n", " .to(x.dtype))\n", " for blk in self.blocks:\n", " blk.H, blk.W = H, W\n", " if self.use_checkpoint:\n", " x = cp.checkpoint(_safe_blk_fwd, blk, x, attn_mask, H, W,\n", " use_reentrant=False)\n", " else:\n", " x = blk(x, attn_mask)\n", " if self.downsample is not None:\n", " xd = self.downsample(x, H, W)\n", " return x, H, W, xd, (H+1)//2, (W+1)//2\n", " return x, H, W, x, H, W\n", " return _fwd\n", " module.forward = types.MethodType(_make_fwd(module, wp_func), module)\n", " patched += 1\n", " if patched:\n", " print(f\" ✓ Patched {patched} BasicLayer(s) for safe checkpointing\")\n", "\n", "def load_model(cfg: Config, device: torch.device) -> nn.Module:\n", " from transformers import logging as hf_logging\n", " hf_logging.set_verbosity_info()\n", " _ = torch.zeros(1, device=device)\n", " print(f\" Loading {cfg.model_id} …\")\n", " t = time.time()\n", " kwargs = dict(trust_remote_code=True, cache_dir=cfg.hf_cache)\n", " if cfg.revision:\n", " kwargs[\"revision\"] = cfg.revision\n", " model = AutoModelForImageSegmentation.from_pretrained(cfg.model_id, **kwargs)\n", " print(f\" from_pretrained: {time.time()-t:.1f}s\")\n", " t = time.time()\n", " model = model.to(device).float()\n", " print(f\" .to(device): {time.time()-t:.1f}s\")\n", " _patch_swin_checkpoint_safety(model)\n", " set_grad_checkpointing(model, False)\n", " total = sum(p.numel() for p in model.parameters())\n", " print(f\" Total params: {total:,}\")\n", " print(f\" ✓ Model ready (NCHW, eager BF16)\")\n", " return model\n", "\n", "def export_onnx(model: nn.Module, ema_sd: dict, out_dir: str,\n", " crop_size: int = 1024) -> Optional[str]:\n", "\n", " out_path = Path(out_dir) / \"best_ema.onnx\"\n", " print(f\"\\n Exporting ONNX → {out_path.name} (opset 17, {crop_size}×{crop_size}) …\")\n", " cpu_model = copy.deepcopy(getattr(model, \"_orig_mod\", model)).cpu().eval()\n", "\n", " set_grad_checkpointing(cpu_model, False)\n", " cpu_model.load_state_dict({k: v.cpu() for k, v in ema_sd.items()}, strict=False)\n", " dummy = torch.zeros(1, 3, crop_size, crop_size, dtype=torch.float32)\n", " try:\n", " torch.onnx.export(\n", " cpu_model, dummy, str(out_path),\n", " opset_version=17,\n", " input_names=[\"image\"], output_names=[\"mask\"],\n", " dynamic_axes={\"image\": {0: \"batch\"}, \"mask\": {0: \"batch\"}},\n", " do_constant_folding=True, export_params=True,\n", " )\n", " print(f\" ✓ ONNX saved ({out_path.stat().st_size / 1e6:.1f} MB)\")\n", " except Exception as e:\n", " print(f\" ✗ ONNX export failed: {e}\")\n", " out_path.unlink(missing_ok=True); return None\n", " try:\n", " import onnxruntime as ort\n", " sess = ort.InferenceSession(str(out_path), providers=[\"CPUExecutionProvider\"])\n", " out = sess.run(None, {\"image\": dummy.numpy()})\n", " print(f\" ✓ ONNXRuntime validation — output shape: {out[0].shape}\")\n", " except ImportError:\n", " print(\" ℹ onnxruntime not installed — skipping validation\")\n", " except Exception as e:\n", " print(f\" ⚠ ONNXRuntime validation failed: {e}\")\n", " del cpu_model\n", " return str(out_path)\n", "\n", "def _optimizer_state_to(opt: torch.optim.Optimizer, device: torch.device):\n", "\n", " for state in opt.state.values():\n", " for k, v in list(state.items()):\n", " if isinstance(v, torch.Tensor):\n", " state[k] = v.to(device, non_blocking=True)\n", "\n", "def _rng_state_dict() -> dict:\n", " return {\n", " \"python\": random.getstate(),\n", " \"numpy\": np.random.get_state(),\n", " \"torch\": torch.get_rng_state(),\n", " \"torch_cuda\": (torch.cuda.get_rng_state_all()\n", " if torch.cuda.is_available() else None),\n", " }\n", "\n", "def _rng_load_state_dict(sd: dict):\n", " try:\n", " random.setstate(sd[\"python\"])\n", " np.random.set_state(sd[\"numpy\"])\n", " torch.set_rng_state(sd[\"torch\"])\n", " if torch.cuda.is_available() and sd.get(\"torch_cuda\") is not None:\n", " torch.cuda.set_rng_state_all(sd[\"torch_cuda\"])\n", " except Exception as e:\n", " print(f\" ⚠ RNG restore failed ({e}) — continuing with current RNG\")\n", "\n", "def make_optimizer(model: nn.Module, phase: int, cfg: Config) -> torch.optim.Optimizer:\n", " use_fused = torch.cuda.is_available()\n", " lr_dec = cfg.lr_decoder_phase[phase - 1]\n", "\n", " def _split_decay(named_params, lr):\n", " \"\"\"Split parameters into decay / no-decay groups.\n", " FIX: bias and normalization params should NOT get weight decay\n", " (Loshchilov & Hutter, ICLR 2019; Swin Transformer official repo).\"\"\"\n", " decay, no_decay = [], []\n", " for n, p in named_params:\n", " if not p.requires_grad:\n", " continue\n", " if p.ndim <= 1 or 'bias' in n or 'norm' in n.lower():\n", " no_decay.append(p)\n", " else:\n", " decay.append(p)\n", " return [\n", " {\"params\": decay, \"lr\": lr, \"weight_decay\": cfg.weight_decay},\n", " {\"params\": no_decay, \"lr\": lr, \"weight_decay\": 0.0},\n", " ]\n", "\n", " if phase == 1:\n", " freeze_backbone(model)\n", " set_grad_checkpointing(model, False)\n", " base = getattr(model, \"_orig_mod\", model)\n", " groups = _split_decay(base.named_parameters(), lr_dec)\n", " n_decay = sum(p.numel() for p in groups[0][\"params\"])\n", " n_nodecay = sum(p.numel() for p in groups[1][\"params\"])\n", " print(f\" Phase 1 optimizer: decoder-only LR={lr_dec:.1e} fused={use_fused}\")\n", " print(f\" decay={n_decay:,} params no_decay={n_nodecay:,} params\")\n", " return torch.optim.AdamW(groups, fused=use_fused)\n", " if phase == 2:\n", " unfreeze_all(model)\n", " set_grad_checkpointing(model, True)\n", " else:\n", " unfreeze_all(model)\n", " set_grad_checkpointing(model, True)\n", " base = getattr(model, \"_orig_mod\", model)\n", " lr_bb = lr_dec * cfg.backbone_lr_frac[phase - 1]\n", " bb_named = [(n, p) for n, p in base.named_parameters() if 'bb.' in n]\n", " dec_named = [(n, p) for n, p in base.named_parameters() if 'bb.' not in n]\n", " groups = _split_decay(bb_named, lr_bb) + _split_decay(dec_named, lr_dec)\n", " print(f\" Phase {phase} optimizer: decoder={lr_dec:.1e} backbone={lr_bb:.1e} fused={use_fused}\")\n", " return torch.optim.AdamW(groups, fused=use_fused)\n", "\n", "def make_scheduler(opt, total_epochs, peak_lr):\n", " return torch.optim.lr_scheduler.CosineAnnealingLR(\n", " opt, T_max=max(1, total_epochs), eta_min=peak_lr * 0.05)\n", "\n", "class HoldThenCosineScheduler(torch.optim.lr_scheduler._LRScheduler):\n", " \"\"\"Sustains 100% peak LR for hold_ratio of T_max, then smoothly cosine-decays to eta_min.\n", " Solves the early-decay problem of standard CosineAnnealingLR where LR halves halfway through a phase.\"\"\"\n", " def __init__(self, optimizer, T_max, hold_ratio=0.60, eta_min=0.0, last_epoch=-1):\n", " self.T_max = max(1, T_max)\n", " self.hold_epochs = int(self.T_max * hold_ratio)\n", " self.decay_epochs = max(1, self.T_max - self.hold_epochs)\n", " self.eta_min = eta_min\n", " super().__init__(optimizer, last_epoch)\n", "\n", " def get_lr(self):\n", " if not self._get_lr_called_within_step:\n", " pass\n", " if self.last_epoch < self.hold_epochs:\n", " return [base_lr for base_lr in self.base_lrs]\n", " else:\n", " progress = (self.last_epoch - self.hold_epochs) / self.decay_epochs\n", " progress = min(1.0, max(0.0, progress))\n", " return [\n", " self.eta_min + (base_lr - self.eta_min) * 0.5 * (1 + math.cos(math.pi * progress))\n", " for base_lr in self.base_lrs\n", " ]\n", "\n", "def make_warmrestart_scheduler(opt, cfg, phase):\n", " peak = cfg.lr_decoder_phase[phase - 1]\n", " T_max = max(1, cfg.max_phase_epochs[phase - 1])\n", " # FIX: Phase 1 uses short hold (decoder-only converges fast).\n", " # Phase 2+ reduced from 0.60→0.30 to avoid double-hold with bb_warmup_epochs=5.\n", " # Old: 60% hold + 5ep warmup = 71% of phase at peak LR → only 12ep of actual decay.\n", " # New: 30% hold + 5ep warmup = 42% → 24ep of cosine decay for proper convergence.\n", " hold = 0.15 if phase == 1 else 0.30\n", " sched = HoldThenCosineScheduler(opt, T_max=T_max, hold_ratio=hold, eta_min=peak * 0.01)\n", " print(f\" Scheduler: hold-then-cosine peak={peak:.1e} hold={int(T_max*hold)}ep T_max={T_max}\")\n", " return sched\n", "\n", "def _release_dl(dl):\n", " try:\n", " if isinstance(dl, DualStreamLoader):\n", " dl.close()\n", " else:\n", " it = getattr(dl, \"_iterator\", None)\n", " if it is not None:\n", " it._shutdown_workers(); dl._iterator = None\n", " except Exception:\n", " pass\n", " gc.collect(); torch.cuda.empty_cache()\n", "\n", "def _val_collate(batch):\n", " max_h = max(max(b[0].shape[-2], b[1].shape[-2]) for b in batch)\n", " max_w = max(max(b[0].shape[-1], b[1].shape[-1]) for b in batch)\n", " imgs, masks = [], []\n", " for img, msk in batch:\n", " ph_i = max_h - img.shape[-2]\n", " pw_i = max_w - img.shape[-1]\n", " if ph_i > 0 or pw_i > 0:\n", " img = F.pad(img, (0, pw_i, 0, ph_i), value=0)\n", " ph_m = max_h - msk.shape[-2]\n", " pw_m = max_w - msk.shape[-1]\n", " if ph_m > 0 or pw_m > 0:\n", " msk = F.pad(msk, (0, pw_m, 0, ph_m), value=0)\n", " imgs.append(img)\n", " masks.append(msk)\n", " return torch.stack(imgs), torch.stack(masks)\n", "\n", "def _make_val_dl(ds, bs):\n", " return DataLoader(ds, batch_size=bs, shuffle=False,\n", " num_workers=min(4, CFG.num_workers), pin_memory=False,\n", " persistent_workers=True, prefetch_factor=2,\n", " collate_fn=_val_collate)\n", "\n", "@torch.no_grad()\n", "def compute_full_val_biou(model, ema, val_ds: ToonDataset, device: torch.device,\n", " cfg: Config) -> dict:\n", " \"\"\"Compute full-image BIoU/PA/IoU averaged over the entire val set.\n", " Bug 5 note: this function is not called during the training loop (the\n", " 8-image fixed set is used instead for cost reasons). It is kept as a\n", " standalone utility for post-hoc evaluation.\"\"\"\n", " ema.apply(model)\n", " try:\n", " base = getattr(model, \"_orig_mod\", model)\n", " base.eval()\n", " biou_sum = pa_sum = iou_sum = sad_sum = mse_sum = 0.0\n", " n = len(val_ds.pairs)\n", " for i, (ip, mp) in enumerate(val_ds.pairs):\n", " img_raw = safe_imread(ip, cv2.IMREAD_UNCHANGED)\n", " if img_raw is None:\n", " continue\n", " if img_raw.ndim == 2:\n", " img_rgb = cv2.cvtColor(img_raw, cv2.COLOR_GRAY2RGB)\n", " elif img_raw.shape[2] == 4:\n", " img_rgb = cv2.cvtColor(img_raw, cv2.COLOR_BGRA2RGB)\n", " else:\n", " img_rgb = cv2.cvtColor(img_raw, cv2.COLOR_BGR2RGB)\n", " mask_gt = safe_imread(mp, cv2.IMREAD_GRAYSCALE)\n", " if mask_gt is None:\n", " continue\n", " pred_full = two_pass_predict(base, img_rgb, cfg, device, tta=False)\n", " gt_np = mask_gt.astype(np.float32) / 255.0\n", " gt_t = torch.from_numpy(gt_np).unsqueeze(0).unsqueeze(0).to(device)\n", " pr_t = torch.from_numpy(pred_full).unsqueeze(0).unsqueeze(0).to(device)\n", " met = compute_metrics_gpu(pr_t, gt_t, cfg.metric_dilation, is_logit=False)\n", " mat_met = compute_matting_metrics(pr_t, gt_t)\n", " biou_sum += met[\"biou\"]\n", " pa_sum += met[\"pa\"]\n", " iou_sum += met[\"iou\"]\n", " sad_sum += mat_met[\"sad\"]\n", " mse_sum += mat_met[\"mse\"]\n", " return dict(biou=biou_sum / max(n, 1), pa=pa_sum / max(n, 1), iou=iou_sum / max(n, 1),\n", " sad=sad_sum / max(n, 1), mse=mse_sum / max(n, 1))\n", " finally:\n", " ema.restore(model)\n", "\n", "\n", "@torch.no_grad()\n", "def compute_fixed_set_biou(model, ema, val_ds: ToonDataset, device: torch.device,\n", " cfg: Config, indices: List[int]) -> dict:\n", " \"\"\"Evaluate full-image two-pass BIoU on a small fixed canonical set of val\n", " images. Used as the trustworthy 'how is the model actually doing' signal,\n", " as opposed to the rotating 1-image preview which is sample-noisy.\n", " C7: TTA (cfg.tta_enable) applied here for free inference improvement.\"\"\"\n", " ema.apply(model)\n", " try:\n", " base = getattr(model, \"_orig_mod\", model)\n", " base.eval()\n", " biou_sum = biou_d2_sum = pa_sum = iou_sum = sad_sum = mse_sum = 0.0\n", " n = 0\n", " for i in indices:\n", " if i >= len(val_ds.pairs):\n", " continue\n", " ip, mp = val_ds.pairs[i]\n", " img_raw = safe_imread(ip, cv2.IMREAD_UNCHANGED)\n", " if img_raw is None: continue\n", " if img_raw.ndim == 2:\n", " img_rgb = cv2.cvtColor(img_raw, cv2.COLOR_GRAY2RGB)\n", " elif img_raw.shape[2] == 4:\n", " img_rgb = cv2.cvtColor(img_raw, cv2.COLOR_BGRA2RGB)\n", " else:\n", " img_rgb = cv2.cvtColor(img_raw, cv2.COLOR_BGR2RGB)\n", " mask_gt = safe_imread(mp, cv2.IMREAD_GRAYSCALE)\n", " if mask_gt is None: continue\n", " # C7: use TTA during fixed-set eval (hflip + scale) for free BIoU gain\n", " pred = two_pass_predict(base, img_rgb, cfg, device, tta=cfg.tta_enable)\n", " gt_np = mask_gt.astype(np.float32) / 255.0\n", " gt_t = torch.from_numpy(gt_np).unsqueeze(0).unsqueeze(0).to(device)\n", " pr_t = torch.from_numpy(pred).unsqueeze(0).unsqueeze(0).to(device)\n", " met = compute_metrics_gpu(pr_t, gt_t, cfg.metric_dilation, is_logit=False)\n", " mat_met = compute_matting_metrics(pr_t, gt_t)\n", " biou_sum += met[\"biou\"]; biou_d2_sum += met.get(\"biou_d2\", 0.0); pa_sum += met[\"pa\"]; iou_sum += met[\"iou\"]\n", " sad_sum += mat_met[\"sad\"]; mse_sum += mat_met[\"mse\"]; n += 1\n", " return dict(biou=biou_sum / max(n, 1), biou_d2=biou_d2_sum / max(n, 1), pa=pa_sum / max(n, 1),\n", " iou=iou_sum / max(n, 1), sad=sad_sum / max(n, 1),\n", " mse=mse_sum / max(n, 1), n=n)\n", " finally:\n", " ema.restore(model)\n", "\n", "\n", "@torch.no_grad()\n", "def save_epoch_preview(model, ema, val_ds: ToonDataset, device: torch.device,\n", " epoch: int, save_dir: str, dilation: int,\n", " crop_metrics: dict, cfg: Config):\n", " ema.apply(model)\n", " try:\n", " base = getattr(model, \"_orig_mod\", model)\n", " base.eval()\n", "\n", " n_pairs = len(val_ds.pairs)\n", " sample_idx = epoch % n_pairs\n", " ip, mp = val_ds.pairs[sample_idx]\n", " img_raw = safe_imread(ip, cv2.IMREAD_UNCHANGED)\n", " if img_raw is None:\n", " return {\"biou\": 0.0, \"pa\": 0.0, \"iou\": 0.0, \"sad\": 0.0, \"mse\": 0.0}\n", " if img_raw.ndim == 2:\n", " img_rgb = cv2.cvtColor(img_raw, cv2.COLOR_GRAY2RGB)\n", " elif img_raw.shape[2] == 4:\n", " img_rgb = cv2.cvtColor(img_raw, cv2.COLOR_BGRA2RGB)\n", " else:\n", " img_rgb = cv2.cvtColor(img_raw, cv2.COLOR_BGR2RGB)\n", " mask_gt = safe_imread(mp, cv2.IMREAD_GRAYSCALE)\n", " if mask_gt is None:\n", " return {\"biou\": 0.0, \"pa\": 0.0, \"iou\": 0.0, \"sad\": 0.0, \"mse\": 0.0}\n", " H, W = img_rgb.shape[:2]\n", "\n", " # C7: use TTA in preview as well for consistency with fixed-set eval\n", " pred_full = two_pass_predict(base, img_rgb, cfg, device, tta=cfg.tta_enable)\n", " pred_show = (pred_full * 255.0).clip(0, 255).astype(np.uint8)\n", "\n", " gt_np = (mask_gt > 127).astype(np.uint8)\n", " p_np = (pred_show > 127).astype(np.uint8)\n", " gt_t = torch.from_numpy(mask_gt.astype(np.float32) / 255.0).unsqueeze(0).unsqueeze(0).to(device)\n", " pr_t = torch.from_numpy(pred_full).unsqueeze(0).unsqueeze(0).to(device)\n", "\n", " fi_met = compute_metrics_gpu(pr_t, gt_t, dilation, is_logit=False)\n", " mat_met = compute_matting_metrics(pr_t, gt_t)\n", " fi_met[\"sad\"] = mat_met[\"sad\"]\n", " fi_met[\"mse\"] = mat_met[\"mse\"]\n", "\n", " gt_cov = 100.0 * gt_np.mean()\n", "\n", " fig = plt.figure(figsize=(22, 6), facecolor=\"#111\")\n", " gs = gridspec.GridSpec(1, 4, figure=fig, wspace=0.04)\n", "\n", " def _show(ax, data, title, sub=\"\"):\n", " ax.set_facecolor(\"#111\")\n", " ax.imshow(data, cmap=None if data.ndim == 3 else \"gray\")\n", " ax.set_title(title, color=\"white\", fontsize=9, pad=4)\n", " if sub:\n", " ax.text(0.02, 0.02, sub, color=\"white\", fontsize=7,\n", " transform=ax.transAxes, va=\"bottom\", alpha=0.85)\n", " ax.axis(\"off\")\n", "\n", " overlay = img_rgb.copy()\n", " gt_bool = gt_np.astype(bool)\n", " overlay[gt_bool, 0] = (overlay[gt_bool, 0].astype(int) * 0.55 + 0 * 0.45).clip(0, 255).astype(np.uint8)\n", " overlay[gt_bool, 1] = (overlay[gt_bool, 1].astype(int) * 0.55 + 200 * 0.45).clip(0, 255).astype(np.uint8)\n", " overlay[gt_bool, 2] = (overlay[gt_bool, 2].astype(int) * 0.55 + 0 * 0.45).clip(0, 255).astype(np.uint8)\n", "\n", " tp = np.zeros((*p_np.shape, 3), dtype=np.uint8)\n", " tp[(p_np == 1) & (gt_np == 1)] = [0, 200, 0]\n", " tp[(p_np == 1) & (gt_np == 0)] = [200, 0, 0]\n", " tp[(p_np == 0) & (gt_np == 1)] = [0, 0, 200]\n", "\n", " ax0 = fig.add_subplot(gs[0]); _show(ax0, img_rgb, \"Original\",\n", " f\"{W}×{H} · sample {sample_idx}\")\n", " ax1 = fig.add_subplot(gs[1]); _show(ax1, overlay, \"GT overlay\",\n", " f\"GT coverage {gt_cov:.1f}%\")\n", " ax2 = fig.add_subplot(gs[2]); _show(ax2, pred_show, \"Prediction (two-pass)\",\n", " f\"BIoU {fi_met['biou']:.1f}% \"\n", " f\"PA {fi_met['pa']:.1f}% \"\n", " f\"SAD {fi_met['sad']:.2f}\")\n", " ax3 = fig.add_subplot(gs[3]); _show(ax3, tp, \"Error map\",\n", " \"TP=green FP=red FN=blue TN=black\")\n", "\n", " cb = crop_metrics\n", " ttl = (f\"Epoch {epoch:03d} \"\n", " f\"Crop BIoU {cb['biou']:.1f}% PA {cb['pa']:.1f}% | \"\n", " f\"Full-img BIoU {fi_met['biou']:.1f}% \"\n", " f\"SAD {fi_met['sad']:.2f} MSE {fi_met['mse']:.4f}\")\n", " fig.suptitle(ttl, color=\"white\", fontsize=11, y=1.02)\n", "\n", " out_path = Path(save_dir) / f\"epoch_{epoch:03d}.png\"\n", " out_path.parent.mkdir(parents=True, exist_ok=True)\n", " fig.savefig(out_path, dpi=100, bbox_inches=\"tight\",\n", " facecolor=fig.get_facecolor())\n", " plt.close(fig)\n", "\n", " return fi_met\n", " finally:\n", "\n", " ema.restore(model)\n", "\n", "def train_epoch(model, loader, criterion, opt, scaler, ema, accum, device, epoch,\n", " grad_clip: float = 5.0):\n", " base = getattr(model, \"_orig_mod\", model)\n", " base.train(); set_bn_eval(base)\n", "\n", " total_loss = gnorm_acc = 0.0\n", " n = n_updates = n_skip = n_spike = 0\n", " comp_acc = {\"db\": 0.0, \"lovasz\": 0.0, \"mae\": 0.0, \"ssim\": 0.0, \"grad\": 0.0,\n", " \"bnd\": 0.0, \"biou_l\": 0.0, \"struct\": 0.0, \"ero\": 0.0, \"conf\": 0.0}\n", " loss_ema_val = None\n", " opt.zero_grad()\n", "\n", " pbar = tqdm(loader, desc=f\" Train E{epoch:03d}\", unit=\"batch\",\n", " dynamic_ncols=True, leave=False, total=getattr(loader, \"length\", None))\n", " total_steps = len(loader) if hasattr(loader, '__len__') else getattr(loader, 'length', None)\n", "\n", " for step, (imgs, masks) in enumerate(pbar):\n", " imgs = imgs.to(device, non_blocking=True)\n", " masks = masks.to(device, non_blocking=True)\n", "\n", " with torch.amp.autocast(\"cuda\", dtype=AMP_DTYPE):\n", " raw = model(imgs)\n", " preds_raw = _normalize_preds(raw)\n", "\n", " preds = _safe_preds(preds_raw)\n", " loss, parts = criterion(preds, masks)\n", "\n", " if not torch.isfinite(loss):\n", " # FIX: Removed opt.zero_grad() — it was destroying ALL accumulated\n", " # gradients from prior microbatches in the window (Bug 1, Gradient Eraser).\n", " # continue skips .backward(), so no NaN enters the accumulator.\n", " n_skip += 1; continue\n", "\n", " lv = loss.item()\n", " if loss_ema_val is None: loss_ema_val = lv\n", " else: loss_ema_val = CFG.loss_ema_beta * loss_ema_val + (1 - CFG.loss_ema_beta) * lv\n", "\n", " if step >= 20 and loss_ema_val > 0.1 and lv > CFG.loss_spike_k * loss_ema_val:\n", " # FIX: Same as above — skip the spike, don't erase the bucket.\n", " n_spike += 1; n_skip += 1; continue\n", "\n", " scaler.scale(loss / accum).backward()\n", "\n", " if (step + 1) % accum == 0 or (total_steps and (step + 1) == total_steps):\n", " scaler.unscale_(opt)\n", " gn = torch.nn.utils.clip_grad_norm_(\n", " [p for p in base.parameters() if p.requires_grad], grad_clip).item()\n", " if not math.isfinite(gn):\n", " opt.zero_grad(); scaler.update(); n_skip += 1; continue\n", " scaler.step(opt); scaler.update()\n", " opt.zero_grad()\n", " ema.update(model)\n", " gnorm_acc += gn; n_updates += 1\n", " else:\n", " gn = 0.0\n", "\n", " total_loss += lv; n += 1\n", " for k, v in parts.items():\n", " if isinstance(v, torch.Tensor):\n", " comp_acc[k] = comp_acc.get(k, 0.0) + v # Acc on GPU\n", " else:\n", " comp_acc[k] = comp_acc.get(k, 0.0) + v\n", "\n", " pbar.set_postfix(\n", " {\"loss\": f\"{lv:.3f}\", \"gn\": f\"{gn:.4f}\", \"up\": n_updates}, refresh=False)\n", "\n", " pbar.close()\n", "\n", " if n_spike > 0:\n", " pct = 100 * n_spike / max(n + n_spike, 1)\n", " print(f\" ℹ Spike guard fired {n_spike}x ({pct:.1f}%)\")\n", " if n_updates == 0:\n", " print(f\" ⚠ 0 updates!\")\n", "\n", " avg_comp = {k: (v.item() if isinstance(v, torch.Tensor) else v) / max(n, 1) \n", " for k, v in comp_acc.items()}\n", " return total_loss / max(n, 1), gnorm_acc / max(n_updates, 1), avg_comp, n_skip, n_spike\n", "\n", "@torch.no_grad()\n", "def val_epoch(model, loader, criterion, ema, device, dilation, epoch):\n", " ema.apply(model)\n", " base = getattr(model, \"_orig_mod\", model)\n", " base.eval()\n", " pbar = None\n", " try:\n", " val_loss = biou = biou_d2 = pa = iou = 0.0; n = 0\n", " pbar = tqdm(loader, desc=f\" Val E{epoch:03d}\", unit=\"batch\",\n", " dynamic_ncols=True, leave=False)\n", " for imgs, masks in pbar:\n", " imgs = imgs.to(device, non_blocking=True)\n", " masks = masks.to(device, non_blocking=True)\n", " with torch.amp.autocast(\"cuda\", dtype=AMP_DTYPE):\n", " raw_fwd = model(imgs)\n", " raw_flp = model(imgs.flip(-1))\n", " pred_avg = (torch.stack([_normalize_preds(raw_fwd)[-1], \n", " _normalize_preds(raw_flp)[-1].flip(-1)]).mean(0))\n", " m = compute_metrics_gpu(pred_avg, masks, dilation, is_logit=True)\n", " v_loss = F.binary_cross_entropy_with_logits(pred_avg, masks)\n", " val_loss += v_loss.item()\n", " biou += m[\"biou\"]; biou_d2 += m.get(\"biou_d2\", 0.0); pa += m[\"pa\"]; iou += m[\"iou\"]; n += 1\n", " del imgs, masks, raw_fwd, raw_flp, pred_avg, v_loss\n", " pbar.set_postfix(\n", " {\"BIoU\": f\"{biou/n:.1f}%\", \"BIoU2\": f\"{biou_d2/n:.1f}%\", \"PA\": f\"{pa/n:.1f}%\",\n", " \"loss\": f\"{val_loss/n:.3f}\"}, refresh=False)\n", " finally:\n", "\n", " if pbar is not None:\n", " try: pbar.close()\n", " except Exception: pass\n", " ema.restore(model)\n", "\n", " return {\"val_loss\": val_loss / max(n, 1), \"biou\": biou / max(n, 1),\n", " \"biou_d2\": biou_d2 / max(n, 1),\n", " \"pa\": pa / max(n, 1), \"iou\": iou / max(n, 1)}\n", "\n", "def main():\n", " gc.collect(); torch.cuda.empty_cache(); torch.cuda.reset_peak_memory_stats()\n", " set_seed(CFG.seed)\n", " device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", " vram_total = (torch.cuda.get_device_properties(0).total_memory / 1e9\n", " if torch.cuda.is_available() else 0)\n", " print(f\"Device: {device} | VRAM: {vram_total:.1f} GB\")\n", " print(f\"AMP: {AMP_DTYPE} | TF32: ON | Dual-stream: {CFG.force_dual_stream}\")\n", " \n", " # ═══════════════════════════════════════════════════════════════════════════\n", " # CONFIGURATION SUMMARY - 10 Boosts + 7 Tuning Changes\n", " # ═══════════════════════════════════════════════════════════════════════════\n", " print(\"\\n\" + \"═\" * 76)\n", " print(\" 🚀 TRAINING CONFIG (10 Boosts + 7 TUNE Changes from Log Analysis)\")\n", " print(\"═\" * 76)\n", " print(f\" C1 (GEMINI): Structure Loss = Phase 1/2/3: {CFG.w_struct}\")\n", " print(f\" └─ TUNE C: Boosted Phase 2: 0.3→0.8, Phase 3: 1.0→1.2\")\n", " print(f\" C2 (GEMINI): Boundary Crop Ratio = {CFG.bnd_ratio}\")\n", " print(f\" C3 (GEMINI): Boundary BCE Weight = Phase 1/2/3: {CFG.w_bnd}\")\n", " print(f\" └─ TUNE D: Adaptive decay DISABLED (was eroding signal)\")\n", " print(f\" C4 (BOTH): Backbone LR Frac = {CFG.backbone_lr_frac}\")\n", " print(f\" └─ Decoder LR = {[f'{x:.1e}' for x in CFG.lr_decoder_phase]}\")\n", " print(f\" └─ TUNE F: Backbone frac 0.15→0.20 | TUNE G: Decoder 5e-5→7e-5\")\n", " print(f\" C5 (MINE): Phase Durations = {CFG.max_phase_epochs} epochs\")\n", " print(f\" C6 (MINE): BIoU Loss Weight = Phase 1/2/3: {CFG.w_biou}\")\n", " print(f\" └─ TUNE B: Reduced from [1.0, 1.8, 2.0] (was 116% of total)\")\n", " print(f\" C7 (MINE): Lovász Loss Weight = Phase 1/2/3: {CFG.w_lovasz}\")\n", " print(f\" C8 (MINE): Gradient Clip = Phase 1/2/3: {CFG.grad_clip_phase}\")\n", " print(f\" └─ TUNE E: Phase 2 raised 25→35 for backbone headroom\")\n", " print(f\" C9 (MINE): EMA Decay = Phase 1: {CFG.ema_decay}, Phase 2+: {CFG.ema_decay_phase2}\")\n", " print(f\" C10 (MINE): Backbone Warmup = {CFG.bb_warmup_epochs} epochs\")\n", " print(\"─\" * 76)\n", " print(\" TUNE A (BIGGEST): LR scheduler → CosineAnnealingLR (was WarmRestarts)\")\n", " print(\" └─ Old scheduler peaked backbone LR at epoch 5 then decayed immediately\")\n", " print(\" └─ New: sustained high LR for ~60% of phase, then gentle decay\")\n", " print(\"═\" * 76)\n", " print(\" Expected Results (with TUNE changes):\")\n", " print(\" • Ep 30: BIoU ~76-78% (accelerated from ~73%)\")\n", " print(\" • Ep 40: BIoU ~82-84% (was ~77%)\")\n", " print(\" • Ep 50: BIoU ~86-88% (was ~79%)\")\n", " print(\" • Ep 70: BIoU ~90%+ (target exceeded)\")\n", " print(\"═\" * 76 + \"\\n\")\n", "\n", " for d in [CFG.drive_ckpt_dir, CFG.preview_dir, str(Path(CFG.log_csv).parent)]:\n", " Path(d).mkdir(parents=True, exist_ok=True)\n", "\n", " sync_ok = Path(CFG.ssd_dataset) / \".sync_ok\"\n", " if not sync_ok.exists():\n", " ok = sync_dataset(CFG.drive_dataset, CFG.ssd_dataset, workers=CFG.sync_workers)\n", " if not ok: raise RuntimeError(\"Dataset sync failed\")\n", " else:\n", " print(f\" Dataset ready ({sync_ok.read_text().strip()})\")\n", "\n", " model = load_model(CFG, device)\n", " if CFG.compile_model:\n", " print(\" ⏳ PyTorch 2.x Compiler Enabled (CFG.compile_model=True). Initializing...\")\n", " import torch._dynamo as _dynamo\n", " _dynamo.config.suppress_errors = True\n", " model = torch.compile(model)\n", "\n", " bs = FIXED_BS\n", " accum = max(1, CFG.effective_batch // bs)\n", " print(f\" bs={bs} accum={accum} eff_batch={bs*accum}\")\n", "\n", " train_ds = ToonDataset(\n", " CFG.train_img_dir, CFG.train_mask_dir, crop_size=CFG.crop_size,\n", " bnd_ratio=CFG.bnd_ratio[0], augment=True,\n", " min_fg_ratio=CFG.min_fg_ratio, fg_retry=CFG.fg_retry,\n", " scale_range=(CFG.scale_aug_lo, CFG.scale_aug_hi),\n", " fixed_crops=False,\n", " p_global=CFG.p_global_fallback)\n", "\n", " val_ds = ToonDataset(\n", " CFG.val_img_dir, CFG.val_mask_dir, crop_size=CFG.crop_size,\n", " bnd_ratio=0.0, augment=False, min_fg_ratio=0.0, fg_retry=1,\n", " scale_range=None, fixed_crops=True,\n", " crops_per_image=CFG.val_crops_per_image,\n", " p_global=0.0)\n", "\n", " print(f\" Train: {len(train_ds)} pairs | Val: {len(val_ds)} items\")\n", " if CFG.force_dual_stream:\n", " n_g = int(bs * CFG.global_ratio + 0.5)\n", " n_g = max(0, min(bs, n_g))\n", " n_l = bs - n_g\n", " print(f\" Dual-stream: each batch is {n_g}× global + {n_l}× local\")\n", " else:\n", " print(f\" Stochastic global: p={CFG.p_global_fallback:.0%}\")\n", "\n", " _fixed_rng = random.Random(CFG.seed)\n", " _n_fixed = min(8, len(val_ds.pairs))\n", " fixed_preview_indices = sorted(_fixed_rng.sample(range(len(val_ds.pairs)), _n_fixed))\n", " print(f\" Fixed preview set: {_n_fixed} canonical val images (indices: {fixed_preview_indices})\")\n", "\n", " criterion = ToonLoss(CFG, phase=1)\n", " ps = PhaseScheduler(CFG)\n", " opt = make_optimizer(model, phase=1, cfg=CFG)\n", " sched = make_warmrestart_scheduler(opt, CFG, 1)\n", " ema = EMA(model, decay=CFG.ema_decay)\n", " ckpt_mgr = CheckpointManager(CFG.drive_ckpt_dir)\n", " logger = CSVLogger(CFG.log_csv)\n", " scaler = NoOpScaler()\n", "\n", " ckpt_mgr.scan_all()\n", "\n", " start_epoch = 1\n", " best_biou = 0.0\n", " best_fi_biou = 0.0\n", " prev_biou = 0.0\n", " history: list = []\n", "\n", " saved = ckpt_mgr.load_latest()\n", " if saved is not None and not FORCE_BEST_EMA:\n", " try:\n", " base = getattr(model, \"_orig_mod\", model)\n", " base.load_state_dict(saved[\"model_state\"])\n", " ema.load_state_dict(saved[\"ema_state\"],\n", " device=next(base.parameters()).device)\n", " base.float()\n", " ps.load_state_dict(saved[\"phase_state\"])\n", " resume_phase = ps.phase\n", "\n", " # Force phase transition at resume if config has shortened the phase\n", " forced_transition_at_resume = False\n", " if resume_phase < 3 and ps.phase_ep >= CFG.max_phase_epochs[resume_phase - 1]:\n", " print(f\" ⚡ Forcing Phase {resume_phase+1} transition at resume \"\n", " f\"(phase_ep={ps.phase_ep} >= max={CFG.max_phase_epochs[resume_phase-1]})\")\n", " ps.phase = resume_phase + 1\n", " ps.phase_ep = 0\n", " ps._biou_history.clear()\n", " ps._best_in_phase = 0.0\n", " resume_phase = ps.phase\n", " forced_transition_at_resume = True\n", "\n", " opt = make_optimizer(model, phase=resume_phase, cfg=CFG)\n", " sched = make_warmrestart_scheduler(opt, CFG, resume_phase)\n", "\n", " if forced_transition_at_resume:\n", " # A phase boundary was just crossed AT RESUME. Treat this exactly like\n", " # the in-loop `if transitioned:` branch does elsewhere in main(): fresh\n", " # optimizer, fresh scheduler, NO state restore. Loading the previous\n", " # phase's opt/sched state here is what corrupted the LR schedule\n", " # (last_epoch/hold_epochs/decay_epochs/eta_min/base_lrs all get\n", " # silently overwritten by the old phase's values).\n", " print(\" ⚡ Forced transition at resume — using FRESH optimizer/scheduler \"\n", " \"(opt/sched state NOT restored, matching in-loop transition behavior)\")\n", " if resume_phase >= 2:\n", " ema.decay = CFG.ema_decay_phase2\n", " print(f\" EMA decay → {ema.decay} (phase {resume_phase}, forced transition)\")\n", " ema.register_new(model)\n", " else:\n", " try:\n", " opt.load_state_dict(saved[\"opt_state\"])\n", " _optimizer_state_to(opt, device)\n", " print(\" Optimizer state restored (tensors moved to device)\")\n", " except Exception as e:\n", " print(f\" Optimizer: fresh ({e})\")\n", "\n", " try:\n", " sched.last_epoch = ps.phase_ep\n", " print(f\" Scheduler last_epoch aligned to phase_ep={sched.last_epoch}\")\n", " except Exception as e:\n", " print(f\" Scheduler: fresh ({e})\")\n", "\n", " # Same-phase resume where you also bumped ema_decay_phase2 in config,\n", " # or resumed straight into phase>=2 from a phase-1 checkpoint some other\n", " # way — keep EMA smoothing consistent with the running phase.\n", " if resume_phase >= 2:\n", " ema.decay = CFG.ema_decay_phase2\n", "\n", " # Re-align optimizer + scheduler LRs to the CURRENT config so that\n", " # config-level changes (e.g. backbone_lr_frac, lr_decoder_phase)\n", " # take effect on resume instead of being overridden by the saved\n", " # checkpoint LRs. Cosine-decay the current epoch from the new base.\n", " try:\n", " if forced_transition_at_resume:\n", " pass # Fresh opt/sched already match current config exactly.\n", " elif isinstance(sched, torch.optim.lr_scheduler.CosineAnnealingWarmRestarts):\n", " print(\" Scheduler is CosineAnnealingWarmRestarts — letting internal state drive learning rates on resume\")\n", " else:\n", " # FIX: group counts must match make_optimizer()'s real construction:\n", " # phase 1 -> [dec_decay, dec_nodecay] (2 groups)\n", " # phase >=2 -> [bb_decay, bb_nodecay, dec_decay, dec_nodecay] (4 groups)\n", " # The old code built 1 or 2 entries here, which could NEVER equal\n", " # opt.param_groups' actual length (2 or 4) -> this block was a\n", " # silent no-op on every single resume.\n", " if resume_phase == 1:\n", " dec = CFG.lr_decoder_phase[0]\n", " new_base_lrs = [dec, dec]\n", " else:\n", " bb_lr = (CFG.lr_decoder_phase[resume_phase - 1]\n", " * CFG.backbone_lr_frac[resume_phase - 1])\n", " dec_lr = CFG.lr_decoder_phase[resume_phase - 1]\n", " new_base_lrs = [bb_lr, bb_lr, dec_lr, dec_lr]\n", " if (hasattr(sched, \"base_lrs\")\n", " and len(sched.base_lrs) == len(new_base_lrs)\n", " and len(opt.param_groups) == len(new_base_lrs)):\n", " old_lrs = [pg[\"lr\"] for pg in opt.param_groups]\n", " sched.base_lrs = list(new_base_lrs)\n", " T_max = getattr(sched, \"T_max\",\n", " CFG.max_phase_epochs[resume_phase - 1])\n", " eta_min = getattr(sched, \"eta_min\", 0.0)\n", " for i, base_lr in enumerate(new_base_lrs):\n", " em = (eta_min[i] if isinstance(eta_min, (list, tuple))\n", " else eta_min)\n", " if hasattr(sched, \"hold_epochs\"):\n", " cur = sched.get_lr()[i]\n", " else:\n", " # CosineAnnealingLR formula at last_epoch\n", " cur = em + 0.5 * (base_lr - em) * (\n", " 1 + math.cos(math.pi * sched.last_epoch\n", " / max(T_max, 1)))\n", " opt.param_groups[i][\"lr\"] = cur\n", " new_lrs = [pg[\"lr\"] for pg in opt.param_groups]\n", " print(f\" LR re-aligned to current config: \"\n", " f\"{[f'{x:.2e}' for x in old_lrs]} -> \"\n", " f\"{[f'{x:.2e}' for x in new_lrs]}\")\n", " else:\n", " print(f\" ⚠ LR re-alignment group-count mismatch — skipped \"\n", " f\"(sched.base_lrs={len(getattr(sched,'base_lrs',[]))}, \"\n", " f\"opt.param_groups={len(opt.param_groups)}, \"\n", " f\"new_base_lrs={len(new_base_lrs)})\")\n", " except Exception as e:\n", " print(f\" LR re-alignment skipped ({e})\")\n", "\n", " try:\n", " # Always set criterion to current resume_phase (may differ from\n", " # checkpoint if phase transition was forced at resume time).\n", " criterion.set_phase(resume_phase)\n", " except Exception as e:\n", " print(f\" Criterion: fresh phase {resume_phase} ({e})\")\n", " criterion.set_phase(resume_phase)\n", "\n", " prev_biou = float(saved.get(\"prev_biou\", 0.0))\n", "\n", " if \"rng_state\" in saved:\n", " _rng_load_state_dict(saved[\"rng_state\"])\n", "\n", " scaler = NoOpScaler()\n", " start_epoch = saved[\"epoch\"] + 1\n", " best_biou = float(saved.get(\"biou_best\",\n", " saved.get(\"best_biou\", 0.0)))\n", " best_fi_biou = float(saved.get(\"fi_biou_best\", 0.0))\n", " train_ds.bnd_ratio = CFG.bnd_ratio[min(resume_phase - 1, len(CFG.bnd_ratio) - 1)]\n", " if resume_phase == 3:\n", " train_ds.scale_rng = (0.55, 1.80)\n", " if train_ds.augment and hasattr(train_ds, '_build_aug'):\n", " train_ds.aug = train_ds._build_aug(phase=3)\n", " print(f\"\\n ✅ Resumed ep={saved['epoch']} → continue {start_epoch}\")\n", " print(f\" Phase={resume_phase} phase_ep={ps.phase_ep} \"\n", " f\"LR={opt.param_groups[-1]['lr']:.2e}\")\n", " print(f\" best_biou={best_biou:.2f}% \"\n", " f\"best_fi_biou={best_fi_biou:.2f}% \"\n", " f\"prev_biou={prev_biou:.2f}%\")\n", " print(f\" adaptive_w_bnd={criterion.effective_w_bnd:.3f}\\n\")\n", " except Exception as exc:\n", " import traceback\n", " traceback.print_exc()\n", " print(f\" ✗ Resume failed ({exc}) — fresh start\")\n", " start_epoch = 1; best_biou = 0.0; best_fi_biou = 0.0\n", " prev_biou = 0.0; history = []\n", " model = load_model(CFG, device)\n", " opt = make_optimizer(model, phase=1, cfg=CFG)\n", " sched = make_warmrestart_scheduler(opt, CFG, 1)\n", " criterion = ToonLoss(CFG, phase=1)\n", " ema = EMA(model, decay=CFG.ema_decay)\n", " ps = PhaseScheduler(CFG)\n", " scaler = NoOpScaler()\n", " else:\n", " if saved is not None and FORCE_BEST_EMA:\n", " print(\" (Ignoring existing checkpoint — FORCE_BEST_EMA is True, \"\n", " \"starting fresh per request)\")\n", "\n", " train_dl = (DualStreamLoader(train_ds, bs, CFG.num_workers,\n", " CFG.seed + start_epoch + ps.phase * 1000)\n", " if CFG.force_dual_stream\n", " else DataLoader(train_ds, batch_size=bs, shuffle=True,\n", " num_workers=CFG.num_workers,\n", " pin_memory=CFG.pin_memory, drop_last=True,\n", " persistent_workers=True, prefetch_factor=4))\n", " val_dl = _make_val_dl(val_ds, bs)\n", "\n", " print(f\"\\n{'═'*76}\")\n", " print(f\" A100 SXM4 MIG 20GB | BF16 AMP | TF32 | NCHW | eager\")\n", " print(f\" Model : {CFG.model_id}\")\n", " print(f\" Crop : {CFG.crop_size}px | bs={bs} accum={accum} eff_batch={bs*accum}\")\n", " print(f\" Dual-st : {CFG.force_dual_stream} | \"\n", " f\"Inference overlap {CFG.inference_overlap:.0%} \"\n", " f\"conf-temp {CFG.confidence_temperature}\")\n", " print(f\" Workers : train={CFG.num_workers} val={min(4,CFG.num_workers)}\")\n", " print(f\" Epochs : {start_epoch} → {CFG.max_epochs}\")\n", " print(f\" Goal : crop-BIoU ≥ {CFG.target_biou}% PA ≥ {CFG.target_pa}% \"\n", " f\"full-img BIoU ≥ {CFG.target_fi_biou}%\")\n", " print(f\"{'═'*76}\\n\")\n", "\n", " # FIX: Persist per_img_loss across epochs so hard-neg mining remembers\n", " # which images are hard (was being reset to 0.5 every epoch = amnesia).\n", " per_img_loss = np.full(len(train_ds.pairs), 0.5, dtype=np.float32)\n", "\n", " try:\n", " for epoch in range(start_epoch, CFG.max_epochs + 1):\n", " t0 = time.time()\n", " if torch.cuda.is_available():\n", " torch.cuda.reset_peak_memory_stats()\n", " phase = ps.phase\n", "\n", " tr_loss, gnorm, comp, n_skip, n_spike = train_epoch(\n", " model, train_dl, criterion, opt, scaler, ema, accum, device, epoch,\n", " grad_clip=CFG.grad_clip_phase[min(phase - 1, len(CFG.grad_clip_phase) - 1)])\n", "\n", " torch.cuda.empty_cache()\n", "\n", " vm = val_epoch(model, val_dl, criterion, ema, device,\n", " CFG.metric_dilation, epoch)\n", " biou = vm[\"biou\"]; biou_d2 = vm.get(\"biou_d2\", 0.0); pa = vm[\"pa\"]; iou = vm[\"iou\"]\n", "\n", " # Compute fixed-set full-image metrics every epoch for reliable checkpoint selection\n", " fi_biou = fi_pa = fi_iou = fi_sad = fi_mse = 0.0\n", " try:\n", " gc.collect()\n", " torch.cuda.empty_cache() # Free fragmented allocations before tiling\n", " fxd = compute_fixed_set_biou(model, ema, val_ds, device, CFG,\n", " fixed_preview_indices)\n", " fi_biou = fxd[\"biou\"]; fi_pa = fxd[\"pa\"]; fi_iou = fxd[\"iou\"]\n", " fi_sad = fxd[\"sad\"]; fi_mse = fxd[\"mse\"]\n", " except Exception as exc:\n", " print(f\" ⚠ Fixed-set eval failed: {exc}\")\n", "\n", " biou_delta = fi_biou - prev_biou\n", " criterion.update_adaptive_bnd(biou_delta)\n", " prev_biou = fi_biou\n", "\n", " # C5: Update hard-negative sample weights based on per-sample val BIoU.\n", " # After hard_neg_warmup epochs, up-sample hard images proportional to\n", " # their loss^alpha so the model sees difficult cases more often.\n", " if (CFG.force_dual_stream and isinstance(train_dl, DualStreamLoader)\n", " and epoch >= CFG.hard_neg_warmup):\n", " # Use per-image avg BIoU from val set as difficulty proxy:\n", " # lower BIoU → harder → higher weight.\n", " n_train = len(train_ds.pairs)\n", " # Build per-training-image weights via a quick fixed-set style pass\n", " # over a random 10 % sample to keep cost low.\n", " try:\n", " rng_hn = random.Random(epoch * 7919)\n", " sample_n = max(10, n_train // 10)\n", " hn_indices = rng_hn.sample(range(n_train), min(sample_n, n_train))\n", " ema.apply(model)\n", " try:\n", " base_m = getattr(model, \"_orig_mod\", model)\n", " base_m.eval()\n", " # FIX: per_img_loss is now persistent (created before loop).\n", " # Only update the sampled indices; rest keep prior-epoch scores.\n", " with torch.no_grad():\n", " for hi in hn_indices:\n", " # FIX: Use RAM cache instead of reading from disk.\n", " # _img_cache was populated at startup; cv2.imread was redundant.\n", " if hasattr(train_ds, '_img_cache') and train_ds._img_cache:\n", " img_h, msk_h = train_ds._img_cache[hi]\n", " else:\n", " ip_h, mp_h = train_ds.pairs[hi]\n", " img_h = safe_imread(ip_h, cv2.IMREAD_UNCHANGED)\n", " msk_h = safe_imread(mp_h, cv2.IMREAD_GRAYSCALE)\n", " if img_h is None or msk_h is None:\n", " continue\n", " if img_h.ndim == 2:\n", " img_h = cv2.cvtColor(img_h, cv2.COLOR_GRAY2RGB)\n", " elif img_h.shape[2] == 4:\n", " img_h = cv2.cvtColor(img_h, cv2.COLOR_BGRA2RGB)\n", " else:\n", " img_h = cv2.cvtColor(img_h, cv2.COLOR_BGR2RGB)\n", " if msk_h.shape[:2] != img_h.shape[:2]:\n", " msk_h = cv2.resize(\n", " msk_h, (img_h.shape[1], img_h.shape[0]),\n", " interpolation=cv2.INTER_LINEAR)\n", " pred_h = fast_global_predict(base_m, img_h, CFG, device)\n", " gt_h = msk_h.astype(np.float32) / 255.0\n", " gt_ht = torch.from_numpy(gt_h).unsqueeze(0).unsqueeze(0).to(device)\n", " pr_ht = torch.from_numpy(pred_h).unsqueeze(0).unsqueeze(0).to(device)\n", " m_h = compute_metrics_gpu(pr_ht, gt_ht,\n", " dilation=2, is_logit=False)\n", " # difficulty = 1 - BIoU/100; clamp to [0.01, 1]\n", " diff = max(0.01, 1.0 - m_h[\"biou\"] / 100.0)\n", " per_img_loss[hi] = diff\n", " finally:\n", " ema.restore(model)\n", " # weight = difficulty^alpha\n", " weights_hn = per_img_loss ** CFG.hard_neg_alpha\n", " train_dl.set_sample_weights(weights_hn)\n", " except Exception as exc_hn:\n", " print(f\" ⚠ Hard-neg weight update failed: {exc_hn}\")\n", "\n", " lr = opt.param_groups[-1][\"lr\"]\n", " mins = (time.time() - t0) / 60.0\n", "\n", " # FIX: Record phase BEFORE transition so CSV labels the phase\n", " # that actually trained this epoch (not the new one).\n", " trained_phase = ps.phase\n", " trained_phase_ep = ps.phase_ep\n", "\n", " transitioned, phase = ps.step(biou)\n", " if transitioned:\n", " criterion.set_phase(phase)\n", " train_ds.bnd_ratio = CFG.bnd_ratio[min(phase-1, len(CFG.bnd_ratio)-1)]\n", " if phase == 3:\n", " train_ds.scale_rng = (0.35, 1.80) # keep large-canvas coverage from Phase 2\n", " if train_ds.augment and hasattr(train_ds, '_build_aug'):\n", " train_ds.aug = train_ds._build_aug(phase=3)\n", " _release_dl(train_dl); _release_dl(val_dl)\n", " opt = make_optimizer(model, phase=phase, cfg=CFG)\n", " sched = make_warmrestart_scheduler(opt, CFG, phase)\n", " ema.register_new(model)\n", " # C3: Bump EMA decay at Phase 2 for fine-tuning stability\n", " if phase >= 2:\n", " ema.decay = CFG.ema_decay_phase2\n", " print(f\" EMA decay → {ema.decay} (phase {phase})\")\n", " # BOOST: Structure Loss activates at Phase 2 - expect loss spike\n", " if CFG.w_struct[1] > 0:\n", " print(f\" 🔥 BOOST ALERT: Structure Loss activating (w={CFG.w_struct[1]})\")\n", " print(f\" ✓ EXPECTED: Train loss will spike ~0.15-0.20 (NORMAL)\")\n", " print(f\" ✓ EXPECTED: BIoU may dip 1-2% for 2-3 epochs (recalibration)\")\n", " print(f\" ✓ EXPECTED: BIoU will surge past 75% by epoch {epoch+6}\")\n", " print(f\" ⚠ ALERT: If loss_struct > 2.0, reduce w_struct to 0.8\")\n", " scaler = NoOpScaler()\n", " train_dl = (DualStreamLoader(train_ds, bs, CFG.num_workers, CFG.seed+phase)\n", " if CFG.force_dual_stream\n", " else DataLoader(train_ds, batch_size=bs, shuffle=True,\n", " num_workers=CFG.num_workers,\n", " pin_memory=CFG.pin_memory, drop_last=True,\n", " persistent_workers=True, prefetch_factor=4))\n", " val_dl = _make_val_dl(val_ds, bs)\n", " else:\n", " sched.step()\n", "\n", " # Phase 2 backbone warmup. The warmup block runs at the END of each\n", " # epoch and sets the LR used by the NEXT epoch's training step. So:\n", " # - At the transition itself (phase_ep == 0) we set the LR for the\n", " # FIRST phase-2 training epoch to (1/N) * target_bb_lr, not 0.\n", " # - Subsequent epochs ramp 2/N, 3/N, ..., then cosine takes over.\n", " if phase == 2 and ps.phase_ep < CFG.bb_warmup_epochs and CFG.bb_warmup_epochs > 0:\n", " target_bb_lr = CFG.lr_decoder_phase[1] * CFG.backbone_lr_frac[1]\n", " frac = (ps.phase_ep + 1) / CFG.bb_warmup_epochs\n", " opt.param_groups[0][\"lr\"] = target_bb_lr * frac\n", " elif phase == 2 and ps.phase_ep == CFG.bb_warmup_epochs:\n", " # Final pin to full target right before cosine takes over,\n", " # so cosine starts from a known anchor.\n", " target_bb_lr = CFG.lr_decoder_phase[1] * CFG.backbone_lr_frac[1]\n", " opt.param_groups[0][\"lr\"] = target_bb_lr\n", "\n", " # Checkpoint selection driven by Crop-BIoU (biou) per user optimization target.\n", " is_best = biou > best_biou\n", " if is_best:\n", " best_biou = biou\n", " best_fi_biou = max(best_fi_biou, fi_biou)\n", "\n", " star = \"★\" if is_best else \" \"\n", " # SURGICAL FIX 4: Display effective boundary weight in logs\n", " effective_bnd_w = criterion.effective_w_bnd\n", " print(\n", " f\"E{epoch:03d}|Ph{phase}|pe={ps.phase_ep:02d}|\"\n", " f\"LR:{lr:.2e}|\"\n", " f\"Tr:{tr_loss:.3f}|GN:{gnorm:.4f}|\"\n", " f\"db:{comp['db']:.3f} lov:{comp['lovasz']:.3f} mae:{comp.get('mae',0):.3f} ssim:{comp.get('ssim',0):.3f} grad:{comp.get('grad',0):.3f} \"\n", " f\"bnd:{comp['bnd']:.3f}(w={effective_bnd_w:.2f}) bi:{comp.get('biou_l',0):.3f} st:{comp.get('struct',0):.3f} ero:{comp.get('ero',0):.3f} conf:{comp.get('conf',0):.3f}|\"\n", " f\"FI-BIoU={fi_biou:.2f}% SAD={fi_sad:.2f} MSE={fi_mse:.4f} | Crop-BIoU={biou:.2f}%{star}(d2={biou_d2:.2f}%)|\"\n", " f\"{mins:.1f}min|VRAM:{vram_gb():.1f}GB|Peak:{vram_peak_gb():.1f}GB\"\n", " )\n", " if gnorm > 80: print(f\" ⚠ grad norm {gnorm:.2f} elevated\")\n", " if gnorm > 300: print(f\" 🚨 grad norm {gnorm:.2f} — monitor closely\")\n", "\n", " preview_ran = False\n", " sample_fi_biou = 0.0\n", " if epoch % CFG.preview_every == 0:\n", " try:\n", " fi_met = save_epoch_preview(\n", " model, ema, val_ds, device, epoch, CFG.preview_dir,\n", " dilation=CFG.metric_dilation,\n", " crop_metrics={\"biou\": biou, \"pa\": pa, \"iou\": iou},\n", " cfg=CFG)\n", " sample_fi_biou = fi_met[\"biou\"]\n", " preview_ran = True\n", " except Exception as exc:\n", " print(f\" ⚠ Preview failed: {exc}\")\n", "\n", " # Bug 5 fix: removed the four dead variables (full_biou, full_pa,\n", " # full_iou, full_val_ran) that were set and never read. Full-dataset\n", " # validation is deliberately not run per-epoch; compute_full_val_biou\n", " # is available as a standalone post-hoc utility.\n", "\n", " row = dict(\n", " epoch=epoch, phase=trained_phase, phase_ep=trained_phase_ep,\n", " lr_decoder=f\"{lr:.2e}\",\n", " lr_backbone=f\"{opt.param_groups[0]['lr']:.2e}\" if len(opt.param_groups) > 1 else \"0.00e+00\",\n", " train_loss=round(tr_loss, 4), val_loss=round(vm[\"val_loss\"], 4),\n", " grad_norm=round(gnorm, 4),\n", " n_skip=n_skip, n_spike=n_spike,\n", " biou=round(biou, 4), biou_d2=round(biou_d2, 4), pa=round(pa, 4), iou=round(iou, 4),\n", " best_biou=round(best_biou, 4),\n", " fi_biou=round(fi_biou, 4),\n", " fi_pa=round(fi_pa, 4),\n", " fi_iou=round(fi_iou, 4),\n", " fi_sad=round(fi_sad, 4),\n", " fi_mse=round(fi_mse, 6),\n", " gap_crop_full=round(biou - fi_biou, 4),\n", " loss_db=round(comp[\"db\"], 4),\n", " loss_lovasz=round(comp[\"lovasz\"], 4),\n", " loss_mae=round(comp.get(\"mae\", 0.0), 4),\n", " loss_ssim=round(comp.get(\"ssim\", 0.0), 4),\n", " loss_grad=round(comp.get(\"grad\", 0.0), 4),\n", " loss_bnd=round(comp[\"bnd\"], 4),\n", " loss_biou=round(comp.get(\"biou_l\", 0.0), 4),\n", " loss_struct=round(comp.get(\"struct\", 0.0), 4),\n", " loss_ero=round(comp.get(\"ero\", 0.0), 4),\n", " loss_conf=round(comp.get(\"conf\", 0.0), 4),\n", " adapt_w_bnd=round(criterion.effective_w_bnd, 4),\n", " minutes=round(mins, 1))\n", " logger.log(row); history.append(row)\n", "\n", " payload = {\n", " \"epoch\": epoch,\n", " # FIX: Snapshot config so we can always trace what produced this checkpoint.\n", " \"config_snapshot\": {k: (list(v) if isinstance(v, (list, tuple)) else v)\n", " for k, v in vars(CFG).items()\n", " if not k.startswith('_') and not callable(v)},\n", " \"phase_state\": ps.state_dict(),\n", " \"criterion_state\": criterion.state_dict(),\n", " # Bug 6 fix: removed duplicate key 'biou_best' (same value as\n", " # 'best_biou'). Load path uses .get('biou_best', .get('best_biou'))\n", " # so old checkpoints still load correctly.\n", " \"best_biou\": best_biou,\n", " \"fi_biou_best\": best_fi_biou,\n", " \"prev_biou\": prev_biou,\n", " \"model_state\": getattr(model, \"_orig_mod\", model).state_dict(),\n", " \"ema_state\": ema.state_dict(),\n", " \"opt_state\": opt.state_dict(),\n", " \"sched_state\": sched.state_dict(),\n", " \"scaler_state\": scaler.state_dict(),\n", " \"rng_state\": _rng_state_dict(),\n", " \"history\": history[-10:],\n", " }\n", " ok = ckpt_mgr.save(epoch, payload)\n", " if not ok: print(f\" ⚠ Checkpoint FAILED ep={epoch}\")\n", " if is_best:\n", " ckpt_mgr.save_best(epoch, payload, biou)\n", " ckpt_mgr.save_ema_weights_only(ema.state_dict(), biou)\n", " del payload; gc.collect()\n", "\n", " if (biou >= CFG.target_biou and fi_pa >= CFG.target_pa and\n", " preview_ran and fi_biou >= CFG.target_fi_biou):\n", " print(f\"\\n{'🎯'*5} TARGET REACHED {'🎯'*5}\")\n", " print(f\" crop-BIoU={biou:.2f}% fi_PA={fi_pa:.2f}% full-BIoU={fi_biou:.2f}% (epoch {epoch})\")\n", " break\n", "\n", " sep = \"═\" * 76\n", " print(f\"\\n{sep}\")\n", " print(f\" Training complete. Best BIoU: {best_biou:.2f}% | Best full-img BIoU: {best_fi_biou:.2f}%\")\n", " print(f\" Checkpoints → {CFG.drive_ckpt_dir}\")\n", " print(sep)\n", "\n", " if EXPORT_EMA_ONLY:\n", " thin = \"─\" * 60\n", " print(f\"\\n{thin}\")\n", " print(\" Post-training export (EXPORT_EMA_ONLY=True)\")\n", " ema_w_path = Path(CFG.drive_ckpt_dir) / \"best_ema_weights.pth\"\n", " if ema_w_path.exists():\n", " print(f\" ✓ best_ema_weights.pth exists ({ema_w_path.stat().st_size/1e6:.1f} MB)\")\n", " else:\n", " print(\" ⚠ best_ema_weights.pth not found — saving current EMA now …\")\n", " ckpt_mgr.save_ema_weights_only(ema.state_dict(), best_biou)\n", " export_onnx(model, ema.state_dict(), CFG.drive_ckpt_dir, CFG.crop_size)\n", " print(f\"{thin}\\n\")\n", "\n", " finally:\n", "\n", " try:\n", " if isinstance(train_dl, DualStreamLoader):\n", " train_dl.close()\n", " except Exception:\n", " pass\n", "\n", "if __name__ == \"__main__\":\n", " main()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.12" } }, "nbformat": 4, "nbformat_minor": 5 }