| 31 | """Recursively apply to all objects in different kinds of container types that matches a type function.""" |
| 32 | |
| 33 | def _apply(x: Union[torch.Tensor, np.ndarray, Dict, List, Tuple, Set]) -> Any: |
| 34 | if type_fn(x): |
| 35 | return fn(x) |
| 36 | elif isinstance(x, OrderedDict): |
| 37 | od = x.__class__() |
| 38 | for key, value in x.items(): |
| 39 | od[key] = _apply(value) |
| 40 | return od |
| 41 | elif isinstance(x, PackedSequence): |
| 42 | _apply(x.data) |
| 43 | return x |
| 44 | elif isinstance(x, dict): |
| 45 | return {key: _apply(value) for key, value in x.items()} |
| 46 | elif isinstance(x, list): |
| 47 | return [_apply(x) for x in x] |
| 48 | elif isinstance(x, tuple): |
| 49 | f = getattr(x, "_fields", None) |
| 50 | if f is None: |
| 51 | return tuple(_apply(x) for x in x) |
| 52 | else: |
| 53 | assert isinstance(f, tuple), "This needs to be a namedtuple" |
| 54 | # convert the namedtuple to a dict and _apply(). |
| 55 | x = cast(NamedTuple, x) |
| 56 | _dict: Dict[str, Any] = x._asdict() |
| 57 | _dict = {key: _apply(value) for key, value in _dict.items()} |
| 58 | return type(x)(**_dict) # make a copy of the namedtuple |
| 59 | elif isinstance(x, set): |
| 60 | return {_apply(x) for x in x} |
| 61 | else: |
| 62 | return x |
| 63 | |
| 64 | return _apply(container) |
| 65 | |