model_loader.py 1.77 KB
Newer Older
1
"""Utilities for selecting and loading models."""
2
3
from typing import Type

Woosuk Kwon's avatar
Woosuk Kwon committed
4
import torch
Woosuk Kwon's avatar
Woosuk Kwon committed
5
import torch.nn as nn
6
from transformers import PretrainedConfig
Woosuk Kwon's avatar
Woosuk Kwon committed
7

8
from cacheflow.config import ModelConfig
9
10
11
from cacheflow.model_executor.models import (
    GPT2LMHeadModel, GPTNeoXForCausalLM, LlamaForCausalLM, OPTForCausalLM)
from cacheflow.model_executor.weight_utils import initialize_dummy_weights
Woosuk Kwon's avatar
Woosuk Kwon committed
12

Woosuk Kwon's avatar
Woosuk Kwon committed
13
14
15
16
17
18
# TODO(woosuk): Lazy-load the model classes.
_MODEL_REGISTRY = {
    "GPT2LMHeadModel": GPT2LMHeadModel,
    "GPTNeoXForCausalLM": GPTNeoXForCausalLM,
    "LlamaForCausalLM": LlamaForCausalLM,
    "OPTForCausalLM": OPTForCausalLM,
Woosuk Kwon's avatar
Woosuk Kwon committed
19
20
}

21

22
def _get_model_architecture(config: PretrainedConfig) -> Type[nn.Module]:
Woosuk Kwon's avatar
Woosuk Kwon committed
23
24
25
26
27
28
29
30
31
32
    architectures = getattr(config, "architectures", [])
    for arch in architectures:
        if arch in _MODEL_REGISTRY:
            return _MODEL_REGISTRY[arch]
    raise ValueError(
        f"Model architectures {architectures} are not supported for now. "
        f"Supported architectures: {list(_MODEL_REGISTRY.keys())}"
    )


33
34
35
def get_model(model_config: ModelConfig) -> nn.Module:
    model_class = _get_model_architecture(model_config.hf_config)
    torch.set_default_dtype(model_config.dtype)
Woosuk Kwon's avatar
Woosuk Kwon committed
36
37
38

    # Create a model instance.
    # The weights will be initialized as empty tensors.
39
40
    model = model_class(model_config.hf_config)
    if model_config.use_dummy_weights:
Woosuk Kwon's avatar
Woosuk Kwon committed
41
42
43
44
45
46
        model = model.cuda()
        # NOTE(woosuk): For accurate performance evaluation, we assign
        # random values to the weights.
        initialize_dummy_weights(model)
    else:
        # Load the weights from the cached or downloaded files.
47
48
49
        model.load_weights(
            model_config.model, model_config.download_dir,
            model_config.use_np_weights)
Woosuk Kwon's avatar
Woosuk Kwon committed
50
        model = model.cuda()
51
    return model.eval()