This module contains custom models, custom splitters, etc... summarization tasks.
torch.cuda.set_device(1)
print(f'Using GPU #{torch.cuda.current_device()}: {torch.cuda.get_device_name()}')
Using GPU #1: GeForce GTX 1080 Ti

Summarization

The objective of summarization is to generate a concise and accurate representation of a much larger body of text. For example, we may want to summarize an article in a single sentence.

path = Path('./')
cnndm_df = pd.read_csv(path/'cnndm_sample.csv'); len(cnndm_df)
1000
cnndm_df.head(2)
article highlights ds_type
0 (CNN) -- Globalization washes like a flood over the world's cultures and economies. Floods can be destructive; however, they can also bring blessings, as the annual floods of the Nile did for ancient Egypt. The world's great universities can be crucial instruments in shaping, in a positive way, humankind's reaction to globalization and the development of humankind itself. Traditionally, universities have been defined and limited by location, creating an academic community and drawing students and scholars to that place. Eventually, some universities began to encourage students to study el... John Sexton: Traditionally, universities have been defined and limited by location .\nGlobal campuses form a network of thought, innovation, he writes .\nFaculty can teach, Sexton says, students can team up in many cities at once .\nSexton: Research, scholarship can be shared and cultural ties made in "century of knowledge" train
1 (CNN) -- Armenian President Robert Kocharian declared a state of emergency Saturday night after a day of clashes between police and protesters, a spokeswoman for the Armenian Foreign Ministry said. Opposition supporters wave an Armenian flag during a protest rally in Yerevan, Armenia, on Saturday. The protesters claim last month's presidential election was rigged. The state of emergency will "hopefully bring some order" to the capital, Yerevan, said Salpi Ghazarian, assistant to the Armenian foreign minister, who spoke to CNN early Sunday. The state of emergency could last until March 20, ... NEW: Protest moves after crackdown at Freedom Square .\nOrder sought after protests over last month's election turn violent .\nDemonstrators say the election was fraudulent .\nState of emergency could last until March 20, official says . train
pretrained_model_name = "facebook/bart-large-cnn"
hf_arch, hf_config, hf_tokenizer, hf_model = BLURR_MODEL_HELPER.get_hf_objects(pretrained_model_name, 
                                                                               model_cls=BartForConditionalGeneration)

hf_arch, type(hf_config), type(hf_tokenizer), type(hf_model)
('bart',
 transformers.configuration_bart.BartConfig,
 transformers.tokenization_bart.BartTokenizer,
 transformers.modeling_bart.BartForConditionalGeneration)
before_batch_tfm = HF_SummarizationBeforeBatchTransform(hf_arch, hf_tokenizer, max_length=[256, 130])
blocks = (HF_Text2TextBlock(before_batch_tfms=before_batch_tfm, input_return_type=HF_SummarizationInput), noop)

dblock = DataBlock(blocks=blocks, 
                   get_x=ColReader('article'), 
                   get_y=ColReader('highlights'), 
                   splitter=RandomSplitter())
dls = dblock.dataloaders(cnndm_df, bs=2)
b = dls.one_batch()
len(b), b[0]['input_ids'].shape, b[1].shape
(2, torch.Size([2, 256]), torch.Size([2, 68]))
dls.show_batch(dataloaders=dls, max_n=2)
text target
0 Dan Condon believes in recycling. Just not when it comes to his hotel towels. Condon composts when he's at home in Boulder, Colorado. He eats local, organic and fair-trade food and drives a Honda CR-Z hybrid sports car. You might call him green. Except he's not so green when he travels for his work at an education nonprofit and stays in a hotel, which happens about 10 weeks per year. There, he uses a new towel every day. And don't try to bribe him with a drink or dessert coupon to get him to reuse the same one. "I could care less about rewards for environmentally conscious behavior unless it's miles," Condon wrote in an e-mail. If hotels can't convince a hybrid-driving recycling enthusiast like Condon to go green while traveling, how can they possibly convince everyone else? 9 glamorous movie-star hotels. That's the problem of hotels trying to "green" your hotel stay. After guests have paid a pretty penny for a night at the inn, even the most environmental guests may want to treat themselves to fresh towels every day and those little bottles of sweet-smelling shampoo. Despite the fact that most people describe themselves in surveys as environmentally conscious and as preferring green products, Hotel guests who "go green" are happier with their stay.\nIncreasing water and energy costs are pushing hotels to cut costs wherever they can.\nMany hotels find that guests don't mind using the same towels and sheets every night.\nTripAdvisor will be adding a green label for hotels listed on its site.
1 Washington (CNN) -- Few answers have emerged to the myriad questions about the Boston Marathon bombing and its aftermath, but that didn't stop political leaders from clashing about what happened and why it did on Sunday talk shows. Republican members of Congress played up a possible connection to global terrorists and said the lone surviving suspect should be designated an enemy combatant to allow unfettered questioning and unlimited detention. Democratic legislators called for handling the 19-year-old suspect as a crime suspect rather than a war enemy, allowing the U.S. citizen the right to legal representation under federal law that could impose the death penalty. A closer look at their statements and arguments showed how politicians blend facts, conjecture and spin to push their side's agenda while countering arguments from across the aisle. The facts so far tell a still-convoluted story. Tamerlan and Dzhokhar Tsarnaev, brothers of northern Caucasus origin who had lived in the United States for years, allegedly set off two bombs near the finish line of Monday's Boston Marathon, killing three people and injuring more than 170. Graham: 'Ball was dropped' in probe of Tamerlan. After the FBI released video footage and photos of the pair on Thursday, they allegedly shot to death a university police officer and Partisan posturing emerges over Boston bombings on Sunday talk shows.\nDespite little evidence, Republicans hint of possible international terror ties.\nDemocrats argue against designating the suspect an enemy combatant.\nAuthors of immigration reform reject conservative calls to put off the issue.

Metrics

In this section, we'll add helpful metrics for summarization tasks

calculate_rouge[source]

calculate_rouge(predicted_txts, reference_txts, rouge_keys=['rouge1', 'rouge2', 'rougeL'], use_stemmer=True)

Training

Here we create a summarization specific subclass of HF_BaseModelCallback in order to include custom, summarization specific, metrics, and also handle the pre-calculated loss during training

class HF_SummarizationModelCallback[source]

HF_SummarizationModelCallback(rouge_metrics=['rouge1', 'rouge2', 'rougeL'], ignore_token_id=-100, text_gen_kwargs={}, **kwargs) :: HF_BaseModelCallback

Basic class handling tweaks of the training loop by changing a Learner in various events

We add a custom param splitter to give us a bit more depth in applying discriminative learning rates for summarization.

summarization_splitter[source]

summarization_splitter(m, arch)

Custom param splitter for summarization models

text_gen_kwargs = { **hf_config.task_specific_params['summarization'], **{'max_length': 130, 'min_length': 30} }
text_gen_kwargs
{'early_stopping': True,
 'length_penalty': 2.0,
 'max_length': 130,
 'min_length': 30,
 'no_repeat_ngram_size': 3,
 'num_beams': 4}
generate_func_args = list(inspect.signature(hf_model.generate).parameters.keys())
for k in text_gen_kwargs:
    if k not in generate_func_args: del text_gen_kwargs[k]
        
text_gen_kwargs
{'early_stopping': True,
 'length_penalty': 2.0,
 'max_length': 130,
 'min_length': 30,
 'no_repeat_ngram_size': 3,
 'num_beams': 4}
model = HF_BaseModelWrapper(hf_model)
model_cb = HF_SummarizationModelCallback(text_gen_kwargs=text_gen_kwargs)

learn = Learner(dls, 
                model,
                opt_func=partial(Adam),
                loss_func=CrossEntropyLossFlat(), #HF_PreCalculatedLoss()
                cbs=[model_cb],
                splitter=partial(summarization_splitter, arch=hf_arch)) #.to_native_fp16() #.to_fp16()

learn.create_opt() 
learn.freeze()
 
b = dls.one_batch()
preds = learn.model(b[0])
len(preds),preds['loss'].shape, preds['logits'].shape
(3, torch.Size([]), torch.Size([2, 77, 50264]))
len(b), len(b[0]), b[0]['input_ids'].shape, len(b[1]), b[1].shape
(2, 4, torch.Size([2, 256]), 2, torch.Size([2, 77]))
print(len(learn.opt.param_groups))
3
learn.lr_find(suggestions=True)
SuggestedLRs(lr_min=0.00010000000474974513, lr_steep=2.0892961401841603e-05)
learn.fit_one_cycle(1, lr_max=4e-5)
epoch train_loss valid_loss rouge1 rouge2 rougeL time
0 1.912652 1.809375 0.375766 0.157390 0.255853 03:46

Showing results

Below we'll add in additional functionality to take advantage of huggingface's PreTrainedModel.generate model, which can be used to easily implement beam search, top-k/nucleous sampling, etc... so that we get more human sounding results.

test_article = """
About 10 men armed with pistols and small machine guns raided a casino in Switzerland and made off 
into France with several hundred thousand Swiss francs in the early hours of Sunday morning, police said. 
The men, dressed in black clothes and black ski masks, split into two groups during the raid on the Grand Casino 
Basel, Chief Inspector Peter Gill told CNN. One group tried to break into the casino's vault on the lower level 
but could not get in, but they did rob the cashier of the money that was not secured, he said. The second group 
of armed robbers entered the upper level where the roulette and blackjack tables are located and robbed the 
cashier there, he said. As the thieves were leaving the casino, a woman driving by and unaware of what was 
occurring unknowingly blocked the armed robbers' vehicles. A gunman pulled the woman from her vehicle, beat 
her, and took off for the French border. The other gunmen followed into France, which is only about 100 
meters (yards) from the casino, Gill said. There were about 600 people in the casino at the time of the robbery. 
There were no serious injuries, although one guest on the Casino floor was kicked in the head by one of the 
robbers when he moved, the police officer said. Swiss authorities are working closely with French authorities, 
Gill said. The robbers spoke French and drove vehicles with French lRicense plates. CNN's Andreena Narayan 
contributed to this report.
"""
res = learn.blurr_predict(test_article)
print(hf_tokenizer.decode(res[0][:20]))
 10 10About 10 men robbed with pistols and machine machine guns raid a casino in Switzerland and made off

That doesn't look much like a human-generated summary. Let's use huggingface's PreTrainedModel.generate method to create something more human-like.

b = dls.valid.one_batch()

b_before_batch_tfm = dls.before_batch[0]
b_hf_tokenizer = before_batch_tfm.hf_tokenizer
b_ignore_token_id = before_batch_tfm.ignore_token_id

test_input_ids = b[0]['input_ids'][0].unsqueeze(0).to(learn.model.hf_model.device)
test_trg_ids = b[1][0].unsqueeze(0).to(learn.model.hf_model.device)
test_trg_ids = [ trg[trg != b_ignore_token_id] for trg in test_trg_ids ]

gen_text = learn.model.hf_model.generate(test_input_ids, num_beams=4, max_length=130, min_length=30)

print('=== Target ===')
print(f'{b_hf_tokenizer.decode(test_trg_ids[0], skip_special_tokens=True, clean_up_tokenization_spaces=True)}\n')

print('=== Prediction ===')
print(b_hf_tokenizer.decode(gen_text[0], skip_special_tokens=True, clean_up_tokenization_spaces=True))
=== Target ===
 Mexico hosts to up to 10 percent of all known species on Earth.
It is home to 502 types of mammals, 290 bird species and 26,000 types of plants.
Human development and climate change is placing a big strain on its biodiversity.
The Golden Eagle is under threat in spite of being the country's national symbol.

=== Prediction ===
 Climate change and human encroachment on natural environments threaten Mexico's rich wildlife.
Mexico is home to 502 types of mammals, 290 species of birds, 1,150 varieties of birds and 26,000 classifications of plants.
Some 574 out of 717 reptile species found in Mexico -- the most in any country -- can only be encountered within its borders.
Pronatura, a non-profit organization, has selected six species it says symbolize the problems faced by the country.

We'll add a blurr_summarize method to Learner that uses huggingface's PreTrainedModel.generate to create our predictions. For the full list of arguments you can pass in see here. You can also check out their "How To Generate" notebook for more information about how it all works.

Learner.blurr_summarize[source]

Learner.blurr_summarize(inp, **kwargs)

Uses the built-in generate method to generate the text (see here for a list of arguments you can pass in)

outputs = learn.blurr_summarize(test_article, num_return_sequences=3)

for idx, o in enumerate(outputs):
    print(f'=== Prediction {idx+1} ===\n{o}\n')
=== Prediction 1 ===
 Robbers made off with several hundred thousand Swiss francs in the early hours of Sunday morning, police say .
The men, dressed in black clothes and black ski masks, split into two groups during the raid on the Grand Casino Basel .
There were no serious injuries, although one guest was kicked in the head by one of the robbers when he moved, police officer says .
A woman driving by unknowingly blocked the robbers' vehicles and was beaten to death .
Swiss authorities are working closely with French authorities, police chief says .

=== Prediction 2 ===
 Robbers made off with several hundred thousand Swiss francs in the early hours of Sunday morning, police say .
The men, dressed in black clothes and black ski masks, split into two groups during the raid on the Grand Casino Basel .
There were no serious injuries, although one guest was kicked in the head by one of the robbers when he moved, police officer says .
A woman driving by unknowingly blocked the robbers' vehicles and was beaten to death .
Swiss authorities are working closely with French authorities, an officer says.

=== Prediction 3 ===
 Robbers made off with several hundred thousand Swiss francs in the early hours of Sunday morning, police say .
The men, dressed in black clothes and black ski masks, split into two groups during the raid on the Grand Casino Basel .
There were no serious injuries, although one guest was kicked in the head by one of the robbers when he moved, police officer says .
A woman driving by unknowingly blocked the robbers' vehicles and was beaten to death .

Much nicer!!! Now, we can update our @typedispatched show_results to use this new method.

learn.show_results(learner=learn, input_trunc_at=500, target_trunc_at=250)
text target prediction
0 (CNN) -- Home to up to 10 percent of all known species, Mexico is recognized as one of the most biodiverse regions on the planet. The twin threats of climate change and human encroachment on natural environments are, however, threatening the existence of the country's rich wildlife. And there is a great deal to lose. In the United Nations Environment Program (UNEP) World Conservation Monitoring Centre's list of megadiverse countries Mexico ranks 11th. The list represents a group of 17 countries Mexico hosts to up to 10 percent of all known species on Earth.\nIt is home to 502 types of mammals, 290 bird species and 26,000 types of plants.\nHuman development and climate change is placing a big strain on its biodiversity.\nThe Golden Eagle is un Climate change and human encroachment on natural environments threaten Mexico's rich wildlife .\nMexico is home to 502 types of mammals, 290 species of birds, 1,150 varieties of birds and 26,000 classifications of plants .\nSome 574 out of 717 reptile
1 (CNN Student News) -- Parents and Teachers: Watch with your students or record "Gary + Tony Have a Baby" when it airs on CNN on Thursday, June 24 at 8 p.m. ET. By recording the documentary, you agree that you will use the program for educational viewing purposes for a one-year period only. No other rights of any kind or nature whatsoever are granted, including, without limitation, any rights to sell, publish, distribute, post online or distribute in any other medium or forum, or use for any com "Gary + Tony Have a Baby" is a documentary that follows the journey of a gay couple as they attempt to become parents.\nParents and educators can use this guide to initiate discussion with students about the documentary. "Gary + Tony Have a Baby" is a documentary that follows the journey of a gay couple as they attempt to become parents .\nWe recommend that you preview this program and determine whether it is appropriate before showing it to students .\nBy recording t

Inference

learn.export(fname='summarize_export.pkl')
inf_learn = load_learner(fname='summarize_export.pkl')
inf_learn.blurr_summarize(test_article)
[" Robbers made off with several hundred thousand Swiss francs in the early hours of Sunday morning, police say .\nThe men, dressed in black clothes and black ski masks, split into two groups during the raid on the Grand Casino Basel .\nThere were no serious injuries, although one guest was kicked in the head by one of the robbers when he moved, police officer says .\nA woman driving by unknowingly blocked the robbers' vehicles and was beaten to death .\nSwiss authorities are working closely with French authorities, police chief says ."]

Tests

The tests below to ensure the core training code above works for all pretrained summarization models available in huggingface. These tests are excluded from the CI workflow because of how long they would take to run and the amount of data that would be required to download.

Note: Feel free to modify the code below to test whatever pretrained summarization models you are working with ... and if any of your pretrained summarization models fail, please submit a github issue (or a PR if you'd like to fix it yourself)

try: del learn; torch.cuda.empty_cache()
except: pass
BLURR_MODEL_HELPER.get_models(task='ConditionalGeneration')
[transformers.modeling_bart.BartForConditionalGeneration,
 transformers.modeling_blenderbot.BlenderbotForConditionalGeneration,
 transformers.modeling_fsmt.FSMTForConditionalGeneration,
 transformers.modeling_mbart.MBartForConditionalGeneration,
 transformers.modeling_pegasus.PegasusForConditionalGeneration,
 transformers.modeling_prophetnet.ProphetNetForConditionalGeneration,
 transformers.modeling_t5.T5ForConditionalGeneration,
 transformers.modeling_xlm_prophetnet.XLMProphetNetForConditionalGeneration]
pretrained_model_names = [
    ('facebook/bart-large-cnn',BartForConditionalGeneration),
    ('t5-small', T5ForConditionalGeneration),
    #('google/pegasus-cnn_dailymail', PegasusForConditionalGeneration), ... don't fit on my 1080TI :(
]
path = Path('./')
cnndm_df = pd.read_csv(path/'cnndm_sample.csv')
#hide_output
bsz = 2
inp_seq_sz = 128; trg_seq_sz = 130

test_results = []
for model_name, model_cls in pretrained_model_names:
    error=None
    
    print(f'=== {model_name} ===\n')
    
    hf_arch, hf_config, hf_tokenizer, hf_model = BLURR_MODEL_HELPER.get_hf_objects(model_name, 
                                                                                   model_cls=model_cls)
    
    print(f'architecture:\t{hf_arch}\ntokenizer:\t{type(hf_tokenizer).__name__}\nmodel:\t\t{type(hf_model).__name__}\n')
    
    # 1. build your DataBlock
    def add_t5_prefix(inp): return f'summarize: {inp}' if (hf_arch == 't5') else inp
    
    before_batch_tfm = HF_SummarizationBeforeBatchTransform(hf_arch, hf_tokenizer, 
                                                            max_length=[inp_seq_sz, trg_seq_sz])
    
    blocks = (
        HF_Text2TextBlock(before_batch_tfms=before_batch_tfm, input_return_type=HF_SummarizationInput), 
        noop
    )
    
    dblock = DataBlock(blocks=blocks, 
                       get_x=Pipeline([ColReader('article'), add_t5_prefix]), 
                       get_y=ColReader('highlights'), 
                       splitter=RandomSplitter())

    dls = dblock.dataloaders(cnndm_df, bs=bsz)

    # 2. build your Learner
    text_gen_kwargs = {}
    if (hf_arch in ['bart', 't5']):
        text_gen_kwargs = { 
            **hf_config.task_specific_params['summarization'], 
            **{'max_length': 30, 'min_length': 10} 
        }
    
    # not all "summarization" parameters are for the model.generate method ... remove them here
    generate_func_args = list(inspect.signature(hf_model.generate).parameters.keys())
    for k in text_gen_kwargs.copy():
        if k not in generate_func_args: del text_gen_kwargs[k]
    
    
    model = HF_BaseModelWrapper(hf_model)
    model_cb = HF_SummarizationModelCallback(text_gen_kwargs=text_gen_kwargs)

    learn = Learner(dls, 
                    model,
                    opt_func=ranger,
                    loss_func=HF_PreCalculatedLoss(),
                    cbs=[model_cb],
                    splitter=partial(summarization_splitter, arch=hf_arch))

    learn.create_opt() 
    learn.freeze()
    
    # 3. Run your tests
    b = dls.one_batch()

    try:
        print('*** TESTING DataLoaders ***\n')
        test_eq(len(b), 2)
        test_eq(len(b[0]['input_ids']), bsz)
        test_eq(b[0]['input_ids'].shape, torch.Size([bsz, inp_seq_sz]))
        test_eq(len(b[1]), bsz)

        print('*** TESTING One pass through the model ***')
        preds = learn.model(b[0])
        test_eq(preds[1].shape[0], bsz)
        test_eq(preds[1].shape[2], hf_config.vocab_size)

        print('*** TESTING Training/Results ***')
        learn.fit_one_cycle(1, lr_max=1e-3)

        test_results.append((hf_arch, type(hf_tokenizer).__name__, type(hf_model).__name__, 'PASSED', ''))
        learn.show_results(learner=learn, max_n=2, input_trunc_at=500, target_trunc_at=250)
    except Exception as err:
        test_results.append((hf_arch, type(hf_tokenizer).__name__, type(hf_model).__name__, 'FAILED', err))
    finally:
        # cleanup
        del learn; torch.cuda.empty_cache()
arch tokenizer model_name result error
0 bart BartTokenizer BartForConditionalGeneration PASSED
1 t5 T5Tokenizer T5ForConditionalGeneration PASSED

Cleanup