cyd0806 commited on
Commit
960e7c9
·
verified ·
1 Parent(s): ecd4722

Upload apex-master/tests/distributed/synced_batchnorm/two_gpu_unit_test.py with huggingface_hub

Browse files
apex-master/tests/distributed/synced_batchnorm/two_gpu_unit_test.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import apex
4
+ import syncbn
5
+ import os
6
+ import argparse
7
+ import torch.optim as optim
8
+
9
+ def compare(desc, inp1, inp2, error):
10
+ a = inp1.clone().detach().cpu().numpy()
11
+ b = inp2.clone().detach().cpu().numpy()
12
+ close = np.allclose(a,b, error, error)
13
+ if not close:
14
+ print(desc, close)
15
+ z = a - b
16
+ index = (np.abs(z) >= error + error * np.abs(b)).nonzero()
17
+ print("dif : ", z[index])
18
+ print("inp1 : ", a[index])
19
+ print("inp2 : ", b[index])
20
+ return close
21
+
22
+ feature_size = 10
23
+ space_size = 40
24
+ batch_size = 32
25
+
26
+
27
+ from apex.parallel import DistributedDataParallel as DDP
28
+ parser = argparse.ArgumentParser()
29
+ parser.add_argument("--local_rank", default=0, type=int)
30
+ parser.add_argument("--fp16", action='store_true', default=False)
31
+ parser.add_argument("--fp64", action='store_true', default=False)
32
+ args = parser.parse_args()
33
+ args.world_size = int(os.environ['WORLD_SIZE'])
34
+ torch.cuda.set_device(args.local_rank)
35
+ torch.distributed.init_process_group(backend='nccl', init_method='env://')
36
+ start = args.local_rank * batch_size//args.world_size
37
+ finish = (args.local_rank + 1) * batch_size//args.world_size
38
+
39
+ error = 1e-5
40
+ dtype = np.float32
41
+ if args.fp16:
42
+ error = 1e-3
43
+ dtype = np.float16
44
+ elif args.fp64:
45
+ error = 1e-8
46
+ dtype = np.float64
47
+
48
+ np.random.seed(18)
49
+ inp = np.random.randn(batch_size, feature_size, space_size, space_size).astype(dtype)
50
+ grad = np.random.randn(batch_size, feature_size, space_size, space_size).astype(dtype)
51
+ weight = np.random.randn(feature_size).astype(dtype)
52
+ bias = np.random.randn(feature_size).astype(dtype)
53
+
54
+
55
+ type_tensor = torch.cuda.FloatTensor
56
+ if args.fp16:
57
+ type_tensor = torch.cuda.HalfTensor
58
+ if args.fp64:
59
+ type_tensor = torch.cuda.DoubleTensor
60
+
61
+ ref_tensor = torch.cuda.DoubleTensor
62
+
63
+ inp_t = type_tensor(inp)
64
+ weight_t = type_tensor(weight)
65
+ bias_t = type_tensor(bias)
66
+
67
+ inp_r = ref_tensor(inp.transpose(1, 0, 2, 3).reshape(feature_size, -1))
68
+ inp2_r = ref_tensor(inp)
69
+ weight_r = ref_tensor(weight).view(-1, 1, 1)
70
+ bias_r = ref_tensor(bias).view(-1, 1, 1)
71
+
72
+ grad_output_t = type_tensor(grad)
73
+
74
+ m = inp_r.mean(1)
75
+ b_v = inp_r.var(1, unbiased=False)
76
+ unb_v = inp_r.var(1, unbiased=True)
77
+
78
+ eps = 1e-5
79
+
80
+ mean, var_biased = syncbn.welford_mean_var(inp_t)
81
+ inv_std = 1.0 / torch.sqrt(var_biased + eps)
82
+
83
+ bn = torch.nn.BatchNorm2d(feature_size).cuda()
84
+ bn.momentum = 1.0
85
+ bn.weight.data = weight_t.clone()
86
+ bn.bias.data = bias_t.clone()
87
+ if args.fp16:
88
+ bn.half()
89
+ if args.fp64:
90
+ bn.double()
91
+ inp_bn = inp_t.clone().requires_grad_()
92
+ grad_bn = grad_output_t.clone().detach()
93
+ out_bn = bn(inp_bn)
94
+ out_bn.backward(grad_bn)
95
+ # compensating the averaging over processes done by DDP
96
+ # in order to produce mathematically equivalent result
97
+ # https://github.com/NVIDIA/apex/issues/134#issuecomment-458307368
98
+ for param in bn.parameters():
99
+ param.grad = param.grad / args.world_size
100
+ bn_opt = optim.SGD(bn.parameters(), lr=1.0)
101
+
102
+ sbn = apex.parallel.SyncBatchNorm(feature_size).cuda()
103
+ sbn.momentum = 1.0
104
+ sbn.weight.data = weight_t.clone()
105
+ sbn.bias.data = bias_t.clone()
106
+ if args.fp16:
107
+ sbn.half()
108
+ if args.fp64:
109
+ sbn.double()
110
+ sbn = DDP(sbn)
111
+ sbn_opt = optim.SGD(sbn.parameters(), lr=1.0)
112
+ inp_sbn = inp_t.clone().requires_grad_()
113
+ grad_sbn = grad_output_t.clone().detach()
114
+ out_sbn = sbn(inp_sbn[start:finish])
115
+ out_sbn.backward(grad_sbn[start:finish])
116
+
117
+ count = [ space_size**2 * ( (i+1) * batch_size // args.world_size - i * batch_size // args.world_size ) for i in range(0, args.world_size)]
118
+ count = torch.cuda.IntTensor(count)
119
+
120
+ print("--- count : " , count)
121
+
122
+ sbn_result = True
123
+ bn_result = True
124
+
125
+ if args.local_rank == 0:
126
+ sbn_result = compare("comparing mean: ", mean, m, error) and sbn_result
127
+ sbn_result = compare("comparing biased variance: ", var_biased, b_v, error) and sbn_result
128
+
129
+ out = syncbn.batchnorm_forward(inp_t, mean, inv_std, weight_t, bias_t)
130
+ out_r = weight_r * (inp2_r - m.view(-1, 1, 1)) * torch.rsqrt(b_v.view(-1,1,1) + eps) + bias_r
131
+
132
+ if args.local_rank == 0:
133
+ sbn_result = compare("comparing output: ", out, out_r, error) and sbn_result
134
+ compare("comparing bn output: ", out_bn, out_r, error)
135
+
136
+ grad_output_t = type_tensor(grad)
137
+
138
+ grad_output_r = ref_tensor(grad.transpose(1, 0, 2, 3).reshape(feature_size, -1))
139
+ grad_output2_r = ref_tensor(grad)
140
+
141
+ grad_bias_r = grad_output_r.sum(1)
142
+ grad_weight_r = ((inp2_r - m.view(-1, 1, 1)) * torch.rsqrt(b_v.view(-1,1,1) + eps) * grad_output2_r).transpose(1,0).contiguous().view(feature_size, -1).sum(1)
143
+
144
+ sum_dy_r = grad_output_r.sum(1)
145
+ mean_dy_r = grad_output_r.mean(1)
146
+ mean_dy_xmu_r = ((inp2_r - m.view(-1, 1, 1)) * grad_output2_r).transpose(1,0).contiguous().view(feature_size, -1).mean(1)
147
+ sum_dy_xmu_r = ((inp2_r - m.view(-1, 1, 1)) * grad_output2_r).transpose(1,0).contiguous().view(feature_size, -1).sum(1)
148
+
149
+ grad_input_r = (grad_output2_r - mean_dy_r.view(-1, 1, 1) - (inp2_r - m.view(-1, 1, 1)) / (b_v.view(-1,1,1) + eps) * mean_dy_xmu_r.view(-1, 1, 1) ) * torch.rsqrt(b_v.view(-1,1,1) + eps) * weight_r.view(-1,1,1)
150
+
151
+ sum_dy, sum_dy_xmu, grad_weight, grad_bias = syncbn.reduce_bn(grad_output_t, inp_t, mean, inv_std, weight_t)
152
+ grad_input = syncbn.batchnorm_backward(grad_output_t, inp_t, mean, inv_std, weight_t, sum_dy, sum_dy_xmu, count)
153
+ if args.local_rank == 0:
154
+ sbn_result = compare("comparing bias grad: ", grad_bias, grad_bias_r, error) and sbn_result
155
+ sbn_result = compare("comparing weight grad: ", grad_weight, grad_weight_r, error) and sbn_result
156
+ sbn_result = compare("comparing sum_dy grad: ", sum_dy, sum_dy_r, error) and sbn_result
157
+ sbn_result = compare("comparing sum_dy_xmu grad: ", sum_dy_xmu, sum_dy_xmu_r, error) and sbn_result
158
+ sbn_result = compare("comparing input grad: ", grad_input, grad_input_r, error) and sbn_result
159
+ compare("comparing bn input grad: ", inp_bn.grad, grad_input_r, error)
160
+
161
+ if args.local_rank == 0:
162
+ sbn_result = compare("comparing running_mean: ", bn.running_mean.data, sbn.module.running_mean.data, error) and sbn_result
163
+ sbn_result = compare("comparing running_variance: ", bn.running_var.data, sbn.module.running_var.data, error) and sbn_result
164
+
165
+ # execute by both
166
+ compare("comparing layers output: ", out_bn[start:finish], out_sbn, error) and sbn_result
167
+ compare("comparing layers grad_input: ", inp_bn.grad[start:finish], inp_sbn.grad[start:finish], error) and sbn_result
168
+
169
+ bn_opt.step()
170
+ sbn_opt.step()
171
+
172
+ if args.local_rank == 0:
173
+ compare("comparing bn vs sbn bias: ", bn.bias, sbn.module.bias, error)
174
+ compare("comparing bn vs sbn weight: ", bn.weight, sbn.module.weight, error)
175
+
176
+
177
+ if sbn_result:
178
+ print("====SBN two gpu passed tests")
179
+ else:
180
+ print("*SBN two gpu failed*")