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
| 21 | |
| 22 | |
| 23 | class 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]) |
no outgoing calls