dim=-1,
mesh=mesh,
mesh_dim=0,
)
local_probabilities = local_log_probs.exp()
local_entropy = -(local_probabilities * local_log_probs).sum(dim=-1)
torch.distributed.all_reduce(local_entropy, group=mesh.get_group())
entropy[start : start + len(values)] = local_entropy
if needs_backward:
ctx.save_for_backward(logits, entropy)
ctx.mesh = mesh
ctx.chunk_size = chunk_size
return entropy.reshape(logits.shape[:-1])
@staticmethod
def backward(ctx: Any, grad_output: Tensor) -> Tuple[Tensor, None, None]:
"""Recompute local probabilities and return the logits-shard gradient."""
logits, entropy = ctx.saved_tensors
flat = logits.reshape(-1, logits.shape[-1])
gradient = torch.empty_like(flat)
grad = grad_output.reshape(-1)
for start in range(0, flat.shape[0], ctx.chunk_size):
end = start + ctx.chunk_size
log_probs = distributed_log_softmax(
flat[start:end].float(),
dim=-1,
mesh=ctx.mesh,
mesh_dim=0,