t5-ft-demo / title_gen.py
alakxender's picture
tg
d6fee57
raw
history blame
1.57 kB
import random
import numpy as np
import torch
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
MODEL_DIR = "alakxender/t5-dhivehi-title-generation-xs"
tokenizer = AutoTokenizer.from_pretrained(MODEL_DIR)
model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_DIR)
prefix = "2title: "
max_input_length = 512
max_target_length = 32
def generate_title(content, seed, use_sampling):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
input_text = prefix + content.strip()
inputs = tokenizer(
input_text,
max_length=max_input_length,
truncation=True,
return_tensors="pt"
)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
inputs = {k: v.to(device) for k, v in inputs.items()}
gen_kwargs = {
"input_ids": inputs["input_ids"],
"attention_mask": inputs["attention_mask"],
"max_length": max_target_length,
"no_repeat_ngram_size": 2,
}
if use_sampling:
gen_kwargs.update({
"do_sample": True,
"temperature": 1.0,
"top_p": 0.95,
"num_return_sequences": 1,
})
else:
gen_kwargs.update({
"num_beams": 4,
"do_sample": False,
"early_stopping": True,
})
with torch.no_grad():
outputs = model.generate(**gen_kwargs)
title = tokenizer.decode(outputs[0], skip_special_tokens=True)
return title