_reduction.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. from typing import Optional
  2. import warnings
  3. # NB: Keep this file in sync with enums in aten/src/ATen/core/Reduction.h
  4. def get_enum(reduction: str) -> int:
  5. if reduction == 'none':
  6. ret = 0
  7. elif reduction == 'mean':
  8. ret = 1
  9. elif reduction == 'elementwise_mean':
  10. warnings.warn("reduction='elementwise_mean' is deprecated, please use reduction='mean' instead.")
  11. ret = 1
  12. elif reduction == 'sum':
  13. ret = 2
  14. else:
  15. ret = -1 # TODO: remove once JIT exceptions support control flow
  16. raise ValueError("{} is not a valid value for reduction".format(reduction))
  17. return ret
  18. # In order to support previous versions, accept boolean size_average and reduce
  19. # and convert them into the new constants for now
  20. # We use these functions in torch/legacy as well, in which case we'll silence the warning
  21. def legacy_get_string(size_average: Optional[bool], reduce: Optional[bool], emit_warning: bool = True) -> str:
  22. warning = "size_average and reduce args will be deprecated, please use reduction='{}' instead."
  23. if size_average is None:
  24. size_average = True
  25. if reduce is None:
  26. reduce = True
  27. if size_average and reduce:
  28. ret = 'mean'
  29. elif reduce:
  30. ret = 'sum'
  31. else:
  32. ret = 'none'
  33. if emit_warning:
  34. warnings.warn(warning.format(ret))
  35. return ret
  36. def legacy_get_enum(size_average: Optional[bool], reduce: Optional[bool], emit_warning: bool = True) -> int:
  37. return get_enum(legacy_get_string(size_average, reduce, emit_warning))