# File: notebooks-main/longform-qa/lfqa_utils.py import functools import math import os from random import choice, randint from time import time import numpy as np import torch import torch.utils.checkpoint as checkpoint from torch.utils.data import DataLoader, Dataset, RandomSampler, SequentialSampler from tqdm import tqdm import faiss import nlp import pandas as pd from elasticsearch import Elasticsearch from elasticsearch.helpers import bulk, streaming_bulk from transformers import AdamW, AutoModel, AutoModelForSeq2SeqLM, AutoTokenizer, get_linear_schedule_with_warmup pd.set_option('display.max_colwidth', None) def make_es_index_snippets(es_client, passages_dset, index_name='english_wiki_kilt_snippets_100w'): index_config = {'settings': {'number_of_shards': 1, 'analysis': {'analyzer': {'stop_standard': {'type': 'standard', ' stopwords': '_english_'}}}}, 'mappings': {'properties': {'article_title': {'type': 'text', 'analyzer': 'standard', 'similarity': 'BM25'}, 'section_title': {'type': 'text', 'analyzer': 'standard', 'similarity': 'BM25'}, 'passage_text': {'type': 'text', 'analyzer': 'standard', 'similarity': 'BM25'}}}} es_client.indices.create(index=index_name, body=index_config) number_of_docs = passages_dset.num_rows progress = tqdm(unit='docs', total=number_of_docs) successes = 0 def passage_generator(): for passage in passages_dset: yield passage for (ok, action) in streaming_bulk(client=es_client, index=index_name, actions=passage_generator()): progress.update(1) successes += ok print('Indexed %d documents' % (successes,)) def query_es_index(question, es_client, index_name='english_wiki_kilt_snippets_100w', n_results=10, min_length=20): q = question.lower() banned = ['how', 'why', 'what', 'where', 'which', 'do', 'does', 'is', '?', 'eli5', 'eli5:'] q = ' '.join([w for w in q.split() if w not in banned]) response = es_client.search(index=index_name, body={'query': {'multi_match': {'query': q, 'fields': ['article_title', 'section_title', 'passage_text^2'], 'type': 'cross_fields'}}, 'size': 2 * n_results}) hits = response['hits']['hits'] support_doc = '
' + '
'.join([hit['_source']['passage_text'] for hit in hits]) res_list = [dict([(k, hit['_source'][k]) for k in hit['_source'] if k != 'passage_text']) for hit in hits] for (r, hit) in zip(res_list, hits): r['passage_id'] = hit['_id'] r['score'] = hit['_score'] r['passage_text'] = hit['_source']['passage_text'] res_list = [res for res in res_list if len(res['passage_text'].split()) > min_length][:n_results] return (support_doc, res_list) class ELI5DatasetQARetriver(Dataset): def __init__(self, examples_array, extra_answer_threshold=3, min_answer_length=64, training=True, n_samples=None): self.data = examples_array self.answer_thres = extra_answer_threshold self.min_length = min_answer_length self.training = training self.n_samples = self.data.num_rows if n_samples is None else n_samples def __len__(self): return self.n_samples def make_example(self, idx): example = self.data[idx] question = example['title'] if self.training: answers = [a for (i, (a, sc)) in enumerate(zip(example['answers']['text'], example['answers']['score']))] answer_tab = choice(answers).split(' ') start_idx = randint(0, max(0, len(answer_tab) - self.min_length)) answer_span = ' '.join(answer_tab[start_idx:]) else: answer_span = example['answers']['text'][0] return (question, answer_span) def __getitem__(self, idx): return self.make_example(idx % self.data.num_rows) class RetrievalQAEmbedder(torch.nn.Module): def __init__(self, sent_encoder, dim): super(RetrievalQAEmbedder, self).__init__() self.sent_encoder = sent_encoder self.output_dim = 128 self.project_q = torch.nn.Linear(dim, self.output_dim, bias=False) self.project_a = torch.nn.Linear(dim, self.output_dim, bias=False) self.ce_loss = torch.nn.CrossEntropyLoss(reduction='mean') def embed_sentences_checkpointed(self, input_ids, attention_mask, checkpoint_batch_size=-1): if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size: return self.sent_encoder(input_ids, attention_mask=attention_mask)[1] else: device = input_ids.device input_shape = input_ids.size() token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device) head_mask = [None] * self.sent_encoder.config.num_hidden_layers extended_attention_mask: torch.Tensor = self.sent_encoder.get_extended_attention_mask(attention_mask, input_shape, device) def partial_encode(*inputs): encoder_outputs = self.sent_encoder.encoder(inputs[0], attention_mask=inputs[1], head_mask=head_mask) sequence_output = encoder_outputs[0] pooled_output = self.sent_encoder.pooler(sequence_output) return pooled_output embedding_output = self.sent_encoder.embeddings(input_ids=input_ids, position_ids=None, token_type_ids=token_type_ids, inputs_embeds=None) pooled_output_list = [] for b in range(math.ceil(input_ids.shape[0] / checkpoint_batch_size)): b_embedding_output = embedding_output[b * checkpoint_batch_size:(b + 1) * checkpoint_batch_size] b_attention_mask = extended_attention_mask[b * checkpoint_batch_size:(b + 1) * checkpoint_batch_size] pooled_output = checkpoint.checkpoint(partial_encode, b_embedding_output, b_attention_mask) pooled_output_list.append(pooled_output) return torch.cat(pooled_output_list, dim=0) def embed_questions(self, q_ids, q_mask, checkpoint_batch_size=-1): q_reps = self.embed_sentences_checkpointed(q_ids, q_mask, checkpoint_batch_size) return self.project_q(q_reps) def embed_answers(self, a_ids, a_mask, checkpoint_batch_size=-1): a_reps = self.embed_sentences_checkpointed(a_ids, a_mask, checkpoint_batch_size) return self.project_a(a_reps) def forward(self, q_ids, q_mask, a_ids, a_mask, checkpoint_batch_size=-1): device = q_ids.device q_reps = self.embed_questions(q_ids, q_mask, checkpoint_batch_size) a_reps = self.embed_answers(a_ids, a_mask, checkpoint_batch_size) compare_scores = torch.mm(q_reps, a_reps.t()) loss_qa = self.ce_loss(compare_scores, torch.arange(compare_scores.shape[1]).to(device)) loss_aq = self.ce_loss(compare_scores.t(), torch.arange(compare_scores.shape[0]).to(device)) loss = (loss_qa + loss_aq) / 2 return loss def make_qa_retriever_model(model_name='google/bert_uncased_L-8_H-512_A-8', from_file=None, device='cuda:0'): tokenizer = AutoTokenizer.from_pretrained(model_name) bert_model = AutoModel.from_pretrained(model_name).to(device) d_ids = torch.LongTensor([[bert_model.config.bos_token_id if bert_model.config.bos_token_id is not None else 1]]).to(device) d_mask = torch.LongTensor([[1]]).to(device) sent_dim = bert_model(d_ids, attention_mask=d_mask)[1].shape[-1] qa_embedder = RetrievalQAEmbedder(bert_model, sent_dim).to(device) if from_file is not None: param_dict = torch.load(from_file) qa_embedder.load_state_dict(param_dict['model']) return (tokenizer, qa_embedder) def make_qa_retriever_batch(qa_list, tokenizer, max_len=64, device='cuda:0'): q_ls = [q for (q, a) in qa_list] a_ls = [a for (q, a) in qa_list] q_toks = tokenizer.batch_encode_plus(q_ls, max_length=max_len, pad_to_max_length=True) (q_ids, q_mask) = (torch.LongTensor(q_toks['input_ids']).to(device), torch.LongTensor(q_toks['attention_mask']).to(device)) a_toks = tokenizer.batch_encode_plus(a_ls, max_length=max_len, pad_to_max_length=True) (a_ids, a_mask) = (torch.LongTensor(a_toks['input_ids']).to(device), torch.LongTensor(a_toks['attention_mask']).to(device)) return (q_ids, q_mask, a_ids, a_mask) def train_qa_retriever_epoch(model, dataset, tokenizer, optimizer, scheduler, args, e=0): model.train() train_sampler = RandomSampler(dataset) model_collate_fn = functools.partial(make_qa_retriever_batch, tokenizer=tokenizer, max_len=args.max_length, device='cuda:0') data_loader = DataLoader(dataset, batch_size=args.batch_size, sampler=train_sampler, collate_fn=model_collate_fn) epoch_iterator = tqdm(data_loader, desc='Iteration', disable=True) loc_steps = 0 loc_loss = 0.0 st_time = time() for (step, batch) in enumerate(epoch_iterator): (q_ids, q_mask, a_ids, a_mask) = batch pre_loss = model(q_ids, q_mask, a_ids, a_mask, checkpoint_batch_size=args.checkpoint_batch_size) loss = pre_loss.sum() loss.backward() optimizer.step() scheduler.step() model.zero_grad() loc_loss += loss.item() loc_steps += 1 if step % args.print_freq == 0 or step == 1: print('{:2d} {:5d} of {:5d} \t L: {:.3f} \t -- {:.3f}'.format(e, step, len(dataset) // args.batch_size, loc_loss / loc_steps, time() - st_time)) loc_loss = 0 loc_steps = 0 def train_qa_retriever_joint_epoch(model, dataset_list, tokenizer, optimizer, scheduler, args, e=0): model.train() model_collate_fn = functools.partial(make_qa_retriever_batch, tokenizer=tokenizer, max_len=args.max_length, device='cuda:0') train_samplers = [RandomSampler(dataset) for dataset in dataset_list] data_loaders = [DataLoader(dataset, batch_size=args.batch_size, sampler=train_sampler, collate_fn=model_collate_fn) for (dataset, train_sampler) in zip(dataset_list, train_samplers)] iterators = [iter(dloader) for dloader in data_loaders] joint_iter = zip(*iterators) loc_steps = 0 loc_loss = 0.0 st_time = time() for (step, (batches,)) in enumerate(zip(joint_iter)): for batch in batches: (q_ids, q_mask, a_ids, a_mask) = batch loss = model(q_ids, q_mask, a_ids, a_mask, checkpoint_batch_size=args.checkpoint_batch_size) loss.backward() optimizer.step() scheduler.step() model.zero_grad() loc_loss += loss.item() loc_steps += 1 if step % args.print_freq == 0: print('{:2d} {:5d} of {:5d} \t L: {:.3f} \t -- {:.3f}'.format(e, step, len(dataset_list[0]) // args.batch_size, loc_loss / loc_steps, time() - st_time)) loc_loss = 0 loc_steps = 0 def evaluate_qa_retriever(model, dataset, tokenizer, args): model.eval() eval_sampler = SequentialSampler(dataset) model_collate_fn = functools.partial(make_qa_retriever_batch, tokenizer=tokenizer, max_len=args.max_length, device='cuda:0') data_loader = DataLoader(dataset, batch_size=args.batch_size, sampler=eval_sampler, collate_fn=model_collate_fn) epoch_iterator = tqdm(data_loader, desc='Iteration', disable=True) tot_loss = 0.0 with torch.no_grad(): for (step, batch) in enumerate(epoch_iterator): (q_ids, q_mask, a_ids, a_mask) = batch loss = model(q_ids, q_mask, a_ids, a_mask) tot_loss += loss.item() return tot_loss / (step + 1) def train_qa_retriever(qar_model, qar_tokenizer, qar_train_dset, qar_valid_dset, qar_args): qar_optimizer = AdamW(qar_model.parameters(), lr=qar_args.learning_rate, eps=1e-08) qar_scheduler = get_linear_schedule_with_warmup(qar_optimizer, num_warmup_steps=100, num_training_steps=(qar_args.num_epochs + 1) * math.ceil(len(qar_train_dset) / qar_args.batch_size)) for e in range(qar_args.num_epochs): train_qa_retriever_epoch(qar_model, qar_train_dset, qar_tokenizer, qar_optimizer, qar_scheduler, qar_args, e) m_save_dict = {'model': qar_model.state_dict(), 'optimizer': qar_optimizer.state_dict(), 'scheduler': qar_scheduler.state_dict()} print('Saving model {}'.format(qar_args.model_save_name)) torch.save(m_save_dict, '{}_{}.pth'.format(qar_args.model_save_name, e)) eval_loss = evaluate_qa_retriever(qar_model, qar_valid_dset, qar_tokenizer, qar_args) print('Evaluation loss epoch {:4d}: {:.3f}'.format(e, eval_loss)) class ELI5DatasetS2S(Dataset): def __init__(self, examples_array, make_doc_fun=None, extra_answer_threshold=3, document_cache=None, training=True): self.training = training self.data = examples_array self.make_doc_function = make_doc_fun self.document_cache = {} if document_cache is None else document_cache assert not (make_doc_fun is None and document_cache is None) if self.training: self.qa_id_list = [(i, j) for (i, qa) in enumerate(self.data) for (j, (a, sc)) in enumerate(zip(qa['answers']['text'], qa['answers']['score'])) if j == 0 or sc >= extra_answer_threshold] else: self.qa_id_list = [(i, 0) for i in range(self.data.num_rows)] def __len__(self): return len(self.qa_id_list) def make_example(self, idx): (i, j) = self.qa_id_list[idx] example = self.data[i] question = example['title'] + ' ' + example['selftext'] answer = example['answers']['text'][j] q_id = example['q_id'] if self.make_doc_function is not None: self.document_cache[q_id] = self.document_cache.get(q_id, self.make_doc_function(example['title'])) document = self.document_cache[q_id] in_st = 'question: {} context: {}'.format(question.lower().replace(' --t--', '').strip(), document.lower().strip()) out_st = answer return (in_st, out_st) def __getitem__(self, idx): return self.make_example(idx) def make_qa_s2s_model(model_name='facebook/bart-large', from_file=None, device='cuda:0'): tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForSeq2SeqLM.from_pretrained(model_name).to(device) if from_file is not None: param_dict = torch.load(from_file) model.load_state_dict(param_dict['model']) return (tokenizer, model) def make_qa_s2s_batch(qa_list, tokenizer, max_len=64, max_a_len=360, device='cuda:0'): q_ls = [q for (q, a) in qa_list] a_ls = [a for (q, a) in qa_list] q_toks = tokenizer.batch_encode_plus(q_ls, max_length=max_len, pad_to_max_length=True) (q_ids, q_mask) = (torch.LongTensor(q_toks['input_ids']).to(device), torch.LongTensor(q_toks['attention_mask']).to(device)) a_toks = tokenizer.batch_encode_plus(a_ls, max_length=min(max_len, max_a_len), pad_to_max_length=True) (a_ids, a_mask) = (torch.LongTensor(a_toks['input_ids']).to(device), torch.LongTensor(a_toks['attention_mask']).to(device)) lm_labels = a_ids[:, 1:].contiguous().clone() lm_labels[a_mask[:, 1:].contiguous() == 0] = -100 model_inputs = {'input_ids': q_ids, 'attention_mask': q_mask, 'decoder_input_ids': a_ids[:, :-1].contiguous(), 'lm_labels': lm_labels} return model_inputs def train_qa_s2s_epoch(model, dataset, tokenizer, optimizer, scheduler, args, e=0, curriculum=False): model.train() if curriculum: train_sampler = SequentialSampler(dataset) else: train_sampler = RandomSampler(dataset) model_collate_fn = functools.partial(make_qa_s2s_batch, tokenizer=tokenizer, max_len=args.max_length, device='cuda:0') data_loader = DataLoader(dataset, batch_size=args.batch_size, sampler=train_sampler, collate_fn=model_collate_fn) epoch_iterator = tqdm(data_loader, desc='Iteration', disable=True) loc_steps = 0 loc_loss = 0.0 st_time = time() for (step, batch_inputs) in enumerate(epoch_iterator): pre_loss = model(**batch_inputs)[0] loss = pre_loss.sum() / pre_loss.shape[0] loss.backward() if step % args.backward_freq == 0: optimizer.step() scheduler.step() model.zero_grad() loc_loss += loss.item() loc_steps += 1 if step % args.print_freq == 0 or step == 1: print('{:2d} {:5d} of {:5d} \t L: {:.3f} \t -- {:.3f}'.format(e, step, len(dataset) // args.batch_size, loc_loss / loc_steps, time() - st_time)) loc_loss = 0 loc_steps = 0 def eval_qa_s2s_epoch(model, dataset, tokenizer, args): model.eval() train_sampler = SequentialSampler(dataset) model_collate_fn = functools.partial(make_qa_s2s_batch, tokenizer=tokenizer, max_len=args.max_length, device='cuda:0') data_loader = DataLoader(dataset, batch_size=args.batch_size, sampler=train_sampler, collate_fn=model_collate_fn) epoch_iterator = tqdm(data_loader, desc='Iteration', disable=True) loc_steps = 0 loc_loss = 0.0 st_time = time() with torch.no_grad(): for (step, batch_inputs) in enumerate(epoch_iterator): pre_loss = model(**batch_inputs)[0] loss = pre_loss.sum() / pre_loss.shape[0] loc_loss += loss.item() loc_steps += 1 if step % args.print_freq == 0: print('{:5d} of {:5d} \t L: {:.3f} \t -- {:.3f}'.format(step, len(dataset) // args.batch_size, loc_loss / loc_steps, time() - st_time)) print('Total \t L: {:.3f} \t -- {:.3f}'.format(loc_loss / loc_steps, time() - st_time)) def train_qa_s2s(qa_s2s_model, qa_s2s_tokenizer, s2s_train_dset, s2s_valid_dset, s2s_args): s2s_optimizer = AdamW(qa_s2s_model.parameters(), lr=s2s_args.learning_rate, eps=1e-08) s2s_scheduler = get_linear_schedule_with_warmup(s2s_optimizer, num_warmup_steps=400, num_training_steps=(s2s_args.num_epochs + 1) * math.ceil(len(s2s_train_dset) / s2s_args.batch_size)) for e in range(s2s_args.num_epochs): train_qa_s2s_epoch(qa_s2s_model, s2s_train_dset, qa_s2s_tokenizer, s2s_optimizer, s2s_scheduler, s2s_args, e, curriculum=e == 0) m_save_dict = {'model': qa_s2s_model.state_dict(), 'optimizer': s2s_optimizer.state_dict(), 'scheduler': s2s_scheduler.state_dict()} print('Saving model {}'.format(s2s_args.model_save_name)) eval_qa_s2s_epoch(qa_s2s_model, s2s_valid_dset, qa_s2s_tokenizer, s2s_args) torch.save(m_save_dict, '{}_{}.pth'.format(s2s_args.model_save_name, e)) def qa_s2s_generate(question_doc, qa_s2s_model, qa_s2s_tokenizer, num_answers=1, num_beams=None, min_len=64, max_len=256, do_sample=False, temp=1.0, top_p=None, top_k=None, max_input_length=512, device='cuda:0'): model_inputs = make_qa_s2s_batch([(question_doc, 'A')], qa_s2s_tokenizer, max_input_length, device=device) n_beams = num_answers if num_beams is None else max(num_beams, num_answers) generated_ids = qa_s2s_model.generate(input_ids=model_inputs['input_ids'], attention_mask=model_inputs['attention_mask'], min_length=min_len, max_length=max_len, do_sample=do_sample, early_stopping=True, num_beams=1 if do_sample else n_beams, temperature=temp, top_k=top_k, top_p=top_p, eos_token_id=qa_s2s_tokenizer.eos_token_id, no_repeat_ngram_size=3, num_return_sequences=num_answers, decoder_start_token_id=qa_s2s_tokenizer.bos_token_id) return [qa_s2s_tokenizer.decode(ans_ids, skip_special_tokens=True).strip() for ans_ids in generated_ids] def embed_passages_for_retrieval(passages, tokenizer, qa_embedder, max_length=128, device='cuda:0'): a_toks = tokenizer.batch_encode_plus(passages, max_length=max_length, pad_to_max_length=True) (a_ids, a_mask) = (torch.LongTensor(a_toks['input_ids']).to(device), torch.LongTensor(a_toks['attention_mask']).to(device)) with torch.no_grad(): a_reps = qa_embedder.embed_answers(a_ids, a_mask).cpu().type(torch.float) return a_reps.numpy() def embed_questions_for_retrieval(q_ls, tokenizer, qa_embedder, device='cuda:0'): q_toks = tokenizer.batch_encode_plus(q_ls, max_length=128, pad_to_max_length=True) (q_ids, q_mask) = (torch.LongTensor(q_toks['input_ids']).to(device), torch.LongTensor(q_toks['attention_mask']).to(device)) with torch.no_grad(): q_reps = qa_embedder.embed_questions(q_ids, q_mask).cpu().type(torch.float) return q_reps.numpy() def make_qa_dense_index(qa_embedder, tokenizer, passages_dset, batch_size=512, max_length=128, index_name='kilt_passages_reps.dat', dtype='float32', device='cuda:0'): st_time = time() fp = np.memmap(index_name, dtype=dtype, mode='w+', shape=(passages_dset.num_rows, 128)) n_batches = math.ceil(passages_dset.num_rows / batch_size) for i in range(n_batches): passages = [p for p in passages_dset[i * batch_size:(i + 1) * batch_size]['passage_text']] reps = embed_passages_for_retrieval(passages, tokenizer, qa_embedder, max_length, device) fp[i * batch_size:(i + 1) * batch_size] = reps if i % 50 == 0: print(i, time() - st_time) def evaluate_retriever(qa_list, retriever_func, scoring_func, n_ret=10, verbose=False): total_retriever_time = 0.0 total_retriever_score = 0.0 st_time = time() for (i, (question, answer)) in enumerate(qa_list): r_time = time() retrieved_passages = retriever_func(question, n_ret) total_retriever_time += time() - r_time total_retriever_score += scoring_func(retrieved_passages, answer) if verbose and ((i + 1) % 500 == 0 or i <= 1): print('{:03d}: S-{:.4f} T-{:.4f} | {:.2f}'.format(i + 1, total_retriever_score / (i + 1), total_retriever_time / (i + 1), time() - st_time)) return {'idf_recall': total_retriever_score / (i + 1), 'retrieval_time': total_retriever_time / (i + 1)} def query_qa_dense_index(question, qa_embedder, tokenizer, wiki_passages, wiki_index, n_results=10, min_length=20, device='cuda:0'): q_rep = embed_questions_for_retrieval([question], tokenizer, qa_embedder, device=device) (D, I) = wiki_index.search(q_rep, 2 * n_results) res_passages = [wiki_passages[int(i)] for i in I[0]] support_doc = '
' + '
'.join([p['passage_text'] for p in res_passages]) res_list = [dict([(k, p[k]) for k in wiki_passages.column_names]) for p in res_passages] res_list = [res for res in res_list if len(res['passage_text'].split()) > min_length][:n_results] for (r, sc) in zip(res_list, D[0]): r['score'] = float(sc) return (support_doc, res_list) def batch_query_qa_dense_index(questions, qa_embedder, tokenizer, wiki_passages, wiki_index, n_results=10): q_rep = embed_questions_for_retrieval(questions, tokenizer, qa_embedder) (D, I) = wiki_index.search(q_rep, n_results) res_passages_lst = [[wiki_passages[int(i)] for i in i_lst] for i_lst in I] support_doc_lst = ['
' + '
'.join([p['passage_text'] for p in res_passages]) for res_passages in res_passages_lst] all_res_lists = [] for (res_passages, dl) in zip(res_passages_lst, D): res_list = [dict([(k, p[k]) for k in wiki_passages.column_names]) for p in res_passages] for (r, sc) in zip(res_list, dl): r['score'] = float(sc) all_res_lists += [res_list[:]] return (support_doc_lst, all_res_lists) def query_qa_dense_index_nn(passage, qa_embedder, tokenizer, wiki_passages, wiki_index, n_results=10, min_length=20): a_rep = embed_passages_for_retrieval([passage], tokenizer, qa_embedder) (D, I) = wiki_index.search(a_rep, 2 * n_results) res_passages = [wiki_passages[int(i)] for i in I[0]] support_doc = '
' + '
'.join([p['passage_text'] for p in res_passages]) res_list = [dict([(k, p[k]) for k in wiki_passages.column_names]) for p in res_passages] res_list = [res for res in res_list if len(res['passage_text'].split()) > min_length][:n_results] for (r, sc, i) in zip(res_list, D[0], I[0]): r['passage_id'] = int(i) r['score'] = float(sc) return (support_doc, res_list) def batch_query_qa_dense_index_nn(passages, qa_embedder, tokenizer, wiki_passages, wiki_index, n_results=10): a_reps = embed_passages_for_retrieval(passages, tokenizer, qa_embedder) (D, I) = wiki_index.search(a_reps, n_results) res_passages_lst = [[wiki_passages[int(i)] for i in i_lst] for i_lst in I] support_doc_lst = ['
' + '
'.join([p['passage_text'] for p in res_passages]) for res_passages in res_passages_lst]
all_res_lists = []
for (res_passages, dl, il) in zip(res_passages_lst, D, I):
res_list = [dict([(k, p[k]) for k in wiki_passages.column_names]) for p in res_passages]
for (r, sc, i) in zip(res_list, dl, il):
r['passage_id'] = int(i)
r['score'] = float(sc)
all_res_lists += [res_list[:]]
return (support_doc_lst, all_res_lists)
# File: notebooks-main/sagemaker/17_custom_inference_script/code/inference.py
from transformers import AutoTokenizer, AutoModel
import torch
import torch.nn.functional as F
def mean_pooling(model_output, attention_mask):
token_embeddings = model_output[0]
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-09)
def model_fn(model_dir):
tokenizer = AutoTokenizer.from_pretrained(model_dir)
model = AutoModel.from_pretrained(model_dir)
return (model, tokenizer)
def predict_fn(data, model_and_tokenizer):
(model, tokenizer) = model_and_tokenizer
sentences = data.pop('inputs', data)
encoded_input = tokenizer(sentences, padding=True, truncation=True, return_tensors='pt')
with torch.no_grad():
model_output = model(**encoded_input)
sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask'])
sentence_embeddings = F.normalize(sentence_embeddings, p=2, dim=1)
return {'vectors': sentence_embeddings}
# File: notebooks-main/sagemaker/18_inferentia_inference/code/inference.py
import os
from transformers import AutoConfig, AutoTokenizer
import torch
import torch.neuron
os.environ['NEURON_RT_NUM_CORES'] = '1'
AWS_NEURON_TRACED_WEIGHTS_NAME = 'neuron_model.pt'
def model_fn(model_dir):
tokenizer = AutoTokenizer.from_pretrained(model_dir)
model = torch.jit.load(os.path.join(model_dir, AWS_NEURON_TRACED_WEIGHTS_NAME))
model_config = AutoConfig.from_pretrained(model_dir)
return (model, tokenizer, model_config)
def predict_fn(data, model_tokenizer_model_config):
(model, tokenizer, model_config) = model_tokenizer_model_config
inputs = data.pop('inputs', data)
embeddings = tokenizer(inputs, return_tensors='pt', max_length=model_config.traced_sequence_length, padding='max_length', truncation=True)
neuron_inputs = tuple(embeddings.values())
with torch.no_grad():
predictions = model(*neuron_inputs)[0]
scores = torch.nn.Softmax(dim=1)(predictions)
return [{'label': model_config.id2label[item.argmax().item()], 'score': item.max().item()} for item in scores]
# File: notebooks-main/sagemaker/22_accelerate_sagemaker_examples/src/seq2seq/run_seq2seq_no_trainer.py
""""""
import argparse
import json
import logging
import math
import os
import random
from pathlib import Path
from time import time
import datasets
import nltk
import numpy as np
import torch
from datasets import load_dataset, load_metric
from torch.utils.data import DataLoader
from tqdm.auto import tqdm
import transformers
from accelerate import Accelerator
from accelerate.logging import get_logger
from accelerate.utils import DummyOptim, DummyScheduler, set_seed
from filelock import FileLock
from huggingface_hub import Repository
from transformers import CONFIG_MAPPING, MODEL_MAPPING, AutoConfig, AutoModelForSeq2SeqLM, AutoTokenizer, DataCollatorForSeq2Seq, SchedulerType, get_scheduler
from transformers.utils import get_full_repo_name, is_offline_mode
from transformers.utils.versions import require_version
logger = get_logger(__name__)
require_version('datasets>=1.8.0', 'To fix: pip install -r examples/pytorch/summarization/requirements.txt')
MODEL_CONFIG_CLASSES = list(MODEL_MAPPING.keys())
MODEL_TYPES = tuple((conf.model_type for conf in MODEL_CONFIG_CLASSES))
try:
nltk.data.find('tokenizers/punkt')
except (LookupError, OSError):
if is_offline_mode():
raise LookupError('Offline mode: run this script without TRANSFORMERS_OFFLINE first to download nltk data files')
with FileLock('.lock') as lock:
nltk.download('punkt', quiet=True)
def parse_args():
parser = argparse.ArgumentParser(description='Finetune a transformers model on a summarization task')
parser.add_argument('--dataset_name', type=str, default=None, help='The name of the dataset to use (via the datasets library).')
parser.add_argument('--dataset_config_name', type=str, default=None, help='The configuration name of the dataset to use (via the datasets library).')
parser.add_argument('--train_file', type=str, default=None, help='A csv or a json file containing the training data.')
parser.add_argument('--validation_file', type=str, default=None, help='A csv or a json file containing the validation data.')
parser.add_argument('--ignore_pad_token_for_loss', type=bool, default=True, help='Whether to ignore the tokens corresponding to padded labels in the loss computation or not.')
parser.add_argument('--max_source_length', type=int, default=1024, help='The maximum total input sequence length after tokenization.Sequences longer than this will be truncated, sequences shorter will be padded.')
parser.add_argument('--source_prefix', type=str, default=None, help='A prefix to add before every source text (useful for T5 models).')
parser.add_argument('--preprocessing_num_workers', type=int, default=None, help='The number of processes to use for the preprocessing.')
parser.add_argument('--overwrite_cache', type=bool, default=None, help='Overwrite the cached training and evaluation sets')
parser.add_argument('--max_target_length', type=int, default=128, help='The maximum total sequence length for target text after tokenization. Sequences longer than this will be truncated, sequences shorter will be padded.during ``evaluate`` and ``predict``.')
parser.add_argument('--val_max_target_length', type=int, default=None, help='The maximum total sequence length for validation target text after tokenization.Sequences longer than this will be truncated, sequences shorter will be padded. Will default to `max_target_length`.This argument is also used to override the ``max_length`` param of ``model.generate``, which is used during ``evaluate`` and ``predict``.')
parser.add_argument('--val_min_target_length', type=int, default=10, help='The minimum total sequence length for validation target text after tokenization.Sequences longer than this will be truncated, sequences shorter will be padded. Will default to `max_target_length`.This argument is also used to override the ``max_length`` param of ``model.generate``, which is used during ``evaluate`` and ``predict``.')
parser.add_argument('--n_train', type=int, default=2000, help='Number of training examples to use. If None, all training examples will be used.')
parser.add_argument('--n_val', type=int, default=500, help='Number of validation examples to use. If None, all validation examples will be used.')
parser.add_argument('--n_val_batch_generations', type=int, default=5, help='Number of validation examples to use. If None, all validation examples will be used.')
parser.add_argument('--max_length', type=int, default=128, help='The maximum total input sequence length after tokenization. Sequences longer than this will be truncated, sequences shorter will be padded if `--pad_to_max_lengh` is passed.')
parser.add_argument('--num_beams', type=int, default=None, help='Number of beams to use for evaluation. This argument will be passed to ``model.generate``, which is used during ``evaluate`` and ``predict``.')
parser.add_argument('--pad_to_max_length', type=bool, default=False, help='If passed, pad all samples to `max_length`. Otherwise, dynamic padding is used.')
parser.add_argument('--model_name_or_path', type=str, help='Path to pretrained model or model identifier from huggingface.co/models.', required=False)
parser.add_argument('--config_name', type=str, default=None, help='Pretrained config name or path if not the same as model_name')
parser.add_argument('--tokenizer_name', type=str, default=None, help='Pretrained tokenizer name or path if not the same as model_name')
parser.add_argument('--text_column', type=str, default=None, help='The name of the column in the datasets containing the full texts (for summarization).')
parser.add_argument('--summary_column', type=str, default=None, help='The name of the column in the datasets containing the summaries (for summarization).')
parser.add_argument('--use_slow_tokenizer', type=bool, default=False, help='If passed, will use a slow tokenizer (not backed by the 🤗 Tokenizers library).')
parser.add_argument('--per_device_train_batch_size', type=int, default=8, help='Batch size (per device) for the training dataloader.')
parser.add_argument('--per_device_eval_batch_size', type=int, default=8, help='Batch size (per device) for the evaluation dataloader.')
parser.add_argument('--learning_rate', type=float, default=5e-05, help='Initial learning rate (after the potential warmup period) to use.')
parser.add_argument('--weight_decay', type=float, default=0.0, help='Weight decay to use.')
parser.add_argument('--num_train_epochs', type=int, default=3, help='Total number of training epochs to perform.')
parser.add_argument('--max_train_steps', type=int, default=None, help='Total number of training steps to perform. If provided, overrides num_train_epochs.')
parser.add_argument('--gradient_accumulation_steps', type=int, default=1, help='Number of updates steps to accumulate before performing a backward/update pass.')
parser.add_argument('--lr_scheduler_type', type=SchedulerType, default='linear', help='The scheduler type to use.', choices=['linear', 'cosine', 'cosine_with_restarts', 'polynomial', 'constant', 'constant_with_warmup'])
parser.add_argument('--num_warmup_steps', type=int, default=0, help='Number of steps for the warmup in the lr scheduler.')
parser.add_argument('--output_dir', type=str, default=None, help='Where to store the final model.')
parser.add_argument('--seed', type=int, default=None, help='A seed for reproducible training.')
parser.add_argument('--model_type', type=str, default=None, help='Model type to use if training from scratch.', choices=MODEL_TYPES)
parser.add_argument('--push_to_hub', type=bool, default=False, help='Whether or not to push the model to the Hub.')
parser.add_argument('--hub_model_id', type=str, help='The name of the repository to keep in sync with the local `output_dir`.')
parser.add_argument('--hub_token', type=str, help='The token to use to push to the Model Hub.')
parser.add_argument('--checkpointing_steps', type=str, default=None, help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.")
parser.add_argument('--resume_from_checkpoint', type=str, default=None, help='If the training should continue from a checkpoint folder.')
parser.add_argument('--load_best_model', type=bool, default=False, help='Whether to load the best model at the end of training')
parser.add_argument('--logging_steps', type=int, default=None, help='log every n steps')
parser.add_argument('--with_tracking', type=bool, default=False, help='Whether to enable experiment trackers for logging.')
parser.add_argument('--report_to', type=str, default='all', help='The integration to report the results and logs to. Supported platforms are `"tensorboard"`, `"wandb"` and `"comet_ml"`. Use `"all"` (default) to report to all integrations.Only applicable when `--with_tracking` is passed.')
parser.add_argument('--report_name', type=str, default='chatbot_no_trainer', help='The name of the experiment tracking folder. Only applicable when `--with_tracking` is passed.')
args = parser.parse_args()
if args.dataset_name is None and args.train_file is None and (args.validation_file is None):
raise ValueError('Need either a dataset name or a training/validation file.')
else:
if args.train_file is not None:
extension = args.train_file.split('.')[-1]
assert extension in ['csv', 'json'], '`train_file` should be a csv or a json file.'
if args.validation_file is not None:
extension = args.validation_file.split('.')[-1]
assert extension in ['csv', 'json'], '`validation_file` should be a csv or a json file.'
if args.push_to_hub:
assert args.output_dir is not None, 'Need an `output_dir` to create a repo when `--push_to_hub` is passed.'
return args
def checkpoint_model(checkpoint_folder, ckpt_id, model, epoch, last_global_step, **kwargs):
checkpoint_state_dict = {'epoch': epoch, 'last_global_step': last_global_step}
checkpoint_state_dict.update(kwargs)
success = model.save_checkpoint(checkpoint_folder, ckpt_id, checkpoint_state_dict)
status_msg = f'checkpointing: checkpoint_folder={checkpoint_folder}, ckpt_id={ckpt_id}'
if success:
logging.info(f'Success {status_msg}')
else:
logging.warning(f'Failure {status_msg}')
return
def evaluate(args, model, metric, tokenizer, eval_dataloader, accelerator, max_length):
accelerator.print('starting evaluation')
count_printed = 0
def postprocess_text(preds, labels):
preds = [pred.strip() for pred in preds]
labels = [[label.strip()] for label in labels]
return (preds, labels)
model.eval()
if args.val_max_target_length is None:
args.val_max_target_length = args.max_target_length
gen_kwargs = {'max_length': args.val_max_target_length if args is not None else max_length, 'num_beams': args.num_beams, 'min_length': args.val_min_target_length, 'length_penalty': False, 'no_repeat_ngram_size': 3, 'encoder_no_repeat_ngram_size': 3, 'repetition_penalty': 1.2}
samples_seen = 0
for (step, batch) in enumerate(eval_dataloader):
with torch.no_grad():
generated_tokens = accelerator.unwrap_model(model).generate(batch['input_ids'], attention_mask=batch['attention_mask'], **gen_kwargs)
generated_tokens = accelerator.pad_across_processes(generated_tokens, dim=1, pad_index=tokenizer.pad_token_id)
labels = batch['labels']
if not args.pad_to_max_length:
labels = accelerator.pad_across_processes(batch['labels'], dim=1, pad_index=tokenizer.pad_token_id)
(generated_tokens, labels) = accelerator.gather((generated_tokens, labels))
generated_tokens = generated_tokens.cpu().numpy()
labels = labels.cpu().numpy()
if args.ignore_pad_token_for_loss:
labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
decoded_preds = tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
if count_printed < args.n_val_batch_generations:
logger.info('printing few sample generations and corresponding labels from eval set')
logger.info('prompt | generated | label')
decoded_prompts = tokenizer.batch_decode(batch['input_ids'], skip_special_tokens=False)
for (prompt, generated_response, response) in zip(decoded_prompts, decoded_preds, decoded_labels):
cleaned_prompt = prompt.replace('