MCPcopy Create free account
hub / github.com/OpenMined/SyMPC / FixedPointEncoder

Class FixedPointEncoder

src/sympc/encoder/fp_encoder.py:23–141  ·  view source on GitHub ↗

Encoding/decoding a tensor to/from a fixed precision representation. This class was inspired from the Facebook Research - CrypTen project Attributes: _precision (int): the precision for the encoder _base (int): the base for the encoder _scale (int): the scale used f

Source from the content-addressed store, hash-verified

21
22
23class FixedPointEncoder:
24 """Encoding/decoding a tensor to/from a fixed precision representation.
25
26 This class was inspired from the Facebook Research - CrypTen project
27
28 Attributes:
29 _precision (int): the precision for the encoder
30 _base (int): the base for the encoder
31 _scale (int): the scale used for encoding/decoding
32 """
33
34 __slots__ = {"_precision", "_base", "_scale"}
35
36 def __init__(self, base: int = 2, precision: int = 16):
37 """Initialize FP Encoder.
38
39 Args:
40 base (int): The base for the encoder.
41 precision (int): The precision for the encoder.
42 """
43 self._precision = precision
44 self._base = base
45 self._scale = base ** precision
46
47 def encode(self, value: Union[torch.Tensor, float, int]) -> torch.LongTensor:
48 """Encode a value using the FixedPoint Encoder.
49
50 Args:
51 value (Union[torch.Tensor, float, int]): value to encode
52
53 Returns:
54 torch.LongTensor: encoded value
55 """
56 if not isinstance(value, torch.Tensor):
57 value = torch.tensor(data=[value])
58
59 # Use the largest type
60 long_value = (value * self._scale).long()
61
62 return long_value
63
64 def decode(self, value: Union[int, torch.Tensor]) -> torch.Tensor:
65 """Decode a value using the FixedPoint Encoder.
66
67 Args:
68 value (Union[int, torch.Tensor]): Value to decode.
69
70 Returns:
71 torch.Tensor: Decoded tensor.
72
73 Raises:
74 ValueError: If value is a floating torch.Tensor.
75 """
76 if isinstance(value, torch.Tensor) and value.dtype.is_floating_point:
77 raise ValueError(f"{value} should be converted to long format")
78
79 if isinstance(value, int):
80 value = torch.LongTensor([value])

Callers 14

__init__Method · 0.90
__init__Method · 0.90
reconstructMethod · 0.90
ltMethod · 0.90
gtMethod · 0.90
test_fixed_pointFunction · 0.90
test_private_compareFunction · 0.90
test_fp_encoder_initFunction · 0.90
test_fp_encodingFunction · 0.90
test_fp_decodingFunction · 0.90
test_fp_precision_setterFunction · 0.90

Calls

no outgoing calls

Tested by 9

test_fixed_pointFunction · 0.72
test_private_compareFunction · 0.72
test_fp_encoder_initFunction · 0.72
test_fp_encodingFunction · 0.72
test_fp_decodingFunction · 0.72
test_fp_precision_setterFunction · 0.72
test_fp_base_setterFunction · 0.72