_composable_state.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import weakref
  2. from typing import cast, Optional
  3. import torch.nn as nn
  4. class _State:
  5. pass
  6. _module_state_mapping: weakref.WeakKeyDictionary[
  7. nn.Module, weakref.ReferenceType[_State]
  8. ] = weakref.WeakKeyDictionary()
  9. def _insert_module_state(module: nn.Module, state: _State) -> None:
  10. global _module_state_mapping
  11. assert module not in _module_state_mapping, f"Inserting {module} more than once."
  12. _module_state_mapping[module] = weakref.ref(state)
  13. def _get_module_state(module: nn.Module) -> Optional[_State]:
  14. """
  15. Return the ``_State`` in ``model``.
  16. Given a ``module``, this API finds out if the module is also a ``_State``
  17. instance or if the module is managed by a composable API. If the module
  18. is also a ``_State``, ``module`` will be casted to ``_State` and returned.
  19. If it is managed by a composable API, the corresponding ``_State`` will
  20. be returned.
  21. """
  22. global _module_state_mapping
  23. if isinstance(module, _State):
  24. return cast(_State, module)
  25. else:
  26. # https://github.com/pytorch/pytorch/issues/107054
  27. if module in _module_state_mapping:
  28. state_ref = _module_state_mapping[module]
  29. state = state_ref()
  30. if state is None:
  31. raise AssertionError("State has already been garbage collected")
  32. return state
  33. else:
  34. return None