hasher.py 2.54 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
import pickle
5
from collections.abc import Iterable, Mapping
6
7
8
9
10
11
12

import numpy as np
import torch
from blake3 import blake3
from PIL import Image

from vllm.logger import init_logger
13
from vllm.multimodal.image import convert_image_mode
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

logger = init_logger(__name__)

MultiModalHashDict = Mapping[str, list[str]]
"""
A dictionary containing hashes for items in each modality.
"""


class MultiModalHasher:

    @classmethod
    def serialize_item(cls, obj: object) -> bytes:
        # Simple cases
        if isinstance(obj, str):
            return obj.encode("utf-8")
        if isinstance(obj, bytes):
            return obj
32
33
        if isinstance(obj, (int, float)):
            return np.array(obj).tobytes()
34

35
        if isinstance(obj, Image.Image):
36
37
            return cls.item_to_bytes(
                "image", np.asarray(convert_image_mode(obj, "RGBA")))
38
        if isinstance(obj, torch.Tensor):
39
            return cls.item_to_bytes("tensor", obj.numpy())
40
        if isinstance(obj, np.ndarray):
41
42
43
44
            return cls.item_to_bytes(
                "ndarray", {
                    "dtype": obj.dtype.str,
                    "shape": obj.shape,
45
                    "data": obj.tobytes(),
46
                })
47
48
49
50
51
52
53
54
55
56
57
58

        logger.warning(
            "No serialization method found for %s. "
            "Falling back to pickle.", type(obj))

        return pickle.dumps(obj)

    @classmethod
    def item_to_bytes(
        cls,
        key: str,
        obj: object,
59
60
61
62
63
64
65
66
    ) -> bytes:
        return b''.join(kb + vb for kb, vb in cls.iter_item_to_bytes(key, obj))

    @classmethod
    def iter_item_to_bytes(
        cls,
        key: str,
        obj: object,
67
68
69
70
    ) -> Iterable[tuple[bytes, bytes]]:
        # Recursive cases
        if isinstance(obj, (list, tuple)):
            for i, elem in enumerate(obj):
71
                yield from cls.iter_item_to_bytes(f"{key}.{i}", elem)
72
73
        elif isinstance(obj, dict):
            for k, v in obj.items():
74
                yield from cls.iter_item_to_bytes(f"{key}.{k}", v)
75
76
77
78
79
80
81
82
83
84
        else:
            key_bytes = cls.serialize_item(key)
            value_bytes = cls.serialize_item(obj)
            yield key_bytes, value_bytes

    @classmethod
    def hash_kwargs(cls, **kwargs: object) -> str:
        hasher = blake3()

        for k, v in kwargs.items():
85
            for k_bytes, v_bytes in cls.iter_item_to_bytes(k, v):
86
87
88
89
                hasher.update(k_bytes)
                hasher.update(v_bytes)

        return hasher.hexdigest()