_composable_state.py 949 B

1234567891011121314151617181920212223242526272829303132
  1. from typing import cast, Dict, Optional
  2. import torch.nn as nn
  3. class _State:
  4. pass
  5. _module_state_mapping: Dict[nn.Module, _State] = {}
  6. def _insert_module_state(module: nn.Module, state: _State) -> None:
  7. global _module_state_mapping
  8. assert module not in _module_state_mapping, f"Inserting {module} more than once."
  9. _module_state_mapping[module] = state
  10. def _get_module_state(module: nn.Module) -> Optional[_State]:
  11. """
  12. Given a ``module``, this API finds out if the module is also a ``_State``
  13. instance or if the module is managed by a composable API. If the module
  14. is also a ``_State``, ``module`` will be casted to ``_State` and returned.
  15. If it is managed by a composable API, the corresponding ``_State`` will
  16. be returned.
  17. """
  18. global _module_state_mapping
  19. if isinstance(module, _State):
  20. return cast(_State, module)
  21. else:
  22. return _module_state_mapping.get(module, None)