Langchain-Chatchat/chatglm_llm.py

65 lines
1.7 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
DEVICE = "cuda"
DEVICE_ID = "0"
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):
model_name: str
2023-03-31 20:09:40 +08:00
max_token: int = 10000
temperature: float = 0.1
top_p = 0.9
history = []
tokenizer: object = None
model: object = None
2023-03-31 20:09:40 +08:00
def __init__(self):
super().__init__()
def load_model(self,
model_name_or_path: str = "THUDM/chatglm-6b"):
self.tokenizer = AutoTokenizer.from_pretrained(
model_name_or_path,
trust_remote_code=True
)
self.model = (
AutoModel.from_pretrained(
model_name_or_path,
trust_remote_code=True)
.half()
.cuda()
)
2023-03-31 20:09:40 +08:00
@property
def _llm_type(self) -> str:
return "ChatGLM"
def _call(self,
prompt: str,
stop: Optional[List[str]] = None) -> str:
response, updated_history = self.model.chat(
self.tokenizer,
2023-03-31 20:09:40 +08:00
prompt,
history=self.history,
max_length=self.max_token,
temperature=self.temperature,
)
torch_gc()
2023-03-31 20:09:40 +08:00
print("history: ", self.history)
if stop is not None:
response = enforce_stop_tokens(response, stop)
self.history = updated_history
return response