Langchain-Chatchat/models/chatglm_llm.py

76 lines
2.2 KiB
Python
Raw Normal View History

2023-03-31 20:09:40 +08:00
from langchain.llms.base import LLM
from typing import Optional, List
from langchain.llms.utils import enforce_stop_tokens
from transformers import AutoTokenizer, AutoModel
import torch
2023-04-13 23:01:52 +08:00
from configs.model_config import LLM_DEVICE
2023-04-13 23:01:52 +08:00
DEVICE = LLM_DEVICE
2023-04-11 21:55:42 +08:00
DEVICE_ID = "0" if torch.cuda.is_available() else None
CUDA_DEVICE = f"{DEVICE}:{DEVICE_ID}" if DEVICE_ID else DEVICE
def torch_gc():
if torch.cuda.is_available():
with torch.cuda.device(CUDA_DEVICE):
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
2023-03-31 20:09:40 +08:00
class ChatGLM(LLM):
max_token: int = 10000
2023-04-11 21:55:42 +08:00
temperature: float = 0.01
2023-03-31 20:09:40 +08:00
top_p = 0.9
history = []
tokenizer: object = None
model: object = None
history_len: int = 10
2023-03-31 20:09:40 +08:00
def __init__(self):
super().__init__()
@property
def _llm_type(self) -> str:
return "ChatGLM"
def _call(self,
prompt: str,
stop: Optional[List[str]] = None) -> str:
response, _ = self.model.chat(
self.tokenizer,
2023-03-31 20:09:40 +08:00
prompt,
history=self.history[-self.history_len:] if self.history_len>0 else [],
2023-03-31 20:09:40 +08:00
max_length=self.max_token,
temperature=self.temperature,
)
torch_gc()
2023-03-31 20:09:40 +08:00
if stop is not None:
response = enforce_stop_tokens(response, stop)
self.history = self.history+[[None, response]]
2023-03-31 20:09:40 +08:00
return response
2023-04-13 23:01:52 +08:00
def load_model(self,
model_name_or_path: str = "THUDM/chatglm-6b",
llm_device=LLM_DEVICE):
self.tokenizer = AutoTokenizer.from_pretrained(
model_name_or_path,
trust_remote_code=True
)
2023-04-13 23:01:52 +08:00
if torch.cuda.is_available() and llm_device.lower().startswith("cuda"):
2023-04-11 21:55:42 +08:00
self.model = (
AutoModel.from_pretrained(
model_name_or_path,
trust_remote_code=True)
.half()
.cuda()
)
else:
self.model = (
AutoModel.from_pretrained(
model_name_or_path,
trust_remote_code=True)
.float()
2023-04-13 23:01:52 +08:00
.to(llm_device)
2023-04-11 21:55:42 +08:00
)
self.model = self.model.eval()