diff --git a/kimi - 23-08-26/ai.ipynb b/kimi - 23-08-26/ai.ipynb deleted file mode 100644 index d32e21ef945549a6a464c5d8d7568f290075d501..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/ai.ipynb +++ /dev/null @@ -1,3010 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "id": "3e33bc8e-6677-466b-bed6-b79cd09c4b59", - "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", - " SURGICAL PLAN v2 — sharp-boundary objective (cold start)\n", - "════════════════════════════════════════════════════════════════════════════\n", - " Losses : dicebce=[2.0, 2.0, 1.5] ssim=[0.5, 0.5, 0.5] biou=[0.1, 0.1, 0.1]\n", - " lovasz=[0.1, 0.1, 0.1] struct=[0.0, 0.2, 0.2] aux=[0.3, 0.15, 0.05]\n", - " bnd/mae/grad/ero/conf = 0 (computed only if >0)\n", - " LR : decoder=[0.0001, 7e-05, 3e-05] bb_frac=[0.0, 0.25, 0.1] wd=0.0002\n", - " Schedule : hold-then-cosine (hold 15%/20%) phases=[18, 40, 72]\n", - " EMA : 0.995 → 0.9985 (P2+) clip=[5.0, 35.0, 25.0]\n", - " Data : bnd_crop=[0.25, 0.45, 0.35] scale=[0.35,1.8] global=0.25→0.35@P3\n", - "────────────────────────────────────────────────────────────────────────────\n", - " Kill-switch: ep10 ≥68 | ep18 ≥72 | ep30 ≥76 w/ val_loss falling\n", - " Selection: crop-BIoU | fi_* tracked every epoch on 25-image fixed set\n", - "════════════════════════════════════════════════════════════════════════════\n", - "\n", - " Dataset ready (ok:same_path)\n", - " Loading joelseytre/toonout …\n", - " [Fix] joelseytre/toonout is missing config files. Using base architecture from 'ZhengPeng7/BiRefNet'...\n", - " [Fix] Downloading custom weights 'birefnet_finetuned_toonout.pth'...\n", - " [Fix] Applying custom weights to model...\n", - " from_pretrained: 31.4s\n", - " .to(device): 0.2s\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", - " ✓ Loaded RAM cache from .ram_cache_images.pkl (1869 pairs, 39.5s)\n", - " ✓ Loaded RAM cache from .ram_cache_images.pkl (250 pairs, 5.6s)\n", - " [val] 1250 fixed crops from 250 images (seed=42, k=5)\n", - " Train: 1869 pairs | Val: 1250 items\n", - " Dual-stream: each batch is 1× global + 1× local\n", - " Fixed preview set: 25 canonical val images (indices: [6, 7, 8, 22, 23, 26, 28, 35, 55, 57, 59, 62, 70, 108, 129, 139, 151, 154, 163, 173, 188, 189, 228, 246, 247])\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 66)\n", - " Loaded ckpt_B.pth (epoch 66)\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=14ep T_max=72\n", - " Optimizer state restored (tensors moved to device)\n", - " Scheduler last_epoch aligned to phase_ep=8\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=1.5 lovasz=0.1 mae=0.0 ssim=0.5 grad=0.0 struct=0.2 bnd=0.0 biou=0.1 ero=0.0 conf=0.0 aux=0.05\n", - "\n", - " ✅ Resumed ep=66 → continue 67\n", - " Phase=3 phase_ep=8 LR=3.00e-05\n", - " best_biou=81.87% best_fi_biou=86.32% prev_biou=86.28%\n", - " adaptive_w_bnd=0.000\n", - "\n", - "\n", - "════════════════════════════════════════════════════════════════════════════\n", - " A100 SXM4 MIG 20GB | BF16 AMP | TF32 | NCHW | eager\n", - " Model : joelseytre/toonout\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 : 67 → 130\n", - " Goal : crop-BIoU ≥ 95.0% PA ≥ 99.5% full-img BIoU ≥ 95.0%\n", - "════════════════════════════════════════════════════════════════════════════\n", - "\n" - ] - }, - { - "name": "stderr", - "output_type": "stream", - "text": [ - " \r" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "E067|Ph3|pe=09|LR:3.00e-05|Tr:0.107|GN:2.1717|db:0.019 lov:0.069 mae:0.000 ssim:0.025 grad:0.000 bnd:0.000(w=0.00) bi:0.343 st:0.095 ero:0.000 conf:0.000|FI-BIoU=86.31% SAD=8.59 MSE=0.0036 | Crop-BIoU=81.70% (d2=75.46%)|40.5min|VRAM:11.3GB|Peak:17.2GB\n" - ] - }, - { - "name": "stderr", - "output_type": "stream", - "text": [ - " \r" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "E068|Ph3|pe=10|LR:3.00e-05|Tr:0.110|GN:2.2229|db:0.020 lov:0.068 mae:0.000 ssim:0.026 grad:0.000 bnd:0.000(w=0.00) bi:0.346 st:0.097 ero:0.000 conf:0.000|FI-BIoU=86.65% SAD=8.72 MSE=0.0037 | Crop-BIoU=81.43% (d2=75.20%)|40.0min|VRAM:12.2GB|Peak:18.8GB\n" - ] - }, - { - "name": "stderr", - "output_type": "stream", - "text": [ - " \r" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "E069|Ph3|pe=11|LR:3.00e-05|Tr:0.109|GN:2.2497|db:0.019 lov:0.069 mae:0.000 ssim:0.026 grad:0.000 bnd:0.000(w=0.00) bi:0.350 st:0.095 ero:0.000 conf:0.000|FI-BIoU=86.68% SAD=8.71 MSE=0.0037 | Crop-BIoU=81.50% (d2=75.29%)|39.8min|VRAM:12.3GB|Peak:17.6GB\n" - ] - }, - { - "name": "stderr", - "output_type": "stream", - "text": [ - " \r" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "E070|Ph3|pe=12|LR:3.00e-05|Tr:0.106|GN:2.2829|db:0.019 lov:0.067 mae:0.000 ssim:0.022 grad:0.000 bnd:0.000(w=0.00) bi:0.336 st:0.096 ero:0.000 conf:0.000|FI-BIoU=86.74% SAD=8.64 MSE=0.0037 | Crop-BIoU=81.64% (d2=75.44%)|39.9min|VRAM:12.3GB|Peak:17.7GB\n" - ] - }, - { - "name": "stderr", - "output_type": "stream", - "text": [ - " \r" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "E071|Ph3|pe=13|LR:3.00e-05|Tr:0.125|GN:2.4956|db:0.024 lov:0.081 mae:0.000 ssim:0.032 grad:0.000 bnd:0.000(w=0.00) bi:0.371 st:0.107 ero:0.000 conf:0.000|FI-BIoU=86.79% SAD=8.68 MSE=0.0037 | Crop-BIoU=81.70% (d2=75.53%)|39.7min|VRAM:12.3GB|Peak:17.7GB\n" - ] - }, - { - "name": "stderr", - "output_type": "stream", - "text": [ - " Val E072: 24%|██▍ | 153/625 [01:48<05:35, 1.41batch/s, BIoU=83.0%, BIoU2=76.8%, PA=96.0%, loss=0.117]" - ] - } - ], - "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\",\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", - " # v3 FIX: ONNX export failed post-training (\"No module named 'onnxscript'\")\n", - " \"onnx\",\n", - " \"onnxscript\",\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\", \"--user\", \"packaging\"])\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\", \"--user\", pkg])\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", - "\n", - "# Quiet HF hub console noise (progress bars, \"new version\" warnings) — must be set\n", - "# before transformers/huggingface_hub are imported below.\n", - "os.environ.setdefault(\"HF_HUB_DISABLE_PROGRESS_BARS\", \"1\")\n", - "os.environ.setdefault(\"TRANSFORMERS_NO_ADVISORY_WARNINGS\", \"1\")\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 = \".\"\n", - " drive_dataset : str = \"./dataset\"\n", - " ssd_dataset : str = \"./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 = \"joelseytre/toonout\"\n", - " revision : Optional[str] = None\n", - " hf_cache : str = \"./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", - " # v2: Phase 2 shortened 41→40, Phase 3 extended 70→72 (total stays 130).\n", - " # Overfitting onset in the old run coincided with the tail of the P2 peak-LR hold.\n", - " max_phase_epochs : List[int] = field(default_factory=lambda: [18, 40, 72])\n", - " # Per-phase patience and sensitivity.\n", - " # Phase 1: decoder-only converges fast; 5-epoch window catches plateau early.\n", - " # Phase 2: backbone + decoder co-adapting; need 10 epochs to confirm stall.\n", - " # Phase 3: fine-tuning; let it run the full 15 epochs before giving up.\n", - " phase_patience_per_phase : List[int] = field(default_factory=lambda: [5, 10, 15])\n", - " phase_min_delta_per_phase : List[float] = field(default_factory=lambda: [0.15, 0.25, 0.30])\n", - "\n", - " force_dual_stream : bool = True\n", - " p_global_fallback : float = 0.35\n", - "\n", - " # ── SURGICAL PLAN v2 (cold-start): sharp-boundary objective ──────────────\n", - " # Dataset analysis: edge transition width 0.34px → masks are effectively hard.\n", - " # Ep40 loss decomposition showed boundary-BCE + gradient loss consumed ~53% of the\n", - " # scalar objective chasing sub-pixel AA noise. New shares at convergence levels:\n", - " # DiceBCE ~38%, BIoU ~31%, Struct ~17%, SSIM ~8%, Lovász ~6%.\n", - " w_dicebce : List[float] = field(default_factory=lambda: [2.0, 2.0, 1.5])\n", - " # Lovász: IoU-aware surrogate. Kept low — covers the IoU surface.\n", - " w_lovasz : List[float] = field(default_factory=lambda: [0.1, 0.1, 0.1])\n", - " # MAE: REMOVED — redundant with DiceBCE on sharp masks.\n", - " w_mae : List[float] = field(default_factory=lambda: [0.0, 0.0, 0.0])\n", - " w_ssim : List[float] = field(default_factory=lambda: [0.5, 0.5, 0.5])\n", - " # Gradient loss: REMOVED — Sobel/Laplacian chases 1px anti-aliasing noise.\n", - " w_grad : List[float] = field(default_factory=lambda: [0.0, 0.0, 0.0])\n", - " # Structure Loss: BiRefNet's official spatially-weighted BCE+IoU.\n", - " w_struct : List[float] = field(default_factory=lambda: [0.0, 0.2, 0.2])\n", - " # Boundary BCE: REMOVED — band-normalized BCE is noisy on 0.34px-sharp GT.\n", - " w_bnd : List[float] = field(default_factory=lambda: [0.0, 0.0, 0.0])\n", - " # BIoU loss: soft band-IoU at d=5,12. Raw value ~0.42 is deceptively heavy —\n", - " # 0.3 weight = ~57% of objective (past failure mode). Keep at 0.1 flat.\n", - " w_biou : List[float] = field(default_factory=lambda: [0.1, 0.1, 0.1])\n", - " w_aux : List[float] = field(default_factory=lambda: [0.3, 0.15, 0.05])\n", - " # Erosion consistency: OFF. Re-enable at 0.05 in P3 ONLY if blob artifacts appear.\n", - " w_erosion : List[float] = field(default_factory=lambda: [0.0, 0.0, 0.0])\n", - " # Confidence loss: OFF. P3 candidate at 0.05 if interiors hedge at p≈0.8.\n", - " w_confidence : List[float] = field(default_factory=lambda: [0.0, 0.0, 0.0])\n", - " global_ratio : float = 0.25\n", - " # v2: more full-image views during Phase 3 polish (targets fi_sad degradation).\n", - " global_ratio_phase3 : float = 0.35\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", - " # v2: 1e-4 → 2e-4 — anti-overfit on 1,850 images; 3e-4 risked underfitting P1.\n", - " weight_decay : float = 2e-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", - " # v3 FIX: owner's actual targets — the gate now means \"mission accomplished\",\n", - " # never an early stop. (Old 80/99.5/86 fired at ep50 and killed a winning run.)\n", - " target_biou : float = 95.0\n", - " target_pa : float = 99.5\n", - " target_fi_biou : float = 95.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=None, 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=None, 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_REFLECT_101)\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", - " # 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", - " mask_interp = cv2.INTER_AREA 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_CONSTANT, value=0)\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 = sum(1 for _ in range(self.bs) if self.rng.random() < CFG.global_ratio)\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", - " _zero = torch.zeros(1, device=main.device)\n", - " if self.w_lovasz > 0.0:\n", - " lov = _lovasz_hinge_loss(main, gt_r)\n", - " else:\n", - " lov = _zero\n", - " # v2: guard zero-weight terms — skips MAE, SSIM-11, 7-conv2d gradient loss and\n", - " # the 4-scale maxpool boundary BCE at 1024² (~15-25% of step time) when w=0.\n", - " mae = _l1_loss(p, gt_r) if self.w_mae > 0.0 else _zero\n", - " ssim = self._ssim_loss_fn(p, gt_r) if self.w_ssim > 0.0 else _zero\n", - " grad = _gradient_loss(p, gt_r) if self.w_grad > 0.0 else _zero\n", - " bnd = (_multiscale_boundary_bce_loss(main, gt_r,\n", - " bce_clamp=self.cfg.bnd_bce_clamp)\n", - " if self.w_bnd > 0.0 else _zero)\n", - " if self.w_struct > 0.0:\n", - " struct = _structure_loss(main, p, gt_r)\n", - " else:\n", - " struct = _zero\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(dim=(1,2,3))\n", - " union_b = (p_bnd + g_bnd - p_bnd * g_bnd).sum(dim=(1,2,3))\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 = torch.where(union_b > 1e-6, 100.0 * inter_b / union_b.clamp_min(1e-6), torch.full_like(union_b, 100.0)).mean().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(dim=(1,2,3))\n", - " union_b2 = (p_bnd2 + g_bnd2 - p_bnd2 * g_bnd2).sum(dim=(1,2,3))\n", - " biou_d2 = torch.where(union_b2 > 1e-6, 100.0 * inter_b2 / union_b2.clamp_min(1e-6), torch.full_like(union_b2, 100.0)).mean().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", - " ph_idx = self.phase - 1\n", - " patience = self.cfg.phase_patience_per_phase[ph_idx]\n", - " min_delt = self.cfg.phase_min_delta_per_phase[ph_idx]\n", - "\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 < min_delt:\n", - " print(f\" Phase {self.phase} plateau (Δ={recent_delta:.3f} < {min_delt}) — 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", - " import torch\n", - " import torch.utils._pytree\n", - " if not hasattr(torch.utils._pytree, 'register_constant'):\n", - " torch.utils._pytree.register_constant = lambda *args, **kwargs: None\n", - " \n", - " from transformers import logging as hf_logging\n", - " from transformers.modeling_utils import PreTrainedModel\n", - " import transformers\n", - " transformers.PreTrainedModel = PreTrainedModel\n", - "\n", - " # Quiet console: ERROR-only HF logging (kills config JSON dump + \"loading from\n", - " # cache\" lines), no download progress bars, no \"new version of files\" warnings.\n", - " import logging as _logging\n", - " os.environ.setdefault(\"HF_HUB_DISABLE_PROGRESS_BARS\", \"1\")\n", - " hf_logging.set_verbosity_error()\n", - " _logging.getLogger(\"huggingface_hub\").setLevel(_logging.ERROR)\n", - " try:\n", - " from huggingface_hub.utils import disable_progress_bars\n", - " disable_progress_bars()\n", - " except Exception:\n", - " pass\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", - " \n", - " if cfg.model_id == \"joelseytre/toonout\":\n", - " print(f\" [Fix] {cfg.model_id} is missing config files. Using base architecture from 'ZhengPeng7/BiRefNet'...\")\n", - " model = AutoModelForImageSegmentation.from_pretrained(\"ZhengPeng7/BiRefNet\", **kwargs)\n", - " \n", - " print(\" [Fix] Downloading custom weights 'birefnet_finetuned_toonout.pth'...\")\n", - " from huggingface_hub import hf_hub_download\n", - " weight_path = hf_hub_download(repo_id=\"joelseytre/toonout\", filename=\"birefnet_finetuned_toonout.pth\", cache_dir=cfg.hf_cache)\n", - " \n", - " state_dict = torch.load(weight_path, map_location=\"cpu\", weights_only=False)\n", - " if \"state_dict\" in state_dict: \n", - " state_dict = state_dict[\"state_dict\"]\n", - " \n", - " print(\" [Fix] Applying custom weights to model...\")\n", - " model.load_state_dict(state_dict, strict=False)\n", - " else:\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", - " # v2: Phase 2+ hold 0.30→0.20 — overfitting onset in the old run coincided with the\n", - " # tail of the 12-epoch peak-LR hold; cosine decay now starts ~4 epochs earlier.\n", - " hold = 0.15 if phase == 1 else 0.20\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()\n", - " if torch.cuda.is_available():\n", - " torch.cuda.empty_cache()\n", - " try:\n", - " torch.cuda.reset_peak_memory_stats()\n", - " except RuntimeError:\n", - " pass # Some MIG instances or PyTorch versions crash on this call\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", - " # COMPACT CONFIG SUMMARY (v2)\n", - " # ═══════════════════════════════════════════════════════════════════════════\n", - " print(\"\\n\" + \"═\" * 76)\n", - " print(\" SURGICAL PLAN v2 — sharp-boundary objective (cold start)\")\n", - " print(\"═\" * 76)\n", - " print(f\" Losses : dicebce={CFG.w_dicebce} ssim={CFG.w_ssim} biou={CFG.w_biou}\")\n", - " print(f\" lovasz={CFG.w_lovasz} struct={CFG.w_struct} aux={CFG.w_aux}\")\n", - " print(f\" bnd/mae/grad/ero/conf = 0 (computed only if >0)\")\n", - " print(f\" LR : decoder={CFG.lr_decoder_phase} bb_frac={CFG.backbone_lr_frac} wd={CFG.weight_decay}\")\n", - " print(f\" Schedule : hold-then-cosine (hold 15%/20%) phases={CFG.max_phase_epochs}\")\n", - " print(f\" EMA : {CFG.ema_decay} → {CFG.ema_decay_phase2} (P2+) clip={CFG.grad_clip_phase}\")\n", - " print(f\" Data : bnd_crop={CFG.bnd_ratio} scale=[{CFG.scale_aug_lo},{CFG.scale_aug_hi}] \"\n", - " f\"global={CFG.global_ratio}→{CFG.global_ratio_phase3}@P3\")\n", - " print(\"─\" * 76)\n", - " print(\" Kill-switch: ep10 ≥68 | ep18 ≥72 | ep30 ≥76 w/ val_loss falling\")\n", - " print(\" Selection: crop-BIoU | fi_* tracked every epoch on 25-image fixed set\")\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", - " # v2: 8 → 25 fixed eval images — 8-image fi metrics were too noisy to select on\n", - " # (fi_sad swings ep32→34 were partly sampling noise). Cost ~5-8 min/epoch.\n", - " _n_fixed = min(25, 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", - " CFG.global_ratio = CFG.global_ratio_phase3 # v2: match in-loop P3 transition\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", - " # v2: raise full-image share in P3 (DualStreamLoader reads\n", - " # CFG.global_ratio live, so this takes effect next batch).\n", - " CFG.global_ratio = CFG.global_ratio_phase3\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()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "81844e7d-06ef-42d3-b000-80a40d07ea09", - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "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.11.6" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/kimi - 23-08-26/baseline_toonout.csv b/kimi - 23-08-26/baseline_toonout.csv deleted file mode 100644 index b8f73a74f5290443861e7353d13bb78f3a647615..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/baseline_toonout.csv +++ /dev/null @@ -1,27 +0,0 @@ -image,biou,biou_d2,pa,iou,sad,mse,secs -1053.png,80.0056,67.0234,99.6351,98.5182,4.0723,0.002014,65.0 -106.png,73.6253,61.6587,98.6153,96.2868,17.2347,0.010809,17.1 -1060.png,76.8785,66.684,99.6546,99.267,3.9899,0.002604,13.6 -1170.png,74.4277,64.3158,97.9075,97.1965,20.2663,0.012618,26.1 -1179.png,76.6178,64.3149,99.4525,99.1635,8.0347,0.003756,19.3 -1196.png,81.9554,64.93,99.724,99.4328,19.2462,0.002457,36.6 -1228.png,57.2479,45.6874,93.4081,89.6683,148.3074,0.072448,37.0 -127.png,94.6737,88.3986,99.9803,99.9263,0.8948,7.1e-05,80.7 -1487.png,94.1883,86.0171,99.9201,99.8731,1.2315,0.000255,8.5 -1529.png,65.4592,51.9432,98.6033,98.0285,14.3458,0.011324,6.1 -1544.png,79.551,62.7899,99.8292,99.7863,13.3749,0.001546,9.5 -1586.png,46.5923,41.4743,94.8132,91.5803,55.7963,0.050726,5.5 -1668.png,89.0635,80.7666,99.8559,99.7941,2.872,0.000869,5.0 -1900.png,86.8495,73.5668,99.9084,99.6541,7.9651,0.000793,37.8 -2079.png,23.8443,20.006,96.9959,96.8153,53.447,0.030249,9.3 -239.png,91.9354,85.4717,99.9089,99.8562,1.3578,0.000412,10.1 -345.png,85.5893,79.1867,99.7204,99.5246,5.9683,0.002703,7.8 -362.png,82.3303,68.1581,99.781,99.6319,5.4144,0.001097,30.4 -426.png,75.521,60.5519,99.7353,99.4698,3.8173,0.001566,25.5 -489.png,88.0337,76.4891,99.8503,99.6605,8.7023,0.00114,35.4 -63.png,87.8608,78.7032,99.8305,99.7754,2.6133,0.001,7.8 -630.png,87.8979,74.9435,99.8739,99.6825,2.3538,0.000657,14.4 -894.png,72.1702,65.4221,96.9108,95.0816,35.001,0.02941,20.8 -979.png,87.5784,81.5235,99.3436,99.1986,6.5843,0.003076,11.6 -991.png,83.905,70.0287,99.7764,99.6746,14.5152,0.001861,23.4 -SUMMARY (mean),77.7521,67.2022,98.9214,98.2619,18.2963,0.0098, diff --git a/kimi - 23-08-26/checkpoints/best_ema.pth b/kimi - 23-08-26/checkpoints/best_ema.pth deleted file mode 100644 index 88d7ba057e938f07cd3fe529ccfecb1dbdc7b785..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/checkpoints/best_ema.pth +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dbfc779b74fb38c7da576278da3c090468a98bcd6e7101a168b7a0a8565cb406 -size 3530077646 diff --git a/kimi - 23-08-26/checkpoints/best_ema_weights.pth b/kimi - 23-08-26/checkpoints/best_ema_weights.pth deleted file mode 100644 index 1fbf84478752cb9acc854f037a311b1194af6136..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/checkpoints/best_ema_weights.pth +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1065b5102e222b5d3d0e1112b17827a92ffd5c100c18a0508711b60126881942 -size 883048244 diff --git a/kimi - 23-08-26/checkpoints/ckpt_A.pth b/kimi - 23-08-26/checkpoints/ckpt_A.pth deleted file mode 100644 index 964c63a6e5c571548594830dd79413e6e4b740b3..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/checkpoints/ckpt_A.pth +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:798a61f31bce3b502db450bf366ee737d989e7c85a14b0dbf8bd14d70752dfe6 -size 3530062884 diff --git a/kimi - 23-08-26/checkpoints/ckpt_B.pth b/kimi - 23-08-26/checkpoints/ckpt_B.pth deleted file mode 100644 index 03d378a1efb23ac5539eca6f000c8f9f95dc2e42..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/checkpoints/ckpt_B.pth +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:890ba0861610262678bd04fccf94fe97d48cffb1d61c9ccb81db1f8018e9791c -size 3530063332 diff --git a/kimi - 23-08-26/checkpoints/ckpt_C.pth b/kimi - 23-08-26/checkpoints/ckpt_C.pth deleted file mode 100644 index a4469e6897b608112d91a4d8eab2e140842e2f22..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/checkpoints/ckpt_C.pth +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:02d4a77835efe533be63339ac6e2b30c7454af97c3d66bd6df8ae542303417be -size 3530062436 diff --git a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_002-checkpoint.png b/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_002-checkpoint.png deleted file mode 100644 index d268091547c7a5cd22fedf3f1942897361847809..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_002-checkpoint.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:3e5cd31341f718461f2e5103b3f5991cb2caad4346400f2b921b27f5e7832481 -size 417648 diff --git a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_004-checkpoint.png b/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_004-checkpoint.png deleted file mode 100644 index 222b1b12dd002aa6e1a859b197f31c770a204a80..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_004-checkpoint.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d1e5a64f2bcffa29ccd9498dbd4ae2506582f85396b39eaa7ed97b80e317eacf -size 514666 diff --git a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_006-checkpoint.png b/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_006-checkpoint.png deleted file mode 100644 index 9d1a59e2a7b8a0c290d1f3eb25da16968820b8a8..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_006-checkpoint.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:327d4c0cdd2ff366ad2f18f074ae27c16c475c9e24e39374c95543abe90d745f -size 294330 diff --git a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_008-checkpoint.png b/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_008-checkpoint.png deleted file mode 100644 index ccd2237cae90cb34b28bc88aa1a4fbc59c58d471..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_008-checkpoint.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2595b11769286402a9f2732fc98b4a4327ffe21a99524b7fed1d9dedd486b782 -size 353187 diff --git a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_012-checkpoint.png b/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_012-checkpoint.png deleted file mode 100644 index 3ff8672818a8e73fd3fe592ab8fa1232dd5a7211..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_012-checkpoint.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4adce132db5aa717f678f0af062de48cfab60452c135e12454b8fdf9eb9c4c70 -size 300577 diff --git a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_014-checkpoint.png b/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_014-checkpoint.png deleted file mode 100644 index fb3d7a9fc617bc5cbcbca486cfa6114950f01460..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_014-checkpoint.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a789363b73320ae18abb6849503450f6023cdd126da5a5ff09bfaf41e1c912fc -size 450549 diff --git a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_024-checkpoint.png b/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_024-checkpoint.png deleted file mode 100644 index 106f7126fc76c3c5977520bfd66fa88952e7202c..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_024-checkpoint.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:32c525b631a82ba86a741991e2062cdfe8df780bc8ec073debbaad9d6d68c908 -size 326612 diff --git a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_028-checkpoint.png b/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_028-checkpoint.png deleted file mode 100644 index a8d2be9ca1a4a7fe5b4986408b68c5500bb6e9ec..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_028-checkpoint.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e5aed9ed621d33f817d871aa05f7d957d84830fa6d7b06c9e78f2fff3d799a80 -size 418537 diff --git a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_030-checkpoint.png b/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_030-checkpoint.png deleted file mode 100644 index e01bdd08a8988205b622d96d906bfe16fa7da3e6..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_030-checkpoint.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:da91389272639bc24fe70205676ac5cfba011254528c531c5e409dfffc68059b -size 445574 diff --git a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_032-checkpoint.png b/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_032-checkpoint.png deleted file mode 100644 index 38f653ba19f28c575ec99ce717a028689449c4e2..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_032-checkpoint.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6470e04ba286e74b1fc4f51057ad0fd4484eca548b8d9f67c599190948bef469 -size 423993 diff --git a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_034-checkpoint.png b/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_034-checkpoint.png deleted file mode 100644 index d36f1fb3944d7970cd3a8e169a67c474e4c2d9f3..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_034-checkpoint.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a909e328121e201adcdd31b0f1a884de43ee26cea5f3d15f2f2440cb6910c239 -size 606049 diff --git a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_036-checkpoint.png b/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_036-checkpoint.png deleted file mode 100644 index 380641557eaf87b4e11ccf57b715b8bb5d9483a9..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_036-checkpoint.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7c6eadf2763ce058a760e7f6121601255b90edf025f40fc903613ded6361dd4d -size 328791 diff --git a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_038-checkpoint.png b/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_038-checkpoint.png deleted file mode 100644 index fcd43778ddb5603fad017b3e88161f9e14c9eb6e..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_038-checkpoint.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c7a26fba557c59bd9d9b8f72fc997868573b642f54dfd6fe739fb1ae78814e60 -size 454227 diff --git a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_040-checkpoint.png b/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_040-checkpoint.png deleted file mode 100644 index 9680dc9505065ece6ab010cce648035f1a0cf1b7..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_040-checkpoint.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:82ca850f6e025f249c3cef44f5d3a5ec67aaad20a5246ca22ea687f9ae42ce15 -size 267733 diff --git a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_042-checkpoint.png b/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_042-checkpoint.png deleted file mode 100644 index a8f2b0cf99b3e5c0622d5e62b569d9d7a4d7e9c0..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_042-checkpoint.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0cc81c6671907555cd2cfca1b694daac44d64a873a1c3b268eca93fda6a59f8f -size 602322 diff --git a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_046-checkpoint.png b/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_046-checkpoint.png deleted file mode 100644 index 4a628ddc610bbb446cc0d57daec31b146f7a50a3..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_046-checkpoint.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0cea885e6b12894b1cb18e372db62478157fbd227bf2271fe8ebcc3ca15cded6 -size 483759 diff --git a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_050-checkpoint.png b/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_050-checkpoint.png deleted file mode 100644 index 6c39e4b57d5836956d4fc2dba4d096162cda751f..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_050-checkpoint.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:bbbf90069512ac66353b072395180048526d153e5122cbc5ee036f81f280a0a7 -size 350986 diff --git a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_052-checkpoint.png b/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_052-checkpoint.png deleted file mode 100644 index aed86feb57381111affb2a812b0bacaffc852414..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_052-checkpoint.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f18602658d38b5c239e8e31b365920e969a9b60ce079e415bc436ac78cb220ae -size 457118 diff --git a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_054-checkpoint.png b/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_054-checkpoint.png deleted file mode 100644 index 1926b69f2593d2e20ef5a510bff5f238651faf54..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_054-checkpoint.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:61bd294c235fb811f0792b11f10a92a5e591b91746aa442b264643e9a537bb44 -size 388920 diff --git a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_056-checkpoint.png b/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_056-checkpoint.png deleted file mode 100644 index bac129c06b215c9ba491b6274b57b2c3d85ff2be..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_056-checkpoint.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b3d9356335f1c65cacc0b3977b6e3d7b470536dc5048bbdbc2cb1c2f133cf8e8 -size 353904 diff --git a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_060-checkpoint.png b/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_060-checkpoint.png deleted file mode 100644 index 3cdee034051d0f681c2bd347511b946f943c3d83..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_060-checkpoint.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:db324aebe6ec036c71ebab5a5fff54ff5fed3f4af1f512d2f648d2f725abf862 -size 495271 diff --git a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_062-checkpoint.png b/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_062-checkpoint.png deleted file mode 100644 index e41af0b5e7c899f1c490b5d8b0a9447d442c6e52..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_062-checkpoint.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9090be94cf235aeb6743b816a6f69e2c43be6a31bd050b9e8c05b33bdb1c0532 -size 551855 diff --git a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_066-checkpoint.png b/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_066-checkpoint.png deleted file mode 100644 index e347e9587a1d5448c875d76e2fe3506d84d821ba..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/.ipynb_checkpoints/epoch_066-checkpoint.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:20d1e21046332e599aa77761a6fb55bba548f5ee162a372aeb6d0439255c993c -size 396208 diff --git a/kimi - 23-08-26/preview/epoch_002.png b/kimi - 23-08-26/preview/epoch_002.png deleted file mode 100644 index d268091547c7a5cd22fedf3f1942897361847809..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_002.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:3e5cd31341f718461f2e5103b3f5991cb2caad4346400f2b921b27f5e7832481 -size 417648 diff --git a/kimi - 23-08-26/preview/epoch_004.png b/kimi - 23-08-26/preview/epoch_004.png deleted file mode 100644 index 222b1b12dd002aa6e1a859b197f31c770a204a80..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_004.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d1e5a64f2bcffa29ccd9498dbd4ae2506582f85396b39eaa7ed97b80e317eacf -size 514666 diff --git a/kimi - 23-08-26/preview/epoch_006.png b/kimi - 23-08-26/preview/epoch_006.png deleted file mode 100644 index 9d1a59e2a7b8a0c290d1f3eb25da16968820b8a8..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_006.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:327d4c0cdd2ff366ad2f18f074ae27c16c475c9e24e39374c95543abe90d745f -size 294330 diff --git a/kimi - 23-08-26/preview/epoch_008.png b/kimi - 23-08-26/preview/epoch_008.png deleted file mode 100644 index ccd2237cae90cb34b28bc88aa1a4fbc59c58d471..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_008.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2595b11769286402a9f2732fc98b4a4327ffe21a99524b7fed1d9dedd486b782 -size 353187 diff --git a/kimi - 23-08-26/preview/epoch_010.png b/kimi - 23-08-26/preview/epoch_010.png deleted file mode 100644 index fa6d0c94623729106e24564cf529772c7a7186d0..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_010.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2b6e22bd22658d7ef5e538b0c39afaa98849e64e7c7dc018eb71ae5cf7a517f6 -size 286715 diff --git a/kimi - 23-08-26/preview/epoch_012.png b/kimi - 23-08-26/preview/epoch_012.png deleted file mode 100644 index 3ff8672818a8e73fd3fe592ab8fa1232dd5a7211..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_012.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4adce132db5aa717f678f0af062de48cfab60452c135e12454b8fdf9eb9c4c70 -size 300577 diff --git a/kimi - 23-08-26/preview/epoch_014.png b/kimi - 23-08-26/preview/epoch_014.png deleted file mode 100644 index fb3d7a9fc617bc5cbcbca486cfa6114950f01460..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_014.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a789363b73320ae18abb6849503450f6023cdd126da5a5ff09bfaf41e1c912fc -size 450549 diff --git a/kimi - 23-08-26/preview/epoch_016.png b/kimi - 23-08-26/preview/epoch_016.png deleted file mode 100644 index fb8274c1b4e45560e2f95e5c3897761343aaf13e..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_016.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7fea974a951af292f113bfa10ac2478bd0f229e1f9dc25257b8c67319cf32e38 -size 479605 diff --git a/kimi - 23-08-26/preview/epoch_018.png b/kimi - 23-08-26/preview/epoch_018.png deleted file mode 100644 index b41bbfbd7c65a22f86d92ae450919b421a3aabc0..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_018.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6fd1ad5b7a532f90032f560fa619bc5f7afe28314c8659728557d5d0fa1e808f -size 323041 diff --git a/kimi - 23-08-26/preview/epoch_020.png b/kimi - 23-08-26/preview/epoch_020.png deleted file mode 100644 index 4d5095f9881511220015f15a396f5437de3ffc0c..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_020.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:de19d8d6fecdcb5f684b1914bb6ae193e28df08b917b87c5f46d0dd72723d9e7 -size 478838 diff --git a/kimi - 23-08-26/preview/epoch_022.png b/kimi - 23-08-26/preview/epoch_022.png deleted file mode 100644 index c8698bfe605a3d2f3e98346b239d82ef4b8c6157..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_022.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:579fcb453d9790ff5bafc148361c768a938b08135640d9b830c9523afbf249c7 -size 405978 diff --git a/kimi - 23-08-26/preview/epoch_024.png b/kimi - 23-08-26/preview/epoch_024.png deleted file mode 100644 index 106f7126fc76c3c5977520bfd66fa88952e7202c..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_024.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:32c525b631a82ba86a741991e2062cdfe8df780bc8ec073debbaad9d6d68c908 -size 326612 diff --git a/kimi - 23-08-26/preview/epoch_026.png b/kimi - 23-08-26/preview/epoch_026.png deleted file mode 100644 index a67e0d3772245cf5d1f22605d04eb75c54aad117..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_026.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8f7ccd5c8dd291af4dc36a00b5c76fe0474d4a8b767fb03b4ee2cd3547677f93 -size 254664 diff --git a/kimi - 23-08-26/preview/epoch_028.png b/kimi - 23-08-26/preview/epoch_028.png deleted file mode 100644 index a8d2be9ca1a4a7fe5b4986408b68c5500bb6e9ec..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_028.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e5aed9ed621d33f817d871aa05f7d957d84830fa6d7b06c9e78f2fff3d799a80 -size 418537 diff --git a/kimi - 23-08-26/preview/epoch_030.png b/kimi - 23-08-26/preview/epoch_030.png deleted file mode 100644 index e01bdd08a8988205b622d96d906bfe16fa7da3e6..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_030.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:da91389272639bc24fe70205676ac5cfba011254528c531c5e409dfffc68059b -size 445574 diff --git a/kimi - 23-08-26/preview/epoch_032.png b/kimi - 23-08-26/preview/epoch_032.png deleted file mode 100644 index 38f653ba19f28c575ec99ce717a028689449c4e2..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_032.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6470e04ba286e74b1fc4f51057ad0fd4484eca548b8d9f67c599190948bef469 -size 423993 diff --git a/kimi - 23-08-26/preview/epoch_034.png b/kimi - 23-08-26/preview/epoch_034.png deleted file mode 100644 index d36f1fb3944d7970cd3a8e169a67c474e4c2d9f3..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_034.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a909e328121e201adcdd31b0f1a884de43ee26cea5f3d15f2f2440cb6910c239 -size 606049 diff --git a/kimi - 23-08-26/preview/epoch_036.png b/kimi - 23-08-26/preview/epoch_036.png deleted file mode 100644 index 380641557eaf87b4e11ccf57b715b8bb5d9483a9..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_036.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7c6eadf2763ce058a760e7f6121601255b90edf025f40fc903613ded6361dd4d -size 328791 diff --git a/kimi - 23-08-26/preview/epoch_038.png b/kimi - 23-08-26/preview/epoch_038.png deleted file mode 100644 index fcd43778ddb5603fad017b3e88161f9e14c9eb6e..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_038.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c7a26fba557c59bd9d9b8f72fc997868573b642f54dfd6fe739fb1ae78814e60 -size 454227 diff --git a/kimi - 23-08-26/preview/epoch_040.png b/kimi - 23-08-26/preview/epoch_040.png deleted file mode 100644 index 9680dc9505065ece6ab010cce648035f1a0cf1b7..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_040.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:82ca850f6e025f249c3cef44f5d3a5ec67aaad20a5246ca22ea687f9ae42ce15 -size 267733 diff --git a/kimi - 23-08-26/preview/epoch_042.png b/kimi - 23-08-26/preview/epoch_042.png deleted file mode 100644 index a8f2b0cf99b3e5c0622d5e62b569d9d7a4d7e9c0..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_042.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0cc81c6671907555cd2cfca1b694daac44d64a873a1c3b268eca93fda6a59f8f -size 602322 diff --git a/kimi - 23-08-26/preview/epoch_044.png b/kimi - 23-08-26/preview/epoch_044.png deleted file mode 100644 index 6d6120e0eb3e2a6a9a94e097a2bb0419ef406931..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_044.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d28ddf51f623352eb998807b8760ba5bf1aee0d590c00decaf24392a18ad91dd -size 324735 diff --git a/kimi - 23-08-26/preview/epoch_046.png b/kimi - 23-08-26/preview/epoch_046.png deleted file mode 100644 index 4a628ddc610bbb446cc0d57daec31b146f7a50a3..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_046.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0cea885e6b12894b1cb18e372db62478157fbd227bf2271fe8ebcc3ca15cded6 -size 483759 diff --git a/kimi - 23-08-26/preview/epoch_048.png b/kimi - 23-08-26/preview/epoch_048.png deleted file mode 100644 index 6568bd9156a023e8036e8af168524c3c59983d51..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_048.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ad528d015cbb8a1fad7d0a55a688bfabb67461d8afd02cef369469e297069747 -size 212239 diff --git a/kimi - 23-08-26/preview/epoch_050.png b/kimi - 23-08-26/preview/epoch_050.png deleted file mode 100644 index 6c39e4b57d5836956d4fc2dba4d096162cda751f..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_050.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:bbbf90069512ac66353b072395180048526d153e5122cbc5ee036f81f280a0a7 -size 350986 diff --git a/kimi - 23-08-26/preview/epoch_052.png b/kimi - 23-08-26/preview/epoch_052.png deleted file mode 100644 index aed86feb57381111affb2a812b0bacaffc852414..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_052.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f18602658d38b5c239e8e31b365920e969a9b60ce079e415bc436ac78cb220ae -size 457118 diff --git a/kimi - 23-08-26/preview/epoch_054.png b/kimi - 23-08-26/preview/epoch_054.png deleted file mode 100644 index 1926b69f2593d2e20ef5a510bff5f238651faf54..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_054.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:61bd294c235fb811f0792b11f10a92a5e591b91746aa442b264643e9a537bb44 -size 388920 diff --git a/kimi - 23-08-26/preview/epoch_056.png b/kimi - 23-08-26/preview/epoch_056.png deleted file mode 100644 index bac129c06b215c9ba491b6274b57b2c3d85ff2be..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_056.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b3d9356335f1c65cacc0b3977b6e3d7b470536dc5048bbdbc2cb1c2f133cf8e8 -size 353904 diff --git a/kimi - 23-08-26/preview/epoch_058.png b/kimi - 23-08-26/preview/epoch_058.png deleted file mode 100644 index f5a87b1f4d84f6ea0ec8c99274f0de1843571229..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_058.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:86d96e08bf7b0004fee1887b5001d0e30b82ab76e76d155d0df665fe37228504 -size 401794 diff --git a/kimi - 23-08-26/preview/epoch_060.png b/kimi - 23-08-26/preview/epoch_060.png deleted file mode 100644 index 3cdee034051d0f681c2bd347511b946f943c3d83..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_060.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:db324aebe6ec036c71ebab5a5fff54ff5fed3f4af1f512d2f648d2f725abf862 -size 495271 diff --git a/kimi - 23-08-26/preview/epoch_062.png b/kimi - 23-08-26/preview/epoch_062.png deleted file mode 100644 index e41af0b5e7c899f1c490b5d8b0a9447d442c6e52..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_062.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9090be94cf235aeb6743b816a6f69e2c43be6a31bd050b9e8c05b33bdb1c0532 -size 551855 diff --git a/kimi - 23-08-26/preview/epoch_064.png b/kimi - 23-08-26/preview/epoch_064.png deleted file mode 100644 index c39124f0d4d4c72da67d6938234a9a03d8893f0a..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_064.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7d542e9d7412913456275bba581f36a0fbe0b9b22e88ac682fe07685d9d0a23f -size 572958 diff --git a/kimi - 23-08-26/preview/epoch_066.png b/kimi - 23-08-26/preview/epoch_066.png deleted file mode 100644 index e347e9587a1d5448c875d76e2fe3506d84d821ba..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_066.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:20d1e21046332e599aa77761a6fb55bba548f5ee162a372aeb6d0439255c993c -size 396208 diff --git a/kimi - 23-08-26/preview/epoch_068.png b/kimi - 23-08-26/preview/epoch_068.png deleted file mode 100644 index 296e557af7d52782e5a8c402ec662a0e020de327..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_068.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:af650416204fc7180785df7dd4ec870bb02c4409c30aa66ddd67028ac6999a59 -size 508275 diff --git a/kimi - 23-08-26/preview/epoch_070.png b/kimi - 23-08-26/preview/epoch_070.png deleted file mode 100644 index 35f18a3a4e52bc745a8bb2f8fb41c6802ce9dd0e..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/preview/epoch_070.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4d5ca8043114ed7223e4e8859c4d1dd661f87f1f69f7aef65a8a62ea90241501 -size 445213 diff --git a/kimi - 23-08-26/training_log.csv b/kimi - 23-08-26/training_log.csv deleted file mode 100644 index ff8f3ee477aeae1318a1177cd1403e1980b337bf..0000000000000000000000000000000000000000 --- a/kimi - 23-08-26/training_log.csv +++ /dev/null @@ -1,72 +0,0 @@ -epoch,phase,phase_ep,lr_decoder,lr_backbone,train_loss,val_loss,grad_norm,n_skip,n_spike,biou,biou_d2,pa,iou,best_biou,fi_biou,fi_pa,fi_iou,fi_sad,fi_mse,gap_crop_full,loss_db,loss_lovasz,loss_mae,loss_ssim,loss_grad,loss_bnd,loss_biou,loss_struct,loss_ero,loss_conf,adapt_w_bnd,minutes -1,1,0,1.00e-04,1.00e-04,0.5372,0.1569,11.1762,0,0,53.0882,42.3626,94.396,91.7195,53.0882,56.866,98.6181,97.2663,59.9926,0.014792,-3.7778,0.1259,0.4189,0.0,0.1148,0.0,0.0,0.9961,0.0,0.0,0.0,0.0,34.4 -2,1,1,1.00e-04,1.00e-04,0.3465,0.1356,4.0848,0,0,58.7261,48.9419,95.1979,92.7129,58.7261,69.4528,99.0619,98.3356,29.4547,0.007745,-10.7267,0.0715,0.256,0.0,0.0632,0.0,0.0,0.7661,0.0,0.0,0.0,0.0,27.8 -3,1,2,1.00e-04,9.90e-05,0.3043,0.1285,3.1486,0,0,63.159,54.1046,95.7682,93.4842,63.159,74.237,99.1822,98.5409,23.2716,0.006658,-11.078,0.0618,0.2225,0.0,0.0546,0.0,0.0,0.6969,0.0,0.0,0.0,0.0,28.3 -4,1,3,9.90e-05,9.62e-05,0.2965,0.1256,2.6189,0,0,65.7496,57.287,96.1567,94.013,65.7496,76.6204,99.2178,98.5988,20.4016,0.006231,-10.8708,0.0618,0.2215,0.0,0.0559,0.0,0.0,0.6682,0.0,0.0,0.0,0.0,28.5 -5,1,4,9.62e-05,9.17e-05,0.2907,0.1252,2.2858,0,0,67.0149,58.853,96.2516,94.1411,67.0149,77.3571,99.2289,98.6061,20.3546,0.006218,-10.3422,0.0611,0.2097,0.0,0.0537,0.0,0.0,0.6731,0.0,0.0,0.0,0.0,28.2 -6,1,5,9.17e-05,8.55e-05,0.2955,0.1239,2.3453,0,0,68.1453,60.2132,96.3736,94.2786,68.1453,78.7115,99.2398,98.622,19.8168,0.006277,-10.5662,0.0639,0.2171,0.0,0.0572,0.0,0.0,0.6481,0.0,0.0,0.0,0.0,28.4 -7,1,6,8.55e-05,7.80e-05,0.2855,0.1206,2.0525,0,0,68.6257,60.7292,96.4243,94.3027,68.6257,79.1384,99.251,98.6467,19.5308,0.006324,-10.5127,0.0598,0.2088,0.0,0.0569,0.0,0.0,0.6592,0.0,0.0,0.0,0.0,28.3 -8,1,7,7.80e-05,6.94e-05,0.2862,0.1178,2.1482,0,0,68.92,61.1029,96.4639,94.343,68.92,79.5387,99.2392,98.6278,18.9474,0.006348,-10.6188,0.062,0.212,0.0,0.0536,0.0,0.0,0.6421,0.0,0.0,0.0,0.0,28.2 -9,1,8,6.94e-05,6.02e-05,0.2569,0.117,1.7361,0,0,69.3925,61.6414,96.4629,94.3562,69.3925,80.1504,99.2621,98.6674,17.812,0.006147,-10.7579,0.0519,0.1837,0.0,0.0504,0.0,0.0,0.6159,0.0,0.0,0.0,0.0,28.4 -10,1,9,6.02e-05,5.05e-05,0.2706,0.1139,1.7038,0,0,69.5298,61.7264,96.415,94.3821,69.5298,80.4185,99.27,98.6817,18.1486,0.006024,-10.8887,0.0569,0.1977,0.0,0.0507,0.0,0.0,0.6251,0.0,0.0,0.0,0.0,28.3 -11,1,10,5.05e-05,4.08e-05,0.2521,0.1125,1.5811,0,0,69.8105,62.1256,96.4416,94.484,69.8105,80.695,99.2704,98.6832,17.5451,0.005944,-10.8845,0.0515,0.1771,0.0,0.0499,0.0,0.0,0.5882,0.0,0.0,0.0,0.0,28.3 -12,1,11,4.08e-05,3.16e-05,0.2478,0.1094,1.6001,0,0,70.0531,62.471,96.5116,94.59,70.0531,81.0994,99.2706,98.6831,16.9891,0.005868,-11.0464,0.0504,0.1742,0.0,0.0463,0.0,0.0,0.5943,0.0,0.0,0.0,0.0,28.7 -13,1,12,3.16e-05,2.30e-05,0.2642,0.1071,2.0183,0,0,70.2878,62.7671,96.5605,94.6429,70.2878,81.4231,99.2846,98.7093,16.9236,0.005761,-11.1353,0.0562,0.1874,0.0,0.05,0.0,0.0,0.6015,0.0,0.0,0.0,0.0,28.4 -14,1,13,2.30e-05,1.55e-05,0.2533,0.1056,1.5792,0,0,70.495,62.9856,96.6278,94.7161,70.495,81.4705,99.2969,98.7305,17.3133,0.005679,-10.9755,0.0522,0.1785,0.0,0.0502,0.0,0.0,0.5857,0.0,0.0,0.0,0.0,28.3 -15,1,14,1.55e-05,9.34e-06,0.2525,0.1044,1.5738,0,0,70.5522,63.0335,96.6998,94.8334,70.5522,81.4864,99.326,98.7799,17.2415,0.005531,-10.9342,0.052,0.178,0.0,0.05,0.0,0.0,0.5825,0.0,0.0,0.0,0.0,28.3 -16,1,15,9.34e-06,4.77e-06,0.2308,0.1048,1.4715,0,0,70.749,63.2864,96.7531,94.8839,70.749,81.6669,99.3479,98.82,17.0433,0.005466,-10.9179,0.0455,0.1585,0.0,0.0434,0.0,0.0,0.5572,0.0,0.0,0.0,0.0,28.3 -17,1,16,4.77e-06,1.95e-06,0.2343,0.105,1.3813,0,0,70.8708,63.4236,96.7663,94.9085,70.8708,81.7868,99.343,98.8094,17.0479,0.005434,-10.916,0.0461,0.1591,0.0,0.0437,0.0,0.0,0.5788,0.0,0.0,0.0,0.0,28.4 -18,1,17,1.95e-06,3.50e-06,0.2392,0.105,1.6804,0,0,70.8163,63.3719,96.7691,94.9206,70.8708,81.8197,99.3573,98.8312,16.7039,0.005375,-11.0034,0.0487,0.1639,0.0,0.0444,0.0,0.0,0.5607,0.0,0.0,0.0,0.0,28.3 -19,2,0,7.00e-05,7.00e-06,0.2649,0.1051,4.5668,0,0,71.104,63.7436,96.8076,94.9605,71.104,82.0154,99.3928,98.8893,16.0436,0.005172,-10.9113,0.0502,0.1793,0.0,0.0473,0.0,0.0,0.5584,0.2152,0.0,0.0,0.0,37.5 -20,2,1,7.00e-05,1.05e-05,0.2587,0.1035,4.306,0,0,71.5035,64.1608,96.8203,95.016,71.5035,81.9419,99.3845,98.8762,15.6093,0.005151,-10.4384,0.0489,0.1706,0.0,0.0455,0.0,0.0,0.5555,0.2101,0.0,0.0,0.0,37.4 -21,2,2,7.00e-05,1.40e-05,0.2541,0.1017,4.8015,0,0,72.1065,64.8016,96.8594,95.0601,72.1065,81.9306,99.4279,98.9534,14.9735,0.005004,-9.8241,0.048,0.1692,0.0,0.043,0.0,0.0,0.5498,0.2057,0.0,0.0,0.0,37.3 -22,2,3,7.00e-05,1.75e-05,0.2579,0.1002,4.5661,0,0,72.9618,65.6631,96.9065,95.1144,72.9618,82.5902,99.4885,99.0619,14.0048,0.004749,-9.6284,0.0502,0.1746,0.0,0.0441,0.0,0.0,0.5364,0.206,0.0,0.0,0.0,37.4 -23,2,4,7.00e-05,1.75e-05,0.2487,0.0995,4.6145,0,0,73.7044,66.4109,97.0124,95.1745,73.7044,83.3189,99.5232,99.1299,13.1119,0.00446,-9.6145,0.0481,0.1608,0.0,0.0414,0.0,0.0,0.5332,0.1978,0.0,0.0,0.0,37.2 -24,2,5,7.00e-05,1.75e-05,0.2251,0.0971,3.7698,0,0,74.4042,67.1829,97.0992,95.2619,74.4042,83.3627,99.5336,99.1516,12.2339,0.004272,-8.9585,0.041,0.1427,0.0,0.0386,0.0,0.0,0.5081,0.1815,0.0,0.0,0.0,37.4 -25,2,6,7.00e-05,1.75e-05,0.2065,0.0941,3.3601,0,0,74.982,67.7791,97.1959,95.3777,74.982,83.3997,99.5286,99.1454,11.4592,0.004161,-8.4178,0.0376,0.1315,0.0,0.0322,0.0,0.0,0.4791,0.1617,0.0,0.0,0.0,37.3 -26,2,7,7.00e-05,1.75e-05,0.2129,0.0914,3.7874,0,0,75.529,68.3689,97.3341,95.5249,75.529,83.5196,99.505,99.1074,10.892,0.004117,-7.9905,0.0394,0.1395,0.0,0.0347,0.0,0.0,0.4703,0.1662,0.0,0.0,0.0,37.3 -27,2,8,7.00e-05,1.75e-05,0.2028,0.091,4.216,0,0,75.9776,68.815,97.4212,95.6243,75.9776,83.857,99.48,99.0673,13.0228,0.004317,-7.8794,0.0361,0.1267,0.0,0.0329,0.0,0.0,0.4745,0.1612,0.0,0.0,0.0,37.3 -28,2,9,6.98e-05,1.73e-05,0.2075,0.0925,3.7338,0,0,76.0081,68.903,97.4242,95.5724,76.0081,84.0023,99.4747,99.0589,13.2299,0.004435,-7.9942,0.0387,0.1322,0.0,0.0325,0.0,0.0,0.4618,0.1614,0.0,0.0,0.0,37.3 -29,2,10,6.93e-05,1.71e-05,0.2117,0.0922,4.8712,0,0,76.2913,69.2282,96.9894,95.1268,76.2913,84.2277,99.4818,99.071,11.6025,0.00427,-7.9364,0.0381,0.1357,0.0,0.0348,0.0,0.0,0.4867,0.1698,0.0,0.0,0.0,37.3 -30,2,11,6.85e-05,1.69e-05,0.2103,0.0902,3.8454,0,0,76.4326,69.4235,96.8571,95.2056,76.4326,84.1848,99.4786,99.0666,11.6435,0.004234,-7.7522,0.038,0.1343,0.0,0.0336,0.0,0.0,0.4866,0.1671,0.0,0.0,0.0,37.4 -31,2,12,6.74e-05,1.65e-05,0.1975,0.0887,3.7745,0,0,76.8322,69.8578,96.881,95.2766,76.8322,84.5679,99.4961,99.0976,11.3562,0.004179,-7.7357,0.0346,0.1251,0.0,0.0326,0.0,0.0,0.4641,0.1583,0.0,0.0,0.0,37.3 -32,2,13,6.59e-05,1.61e-05,0.2038,0.0873,3.3565,0,0,77.2897,70.3029,96.9416,95.3887,77.2897,84.7149,99.4998,99.104,11.1636,0.004163,-7.4251,0.0365,0.1282,0.0,0.0321,0.0,0.0,0.4781,0.1632,0.0,0.0,0.0,37.3 -33,2,14,6.42e-05,1.56e-05,0.1974,0.0848,4.2405,0,0,77.5442,70.6074,97.0229,95.4839,77.5442,84.8866,99.5013,99.1072,10.9314,0.004156,-7.3424,0.0357,0.1277,0.0,0.0317,0.0,0.0,0.4523,0.1531,0.0,0.0,0.0,37.2 -34,2,15,6.21e-05,1.50e-05,0.1801,0.0844,3.2498,0,0,77.8473,70.9286,96.9848,95.3847,77.8473,84.9365,99.5028,99.1111,10.7458,0.004137,-7.0892,0.0307,0.1074,0.0,0.0298,0.0,0.0,0.4363,0.1407,0.0,0.0,0.0,37.3 -35,2,16,5.99e-05,1.44e-05,0.1726,0.0836,3.3618,0,0,78.1456,71.2402,97.1418,95.4565,78.1456,84.9788,99.503,99.1118,10.9566,0.004144,-6.8332,0.0289,0.1053,0.0,0.0263,0.0,0.0,0.4294,0.1359,0.0,0.0,0.0,37.3 -36,2,17,5.73e-05,1.38e-05,0.1744,0.0829,3.4668,0,0,78.3228,71.4379,97.2664,95.5545,78.3228,85.0307,99.504,99.1147,11.0378,0.00414,-6.708,0.0288,0.103,0.0,0.0275,0.0,0.0,0.4402,0.1385,0.0,0.0,0.0,37.3 -37,2,18,5.46e-05,1.31e-05,0.1738,0.0817,3.4634,0,0,78.4763,71.5942,97.4719,95.7002,78.4763,85.0446,99.5039,99.1146,11.2393,0.004179,-6.5683,0.0292,0.106,0.0,0.0276,0.0,0.0,0.4304,0.1358,0.0,0.0,0.0,37.3 -38,2,19,5.17e-05,1.23e-05,0.1813,0.0821,3.1286,0,0,78.4416,71.5909,97.1604,95.4943,78.4763,85.1081,99.5052,99.1176,10.5996,0.004126,-6.6666,0.0316,0.1118,0.0,0.0297,0.0,0.0,0.4204,0.1441,0.0,0.0,0.0,37.3 -39,2,20,4.86e-05,1.15e-05,0.1579,0.0819,2.7184,0,0,78.8023,71.9742,97.189,95.5014,78.8023,85.1763,99.506,99.1192,10.4674,0.004122,-6.3739,0.0267,0.0911,0.0,0.0235,0.0,0.0,0.3924,0.1196,0.0,0.0,0.0,39.5 -40,2,21,4.54e-05,1.07e-05,0.1516,0.0824,3.2208,0,0,78.955,72.1595,97.3219,95.5818,78.955,85.2398,99.5072,99.121,10.2661,0.004112,-6.2847,0.0249,0.0872,0.0,0.0221,0.0,0.0,0.3822,0.1169,0.0,0.0,0.0,37.4 -41,2,22,4.21e-05,9.92e-06,0.1561,0.0829,2.9188,0,0,79.1362,72.3773,97.1738,95.5204,79.1362,85.3329,99.509,99.1247,10.1127,0.004095,-6.1967,0.0255,0.0916,0.0,0.0239,0.0,0.0,0.3907,0.1212,0.0,0.0,0.0,37.5 -42,2,23,3.87e-05,9.10e-06,0.1577,0.0828,2.7842,0,0,79.411,72.6844,97.1817,95.5515,79.411,85.4453,99.51,99.1262,9.956,0.004069,-6.0343,0.0261,0.0905,0.0,0.0236,0.0,0.0,0.3939,0.1226,0.0,0.0,0.0,37.6 -43,2,24,3.53e-05,8.28e-06,0.1577,0.0826,3.0969,0,0,79.6863,73.0025,97.1492,95.5801,79.6863,85.4922,99.5105,99.1268,9.9577,0.004043,-5.806,0.0257,0.0914,0.0,0.0248,0.0,0.0,0.3973,0.1228,0.0,0.0,0.0,37.6 -44,2,25,3.20e-05,7.46e-06,0.1398,0.0831,2.9031,0,0,79.8768,73.2215,97.1787,95.6125,79.8768,85.5443,99.5117,99.1292,9.8567,0.004036,-5.6675,0.0211,0.0795,0.0,0.0204,0.0,0.0,0.3766,0.1087,0.0,0.0,0.0,37.4 -45,2,26,2.86e-05,6.66e-06,0.1422,0.0834,2.5132,0,0,80.2003,73.5887,97.1818,95.6242,80.2003,85.5919,99.513,99.1314,9.6313,0.003987,-5.3916,0.0218,0.08,0.0,0.0204,0.0,0.0,0.385,0.1083,0.0,0.0,0.0,37.6 -46,2,27,2.53e-05,5.89e-06,0.1436,0.0842,3.2394,0,0,80.5542,73.9592,97.2052,95.7973,80.5542,85.6644,99.5151,99.1351,9.3935,0.00393,-5.1102,0.0221,0.0803,0.0,0.0218,0.0,0.0,0.3818,0.1108,0.0,0.0,0.0,38.5 -47,2,28,2.21e-05,5.14e-06,0.1294,0.0854,2.969,0,0,80.7335,74.1732,97.219,95.8002,80.7335,85.7691,99.518,99.1404,9.162,0.003821,-5.0356,0.0183,0.0711,0.0,0.0189,0.0,0.0,0.3648,0.0993,0.0,0.0,0.0,38.1 -48,2,29,1.90e-05,4.43e-06,0.1493,0.0862,2.9094,0,0,80.9065,74.3548,97.2473,95.8074,80.9065,85.8439,99.5195,99.144,9.0602,0.003799,-4.9374,0.024,0.0841,0.0,0.0224,0.0,0.0,0.3856,0.1145,0.0,0.0,0.0,38.1 -49,2,30,1.61e-05,3.77e-06,0.1415,0.0863,2.4852,0,0,81.0025,74.4803,97.2761,95.8421,81.0025,85.9917,99.5217,99.1481,9.0037,0.003761,-4.9892,0.0219,0.0786,0.0,0.0209,0.0,0.0,0.3731,0.1098,0.0,0.0,0.0,37.9 -50,2,31,1.34e-05,3.16e-06,0.1336,0.0867,2.2857,0,0,81.0764,74.5467,97.2923,95.8411,81.0764,86.0579,99.5237,99.1514,8.9147,0.003702,-4.9816,0.0203,0.0712,0.0,0.0188,0.0,0.0,0.3565,0.1039,0.0,0.0,0.0,37.5 -51,2,32,1.08e-05,2.61e-06,0.1385,0.0862,2.4542,0,0,81.3541,74.8516,97.3145,96.0256,81.3541,86.1215,99.526,99.1557,8.87,0.003661,-4.7673,0.0206,0.0722,0.0,0.0266,0.0,0.0,0.3579,0.1042,0.0,0.0,0.0,40.6 -52,2,33,8.57e-06,2.12e-06,0.1296,0.0859,2.0425,0,0,81.4174,74.9228,97.3605,96.0401,81.4174,86.2314,99.5265,99.1568,8.8074,0.003651,-4.8139,0.0178,0.0676,0.0,0.026,0.0,0.0,0.3525,0.0957,0.0,0.0,0.0,40.1 -53,2,34,6.54e-06,1.69e-06,0.1321,0.0851,2.3806,0,0,81.3656,74.8852,97.3972,96.0605,81.4174,86.2597,99.5267,99.1575,8.7788,0.00365,-4.8941,0.0184,0.0686,0.0,0.0279,0.0,0.0,0.348,0.099,0.0,0.0,0.0,40.1 -54,2,35,4.79e-06,1.34e-06,0.1352,0.0842,2.1949,0,0,81.4155,74.9498,97.4267,96.0841,81.4174,86.235,99.5265,99.157,8.8057,0.003661,-4.8195,0.0189,0.069,0.0,0.0301,0.0,0.0,0.3558,0.1001,0.0,0.0,0.0,39.9 -55,2,36,3.34e-06,1.06e-06,0.1452,0.0835,2.4475,0,0,81.3792,74.9169,97.4412,96.0994,81.4174,86.2288,99.527,99.158,8.8235,0.003653,-4.8496,0.0224,0.0795,0.0,0.0285,0.0,0.0,0.3662,0.108,0.0,0.0,0.0,39.7 -56,2,37,2.19e-06,8.61e-07,0.1412,0.0827,2.4377,0,0,81.5022,75.0385,97.4495,96.1084,81.5022,86.2327,99.5272,99.1583,8.8674,0.003657,-4.7306,0.0202,0.0745,0.0,0.0306,0.0,0.0,0.3743,0.1036,0.0,0.0,0.0,40.3 -57,2,38,1.37e-06,7.40e-07,0.1375,0.0823,2.4977,0,0,81.5882,75.1235,97.4565,96.1174,81.5882,86.2363,99.5273,99.1586,8.8998,0.003661,-4.6481,0.0198,0.0734,0.0,0.0295,0.0,0.0,0.3557,0.1019,0.0,0.0,0.0,39.7 -58,2,39,8.67e-07,3.00e-06,0.1478,0.0823,2.6825,0,0,81.5862,75.1344,97.4542,96.117,81.5882,86.21,99.5271,99.1585,8.9116,0.00367,-4.6238,0.0227,0.0839,0.0,0.0299,0.0,0.0,0.3641,0.1118,0.0,0.0,0.0,40.0 -59,3,0,3.00e-05,3.00e-06,0.1074,0.0824,1.9997,0,0,81.581,75.128,97.4611,96.1245,81.5882,86.206,99.5277,99.1593,8.8403,0.003647,-4.625,0.0196,0.0696,0.0,0.0236,0.0,0.0,0.3307,0.0967,0.0,0.0,0.0,39.9 -60,3,1,3.00e-05,3.00e-06,0.1182,0.0827,2.1732,0,0,81.7556,75.3305,97.4758,96.1476,81.7556,86.2012,99.5279,99.1602,8.8021,0.003643,-4.4456,0.023,0.082,0.0,0.0249,0.0,0.0,0.3478,0.1076,0.0,0.0,0.0,39.8 -61,3,2,3.00e-05,3.00e-06,0.1204,0.0824,2.11,0,0,81.7963,75.4001,97.4718,96.1469,81.7963,86.1453,99.5321,99.1674,8.8336,0.003635,-4.349,0.0219,0.0793,0.0,0.0307,0.0,0.0,0.3615,0.1065,0.0,0.0,0.0,39.9 -62,3,3,3.00e-05,3.00e-06,0.1126,0.0833,2.2329,0,0,81.8737,75.4979,97.4903,96.0055,81.8737,86.0665,99.5444,99.1865,8.7075,0.00359,-4.1928,0.0199,0.0722,0.0,0.028,0.0,0.0,0.3465,0.1006,0.0,0.0,0.0,39.8 -63,3,4,3.00e-05,3.00e-06,0.1107,0.0856,2.9213,0,0,81.7052,75.3801,97.4925,96.0077,81.8737,86.1189,99.5605,99.2125,8.5402,0.003546,-4.4137,0.0189,0.0731,0.0,0.0278,0.0,0.0,0.3465,0.0983,0.0,0.0,0.0,39.7 -64,3,5,3.00e-05,3.00e-06,0.1138,0.0862,2.3367,0,0,81.6798,75.3875,97.4992,96.013,81.8737,86.2493,99.5632,99.2161,8.4871,0.003532,-4.5696,0.0193,0.076,0.0,0.0315,0.0,0.0,0.3478,0.0994,0.0,0.0,0.0,39.7 -65,3,6,3.00e-05,3.00e-06,0.1119,0.0868,2.4631,0,0,81.7404,75.4613,97.4937,96.0044,81.8737,86.3205,99.5703,99.2278,8.4533,0.003504,-4.5801,0.0201,0.0759,0.0,0.0276,0.0,0.0,0.3396,0.0988,0.0,0.0,0.0,39.8 -66,3,7,3.00e-05,3.00e-06,0.1106,0.0884,2.3672,0,0,81.658,75.3945,97.4869,95.9917,81.8737,86.2808,99.5632,99.2162,8.5017,0.003541,-4.6228,0.0193,0.0723,0.0,0.0247,0.0,0.0,0.352,0.1005,0.0,0.0,0.0,39.7 -67,3,8,3.00e-05,3.00e-06,0.1074,0.0892,2.1717,0,0,81.6982,75.4648,97.4899,95.994,81.8737,86.3104,99.5405,99.1814,8.5875,0.003599,-4.6122,0.0186,0.0692,0.0,0.0253,0.0,0.0,0.343,0.0949,0.0,0.0,0.0,40.5 -68,3,9,3.00e-05,3.00e-06,0.1099,0.0881,2.2229,0,0,81.4252,75.2023,97.4979,96.0055,81.8737,86.6517,99.5328,99.1698,8.7156,0.003663,-5.2265,0.0197,0.0683,0.0,0.0256,0.0,0.0,0.3457,0.0972,0.0,0.0,0.0,40.0 -69,3,10,3.00e-05,3.00e-06,0.1092,0.087,2.2497,0,0,81.4951,75.2916,97.5041,96.0155,81.8737,86.6807,99.5332,99.1714,8.7124,0.003676,-5.1857,0.0189,0.0685,0.0,0.0265,0.0,0.0,0.3501,0.0949,0.0,0.0,0.0,39.8 -70,3,11,3.00e-05,3.00e-06,0.1055,0.0871,2.2829,0,0,81.6424,75.436,97.5351,96.0598,81.8737,86.7405,99.5339,99.1736,8.6429,0.003667,-5.0981,0.0188,0.0673,0.0,0.0222,0.0,0.0,0.3363,0.0958,0.0,0.0,0.0,39.9 -71,3,12,3.00e-05,3.00e-06,0.1246,0.0856,2.4956,0,0,81.6999,75.5255,97.5579,96.0967,81.8737,86.7942,99.5355,99.1774,8.6751,0.003676,-5.0943,0.0236,0.0807,0.0,0.032,0.0,0.0,0.3709,0.1066,0.0,0.0,0.0,39.7