|
3 | 3 | Any, |
4 | 4 | Callable, |
5 | 5 | Dict, |
| 6 | + List, |
6 | 7 | Mapping, |
| 8 | + NamedTuple, |
7 | 9 | Optional, |
8 | 10 | Sequence, |
9 | 11 | Tuple, |
10 | 12 | Type, |
11 | 13 | Union, |
| 14 | + cast, |
12 | 15 | ) |
13 | 16 |
|
14 | 17 | import pytorch_pfn_extras.handler as handler_module |
|
27 | 30 | from pytorch_pfn_extras.training.trigger import TriggerLike |
28 | 31 |
|
29 | 32 |
|
| 33 | +def filter_state_objects( |
| 34 | + args: Any, key_name: str = "" |
| 35 | +) -> List[Tuple[str, StateObjectProtocol]]: |
| 36 | + if isinstance(args, tuple) and hasattr(args, "_fields"): |
| 37 | + # namedtuple |
| 38 | + return filter_state_objects_dict( |
| 39 | + cast(NamedTuple, args)._asdict(), key_name=key_name |
| 40 | + ) |
| 41 | + if isinstance(args, dict): |
| 42 | + return filter_state_objects_dict(args, key_name=key_name) |
| 43 | + if isinstance(args, (list, tuple)): |
| 44 | + return sum( |
| 45 | + [ |
| 46 | + filter_state_objects(v, key_name=f"{key_name}.__{i}__") |
| 47 | + for i, v in enumerate(args) |
| 48 | + ], |
| 49 | + [], |
| 50 | + ) |
| 51 | + if isinstance(args, StateObjectProtocol): |
| 52 | + return [(key_name, args)] |
| 53 | + return [] |
| 54 | + |
| 55 | + |
| 56 | +def filter_state_objects_dict( |
| 57 | + args: Dict[str, Any], key_name: str = "option" |
| 58 | +) -> List[Tuple[str, StateObjectProtocol]]: |
| 59 | + return sum( |
| 60 | + [ |
| 61 | + filter_state_objects(v, key_name=f"{key_name}__::__{k}") |
| 62 | + for k, v in sorted(args.items()) |
| 63 | + ], |
| 64 | + [], |
| 65 | + ) |
| 66 | + |
| 67 | + |
30 | 68 | def create_trainer( |
31 | 69 | models: Union[torch.nn.Module, Mapping[str, torch.nn.Module]], |
32 | 70 | optimizers: Union[ |
@@ -109,9 +147,13 @@ def create_trainer( |
109 | 147 | options = options.copy() if options else {} |
110 | 148 |
|
111 | 149 | state_objects: Dict[str, StateObjectProtocol] = {} |
112 | | - for key, value in options.items(): |
113 | | - if isinstance(value, StateObjectProtocol): |
114 | | - state_objects[f"options_{key}"] = value |
| 150 | + state_objects_list = filter_state_objects(options) |
| 151 | + for key, value in state_objects_list: |
| 152 | + state_objects[f"options_{key}"] = value |
| 153 | + |
| 154 | + assert len(state_objects_list) == len( |
| 155 | + state_objects |
| 156 | + ), "There was a duplicate key name in the flattened options dictionary object." |
115 | 157 |
|
116 | 158 | # TODO(kmaehashi): deprecate specifying 'runtime' key in options |
117 | 159 | runtime_options = dict( |
|
0 commit comments