-
Notifications
You must be signed in to change notification settings - Fork 274
/
debug.py
132 lines (103 loc) · 4.17 KB
/
debug.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
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import pdb as pythondebugger
import sys
from crypten.config import cfg
class MultiprocessingPdb(pythondebugger.Pdb):
"""A Pdb subclass that may be used
from a forked multiprocessing child
"""
def interaction(self, *args, **kwargs):
_stdin = sys.stdin
try:
with open("/dev/stdin") as file:
sys.stdin = file
pythondebugger.Pdb.interaction(self, *args, **kwargs)
finally:
sys.stdin = _stdin
def configure_logging():
"""Configures a logging template useful for debugging multiple processes."""
level = logging.INFO
logging.getLogger().setLevel(level)
logging.basicConfig(
level=level,
format=(
"[%(asctime)s][%(levelname)s][%(filename)s:%(lineno)d]"
+ "[%(processName)s] %(message)s"
),
)
def crypten_print(*args, dst=0, **kwargs):
"""
Prints a message to only parties whose rank is contained by `dst` kwarg (default: 0).
"""
if isinstance(dst, int):
dst = [dst]
assert isinstance(
dst, (list, tuple)
), "print destination must be a list or tuple of party ranks"
import crypten.communicator as comm
if comm.get().get_rank() in dst:
print(*args, **kwargs)
def crypten_log(*args, level=logging.INFO, dst=0, **kwargs):
"""
Logs a message to logger of parties whose rank is contained by `dst` kwarg (default: 0).
Uses logging.INFO as default level.
"""
if isinstance(dst, int):
dst = [dst]
assert isinstance(
dst, (list, tuple)
), "log destination must be a list or tuple of party ranks"
import crypten.communicator as comm
if comm.get().get_rank() in dst:
logging.log(level, *args, **kwargs)
def crypten_print_in_order(*args, **kwargs):
"""
Calls print(*args, **kwargs) on each party in rank order to ensure each party
can print its full message uninterrupted and the full output is deterministic
"""
import crypten.communicator as comm
for i in range(comm.get().get_world_size()):
if comm.get().get_rank() == i:
print(*args, **kwargs)
comm.get().barrier()
def validate_correctness(self, func, func_name, tolerance=0.05):
import crypten
import torch
if not hasattr(torch.tensor([]), func_name):
return func
def validation_function(*args, **kwargs):
with cfg.temp_override({"debug.validation_mode": False}):
# Compute crypten result
result_enc = func(*args, **kwargs)
result = result_enc.get_plain_text()
# Compute torch result for corresponding function
for i, arg in enumerate(args):
if crypten.is_encrypted_tensor(arg):
args[i] = args[i].get_plain_text()
for key, value in kwargs.items():
if crypten.is_encrypted_tensor(value):
kwargs[key] = value.get_plain_text()
reference = getattr(self.get_plain_text(), func_name)(*args, **kwargs)
# Check sizes match
if result.size() != reference.size():
crypten_log(
f"Size mismatch: Expected {reference.size()} but got {result.size()}"
)
raise ValueError(f"Function {func_name} returned incorrect size")
# Check that results match
diff = (result - reference).abs_()
norm_diff = diff.div(result.abs() + reference.abs()).abs_()
test_passed = norm_diff.le(tolerance) + diff.le(tolerance * 0.1)
test_passed = test_passed.gt(0).all().item() == 1
if not test_passed:
crypten_log(f"Function {func_name} returned incorrect values")
crypten_log("Result %s" % result)
crypten_log("Result - Reference = %s" % (result - reference))
raise ValueError(f"Function {func_name} returned incorrect values")
return result_enc
return validation_function