SmoothAPLoss¶
Differentiable Average Precision loss with an optional memory queue. Approximates AP using sigmoid-based soft rank estimation (Smooth-AP, Brown et al. 2020).
imbalanced_losses.ap_loss.SmoothAPLoss
¶
Bases: _QueuedRankingLoss
Differentiable Average Precision loss with an optional memory queue.
Approximates AP using soft sigmoid-based rank estimation (Smooth-AP, Brown et al. 2020). Supports multi-class (one-vs-rest) and binary (num_classes=1) classification. Expects logits [N, C] and targets [N]; this class is agnostic to sequence structure — flatten upstream.
Inherits queue management, DDP gather, ignore-index filtering,
subsampling, and reduction logic from _QueuedRankingLoss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_classes
|
int
|
Number of output classes. Use 1 for binary mode. |
required |
queue_size
|
int
|
Number of (logits, targets) rows stored in the circular buffer. Larger queues give more stable AP estimates at the cost of O(|P|×M) memory in _compute_smooth_ap, where |P| is the number of positives. Set to 0 to disable. Default: 1024. DDP note: when |
1024
|
temperature
|
float
|
Sigmoid sharpness τ. Smaller values approximate the true discontinuous rank more closely but produce harder gradients. Typical range: 0.005–0.05. Default: 0.01. |
0.01
|
reduction
|
('mean', 'sum', 'none')
|
How to aggregate per-class losses. - 'mean': scalar average over valid classes. - 'sum': scalar sum over valid classes. - 'none': tensor of shape [C]; degenerate classes are nan. Default: 'mean'. |
'mean'
|
ignore_index
|
int
|
Target value marking padded positions. Matching rows are excluded from ranking and the positive set. Default: -100. |
-100
|
update_queue_in_eval
|
bool
|
If False (default), the queue is frozen during eval mode. Set to True to allow queue updates during validation. Default: False. |
False
|
gather_distributed
|
bool or None
|
Whether to all-gather logits and targets across DDP workers before
computing the loss. |
None
|
max_pool_size
|
int or None
|
Maximum number of rows in the ranking pool (live batch + queue after
ignore_index filtering). When the pool exceeds this value,
minimum-quota subsampling is applied: each observed class is guaranteed
an equal quota of rows ( Use this for seq2seq tasks where flattened inputs produce very large
pools. The pairwise matrix in .. note:: Subsampling is a stochastic approximation — the loss value will vary across steps even for the same batch. Use the largest value your GPU allows for the most stable gradient estimates. |
None
|
Examples:
>>> loss_fn = SmoothAPLoss(num_classes=4, queue_size=512)
>>> logits = torch.randn(32, 4)
>>> targets = torch.randint(0, 4, (32,))
>>> loss = loss_fn(logits, targets)
>>> loss.backward()
Notes
Complexity of _compute_smooth_ap is O(|P| × M), where |P| is the number of positives in the pool and M = batch_size + queue_size. At low positive rates this is much cheaper than the naive O(M²) formulation.
In DDP, set gather_distributed=False to opt out; otherwise the loss
auto-detects and all-gathers on first forward when world_size > 1.
Because the gather happens before the enqueue, every rank stores
identical global-batch rows — queues stay in sync automatically, but
the pool per step is global_batch_size + queue_size. At large
global batch sizes the queue contribution may be negligible; prefer
queue_size=0 when the global batch already provides a stable pool.
Source code in src/imbalanced_losses/ap_loss.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 | |
Quick examples¶
Multi-class¶
from imbalanced_losses import SmoothAPLoss
import torch
loss_fn = SmoothAPLoss(num_classes=4, queue_size=1024, temperature=0.01)
logits = torch.randn(32, 4)
targets = torch.randint(0, 4, (32,))
loss = loss_fn(logits, targets)
loss.backward()
Binary classification¶
loss_fn = SmoothAPLoss(num_classes=1, queue_size=256)
logits = torch.randn(32, 1)
targets = torch.randint(0, 2, (32,))
loss = loss_fn(logits, targets)
Per-class logging¶
loss, per_class, valid = loss_fn(logits, targets, return_per_class=True)
loss.backward()
for c in valid.nonzero(as_tuple=True)[0].tolist():
print(f"Class {c} AP-loss: {per_class[c].item():.4f}")
Queue management¶
Parameter guidance¶
| Parameter | Default | Notes |
|---|---|---|
num_classes |
required | Use 1 for binary |
queue_size |
1024 |
0 to disable; keep batch + queue ≤ 4096 |
temperature |
0.01 |
Range 0.005–0.05; lower = sharper, closer to true rank |
reduction |
"mean" |
"none" returns [C] tensor with nan for degenerate classes |
ignore_index |
-100 |
Excludes padding from ranking and the positive set |
update_queue_in_eval |
False |
Freezes queue during model.eval() by default |
gather_distributed |
None |
Auto-detects DDP; set False to opt out |
Complexity note¶
The core computation is O(|P| × M) where |P| is the number of positives and M = batch_size + queue_size. At low positive rates this is much less than O(M²) — roughly 200× cheaper at 0.5% positives.