Distributed Utilities¶
Helper functions for DDP all-gather with correct gradient handling. Located in imbalanced_losses.distributed.
imbalanced_losses.distributed.all_gather_with_grad(tensor, scale_grad=True)
¶
All-gather a tensor across all workers, preserving gradients for the local rank's slice.
Standard dist.all_gather returns detached tensors. This function
replaces the local rank's slice in the output with the original tensor,
so gradients flow back to the local model parameters. Other workers'
slices remain stop-gradient, matching DDP semantics (each worker
optimizes its own parameters via all-reduced gradients).
DDP averages gradients across ranks, and each rank only backpropagates
through its own slice. To make the averaged gradient equal the
single-process gradient on the global batch, the gradient flowing into
the local slice is multiplied by world_size (identity in the forward
pass, so the gathered values and the loss are unchanged).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tensor
|
Tensor
|
Local tensor to gather. Typically |
required |
scale_grad
|
bool
|
Multiply the local slice's gradient by |
True
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Concatenation of all workers' tensors along dim 0, shape
|
Notes
Dim 0 may vary across ranks (e.g. unequal last-batch sizes). When sizes differ, tensors are zero-padded to the max for the collective, then trimmed back to their true lengths before concatenation. An equal-size fast path skips padding when all ranks contribute the same number of rows.
All workers' queues stay synchronized automatically: since every worker
calls all_gather before passing to the loss, every worker enqueues
the same rows (the non-ignored rows of the global batch). No extra
synchronization is needed.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
Examples:
Manual gathering in a DDP training step. The loss must be constructed
with gather_distributed=False, otherwise it gathers again: every row
is duplicated and the gradient is scaled by world_size twice::
from imbalanced_losses import SmoothAPLoss
from imbalanced_losses.distributed import (
all_gather_no_grad,
all_gather_with_grad,
)
loss_fn = SmoothAPLoss(num_classes=4, gather_distributed=False)
logits_global = all_gather_with_grad(logits) # [sum(N_i), C]
targets_global = all_gather_no_grad(targets) # [sum(N_i)]
loss = loss_fn(logits_global, targets_global)
loss.backward()
Source code in src/imbalanced_losses/distributed.py
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 | |
imbalanced_losses.distributed.all_gather_no_grad(tensor)
¶
All-gather a tensor across all workers without gradient tracking.
Intended for targets / labels, which are integer tensors with no gradient.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tensor
|
Tensor
|
Local tensor to gather. Typically |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Concatenation of all workers' tensors along dim 0, shape
|
Notes
Dim 0 may vary across ranks (e.g. unequal last-batch sizes). When sizes differ, tensors are zero-padded to the max for the collective, then trimmed back to their true lengths before concatenation. An equal-size fast path skips padding when all ranks contribute the same number of rows.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
Source code in src/imbalanced_losses/distributed.py
Usage pattern¶
from imbalanced_losses import SmoothAPLoss
from imbalanced_losses.distributed import all_gather_with_grad, all_gather_no_grad
# The loss must not gather again: construct it with gather_distributed=False.
loss_fn = SmoothAPLoss(num_classes=4, queue_size=1024, gather_distributed=False)
# In a DDP training step:
logits_global = all_gather_with_grad(logits) # [sum(N_i), C] — grad flows, scaled by world_size
targets_global = all_gather_no_grad(targets) # [sum(N_i)] — no grad
loss = loss_fn(logits_global, targets_global)
loss.backward()
all_gather_with_grad scales the local slice's gradient by world_size so that DDP's gradient averaging yields the full-batch gradient. Pass scale_grad=False when gradients are summed across ranks instead of averaged; the returned values are identical either way.
Behavior summary¶
| Function | Gradient | Use for |
|---|---|---|
all_gather_with_grad |
Flows through local rank's slice, scaled by world_size (disable with scale_grad=False) |
Logits, embeddings |
all_gather_no_grad |
None | Integer targets, labels |
Both functions:
- Raise
RuntimeErroriftorch.distributedis not available or not initialized - Are no-ops (return input unchanged) when
world_size == 1 - Support variable dim-0 sizes across ranks (e.g. unequal last-batch without
drop_last=True). Tensors are padded to the max size for the collective, then trimmed. An equal-size fast path skips this overhead when all ranks have the same batch size.