vllm/cacheflow/models/model_utils.py

43 lines
1005 B
Python
Raw Normal View History

import random
2023-02-24 05:31:39 +08:00
from typing import Union
import numpy as np
2023-02-24 05:31:39 +08:00
import torch
2023-02-13 17:36:12 +08:00
import torch.nn as nn
2023-02-23 02:08:25 +08:00
from cacheflow.models.opt import OPTForCausalLM
2023-02-13 17:36:12 +08:00
MODEL_CLASSES = {
'opt': OPTForCausalLM,
}
2023-02-24 05:31:39 +08:00
STR_DTYPE_TO_TORCH_DTYPE = {
'half': torch.half,
'float': torch.float,
'float16': torch.float16,
'float32': torch.float32,
}
2023-02-13 17:36:12 +08:00
2023-02-24 05:31:39 +08:00
def get_model(
model_name: str,
dtype: Union[torch.dtype, str],
) -> nn.Module:
if isinstance(dtype, str):
torch_dtype = STR_DTYPE_TO_TORCH_DTYPE[dtype.lower()]
else:
torch_dtype = dtype
2023-02-25 08:29:36 +08:00
for model_class, hf_model in MODEL_CLASSES.items():
2023-02-14 06:51:03 +08:00
if model_class in model_name:
2023-02-25 08:29:36 +08:00
model = hf_model.from_pretrained(model_name, torch_dtype=torch_dtype)
return model.eval()
2023-02-14 06:51:03 +08:00
raise ValueError(f'Invalid model name: {model_name}')
def set_seed(seed: int) -> None:
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)