_nested_dict.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # Copyright (c) Meta Platforms, Inc. and affiliates
  2. from typing import Dict, Tuple
  3. from torch.distributed.checkpoint.metadata import (
  4. STATE_DICT_TYPE,
  5. )
  6. from ._traverse import (
  7. traverse_state_dict,
  8. set_element,
  9. OBJ_PATH,
  10. STATE_DICT_ITEM,
  11. )
  12. """
  13. TODO:
  14. Need to add ability to handle tuple, OrderedDict, NamedTuple.
  15. Update mappings from dict to a class.
  16. Change set_element to recreate the right type for tuple, OrderedDict, and NamedTuple.
  17. """
  18. FLATTEN_MAPPING = Dict[str, OBJ_PATH]
  19. # TODO: Update Docstring for nested_dict.py
  20. def flatten_state_dict(
  21. state_dict: STATE_DICT_TYPE,
  22. ) -> Tuple[STATE_DICT_TYPE, FLATTEN_MAPPING]:
  23. """
  24. Flatten ``state_dict`` made of nested dicts and lists into a top level dictionary.
  25. Use ``unflatten_state_dict`` to revert this process.
  26. Returns:
  27. A tuple with the flaten state_dict and a mapping from original to new state_dict.
  28. N.B. The new keys are derived from the object paths, joined by dot.
  29. For example: ``{ 'a': {'b':...}}`` results in the key `a.b`.
  30. """
  31. flattened: STATE_DICT_TYPE = {}
  32. mappings: FLATTEN_MAPPING = {}
  33. def flat_copy(path: OBJ_PATH, value: STATE_DICT_ITEM) -> None:
  34. new_fqn = ".".join(map(str, path))
  35. if new_fqn in flattened:
  36. raise ValueError(f"duplicated flatten key {new_fqn}")
  37. flattened[new_fqn] = value
  38. mappings[new_fqn] = path
  39. traverse_state_dict(state_dict, flat_copy)
  40. return flattened, mappings
  41. def unflatten_state_dict(
  42. state_dict: STATE_DICT_TYPE, mapping: FLATTEN_MAPPING
  43. ) -> STATE_DICT_TYPE:
  44. """
  45. Restore the original nested state_dict according to ``mapping`` and the flattened ``state_dict``
  46. """
  47. nested: STATE_DICT_TYPE = {}
  48. for key, value in state_dict.items():
  49. set_element(nested, mapping[key], value)
  50. return nested