-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils.py
More file actions
36 lines (27 loc) · 1 KB
/
utils.py
File metadata and controls
36 lines (27 loc) · 1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from typing import Any, Optional, Tuple
import torch
class AllGatherGrad(torch.autograd.Function):
# stolen from pytorch lightning
@staticmethod
def forward(
ctx: Any,
tensor: torch.Tensor,
group: Optional["torch.distributed.ProcessGroup"] = None,
) -> torch.Tensor:
ctx.group = group
gathered_tensor = [
torch.zeros_like(tensor) for _ in range(torch.distributed.get_world_size())
]
torch.distributed.all_gather(gathered_tensor, tensor, group=group)
gathered_tensor = torch.stack(gathered_tensor, dim=0)
return gathered_tensor
@staticmethod
def backward(ctx: Any, *grad_output: torch.Tensor) -> Tuple[torch.Tensor, None]:
grad_output = torch.cat(grad_output)
torch.distributed.all_reduce(
grad_output,
op=torch.distributed.ReduceOp.SUM,
async_op=False,
group=ctx.group,
)
return grad_output[torch.distributed.get_rank()], None