[BUG] SIGReg with `gather_distributed=True` produces gradient which is off by `1/world_size` under DDP
Summary
SIGReg, introduced in #1893, supports a gather_distributed=True mode for cross-rank ECF aggregation. The forward pass is correct, the loss value at every rank equals the global SIGReg statistic on the concatenated batch. But the backward pass is not. The gradient is off by a factor of 1/world_size. Under DDP gradient averaging, the parameter gradient through SIGReg is exactly 1/world_size of the true gradient that single-GPU SIGReg on the global batch would produce.
SIGReg is intended to be combined with other loss terms via a weighting coefficient (e.g., lambda_param in the proposed LeJEPALoss from #1916). With the current bug, training with gather_distributed=True silently divides the user-set lambda_param by world_size.
I came across this while implementing #1916 (LeJEPA core building blocks) for #1888.
Cause
https://github.com/lightly-ai/lightly/blob/a00699bbeaa3e9f4ff879a7d0d6d4f211c793ff7/lightly/loss/lejepa_loss.py#L90-L94
The low-level torch.distributed.all_reduce is not autograd-aware. Both calls (for cos_sum and sin_sum) overwrite the tensor's .data in place with the global sum but do not register the cross-rank operation in the autograd graph. The forward values at each rank correctly become the global sums, but autograd at each rank still treats both cos_sum and sin_sum as functions of local x_t only.
Each rank's autograd computes the partial gradient from its local samples only. DDP then averages across ranks, yielding (1/world_size) * sum_r partial_r = (1/world_size) * total.
Reference comparison
The reference repository galilai-group/lejepa handles distributed SIGReg in lejepa/univariate/epps_pulley.py using autograd-aware all_reduce with op="AVG" and multiplies the final statistic by self.world_size. Copying the relevant code below for easy reference:
from torch.distributed.nn import all_reduce as functional_all_reduce
from torch.distributed.nn import ReduceOp
def all_reduce(x, op="AVG"):
if dist.is_available() and dist.is_initialized():
op = ReduceOp.__dict__[op.upper()]
return functional_all_reduce(x, op)
else:
return x
# in forward:
cos_mean = all_reduce(cos_mean)
sin_mean = all_reduce(sin_mean)
err = (cos_mean - self.phi).square() + sin_mean.square()
return (err @ self.weights) * N * self.world_size
The * self.world_size multiplier exactly cancels the 1/world_size factor that op="AVG" introduces in the autograd backward. Lightly uses neither.
Numerical reproduction
Two-rank simulation (no real DDP, mocks the torch.distributed.all_reduce by overwriting .data in place)
import torch
from lightly.loss.lejepa_loss import SIGReg
torch.manual_seed(42)
N_global, D, world_size = 8, 16, 2
N_local = N_global // world_size
x_global = torch.randn(N_global, D)
x_local = [x_global[i*N_local:(i+1)*N_local] for i in range(world_size)]
A = torch.randn(D, 4); A /= A.norm(p=2, dim=0)
def sr_with_fixed_A():
sr = SIGReg(num_vectors=4, gather_distributed=False)
sr._generate_unit_vectors = lambda device, dtype, num_features: A.to(device, dtype)
return sr
# Truth: single-rank, full batch
theta = torch.tensor(2.0, requires_grad=True)
sr_with_fixed_A()(theta * x_global).backward()
g_truth = float(theta.grad)
# Lightly's gather_distributed=True mode (simulated)
per_rank = []
for rank in range(world_size):
theta_r = torch.tensor(2.0, requires_grad=True)
y_r = theta_r * x_local[rank]
sr = sr_with_fixed_A()
x_t_r = (y_r @ A).unsqueeze(-1) * sr.t
cos_sum, sin_sum = x_t_r.cos().sum(-3), x_t_r.sin().sum(-3)
with torch.no_grad():
cos_g, sin_g = torch.zeros_like(cos_sum), torch.zeros_like(sin_sum)
for r2 in range(world_size):
x_t_r2 = (2.0 * x_local[r2] @ A).unsqueeze(-1) * sr.t
cos_g += x_t_r2.cos().sum(-3); sin_g += x_t_r2.sin().sum(-3)
cos_sum.data.copy_(cos_g); sin_sum.data.copy_(sin_g)
cos_mean, sin_mean = cos_sum / N_global, sin_sum / N_global
err = (cos_mean - sr.phi).square() + sin_mean.square()
((err @ sr.weights) * N_global).mean().backward()
per_rank.append(float(theta_r.grad))
ddp_avg = sum(per_rank) / world_size
print(f"truth={g_truth:.6f} lightly_ddp_avg={ddp_avg:.6f} ratio={ddp_avg/g_truth:.4f}")
Output:
truth=2.829901 lightly_ddp_avg=1.414950 ratio=0.5000
For world_size=2, the ratio is 0.5000, exactly 1/2. Forward loss values at every rank equal the single-rank truth (the bug is gradient-only).
@IgorSusmelj @gabrielfruet could you take a look when you have a moment? Since you authored SIGReg in #1893, this would benefit from your read on the fix direction.
I can think of three options:
Option A: match the reference repo
import torch.distributed.nn as torch_dist_nn
# in _compute_cf_error_at_each_frequency, num_samples is now the LOCAL count:
cos_mean = x_t.cos().mean(-3)
sin_mean = x_t.sin().mean(-3)
if self.gather_distributed and lightly_dist.world_size() > 1:
cos_mean = torch_dist_nn.all_reduce(cos_mean, op=torch.distributed.ReduceOp.AVG)
sin_mean = torch_dist_nn.all_reduce(sin_mean, op=torch.distributed.ReduceOp.AVG)
phi = self.phi.to(dtype=x_t.dtype)
return (cos_mean - phi).square() + sin_mean.square()
# in _integrate_via_trapezoidal_rule, multiply by world_size to compensate
# AVG's 1/world_size factor in the autograd backward:
weights = self.weights.to(dtype=err_per_frequency.dtype)
world_size = lightly_dist.world_size() if self.gather_distributed else 1
statistic = (err_per_frequency @ weights) * num_samples * world_size
return statistic.mean()
# in forward: drop the num_samples_tensor all_reduce, num_samples stays
# as proj.size(-2) (the local count).
Pros:
- matches reference exactly,
- memory-efficient,
- only
(num_vectors, knots)reduced across ranks.
Cons: requires the * world_size factor with explanatory comment. (not really a con IMO)
Option B: use lightly's `GatherLayer` pattern
if self.gather_distributed and lightly_dist.world_size() > 1:
gathered = lightly_dist.gather(x_t) # autograd-aware via GatherLayer
x_t_global = torch.cat(gathered, dim=-3) # cat over the sample dim
else:
x_t_global = x_t
cos_sum = x_t_global.cos().sum(-3)
sin_sum = x_t_global.sin().sum(-3)
cos_mean = cos_sum / num_samples_global
sin_mean = sin_sum / num_samples_global
Pros: matches lightly's existing distributed pattern (NTXent, DCL, VICReg).
Cons: gathers the full (N_global, num_vectors, knots) x_t, higher memory and bandwidth.
Option C: minimal change, swap to autograd-aware SUM all_reduce
import torch.distributed.nn as torch_dist_nn
# in _compute_cf_error_at_each_frequency, two-line change:
cos_sum = x_t.cos().sum(-3)
sin_sum = x_t.sin().sum(-3)
if self.gather_distributed and lightly_dist.world_size() > 1:
cos_sum = torch_dist_nn.all_reduce(cos_sum) # autograd-aware, default SUM
sin_sum = torch_dist_nn.all_reduce(sin_sum)
cos_mean = cos_sum / num_samples
sin_mean = sin_sum / num_samples
Pros:
- smallest diff (effectively two lines),
- no
* world_sizecompensation factor, - preserves lightly's existing
num_samplesglobal handling andforwardflow.
Cons: uses SUM where the reference uses AVG, so structurally diverges from the reference (math is identical, just routed via _AllReduce.backward differently).
All three give the correct gradient under DDP averaging (verified numerically at world_size=2 and world_size=4). Concretely, Option B's per-rank bandwidth is ~N_local times more than A or C, since it gathers the full (N_local, num_vectors, knots) tensor rather than reducing the small (num_vectors, knots) tensor. With typical SSL defaults (N_local=128-256), that's a ~128-256x difference per rank.
My recommendation: Option C. Smallest change, simplest story, same performance as A. Option A is the strict reference-match if alignment with the paper authors' implementation matters more. Option B has the same correctness but a real bandwidth cost I'd avoid for SIGReg specifically.
Happy to send a PR, once the fix direction is confirmed.
Hi, I already read your report and solution.
I'll try to look more in depth early next week.
I didn't know that it wasn't autograd aware, thanks.
Very nice finding! Thank you.
You can go with the 3rd option, I think it's cleaner. Would be nice to have some tests on it, comparing distributed with non-distributed.
You can go with the 3rd option, I think it's cleaner. Would be nice to have some tests on it, comparing distributed with non-distributed.
Sure, will send a PR this week.