You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

module_utils.py 2.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  2. #
  3. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  4. #
  5. # Unless required by applicable law or agreed to in writing,
  6. # software distributed under the License is distributed on an
  7. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8. import contextlib
  9. from collections import Iterable
  10. from ..module import Sequential
  11. from ..module.module import Module, _access_structure
  12. from ..tensor import Tensor
  13. def get_expand_structure(obj: Module, key: str):
  14. r"""Gets Module's attribute compatible with complex key from Module's :meth:`~.named_children`.
  15. Supports handling structure containing list or dict.
  16. Args:
  17. obj: Module:
  18. key: str:
  19. """
  20. def f(_, __, cur):
  21. return cur
  22. return _access_structure(obj, key, callback=f)
  23. def set_expand_structure(obj: Module, key: str, value):
  24. r"""Sets Module's attribute compatible with complex key from Module's :meth:`~.named_children`.
  25. Supports handling structure containing list or dict.
  26. """
  27. def f(parent, key, cur):
  28. if isinstance(parent, (Tensor, Module)):
  29. # cannnot use setattr to be compatible with Sequential's ``__setitem__``
  30. if isinstance(cur, Sequential):
  31. parent[int(key)] = value
  32. else:
  33. setattr(parent, key, value)
  34. else:
  35. parent[key] = value
  36. _access_structure(obj, key, callback=f)
  37. @contextlib.contextmanager
  38. def set_module_mode_safe(
  39. module: Module, training: bool = False,
  40. ):
  41. r"""Adjust module to training/eval mode temporarily.
  42. Args:
  43. module: used module.
  44. training: training (bool): training mode. True for train mode, False fro eval mode.
  45. """
  46. backup_stats = {}
  47. def recursive_backup_stats(module, mode):
  48. for m in module.modules():
  49. backup_stats[m] = m.training
  50. m.train(mode, recursive=False)
  51. def recursive_recover_stats(module):
  52. for m in module.modules():
  53. m.training = backup_stats.pop(m)
  54. recursive_backup_stats(module, mode=training)
  55. yield module
  56. recursive_recover_stats(module)