RecallAtQuantileLoss¶
Differentiable Recall-at-Quantile loss with an optional memory queue. Optimizes recall above a score threshold set at the q-th quantile of the pooled distribution. Useful for alert/detection workloads.
imbalanced_losses.recall_loss.RecallAtQuantileLoss
¶
Bases: _QueuedRankingLoss
Differentiable Recall-at-Quantile loss with an optional memory queue.
For a given quantile q, a threshold θ is estimated from the pooled score distribution (live batch + queue) without gradient, then soft recall over positives is computed per class:
θ = quantile(scores, 1 - q) [stop-gradient]
soft_recall = mean_{i∈P} σ((s_i − θ) / τ)
loss = 1 − soft_recall
Multi-class: one-vs-rest per class using logits[:, c], then reduce. Binary: logits[:, 0] with targets in {0, 1}.
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 |
quantile
|
float
|
Fraction of the score distribution treated as the alert region. E.g. 0.005 = top 50 bps, 0.01 = top 100 bps. Must be in (0, 1). Default: 0.005. |
0.005
|
queue_size
|
int
|
Circular buffer size (rows). Larger queues stabilise the quantile estimate — at 50 bps you need at least ~200 samples for a meaningful 99.5th percentile. Set to 0 to disable. Default: 1024. DDP note: when |
1024
|
temperature
|
float
|
Sigmoid sharpness τ around the threshold. Larger values give smoother gradients but less precise recall estimates. 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]; classes with no positives are nan. Default: 'mean'. |
'mean'
|
ignore_index
|
int
|
Target value marking padded positions. Excluded from threshold estimation and recall. Default: -100. |
-100
|
update_queue_in_eval
|
bool
|
If False (default), the queue is frozen during eval mode. Default: False. |
False
|
gather_distributed
|
bool or None
|
Whether to all-gather logits and targets across DDP workers before
computing the loss. |
None
|
quantile_interpolation
|
str
|
Interpolation method passed to torch.quantile. 'higher' is the conservative default — the threshold never undershoots the true cutoff. One of ('linear', 'lower', 'higher', 'nearest', 'midpoint'). Default: 'higher'. |
'higher'
|
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 caps it at Use this for seq2seq tasks with very large flattened pool sizes. Recommended: 2048–4096. Subsampling also introduces noise into the quantile threshold estimate, so use the largest value your GPU allows. |
None
|
Examples:
>>> loss_fn = RecallAtQuantileLoss(num_classes=4, quantile=0.005, queue_size=512)
>>> logits = torch.randn(32, 4)
>>> targets = torch.randint(0, 4, (32,))
>>> loss = loss_fn(logits, targets)
>>> loss.backward()
Notes
The quantile must exceed the positive class fraction for the threshold to fall in the negative region under perfect classification. With C=4 balanced classes (25% positives), use quantile > 0.25 for sanity tests.
In DDP, the all-gather runs before the enqueue, so every rank stores
identical global-batch rows and queues stay in sync automatically. The
effective 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 quantile
estimate.
Source code in src/imbalanced_losses/recall_loss.py
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 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 | |
Quick examples¶
Optimize recall at top 0.5%¶
from imbalanced_losses import RecallAtQuantileLoss
import torch
loss_fn = RecallAtQuantileLoss(num_classes=4, quantile=0.005, queue_size=1024)
logits = torch.randn(32, 4)
targets = torch.randint(0, 4, (32,))
loss = loss_fn(logits, targets)
loss.backward()
Binary classification¶
loss_fn = RecallAtQuantileLoss(num_classes=1, quantile=0.01, queue_size=512)
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} recall-loss: {per_class[c].item():.4f}")
Parameter guidance¶
| Parameter | Default | Notes |
|---|---|---|
num_classes |
required | Use 1 for binary |
quantile |
0.005 |
Fraction targeted as alert region; must be in (0, 1) |
queue_size |
1024 |
For quantile=0.005, need ≥ 200 pooled samples |
temperature |
0.01 |
Larger = smoother gradient; smaller = sharper recall estimate |
reduction |
"mean" |
"none" returns [C] tensor; classes with no positives are nan |
ignore_index |
-100 |
Excluded from threshold estimation and recall |
update_queue_in_eval |
False |
Freezes queue during model.eval() by default |
quantile_interpolation |
"higher" |
Conservative default; use "linear" for a softer threshold |
Quantile selection guidance¶
The threshold is the (1 - quantile) percentile of all pooled scores. For the threshold to fall in the negative score region under a perfect model, quantile must exceed the positive class fraction:
- 4 balanced classes (25% positives per class): use
quantile > 0.25for sanity tests - Real-world imbalance (1% positives):
quantile=0.005is well above the positive fraction