Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix decode float #203

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 15 additions & 7 deletions test/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,15 @@
from crypten.encoder import FixedPointEncoder, nearest_integer_division


def get_test_tensor(max_value=10, float=False):
def get_test_tensor(max_value=10, is_float=False):
"""Create simple test tensor."""
tensor = torch.LongTensor(list(range(max_value)))
if float:
tensor = tensor.float()
dtype = torch.long
step = 1

if is_float:
dtype = torch.float
step = 0.2
tensor = torch.arange(start=0, end=max_value, step=step, dtype=dtype)
return tensor


Expand All @@ -28,7 +32,11 @@ class TestCommon(unittest.TestCase):
"""

def _check(self, tensor, reference, msg):
test_passed = (tensor == reference).all().item() == 1
if tensor.dtype == torch.long:
tensor = tensor.float()
if reference.dtype == torch.long:
reference = reference.float()
test_passed = torch.allclose(tensor, reference, rtol=1/2 ** 15)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Q: Does this look strange? (to use rtol with 1/2 ** 15)
I think this might also be changed to 1e-4<-- this is the biggest power of 10 that we could use to "catch" the precision given by 2**16 (< 10^5)

self.assertTrue(test_passed, msg=msg)

def test_encode_decode(self):
Expand All @@ -38,7 +46,7 @@ def test_encode_decode(self):
fpe = FixedPointEncoder(precision_bits=16)
else:
fpe = FixedPointEncoder(precision_bits=0)
tensor = get_test_tensor(float=float)
tensor = get_test_tensor(is_float=float)
decoded = fpe.decode(fpe.encode(tensor))
self._check(
decoded,
Expand All @@ -50,7 +58,7 @@ def test_encode_decode(self):
crypten.mpc.set_default_provider(crypten.mpc.provider.TrustedFirstParty)
crypten.init()

tensor = get_test_tensor(float=True)
tensor = get_test_tensor(is_float=True)
encrypted_tensor = crypten.cryptensor(tensor)
encrypted_tensor = fpe.encode(encrypted_tensor)
self._check(
Expand Down