Views
No views yet
1
2from transformers import (
3 BartForConditionalGeneration,
4 BartTokenizer
5)
6import torch
7import json
8
9def read_json_file_2_dict(filename, store_dir='.'):
10 with open(f'{store_dir}/{filename}', 'r', encoding='utf-8') as file:
11 return json.load(file)
12
13def get_device():
14 # If there's a GPU available...
15 if torch.cuda.is_available():
16 device = torch.device("cuda")
17 n_gpus = torch.cuda.device_count()
18 first_gpu = torch.cuda.get_device_name(0)
19
20 print(f'There are {n_gpus} GPU(s) available.')
21 print(f'GPU gonna be used: {first_gpu}')
22 else:
23 print('No GPU available, using the CPU instead.')
24 device = torch.device("cpu")
25 return device
26
27model_name = 'unlisboa/bart_qa_assistant'
28tokenizer = BartTokenizer.from_pretrained(model_name)
29device = get_device()
30model = BartForConditionalGeneration.from_pretrained(model_name).to(device)
31model.eval()
32
33model_input = tokenizer(question, truncation=True, padding=True, return_tensors="pt")
34generated_answers_encoded = model.generate(input_ids=model_input["input_ids"].to(device),attention_mask=model_input["attention_mask"].to(device),
35 force_words_ids=None,
36 min_length=1,
37 max_length=100,
38 do_sample=True,
39 early_stopping=True,
40 num_beams=4,
41 temperature=1.0,
42 top_k=None,
43 top_p=None,
44 # eos_token_id=tokenizer.eos_token_id,
45 no_repeat_ngram_size=2,
46 num_return_sequences=1,
47 return_dict_in_generate=True,
48 output_scores=True)
49response = tokenizer.batch_decode(generated_answers_encoded['sequences'], skip_special_tokens=True,clean_up_tokenization_spaces=True)
50print(response)
51