|
| 1 | +# |
| 2 | +# Copyright 2016 The BigDL Authors. |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +# |
| 16 | +# =========================================================================== |
| 17 | +# |
| 18 | +# This file is adapted from |
| 19 | +# https://github.com/ggerganov/llama.cpp/blob/master/convert.py#L516 |
| 20 | +# |
| 21 | +# MIT License |
| 22 | +# |
| 23 | +# Copyright (c) 2023 Georgi Gerganov |
| 24 | +# |
| 25 | +# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 26 | +# of this software and associated documentation files (the "Software"), to deal |
| 27 | +# in the Software without restriction, including without limitation the rights |
| 28 | +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 29 | +# copies of the Software, and to permit persons to whom the Software is |
| 30 | +# furnished to do so, subject to the following conditions: |
| 31 | +# |
| 32 | +# The above copyright notice and this permission notice shall be included in all |
| 33 | +# copies or substantial portions of the Software. |
| 34 | +# |
| 35 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 36 | +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 37 | +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 38 | +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 39 | +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 40 | +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 41 | +# SOFTWARE. |
| 42 | + |
| 43 | + |
| 44 | +import torch |
| 45 | +from torch.serialization import StorageType |
| 46 | +import pickle |
| 47 | +import zipfile |
| 48 | +import io |
| 49 | +from typing import Dict, IO, Any, Callable |
| 50 | +from dataclasses import dataclass |
| 51 | +from .common import invalidInputError |
| 52 | + |
| 53 | + |
| 54 | +item_size = {torch.bfloat16: 2, |
| 55 | + torch.float16: 2, |
| 56 | + torch.int: 4, |
| 57 | + torch.float: 4, |
| 58 | + torch.float32: 4, |
| 59 | + torch.int8: 1} |
| 60 | + |
| 61 | + |
| 62 | +@dataclass |
| 63 | +class LazyStorage: |
| 64 | + load: Callable[[int, int], torch.Tensor] |
| 65 | + kind: StorageType |
| 66 | + description: str |
| 67 | + |
| 68 | + |
| 69 | +@dataclass |
| 70 | +class LazyTensor: |
| 71 | + _load: Callable[[], torch.Tensor] |
| 72 | + shape: list[int] |
| 73 | + data_type: torch.dtype |
| 74 | + description: str |
| 75 | + |
| 76 | + def load(self) -> torch.Tensor: |
| 77 | + ret = self._load() |
| 78 | + return ret |
| 79 | + |
| 80 | + def to(self, data_type): |
| 81 | + # self.validate_conversion_to(data_type) |
| 82 | + |
| 83 | + def load() -> torch.Tensor: |
| 84 | + print(f"to {data_type}") |
| 85 | + return self.load().to(data_type) |
| 86 | + return LazyTensor(load, self.shape, data_type, f'convert({data_type}) {self.description}') |
| 87 | + |
| 88 | + |
| 89 | +def _load(pickle_fp, map_location, picklemoudle, pickle_file='data.pkl', zip_file=None): |
| 90 | + |
| 91 | + load_module_mapping: Dict[str, str] = { |
| 92 | + 'torch.tensor': 'torch._tensor' |
| 93 | + } |
| 94 | + |
| 95 | + class LazyUnpickler(picklemoudle.Unpickler): |
| 96 | + def __init__(self, fp: IO[bytes], data_base_path: str, zip_file: zipfile.ZipFile): |
| 97 | + super().__init__(fp) |
| 98 | + self.data_base_path = data_base_path |
| 99 | + self.zip_file = zip_file |
| 100 | + |
| 101 | + def persistent_load(self, pid): |
| 102 | + data_type = pid[1].dtype |
| 103 | + filename_stem = pid[2] |
| 104 | + filename = f'{self.data_base_path}/{filename_stem}' |
| 105 | + info = self.zip_file.getinfo(filename) |
| 106 | + |
| 107 | + def load(offset: int, elm_count: int): |
| 108 | + dtype = data_type |
| 109 | + fp = self.zip_file.open(info) |
| 110 | + fp.seek(offset * item_size[dtype]) |
| 111 | + size = elm_count * item_size[dtype] |
| 112 | + data = fp.read(size) |
| 113 | + return torch.frombuffer(bytearray(data), dtype=dtype) |
| 114 | + description = f'storage data_type={data_type} ' \ |
| 115 | + 'path-in-zip={filename} path={self.zip_file.filename}' |
| 116 | + return LazyStorage(load=load, kind=pid[1], description=description) |
| 117 | + |
| 118 | + @staticmethod |
| 119 | + def lazy_rebuild_tensor_v2(storage: Any, |
| 120 | + storage_offset: Any, |
| 121 | + size: Any, |
| 122 | + stride: Any, |
| 123 | + requires_grad: Any, |
| 124 | + backward_hooks: Any, |
| 125 | + metadata: Any = None) -> LazyTensor: |
| 126 | + invalidInputError(isinstance(storage, LazyStorage), |
| 127 | + "storage should be an instance of class `LazyStorage`, " |
| 128 | + f"but get {type(storage)}.") |
| 129 | + |
| 130 | + def load() -> torch.Tensor: |
| 131 | + elm_count = stride[0] * size[0] |
| 132 | + return storage.load(storage_offset, elm_count).reshape(size) |
| 133 | + description = f'pickled storage_offset={storage_offset} in {storage.description}' |
| 134 | + return LazyTensor(load, list(size), storage.kind.dtype, description) |
| 135 | + |
| 136 | + @staticmethod |
| 137 | + def rebuild_from_type_v2(func, new_type, args, state): |
| 138 | + return func(*args) |
| 139 | + |
| 140 | + CLASSES: dict[tuple[str, str], Any] = { |
| 141 | + ('torch._tensor', '_rebuild_from_type_v2'): getattr(rebuild_from_type_v2, '__func__'), |
| 142 | + ('torch._utils', '_rebuild_tensor_v2'): getattr(lazy_rebuild_tensor_v2, '__func__'), |
| 143 | + ('torch', 'Tensor'): LazyTensor, |
| 144 | + } |
| 145 | + |
| 146 | + def find_class(self, mod_name, name): |
| 147 | + if (mod_name, name) in self.CLASSES: |
| 148 | + return self.CLASSES[(mod_name, name)] |
| 149 | + if type(name) is str and 'Storage' in name: |
| 150 | + try: |
| 151 | + return StorageType(name) |
| 152 | + except KeyError: |
| 153 | + pass |
| 154 | + mod_name = load_module_mapping.get(mod_name, mod_name) |
| 155 | + return super().find_class(mod_name, name) |
| 156 | + |
| 157 | + unpickler = LazyUnpickler(pickle_fp, |
| 158 | + data_base_path=pickle_file, |
| 159 | + zip_file=zip_file) |
| 160 | + result = unpickler.load() |
| 161 | + |
| 162 | + return result |
| 163 | + |
| 164 | + |
| 165 | +# This can only be used on huggingface transformers loaded from a zip file. |
| 166 | +def lazyload( |
| 167 | + f, |
| 168 | + *args, |
| 169 | + **kwargs |
| 170 | +): |
| 171 | + if isinstance(f, io.BufferedIOBase): |
| 172 | + fp = f |
| 173 | + else: |
| 174 | + fp = open(f, 'rb') |
| 175 | + zf = zipfile.ZipFile(fp) |
| 176 | + pickle_paths = [name for name in zf.namelist() if name.endswith('.pkl')] |
| 177 | + invalidInputError(len(pickle_paths) == 1, |
| 178 | + "There should be only one pickle_paths found, " |
| 179 | + f"but get {pickle_paths}. ") |
| 180 | + pickle_fp = zf.open(pickle_paths[0], 'r') |
| 181 | + state_dict = _load(pickle_fp, None, pickle, pickle_file=pickle_paths[0][:-4], zip_file=zf) |
| 182 | + return state_dict |
| 183 | + |
| 184 | + |
| 185 | +class LazyLoadTensors: |
| 186 | + def __init__(self): |
| 187 | + self.torch_load = torch.load |
| 188 | + |
| 189 | + def __enter__(self): |
| 190 | + torch.load = lazyload |
| 191 | + |
| 192 | + def __exit__(self, exc_type, exc_value, traceback): |
| 193 | + torch.load = self.torch_load |
0 commit comments