Chucks90's picture
download
raw
10.2 kB
"""J2 CountNet-µL (Addendum J, locked sha256 e6afa2c1…): count-native edge model for thick-smear microscopy.
Backbone: timm MobileNetV4-Conv-Small (ImageNet weights), features at strides 8/16/32 fused top-down (FPN-lite,
3 lateral 1x1 convs + upsample-add) to one stride-4 map. Heads: two 1-channel density maps (parasite, WBC), softplus
so density >= 0. Readout = SUM over the map (cardinality channel, Addendum I #2): no NMS, no anchors, fixed latency,
int8-friendly. Image-level parasites per µL = 8000 x sum(P) / sum(W) (WHO thick-smear convention, 8000 WBC/µL).
Targets: each annotated point becomes a unit-mass Gaussian on the stride-4 grid (sigma from its box size), so the
map's sum equals the count exactly. Loss = pixel MSE on the (scaled) density + L1 on the per-image counts.
"""
from __future__ import annotations
import math
import numpy as np
import timm
import torch
import torch.nn as nn
import torch.nn.functional as F
STRIDE = 4
SCALE = 100.0 # density maps are multiplied by this for the pixel loss (tiny per-pixel values otherwise)
class CountNet(nn.Module):
def __init__(self, backbone="mobilenetv4_conv_small", pretrained=True, width=64, n_out=2, act="softplus",
wbc="density", tau=0.3):
super().__init__()
# wbc="peak" (J2c): channel 1 is a CenterNet-style centre heatmap (logits); WBC count = local maxima above tau.
# WBC are sparse and large (3-6 per image): integrating a density over them drifted with magnification and
# regressed to the mean (J2b WBC slope 0.46). Parasites stay density + sum (2.8x better than detection).
self.wbc, self.tau = wbc, tau
self.act = act # "softplus" (v2) | "relu" (J2b: exact zeros, no background leak)
self.body = timm.create_model(backbone, pretrained=pretrained, features_only=True, out_indices=(1, 2, 3, 4))
chs = self.body.feature_info.channels() # strides 4, 8, 16, 32
self.lat = nn.ModuleList(nn.Conv2d(c, width, 1) for c in chs)
self.head = nn.Sequential(nn.Conv2d(width, width, 3, padding=1), nn.ReLU(inplace=True),
nn.Conv2d(width, n_out, 1))
nn.init.constant_(self.head[-1].bias, -4.0 if act == "softplus" else 0.0) # start near-zero density
def forward(self, x):
feats = self.body(x)
y = self.lat[-1](feats[-1])
for f, lat in zip(reversed(feats[:-1]), reversed(list(self.lat[:-1]))):
y = F.interpolate(y, size=f.shape[-2:], mode="nearest") + lat(f)
h = self.head(y)
# softplus never reaches 0: at bias -4 every background cell carries ~1.8e-4, i.e. ~20 counts over a full map.
# Negligible next to ~100 parasites, decisive next to 3-6 WBC (J2 v2 diagnosis, 2026-10-16).
d = (F.softplus(h) if self.act == "softplus" else F.relu(h)) / SCALE # [B, 2, H/4, W/4], sums = counts
if self.wbc == "peak":
d = torch.cat([d[:, :1], h[:, 1:2]], 1) # channel 1 = WBC centre logits
return d
def counts(self, d, tau=None):
"""[B, 2]: parasites (density sum), WBC (density sum, or peak count for wbc="peak")."""
par = d[:, 0].sum(dim=(-2, -1))
if getattr(self, "wbc", "density") != "peak":
return torch.stack([par, d[:, 1].sum(dim=(-2, -1))], 1)
return torch.stack([par, peak_count(d[:, 1], self.tau if tau is None else tau)], 1)
def peak_count(logits, tau):
p = torch.sigmoid(logits)
keep = (p == F.max_pool2d(p[:, None], 3, 1, 1)[:, 0]) & (p > tau)
return keep.flatten(1).sum(1).float()
def peak_target(points, h, w, cls=1, stride=STRIDE, min_sigma=1.0):
"""CenterNet heatmap for one class: Gaussian with PEAK 1 at each centre (max-combined), sigma from box size."""
H, W = math.ceil(h / stride), math.ceil(w / stride)
out = np.zeros((H, W), np.float32)
yy, xx = np.mgrid[0:H, 0:W]
for c, x, y, bw, bh in points:
if int(c) != cls:
continue
cx, cy = x / stride - 0.5, y / stride - 0.5
if not (0 <= cx < W and 0 <= cy < H):
continue # peaks only for centres inside the frame
sig = max(min_sigma, 0.25 * max(bw, bh) / stride)
g = np.exp(-((xx - cx) ** 2 + (yy - cy) ** 2) / (2 * sig ** 2))
g[int(round(cy)) if int(round(cy)) < H else H - 1, int(round(cx)) if int(round(cx)) < W else W - 1] = 1.0
np.maximum(out, g, out=out)
return out
def focal_loss(logits, target, alpha=2.0, beta=4.0):
"""CenterNet penalty-reduced focal loss; positives = pixels where target == 1."""
p = torch.sigmoid(logits).clamp(1e-4, 1 - 1e-4)
pos = target.eq(1).float()
neg = 1 - pos
pl = -(torch.log(p) * (1 - p) ** alpha * pos).sum()
nl = -(torch.log(1 - p) * p ** alpha * (1 - target) ** beta * neg).sum()
return (pl + nl) / pos.sum().clamp_min(1.0)
def density_target(points, h, w, n_out=2, stride=STRIDE, min_sigma=1.0, visible=False):
"""points: iterable of (cls, x, y, bw, bh) in input pixels -> [n_out, ceil(h/s), ceil(w/s)].
visible=False (v2): each object's Gaussian is renormalised to unit mass inside the frame, so a cell cut by a crop
edge counts fully and one whose centre is just outside counts zero. visible=True (J2b): mass = the fraction of the
object's Gaussian inside the frame (consistent with what the image shows); callers pass points whose centre lies
outside the frame but within 3 sigma."""
H, W = math.ceil(h / stride), math.ceil(w / stride)
out = np.zeros((n_out, H, W), np.float32)
for c, x, y, bw, bh in points:
c = int(c) # class ids arrive as floats from the point array
if c >= n_out:
continue
cx, cy = x / stride - 0.5, y / stride - 0.5
sig = max(min_sigma, 0.25 * max(bw, bh) / stride)
r = int(3 * sig) + 1
gx = np.arange(int(np.floor(cx)) - r, int(np.floor(cx)) + r + 2)
gy = np.arange(int(np.floor(cy)) - r, int(np.floor(cy)) + r + 2)
g = np.exp(-((gx[None, :] - cx) ** 2 + (gy[:, None] - cy) ** 2) / (2 * sig ** 2))
full = g.sum()
mx, my = (gx >= 0) & (gx < W), (gy >= 0) & (gy < H)
if not mx.any() or not my.any() or full <= 0:
continue
gv = g[np.ix_(my, mx)]
if gv.sum() <= 0:
continue
out[c, gy[my][0]:gy[my][-1] + 1, gx[mx][0]:gx[mx][-1] + 1] += gv / (full if visible else gv.sum())
return out
def loss_fn(pred, target, w_count=0.01, mode="v2", cls_mask=None):
"""mode "v2": pixel MSE (scaled) + 0.01 * L1 on counts. Diagnosis: Gaussian energy scales as 1/sigma^2, so a WBC
(sigma ~4.5 cells) carries ~175x less pixel-loss signal per image than the parasites (sigma ~1.5, ~100 of them);
the WBC head learned to output ~3 per image regardless of content (slope 0.1-0.45).
mode "balanced" (J2b): per-class pixel MSE normalised by that class's target energy in the batch, plus a
log-count L1 per class (scale-free, aligned with the density ratio 8000 * P / W), averaged over classes.
cls_mask [B, C] (1 = labelled): zeroes the loss of a class whose labels are missing in that image."""
if mode == "j2c": # parasite: energy-normalised MSE + log-count; WBC: focal on peak heatmap
se = ((pred[:, 0] - target[:, 0]) * SCALE) ** 2
energy = ((target[:, 0] * SCALE) ** 2).mean().clamp_min(1e-6)
pix = se.mean() / energy
cnt = (torch.log1p(pred[:, 0].sum(dim=(-2, -1))) - torch.log1p(target[:, 0].sum(dim=(-2, -1)))).abs().mean()
fl = focal_loss(pred[:, 1], target[:, 1])
return pix + cnt + fl, pix.detach(), (cnt + fl).detach()
if mode == "v2":
pix = F.mse_loss(pred * SCALE, target * SCALE)
cnt = F.l1_loss(pred.sum(dim=(-2, -1)), target.sum(dim=(-2, -1)))
return pix + w_count * cnt, pix.detach(), cnt.detach()
B, C = pred.shape[:2]
m = torch.ones(B, C, device=pred.device) if cls_mask is None else cls_mask.to(pred.device).float()
se = ((pred - target) * SCALE) ** 2 # [B, C, H, W]
energy = ((target * SCALE) ** 2).mean(dim=(0, 2, 3)).clamp_min(1e-6) # per class
pix_c = (se.mean(dim=(2, 3)) * m).sum(0) / m.sum(0).clamp_min(1) / energy
lc = (torch.log1p(pred.sum(dim=(-2, -1))) - torch.log1p(target.sum(dim=(-2, -1)))).abs()
cnt_c = (lc * m).sum(0) / m.sum(0).clamp_min(1)
pix, cnt = pix_c.mean(), cnt_c.mean()
return pix + cnt, pix.detach(), cnt.detach()
def per_ul(par, wbc, wbc_per_ul=8000.0):
return wbc_per_ul * par / max(wbc, 1e-6)
if __name__ == "__main__":
m = CountNet(pretrained=False)
x = torch.randn(2, 3, 512, 768)
d = m(x)
assert d.shape == (2, 2, 128, 192), d.shape
t = density_target([(0, 100.0, 50.0, 20, 20), (1, 700.0, 500.0, 40, 40), (0, 2.0, 2.0, 10, 10)], 512, 768)
assert abs(t[0].sum() - 2) < 1e-4 and abs(t[1].sum() - 1) < 1e-4, t.sum((1, 2))
tv = density_target([(1, 0.0, 300.0, 40, 40), (1, -8.0, 300.0, 40, 40), (0, 300.0, 300.0, 10, 10)], 512, 768, visible=True)
assert 0.3 < tv[1].sum() < 0.9 and abs(tv[0].sum() - 1) < 1e-4, tv.sum((1, 2)) # edge cells: partial mass
mp = CountNet(pretrained=False, act="relu", wbc="peak"); dp = mp(x)
tp = np.stack([t[0], peak_target([(1, 700.0, 500.0, 40, 40), (1, 300.0, 100.0, 40, 40)], 512, 768)])
assert abs(tp[1].max() - 1) < 1e-6 and int((tp[1] == 1).sum()) == 2, (tp[1] == 1).sum()
lp, _, _ = loss_fn(dp, torch.from_numpy(np.stack([tp, tp])), mode="j2c"); lp.backward(); assert torch.isfinite(lp)
hm = torch.full((1, 128, 192), -9.0); hm[0, 10, 10] = 5; hm[0, 50, 60] = 5
assert int(peak_count(hm, 0.3)) == 2
for act in ("softplus", "relu"):
mm = CountNet(pretrained=False, act=act); dd = mm(x)
lo, _, _ = loss_fn(dd, torch.from_numpy(np.stack([t, t])), mode="balanced", cls_mask=torch.tensor([[1, 1], [1, 0]]))
lo.backward(); assert torch.isfinite(lo), act
print("params", sum(p.numel() for p in m.parameters()), "| density shape", tuple(d.shape), "| target mass", t.sum((1, 2)))

Xet Storage Details

Size:
10.2 kB
·
Xet hash:
54e0693e575a1fb521899e5f996f6e7d94a0ad405107d4402cb7993ac954148a

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