|
| 1 | +# Copyright 2023 MathInf GmbH |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this files from this repository except in compliance |
| 5 | +# with the License reproduced below (also at |
| 6 | +# http://www.apache.org/licenses/LICENSE-2.0). |
| 7 | +# |
| 8 | +# Unless required by applicable law or agreed to in writing, software |
| 9 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +# See the License for the specific language governing permissions and |
| 12 | +# limitations under the License. |
| 13 | +import pickle |
| 14 | +import warnings |
| 15 | +from functools import partial |
| 16 | +from io import BytesIO |
| 17 | +from typing import Any, Callable, Dict, IO, Optional, OrderedDict, Sequence, TYPE_CHECKING, Union |
| 18 | + |
| 19 | +import torch |
| 20 | +from lightning_utilities.core.apply_func import apply_to_collection |
| 21 | +from torch import Tensor |
| 22 | +from torch._C import _TensorMeta |
| 23 | +from torch.nn import Parameter |
| 24 | + |
| 25 | +from lightning.fabric.utilities.imports import _TORCH_GREATER_EQUAL_2_0 |
| 26 | +from lightning.fabric.utilities.types import _PATH |
| 27 | + |
| 28 | +if TYPE_CHECKING: |
| 29 | + from torch.storage import TypedStorage |
| 30 | + |
| 31 | + |
| 32 | +# Modified from https://github.com/lernapparat/torchhacks by Thomas Viehmann |
| 33 | +class _NotYetLoadedTensor: |
| 34 | + def __init__( |
| 35 | + self, |
| 36 | + metatensor: Tensor, |
| 37 | + archiveinfo: "_LazyLoadingUnpickler", |
| 38 | + storageinfo: tuple, |
| 39 | + rebuild_args: tuple, |
| 40 | + ) -> None: |
| 41 | + self.metatensor = metatensor |
| 42 | + self.archiveinfo = archiveinfo |
| 43 | + self.storageinfo = storageinfo |
| 44 | + self.rebuild_args = rebuild_args |
| 45 | + |
| 46 | + @classmethod |
| 47 | + def rebuild_from_type_v2( |
| 48 | + cls, |
| 49 | + func: Callable, |
| 50 | + new_type: _TensorMeta, |
| 51 | + args: tuple, |
| 52 | + state: dict, |
| 53 | + *, |
| 54 | + archiveinfo: Optional["_LazyLoadingUnpickler"] = None, |
| 55 | + ) -> Any: |
| 56 | + ret = func(*args) |
| 57 | + if isinstance(ret, _NotYetLoadedTensor): |
| 58 | + old_lt = ret._load_tensor |
| 59 | + |
| 60 | + def _load_tensor() -> Any: |
| 61 | + t = old_lt() |
| 62 | + return torch._tensor._rebuild_from_type_v2(lambda: t, new_type, (), state) |
| 63 | + |
| 64 | + ret._load_tensor = _load_tensor # type: ignore[method-assign] |
| 65 | + return ret |
| 66 | + return torch._tensor._rebuild_from_type_v2(func, new_type, args, state) |
| 67 | + |
| 68 | + @classmethod |
| 69 | + def rebuild_parameter( |
| 70 | + cls, |
| 71 | + data: Any, |
| 72 | + requires_grad: bool, |
| 73 | + backward_hooks: OrderedDict, |
| 74 | + *, |
| 75 | + archiveinfo: Optional["_LazyLoadingUnpickler"] = None, |
| 76 | + ) -> Union[Tensor, "_NotYetLoadedTensor"]: |
| 77 | + if isinstance(data, _NotYetLoadedTensor): |
| 78 | + old_lt = data._load_tensor |
| 79 | + |
| 80 | + def _load_tensor() -> Parameter: |
| 81 | + t = old_lt() |
| 82 | + return torch._utils._rebuild_parameter(t, requires_grad, backward_hooks) |
| 83 | + |
| 84 | + data._load_tensor = _load_tensor # type: ignore[method-assign] |
| 85 | + return data |
| 86 | + return torch._utils._rebuild_parameter(data, requires_grad, backward_hooks) |
| 87 | + |
| 88 | + @classmethod |
| 89 | + def rebuild_tensor_v2( |
| 90 | + cls, |
| 91 | + storage: "TypedStorage", |
| 92 | + storage_offset: int, |
| 93 | + size: tuple, |
| 94 | + stride: tuple, |
| 95 | + requires_grad: bool, |
| 96 | + backward_hooks: OrderedDict, |
| 97 | + metadata: Optional[Any] = None, |
| 98 | + *, |
| 99 | + archiveinfo: "_LazyLoadingUnpickler", |
| 100 | + ) -> "_NotYetLoadedTensor": |
| 101 | + rebuild_args = (storage_offset, size, stride, requires_grad, backward_hooks, metadata) |
| 102 | + metatensor = torch._utils._rebuild_tensor_v2( |
| 103 | + storage, storage_offset, size, stride, requires_grad, backward_hooks, metadata |
| 104 | + ) |
| 105 | + storageinfo = storage.archiveinfo |
| 106 | + return _NotYetLoadedTensor(metatensor, archiveinfo, storageinfo, rebuild_args) |
| 107 | + |
| 108 | + def _load_tensor(self) -> Tensor: |
| 109 | + from torch.storage import TypedStorage, UntypedStorage |
| 110 | + |
| 111 | + name, storage_cls, fn, device, size = self.storageinfo |
| 112 | + dtype = self.metatensor.dtype |
| 113 | + |
| 114 | + storage = self.archiveinfo.file_reader.get_storage_from_record( |
| 115 | + f"data/{fn}", size * torch._utils._element_size(dtype), UntypedStorage |
| 116 | + ) |
| 117 | + uts = storage._typed_storage()._untyped_storage |
| 118 | + |
| 119 | + with warnings.catch_warnings(): |
| 120 | + # The TypedStorage APIs have heavy deprecations in torch, suppress all these warnings for now |
| 121 | + warnings.simplefilter("ignore") |
| 122 | + storage = TypedStorage(wrap_storage=uts, dtype=dtype, _internal=True) |
| 123 | + return torch._utils._rebuild_tensor_v2(storage, *self.rebuild_args) |
| 124 | + |
| 125 | + @classmethod |
| 126 | + def __torch_function__( |
| 127 | + cls, |
| 128 | + func: Callable, |
| 129 | + types: Sequence, |
| 130 | + args: Sequence[Any] = (), |
| 131 | + kwargs: Optional[Dict] = None, |
| 132 | + ) -> Any: |
| 133 | + kwargs = kwargs or {} |
| 134 | + loaded_args = [(arg._load_tensor() if isinstance(arg, _NotYetLoadedTensor) else arg) for arg in args] |
| 135 | + return func(*loaded_args, **kwargs) |
| 136 | + |
| 137 | + def __getattr__(self, name: str) -> Any: |
| 138 | + # These properties don't require materialization and can be accessed through the meta tensor directly |
| 139 | + if name in { |
| 140 | + "dtype", |
| 141 | + "grad", |
| 142 | + "grad_fn", |
| 143 | + "layout", |
| 144 | + "names", |
| 145 | + "ndim", |
| 146 | + "output_nr", |
| 147 | + "requires_grad", |
| 148 | + "retains_grad", |
| 149 | + "size", |
| 150 | + "shape", |
| 151 | + "volatile", |
| 152 | + }: |
| 153 | + return getattr(self.metatensor, name) |
| 154 | + |
| 155 | + # Materialization with contiguous is needed for quantization (see lit-gpt) |
| 156 | + if name in {"contiguous"}: |
| 157 | + return getattr(self._load_tensor(), name) |
| 158 | + |
| 159 | + raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'") |
| 160 | + |
| 161 | + def __repr__(self) -> str: |
| 162 | + return f"{self.__class__.__name__}({repr(self.metatensor)})" |
| 163 | + |
| 164 | + |
| 165 | +# Modified from https://github.com/lernapparat/torchhacks by Thomas Viehmann |
| 166 | +class _LazyLoadingUnpickler(pickle.Unpickler): |
| 167 | + def __init__(self, file: IO, file_reader: torch.PyTorchFileReader) -> None: |
| 168 | + super().__init__(file) |
| 169 | + self.file_reader = file_reader |
| 170 | + |
| 171 | + def find_class(self, module: str, name: str) -> Any: |
| 172 | + if module == "torch._utils" and name == "_rebuild_tensor_v2": |
| 173 | + return partial(_NotYetLoadedTensor.rebuild_tensor_v2, archiveinfo=self) |
| 174 | + if module == "torch._tensor" and name == "_rebuild_from_type_v2": |
| 175 | + return partial(_NotYetLoadedTensor.rebuild_from_type_v2, archiveinfo=self) |
| 176 | + if module == "torch._utils" and name == "_rebuild_parameter": |
| 177 | + return partial(_NotYetLoadedTensor.rebuild_parameter, archiveinfo=self) |
| 178 | + return super().find_class(module, name) |
| 179 | + |
| 180 | + def persistent_load(self, pid: tuple) -> "TypedStorage": |
| 181 | + from torch.storage import TypedStorage |
| 182 | + |
| 183 | + name, cls, fn, device, size = pid |
| 184 | + with warnings.catch_warnings(): |
| 185 | + # The TypedStorage APIs have heavy deprecations in torch, suppress all these warnings for now |
| 186 | + warnings.simplefilter("ignore") |
| 187 | + storage = TypedStorage(dtype=cls().dtype, device="meta") |
| 188 | + storage.archiveinfo = pid |
| 189 | + return storage |
| 190 | + |
| 191 | + |
| 192 | +def _lazy_load(filename: _PATH) -> Any: |
| 193 | + if not _TORCH_GREATER_EQUAL_2_0: |
| 194 | + raise NotImplementedError("Lazy-loading is only supported with PyTorch >= 2.0.") |
| 195 | + file_reader = torch.PyTorchFileReader(str(filename)) |
| 196 | + with BytesIO(file_reader.get_record("data.pkl")) as pkl: |
| 197 | + mup = _LazyLoadingUnpickler(pkl, file_reader) |
| 198 | + return mup.load() |
| 199 | + |
| 200 | + |
| 201 | +def _materialize_tensors(collection: Any) -> Any: |
| 202 | + def _load_tensor(t: _NotYetLoadedTensor) -> Tensor: |
| 203 | + return t._load_tensor() |
| 204 | + |
| 205 | + return apply_to_collection(collection, dtype=_NotYetLoadedTensor, function=_load_tensor) |
0 commit comments