# 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('', '').strip() logger.info(f'{cleaned_prompt} | {generated_response} | {response}') count_printed += 1 (decoded_preds, decoded_labels) = postprocess_text(decoded_preds, decoded_labels) if accelerator.num_processes > 1: if step == len(eval_dataloader) - 1: decoded_preds = decoded_preds[:len(eval_dataloader.dataset) - samples_seen] decoded_labels = decoded_labels[:len(eval_dataloader.dataset) - samples_seen] else: samples_seen += len(decoded_labels) metric.add_batch(predictions=decoded_preds, references=decoded_labels) result = metric.compute() logger.info({'bleu': result['score']}) accelerator.print('evaluation completed') return result['score'] def load_training_checkpoint(model, load_dir, tag=None, **kwargs): (_, checkpoint_state_dict) = model.load_checkpoint(load_dir, tag=tag, **kwargs) epoch = checkpoint_state_dict['epoch'] last_global_step = checkpoint_state_dict['last_global_step'] del checkpoint_state_dict return (epoch, last_global_step) def main(): args = parse_args() accelerator = Accelerator(log_with=args.report_to, logging_dir=args.output_dir) if args.with_tracking else Accelerator() if args.source_prefix is None and args.model_name_or_path in ['t5-small', 't5-base', 't5-large', 't5-3b', 't5-11b']: logger.warning("You're running a t5 model but didn't provide a source prefix, which is the expected, e.g. with `--source_prefix 'summarize: ' `") logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO) logger.info(accelerator.state, main_process_only=False) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() if args.seed is not None: set_seed(args.seed) if accelerator.is_main_process: if args.push_to_hub: if args.hub_model_id is None: repo_name = get_full_repo_name(Path(args.output_dir).name, token=args.hub_token) else: repo_name = args.hub_model_id repo = Repository(args.output_dir, clone_from=repo_name) with open(os.path.join(args.output_dir, '.gitignore'), 'w+') as gitignore: if 'step_*' not in gitignore: gitignore.write('step_*\n') if 'epoch_*' not in gitignore: gitignore.write('epoch_*\n') elif args.output_dir is not None: os.makedirs(args.output_dir, exist_ok=True) accelerator.wait_for_everyone() if args.dataset_name is not None: raw_datasets = load_dataset(args.dataset_name, args.dataset_config_name) if args.n_train > 0: raw_datasets['train'] = datasets.Dataset.from_dict(raw_datasets['train'][:args.n_train]) if args.n_val > 0: raw_datasets['validation'] = datasets.Dataset.from_dict(raw_datasets['validation'][:args.n_val]) else: data_files = {} if args.train_file is not None: data_files['train'] = args.train_file if args.validation_file is not None: data_files['validation'] = args.validation_file extension = args.train_file.split('.')[-1] raw_datasets = load_dataset(extension, data_files=data_files) if args.config_name: config = AutoConfig.from_pretrained(args.config_name) elif args.model_name_or_path: config = AutoConfig.from_pretrained(args.model_name_or_path) else: config = CONFIG_MAPPING[args.model_type]() logger.warning('You are instantiating a new config instance from scratch.') if args.tokenizer_name: tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=not args.use_slow_tokenizer) elif args.model_name_or_path: tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, use_fast=not args.use_slow_tokenizer) else: raise ValueError('You are instantiating a new tokenizer from scratch. This is not supported by this script.You can do it from another script, save it, and load it from here, using --tokenizer_name.') if args.model_name_or_path: model = AutoModelForSeq2SeqLM.from_pretrained(args.model_name_or_path, from_tf=bool('.ckpt' in args.model_name_or_path), config=config) else: logger.info('Training new model from scratch') model = AutoModelForSeq2SeqLM.from_config(config) model.resize_token_embeddings(len(tokenizer)) if model.config.decoder_start_token_id is None: raise ValueError('Make sure that `config.decoder_start_token_id` is correctly defined') prefix = args.source_prefix if args.source_prefix is not None else '' column_names = raw_datasets['train'].column_names dataset_columns = column_names if args.text_column is None: text_column = dataset_columns[0] if dataset_columns is not None else column_names[0] else: text_column = args.text_column if text_column not in column_names: raise ValueError(f"--text_column' value '{args.text_column}' needs to be one of: {', '.join(column_names)}") if args.summary_column is None: summary_column = dataset_columns[1] if dataset_columns is not None else column_names[1] else: summary_column = args.summary_column if summary_column not in column_names: raise ValueError(f"--summary_column' value '{args.summary_column}' needs to be one of: {', '.join(column_names)}") max_target_length = args.max_target_length padding = 'max_length' if args.pad_to_max_length else False def preprocess_function(examples): inputs = examples[text_column] targets = examples[summary_column] inputs = [prefix + inp for inp in inputs] model_inputs = tokenizer(inputs, max_length=args.max_source_length, padding=padding, truncation=True) if 't5' in args.model_name_or_path: with tokenizer.as_target_tokenizer(): labels = tokenizer(targets, max_length=max_target_length, padding=padding, truncation=True) else: labels = tokenizer(targets, max_length=max_target_length, padding=padding, truncation=True) if padding == 'max_length' and args.ignore_pad_token_for_loss: labels['input_ids'] = [[l if l != tokenizer.pad_token_id else -100 for l in label] for label in labels['input_ids']] model_inputs['labels'] = labels['input_ids'] return model_inputs with accelerator.main_process_first(): processed_datasets = raw_datasets.map(preprocess_function, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc='Running tokenizer on dataset') train_dataset = processed_datasets['train'] eval_dataset = processed_datasets['validation'] for index in random.sample(range(len(train_dataset)), 1): logger.info(f'Sample {index} of the training set: {train_dataset[index]}.') label_pad_token_id = -100 if args.ignore_pad_token_for_loss else tokenizer.pad_token_id data_collator = DataCollatorForSeq2Seq(tokenizer, model=model, label_pad_token_id=label_pad_token_id, pad_to_multiple_of=8 if accelerator.use_fp16 else None) train_dataloader = DataLoader(train_dataset, shuffle=True, collate_fn=data_collator, batch_size=args.per_device_train_batch_size) eval_dataloader = DataLoader(eval_dataset, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size) no_decay = ['bias', 'LayerNorm.weight'] optimizer_grouped_parameters = [{'params': [p for (n, p) in model.named_parameters() if not any((nd in n for nd in no_decay))], 'weight_decay': args.weight_decay}, {'params': [p for (n, p) in model.named_parameters() if any((nd in n for nd in no_decay))], 'weight_decay': 0.0}] optimizer_cls = torch.optim.Adam if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim optimizer = optimizer_cls(optimizer_grouped_parameters, lr=args.learning_rate) if accelerator.state.deepspeed_plugin is not None: args.gradient_accumulation_steps = accelerator.state.deepspeed_plugin.deepspeed_config['gradient_accumulation_steps'] num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps) if args.max_train_steps is None: args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch else: args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch) if accelerator.state.deepspeed_plugin is None or 'scheduler' not in accelerator.state.deepspeed_plugin.deepspeed_config: lr_scheduler = get_scheduler(name=args.lr_scheduler_type, optimizer=optimizer, num_warmup_steps=args.num_warmup_steps, num_training_steps=args.max_train_steps) else: lr_scheduler = DummyScheduler(optimizer, total_num_steps=args.max_train_steps, warmup_num_steps=args.num_warmup_steps) (model, optimizer, train_dataloader, eval_dataloader, lr_scheduler) = accelerator.prepare(model, optimizer, train_dataloader, eval_dataloader, lr_scheduler) num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps) args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch if hasattr(args.checkpointing_steps, 'isdigit'): checkpointing_steps = args.checkpointing_steps if args.checkpointing_steps.isdigit(): checkpointing_steps = int(args.checkpointing_steps) else: checkpointing_steps = None if args.with_tracking: if accelerator.is_main_process: experiment_config = vars(args) experiment_config['lr_scheduler_type'] = experiment_config['lr_scheduler_type'].value accelerator.init_trackers(args.report_name, experiment_config) metric = load_metric('sacrebleu') total_batch_size = args.per_device_train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps logger.info('***** Running training *****') logger.info(f' Num examples = {len(train_dataset)}') logger.info(f' Num Epochs = {args.num_train_epochs}') logger.info(f' Instantaneous batch size per device = {args.per_device_train_batch_size}') logger.info(f' Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}') logger.info(f' Gradient Accumulation steps = {args.gradient_accumulation_steps}') logger.info(f' Total optimization steps = {args.max_train_steps}') progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process) completed_steps = 0 starting_epoch = 0 best_metric = None best_metric_checkpoint = None if args.resume_from_checkpoint: (_, last_global_step) = load_training_checkpoint(model, args.resume_from_checkpoint, **{'load_optimizer_states': True, 'load_lr_scheduler_states': True}) accelerator.print(f'Resumed from checkpoint: {args.resume_from_checkpoint}') resume_step = last_global_step starting_epoch = resume_step // len(train_dataloader) resume_step -= starting_epoch * len(train_dataloader) for epoch in range(starting_epoch, args.num_train_epochs): start_time = time() model.train() if args.with_tracking: total_loss = 0 for (step, batch) in enumerate(train_dataloader): if args.resume_from_checkpoint and epoch == starting_epoch: if resume_step is not None and step < resume_step: completed_steps += 1 continue decoder_input_ids = batch['labels'].new_zeros(batch['labels'].shape) decoder_input_ids[..., 1:] = batch['labels'][..., :-1].clone() decoder_input_ids[..., 0] = 0 decoder_input_ids.masked_fill_(decoder_input_ids == -100, 0) batch['decoder_input_ids'] = decoder_input_ids outputs = model(**batch) loss = outputs.loss if args.with_tracking: total_loss += loss.detach().float() loss = loss / args.gradient_accumulation_steps accelerator.backward(loss) if step % args.gradient_accumulation_steps == 0 or step == len(train_dataloader) - 1: optimizer.step() lr_scheduler.step() optimizer.zero_grad() progress_bar.update(1) completed_steps += 1 if isinstance(args.logging_steps, int): if completed_steps % args.logging_steps == 0: steps_this_epoch = completed_steps % len(train_dataloader) train_loss = total_loss.item() / steps_this_epoch train_perplexity = math.exp(train_loss) accelerator.log({'train_loss': train_loss, 'train_perplexity': train_perplexity, 'epoch': epoch, 'step': completed_steps, 'steps_this_epoch': steps_this_epoch}, step=completed_steps) logger.info(f'Epoch: {epoch}, Step: {completed_steps}, Loss: {train_loss}, Perplexity: {train_perplexity}') if isinstance(checkpointing_steps, int): if completed_steps % checkpointing_steps == 0: if accelerator.state.deepspeed_plugin is not None: checkpoint_model(args.output_dir, epoch, model, epoch, completed_steps) else: accelerator.wait_for_everyone() if accelerator.is_main_process: ckpt_path = os.path.join(args.output_dir, str(epoch)) os.makedirs(ckpt_path, exist_ok=True) accelerator.save(accelerator.get_state_dict(model), os.path.join(ckpt_path, 'model.pt')) if completed_steps >= args.max_train_steps: break end_time = time() logger.info(f'Epoch {epoch} training took {end_time - start_time} seconds') if accelerator.state.deepspeed_plugin is not None: checkpoint_model(args.output_dir, epoch, model, epoch, completed_steps) else: accelerator.wait_for_everyone() if accelerator.is_main_process: ckpt_path = os.path.join(args.output_dir, str(epoch)) os.makedirs(ckpt_path, exist_ok=True) accelerator.save(accelerator.get_state_dict(model), os.path.join(ckpt_path, 'model.pt')) start_time = time() bleu_score = evaluate(args, model, metric, tokenizer, eval_dataloader, accelerator, config.max_length) end_time = time() logger.info(f'Epoch {epoch} evaluation took {end_time - start_time} seconds') result = {} if args.with_tracking: result['bleu_score'] = bleu_score result['train_loss'] = total_loss.item() / len(train_dataloader) result['train_perplexity'] = math.exp(result['train_loss']) result['epoch'] = epoch result['step'] = completed_steps accelerator.log(result, step=completed_steps) if (best_metric is None or best_metric < bleu_score) and args.load_best_model: best_metric = bleu_score best_metric_checkpoint = os.path.join(args.output_dir, str(epoch)) accelerator.print(f'New best metric: {best_metric} at epoch {epoch}') accelerator.print(f'best_metric_checkpoint: {best_metric_checkpoint}') if args.load_best_model: if accelerator.state.deepspeed_plugin is not None: (_, last_global_step) = load_training_checkpoint(model, '/'.join(best_metric_checkpoint.split('/')[:-1]), tag=best_metric_checkpoint.split('/')[-1], **{'load_optimizer_states': True, 'load_lr_scheduler_states': True}) else: map_location = {'cuda:0': 'cuda:{}'.format(accelerator.local_process_index)} model.load_state_dict(torch.load(os.path.join(best_metric_checkpoint, 'model.pt'), map_location=map_location)) bleu_score = evaluate(args, model, metric, tokenizer, eval_dataloader, accelerator, config.max_length) logger.info(f'Best model metrics: bleu_score: {bleu_score}') if bleu_score != best_metric: raise AssertionError(f'Best metric {best_metric} does not match the metric {bleu_score} of the loaded best model.') if args.output_dir is not None: accelerator.wait_for_everyone() unwrapped_model = accelerator.unwrap_model(model) unwrapped_model.save_pretrained(args.output_dir, is_main_process=accelerator.is_main_process, save_function=accelerator.save, state_dict=accelerator.get_state_dict(model)) if accelerator.is_main_process: tokenizer.save_pretrained(args.output_dir) if args.push_to_hub: repo.push_to_hub(commit_message='End of training', auto_lfs_prune=True) with open(os.path.join(args.output_dir, 'all_results.json'), 'w') as f: json.dump({'eval_bleu': bleu_score}, f) if __name__ == '__main__': main() # File: notebooks-main/sagemaker/22_accelerate_sagemaker_examples/src/text-classification/train_using_s3_data.py import argparse import os import torch from torch.optim import AdamW from torch.utils.data import DataLoader import evaluate from accelerate import Accelerator, DistributedType from datasets import load_from_disk from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed MAX_GPU_BATCH_SIZE = 16 EVAL_BATCH_SIZE = 32 def training_function(config, args): if args.with_tracking: accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision, log_with='all', logging_dir=args.logging_dir) else: accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision) if hasattr(args.checkpointing_steps, 'isdigit'): if args.checkpointing_steps == 'epoch': checkpointing_steps = args.checkpointing_steps elif args.checkpointing_steps.isdigit(): checkpointing_steps = int(args.checkpointing_steps) else: raise ValueError(f'Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.') else: checkpointing_steps = None lr = config['lr'] num_epochs = int(config['num_epochs']) seed = int(config['seed']) batch_size = int(config['batch_size']) if args.with_tracking: run = os.path.split(__file__)[-1].split('.')[0] accelerator.init_trackers(run, config) tokenizer = AutoTokenizer.from_pretrained('bert-base-cased') metric = evaluate.load('glue', 'mrpc') gradient_accumulation_steps = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE batch_size = MAX_GPU_BATCH_SIZE def collate_fn(examples): if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(examples, padding='max_length', max_length=128, return_tensors='pt') return tokenizer.pad(examples, padding='longest', return_tensors='pt') train_dataset = load_from_disk(args.training_dir) validation_dataset = load_from_disk(args.validation_dir) accelerator.print(f' loaded train_dataset length is: {len(train_dataset)}') accelerator.print(f' loaded test_dataset length is: {len(validation_dataset)}') train_dataloader = DataLoader(train_dataset, shuffle=True, collate_fn=collate_fn, batch_size=batch_size) eval_dataloader = DataLoader(validation_dataset, shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE) set_seed(seed) model = AutoModelForSequenceClassification.from_pretrained('bert-base-cased', return_dict=True) model = model.to(accelerator.device) optimizer = AdamW(params=model.parameters(), lr=lr) lr_scheduler = get_linear_schedule_with_warmup(optimizer=optimizer, num_warmup_steps=100, num_training_steps=len(train_dataloader) * num_epochs // gradient_accumulation_steps) (model, optimizer, train_dataloader, eval_dataloader, lr_scheduler) = accelerator.prepare(model, optimizer, train_dataloader, eval_dataloader, lr_scheduler) overall_step = 0 starting_epoch = 0 if args.resume_from_checkpoint: if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != '': accelerator.print(f'Resumed from checkpoint: {args.resume_from_checkpoint}') accelerator.load_state(args.resume_from_checkpoint) path = os.path.basename(args.resume_from_checkpoint) else: dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()] dirs.sort(key=os.path.getctime) path = dirs[-1] training_difference = os.path.splitext(path)[0] if 'epoch' in training_difference: starting_epoch = int(training_difference.replace('epoch_', '')) + 1 resume_step = None else: resume_step = int(training_difference.replace('step_', '')) starting_epoch = resume_step // len(train_dataloader) resume_step -= starting_epoch * len(train_dataloader) for epoch in range(starting_epoch, num_epochs): model.train() if args.with_tracking: total_loss = 0 for (step, batch) in enumerate(train_dataloader): if args.resume_from_checkpoint and epoch == starting_epoch: if resume_step is not None and step < resume_step: overall_step += 1 continue batch.to(accelerator.device) outputs = model(**batch) loss = outputs.loss loss = loss / gradient_accumulation_steps if args.with_tracking: total_loss += loss.detach().float() accelerator.backward(loss) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 if isinstance(checkpointing_steps, int): output_dir = f'step_{overall_step}' if overall_step % checkpointing_steps == 0: if args.output_dir is not None: output_dir = os.path.join(args.output_dir, output_dir) accelerator.save_state(output_dir) model.eval() for (step, batch) in enumerate(eval_dataloader): batch.to(accelerator.device) with torch.no_grad(): outputs = model(**batch) predictions = outputs.logits.argmax(dim=-1) (predictions, references) = accelerator.gather_for_metrics((predictions, batch['labels'])) metric.add_batch(predictions=predictions, references=references) eval_metric = metric.compute() accelerator.print(f'epoch {epoch}:', eval_metric) if args.with_tracking: accelerator.log({'accuracy': eval_metric['accuracy'], 'f1': eval_metric['f1'], 'train_loss': total_loss.item() / len(train_dataloader), 'epoch': epoch}, step=epoch) if checkpointing_steps == 'epoch': output_dir = f'epoch_{epoch}' if args.output_dir is not None: output_dir = os.path.join(args.output_dir, output_dir) accelerator.save_state(output_dir) accelerator.save(accelerator.get_state_dict(model), os.path.join(args.output_dir, 'model.pt')) if args.with_tracking: accelerator.end_training() def main(): parser = argparse.ArgumentParser(description='Simple example of training script.') parser.add_argument('--mixed_precision', type=str, default='no', choices=['no', 'fp16', 'bf16'], help='Whether to use mixed precision. Choosebetween fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.and an Nvidia Ampere GPU.') parser.add_argument('--cpu', action='store_true', help='If passed, will train on the CPU.') 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('--with_tracking', action='store_true', help='Whether to load in all available experiment trackers from the environment and use them for logging.') parser.add_argument('--logging_dir', type=str, default=os.path.join(os.environ['SM_OUTPUT_DATA_DIR'], 'logs'), help='Location on where to store experiment tracking logs`') parser.add_argument('--output_dir', type=str, default=os.environ['SM_MODEL_DIR']) parser.add_argument('--training_dir', type=str, default=os.environ['SM_CHANNEL_TRAIN']) parser.add_argument('--validation_dir', type=str, default=os.environ['SM_CHANNEL_VALIDATION']) args = parser.parse_args() config = {'lr': 2e-05, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(config, args) if __name__ == '__main__': main() # File: notebooks-main/sagemaker/23_stable_diffusion_inference/code/inference.py import base64 import torch from io import BytesIO from diffusers import StableDiffusionPipeline def model_fn(model_dir): pipe = StableDiffusionPipeline.from_pretrained(model_dir, torch_dtype=torch.float16) pipe = pipe.to('cuda') return pipe def predict_fn(data, pipe): prompt = data.pop('inputs', data) num_inference_steps = data.pop('num_inference_steps', 50) guidance_scale = data.pop('guidance_scale', 7.5) num_images_per_prompt = data.pop('num_images_per_prompt', 4) generated_images = pipe(prompt, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale, num_images_per_prompt=num_images_per_prompt)['images'] encoded_images = [] for image in generated_images: buffered = BytesIO() image.save(buffered, format='JPEG') encoded_images.append(base64.b64encode(buffered.getvalue()).decode()) return {'generated_images': encoded_images}