Chucks90's picture
download
raw
17.2 kB
"""J2 CountNet-µL training + decision-level evaluation (Addendum J, locked sha256 e6afa2c1…).
Data: malaria_j2_prep_job.py output (images/ at long side 1536, manifest.csv, points.csv; class 0 parasite, 1 WBC).
Splits (no slide IDs in the release, so leakage is controlled with PSEUDO-SLIDES):
- pseudo-slide = (EXIF device, capture-time cluster), where a new cluster starts after a GAP_MIN-minute gap. Images
without EXIF time are their own group.
- SPLIT=group: 70/15/15 by pseudo-slide (seeded). SPLIT=device: train/val on every device except HOLDOUT_DEVICE,
test on it (acquisition-shift test, if EXIF shows >= 2 devices).
Model selection on val count MAE. Test outputs per image: true/pred parasite and WBC counts, density per µL
(8000 x P/W), and decisions:
- positive: pred parasite count >= T_POS, T_POS calibrated on val for 95% specificity on zero-parasite images;
- high density: >= HIGH_UL parasites/µL (default 100,000/µL, a commonly used hyperparasitaemia cut-off; declared, not tuned).
Also single-thread CPU latency for one full image (edge proxy). Writes OUT/<tag>_per_image.csv and OUT/<tag>.json.
Env: DATA, OUT, SPLIT, HOLDOUT_DEVICE, SEED, EPOCHS (30), BS (8), CROP (768), LR (1e-3), GAP_MIN (5), HIGH_UL.
"""
from __future__ import annotations
import json
import math
import os
import sys
import time
from pathlib import Path
import numpy as np
import pandas as pd
import torch
from PIL import Image
sys.path.insert(0, str(Path(__file__).resolve().parent))
from countnet import CountNet, density_target, loss_fn, peak_target, per_ul # noqa: E402
E = os.environ.get
DATA, OUT = Path(E("DATA", "data/ghana_thick")), Path(E("OUT", "results/j2")); OUT.mkdir(parents=True, exist_ok=True)
SPLIT, HOLD, SEED = E("SPLIT", "group"), E("HOLDOUT_DEVICE", ""), int(E("SEED", "0"))
EPOCHS, BS, CROP, LR = int(E("EPOCHS", "30")), int(E("BS", "8")), int(E("CROP", "768")), float(E("LR", "1e-3"))
GAP_MIN, HIGH_UL = float(E("GAP_MIN", "5")), float(E("HIGH_UL", "100000"))
LIMIT = int(E("LIMIT", "0"))
# J2b (diagnosis 2026-10-16, results/J2_V2_RESULTS_2026-10-16.md): V=j2b switches every fix on; each is also a flag.
V = E("V", "v2")
J2C = V == "j2c" # J2c (pre-registered in results/J2_V2_RESULTS_2026-10-16.md): peak-head WBC + weight averaging
J2B = V in ("j2b", "j2c") # J2c keeps every J2b fix except the (no-effect) WBC mask, which it overrides below
ACT = E("ACT", "relu" if J2B else "softplus") # relu: no background mass leak
LOSS = E("LOSS", "j2c" if J2C else ("balanced" if J2B else "v2"))
WBC_HEAD = "peak" if J2C else "density"
SWA_FRAC = float(E("SWA_FRAC", "0.25" if J2C else "0")) # final model = average of EMA snapshots over the last 25% epochs # class-balanced pixel + log-count loss
VISIBLE = E("VISIBLE", "1" if J2B else "0") == "1" # crop-edge cells carry their visible mass
WBC_MASK = E("WBC_MASK", "1" if (J2B and not J2C) else "0") == "1" # parasites>0 & 0 WBC labels => WBC labels missing
SELECT = E("SELECT", "logdens" if J2B else "par_mae") # checkpoint selection metric on val
EMA = float(E("EMA", "0.9995" if J2C else ("0.999" if J2B else "0")))
if J2B and "LR" not in os.environ:
LR = 3e-4
DEV = torch.device("cuda" if torch.cuda.is_available() else "cpu")
MEAN, STD = np.array([0.485, 0.456, 0.406], np.float32), np.array([0.229, 0.224, 0.225], np.float32)
def log(m):
print(f"[j2 {SPLIT} s{SEED}] {m}", flush=True)
def pseudo_slides(M):
M = M.copy()
M["device"] = (M.exif_make.fillna("") + " " + M.exif_model.fillna("")).str.strip().replace("", "unknown")
t = pd.to_datetime(M.exif_datetime, format="%Y:%m:%d %H:%M:%S", errors="coerce")
M["t"] = t
gid, groups = 0, {}
for dev, g in M.sort_values("t").groupby("device", sort=False):
last = None
for i, r in g.iterrows():
if pd.isna(r.t):
groups[i] = f"{dev}#solo{i}"; continue
if last is None or (r.t - last).total_seconds() > GAP_MIN * 60:
gid += 1
groups[i] = f"{dev}#{gid}"; last = r.t
M["group"] = pd.Series(groups)
return M
def make_split(M):
rng = np.random.default_rng(SEED)
if SPLIT == "device":
te = M[M.device == HOLD]; rest = M[M.device != HOLD]
assert len(te) and len(rest), f"holdout device {HOLD!r} not found or is everything"
gs = rest.group.unique(); rng.shuffle(gs); va_g = set(gs[: max(1, int(0.15 * len(gs)))])
return rest[~rest.group.isin(va_g)], rest[rest.group.isin(va_g)], te
gs = M.group.unique(); rng.shuffle(gs)
n = len(gs); te_g, va_g = set(gs[: int(0.15 * n)]), set(gs[int(0.15 * n): int(0.30 * n)])
return M[~M.group.isin(te_g | va_g)], M[M.group.isin(va_g)], M[M.group.isin(te_g)]
def load(name):
return np.asarray(Image.open(DATA / "images" / name).convert("RGB"), np.float32) / 255.0
def to_tensor(a):
return torch.from_numpy(((a - MEAN) / STD).transpose(2, 0, 1).copy())
class Train(torch.utils.data.Dataset):
def __init__(self, rows, P):
self.rows, self.P = rows.reset_index(drop=True), P
# 11% of Samsung images (vs 1% LG) have parasites but zero WBC boxes; a thick-smear field nearly always shows
# WBC and visual audit found unlabelled WBC, so WBC labels are treated as MISSING there, not as zero.
self.wbc_missing = ((self.rows.n_wbc == 0) & (self.rows.n_parasite > 0)).to_numpy()
def __len__(self):
return len(self.rows)
def __getitem__(self, i):
r = self.rows.iloc[i]; a = load(r.image); h, w = a.shape[:2]
rng = np.random.default_rng()
y0, x0 = rng.integers(0, max(1, h - CROP + 1)), rng.integers(0, max(1, w - CROP + 1))
a = a[y0:y0 + CROP, x0:x0 + CROP]
p = self.P.get(r.image, np.zeros((0, 5), np.float32)).copy()
if len(p):
p[:, 1] -= x0; p[:, 2] -= y0
m = 1.5 * np.maximum(p[:, 3], p[:, 4]) if VISIBLE else 0.0 # keep centres just outside (visible mass)
p = p[(p[:, 1] >= -m) & (p[:, 1] < a.shape[1] + m) & (p[:, 2] >= -m) & (p[:, 2] < a.shape[0] + m)]
if rng.random() < 0.5:
a = a[:, ::-1]; p[:, 1] = a.shape[1] - 1 - p[:, 1]
if rng.random() < 0.5:
a = a[::-1]; p[:, 2] = a.shape[0] - 1 - p[:, 2]
a = np.clip(a * rng.uniform(0.85, 1.15) + rng.uniform(-0.05, 0.05), 0, 1) # mild photometric jitter
ph, pw = CROP - a.shape[0], CROP - a.shape[1]
if ph > 0 or pw > 0:
a = np.pad(a, ((0, max(ph, 0)), (0, max(pw, 0)), (0, 0)))
t = density_target([tuple(q) for q in p], CROP, CROP, visible=VISIBLE)
if WBC_HEAD == "peak":
t[1] = peak_target([tuple(q) for q in p], CROP, CROP, cls=1)
cm = torch.tensor([1.0, 0.0 if (WBC_MASK and self.wbc_missing[i]) else 1.0])
return to_tensor(np.ascontiguousarray(a)), torch.from_numpy(t), cm
@torch.no_grad()
def predict(model, rows, taus=None):
"""taus (peak head only): also return WBC counts at each candidate threshold, for validation calibration."""
model.eval(); out = []
for r in rows.itertuples():
x = to_tensor(load(r.image))[None].to(DEV)
with torch.autocast("cuda", dtype=torch.float16, enabled=DEV.type == "cuda"):
d = model(x).float()
c = model.counts(d)[0].cpu().numpy()
rec = [r.image, float(c[0]), float(c[1])]
if taus is not None:
rec += [float(model.counts(d, tau=t)[0, 1]) for t in taus]
out.append(rec)
model.train()
cols = ["image", "pred_parasite", "pred_wbc"] + ([f"wbc_tau_{t}" for t in taus] if taus is not None else [])
return pd.DataFrame(out, columns=cols)
def evaluate(pred, rows, t_pos):
D = rows[["image", "device", "group", "n_parasite", "n_wbc"]].merge(pred, on="image")
D["true_ul"] = [per_ul(p, w) for p, w in zip(D.n_parasite, D.n_wbc)]
D["pred_ul"] = [per_ul(p, w) for p, w in zip(D.pred_parasite, D.pred_wbc)]
D["true_pos"], D["pred_pos"] = D.n_parasite > 0, D.pred_parasite >= t_pos
D["true_high"], D["pred_high"] = D.true_ul >= HIGH_UL, D.pred_ul >= HIGH_UL
has_w = D.n_wbc > 0
m = {"n": len(D), "mae_parasite": float((D.pred_parasite - D.n_parasite).abs().mean()),
"mae_wbc": float((D.pred_wbc - D.n_wbc).abs().mean()),
"log10_ul_err_median": float(np.median(np.abs(np.log10(D.pred_ul[has_w] + 1) - np.log10(D.true_ul[has_w] + 1)))) if has_w.any() else None,
"pos_sens": float((D.pred_pos & D.true_pos).sum() / max(D.true_pos.sum(), 1)),
"pos_spec": float((~D.pred_pos & ~D.true_pos).sum() / max((~D.true_pos).sum(), 1)),
"high_decision_acc": float((D.pred_high == D.true_high)[has_w].mean()) if has_w.any() else None,
"high_flips": int((D.pred_high != D.true_high)[has_w].sum())}
return D, m
def cpu_latency(model, h, w):
m = CountNet(pretrained=False, act=ACT, wbc=WBC_HEAD).eval(); m.load_state_dict({k: v.cpu() for k, v in model.state_dict().items()})
torch.set_num_threads(1); x = torch.randn(1, 3, h, w)
with torch.no_grad():
m(x); t0 = time.time(); [m(x) for _ in range(3)]
return (time.time() - t0) / 3
def main():
torch.manual_seed(SEED); np.random.seed(SEED)
M = pseudo_slides(pd.read_csv(DATA / "manifest.csv"))
# images with no boxes at all (no parasite AND no WBC) are UNANNOTATED, not negative: a thick smear always shows
# WBCs. Audit 2026-10-15: all 70 zero-parasite test images also had 0 WBC and the model predicted ~103 parasites
# on them. They are excluded from train, val and test; there are then no true negatives, so the positive /
# negative decision is not evaluable on this release and only density decisions are reported.
n0 = len(M); M = M[(M.n_parasite + M.n_wbc) > 0].copy()
log(f"excluded {n0 - len(M)} unannotated images (0 boxes)")
if LIMIT:
M = M.head(LIMIT)
Pt = pd.read_csv(DATA / "points.csv")
P = {k: g[["cls", "x", "y", "bw", "bh"]].to_numpy(np.float32) for k, g in Pt.groupby("image")}
tr, va, te = make_split(M)
assert not (set(tr.group) & set(te.group)) and not (set(va.group) & set(te.group)), "pseudo-slide leak"
log(f"devices {M.device.value_counts().to_dict()} | pseudo-slides {M.group.nunique()} | "
f"train {len(tr)} val {len(va)} test {len(te)}")
model = CountNet(act=ACT, wbc=WBC_HEAD).to(DEV)
ema = None
if EMA > 0:
def _ema(avg, cur, n): # warm-up: decay min(EMA, (1+n)/(10+n)); fixed 0.999 from step 0
d = min(EMA, (1.0 + float(n)) / (10.0 + float(n))) # leaves the EMA at the init weights for ~1000 steps
return d * avg + (1.0 - d) * cur
ema = torch.optim.swa_utils.AveragedModel(model, avg_fn=_ema, use_buffers=True) # BN stats averaged too
log(f"config V={V} act={ACT} loss={LOSS} visible={VISIBLE} wbc_mask={WBC_MASK} select={SELECT} ema={EMA} lr={LR}")
opt = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=1e-4)
dl = torch.utils.data.DataLoader(Train(tr, P), batch_size=BS, shuffle=True, num_workers=4, drop_last=True)
steps = EPOCHS * len(dl)
warm = max(1, steps // 20) # warmup + cosine; safe for very short runs (OneCycle divides by 0)
sched = torch.optim.lr_scheduler.LambdaLR(opt, lambda i: min(1.0, (i + 1) / warm) * 0.5 * (1 + math.cos(math.pi * min(i, steps) / max(steps, 1))))
scaler = torch.amp.GradScaler("cuda", enabled=DEV.type == "cuda")
best, best_state, hist = math.inf, None, []
swa, swa_start = None, int(math.ceil(EPOCHS * (1 - SWA_FRAC))) if SWA_FRAC > 0 else None
for ep in range(EPOCHS):
for x, t, cm in dl:
with torch.autocast("cuda", dtype=torch.float16, enabled=DEV.type == "cuda"):
d = model(x.to(DEV))
loss, pix, cnt = loss_fn(d.float(), t.to(DEV), mode=LOSS, cls_mask=cm)
opt.zero_grad(set_to_none=True); scaler.scale(loss).backward(); scaler.step(opt); scaler.update(); sched.step()
if ema is not None:
ema.update_parameters(model)
net = ema.module if ema is not None else model
if swa_start is not None and ep >= swa_start: # average EMA snapshots (weights AND BN buffers)
if swa is None: # custom avg: the default (addcdiv) fails on
def _swa(avg, cur, n): # BN's integer num_batches_tracked buffer
return avg + (cur - avg) / (n + 1) if avg.is_floating_point() else cur
swa = torch.optim.swa_utils.AveragedModel(net, avg_fn=_swa, use_buffers=True)
else:
swa.update_parameters(net)
pv = predict(net, va)
Dv = va.merge(pv, on="image"); mae = float((Dv.pred_parasite - Dv.n_parasite).abs().mean())
w = Dv.n_wbc > 0
logd = float(np.median(np.abs(np.log10(8000 * Dv.pred_parasite[w] / Dv.pred_wbc[w].clip(lower=0.5) + 1)
- np.log10(8000 * Dv.n_parasite[w] / Dv.n_wbc[w] + 1))))
wslope = float(np.polyfit(Dv.n_wbc, Dv.pred_wbc, 1)[0]) if Dv.n_wbc.nunique() > 1 else float("nan")
hist.append({"epoch": ep + 1, "loss": round(float(loss), 4), "val_mae_parasite": round(mae, 2),
"val_mae_wbc": round(float((Dv.pred_wbc - Dv.n_wbc).abs().mean()), 2),
"val_logdens": round(logd, 4), "val_wbc_slope": round(wslope, 3)})
log(f"epoch {ep + 1} loss {float(loss):.4f} (pix {float(pix):.4f} cnt {float(cnt):.3f}) val MAE {mae:.2f} "
f"logdens {logd:.3f} WBC slope {wslope:.2f}")
score = logd if SELECT == "logdens" else mae
if score < best:
best, best_state = score, {k: v.detach().cpu().clone() for k, v in net.state_dict().items()}
model = CountNet(act=ACT, wbc=WBC_HEAD).to(DEV)
if swa is not None: # pre-registered: fixed average, no per-epoch pick
best_state = {k: v.detach().cpu().clone() for k, v in swa.module.state_dict().items()}
model.load_state_dict(best_state)
if WBC_HEAD == "peak": # calibrate the WBC peak threshold on VAL only
taus = [0.1, 0.15, 0.2, 0.25, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]
pvt = predict(model, va, taus=taus).merge(va[["image", "n_wbc"]], on="image")
maes = {t: float((pvt[f"wbc_tau_{t}"] - pvt.n_wbc).abs().mean()) for t in taus}
model.tau = min(maes, key=maes.get)
log(f"WBC peak tau calibrated on val: {model.tau} (MAE by tau {maes})")
pv = predict(model, va).merge(va[["image", "n_parasite"]], on="image")
neg = pv[pv.n_parasite == 0].pred_parasite
t_pos = float(np.quantile(neg, 0.95)) + 1e-6 if len(neg) >= 10 else 0.5
D, m = evaluate(predict(model, te), te, t_pos)
tag = f"{V if V in ('j2b', 'j2c') else 'j2'}_{SPLIT}{('_' + HOLD.replace(' ', '_')) if SPLIT == 'device' else ''}_s{SEED}"
D.to_csv(OUT / f"{tag}_per_image.csv", index=False)
lat = cpu_latency(model, int(M.h.median()), int(M.w.median()))
wb = np.polyfit(D.n_wbc, D.pred_wbc, 1) if D.n_wbc.nunique() > 1 else [float("nan")] * 2
pb = np.polyfit(D.n_parasite, D.pred_parasite, 1) if D.n_parasite.nunique() > 1 else [float("nan")] * 2
m["wbc_slope"], m["wbc_intercept"] = round(float(wb[0]), 3), round(float(wb[1]), 3)
m["par_slope"], m["par_intercept"] = round(float(pb[0]), 3), round(float(pb[1]), 3)
info = {"version": V, "config": {"act": ACT, "loss": LOSS, "visible": VISIBLE, "wbc_mask": WBC_MASK, "select": SELECT,
"wbc_head": WBC_HEAD, "swa_frac": SWA_FRAC, "wbc_tau": getattr(model, "tau", None),
"ema": EMA, "lr": LR},
"split": SPLIT, "holdout_device": HOLD, "seed": SEED, "t_pos": t_pos, "high_ul": HIGH_UL, "test": m,
"best_val_mae": best, "history": hist, "cpu_1thread_s_per_image": round(lat, 3),
"params": sum(p.numel() for p in model.parameters()), "n_val_negatives": int(len(neg))}
# J4 step 1: decision flips under simulated int8 / int4 (calibrated on val only), per device
from quant_eval import flips, quantise
calib = [to_tensor(load(r))[None].to(DEV) for r in va.image.head(16)]
base = D[["image", "pred_parasite", "pred_pos", "pred_high"]]
info["quant"] = {}
for name, wb, ab in (("w8a8", 8, 8), ("w4a8", 4, 8), ("w8", 8, 0)):
qm = quantise(model.float().eval(), wb, ab, calib)
Dq, mq = evaluate(predict(qm, te), te, t_pos)
info["quant"][name] = {"test": mq, **flips(base, Dq[["image", "pred_parasite", "pred_pos", "pred_high"]], te)}
log(f"{name}: pos flips {info['quant'][name]['pred_pos_flips']}, high flips {info['quant'][name]['pred_high_flips']}, "
f"count MAE vs fp32 {info['quant'][name]['count_mae_vs_fp32']:.2f}")
(OUT / f"{tag}.json").write_text(json.dumps(info, indent=1))
torch.save(best_state, OUT / f"{tag}.pt")
print("J2_RESULT " + json.dumps({"tag": tag, **m, "cpu_s": info["cpu_1thread_s_per_image"]}), flush=True)
if __name__ == "__main__":
main()

Xet Storage Details

Size:
17.2 kB
·
Xet hash:
f1cb2f22612454c00c5496caebdc0876ad3b46dea5480b0434d8fb94f0ed3df6

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.