netserve / Backend.py
chandanrajCL's picture
Update Backend.py
36eca55 verified
Raw History Blame Contribute Delete
1.45 kB
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
import torchvision
class Backend:
def __init__(self, model_path, tokenizer_path):
# Load the model and tokenizer
self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)
self.model = AutoModelForCausalLM.from_pretrained(model_path)
def predict(self, user_input):
# Tokenize user input
bot_input_ids = self.tokenizer.encode(user_input + self.tokenizer.eos_token, return_tensors='pt')
attention_mask = torch.ones(bot_input_ids.shape, dtype=torch.long)
chat_history_ids = self.model.generate(
bot_input_ids,
max_length=200,
attention_mask=attention_mask,
pad_token_id=self.tokenizer.eos_token_id, # Use the EOS token as the padding token
no_repeat_ngram_size=3, # Prevent repetition of 3-grams
do_sample=True, # Enable sampling (vs. greedy decoding)
top_k=10, # Top-k sampling (randomly select from the top 10 probable tokens)
top_p=0.7, # Top-p sampling (only consider tokens whose cumulative probability is less than 0.7)
temperature=0.8 # Control randomness of the generation (higher = more random)
)
# Decode the response
response = self.tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
return response