utils.py 1.86 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
"""Utils for model executor."""
3
from typing import Any, Optional
4
5
6
7
8

import torch


def set_random_seed(seed: int) -> None:
9
    from vllm.platforms import current_platform
10
    current_platform.seed_everything(seed)
11
12
13
14


def set_weight_attrs(
    weight: torch.Tensor,
15
    weight_attrs: Optional[dict[str, Any]],
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
):
    """Set attributes on a weight tensor.

    This method is used to set attributes on a weight tensor. This method
    will not overwrite existing attributes.

    Args:
        weight: The weight tensor.
        weight_attrs: A dictionary of attributes to set on the weight tensor.
    """
    if weight_attrs is None:
        return
    for key, value in weight_attrs.items():
        assert not hasattr(
            weight, key), (f"Overwriting existing tensor attribute: {key}")
31
32
33
34
35
36
37
38
39
40

        # NOTE(woosuk): During weight loading, we often do something like:
        # narrowed_tensor = param.data.narrow(0, offset, len)
        # narrowed_tensor.copy_(real_weight)
        # expecting narrowed_tensor and param.data to share the same storage.
        # However, on TPUs, narrowed_tensor will lazily propagate to the base
        # tensor, which is param.data, leading to the redundant memory usage.
        # This sometimes causes OOM errors during model loading. To avoid this,
        # we sync the param tensor after its weight loader is called.
        # TODO(woosuk): Remove this hack once we have a better solution.
41
        from vllm.platforms import current_platform
42
43
        if current_platform.is_tpu() and key == "weight_loader":
            value = _make_synced_weight_loader(value)
44
        setattr(weight, key, value)
45
46
47
48
49
50
51
52
53


def _make_synced_weight_loader(original_weight_loader):

    def _synced_weight_loader(param, *args, **kwargs):
        original_weight_loader(param, *args, **kwargs)
        torch._sync(param)

    return _synced_weight_loader