-
Notifications
You must be signed in to change notification settings - Fork 449
/
Copy pathtest_utils.py
467 lines (389 loc) · 15 KB
/
test_utils.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
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
import pytest
from fastNLP.envs.imports import _NEED_IMPORT_JITTOR, _NEED_IMPORT_PADDLE, _NEED_IMPORT_TORCH
from fastNLP.modules.mix_modules.utils import (
paddle2torch,
torch2paddle,
jittor2torch,
torch2jittor,
)
if _NEED_IMPORT_TORCH:
import torch
if _NEED_IMPORT_PADDLE:
import paddle
if _NEED_IMPORT_JITTOR:
import jittor
############################################################################
#
# 测试paddle到torch的转换
#
############################################################################
@pytest.mark.torchpaddle
class TestPaddle2Torch:
def check_torch_tensor(self, tensor, device, requires_grad):
"""
检查张量设备和梯度情况的工具函数
"""
assert isinstance(tensor, torch.Tensor)
if device == "cpu":
assert not tensor.is_cuda
else:
assert tensor.is_cuda
assert tensor.device.index == torch.device(device).index
assert tensor.requires_grad == requires_grad
def test_gradient(self):
"""
测试张量转换后的反向传播是否正确
"""
x = paddle.to_tensor([1.0, 2.0, 3.0, 4.0, 5.0], stop_gradient=False)
y = paddle2torch(x)
z = 3 * (y ** 2)
z.sum().backward()
assert y.grad.tolist() == [6, 12, 18, 24, 30]
def test_tensor_transfer(self):
"""
测试单个张量的设备和梯度转换是否正确
"""
paddle_tensor = paddle.rand((3, 4, 5)).cpu()
res = paddle2torch(paddle_tensor)
self.check_torch_tensor(res, "cpu", not paddle_tensor.stop_gradient)
res = paddle2torch(paddle_tensor, device="cuda:2", no_gradient=None)
self.check_torch_tensor(res, "cuda:2", not paddle_tensor.stop_gradient)
res = paddle2torch(paddle_tensor, device="cuda:1", no_gradient=True)
self.check_torch_tensor(res, "cuda:1", False)
res = paddle2torch(paddle_tensor, device="cuda:1", no_gradient=False)
self.check_torch_tensor(res, "cuda:1", True)
def test_list_transfer(self):
"""
测试张量列表的转换
"""
paddle_list = [paddle.rand((6, 4, 2)).cuda(1) for i in range(10)]
res = paddle2torch(paddle_list)
assert isinstance(res, list)
for t in res:
self.check_torch_tensor(t, "cuda:1", False)
res = paddle2torch(paddle_list, device="cpu", no_gradient=False)
assert isinstance(res, list)
for t in res:
self.check_torch_tensor(t, "cpu", True)
def test_tensor_tuple_transfer(self):
"""
测试张量元组的转换
"""
paddle_list = [paddle.rand((6, 4, 2)).cuda(1) for i in range(10)]
paddle_tuple = tuple(paddle_list)
res = paddle2torch(paddle_tuple)
assert isinstance(res, tuple)
for t in res:
self.check_torch_tensor(t, "cuda:1", False)
def test_dict_transfer(self):
"""
测试包含复杂结构的字典的转换
"""
paddle_dict = {
"tensor": paddle.rand((3, 4)).cuda(0),
"list": [paddle.rand((6, 4, 2)).cuda(0) for i in range(10)],
"dict":{
"list": [paddle.rand((6, 4, 2)).cuda(0) for i in range(10)],
"tensor": paddle.rand((3, 4)).cuda(0)
},
"int": 2,
"string": "test string"
}
res = paddle2torch(paddle_dict)
assert isinstance(res, dict)
self.check_torch_tensor(res["tensor"], "cuda:0", False)
assert isinstance(res["list"], list)
for t in res["list"]:
self.check_torch_tensor(t, "cuda:0", False)
assert isinstance(res["int"], int)
assert isinstance(res["string"], str)
assert isinstance(res["dict"], dict)
assert isinstance(res["dict"]["list"], list)
for t in res["dict"]["list"]:
self.check_torch_tensor(t, "cuda:0", False)
self.check_torch_tensor(res["dict"]["tensor"], "cuda:0", False)
############################################################################
#
# 测试torch到paddle的转换
#
############################################################################
@pytest.mark.torchpaddle
class TestTorch2Paddle:
def check_paddle_tensor(self, tensor, device, stop_gradient):
"""
检查得到的paddle张量设备和梯度情况的工具函数
"""
assert isinstance(tensor, paddle.Tensor)
if device == "cpu":
assert tensor.place.is_cpu_place()
elif device.startswith("gpu"):
paddle_device = paddle.device._convert_to_place(device)
assert tensor.place.is_gpu_place()
if hasattr(tensor.place, "gpu_device_id"):
# paddle中,有两种Place
# paddle.fluid.core.Place是创建Tensor时使用的类型
# 有函数gpu_device_id获取设备
assert tensor.place.gpu_device_id() == paddle_device.get_device_id()
else:
# 通过_convert_to_place得到的是paddle.CUDAPlace
# 通过get_device_id获取设备
assert tensor.place.get_device_id() == paddle_device.get_device_id()
else:
raise NotImplementedError
assert tensor.stop_gradient == stop_gradient
def test_gradient(self):
"""
测试转换后梯度的反向传播
"""
x = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0], requires_grad=True)
y = torch2paddle(x)
z = 3 * (y ** 2)
z.sum().backward()
assert y.grad.tolist() == [6, 12, 18, 24, 30]
def test_tensor_transfer(self):
"""
测试单个张量的转换
"""
torch_tensor = torch.rand((3, 4, 5))
res = torch2paddle(torch_tensor)
self.check_paddle_tensor(res, "cpu", True)
res = torch2paddle(torch_tensor, device="gpu:2", no_gradient=None)
self.check_paddle_tensor(res, "gpu:2", True)
res = torch2paddle(torch_tensor, device="gpu:2", no_gradient=True)
self.check_paddle_tensor(res, "gpu:2", True)
res = torch2paddle(torch_tensor, device="gpu:2", no_gradient=False)
self.check_paddle_tensor(res, "gpu:2", False)
def test_tensor_list_transfer(self):
"""
测试张量列表的转换
"""
torch_list = [torch.rand(6, 4, 2) for i in range(10)]
res = torch2paddle(torch_list)
assert isinstance(res, list)
for t in res:
self.check_paddle_tensor(t, "cpu", True)
res = torch2paddle(torch_list, device="gpu:1", no_gradient=False)
assert isinstance(res, list)
for t in res:
self.check_paddle_tensor(t, "gpu:1", False)
def test_tensor_tuple_transfer(self):
"""
测试张量元组的转换
"""
torch_list = [torch.rand(6, 4, 2) for i in range(10)]
torch_tuple = tuple(torch_list)
res = torch2paddle(torch_tuple, device="cpu")
assert isinstance(res, tuple)
for t in res:
self.check_paddle_tensor(t, "cpu", True)
def test_dict_transfer(self):
"""
测试复杂的字典结构的转换
"""
torch_dict = {
"tensor": torch.rand((3, 4)),
"list": [torch.rand(6, 4, 2) for i in range(10)],
"dict":{
"list": [torch.rand(6, 4, 2) for i in range(10)],
"tensor": torch.rand((3, 4))
},
"int": 2,
"string": "test string"
}
res = torch2paddle(torch_dict)
assert isinstance(res, dict)
self.check_paddle_tensor(res["tensor"], "cpu", True)
assert isinstance(res["list"], list)
for t in res["list"]:
self.check_paddle_tensor(t, "cpu", True)
assert isinstance(res["int"], int)
assert isinstance(res["string"], str)
assert isinstance(res["dict"], dict)
assert isinstance(res["dict"]["list"], list)
for t in res["dict"]["list"]:
self.check_paddle_tensor(t, "cpu", True)
self.check_paddle_tensor(res["dict"]["tensor"], "cpu", True)
############################################################################
#
# 测试jittor到torch的转换
#
############################################################################
@pytest.mark.torchjittor
class TestJittor2Torch:
def check_torch_tensor(self, tensor, device, requires_grad):
"""
检查得到的torch张量的工具函数
"""
assert isinstance(tensor, torch.Tensor)
if device == "cpu":
assert not tensor.is_cuda
else:
assert tensor.is_cuda
assert tensor.device.index == torch.device(device).index
assert tensor.requires_grad == requires_grad
def test_var_transfer(self):
"""
测试单个Jittor Var的转换
"""
jittor_var = jittor.rand((3, 4, 5))
res = jittor2torch(jittor_var)
if jittor.flags.use_cuda:
self.check_torch_tensor(res, "cuda:0", True)
else:
self.check_torch_tensor(res, "cpu", True)
res = jittor2torch(jittor_var, device="cuda:2", no_gradient=None)
self.check_torch_tensor(res, "cuda:2", True)
res = jittor2torch(jittor_var, device="cuda:2", no_gradient=True)
self.check_torch_tensor(res, "cuda:2", False)
res = jittor2torch(jittor_var, device="cuda:2", no_gradient=False)
self.check_torch_tensor(res, "cuda:2", True)
def test_var_list_transfer(self):
"""
测试Jittor列表的转换
"""
jittor_list = [jittor.rand((6, 4, 2)) for i in range(10)]
res = jittor2torch(jittor_list)
assert isinstance(res, list)
for t in res:
if jittor.flags.use_cuda:
self.check_torch_tensor(t, "cuda:0", True)
else:
self.check_torch_tensor(t, "cpu", True)
res = jittor2torch(jittor_list, device="cuda:1", no_gradient=False)
assert isinstance(res, list)
for t in res:
self.check_torch_tensor(t, "cuda:1", True)
def test_var_tuple_transfer(self):
"""
测试Jittor变量元组的转换
"""
jittor_list = [jittor.rand((6, 4, 2)) for i in range(10)]
jittor_tuple = tuple(jittor_list)
res = jittor2torch(jittor_tuple, device="cpu")
assert isinstance(res, tuple)
for t in res:
self.check_torch_tensor(t, "cpu", True)
def test_dict_transfer(self):
"""
测试字典结构的转换
"""
jittor_dict = {
"tensor": jittor.rand((3, 4)),
"list": [jittor.rand(6, 4, 2) for i in range(10)],
"dict":{
"list": [jittor.rand(6, 4, 2) for i in range(10)],
"tensor": jittor.rand((3, 4))
},
"int": 2,
"string": "test string"
}
res = jittor2torch(jittor_dict)
assert isinstance(res, dict)
if jittor.flags.use_cuda:
self.check_torch_tensor(res["tensor"], "cuda:0", True)
else:
self.check_torch_tensor(res["tensor"], "cpu", True)
assert isinstance(res["list"], list)
for t in res["list"]:
if jittor.flags.use_cuda:
self.check_torch_tensor(t, "cuda:0", True)
else:
self.check_torch_tensor(t, "cpu", True)
assert isinstance(res["int"], int)
assert isinstance(res["string"], str)
assert isinstance(res["dict"], dict)
assert isinstance(res["dict"]["list"], list)
for t in res["dict"]["list"]:
if jittor.flags.use_cuda:
self.check_torch_tensor(t, "cuda:0", True)
else:
self.check_torch_tensor(t, "cpu", True)
if jittor.flags.use_cuda:
self.check_torch_tensor(res["dict"]["tensor"], "cuda:0", True)
else:
self.check_torch_tensor(res["dict"]["tensor"], "cpu", True)
############################################################################
#
# 测试torch到jittor的转换
#
############################################################################
@pytest.mark.torchjittor
class TestTorch2Jittor:
def check_jittor_var(self, var, requires_grad):
"""
检查得到的Jittor Var梯度情况的工具函数
"""
assert isinstance(var, jittor.Var)
assert var.requires_grad == requires_grad
def test_gradient(self):
"""
测试反向传播的梯度
"""
x = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0], requires_grad=True)
y = torch2jittor(x)
z = 3 * (y ** 2)
grad = jittor.grad(z, y)
assert grad.tolist() == [6.0, 12.0, 18.0, 24.0, 30.0]
def test_tensor_transfer(self):
"""
测试单个张量转换为Jittor
"""
torch_tensor = torch.rand((3, 4, 5))
res = torch2jittor(torch_tensor)
self.check_jittor_var(res, False)
res = torch2jittor(torch_tensor, no_gradient=None)
self.check_jittor_var(res, False)
res = torch2jittor(torch_tensor, no_gradient=True)
self.check_jittor_var(res, False)
res = torch2jittor(torch_tensor, no_gradient=False)
self.check_jittor_var(res, True)
def test_tensor_list_transfer(self):
"""
测试张量列表的转换
"""
torch_list = [torch.rand((6, 4, 2)) for i in range(10)]
res = torch2jittor(torch_list)
assert isinstance(res, list)
for t in res:
self.check_jittor_var(t, False)
res = torch2jittor(torch_list, no_gradient=False)
assert isinstance(res, list)
for t in res:
self.check_jittor_var(t, True)
def test_tensor_tuple_transfer(self):
"""
测试张量元组的转换
"""
torch_list = [torch.rand((6, 4, 2)) for i in range(10)]
torch_tuple = tuple(torch_list)
res = torch2jittor(torch_tuple)
assert isinstance(res, tuple)
for t in res:
self.check_jittor_var(t, False)
def test_dict_transfer(self):
"""
测试字典结构的转换
"""
torch_dict = {
"tensor": torch.rand((3, 4)),
"list": [torch.rand(6, 4, 2) for i in range(10)],
"dict":{
"list": [torch.rand(6, 4, 2) for i in range(10)],
"tensor": torch.rand((3, 4))
},
"int": 2,
"string": "test string"
}
res = torch2jittor(torch_dict)
assert isinstance(res, dict)
self.check_jittor_var(res["tensor"], False)
assert isinstance(res["list"], list)
for t in res["list"]:
self.check_jittor_var(t, False)
assert isinstance(res["int"], int)
assert isinstance(res["string"], str)
assert isinstance(res["dict"], dict)
assert isinstance(res["dict"]["list"], list)
for t in res["dict"]["list"]:
self.check_jittor_var(t, False)
self.check_jittor_var(res["dict"]["tensor"], False)