fp16.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
  2. # Redistribution and use in source and binary forms, with or without
  3. # modification, are permitted provided that the following conditions are met:
  4. # * Redistributions of source code must retain the above copyright
  5. # notice, this list of conditions and the following disclaimer.
  6. # * Redistributions in binary form must reproduce the above copyright
  7. # notice, this list of conditions and the following disclaimer in the
  8. # documentation and/or other materials provided with the distribution.
  9. # * Neither the name of the NVIDIA CORPORATION nor the
  10. # names of its contributors may be used to endorse or promote products
  11. # derived from this software without specific prior written permission.
  12. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  13. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  14. # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  15. # DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
  16. # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  17. # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  18. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  19. # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  20. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  21. # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  22. import torch
  23. import torch.nn as nn
  24. """
  25. Revised based on apex/apex/amp/_initialize.py
  26. """
  27. def _applier(value, fn):
  28. if isinstance(value, torch.cuda.FloatTensor):
  29. return fn(value)
  30. elif isinstance(value, torch.cuda.HalfTensor):
  31. return fn(value)
  32. elif isinstance(value, dict):
  33. return dict({k : _applier(v, fn) for k, v in value.items()})
  34. elif isinstance(value, tuple):
  35. return tuple(_applier(v, fn) for v in value)
  36. else:
  37. return value
  38. def _cast_module_to_half(module, op_list):
  39. for op in op_list:
  40. if isinstance(module, op):
  41. module.half()
  42. module.register_forward_pre_hook(lambda module, input: _applier(input, lambda x: x.half()))
  43. module.register_forward_hook(lambda module, input, output: _applier(output, lambda x: x.float()))
  44. break
  45. else:
  46. for child in module.children():
  47. _cast_module_to_half(child, op_list)
  48. return module
  49. def cast_model_to_half(model, op_list=[nn.Linear, nn.Conv1d]):
  50. model = _cast_module_to_half(model, op_list)
  51. return model