-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathalgo.py
More file actions
201 lines (172 loc) · 7.71 KB
/
algo.py
File metadata and controls
201 lines (172 loc) · 7.71 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import torch
class Sort:
def sort(self) -> None:
"""Resets variables and returns the sorted order of the gradients."""
raise NotImplementedError()
class GraB(Sort):
def __init__(self, n: int, d: int, device: str = None) -> None:
self.n = n
self.d = d
self.avg_grad = torch.zeros(d, device=device)
self.cur_sum = torch.zeros_like(self.avg_grad)
self.next_epoch_avg_grad = torch.zeros_like(self.avg_grad)
self.orders = torch.arange(self.n, device=device, dtype=torch.int64)
self.next_orders = self.orders.clone()
self.left_ptr = 0
self.right_ptr = self.n - 1
@torch.no_grad()
def sort(self) -> torch.Tensor:
"""Resets variables and returns the sorted order of the gradients."""
self.avg_grad.copy_(self.next_epoch_avg_grad / self.n)
self.next_epoch_avg_grad.zero_()
self.cur_sum.zero_()
self.left_ptr = 0
self.right_ptr = self.n - 1
self.orders = self.next_orders
self.next_orders = torch.zeros_like(self.next_orders)
return self.orders.clone()
@torch.no_grad()
def single_step(self, g: torch.Tensor, idx: int) -> None:
"""Updates the sorted order of the gradients with a single gradient pair."""
self.next_epoch_avg_grad.add_(g)
g = g - self.avg_grad
if torch.inner(self.cur_sum, g) <= 0:
self.next_orders[self.left_ptr] = self.orders[idx]
self.left_ptr += 1
self.cur_sum.add_(g)
else:
self.next_orders[self.right_ptr] = self.orders[idx]
self.right_ptr -= 1
self.cur_sum.sub_(g)
@torch.no_grad()
def step(self, batch_grads: torch.Tensor, batch_idx: int) -> None:
"""Updates the sorted order of the gradients with a batch of gradients."""
for i, idx in enumerate(batch_idx):
self.single_step(batch_grads[i], idx)
class GraB_Single(Sort):
def __init__(self, n: int, d: int, device: str = None) -> None:
self.n = n
self.d = d
self.avg_grad = torch.zeros(d, device=device)
self.cur_sum = torch.zeros_like(self.avg_grad)
self.next_epoch_avg_grad = torch.zeros_like(self.avg_grad)
self.orders = torch.randperm(self.n, device=device, dtype=torch.int64)
self.next_orders = self.orders.clone()
self.left_ptr = 0
self.right_ptr = self.n - 1
@torch.no_grad()
def sort(self) -> torch.Tensor:
"""Resets variables and returns the sorted order of the gradients."""
self.avg_grad.copy_(self.next_epoch_avg_grad / self.n)
self.next_epoch_avg_grad.zero_()
self.cur_sum.zero_()
self.left_ptr = 0
self.right_ptr = self.n - 1
self.orders = self.next_orders
self.next_orders = torch.zeros_like(self.next_orders)
return self.orders.clone()
@torch.no_grad()
def step(self, g: torch.Tensor, idx: int) -> None:
"""Updates the sorted order of the gradients with a single gradient pair."""
self.next_epoch_avg_grad.add_(g)
g = g - self.avg_grad
if torch.inner(self.cur_sum, g) <= 0:
self.next_orders[self.left_ptr] = self.orders[idx]
self.left_ptr += 1
self.cur_sum.add_(g)
else:
self.next_orders[self.right_ptr] = self.orders[idx]
self.right_ptr -= 1
self.cur_sum.sub_(g)
class RandomShuffle(Sort):
def __init__(self, num_batches: int, device: str = None) -> None:
super().__init__()
self.device = device
self.num_batches = num_batches
def step(self, *args: str, **kw: int) -> None:
"""Random does not require sorting decisions. Do nothing."""
pass
def sort(self, *args: str, **kw: int) -> torch.Tensor:
"""Returns a random permutation of the batch indices."""
return torch.randperm(self.num_batches, device=self.device)
class PairBalance_Sorter(Sort):
def __init__(self, n: int, d: int, device: str = None) -> None:
assert n % 2 == 0, "pair balance only supports even number"
self.n = n
self.d = d
self.device = device
self.run_pair_diff_sum = torch.zeros(d, device=device)
self.next_orders = torch.arange(n, device=device, dtype=torch.int64)
self.orders = self.next_orders.clone()
self.left_ptr, self.right_ptr = 0, self.n - 1
@torch.no_grad()
# cur_grad: B, d
def step(self, batch_grads: torch.Tensor, batch_idx: int) -> None:
"""Updates the sorted order of the gradients with a batch of gradients.
Args:
batch_grads: microbatch gradients from each node (shape = (B, d). Assumes batch_grads has even number of examples.
batch_idx: range of indices in this node's microbatch (e.g., torch.arange(idx, min(idx + microbatch, d_trainset_X.shape[1]), device=device))
"""
B = len(batch_idx)
batch_grads = batch_grads[0:B:2] - batch_grads[1:B:2]
for i, (idx_1, idx_2) in enumerate(batch_idx.view(B // 2, 2)):
pair_diff = batch_grads[i]
if torch.inner(self.run_pair_diff_sum, pair_diff) <= 0:
self.next_orders[self.left_ptr] = self.orders[idx_1]
self.next_orders[self.right_ptr] = self.orders[idx_2]
self.run_pair_diff_sum.add_(pair_diff)
else:
self.next_orders[self.right_ptr] = self.orders[idx_1]
self.next_orders[self.left_ptr] = self.orders[idx_2]
self.run_pair_diff_sum.sub_(pair_diff)
self.left_ptr += 1
self.right_ptr -= 1
@torch.no_grad()
def sort(self) -> torch.Tensor:
"""Resets variables and returns the sorted order of the gradients."""
self.left_ptr = 0
self.right_ptr = self.n - 1
self.orders = self.next_orders
self.next_orders = torch.zeros_like(self.next_orders)
self.run_pair_diff_sum.zero_()
return self.orders.clone()
class PairBalance_Single(Sort):
def __init__(self, n: int, d: int, device: str = None) -> None:
assert n % 2 == 0, "pair balance only supports even number"
self.n = n
self.d = d
self.device = device
self.run_pair_diff_sum = torch.zeros(d, device=device)
self.next_orders = torch.randperm(n, device=device, dtype=torch.int64)
self.orders = self.next_orders.clone()
self.left_ptr, self.right_ptr = 0, self.n - 1
@torch.no_grad()
def step(self, g: torch.Tensor, idx: int) -> None:
"""Updates the sorted order of the gradients with a single gradient pair.
Args:
g: gradient pair from a node (shape = (d))
idx: index of the gradient pair in the node's microbatch
"""
if idx % 2 == 0:
self.cache = g.clone()
else:
self.cache = self.cache - g
if torch.inner(self.run_pair_diff_sum, self.cache) <= 0:
self.next_orders[self.left_ptr] = self.orders[idx - 1]
self.next_orders[self.right_ptr] = self.orders[idx]
self.run_pair_diff_sum.add_(self.cache)
else:
self.next_orders[self.right_ptr] = self.orders[idx - 1]
self.next_orders[self.left_ptr] = self.orders[idx]
self.run_pair_diff_sum.sub_(self.cache)
self.left_ptr += 1
self.right_ptr -= 1
@torch.no_grad()
def sort(self) -> torch.Tensor:
"""Resets variables and returns the sorted order of the gradients."""
self.left_ptr = 0
self.right_ptr = self.n - 1
self.orders = self.next_orders
self.next_orders = torch.zeros_like(self.next_orders)
self.run_pair_diff_sum.zero_()
return self.orders.clone()