An example of how to incorporate the transfomers library from HuggingFace with fastai

In this tutorial, we will see how we can use the fastai library to fine-tune a pretrained transformer model from the transformers library by HuggingFace. We will use the mid-level API to gather the data. Even if this tutorial is self contained, it might help to check the imagenette tutorial to have a second look on the mid-level API (with a gentle introduction using the higher level APIs) in computer vision.

Importing a transformers pretrained model

First things first, we will need to install the transformers library. If you haven't done it yet, just uncomment the following cell.

# ! pip install transformers

Then let's import what will need: we will fine-tune the GPT2 pretrained model and fine-tune on wikitext-2 here. For this, we need the GPT2LMHeadModel (since we want a language model) and the GPT2Tokenizer to prepare the data.

from transformers import GPT2LMHeadModel, GPT2TokenizerFast

We can use several verions of this GPT2 model, look at the transformers documentation for more details. Here we will use the basic version (that laready takes a lot of space in memory!) You can change the model used by changing the content of pretrained_weights (if it's not a GPT2 model, you'll need to change the classes used for the model and the tokenizer of course).

pretrained_weights = 'gpt2'
tokenizer = GPT2TokenizerFast.from_pretrained(pretrained_weights)
model = GPT2LMHeadModel.from_pretrained(pretrained_weights)

Before we move on to the fine-tuning part, let's have a look at this tokenizer and this model. The tokenizers in HuggingFace usually do the tokenization and the numericalization in one step (we ignore the padding warning for now):

ids = tokenizer.encode('This is an example of text, and')
ids
Using pad_token, but it is not set yet.
[1212, 318, 281, 1672, 286, 2420, 11, 290]

Like fastai Transforms, the tokenizer has a decode method to give you back a text from ids:

tokenizer.decode(ids)
'This is an example of text, and'

The model can be used to generate predictions (it is pretrained). It has a generate method that expects a batch of prompt, so we feed it our ids and add one batch dimension (there is a padding warning we can ignore as well):

import torch
t = torch.LongTensor(ids)[None]
preds = model.generate(t)
Setting `pad_token_id` to 50256 (first `eos_token_id`) to generate sequence

The predictions, by default, are of length 20:

preds.shape,preds[0]
(torch.Size([1, 20]),
 tensor([1212,  318,  281, 1672,  286, 2420,   11,  290,  340,  338,  407,  257,
          922,  530,   13,  198,  198,  464,  717, 1517]))

We can use the decode method (that prefers a numpy array to a tensor):

tokenizer.decode(preds[0].numpy())
"This is an example of text, and it's not a good one.\n\nThe first thing"

Bridging the gap with fastai

Now let's see how we can use fastai to fine-tune this model on wikitext-2, using all the training utilies (learning rate finder, 1cycle policy etc...). First, we import all the text utilities:

from fastai2.text.all import *

Preparing the data

Then we download the dataset (if not present), it comes as two csv files:

path = untar_data(URLs.WIKITEXT_TINY)
path.ls()
(#2) [Path('/home/sgugger/.fastai/data/wikitext-2/train.csv'),Path('/home/sgugger/.fastai/data/wikitext-2/test.csv')]

Let's have a look at what those csv files look like:

df_train = pd.read_csv(path/'train.csv', header=None)
df_valid = pd.read_csv(path/'test.csv', header=None)
df_train.head()
0
0 \n = 2013 – 14 York City F.C. season = \n \n The 2013 – 14 season was the <unk> season of competitive association football and 77th season in the Football League played by York City Football Club , a professional football club based in York , North Yorkshire , England . Their 17th @-@ place finish in 2012 – 13 meant it was their second consecutive season in League Two . The season ran from 1 July 2013 to 30 June 2014 . \n Nigel Worthington , starting his first full season as York manager , made eight permanent summer signings . By the turn of the year York were only above the relegation z...
1 \n = Big Boy ( song ) = \n \n " Big Boy " <unk> " I 'm A Big Boy Now " was the first single ever recorded by the Jackson 5 , which was released by Steeltown Records in January 1968 . The group played instruments on many of their Steeltown compositions , including " Big Boy " . The song was neither a critical nor commercial success , but the Jackson family were delighted with the outcome nonetheless . \n The Jackson 5 would release a second single with Steeltown Records before moving to Motown Records . The group 's recordings at Steeltown Records were thought to be lost , but they were re...
2 \n = The Remix ( Lady Gaga album ) = \n \n The Remix is a remix album by American recording artist Lady Gaga . Released in Japan on March 3 , 2010 , it contains remixes of the songs from her first studio album , The Fame ( 2008 ) , and her third extended play , The Fame Monster ( 2009 ) . A revised version of the track list was prepared for release in additional markets , beginning with Mexico on May 3 , 2010 . A number of recording artists have produced the songs , including Pet Shop Boys , Passion Pit and The Sound of Arrows . The remixed versions feature both uptempo and <unk> composit...
3 \n = New Year 's Eve ( Up All Night ) = \n \n " New Year 's Eve " is the twelfth episode of the first season of the American comedy television series Up All Night . The episode originally aired on NBC in the United States on January 12 , 2012 . It was written by Erica <unk> and was directed by Beth McCarthy @-@ Miller . The episode also featured a guest appearance from Jason Lee as Chris and Reagan 's neighbor and Ava 's boyfriend , Kevin . \n During Reagan ( Christina Applegate ) and Chris 's ( Will <unk> ) first New Year 's Eve game night , Reagan 's competitiveness comes out causing Ch...
4 \n = Geopyxis carbonaria = \n \n Geopyxis carbonaria is a species of fungus in the genus Geopyxis , family <unk> . First described to science in 1805 , and given its current name in 1889 , the species is commonly known as the charcoal loving elf @-@ cup , dwarf <unk> cup , <unk> <unk> cup , or pixie cup . The small , <unk> @-@ shaped fruitbodies of the fungus are reddish @-@ brown with a whitish fringe and measure up to 2 cm ( 0 @.@ 8 in ) across . They have a short , tapered stalk . Fruitbodies are commonly found on soil where brush has recently been burned , sometimes in great numbers ....

We gather all texts in one numpy array (since it will be easier to use this way with fastai):

all_texts = np.concatenate([df_train[0].values, df_valid[0].values])

To process this data to train a model, we need to build a Transform that will be applied lazily. In this case we might could do the pre-processing once and for all and only use the transform for decoding (we will see how just after), but the fast tokenizer from HuggingFace is, as its name indicates, fast, so it doesn't really impact performance to do it this way.

In a fastai Transform you can define:

  • an encodes method that is applied when you call the transform (a bit like the forward method in a nn.Module)
  • a decodes method that is applied when you call the decode method of the transform, if you need to decode anything for showing purposes (like converting ids to a text here)
  • a setups method that sets some inner state of the Transform (not needed here so we skip it)
class TransformersTokenizer(Transform):
    def __init__(self, tokenizer): self.tokenizer = tokenizer
    def encodes(self, x): 
        toks = self.tokenizer.tokenize(x)
        return tensor(self.tokenizer.convert_tokens_to_ids(toks))
    def decodes(self, x): return TitledStr(self.tokenizer.decode(x.cpu().numpy()))

Two comments on the code above:

  • in encodes we don't use the tokenizer.encode method since it does some additional preprocessing for the model after tokenizing and numericalizing (the aprt throwing a warning before). Here we don't need any post-processing so it's fine to skip it.
  • in decodes we return a TitledStr object and not jsut a plain string. That's a fastai class that adds a show method to the string, which will allow us to use all the fastai show methods.

You can then group your data with this Transform using a TfmdLists. It has an s in its name because it contains the training and validation set. We indicate the indices of the training set and the validation set with splits (here all the first indices until len(df_train) and then all the remaining indices):

splits = [list(range_of(df_train)), list(range(len(df_train), len(all_texts)))]
tls = TfmdLists(all_texts, TransformersTokenizer(tokenizer), splits=splits, dl_type=LMDataLoader)

We specify dl_type=LMDataLoader for when we will convert this TfmdLists to DataLoaders: we will use an LMDataLoader since we have a language modeling problem, not the usual fastai TfmdDL.

In a TfmdLists you can access to the elements of the training or validation set quite easily:

tls.train[0],tls.valid[0]
(tensor([220, 198, 796,  ..., 198, 220, 198]),
 tensor([220, 198, 796,  ..., 198, 220, 198]))

They both look the same but that just begins they begin and end the same way, we can see the shape are differents:

tls.tfms(tls.train.items[0]).shape, tls.tfms(tls.valid.items[0]).shape
(torch.Size([4576]), torch.Size([1485]))

And we can have a look at both decodes using show_at:

show_at(tls.train, 0)
 
 = 2013 – 14 York City F.C. season = 
 
 The 2013 – 14 season was the <unk> season of competitive association football and 77th season in the Football League played by York City Football Club, a professional football club based in York, North Yorkshire, England. Their 17th @-@ place finish in 2012 – 13 meant it was their second consecutive season in League Two. The season ran from 1 July 2013 to 30 June 2014. 
 Nigel Worthington, starting his first full season as York manager, made eight permanent summer signings. By the turn of the year York were only above the relegation zone on goal difference, before a 17 @-@ match unbeaten run saw the team finish in seventh @-@ place in the 24 @-@ team 2013 – 14 Football League Two. This meant York qualified for the play @-@ offs, and they were eliminated in the semi @-@ final by Fleetwood Town. York were knocked out of the 2013 – 14 FA Cup, Football League Cup and Football League Trophy in their opening round matches. 
 35 players made at least one appearance in nationally organised first @-@ team competition, and there were 12 different <unk>. Defender Ben Davies missed only five of the fifty @-@ two competitive matches played over the season. Wes Fletcher finished as leading scorer with 13 goals, of which 10 came in league competition and three came in the FA Cup. The winner of the <unk> of the Year award, voted for by the club's supporters, was <unk> Oyebanjo. 
 
 = = Background and pre @-@ season = = 
 
 The 2012 – 13 season was York City's first season back in the Football League, having won the Conference Premier play @-@ offs in 2011 – 12 after <unk> years in the Football Conference. Manager Gary Mills was sacked in March 2013 following an 11 @-@ match run without a victory, and was replaced by former Northern Ireland manager Nigel Worthington. Despite being in the relegation zone with three matches remaining, Worthington led the team to safety from relegation after a 1 – 0 win away to Dagenham & Redbridge on the final day of the season. York finished the season in 17th @-@ place in the 2012 – 13 League Two table. 
 Following the previous season's conclusion Lee <unk>, Jon <unk>, Chris <unk>, Ben Everson, Scott Kerr, David <unk>, Patrick <unk>, Michael Potts, Jamie Reed and Jason Walker were released by York, while <unk> Blair departed for Fleetwood Town. David McGurk, <unk> Oyebanjo, Danny Parslow, Tom Platt and Chris Smith signed new contracts with the club. New players signed ahead of the start of the season were goalkeeper Chris <unk> on a season @-@ long loan from Blackpool, defender Ben Davies on loan from Preston North End, midfielders Craig Clay from Chesterfield and Lewis Montrose from Gillingham, winger <unk> Puri from St <unk> and strikers Ryan Bowman from Hereford United, Richard Cresswell from Sheffield United, Wes Fletcher from Burnley and Ryan Jarvis from Torquay United. Defender Mike Atkinson and striker Chris Dickinson entered the first @-@ team squad from the youth team after agreeing professional contracts. 
 York retained the previous season's home and away kits. The home kit comprised red shirts with white sleeves, light blue shorts and white socks. The away kit included light blue shirts with white sleeves, white shorts and light blue socks. <unk> Health continued as shirt sponsors for the second successive season. 
 
 = = Review = = 
 
 
 = = = August = = = 
 
 York began the season with a 1 – 0 home win over the previous season's play @-@ off finalists, Northampton Town, with <unk> Jarvis scoring the winning goal in the 90th @-@ minute. However, defeat came in York's match against Championship side Burnley in the first round of the League Cup, going down 4 – 0 at home. The team endured their first league defeat of the season in the following game after being beaten 2 – 0 away by Dagenham & Redbridge, the home team scoring in each half. York then held Hartlepool United to a 0 – 0 home draw, before being beaten 3 – 2 away by Bristol Rovers, in which Jarvis scored twice before John @-@ Joe O 'Toole scored the winning goal for the home team in the 67th @-@ minute. Two signings were made shortly before the transfer deadline ; defender George Taft was signed on a one @-@ month loan from Leicester City, while Middlesbrough midfielder Ryan Brobbel joined on a one @-@ month loan. <unk> John <unk>, who had been told he had no future with the club, departed after signing for FC Halifax Town. Jarvis gave York the lead away at Exeter City before Alan <unk> scored in each half to see the home team win 2 – 1. 
 
 = = = September = = = 
 
 York suffered their first home league defeat of the season after AFC Wimbledon won 2 – 0, with Michael Smith scoring in each half. Former Ipswich Town midfielder Josh Carson, who had a spell on loan with York the previous season, signed a contract until the end of 2013 – 14 and Sheffield United midfielder Elliott <unk> signed on a one @-@ month loan. Brobbel opened the scoring in the second minute of his home debut against Mansfield Town, although the away team went on to score twice to win 2 – 1. York's run of four defeats ended following a 1 – 1 draw away to Wycombe Wanderers, in which McGurk gave York the lead before the home team levelled through Dean Morgan. Taft was sent back to Leicester after he fell behind McGurk, Parslow and Smith in the pecking order for a central defensive berth. York achieved their first win since the opening day of the season after beating Portsmouth 4 – 2 at home, with Fletcher ( 2 ), Montrose and Jarvis scoring. 
 
 = = = October = = = 
 
 Defender Luke O 'Neill was signed from Burnley on a 28 @-@ day emergency loan. He made his debut in York's 3 – 0 win away at Torquay, which was the team's first successive win of the season. York were knocked out of the Football League Trophy in the second round after being beaten 3 – 0 at home by League One team Rotherham United, before their winning streak in the league was ended with a 3 – 0 defeat away to Newport County. York drew 2 – 2 away to Chesterfield, having taken a two @-@ goal lead through O 'Neill and Jarvis, before the home team fought back through Armand <unk> and Jay O <unk>. The team then hosted Fleetwood Town, and the visitors won 2 – 0 with goals scored in each half by Gareth Evans and <unk> Matt. Scunthorpe United were beaten 4 – 1 at home to end York's three @-@ match run without a win, with all the team's goals coming in the first half from Carson, Fletcher and Brobbel ( 2 ). 
 
 = = = November = = = 
 
 Bowman scored his first goals for York away to Cheltenham Town, as York twice fought back from behind to draw 2 – 2. York drew 3 – 3 away to Bristol Rovers to earn a first round replay in the FA Cup, taking the lead through Jarvis before Eliot Richards equalised for the home team. Carson scored a 30 yard volley to put York back in the lead, and after Bristol Rovers goals from Matt <unk> and Chris <unk>, Fletcher scored an 86th @-@ minute equaliser for York. Bowman scored with a header from an O 'Neill cross to open the scoring at home to Plymouth Argyle, which was the first goal the visitors had conceded in 500 minutes of action. However, Plymouth equalised 11 minutes later through <unk> <unk> and the match finished a 1 – 1 draw. York were knocked out of the FA Cup after losing 3 – 2 at home to Bristol Rovers in a first round replay ; the visitors were 3 – 0 up by 50 @-@ minutes before Fletcher pulled two back for York with a penalty and a long @-@ range strike. 
 Defender Keith Lowe, of Cheltenham, and goalkeeper Nick Pope, of Charlton Athletic, were signed on loan until January 2014. They both played in York's first league defeat in four weeks, 2 – 1 away, to Southend United. <unk> <unk> gave Southend the lead early into the match and Bowman equalised for York with a low strike during the second half, before Luke Prosser scored the winning goal for the home side in stoppage time. With Pope preferred in goal, <unk> returned to Blackpool on his own accord, although his loan agreement would stay in place until January 2014. York then drew 0 – 0 away to Morecambe. After Pope was recalled from his loan by Charlton, York signed Wolverhampton Wanderers goalkeeper Aaron McCarey on loan until January 2014. McCarey kept a clean sheet in York's 0 – 0 home draw with Rochdale. 
 
 = = = December = = = 
 
 Cresswell retired from playing as a result of an eye complaint and a knee injury. York drew 1 – 1 away to Burton Albion, with an own goal scored by Shane <unk> @-@ <unk> giving York the lead in the 64th @-@ minute before the home team equalised eight minutes later through Billy <unk>. Atkinson was released after failing to force himself into the first team and signed for Scarborough Athletic, with whom he had been on loan. York drew 0 – 0 at home with second @-@ placed Oxford United, in which Carson came closest to scoring with a volley that <unk> across the face of the goal. This was followed by another draw after the match away to Accrington Stanley finished 1 – 1, with the home team <unk> 10 minutes after a Fletcher penalty had given York the lead in the 35th @-@ minute. Striker <unk> McDonald, who had been released by Peterborough United, was signed on a contract until the end of the season. York's last match of 2013 was a 2 – 1 defeat away at Bury, a result that ended York's run of consecutive draws at five. The home team were 2 – 0 up by the 19th @-@ minute, before Michael Coulson scored York's goal in the 73rd @-@ minute. This result meant York would begin 2014 in 22nd @-@ position in the table, only out of the relegation zone on goal difference. 
 
 = = = January = = = 
 
 Jarvis scored the only goal in York's first win since October 2013, a 1 – 0 home victory over Morecambe on New Year's Day. McCarey was recalled by Wolverhampton Wanderers due to an injury to one of their <unk>, while O 'Neill was recalled by Burnley to take part in their FA Cup match. York achieved back @-@ to @-@ back wins for the first time since October 2013 after Dagenham & Redbridge were beaten 3 – 1 at home, with Bowman opening the scoring in the second half before Fletcher scored twice. Adam Reed, who had a spell on loan with York in the previous season, was signed on a contract until the end of the season after parting company with Burton. Davies'loan was extended, while Brobbel and <unk> returned to their parent clubs. Cheltenham club captain Russell Penn, a midfielder, was signed on a two @-@ and @-@ a @-@ half @-@ year contract for an undisclosed fee. Lowe was subsequently signed permanently from Cheltenham on a two @-@ and @-@ a @-@ half @-@ year contract for an undisclosed fee. Having been allowed to leave the club on a free transfer, Ashley Chambers signed for Conference Premier club Cambridge United. 
 York achieved three successive wins for the first time in 2013 – 14 after beating Northampton 2 – 0 away, with Bowman and Fletcher scoring in three @-@ second half minutes. Defender John McCombe was signed on a two @-@ and @-@ a @-@ half @-@ year contract following his release from Mansfield, before Clay and Jamal <unk> left York by mutual consent. Pope returned to York on loan from Charlton for the remainder of the season. York's run of wins ended with a 0 – 0 draw at home to Bristol Rovers, before their first defeat of the year came after losing 2 – 0 away to Hartlepool. Preston winger Will Hayhurst, a Republic of Ireland under @-@ 21 international, was signed on a one @-@ month loan. York fell to a successive defeat for the first time since September 2013 after being beaten 2 – 0 at home by Chesterfield. Shortly after the match, Smith left the club by mutual consent to pursue first @-@ team football. 
 
 = = = February = = = 
 
 Fletcher scored a 90th @-@ minute winner for York away to Fleetwood in a 2 – 1 win, a result that ended Fleetwood's five @-@ match unbeaten run. York then drew 0 – 0 at home to fellow mid @-@ table team Cheltenham, before beating Plymouth 4 – 0 away with goals from Fletcher, McCombe ( 2 ) and Carson as the team achieved successive away wins for the first time in 2013 – 14. York went without scoring for a fourth consecutive home match after drawing 0 – 0 with Southend. Having worn the <unk> since an injury to McGurk, Penn was appointed captain for the rest of the season, a position that had earlier been held by Smith and Parslow. 
 
 = = = March = = = 
 
 York achieved their first home win in five matches after beating Exeter 2 – 1, with first half goals scored by McCombe and Coulson. Hayhurst's loan was extended to the end of the season, having impressed in his six appearances for the club. Coulson scored again with the only goal, a 41st @-@ minute header, in York's 1 – 0 away win over AFC Wimbledon. Bowman scored the only goal with a 32nd @-@ minute penalty as York won 1 – 0 away against Mansfield, in which Fletcher missed the opportunity to extend the lead when his stoppage time penalty was saved by Alan Marriott. York moved one place outside the play @-@ offs with a 2 – 0 home win over Wycombe, courtesy of a second Bowman penalty in as many matches and a Carson goal from the edge of the penalty area. Coulson scored York's only goal in a 1 – 0 away win over struggling Portsmouth with a low volley in the fifth @-@ minute ; this result meant York moved into the play @-@ offs in seventh @-@ place with eight fixtures remaining. 
 Striker Calvin Andrew, who had been released by Mansfield in January 2014, was signed on a contract for the remainder of the season. He made his debut as a substitute in York's 1 – 0 home win over bottom of the table Torquay, in which Hayhurst scored the only goal in the 11th @-@ minute with an 18 yard shot that <unk> off Aaron <unk>. Middlesbrough winger Brobbel rejoined on loan until the end of the season, following an injury to Carson. York's run of successive wins ended on six matches after a 0 – 0 home draw with Burton, and this result saw York drop out of the play @-@ offs in eighth @-@ place. With the team recording six wins and one draw in March 2014, including six clean sheets, Worthington was named League Two Manager of the Month. 
 
 = = = April = = = 
 
 Pope made a number of saves as York held league leaders Rochdale to a 0 – 0 away draw, with a point being enough to lift the team back into seventh @-@ place. York were prevented from equalling a club record of eight consecutive clean sheets when Accrington scored a stoppage time equaliser in a 1 – 1 home draw, in which York had taken earlier taken the lead with a Coulson penalty. A 1 – 0 win away win over Oxford, which was decided by a second half Coulson penalty, resulted in York moving one place above their opponents and back into seventh @-@ place. York consolidated their place in a play @-@ off position after beating Bury 1 – 0 at home with a fifth @-@ minute goal scored by Lowe from a Hayhurst corner. The result meant York opened up a five @-@ point lead over eighth @-@ placed Oxford with two fixtures remaining. A place in the League Two play @-@ offs was secured following a 1 – 0 win over Newport at home, in which Coulson scored the only goal in the 77th @-@ minute with a 25 yard free kick. Pope earned a nomination for League Two Player of the Month for April 2014, having conceded only one goal in five matches in that period. 
 
 = = = May = = = 
 
 The league season concluded with an away match against divisional runners @-@ up Scunthorpe ; having gone two goals down York fought back to draw 2 – 2 with goals scored by Brobbel and Andrew. This result meant York finished the season in seventh @-@ place in League Two, and would thus play fourth @-@ placed Fleetwood in the play @-@ off semi @-@ final on the back of a 17 @-@ match unbeaten run. York lost 1 – 0 to Fleetwood in the first leg at <unk> Crescent ; the goal came from former York player <unk> Blair in the 50th @-@ minute, who scored from close range after Antoni <unk>'s shot was blocked on the line. A 0 – 0 draw away to Fleetwood in the second leg meant York were eliminated 1 – 0 on aggregate, ending the prospect of a second promotion in three seasons. At an awards night held at York Racecourse, Oyebanjo was voted <unk> of the Year for 2013 – 14. 
 
 = = Summary and aftermath = = 
 
 York mostly occupied the bottom half of the table before the turn of the year, and dropped as low as 23rd in September 2013. During February 2014 the team broke into the top half of the table and with one match left were in sixth @-@ place. York's defensive record was the third best in League Two with 41 goals conceded, bettered only by Southend ( 39 ) and Chesterfield ( 40 ). Davies made the highest number of appearances over the season, appearing in 47 of York's 52 matches. Fletcher was York's top scorer in the league and in all competitions, with 10 league goals and 13 in total. He was the only player to reach double figures, and was followed by Jarvis with nine goals. 
 After the season ended York released Tom Allan, Andrew, Dickinson, McDonald, Puri and Reed, while McGurk retired from professional football. Bowman and Oyebanjo left to sign for Torquay and Crawley Town respectively while Coulson signed a new contract with the club. York's summer signings included goalkeeper Jason <unk> from Tranmere Rovers, defenders <unk> <unk> from Dagenham, Marvin McCoy from Wycombe and Dave Winfield from Shrewsbury Town, midfielders <unk> <unk> from Mansfield, Anthony <unk> from Southend and Luke <unk> from Shrewsbury and striker Jake Hyde from <unk>. 
 
 = = Match details = = 
 
 League positions are sourced by <unk>, while the remaining information is referenced individually. 
 
 = = = Football League Two = = = 
 
 
 = = = League table ( part ) = = = 
 
 
 = = = FA Cup = = = 
 
 
 = = = League Cup = = = 
 
 
 = = = Football League Trophy = = = 
 
 
 = = = Football League Two play @-@ offs = = = 
 
 
 = = <unk> = = 
 
 
 = = = In = = = 
 
 <unk> around club names denote the player's contract with that club had expired before he joined York. 
 
 = = = Out = = = 
 
 <unk> around club names denote the player joined that club after his York contract expired. 
 
 = = = Loan in = = = 
 
 
 = = = Loan out = = = 
 
 
 = = Appearances and goals = = 
 
 Source : 
 Numbers in parentheses denote appearances as substitute. 
 Players with names struck through and marked left the club during the playing season. 
 Players with names in italics and marked * were on loan from another club for the whole of their season with York. 
 Players listed with no appearances have been in the <unk> squad but only as unused <unk>. 
 Key to positions : <unk> – <unk> ; <unk> – Defender ; <unk> – <unk> ; <unk> – Forward 
 

show_at(tls.valid, 0)
 
 = Tropical Storm <unk> ( 2008 ) = 
 
 Tropical Storm <unk> was the tenth tropical storm of the 2008 Atlantic hurricane season. <unk> developed out of a strong tropical wave which moved off the African coast on August 31. The wave quickly became organized and was declared Tropical Depression Ten while located 170 mi ( 270 km ) to the south @-@ southeast of the Cape Verde Islands on September 2. The depression was quickly upgraded to Tropical Storm <unk> around noon the same day. Over the next several days, <unk> moved in a general west @-@ northwest direction and reached its peak intensity early on September 3. Strong wind shear, some due to the outflow of Hurricane Ike, and dry air caused the storm to weaken. On September 6, the combination of wind shear, dry air, and cooling waters caused <unk> to weaken into a tropical depression. <unk> deteriorated into a remnant low shortly after as convection continued to dissipate around the storm. The low ultimately dissipated while located 520 mi ( 835 km ) east of <unk> on September 10. However, the remnant moisture led to minor flooding on the island of St. Croix. 
 
 = = Meteorological history = = 
 
 Tropical Storm <unk> formed as a tropical wave that emerged off the west coast of Africa near the end of August 2008. It tracked south of Cape Verde and slowly developed, and on September 2 the disturbance became Tropical Depression Ten while located south @-@ southeast of the Cape Verde islands. As the depression became more organized, an eye @-@ like feature developed in the upper levels of the system. The depression was upgraded to Tropical Storm <unk> six hours after forming. <unk> was located in an area which was supportive for rapid intensification but was not forecast to intensify quickly. 
 <unk> continued to intensify throughout the afternoon as the storm became more symmetrical. However, due to the location of the storm, there was a lack of accurate wind speed readings, and the National Hurricane Center was uncertain of its actual intensity. Despite the lack of wind shear around the storm, the center became slightly exposed and ceased further intensification. The storm was also heading into an area where shear was <unk> to significantly increase due to an upper @-@ level trough diving southward. Despite convection being partially removed from the center of <unk>, the storm intensified slightly in the early morning hours on September 3 as thunderstorm activity to the south of the center became more organized. The intensification was forecast to be short in duration as the trough to the north was deepening, causing the wind shear to the west to become stronger. 
 <unk> reached its peak intensity of 65 mph ( 100 km / h ) around 8 a.m. ( <unk> ) as it continued to become more organized. However, there were indications that it had already begun to weaken. <unk> towards the north was becoming restricted and arc clouds began emanating from the storm, a sign that dry air was entering the system. During the afternoon hours, the structure of <unk> began to rapidly deteriorate as strong wind shear and dry air took their toll. By the late night, the center was almost completely exposed and only a band of convection persisted near the center. 
 Despite continuing effects from the strong wind shear, a large, deep burst of convection formed in the northern <unk> of <unk>. The center was found to have shifted towards the new convection leading to an increase in intensity. The forecast showed a slight decrease in wind shear as <unk> continued westward and no change in intensity over the 5 @-@ day forecast was predicted. However, the convection decreased once more and the low became completely exposed by the late morning hours and <unk> weakened again. By the afternoon, the center of <unk> was only a <unk> of clouds, devoid of convection. During the overnight hours on September 4 into the morning of September 5, convection associated with <unk> began to <unk> somewhat, mostly to the north of the circulation, due to the strong <unk> wind shear. By mid @-@ morning, <unk> re @-@ intensified slightly due to the redevelopment of some convection. However, the redevelopment was short lived and wind shear again took its toll on <unk> by late morning. The convection around the system became <unk> from the center and <unk> weakened slightly. 
 The weakening trend continued through the afternoon as the storm was being affected by strong <unk> shear. <unk> became almost fully devoid of any convection by mid @-@ afternoon and the storm weakened to 40 mph ( 65 km / h ), barely holding on to tropical storm status. <unk> regained a small amount of convection in the late night hours, but not enough to still be classified a tropical storm. Due to the lack of convection, <unk> was downgraded to a Tropical Depression at <unk> ( <unk> ) with winds of 35 mph ( 55 km / h ). Since there was no convection around the system, it would have normally been classified a remnant low but, due to the possibility of the storm <unk> over the next several days, it was considered a tropical depression. The next morning, <unk> was downgraded to a remnant low as strong wind shear and dry air caused the demise of the storm. No redevelopment was expected with <unk> as it began to move over colder waters and remain under strong wind shear until it dissipated. 
 However, the remnant low associated with <unk> began to show signs of redevelopment during the afternoon on September 7. <unk> around the system increased significantly and the low was no longer exposed. On September 8, wind shear took over the system again. <unk> around the remnant low was torn away and the low was exposed once more. The National Hurricane Center did not state the chance of regeneration once the low became exposed. Finally, on September 9, wind shear and dry air led to the remnants of <unk> deteriorating into an open wave. However, on September 10, the remnants of <unk> redeveloped and global models picked up on the reformed system. Once more, the chance of regeneration was possible as the remnants of <unk> headed towards the Bahamas. However, on September 14, dry air and wind shear caused the remnants to dissipate entirely. 
 
 = = Impact = = 
 
 As <unk> passed to the south of the Cape Verde islands on September 2, outer rain bands produced minor rainfall, totaling around 0 @.@ 55 inches ( 14 mm ). There were no reports of damage or flooding from the rain and overall effects were minor. 
 Several days after the low dissipated, the remnant moisture from <unk> brought showers and thunderstorms to St. Croix where up to 1 in ( 25 @.@ 4 mm ) of rain fell. The heavy rains led to minor street flooding and some urban flooding. No known damage was caused by the flood. 
 

The fastai library expects the data to be assembled in a DataLoaders object (something that has a training and validation dataloader). We can get one by using the dataloaders method. We just have to specify a batch size and a sequence length. Since the GPT2 model was trained with sequences of size 1024, we use this sequence length (it's a stateless model, so it will change the perplexity if we use less):

bs,sl = 8,1024
dls = tls.dataloaders(bs=bs, seq_len=sl)

Note that you may have to reduce the batch size depending on your GPU RAM.

In fastai, as soo as we have a DataLoaders, we can use show_batch to have a look at the data (here texts for inputs, and the same text shifted by one token to the right for validation):

dls.show_batch(max_n=5)
text text_
0 \n = History of artificial intelligence = \n \n The history of artificial intelligence ( AI ) began in antiquity, with myths, stories and rumors of artificial beings endowed with intelligence or consciousness by master craftsmen ; as Pamela McCorduck writes, AI began with " an ancient wish to forge the gods. " \n The seeds of modern AI were planted by classical philosophers who attempted to describe the process of human thinking as the mechanical manipulation of symbols. This work culminated in the invention of the programmable digital computer in the 1940s, a machine based on the abstract essence of mathematical reasoning. This device and the ideas behind it inspired a handful of scientists to begin seriously discussing the possibility of building an electronic brain. \n The Turing test was proposed by British mathematician Alan Turing in his 1950 paper Computing Machinery and Intelligence, which opens with the \n = History of artificial intelligence = \n \n The history of artificial intelligence ( AI ) began in antiquity, with myths, stories and rumors of artificial beings endowed with intelligence or consciousness by master craftsmen ; as Pamela McCorduck writes, AI began with " an ancient wish to forge the gods. " \n The seeds of modern AI were planted by classical philosophers who attempted to describe the process of human thinking as the mechanical manipulation of symbols. This work culminated in the invention of the programmable digital computer in the 1940s, a machine based on the abstract essence of mathematical reasoning. This device and the ideas behind it inspired a handful of scientists to begin seriously discussing the possibility of building an electronic brain. \n The Turing test was proposed by British mathematician Alan Turing in his 1950 paper Computing Machinery and Intelligence, which opens with the words
1 och from <unk> in Orkney, which has a Pictish @-@ style looped pin. It is about two inches in diameter, with traces of <unk>, and probably housed a piece of amber surrounded by <unk> ribbons. After the conversion to Christianity, from the tenth to the twelfth centuries, stone crosses and cross @-@ slabs in Viking occupied areas of the Highlands and Islands were carved with successive styles of Viking ornament. They were frequently mixed with native interlace and animal patterns. Examples include the eleventh @-@ century cross @-@ slab from <unk> <unk> on the island of Islay, where the plant motifs on either side of the cross @-@ shaft are based upon the <unk> style of Viking art. The most famous artistic find from modern Scotland, the Lewis <unk>, from Uig, were probably made in Trondheim in Norway, but contain some decoration that may have been influenced by Celtic patterns. from <unk> in Orkney, which has a Pictish @-@ style looped pin. It is about two inches in diameter, with traces of <unk>, and probably housed a piece of amber surrounded by <unk> ribbons. After the conversion to Christianity, from the tenth to the twelfth centuries, stone crosses and cross @-@ slabs in Viking occupied areas of the Highlands and Islands were carved with successive styles of Viking ornament. They were frequently mixed with native interlace and animal patterns. Examples include the eleventh @-@ century cross @-@ slab from <unk> <unk> on the island of Islay, where the plant motifs on either side of the cross @-@ shaft are based upon the <unk> style of Viking art. The most famous artistic find from modern Scotland, the Lewis <unk>, from Uig, were probably made in Trondheim in Norway, but contain some decoration that may have been influenced by Celtic patterns.
2 @ match unbeaten run saw the team finish in seventh @-@ place in the 24 @-@ team 2013 – 14 Football League Two. This meant York qualified for the play @-@ offs, and they were eliminated in the semi @-@ final by Fleetwood Town. York were knocked out of the 2013 – 14 FA Cup, Football League Cup and Football League Trophy in their opening round matches. \n 35 players made at least one appearance in nationally organised first @-@ team competition, and there were 12 different <unk>. Defender Ben Davies missed only five of the fifty @-@ two competitive matches played over the season. Wes Fletcher finished as leading scorer with 13 goals, of which 10 came in league competition and three came in the FA Cup. The winner of the <unk> of the Year award, voted for by the club's supporters, was <unk> Oyebanjo. \n \n = = match unbeaten run saw the team finish in seventh @-@ place in the 24 @-@ team 2013 – 14 Football League Two. This meant York qualified for the play @-@ offs, and they were eliminated in the semi @-@ final by Fleetwood Town. York were knocked out of the 2013 – 14 FA Cup, Football League Cup and Football League Trophy in their opening round matches. \n 35 players made at least one appearance in nationally organised first @-@ team competition, and there were 12 different <unk>. Defender Ben Davies missed only five of the fifty @-@ two competitive matches played over the season. Wes Fletcher finished as leading scorer with 13 goals, of which 10 came in league competition and three came in the FA Cup. The winner of the <unk> of the Year award, voted for by the club's supporters, was <unk> Oyebanjo. \n \n = =
3 more likely to be found in areas that were heavily burned, compared to locations with light to moderate burning where the trees remained viable, or in <unk> areas. <unk> was much denser in spruce forests — with up to 700 – 1000 fruitbodies per square meter — than in pine forests, where fruitbodies were sporadic. Fruitbodies grew by the millions in the year following the Yellowstone fires of 1988. \n \n \n = Tropical Storm Domoina = \n \n Severe Tropical Storm Domoina in 1984 caused 100 year floods in South Africa and record rainfall in Swaziland. The fourth named storm of the season, Domoina developed on January 16 off the northeast coast of Madagascar. With a ridge to the north, the storm tracked generally westward and later southwestward. On January 21, Domoina struck eastern Madagascar, the third storm in six weeks to affect the nation ; collectively, the likely to be found in areas that were heavily burned, compared to locations with light to moderate burning where the trees remained viable, or in <unk> areas. <unk> was much denser in spruce forests — with up to 700 – 1000 fruitbodies per square meter — than in pine forests, where fruitbodies were sporadic. Fruitbodies grew by the millions in the year following the Yellowstone fires of 1988. \n \n \n = Tropical Storm Domoina = \n \n Severe Tropical Storm Domoina in 1984 caused 100 year floods in South Africa and record rainfall in Swaziland. The fourth named storm of the season, Domoina developed on January 16 off the northeast coast of Madagascar. With a ridge to the north, the storm tracked generally westward and later southwestward. On January 21, Domoina struck eastern Madagascar, the third storm in six weeks to affect the nation ; collectively, the storms
4 = = = \n \n The degree to which Tennyson identifies with Ulysses has provided one of the great debates among scholars of the poem. Critics who find that Tennyson identifies with the speaker read Ulysses'speech " <unk> ", or without irony. Many other interpretations of the poem have developed from the argument that Tennyson does not identify with Ulysses, and further criticism has suggested that the purported inconsistencies in Ulysses'character are the fault of the poet himself. \n Key to the <unk> reading of " Ulysses " is the biographical context of the poem. Such a reading takes into account Tennyson's statements about writing the poem — " the need of going forward " — and considers that he would not undermine Ulysses'determination with irony when he needed a similar <unk> to face life after Hallam's death. Ulysses is thus seen as an heroic character whose determination to = = \n \n The degree to which Tennyson identifies with Ulysses has provided one of the great debates among scholars of the poem. Critics who find that Tennyson identifies with the speaker read Ulysses'speech " <unk> ", or without irony. Many other interpretations of the poem have developed from the argument that Tennyson does not identify with Ulysses, and further criticism has suggested that the purported inconsistencies in Ulysses'character are the fault of the poet himself. \n Key to the <unk> reading of " Ulysses " is the biographical context of the poem. Such a reading takes into account Tennyson's statements about writing the poem — " the need of going forward " — and considers that he would not undermine Ulysses'determination with irony when he needed a similar <unk> to face life after Hallam's death. Ulysses is thus seen as an heroic character whose determination to seek

Another way to gather the data is to preprocess the texts once and for all and only use the transform to decode the tensors to texts:

def tokenize(text):
    toks = tokenizer.tokenize(text)
    return tensor(tokenizer.convert_tokens_to_ids(toks))

tokenized = [tokenize(t) for t in progress_bar(all_texts)]
100.00% [662/662 00:05<00:00]

Now we change the previous Tokenizer like this:

class TransformersTokenizer(Transform):
    def __init__(self, tokenizer): self.tokenizer = tokenizer
    def encodes(self, x): 
        return x if isinstance(x, Tensor) else tokenize(x)
        
    def decodes(self, x): return TitledStr(self.tokenizer.decode(x.cpu().numpy()))

In the encodes method, we still account for the case where we get something that's not already tokenized, just in case we were to build a dataset with new texts using this transform.

tls = TfmdLists(tokenized, TransformersTokenizer(tokenizer), splits=splits, dl_type=LMDataLoader)
dls = tls.dataloaders(bs=bs, seq_len=sl)

And we can check it still works properly for showing purposes:

dls.show_batch(max_n=5)
text text_
0 \n = Architecture of the Song dynasty = \n \n The architecture of the Song dynasty ( 960 – 1279 ) was noted for its towering Buddhist pagodas, enormous stone and wooden bridges, lavish tombs, and extravagant palaces. Although literary works on architecture existed beforehand, architectural writing <unk> during the Song dynasty, <unk> into a more professional form that described dimensions and working materials in a <unk>, organized manner. In addition to the examples still standing, depictions in Song artwork, architectural drawings, and illustrations in published books all aid modern historians in understanding the architecture of the period. \n The professions of architect, master craftsman, carpenter, and structural engineer did not have the high status of the Confucian scholar @-@ officials during the dynastic era. Architectural knowledge had been passed down orally for thousands of years, usually from craftsman fathers to their sons. There were also government agencies and \n = Architecture of the Song dynasty = \n \n The architecture of the Song dynasty ( 960 – 1279 ) was noted for its towering Buddhist pagodas, enormous stone and wooden bridges, lavish tombs, and extravagant palaces. Although literary works on architecture existed beforehand, architectural writing <unk> during the Song dynasty, <unk> into a more professional form that described dimensions and working materials in a <unk>, organized manner. In addition to the examples still standing, depictions in Song artwork, architectural drawings, and illustrations in published books all aid modern historians in understanding the architecture of the period. \n The professions of architect, master craftsman, carpenter, and structural engineer did not have the high status of the Confucian scholar @-@ officials during the dynastic era. Architectural knowledge had been passed down orally for thousands of years, usually from craftsman fathers to their sons. There were also government agencies and schools
1 africanus. Several years later, Nopcsa, unaware of Broom's new name, similarly concluded that it represented a new taxon, and named the binomial Paranthodon owenii. However, since the Nopcsa's species name was assigned after Broom's, and Broom did not assign a new genus, both names are now synonyms under the current naming, Paranthodon africanus. The genus name was chosen from the Ancient Greek para, " near " and Anthodon, for the originally proposed similarity of the specimens. \n In identifying the remains as those of Palaeoscincus, Broom basically classified Paranthodon as an ankylosaurian, a statement backed by the research of Coombs. Nopcsa however, identified the genus as a stegosaurid, which most modern studies agree with. In 1981, the genus was reviewed, and found to be a valid genus of stegosaurid. Paranthodon is one of a few genera found in the Kirkwood Formation ; other such taxa include theropods, like <unk> ricanus. Several years later, Nopcsa, unaware of Broom's new name, similarly concluded that it represented a new taxon, and named the binomial Paranthodon owenii. However, since the Nopcsa's species name was assigned after Broom's, and Broom did not assign a new genus, both names are now synonyms under the current naming, Paranthodon africanus. The genus name was chosen from the Ancient Greek para, " near " and Anthodon, for the originally proposed similarity of the specimens. \n In identifying the remains as those of Palaeoscincus, Broom basically classified Paranthodon as an ankylosaurian, a statement backed by the research of Coombs. Nopcsa however, identified the genus as a stegosaurid, which most modern studies agree with. In 1981, the genus was reviewed, and found to be a valid genus of stegosaurid. Paranthodon is one of a few genera found in the Kirkwood Formation ; other such taxa include theropods, like <unk> ;
2 -@ bones indicate it had reduced flight capabilities, a feature perhaps linked to seasonal <unk>. The diet of the Réunion ibis was worms and other items <unk> from soil. It preferred solitude ( hence the name " solitaire " ). In the 17th century, it lived in mountainous areas, but it may have been confined to these remote heights by heavy hunting by humans and predation by introduced animals in the more accessible areas of the island. <unk> to Réunion praised its flavour, and therefore sought after its flesh. These factors are believed to have driven the Réunion ibis to extinction by the early 18th century. \n \n = = Taxonomy = = \n \n The taxonomic history of the Réunion ibis is <unk> and complex, due to the ambiguous and <unk> evidence that was available to scientists until recently. The supposed " white dodo " of Réunion is now @ bones indicate it had reduced flight capabilities, a feature perhaps linked to seasonal <unk>. The diet of the Réunion ibis was worms and other items <unk> from soil. It preferred solitude ( hence the name " solitaire " ). In the 17th century, it lived in mountainous areas, but it may have been confined to these remote heights by heavy hunting by humans and predation by introduced animals in the more accessible areas of the island. <unk> to Réunion praised its flavour, and therefore sought after its flesh. These factors are believed to have driven the Réunion ibis to extinction by the early 18th century. \n \n = = Taxonomy = = \n \n The taxonomic history of the Réunion ibis is <unk> and complex, due to the ambiguous and <unk> evidence that was available to scientists until recently. The supposed " white dodo " of Réunion is now
3 unk> ) is an ancient place of worship dedicated to Eshmun, the Phoenician god of healing. It is located near the Awali river, 2 kilometres ( 1 @.@ 2 mi ) northeast of Sidon in southwestern Lebanon. The site was occupied from the 7th century BC to the 8th century AD, suggesting an integrated relationship with the nearby city of Sidon. Although originally constructed by Sidonian king Eshmunazar II in the Achaemenid era ( c. 529 – 333 BC ) to celebrate the city's recovered wealth and stature, the temple complex was greatly expanded by Bodashtart, <unk> @-@ milk and later monarchs. Because the continued expansion spanned many centuries of alternating independence and foreign <unk>, the sanctuary features a wealth of different architectural and decorative styles and influences. \n The sanctuary consists of an esplanade and a grand court limited by a huge limestone terrace wall that supports a monumental > ) is an ancient place of worship dedicated to Eshmun, the Phoenician god of healing. It is located near the Awali river, 2 kilometres ( 1 @.@ 2 mi ) northeast of Sidon in southwestern Lebanon. The site was occupied from the 7th century BC to the 8th century AD, suggesting an integrated relationship with the nearby city of Sidon. Although originally constructed by Sidonian king Eshmunazar II in the Achaemenid era ( c. 529 – 333 BC ) to celebrate the city's recovered wealth and stature, the temple complex was greatly expanded by Bodashtart, <unk> @-@ milk and later monarchs. Because the continued expansion spanned many centuries of alternating independence and foreign <unk>, the sanctuary features a wealth of different architectural and decorative styles and influences. \n The sanctuary consists of an esplanade and a grand court limited by a huge limestone terrace wall that supports a monumental
4 Middle Eastern music. The final Strapping Young Lad album, The New Black, was released later in 2006. \n \n = = = Ziltoid the Omniscient and hiatus ( 2006 – 2008 ) = = = \n \n Townsend withdrew from touring to spend time with his family. From home, Townsend completed his second solo ambient album, The <unk>, releasing it exclusively on his website in November 2006. \n In May 2007, Townsend released Ziltoid the Omniscient, a tongue @-@ in @-@ cheek rock opera about the eponymous fictional alien. This was truly a solo album ; he programmed the drums using <unk> from Hell, a software drum machine that uses samples recorded by Tomas <unk> of Meshuggah and played all other instruments himself. Shortly after the album's release, Townsend announced that he no longer planned to tour or make albums with Strapping Young Lad or the Devin Townsend Band. Eastern music. The final Strapping Young Lad album, The New Black, was released later in 2006. \n \n = = = Ziltoid the Omniscient and hiatus ( 2006 – 2008 ) = = = \n \n Townsend withdrew from touring to spend time with his family. From home, Townsend completed his second solo ambient album, The <unk>, releasing it exclusively on his website in November 2006. \n In May 2007, Townsend released Ziltoid the Omniscient, a tongue @-@ in @-@ cheek rock opera about the eponymous fictional alien. This was truly a solo album ; he programmed the drums using <unk> from Hell, a software drum machine that uses samples recorded by Tomas <unk> of Meshuggah and played all other instruments himself. Shortly after the album's release, Townsend announced that he no longer planned to tour or make albums with Strapping Young Lad or the Devin Townsend Band. He

Fine-tuning the model

The HuggingFace model will return a tuple in outputs, with the actual predictions and some additional activations (should we want to use them is some regularization scheme). To work inside the fastai training loop, we will need to drop those using a Callback: we use those to alter the behavior of the training loop.

Here we need to write the event after_pred and replace self.learn.pred (which contains the predictions that will be passed to the loss function) by just its first element. In callbacks, there is a shortcut that lets you access any of the underlying Learner attribute so we can write self.pred[0] instead of self.learn.pred[0]. That shorcut only works for read access, not write, so we have to write self.learn.pred on the right side (otherwise we would set a pred attribute in the Callback).

class DropOutput(Callback):
    def after_pred(self): self.learn.pred = self.pred[0]

Of course we could make this a bit more complex and add some penalty to the loss using the other part of the tuple of predictions, like the RNNRegularizer.

Now, we are ready to create our Learner, which is a fastai object grouping data, model and loss function and handles model training or inference. Since we are in a language model setting, we pass perplexity as a metric, and we need to use the callback we just defined. Lastly, we use mixed precision to save every bit of memory we can (and if you have a modern GPU, it will also make training faster):

learn = Learner(dls, model, loss_func=CrossEntropyLossFlat(), cbs=[DropOutput], metrics=Perplexity()).to_fp16()

We can check how good the model is without any fine-tuning step (spoiler alert, it's pretty good!)

learn.validate()
(#2) [3.2440035343170166,25.636152267456055]

This lists comport the validation loss and metrics (so 26.6 as perplexity is kind of amazing).

Now that we have a Learner we can use all the fastai training loop capabilities: learning rate finder, training with 1cycle etc...

learn.lr_find()
SuggestedLRs(lr_min=0.00831763744354248, lr_steep=0.0691830962896347)

The learning rate finder curve suggests picking something between 1e-4 and 1e-3.

learn.fit_one_cycle(1, 1e-4)
epoch train_loss valid_loss perplexity time
0 3.646031 3.244000 25.636072 02:44

Now with just one epoch of fine-tuning and not much regularization, our model did not really improve since it was already amazing. To have a look at some generated texts, let's take a prompt that looks like a wikipedia article:

df_valid.head(1)
0
0 \n = Tropical Storm <unk> ( 2008 ) = \n \n Tropical Storm <unk> was the tenth tropical storm of the 2008 Atlantic hurricane season . <unk> developed out of a strong tropical wave which moved off the African coast on August 31 . The wave quickly became organized and was declared Tropical Depression Ten while located 170 mi ( 270 km ) to the south @-@ southeast of the Cape Verde Islands on September 2 . The depression was quickly upgraded to Tropical Storm <unk> around noon the same day . Over the next several days , <unk> moved in a general west @-@ northwest direction and reached its peak...

Article seems to begin with new line and the title between = signs, so we will mimic that:

prompt = "\n = Unicorn = \n \n A unicorn is a magical creature with a rainbow tail and a horn"

The prompt needs to be tokenized and numericalized, so we use the same function as before to do this, before we use the generate method of the model.

prompt_ids = tokenizer.encode(prompt)
inp = tensor(prompt_ids)[None].cuda()
inp.shape
torch.Size([1, 21])
preds = learn.model.generate(inp, max_length=40, num_beams=5, temperature=1.5)
Setting `pad_token_id` to 50256 (first `eos_token_id`) to generate sequence
tokenizer.decode(preds[0])
'\n = Unicorn = \n \n A unicorn is a magical creature with a rainbow tail and a horn on its head.\n\nA unicorn can fly at speeds of up to 100 miles per hour'