utils.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # Copyright (c) 2018-present, Facebook, Inc.
  2. # All rights reserved.
  3. #
  4. # This source code is licensed under the license found in the
  5. # LICENSE file in the root directory of this source tree.
  6. #
  7. import torch
  8. import numpy as np
  9. import hashlib
  10. def wrap(func, *args, unsqueeze=False):
  11. """
  12. Wrap a torch function so it can be called with NumPy arrays.
  13. Input and return types are seamlessly converted.
  14. """
  15. # Convert input types where applicable
  16. args = list(args)
  17. for i, arg in enumerate(args):
  18. if type(arg) == np.ndarray:
  19. args[i] = torch.from_numpy(arg)
  20. if unsqueeze:
  21. args[i] = args[i].unsqueeze(0)
  22. result = func(*args)
  23. # Convert output types where applicable
  24. if isinstance(result, tuple):
  25. result = list(result)
  26. for i, res in enumerate(result):
  27. if type(res) == torch.Tensor:
  28. if unsqueeze:
  29. res = res.squeeze(0)
  30. result[i] = res.numpy()
  31. return tuple(result)
  32. elif type(result) == torch.Tensor:
  33. if unsqueeze:
  34. result = result.squeeze(0)
  35. return result.numpy()
  36. else:
  37. return result
  38. def deterministic_random(min_value, max_value, data):
  39. digest = hashlib.sha256(data.encode()).digest()
  40. raw_value = int.from_bytes(digest[:4], byteorder='little', signed=False)
  41. return int(raw_value / (2**32 - 1) * (max_value - min_value)) + min_value