cyd0806 commited on
Commit
8aaa43c
·
verified ·
1 Parent(s): 9876d6c

Upload apex-master/tests/L0/run_mlp/test_mlp.py with huggingface_hub

Browse files
apex-master/tests/L0/run_mlp/test_mlp.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for c++ MLP"""
2
+ from itertools import product
3
+ from time import time
4
+
5
+ import torch
6
+ from torch import nn
7
+ from torch.testing._internal import common_utils
8
+ from torch.testing._internal.common_device_type import instantiate_device_type_tests
9
+ from torch.testing._internal.common_device_type import onlyCUDA
10
+
11
+ from apex.mlp import MLP
12
+
13
+
14
+ batch_size = 1024
15
+ mlp_sizes = [480, 1024, 1024, 512, 256, 1]
16
+ num_iters = 10
17
+
18
+
19
+ # note(crcrpar): On Ampere, this test should be run without TF32 enabled.
20
+ class TestMLP(common_utils.TestCase):
21
+ def test_creation(self):
22
+ MLP(mlp_sizes)
23
+
24
+ def test_numeric(self):
25
+ mlp = MLP(mlp_sizes).cuda()
26
+
27
+ mlp_layers = []
28
+ for i in range(mlp.num_layers):
29
+ linear = nn.Linear(mlp_sizes[i], mlp_sizes[i + 1])
30
+ with torch.no_grad():
31
+ mlp.weights[i].copy_(linear.weight)
32
+ mlp.biases[i].copy_(linear.bias)
33
+ mlp_layers.append(linear)
34
+ mlp_layers.append(nn.ReLU())
35
+
36
+ ref_mlp = nn.Sequential(*mlp_layers).cuda()
37
+
38
+ test_input = (
39
+ torch.empty(batch_size, mlp_sizes[0], device="cuda")
40
+ .uniform_(-1.0, 1.0)
41
+ .requires_grad_()
42
+ )
43
+ ref_input = test_input.clone().detach().requires_grad_()
44
+ mlp_out = mlp(test_input)
45
+ ref_out = ref_mlp(ref_input)
46
+ self.assertEqual(mlp_out, ref_out)
47
+
48
+ # Use mean value as scalar loss. Multiply 10 to make it big enough not zero out
49
+ mlp_out.mean().mul(10.0).backward()
50
+ ref_out.mean().mul(10.0).backward()
51
+ self.assertEqual(test_input.grad, ref_input.grad)
52
+ self.assertEqual(mlp.biases[0].grad, ref_mlp[0].bias.grad)
53
+
54
+ def _test_mlp_impl(self, use_activation: str, bias: bool, enable_autocast: bool):
55
+ mlp = MLP(mlp_sizes, bias=bias, activation=use_activation).cuda()
56
+
57
+ mlp_layers = []
58
+ for i in range(mlp.num_layers):
59
+ linear = nn.Linear(mlp_sizes[i], mlp_sizes[i + 1], bias=bias)
60
+ with torch.no_grad():
61
+ mlp.weights[i].copy_(linear.weight)
62
+ if bias:
63
+ mlp.biases[i].copy_(linear.bias)
64
+ mlp_layers.append(linear)
65
+ if use_activation == "relu":
66
+ mlp_layers.append(nn.ReLU())
67
+ if use_activation == "sigmoid":
68
+ mlp_layers.append(nn.Sigmoid())
69
+
70
+ ref_mlp = nn.Sequential(*mlp_layers).cuda()
71
+
72
+ test_input = (
73
+ torch.empty(batch_size, mlp_sizes[0], device="cuda")
74
+ .uniform_(-1.0, 1.0)
75
+ .requires_grad_()
76
+ )
77
+ ref_input = test_input.clone().detach().requires_grad_()
78
+
79
+ with torch.cuda.amp.autocast_mode.autocast(enabled=enable_autocast):
80
+ mlp_out = mlp(test_input)
81
+ mlp_loss = mlp_out.mean().mul(10.0)
82
+ # Use mean value as scalar loss. Multiply 10 to make it big enough not zero out
83
+ ref_out = ref_mlp(ref_input)
84
+ ref_loss = ref_out.mean().mul(10.0)
85
+
86
+ mlp_loss.backward()
87
+ ref_loss.backward()
88
+ if enable_autocast:
89
+ self.assertEqual(mlp_out.dtype, torch.float16)
90
+ self.assertEqual(ref_out.dtype, torch.float16)
91
+ else:
92
+ self.assertEqual(mlp_out, ref_out)
93
+ self.assertEqual(test_input.grad, ref_input.grad)
94
+ self.assertEqual(mlp.weights[0].grad, ref_mlp[0].weight.grad)
95
+
96
+ @common_utils.parametrize(
97
+ "use_activation,bias",
98
+ list(product(("none", "relu", "sigmoid"), (True, False))),
99
+ )
100
+ def test_mlp(self, use_activation: str, bias: bool):
101
+ self._test_mlp_impl(use_activation, bias, enable_autocast=False)
102
+
103
+ @common_utils.parametrize(
104
+ "use_activation,bias",
105
+ list(product(("none", "relu", "sigmoid"), (True, False))),
106
+ )
107
+ def test_mlp_autocast_fp16(self, use_activation: str, bias: bool):
108
+ self._test_mlp_impl(use_activation, bias, enable_autocast=True)
109
+
110
+ def test_no_grad(self):
111
+ mlp = MLP(mlp_sizes).cuda()
112
+
113
+ mlp_layers = []
114
+ for i in range(mlp.num_layers):
115
+ linear = nn.Linear(mlp_sizes[i], mlp_sizes[i + 1])
116
+ with torch.no_grad():
117
+ mlp.weights[i].copy_(linear.weight)
118
+ mlp.biases[i].copy_(linear.bias)
119
+ mlp_layers.append(linear)
120
+ mlp_layers.append(nn.ReLU(inplace=True))
121
+
122
+ ref_mlp = nn.Sequential(*mlp_layers).cuda()
123
+
124
+ test_input = torch.empty(batch_size, mlp_sizes[0], device="cuda").uniform_(-1.0, 1.0)
125
+ ref_input = test_input.clone().detach()
126
+ mlp_out = mlp(test_input)
127
+ ref_out = ref_mlp(ref_input)
128
+ self.assertEqual(mlp_out, ref_out)
129
+
130
+ # Use mean value as scalar loss. Multiply 10 to make it big enough not zero out
131
+ mlp_out.mean().mul(10.0).backward()
132
+ ref_out.mean().mul(10.0).backward()
133
+ self.assertEqual(mlp.weights[0].grad, ref_mlp[0].weight.grad)
134
+
135
+ def test_performance_half(self):
136
+ mlp = MLP(mlp_sizes).cuda().half()
137
+
138
+ mlp_layers = []
139
+ for i in range(mlp.num_layers):
140
+ linear = nn.Linear(mlp_sizes[i], mlp_sizes[i + 1])
141
+ mlp.weights[i].data.copy_(linear.weight)
142
+ mlp.biases[i].data.copy_(linear.bias)
143
+ mlp_layers.append(linear)
144
+ mlp_layers.append(nn.ReLU(inplace=True))
145
+
146
+ ref_mlp = nn.Sequential(*mlp_layers).cuda().half()
147
+
148
+ test_input = (
149
+ torch.empty(batch_size, mlp_sizes[0], device="cuda", dtype=torch.half)
150
+ .fill_(10.0)
151
+ .requires_grad_()
152
+ )
153
+ ref_input = (
154
+ torch.empty(batch_size, mlp_sizes[0], device="cuda", dtype=torch.half)
155
+ .fill_(10.0)
156
+ .requires_grad_()
157
+ )
158
+
159
+ # Warm up GPU
160
+ for _ in range(100):
161
+ ref_out = ref_mlp(ref_input)
162
+ ref_loss = ref_out.mean()
163
+ ref_mlp.zero_grad()
164
+ ref_loss.backward()
165
+ mlp_out = mlp(test_input)
166
+ test_loss = mlp_out.mean()
167
+ mlp.zero_grad()
168
+ test_loss.backward()
169
+
170
+ torch.cuda.profiler.start()
171
+ torch.cuda.synchronize()
172
+ start_time = time()
173
+ for _ in range(num_iters):
174
+ ref_out = ref_mlp(ref_input)
175
+ ref_loss = ref_out.mean()
176
+ ref_mlp.zero_grad()
177
+ ref_loss.backward()
178
+ torch.cuda.synchronize()
179
+ stop_time = time()
180
+ ref_time = (stop_time - start_time) * 1000.0 / num_iters
181
+ print(f"\nPytorch MLP time {ref_time:.4f} ms")
182
+
183
+ torch.cuda.synchronize()
184
+ start_time = time()
185
+ for _ in range(num_iters):
186
+ mlp_out = mlp(test_input)
187
+ test_loss = mlp_out.mean()
188
+ mlp.zero_grad()
189
+ test_loss.backward()
190
+ torch.cuda.synchronize()
191
+ stop_time = time()
192
+ actual_time = (stop_time - start_time) * 1000.0 / num_iters
193
+ print(f"C++ MLP time {actual_time:.4f} ms")
194
+ torch.cuda.profiler.stop()
195
+ self.assertLessEqual(
196
+ actual_time,
197
+ ref_time,
198
+ msg=f"Custom extension took {actual_time:.4f} while PyTorch took {ref_time:.4f}",
199
+ )
200
+
201
+
202
+ instantiate_device_type_tests(TestMLP, globals(), only_for=("cuda",))
203
+
204
+
205
+ if __name__ == "__main__":
206
+ common_utils.run_tests()