LossWarmupWrapper¶
A training utility that wraps a warmup loss and a main ranking loss. Manages three phases: warmup (standard loss only), optional linear blend, and main phase with geometric temperature decay. Exposes PyTorch Lightning hooks.
imbalanced_losses.warmup_wrapper.LossWarmupWrapper
¶
Bases: Module
Wraps a warmup loss and a main ranking loss with two features:
-
Phase switching —
warmup_lossis active during the warmup phase;main_lossis active thereafter. The warmup phase can be defined in epochs (warmup_epochs) or steps (warmup_steps), but not both. -
Geometric temperature decay —
main_loss.temperaturedecays fromtemp_starttotemp_endovertemp_decay_stepsglobal training steps, starting from the moment of phase switch::temp(t) = temp_start * (temp_end / temp_start) ** (t / temp_decay_steps)
After temp_decay_steps steps the temperature is held at
temp_end.
Call :meth:on_train_epoch_start and :meth:on_train_batch_start
from the corresponding PyTorch Lightning hooks (or your training loop).
In step mode, :meth:on_train_epoch_start is optional (only needed
when reset_queue_each_epoch=True).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
warmup_loss
|
Module
|
Loss used during warmup. Must accept |
required |
main_loss
|
Module
|
Loss used after warmup. Must accept |
required |
warmup_epochs
|
int
|
Number of epochs to use |
0
|
temp_start
|
float
|
Temperature at the start of the main phase. |
0.05
|
temp_end
|
float
|
Temperature after |
0.005
|
temp_decay_steps
|
int
|
Number of global training steps over which to decay temperature. |
10000
|
blend_epochs
|
int
|
Number of epochs after warmup to linearly blend from |
0
|
warmup_steps
|
int or None
|
Number of global training steps to use |
None
|
blend_steps
|
int or None
|
Number of global training steps after warmup to linearly blend from
|
None
|
final_main_weight
|
float
|
The Use this when you want a permanent mix — e.g.
.. note::
When |
1.0
|
reset_queue_each_epoch
|
bool
|
Call |
False
|
gather_distributed
|
bool or None
|
Forwarded to |
None
|
Source code in src/imbalanced_losses/warmup_wrapper.py
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 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 | |
in_blend
property
¶
Whether the wrapper is currently in the blend phase.
main_weight
property
¶
Current main loss weight (0.0 during warmup, ramps to final_main_weight during blend, final_main_weight after).
in_warmup
property
¶
Whether the wrapper is currently in the warmup phase.
Returns:
| Type | Description |
|---|---|
bool
|
True while in the warmup phase; False once the main loss is active.
In epoch mode: |
current_temperature
property
¶
The temperature currently set on main_loss.
Returns:
| Type | Description |
|---|---|
float or None
|
|
on_train_epoch_start(epoch)
¶
Advance the epoch counter and handle phase transition bookkeeping.
Call this from LightningModule.on_train_epoch_start passing
self.current_epoch. Responsibilities:
- Updates the internal epoch counter.
- On the first epoch of the main phase, sets the
_switch_stepsentinel so that :meth:on_train_batch_startcan latch the exact global step. - Calls
main_loss.reset_queue()at the start of each main-phase epoch whenreset_queue_each_epoch=Trueand the method exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
epoch
|
int
|
Zero-indexed current epoch number, as provided by
|
required |
Source code in src/imbalanced_losses/warmup_wrapper.py
on_train_batch_start(global_step)
¶
Update the temperature schedule for the current training step.
Call this from LightningModule.on_train_batch_start passing
self.global_step. Responsibilities:
- On the first main-phase batch, latches
_switch_steptoglobal_stepand sets temperature totemp_start. - On all subsequent main-phase batches, applies the geometric
decay formula and writes the result to
main_loss.temperature. - Is a no-op during warmup or before the phase sentinel is set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
global_step
|
int
|
Monotonically increasing global step counter, as provided by
|
required |
Source code in src/imbalanced_losses/warmup_wrapper.py
forward(logits, targets, **kwargs)
¶
Compute loss using the currently active loss module.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
|
Tensor
|
Raw class scores, shape as expected by the active loss. |
required |
targets
|
Tensor
|
Integer class labels or binary targets, shape as expected by the active loss. |
required |
**kwargs
|
Additional keyword arguments forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
Tensor or tuple
|
During warmup or blend: scalar tensor. After blend: output of
|
Source code in src/imbalanced_losses/warmup_wrapper.py
Quick example¶
Epoch-based warmup (default):
from imbalanced_losses import SmoothAPLoss, LossWarmupWrapper
import torch.nn as nn
loss_fn = LossWarmupWrapper(
warmup_loss=nn.CrossEntropyLoss(),
main_loss=SmoothAPLoss(num_classes=10, queue_size=1024),
warmup_epochs=5,
blend_epochs=2,
temp_start=0.5,
temp_end=0.01,
temp_decay_steps=50_000,
)
Step-based warmup (use when you prefer step counts over epochs):
loss_fn = LossWarmupWrapper(
warmup_loss=nn.CrossEntropyLoss(),
main_loss=SmoothAPLoss(num_classes=10, queue_size=1024),
warmup_steps=5_000,
blend_steps=2_000,
temp_start=0.5,
temp_end=0.01,
temp_decay_steps=50_000,
)
warmup_epochs/blend_epochs and warmup_steps/blend_steps are mutually exclusive pairs.
PyTorch Lightning integration¶
Epoch mode — call both hooks:
class MyModel(pl.LightningModule):
def __init__(self):
super().__init__()
self.loss_fn = LossWarmupWrapper(...)
def on_train_epoch_start(self):
self.loss_fn.on_train_epoch_start(self.current_epoch)
def on_train_batch_start(self, batch, batch_idx):
self.loss_fn.on_train_batch_start(self.global_step)
def training_step(self, batch, batch_idx):
logits, targets = batch
loss = self.loss_fn(logits, targets)
self.log("train/loss", loss)
self.log("train/main_weight", self.loss_fn.main_weight)
if (t := self.loss_fn.current_temperature) is not None:
self.log("train/temperature", t)
return loss
Step mode — only the batch hook is required:
class MyModel(pl.LightningModule):
def on_train_batch_start(self, batch, batch_idx):
self.loss_fn.on_train_batch_start(self.global_step)
def training_step(self, batch, batch_idx):
logits, targets = batch
return self.loss_fn(logits, targets)
Phase schedule¶
Epoch mode — with warmup_epochs=5, blend_epochs=2, final_main_weight=1.0 (default):
| Epoch range | Phase | in_warmup |
in_blend |
main_weight |
|---|---|---|---|---|
| 0–4 | warmup | True |
False |
0.0 |
| 5 | blend | False |
True |
0.333 |
| 6 | blend | False |
True |
0.667 |
| 7+ | main | False |
False |
1.0 |
Step mode — with warmup_steps=500, blend_steps=3, final_main_weight=1.0 (default):
| Step range | Phase | in_warmup |
in_blend |
main_weight |
|---|---|---|---|---|
| 0–499 | warmup | True |
False |
0.0 |
| 500 | blend | False |
True |
0.25 |
| 501 | blend | False |
True |
0.50 |
| 502 | blend | False |
True |
0.75 |
| 503+ | main | False |
False |
1.0 |
Permanent mix — with warmup_epochs=5, blend_epochs=2, final_main_weight=0.75:
| Epoch range | Phase | in_warmup |
in_blend |
main_weight |
|---|---|---|---|---|
| 0–4 | warmup | True |
False |
0.0 |
| 5 | blend | False |
True |
0.25 |
| 6 | blend | False |
True |
0.50 |
| 7+ | main | False |
False |
0.75 |
The blend ramp always targets final_main_weight, not 1.0.
Temperature schedule¶
Temperature decays geometrically from temp_start to temp_end over temp_decay_steps steps, measured from the moment of phase switch:
The clock starts at the first main-phase batch, not at training epoch 0.
Parameter reference¶
| Parameter | Default | Description |
|---|---|---|
warmup_loss |
required | Loss used during warmup (e.g. CrossEntropyLoss) |
main_loss |
required | Loss used after warmup (e.g. SmoothAPLoss) |
warmup_epochs |
0 |
Epochs before switching; 0 skips warmup. Mutually exclusive with warmup_steps. |
temp_start |
0.05 |
Temperature at phase switch |
temp_end |
0.005 |
Temperature after temp_decay_steps steps |
temp_decay_steps |
10_000 |
Steps over which to decay temperature |
blend_epochs |
0 |
Linear blend epochs; 0 = hard switch. Mutually exclusive with blend_steps. |
warmup_steps |
None |
Steps before switching. Mutually exclusive with warmup_epochs > 0. |
blend_steps |
None |
Linear blend steps. Mutually exclusive with blend_epochs > 0. |
final_main_weight |
1.0 |
Target main_loss weight after the blend ramp (or at hard switch). Must be in (0, 1]. Use < 1.0 to hold a permanent mix (e.g. 0.75 = 75 % main / 25 % warmup forever). |
reset_queue_each_epoch |
False |
Reset main_loss queue each main-phase epoch |
gather_distributed |
None |
Forwarded to main_loss.gather_distributed; None auto-detects DDP |
Properties¶
| Property | Type | Description |
|---|---|---|
in_warmup |
bool |
True while in the warmup phase |
in_blend |
bool |
True during the blend transition |
main_weight |
float |
Current main loss weight: 0.0 during warmup → ramps to final_main_weight → holds at final_main_weight |
current_temperature |
float or None |
Current main_loss.temperature; None if unavailable |