-
Notifications
You must be signed in to change notification settings - Fork 10
/
torch2cuda.py
831 lines (695 loc) · 28.3 KB
/
torch2cuda.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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
import argparse
import ast
import os
from types import FunctionType
import astunparse
from util import astpasses, util
try:
import numpy as np
import torch
except Exception as e:
pass
try:
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
import tensorflow as tf
tf.get_logger().setLevel("ERROR") # Suppress TF warnings
# https://github.com/tensorflow/tensorflow/issues/56927
# Run with export XLA_FLAGS=--xla_gpu_cuda_data_dir=/usr/lib/cuda/
import numpy as np
except Exception as e:
pass
SEED: int = 420
OUTPUT_LIMIT: int = 1024
ALLCLOSE_RTOL: float = 1e-2 # default 1e-5
ALLCLOSE_ATOL: float = 1e-3 # default 1e-8
class PassManager:
def __init__(self) -> None:
pass
def apply(self, node: ast.AST, gpu: bool = False, chkRand: bool = False) -> ast.AST:
return None
class Config:
def __init__(self) -> None:
self.passManager: PassManager = self.genPassManager()
@staticmethod
def genPassManager() -> PassManager:
return None
def applyPasses(
self, node: ast.AST, gpu: bool = False, chkRand: bool = False
) -> ast.AST:
return self.passManager.apply(node, gpu, chkRand)
@staticmethod
def doInternalRandCheck() -> bool:
return False
@staticmethod
def allclose(lhs, rhs) -> bool:
return True
@staticmethod
def genExecGlobals() -> dict:
return {}
@staticmethod
def isCrash(exceptMsg: str) -> bool:
return False
@staticmethod
def isGpuOom(exceptMsg: str) -> bool:
return False
@staticmethod
def skipApi(api: str, label: str) -> bool:
return False
config: Config = None
class ConfigTorch(Config):
def __init__(self) -> None:
super().__init__()
@staticmethod
def genPassManager() -> PassManager:
class PassManagerTorch(PassManager):
def __init__(self) -> None:
self.generalPasses = []
self.cudaPasses = []
self.chkRandPasses = []
passRemoveImports = astpasses.PassRemoveImports()
self.generalPasses.append(passRemoveImports)
passRemoveNoiseCalls = astpasses.PassRemoveCalls(
[
"print",
"exit",
"torch.save",
"torch.manual_seed",
"torch.set_default_tensor_type",
"torch.cuda.set_device",
"torch.autograd.set_detect_anomaly",
"torch.cuda.is_available",
"torch.cuda.memory_allocated",
"torch.set_grad_enabled",
]
)
self.generalPasses.append(passRemoveNoiseCalls)
passFlattenCall = astpasses.PassFlattenCall()
self.generalPasses.append(passFlattenCall)
passRemoveTorchCuda = astpasses.PassRemoveTorchCuda()
self.generalPasses.append(passRemoveTorchCuda)
passReplaceEmptyTensorCalls = astpasses.PassReplaceCalls(
{
"torch.empty": "torch.randn({})",
"torch.set_grad_enabled": "torch.set_grad_enabled(True)",
}
)
self.generalPasses.append(passReplaceEmptyTensorCalls)
passReplaceRawTensorsWithNoArgs = astpasses.PassReplaceCallsIfArgsEmpty(
{
"torch.Tensor": "torch.randn(3, 3)",
"torch.FloatTensor": "torch.randn(3, 3)",
"torch.DoubleTensor": "torch.randn(3, 3)",
"torch.HalfTensor": "torch.randn(3, 3)",
"torch.BFloat16Tensor": "torch.randn(3, 3)",
"torch.ByteTensor": "torch.randint(0, 128, (3, 3))",
"torch.CharTensor": "torch.randint(0, 128, (3, 3))",
"torch.ShortTensor": "torch.randint(0, 65536, (3, 3))",
"torch.IntTensor": "torch.randint(0, 1048576, (3, 3))",
"torch.LongTensor": "torch.randint(0, 1048576, (3, 3))",
"torch.BoolTensor": "torch.randint(0, 1, (3, 3))",
}
)
self.generalPasses.append(passReplaceRawTensorsWithNoArgs)
passReplaceCallsIfArgsWithoutNameOrList = (
astpasses.PassReplaceCallsIfArgsWithoutNameOrList(
{
"torch.Tensor": "torch.randn({})",
"torch.FloatTensor": "torch.randn({})",
"torch.DoubleTensor": "torch.randn({})",
"torch.HalfTensor": "torch.randn({})",
"torch.BFloat16Tensor": "torch.randn({})",
"torch.ByteTensor": "torch.randint(0, 128, ({},))",
"torch.CharTensor": "torch.randint(0, 128, ({},))",
"torch.ShortTensor": "torch.randint(0, 65536, ({},))",
"torch.IntTensor": "torch.randint(0, 1048576, ({},))",
"torch.LongTensor": "torch.randint(0, 1048576, ({},))",
"torch.BoolTensor": "torch.randint(0, 1, ({},))",
}
)
)
self.generalPasses.append(passReplaceCallsIfArgsWithoutNameOrList)
passReplaceMeths = astpasses.PassReplaceMeths(
{
"numpy": "cpu().numpy()",
"cuda": "",
"cpu": "",
"new": "clone().detach()",
"new_empty": "new_ones({})",
}
)
self.generalPasses.append(passReplaceMeths)
passReplaceRandLikeCalls = astpasses.PassReplaceCalls(
{
"torch.rand_like": "torch.rand_like({}.cpu())",
"torch.randn_like": "torch.randn_like({}.cpu())",
}
)
self.generalPasses.append(passReplaceRandLikeCalls)
passReplaceInplaceRandMeths = astpasses.PassReplaceMeths(
{
"random_": "",
"uniform_": "",
}
)
self.generalPasses.append(passReplaceInplaceRandMeths)
passLogTorchIntermediate = astpasses.PassLogTorchIntermediate()
self.generalPasses.append(passLogTorchIntermediate)
passReplaceAnyCpuTensorType = astpasses.PassReplaceAny(
{
"torch.FloatTensor": "torch.cuda.FloatTensor",
"torch.DoubleTensor": "torch.cuda.DoubleTensor",
"torch.HalfTensor": "torch.cuda.HalfTensor",
"torch.BFloat16Tensor": "torch.cuda.BFloat16Tensor",
"torch.ByteTensor": "torch.cuda.ByteTensor",
"torch.CharTensor": "torch.cuda.CharTensor",
"torch.ShortTensor": "torch.cuda.ShortTensor",
"torch.IntTensor": "torch.cuda.IntTensor",
"torch.LongTensor": "torch.cuda.LongTensor",
"torch.BoolTensor": "torch.cuda.BoolTensor",
}
)
self.cudaPasses.append(passReplaceAnyCpuTensorType)
passAppendTorchCuda = astpasses.PassAppendTorchCuda()
self.cudaPasses.append(passAppendTorchCuda)
passCheckTorchInternalRandom = astpasses.PassCheckTorchInternalRandom()
self.chkRandPasses.append(passCheckTorchInternalRandom)
def apply(
self, node: ast.AST, gpu: bool = False, chkRand: bool = False
) -> ast.AST:
for subpass in (
self.generalPasses + self.cudaPasses + self.chkRandPasses
):
subpass.reset()
for subpass in self.generalPasses:
node = subpass.visit(node)
if gpu:
for subpass in self.cudaPasses:
node = subpass.visit(node)
if chkRand:
for subpass in self.chkRandPasses:
node = subpass.visit(node)
return node
return PassManagerTorch()
@staticmethod
def doInternalRandCheck() -> bool:
return True
@staticmethod
def allclose(lhs, rhs) -> bool:
if isinstance(lhs, torch.Tensor):
return torch.allclose(
lhs.cpu(),
rhs.cpu(),
rtol=ALLCLOSE_RTOL,
atol=ALLCLOSE_ATOL,
equal_nan=True,
)
elif isinstance(lhs, int) or isinstance(lhs, float):
return torch.allclose(
torch.Tensor([lhs]),
torch.Tensor([rhs]),
rtol=ALLCLOSE_RTOL,
atol=ALLCLOSE_ATOL,
equal_nan=True,
)
elif isinstance(lhs, torch.Size):
return lhs == rhs
return True
@staticmethod
def genExecGlobals() -> dict:
return {"torch": torch, "np": np}
@staticmethod
def isCrash(exceptMsg: str) -> bool:
return "INTERNAL ASSERT FAILED" in exceptMsg
@staticmethod
def isGpuOom(exceptMsg: str) -> bool:
return False
@staticmethod
def skipApi(api: str, label: str) -> bool:
return False
class ConfigTf(Config):
def __init__(self) -> None:
super().__init__()
@staticmethod
def genPassManager() -> PassManager:
class PassManagerTf(PassManager):
def __init__(self) -> None:
self.generalPasses = []
self.cpuPasses = []
self.gpuPasses = []
self.chkRandPasses = []
passRemoveImports = astpasses.PassRemoveImports()
self.generalPasses.append(passRemoveImports)
passRemoveCalls = astpasses.PassRemoveCalls(
[
# remove print
"print",
"tf.print",
# make sure nothing disables eager mode during execution
# once disabled, it is hard to re-enable it in the middle of the program
"tf.test.main",
"tf.compat.v1.disable_eager_execution",
"tf1.disable_v2_behavior",
"tf.compat.v1.disable_v2_behavior",
"tf.compat.v1.Graph",
"tf.compat.v1.InteractiveSession",
# forbid file operations
"open",
"tf.compat.v1.keras.experimental.export_saved_model",
"tf.compat.v1.saved_model.experimental.save",
"model.save_weights",
"tf.io.write_file",
"tf.summary.create_file_writer",
# exit
"os._exit",
]
)
self.generalPasses.append(passRemoveCalls)
# Flattening is not a must for TF
# passFlattenCall = astpasses.PassFlattenCall()
# self.generalPasses.append(passFlattenCall)
# passRandomizeTfInput = astpasses.PassRandomizeTfInput()
# self.generalPasses.append(passRandomizeTfInput)
passLogTfIntermediate = astpasses.PassLogTfIntermediate()
self.generalPasses.append(passLogTfIntermediate)
passAddTfEagerCheck = astpasses.PassAddTfEagerCheck()
self.generalPasses.append(passAddTfEagerCheck)
passWithTfDeviceCpu = astpasses.PassWithTfDevice("/cpu:0")
self.cpuPasses.append(passWithTfDeviceCpu)
passWithTfDeviceGpu = astpasses.PassWithTfDevice("/gpu:0")
self.gpuPasses.append(passWithTfDeviceGpu)
passCheckTorchInternalRandom = astpasses.PassCheckTorchInternalRandom()
self.chkRandPasses.append(passCheckTorchInternalRandom)
def apply(
self, node: ast.AST, gpu: bool = False, chkRand: bool = False
) -> ast.AST:
for subpass in (
self.generalPasses
+ self.cpuPasses
+ self.gpuPasses
+ self.chkRandPasses
):
subpass.reset()
for subpass in self.generalPasses:
node = subpass.visit(node)
if gpu:
for subpass in self.gpuPasses:
node = subpass.visit(node)
else:
for subpass in self.cpuPasses:
node = subpass.visit(node)
if chkRand:
for subpass in self.chkRandPasses:
node = subpass.visit(node)
return node
return PassManagerTf()
@staticmethod
def doInternalRandCheck() -> bool:
return False
@staticmethod
def allclose(lhs, rhs) -> bool:
if isinstance(lhs, tf.Tensor):
return np.allclose(
lhs, rhs, rtol=ALLCLOSE_RTOL, atol=ALLCLOSE_ATOL, equal_nan=True
)
elif isinstance(lhs, int) or isinstance(rhs, float):
return np.allclose(
tf.convert_to_tensor(lhs),
tf.convert_to_tensor(rhs),
rtol=ALLCLOSE_RTOL,
atol=ALLCLOSE_ATOL,
equal_nan=True,
)
return True
@staticmethod
def genExecGlobals() -> dict:
return {"tf": tf, "np": np, "os": os}
@staticmethod
def isCrash(exceptMsg: str) -> bool:
# if ConfigTf.isGpuOom(exceptMsg): return False
crash_kws = [
"InternalError",
"SystemError",
]
return any([kw.lower() in exceptMsg.lower() for kw in crash_kws])
@staticmethod
def isGpuOom(exceptMsg: str) -> bool:
allow_errors = [
"Attempting to perform BLAS operation using StreamExecutor without BLAS support",
"CUDA_ERROR_INVALID_HANDLE",
"Could not satisfy device specification",
"Failed to create cuFFT batched plan with scratch allocator",
]
if any([allow_err.lower() in exceptMsg.lower() for allow_err in allow_errors]):
return True
return False
@staticmethod
def skipApi(api: str, label: str) -> bool:
# These failed to be catched.
random_apis = [
# Random sampling
"tf.raw_ops.Multinomial",
"tf.keras.backend.get_uid",
]
unstable_apis = [
# matrix decomposition, multi results
"tf.raw_ops.Svd",
# hangs
"tf.raw_ops.CollectiveReduce",
]
examined_apis = [
# False positives examined.
"tf.compat.v1.gather",
"tf.gather",
"tf.bitwise.right_shift",
"tf.compat.v1.bitwise.right_shift",
"tf.compat.v1.keras.activations.relu",
"tf.experimental.numpy.isclose",
"tf.experimental.numpy.isreal",
"tf.bitwise.left_shift",
"tf.compat.v1.bitwise.left_shift",
"tf.raw_ops.LeftShift",
"tf.keras.layers.Wrapper",
# OOM
"tf.experimental.numpy.conjugate",
"tf.signal.irfft3d",
]
if api in random_apis + unstable_apis + examined_apis:
return True
if any([x in label for x in random_apis]):
return True
skip_unstable_random_kws = ["random", "svd", "segment_max", "segmentmax", "fft"]
for kw in skip_unstable_random_kws:
if kw in api.lower():
return True
# Timeout labels:
# tf-depth
# if label in [
# "tf.image.total_variation_48",
# ]: return True
return False
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument(
"--tf", action="store_true", default=False
) # tensorflow or torch
parser.add_argument("--mode", type=str, default="single")
# for single mode
parser.add_argument("--input", type=str, default=None) # input .py filename
parser.add_argument(
"--code", action="store_true", default=False
) # emit transformed code
parser.add_argument(
"--srcast", action="store_true", default=False
) # emit source AST
parser.add_argument(
"--ast", action="store_true", default=False
) # emit transformed AST
parser.add_argument(
"--cpu", action="store_true", default=False
) # do not insert cuda()
parser.add_argument(
"--chkrand", action="store_true", default=False
) # check internal randomness
parser.add_argument(
"--noexec", action="store_true", default=False
) # do not execute transformed code
parser.add_argument(
"--noresult", action="store_true", default=False
) # do not print result
parser.add_argument("--seed", type=int, default=SEED) # random seed to use
# for batch mode
# --input # input source directory
# --code # emit transformed code
# --srcast # emit source AST
# --ast # emit transformed AST
# --cpu # do not insert cuda()
# --chkrand # check internal randomness
# --noexec # do not execute transformed code
# --noresult # do not print result
# --seed # random seed to use
parser.add_argument("--start", type=int, default=0) # from which testcase to start
parser.add_argument(
"--singleapi", action="store_true", default=False
) # stop when meeting the next api
# for dual mode
# --input # input .py filename
# for race mode
# --input # input source directory
# --start # from which testcase to start
# --singleapi # stop when meeting the next api
# for duel mode
# --input # input .py filename
args = parser.parse_args()
global config
if args.tf:
config = ConfigTf()
else:
config = ConfigTorch()
if args.mode == "single":
modeSingle(args) # coreSingle + frameworkSingle
elif args.mode == "batch":
modeBatch(args) # coreSingle + frameworkSrcBatch
elif args.mode == "dual":
modeDual(args) # coreDual + frameworkSingle
elif args.mode == "race":
modeRace(args) # coreDual + frameworkSrcBatch
elif args.mode == "duel":
modeDuel(args) # coreDuel (contains coreDual) + frameworkSingle
else:
raise NotImplementedError("{} mode".format(args.mode))
def execSingle(seed: int, srcAst: ast.AST) -> dict:
"""Compiles and executes one ast, returns globals produced during its execution.
Throws unformatted exception."""
util.set_seed(seed)
execGlobals = config.genExecGlobals()
exec(compile(astunparse.unparse(srcAst), "", "exec"), execGlobals)
execGlobals = util.removeInternalGlobals(execGlobals)
return execGlobals
def frameworkSingle(args: argparse.Namespace, coreFunc: FunctionType) -> None:
ifs = open(args.input, "r", encoding="utf-8")
src: str = ifs.read()
try:
coreFunc(args.seed, args, src)
except Exception as e:
reason: str = "FrameworkCrashCatch"
detail: str = str(e)
if len(e.args) >= 2:
reason: str = e.args[0]
detail: str = e.args[1]
print("\nFrameworkSingle", reason, SEED, detail)
def frameworkSrcBatch(args: argparse.Namespace, coreFunc: FunctionType) -> None:
"""Framework for sequential runs from source folder, compatible with driver.
Handles arguments --start, --singleapi."""
tasks = util.readAllTasksFromDir(args.input)
lastApi: str = None
for id in range(args.start, len(tasks)):
task = tasks[id]
api, label, src = util.parseTask(task)
if args.singleapi:
# One run only for the same seed
if lastApi != None and lastApi != api:
break
lastApi = api
try:
if config.skipApi(api, label):
raise Exception("Skipped", "no detail")
coreFunc(SEED, args, src)
except Exception as e:
reason: str = "FrameworkCrashCatch"
detail: str = str(e)
if len(e.args) >= 2:
reason: str = e.args[0]
detail: str = e.args[1]
if len(detail) > OUTPUT_LIMIT:
detail = "Detail is too long"
if (
reason == "FrameworkCrashCatch"
): # FrameworkCrashCatch is printed by driver
print(detail)
exit(-1)
if "Catch" in reason:
with open("catches.log", "a") as f:
f.write(
"\nTitanFuzzTestcase {} {} {} {} {} {}".format(
id, api, label, reason, SEED, detail
)
)
print("\nTitanFuzzTestcase", id, api, label, reason, SEED, detail)
def coreSingle(seed: int, args: argparse.Namespace, src: str):
srcAst = ast.parse(src)
if args.srcast:
print(astunparse.dump(srcAst))
srcAst = config.applyPasses(srcAst, gpu=not args.cpu, chkRand=args.chkrand)
if args.code:
print(astunparse.unparse(srcAst))
if args.ast:
print(astunparse.dump(srcAst))
if not args.noexec:
try:
execGlobals = execSingle(args.seed, srcAst)
globalTypes = util.getTypeDict(execGlobals)
if not args.noresult:
util.printPretty(globalTypes)
util.printPretty(execGlobals)
except Exception as e:
raise Exception("ExecFail", str(e))
raise Exception("Success", "succeeded")
def modeSingle(args: argparse.Namespace) -> None:
frameworkSingle(args, coreSingle)
def modeBatch(args: argparse.Namespace) -> None:
frameworkSrcBatch(args, coreSingle)
def coreDual(seed: int, args: argparse.Namespace, src: str) -> None:
"""Throws structured exception"""
# for seedOffset in range(1): # Try different seeds until some problem is found
# seed = SEED + seedOffset
# CPU
cpuAst = ast.parse(src)
cpuAst = config.applyPasses(cpuAst, gpu=False)
cpuExcept = None
try:
cpuGlobals = execSingle(seed, cpuAst)
except Exception as e:
cpuExcept = e
cpuExceptMsg: str = type(cpuExcept).__name__ + " " + str(cpuExcept)
if config.isCrash(cpuExceptMsg):
raise Exception("CpuCrashCatch", cpuExceptMsg)
# GPU
gpuAst = ast.parse(src)
gpuAst = config.applyPasses(gpuAst, gpu=True)
gpuExcept: Exception = None
try:
gpuGlobals = execSingle(seed, gpuAst)
except Exception as e:
gpuExcept = e
gpuExceptMsg: str = type(gpuExcept).__name__ + " " + str(gpuExcept)
if config.isGpuOom(gpuExceptMsg):
raise Exception("GpuOomFail", gpuExceptMsg)
if config.isCrash(gpuExceptMsg):
raise Exception("GpuCrashCatch", gpuExceptMsg)
# state compare
if cpuExcept != None and gpuExcept != None:
# Both failed, should be the problem with CPU AST passes
if (
cpuExceptMsg == gpuExceptMsg
or cpuExceptMsg == gpuExceptMsg.replace(".cuda", "")
or cpuExceptMsg == gpuExceptMsg.replace("cuda", "cpu")
):
raise Exception(
"BothExecFail", "\nCPU: {}\nGPU: {}".format(cpuExceptMsg, gpuExceptMsg)
)
elif "NotImplementedError" in gpuExceptMsg:
raise Exception(
"GpuNotImplementedFail",
"\nCPU: {}\nGPU: {}".format(cpuExceptMsg, gpuExceptMsg),
)
elif "SyntaxError" in cpuExceptMsg and "SyntaxError" in gpuExceptMsg:
raise Exception(
"SyntaxFail", "\nCPU: {}\nGPU: {}".format(cpuExceptMsg, gpuExceptMsg)
)
else:
raise Exception(
"ExceptMsgCatch",
"\nCPU: {}\nGPU: {}".format(cpuExceptMsg, gpuExceptMsg),
)
elif cpuExcept == None and gpuExcept != None:
# Only GPU failed, should be the problem with GPU AST passes
raise Exception("GpuExecFail", gpuExceptMsg)
elif cpuExcept != None and gpuExcept == None:
# GPU passed but CPU failed, strange enough to be considered a catch
raise Exception("ExecStateCatch", cpuExceptMsg)
# value compare
cpuTypes = util.getTypeDict(cpuGlobals)
gpuTypes = util.getTypeDict(gpuGlobals)
cpuTypesStr: str = util.pretty(cpuTypes)
gpuTypesStr: str = util.pretty(gpuTypes)
if cpuTypesStr != gpuTypesStr:
detail: str = "\nCPU:\n{}\nGPU:\n{}".format(cpuTypesStr, gpuTypesStr)
raise Exception("VarTypeConflictCatch", detail)
inconsistentNames = []
for name in cpuGlobals.keys():
cpuVal = cpuGlobals[name]
gpuVal = gpuGlobals[name]
try:
if not config.allclose(cpuVal, gpuVal):
inconsistentNames.append(name)
except Exception as e:
raise Exception("ComparisonFail", str(e))
if len(inconsistentNames) == 0:
raise Exception("Success", "succeeded")
# Check for internal randomness before reporting catch
hasInternalRandomness = False
if config.doInternalRandCheck():
try:
chkAst = ast.parse(src)
chkAst = config.applyPasses(chkAst, gpu=True, chkRand=True)
execSingle(seed, chkAst)
chkHash = torch.randn(3, 3, device="cuda:0")
# If no random numbers are consumed by internal randomness,
# chkHash should be as if generated before execution
util.set_seed(seed)
ansHash = torch.randn(3, 3, device="cuda:0")
hasInternalRandomness = not config.allclose(chkHash, ansHash)
except Exception as e:
raise Exception("RandCheckExecFail", str(e))
if hasInternalRandomness:
raise Exception("InternalRandomFail", "")
cpuGlobalsNumeric = util.removeNonNumericGlobals(cpuGlobals)
gpuGlobalsNumeric = util.removeNonNumericGlobals(gpuGlobals)
detail: str = ""
try:
detail: str = "\ndiff:{}\nCPU:\n{}\nGPU:\n{}".format(
util.pretty(inconsistentNames),
util.pretty(cpuGlobalsNumeric),
util.pretty(gpuGlobalsNumeric),
)
except Exception as e:
raise Exception("VarInconsistentCatch", "Unable to print values " + str(e))
raise Exception("VarInconsistentCatch", detail)
def modeDual(args: argparse.Namespace) -> None:
frameworkSingle(args, coreDual)
def modeRace(args: argparse.Namespace) -> None:
frameworkSrcBatch(args, coreDual)
def coreDuel(seed: int, args: argparse.Namespace, src: str):
srcLines: list[str] = src.split("\n")
lo: int = 0
hi: int = len(srcLines)
lastReason = "no reason"
lastDetail = "no detail"
while hi > lo:
mid: int = (lo + hi) // 2
partialSrc: str = ""
for srcLine in srcLines[0 : mid + 1]:
partialSrc += srcLine + "\n"
try:
coreDual(seed, args, partialSrc)
except Exception as e:
reason: str = "FrameworkCrashCatch"
detail: str = str(e)
if len(e.args) >= 2:
reason: str = e.args[0]
detail: str = e.args[1]
if reason == "Success":
lo = mid + 1
else:
hi = mid
lastReason = reason
lastDetail = detail
if lo == len(srcLines):
raise Exception("DuelFailed", "No problem found")
# Print last lines before problem
problemLines: str = "Last lines before problem: \n"
for i in range(max(hi - 3, 0), hi + 1):
problemLines += "{} > {}\n".format(i + 1, srcLines[i])
raise Exception(
"DuelFinished",
"Problem since line {}\n{}{} {}".format(
hi + 1, problemLines, lastReason, lastDetail
),
)
def modeDuel(args: argparse.Namespace) -> None:
frameworkSingle(args, coreDuel)
if __name__ == "__main__":
main()
# Some sneaky code may contain exit(0) or other equivalent calls
# We distinguish ourselves from them with a magic number
exit(233)