-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshard.py
53 lines (41 loc) · 1.57 KB
/
shard.py
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from typing import Callable, Dict
import ray
import torch
@ray.remote
class Shard:
def __init__(self, module_creator: Callable, lr=0.1):
self._module = module_creator()
self._optimizer = torch.optim.AdamW(self._module.parameters(), lr=lr)
# For forward and backward passes.
self._inputs: Dict[str, torch.Tensor] = {}
self._outputs: Dict[str, torch.Tensor] = {}
def forward(self, inputs):
self._inputs = inputs
self._outputs = self._module(**inputs)
return {
k: (v.detach() if isinstance(v, torch.Tensor) else v)
for k, v in self._outputs.items()
}
def backward(self, gradients):
def _requires_grad(v):
return isinstance(v, torch.Tensor) and v.requires_grad
if not gradients:
assert "loss" in self._outputs
# Last layer. Backward with loss tensor.
self._outputs["loss"].backward()
else:
# Non-last layer. Backward with gradients from next shard.
assert set(self._outputs.keys()) == set(gradients.keys())
# Run backward passes.
for k, output in self._outputs.items():
if not _requires_grad(output):
continue
output.backward(gradient=gradients[k])
# Return accumulated gradients on the input tensors.
return {
k: (v.grad.data if _requires_grad(v) else v)
for k, v in self._inputs
}
def step(self):
self._optimizer.step()
self._optimizer.zero_grad()