This module contains core custom models, loss functions, etc... for Seq2Seq based tasks (e.g., language modeling, summarization, translation, etc...)
[nltk_data] Downloading package wordnet to /home/wgilliam/nltk_data...
[nltk_data]   Package wordnet is already up-to-date!
 
[nltk_data] Downloading package wordnet to /home/wgilliam/nltk_data...
[nltk_data]   Package wordnet is already up-to-date!
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

Seq2Seq

path = Path('./')
cnndm_df = pd.read_csv(path/'cnndm_sample.csv')

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.models.bart.configuration_bart.BartConfig,
 transformers.models.bart.tokenization_bart_fast.BartTokenizerFast,
 transformers.models.bart.modeling_bart.BartForConditionalGeneration)
before_batch_tfm = HF_Seq2SeqBeforeBatchTransform(hf_arch, hf_config, hf_tokenizer, hf_model,
                                                  max_length=256, max_target_length=130)

blocks = (HF_Seq2SeqBlock(before_batch_tfm=before_batch_tfm), 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, 69]))
dls.show_batch(dataloaders=dls, max_n=2)
text target
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 that harbor the majority of the Earth's species and are therefore considered extremely biodiverse. From its coral reefs in the Caribbean Sea to its tropical jungles in Chiapas and the Yucatan peninsula and its deserts and prairies in the north, Mexico boasts an incredibly rich variety of flora and fauna. Some 574 out of 717 reptile species found in Mexico -- the most in any country -- can only be encountered within its borders. It is home to 502 types of mammals, 290 species of birds, 1,150 varieties of birds and 26,000 classifications of plants. Pronatura, a non-profit organization that works to promote conservation and sustainable development in Mexico, has selected six species which it says symbolize the problems faced by the 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 under threat in spite of being the country's national symbol.
1 (CNN) -- Creativity has taken center stage in recent years, with a slew of books, articles and TED talks extolling the virtues of imagination and exhorting young and old to go out and exercise their creative muscle. In a 2010 IBM poll of CEOs worldwide, creativity was identified as the single most important leadership trait for success, enabling businesses to rise above an increasingly complex environment. The future belongs to "creators and empathizers, pattern recognizers and meaning makers," declared author Daniel Pink in the introduction to his best-selling book "A Whole New Mind: Why Right-Brainers Will Rule the Future." Creativity also matters to our emotional well-being as we find our way in an uncertain, rapidly shifting world. Imagination underpins our ability to remain resilient during difficult and stressful times since creative people tend to be more tolerant of ambiguity and better able to come back from defeat. And yet, despite its growing importance, creativity suffers from an odd sort of paradox. According to psychologist and Wharton management professor Jennifer Mueller, research shows that even as people explicitly aspire to creativity and strongly endorse it as a fundamental driving force of positive change, they routinely reject creative ideas and show an implicit bias against them under conditions of uncertainty. Subjects in Mueller's study People routinely reject and show bias against creative ideas, Amanda Enayati says.\nPoll of CEOs: Creativity is the single most important leadership trait for success.\nPeople reject creativity because of uncertainly -- but it's needed to help us through uncertainty.\nInnovator: Build confidence by treating fear of creativity like a phobia of heights or snakes.

Training

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

seq2seq_metrics

  • {'rouge': { 'compute_args': {'return_types': ["rouge1", "rouge2", "rougeL"], 'use_stemmer': True}, 'returns':["rouge1", "rouge2", "rougeL"]}
  • {'bert_score': { 'returns': ["precision", "recall", "f1"] }
  • {'bleu': { 'returns': "bleu" }
  • {'bleurt': { 'returns': "scores" }
  • {'meteor': { 'returns': "meteor" }
  • {'sacrebleu': { 'returns': "score" }

class HF_Seq2SeqMetricsCallback[source]

HF_Seq2SeqMetricsCallback(custom_metrics=None, ignore_token_id=-100, text_gen_kwargs={}, **kwargs) :: Callback

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 Seq2Seq tasks.

seq2seq_splitter[source]

seq2seq_splitter(m, arch)

Custom param splitter for summarization models

seq2seq_metrics = {
    'rouge': {
        'compute_kwargs': {
            'rouge_types': ["rouge1", "rouge2", "rougeL"], 'use_stemmer': True
        }, 
        'returns': ["rouge1", "rouge2", "rougeL"] 
    },
    'bertscore': {
        'compute_kwargs': { 'lang': 'en' },
        'returns': ["precision", "recall", "f1"]
    }, 
    'bleu': { 'returns': "bleu" },
    'meteor': { 'returns': "meteor" },
    'sacrebleu': { 'returns': "score" }
}

model = HF_BaseModelWrapper(hf_model)
learn_cbs = [HF_BaseModelCallback]
fit_cbs = [HF_Seq2SeqMetricsCallback(custom_metrics=seq2seq_metrics)]

learn = Learner(dls, 
                model,
                opt_func=partial(Adam),
                loss_func=CrossEntropyLossFlat(), #HF_PreCalculatedLoss()
                cbs=learn_cbs,
                splitter=partial(seq2seq_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
(4, torch.Size([]), torch.Size([2, 74, 50264]))
b = dls.one_batch()
preds = learn.model(b[0])

len(preds),preds['loss'].shape, preds['logits'].shape
(4, torch.Size([]), torch.Size([2, 69, 50264]))
print(len(learn.opt.param_groups))
3
learn.lr_find(suggestions=True)
SuggestedLRs(lr_min=8.317637839354575e-05, lr_steep=2.2908675418875646e-06)
learn.fit_one_cycle(1, lr_max=4e-5, cbs=fit_cbs)
epoch train_loss valid_loss rouge1 rouge2 rougeL bertscore_precision bertscore_recall bertscore_f1 bleu meteor sacrebleu time
0 1.681393 1.698626 0.383702 0.168457 0.265456 0.876273 0.894792 0.885359 0.146938 0.306586 11.781125 03:34

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][0][0][:20]))
<s><s>                About 10 men with with pistols and small machine guns raid a casino in Switzerland. made

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

b = dls.valid.one_batch()

b_before_batch_tfm = get_blurr_tfm(dls.before_batch)

b_hf_tokenizer = b_before_batch_tfm.hf_tokenizer
b_ignore_token_id = b_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 ===
 Paralympic movement was born in Stoke Mandeville, outside London, in 1948.
2012 Games will be the biggest yet, with 4,200 competitors from 165 countries.
In an echo of the first, post-World War II Games, injured veterans are among the athletes.
They include a U.S. naval officer blinded in Afghanistan and a Briton who lost an arm in Iraq.

=== Prediction ===
 "Stoke Mandeville Games" were organized in 1948 to coincide with the London Olympics.
The first "Paralympic Games" took place at the hospital in Buckinghamshire where Dr. Ludwig Guttmann's spinal injuries unit was based.
Guttmann, a Jewish doctor who fled Nazi Germany, was inspired by sport to change lives of patients with spinal injuries.
Six teams took part in the first Games, with wheelchair netball, a forerunner of wheelchair basketball, introduced.

We'll add a blurr_generate 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_generate[source]

Learner.blurr_generate(inp, task=None, **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_generate(test_article, num_return_sequences=3)

for idx, o in enumerate(outputs):
    print(f'=== Prediction {idx+1} ===\n{o}\n')
=== Prediction 1 ===
 10 men with pistols and small machine guns raid a casino in Switzerland .
They made off with several hundred thousand Swiss francs in the early hours of Sunday morning .
There were no serious injuries, although one guest was kicked in the head by one of the robbers .
The robbers spoke French and drove vehicles with French lRicense plates, police say .

=== Prediction 2 ===
 10 men with pistols and small machine guns raid a casino in Switzerland .
They made off with several hundred thousand Swiss francs in the early hours of Sunday morning .
There were no serious injuries, although one guest was kicked in the head by one of the robbers when he moved .
The robbers spoke French and drove vehicles with French lRicense plates .

=== Prediction 3 ===
 10 men with pistols and small machine guns raid a casino in Switzerland .
They made off with several hundred thousand Swiss francs in the early hours of Sunday morning .
There were no serious injuries, although one guest was kicked in the head by one of the robbers .
The robbers spoke French and drove vehicles with French lRicense plates .

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 London (CNN) -- In 1948, a hospital outside London witnessed the birth of the Paralympic movement, as a Jewish doctor who had fled Nazi Germany sought to change the lives of patients with spinal injuries -- and inspire new hope in them through sport. The first "Stoke Mandeville Games" were organized in 1948 to coincide with the London Olympics, the second to be held in Britain. Named for the hospital in Buckinghamshire where Prof. Ludwig Guttmann's pioneering spinal injuries unit was based, the Paralympic movement was born in Stoke Mandeville, outside London, in 1948.\n2012 Games will be the biggest yet, with 4,200 competitors from 165 countries.\nIn an echo of the first, post-World War II Games, injured veterans are among the athletes.\nThey "Stoke Mandeville Games" were organized in 1948 to coincide with the London Olympics .\nThe first "Paralympic Games" took place at the hospital in Buckinghamshire where Dr. Ludwig Guttmann's spinal injuries unit was based .\nGuttmann, a Jewish doctor
1 Washington (CNN)Almost immediately following the news of the first terrorist attacks that eventually killed 17 people across France, the global community united around a Twitter hashtag "Je suis Charlie" and just days later foreign leaders linked arms with their French counterparts to lead a historic million-person strong rally. Meanwhile, explosives strapped to a girl who appeared to be about 10-years-old detonated on Saturday, killing at least 20 people, in a country whose encounters with ter France and Nigeria experienced waves of terrorism during the first weeks of 2015.\nWhile the terror attacks in Paris sparked international unified outrage, reaction to Nigeria was more muted.\nSymbolism, politics and media all played a role in how Fra Terrorist attacks in Paris and Nigeria fomented unprecedented international reaction .\nThe response to the attacks in Nigeria paled in comparison to the one in Paris .\nBoth attacks were highly symbolic, but the Paris attack was violent and symbolic

Inference

export_fname = 'summarize_export'
learn.metrics = None
learn.export(fname=f'{export_fname}.pkl')
inf_learn = load_learner(fname=f'{export_fname}.pkl')
inf_learn.blurr_generate(test_article)
[' 10 men with pistols and small machine guns raid a casino in Switzerland .\nThey made off with several hundred thousand Swiss francs in the early hours of Sunday morning .\nThere were no serious injuries, although one guest was kicked in the head by one of the robbers .\nThe robbers spoke French and drove vehicles with French lRicense plates, police say .']

Cleanup