base_loader.py 4.45 KB
Newer Older
huteng.ht's avatar
huteng.ht committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
'''
Copyright (c) 2024 Beijing Volcano Engine Technology Ltd.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''

17
import io
huteng.ht's avatar
huteng.ht committed
18
19
20
21
22
23
from typing import Any, Dict

import numpy as np
import torch
from numpy import ndarray

24
25
from veturboio.ops.cipher import CipherInfo, decrypt

huteng.ht's avatar
huteng.ht committed
26
27
28
29
30
31
32
33
34
35
36
# from veturboio.safetensors import SafetensorsFile
from veturboio.types import FILE_PATH

SAFETENSORS_FILE_MAGIC_NUM = 123
BUF_ALIGN_SIZE = 4096


class BaseLoader:
    def __init__(self, method: str) -> None:
        self.method = method

37
38
39
    def load_to_bytes_array(
        self, file: FILE_PATH, offset: int, count: int, cipher_info: CipherInfo = CipherInfo(False)
    ) -> ndarray:
huteng.ht's avatar
huteng.ht committed
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
        raise NotImplementedError

    def load_safetensors(self, safetensors_file: Any, map_location: str = "cpu") -> Dict[str, torch.Tensor]:
        raise NotImplementedError

    def init_aligned_tensor(self, device, device_id: int, file_size, base_offset: int) -> torch.Tensor:
        if device_id != -1:
            try:
                total_tensor = torch.empty(file_size - base_offset, dtype=torch.uint8, device=device)
            except RuntimeError as e:
                msg = str(e)
                raise RuntimeError(msg)

        else:
            array = np.empty(file_size - base_offset + BUF_ALIGN_SIZE, dtype=np.uint8)
            offset1 = array.ctypes.data % BUF_ALIGN_SIZE
            offset2 = base_offset % BUF_ALIGN_SIZE
            if offset1 > offset2:
                align = BUF_ALIGN_SIZE - offset1 + offset2
            else:
                align = offset2 - offset1

            sub_array = array[align : align + file_size - base_offset].view(dtype=np.uint8)
            total_tensor = torch.from_numpy(sub_array)
        return total_tensor


class PosixLoader(BaseLoader):
    def __init__(self) -> None:
        super().__init__(method="posix")

71
72
73
74
75
76
77
78
    def load_to_bytes_array(
        self, file: FILE_PATH, offset: int, count: int, cipher_info: CipherInfo = CipherInfo(False)
    ) -> ndarray:
        arr = np.fromfile(file, dtype=np.uint8, offset=offset, count=count)
        if cipher_info.use_cipher:
            h_off = CipherInfo.HEADER_SIZE if cipher_info.use_header else 0
            decrypt(cipher_info, arr, arr, offset - h_off)
        return arr
huteng.ht's avatar
huteng.ht committed
79
80
81
82
83
84
85

    def load_safetensors(self, safetensors_file: Any, map_location: str = "cpu") -> Dict[str, torch.Tensor]:
        state_dict = {}

        base_offset = safetensors_file.tensor_offset
        device = torch.device(map_location)

86
87
88
        cipher_info = safetensors_file._cipher_info
        mp_mode = "c" if cipher_info.use_cipher else "r"

huteng.ht's avatar
huteng.ht committed
89
90
91
        for tensor_meta in safetensors_file.meta.values():
            tensor_bytes = np.memmap(
                safetensors_file.file,
92
93
                dtype=np.uint8,
                mode=mp_mode,
huteng.ht's avatar
huteng.ht committed
94
95
96
                offset=base_offset + tensor_meta.data_offsets[0],
                shape=tensor_meta.data_offsets[1] - tensor_meta.data_offsets[0],
            )
97
98
99
            if cipher_info.use_cipher:
                h_off = CipherInfo.HEADER_SIZE if cipher_info.use_header else 0
                decrypt(cipher_info, tensor_bytes, tensor_bytes, base_offset + tensor_meta.data_offsets[0] - h_off)
huteng.ht's avatar
huteng.ht committed
100
101
102
103
104
105
106
107
108
            tensor = torch.frombuffer(tensor_bytes, dtype=tensor_meta.dtype)
            tensor = tensor.view(tensor_meta.shape)
            if device.type == "cuda":
                state_dict[tensor_meta.name] = tensor.pin_memory().to(device=device, non_blocking=True)
            else:
                state_dict[tensor_meta.name] = tensor

        return state_dict

109
110
111
112
113
114
115
116
117
    def load_pt(
        self, file: FILE_PATH, map_location: str = "cpu", cipher_info: CipherInfo = CipherInfo(False)
    ) -> Dict[str, torch.Tensor]:
        if cipher_info.use_cipher:
            h_off = CipherInfo.HEADER_SIZE if cipher_info.use_header else 0
            arr = np.fromfile(file, dtype=np.uint8, offset=h_off, count=-1)
            decrypt(cipher_info, arr, arr, 0)
            return torch.load(io.BytesIO(arr.data), map_location=map_location)

huteng.ht's avatar
huteng.ht committed
118
        return torch.load(file, map_location=map_location)