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). :meth:on_train_batch_start
is required whenever main_loss exposes a temperature
(in epoch mode as well as step mode), because it is the only thing
that drives the temperature schedule. Omitting it leaves the
temperature undecayed (it never moves toward temp_end); a one-time
UserWarning is emitted from :meth:forward if this is detected.
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.
|
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
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 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 | |
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
get_extra_state()
¶
Serialise the phase/decay schedule state into the module's state dict.
The wrapper's scheduling state (epoch, step, phase-switch step) is
plain Python, so nn.Module.state_dict() would otherwise drop it.
PyTorch stores the returned mapping under the _extra_state key.
Returns:
| Type | Description |
|---|---|
dict
|
Schedule state. |
Notes
Without this, a resumed run finds _switch_step is None, treats
the first post-resume batch as the phase switch, resets the
temperature to temp_start and wipes the (correctly restored)
memory queue. See :meth:on_train_batch_start.
Source code in src/imbalanced_losses/warmup_wrapper.py
set_extra_state(state)
¶
Restore the phase/decay schedule state from a checkpoint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
dict
|
Mapping produced by :meth: |
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
|
The return shape tracks During warmup: scalar tensor from |
Source code in src/imbalanced_losses/warmup_wrapper.py
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 | |
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, # deliberately above the 0.05 default: softer start
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 exponent fraction is clamped at 1.0, so the temperature holds at temp_end once temp_decay_steps steps have elapsed. The clock starts at the first main-phase batch, not at training epoch 0.
Checkpointing and resume¶
LossWarmupWrapper persists its schedule state (the current epoch, global step, phase-switch step, and temperature) in state_dict() under the standard _extra_state key, via PyTorch's get_extra_state/set_extra_state. Resuming from a checkpoint restores the phase, continues the temperature decay from the correct elapsed step, resumes a blend ramp mid-way, and leaves the restored memory queue intact.
Checkpoints written before this state was persisted still load under strict=True. They restart the temperature schedule on resume, which is the behavior they were saved with.
Temperature set outside the wrapper is not checkpointed
LossWarmupWrapper is the only class in this library that persists training-progress state. The temperature attribute on SmoothAPLoss, RecallAtQuantileLoss, and PAUCAtBudgetLoss is a plain Python float, not a registered buffer, so it is absent from state_dict().
If you drive temperature yourself instead of using the wrapper:
loss = SmoothAPLoss(num_classes=10, queue_size=1024, temperature=0.05)
loss.temperature = my_anneal(global_step) # not saved
the value silently reverts to the constructor argument (0.05 above) on every resume. Either use LossWarmupWrapper for temperature scheduling, or re-apply your schedule from the restored global_step after loading a checkpoint.
Tracked in issue #16.
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 |
None leaves main_loss's own setting untouched (which auto-detects DDP by default); pass True/False to override it |
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 |