random_utils2.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #
  2. # Copyright 2019 The FATE Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import functools
  16. import math
  17. import random
  18. import sys
  19. import numpy as np
  20. from fate_arch.session import is_table
  21. from federatedml.secureprotol.fixedpoint import FixedPointNumber
  22. FLOAT_MANTISSA_BITS = 32
  23. PRECISION = 2 ** FLOAT_MANTISSA_BITS
  24. def rand_number_generator(q_field):
  25. number = FixedPointNumber(encoding=random.randint(1, PRECISION),
  26. exponent=math.floor((FLOAT_MANTISSA_BITS / 2)
  27. / FixedPointNumber.LOG2_BASE),
  28. n=q_field
  29. )
  30. return number
  31. def rand_tensor(q_field, tensor):
  32. if is_table(tensor):
  33. return tensor.mapValues(
  34. lambda x: np.array([rand_number_generator(q_field=q_field)
  35. for _ in x],
  36. dtype=FixedPointNumber)
  37. )
  38. if isinstance(tensor, np.ndarray):
  39. arr = np.zeros(shape=tensor.shape, dtype=FixedPointNumber)
  40. view = arr.view().reshape(-1)
  41. for i in range(arr.size):
  42. view[i] = rand_number_generator(q_field=q_field)
  43. return arr
  44. raise NotImplementedError(f"type={type(tensor)}")
  45. class _MixRand(object):
  46. def __init__(self, q_field, base_size=1000, inc_velocity=0.1, inc_velocity_deceleration=0.01):
  47. self._caches = []
  48. self._q_field = q_field
  49. # generate base random numbers
  50. for _ in range(base_size):
  51. rand_num = rand_number_generator(q_field=self._q_field)
  52. self._caches.append(rand_num)
  53. self._inc_rate = inc_velocity
  54. self._inc_velocity_deceleration = inc_velocity_deceleration
  55. def _inc(self):
  56. rand_num = rand_number_generator(q_field=self._q_field)
  57. self._caches.append(rand_num)
  58. def __next__(self):
  59. if random.random() < self._inc_rate:
  60. self._inc()
  61. return self._caches[random.randint(0, len(self._caches) - 1)]
  62. def __iter__(self):
  63. return self
  64. def _mix_rand_func(it, q_field):
  65. _mix = _MixRand(q_field)
  66. result = []
  67. for k, v in it:
  68. result.append((k, np.array([next(_mix) for _ in v], dtype=object)))
  69. return result
  70. def urand_tensor(q_field, tensor, use_mix=False):
  71. if is_table(tensor):
  72. if use_mix:
  73. return tensor.mapPartitions(functools.partial(_mix_rand_func,
  74. q_field=q_field),
  75. use_previous_behavior=False,
  76. preserves_partitioning=True)
  77. return tensor.mapValues(
  78. lambda x: np.array([rand_number_generator(q_field=q_field)
  79. for _ in x],
  80. dtype=FixedPointNumber))
  81. if isinstance(tensor, np.ndarray):
  82. arr = np.zeros(shape=tensor.shape, dtype=FixedPointNumber)
  83. view = arr.view().reshape(-1)
  84. for i in range(arr.size):
  85. view[i] = rand_number_generator(q_field=q_field)
  86. return arr
  87. raise NotImplementedError(f"type={type(tensor)}")