Views
No views yet
EncoderDecoderModel, meaning that both the encoder and the decoder are roberta-base
RoBERTa models. In this setup the encoder and decoder weights are tied. Leveraging the EncoderDecoderFramework, the
two pretrained models can simply be loaded into the framework via:roberta2roberta = EncoderDecoderModel.from_encoder_decoder_pretrained("roberta-base", "roberta-base", tie_encoder_decoder=True)EncoderDecoder model needs cross-attention layers and usually makes use of causal
masking for auto-regressiv generation.
Thus, roberta2roberta is consequently fined-tuned on the CNN/Daily Maildataset and the resulting model
roberta2roberta-share-cnn_dailymail-fp16 is uploaded here.1from transformers import RobertaTokenizer, EncoderDecoderModel
2
3model = EncoderDecoderModel.from_pretrained("patrickvonplaten/roberta2roberta-share-cnn_dailymail-fp16")
4tokenizer = RobertaTokenizer.from_pretrained("roberta-base")
5
6article = """(CNN)Sigma Alpha Epsilon is under fire for a video showing party-bound fraternity members singing a racist chant. SAE's national chapter suspended the students, but University of Oklahoma President David B
7oren took it a step further, saying the university's affiliation with the fraternity is permanently done. The news is shocking, but it's not the first time SAE has faced controversy. SAE was founded March 9, 185
86, at the University of Alabama, five years before the American Civil War, according to the fraternity website. When the war began, the group had fewer than 400 members, of which "369 went to war for the Confede
9rate States and seven for the Union Army," the website says. The fraternity now boasts more than 200,000 living alumni, along with about 15,000 undergraduates populating 219 chapters and 20 "colonies" seeking fu
10ll membership at universities. SAE has had to work hard to change recently after a string of member deaths, many blamed on the hazing of new recruits, SAE national President Bradley Cohen wrote in a message on t
11he fraternity's website. The fraternity's website lists more than 130 chapters cited or suspended for "health and safety incidents" since 2010. At least 30 of the incidents involved hazing, and dozens more invol
12ved alcohol. However, the list is missing numerous incidents from recent months. Among them, according to various media outlets: Yale University banned the SAEs from campus activities last month after members al
13legedly tried to interfere with a sexual misconduct investigation connected to an initiation rite. Stanford University in December suspended SAE housing privileges after finding sorority members attending a frat
14ernity function were subjected to graphic sexual content. And Johns Hopkins University in November suspended the fraternity for underage drinking. "The media has labeled us as the 'nation's deadliest fraternity,
15' " Cohen said. In 2011, for example, a student died while being coerced into excessive alcohol consumption, according to a lawsuit. SAE's previous insurer dumped the fraternity. "As a result, we are paying Lloy
16d's of London the highest insurance rates in the Greek-letter world," Cohen said. Universities have turned down SAE's attempts to open new chapters, and the fraternity had to close 12 in 18 months over hazing in
17cidents."""
18
19input_ids = tokenizer(article, return_tensors="pt").input_ids
20output_ids = model.generate(input_ids)
21
22print(tokenizer.decode(output_ids[0], skip_special_tokens=True))
23# should produce
24# SAE's national chapter suspended after video shows party-bound fraternity members singing racist chant. University of Oklahoma president says university's affiliation with fraternity is permanently done.
25# SAE has had to close 12 chapters since 2010 after members were killed in hazing. The fraternity has had more than 130 chapters in 18 months.Trainer for EncoderDecoderModels according to this PR: https://github.com/huggingface/transformers/pull/5840.roberta2roberta-cnn_dailymail-fp16 for reproducability. The training last ~9h on a standard GPU.1#!/usr/bin/env python3
2import nlp
3import logging
4from transformers import RobertaTokenizer, EncoderDecoderModel, Trainer, TrainingArguments
5
6logging.basicConfig(level=logging.INFO)
7
8model = EncoderDecoderModel.from_encoder_decoder_pretrained("roberta-base", "roberta-base", tie_encoder_decoder=True)
9tokenizer = RobertaTokenizer.from_pretrained("roberta-base")
10
11# load train and validation data
12train_dataset = nlp.load_dataset("cnn_dailymail", "3.0.0", split="train")
13val_dataset = nlp.load_dataset("cnn_dailymail", "3.0.0", split="validation[:5%]")
14
15# load rouge for validation
16rouge = nlp.load_metric("rouge", experiment_id=0)
17
18# set decoding params
19model.config.decoder_start_token_id = tokenizer.bos_token_id
20model.config.eos_token_id = tokenizer.eos_token_id
21model.config.max_length = 142
22model.config.min_length = 56
23model.config.no_repeat_ngram_size = 3
24model.early_stopping = True
25model.length_penalty = 2.0
26model.num_beams = 4
27
28encoder_length = 512
29decoder_length = 128
30batch_size = 16
31
32
33# map data correctly
34def map_to_encoder_decoder_inputs(batch):
35 # Tokenizer will automatically set [BOS] <text> [EOS]
36 # cut off at Longformer at 2048
37 inputs = tokenizer(batch["article"], padding="max_length", truncation=True, max_length=encoder_length)
38 # force summarization <= 256
39 outputs = tokenizer(batch["highlights"], padding="max_length", truncation=True, max_length=decoder_length)
40
41 batch["input_ids"] = inputs.input_ids
42 batch["attention_mask"] = inputs.attention_mask
43 batch["decoder_input_ids"] = outputs.input_ids
44 batch["labels"] = outputs.input_ids.copy()
45 # mask loss for padding
46 batch["labels"] = [
47 [-100 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch["labels"]
48 ]
49 batch["decoder_attention_mask"] = outputs.attention_mask
50
51 assert all([len(x) == encoder_length for x in inputs.input_ids])
52 assert all([len(x) == decoder_length for x in outputs.input_ids])
53
54 return batch
55
56
57def compute_metrics(pred):
58 labels_ids = pred.label_ids
59 pred_ids = pred.predictions
60
61 # all unnecessary tokens are removed
62 pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
63 labels_ids[labels_ids == -100] = tokenizer.eos_token_id
64 label_str = tokenizer.batch_decode(labels_ids, skip_special_tokens=True)
65
66 rouge_output = rouge.compute(predictions=pred_str, references=label_str, rouge_types=["rouge2"])["rouge2"].mid
67
68 return {
69 "rouge2_precision": round(rouge_output.precision, 4),
70 "rouge2_recall": round(rouge_output.recall, 4),
71 "rouge2_fmeasure": round(rouge_output.fmeasure, 4),
72 }
73
74
75# make train dataset ready
76train_dataset = train_dataset.map(
77 map_to_encoder_decoder_inputs, batched=True, batch_size=batch_size, remove_columns=["article", "highlights"],
78)
79train_dataset.set_format(
80 type="torch", columns=["input_ids", "attention_mask", "decoder_attention_mask", "decoder_input_ids", "labels"],
81)
82
83# same for validation dataset
84val_dataset = val_dataset.map(
85 map_to_encoder_decoder_inputs, batched=True, batch_size=batch_size, remove_columns=["article", "highlights"],
86)
87val_dataset.set_format(
88 type="torch", columns=["input_ids", "decoder_attention_mask", "attention_mask", "decoder_input_ids", "labels"],
89)
90
91# set training arguments - these params are not really tuned, feel free to change
92training_args = TrainingArguments(
93 output_dir="./",
94 per_device_train_batch_size=batch_size,
95 per_device_eval_batch_size=batch_size,
96 predict_from_generate=True,
97 evaluate_during_training=True,
98 do_train=True,
99 do_eval=True,
100 logging_steps=1000,
101 save_steps=1000,
102 eval_steps=1000,
103 overwrite_output_dir=True,
104 warmup_steps=2000,
105 save_total_limit=3,
106 fp16=True,
107)
108
109# instantiate trainer
110trainer = Trainer(
111 model=model,
112 args=training_args,
113 compute_metrics=compute_metrics,
114 train_dataset=train_dataset,
115 eval_dataset=val_dataset,
116)
117
118# start training
119trainer.train()1#!/usr/bin/env python3
2import nlp
3from transformers import RobertaTokenizer, EncoderDecoderModel
4
5tokenizer = RobertaTokenizer.from_pretrained("roberta-base")
6model = EncoderDecoderModel.from_pretrained("patrickvonplaten/roberta2roberta-share-cnn_dailymail-fp16")
7model.to("cuda")
8
9test_dataset = nlp.load_dataset("cnn_dailymail", "3.0.0", split="test")
10batch_size = 128
11
12
13# map data correctly
14def generate_summary(batch):
15 # Tokenizer will automatically set [BOS] <text> [EOS]
16 # cut off at BERT max length 512
17 inputs = tokenizer(batch["article"], padding="max_length", truncation=True, max_length=512, return_tensors="pt")
18 input_ids = inputs.input_ids.to("cuda")
19 attention_mask = inputs.attention_mask.to("cuda")
20
21 outputs = model.generate(input_ids, attention_mask=attention_mask)
22
23 # all special tokens including will be removed
24 output_str = tokenizer.batch_decode(outputs, skip_special_tokens=True)
25
26 batch["pred"] = output_str
27
28 return batch
29
30
31results = test_dataset.map(generate_summary, batched=True, batch_size=batch_size, remove_columns=["article"])
32
33# load rouge for validation
34rouge = nlp.load_metric("rouge")
35
36pred_str = results["pred"]
37label_str = results["highlights"]
38
39rouge_output = rouge.compute(predictions=pred_str, references=label_str, rouge_types=["rouge2"])["rouge2"].mid
40
41print(rouge_output)| - | Rouge2 - mid -precision | Rouge2 - mid - recall | Rouge2 - mid - fmeasure |
|---|---|---|---|
| CNN/Daily Mail | 15.6 | 18.79 | 16.59 |