--- title: modeling.token_classification keywords: fastai sidebar: home_sidebar summary: "This module contains custom models, loss functions, custom splitters, etc... for token classification tasks like named entity recognition." description: "This module contains custom models, loss functions, custom splitters, etc... for token classification tasks like named entity recognition." nb_path: "nbs/02a_modeling-token-classification.ipynb" ---
{% raw %}
{% endraw %} {% raw %}
{% endraw %} {% raw %}
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
{% endraw %}

Token classification

The objective of token classification is to predict the correct label for each token provided in the input. In the computer vision world, this is akin to what we do in segmentation tasks whereby we attempt to predict the class/label for each pixel in an image. Named entity recognition (NER) is an example of token classification in the NLP space

{% raw %}
df_converters = {'tokens': ast.literal_eval, 'labels': ast.literal_eval, 'nested-labels': ast.literal_eval}

# full nlp dataset
# germ_eval_df = pd.read_csv('./data/task-token-classification/germeval2014ner_cleaned.csv', converters=df_converters)

# demo nlp dataset
germ_eval_df = pd.read_csv('./germeval2014_sample.csv', converters=df_converters)

print(len(germ_eval_df))
germ_eval_df.head()
1000
id source tokens labels nested-labels ds_type
0 0 n-tv.de vom 26.02.2005 [2005-02-26] [Schartau, sagte, dem, ", Tagesspiegel, ", vom, Freitag, ,, Fischer, sei, ", in, einer, Weise, aufgetreten, ,, die, alles, andere, als, überzeugend, war, ", .] [B-PER, O, O, O, B-ORG, O, O, O, O, B-PER, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O] [O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O] train
1 1 welt.de vom 29.10.2005 [2005-10-29] [Firmengründer, Wolf, Peter, Bree, arbeitete, Anfang, der, siebziger, Jahre, als, Möbelvertreter, ,, als, er, einen, fliegenden, Händler, aus, dem, Libanon, traf, .] [O, B-PER, I-PER, I-PER, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, B-LOC, O, O] [O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O] train
2 2 http://www.stern.de/sport/fussball/krawalle-in-der-fussball-bundesliga-dfb-setzt-auf-falsche-konzepte-1553657.html#utm_source=standard&utm_medium=rss-feed&utm_campaign=sport [2010-03-25] [Ob, sie, dabei, nach, dem, Runden, Tisch, am, 23., April, in, Berlin, durch, ein, pädagogisches, Konzept, unterstützt, wird, ,, ist, allerdings, zu, bezweifeln, .] [O, O, O, O, O, O, O, O, O, O, O, B-LOC, O, O, O, O, O, O, O, O, O, O, O, O] [O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O] train
3 3 stern.de vom 21.03.2006 [2006-03-21] [Bayern, München, ist, wieder, alleiniger, Top-, Favorit, auf, den, Gewinn, der, deutschen, Fußball-Meisterschaft, .] [B-ORG, I-ORG, O, O, O, O, O, O, O, O, O, B-LOCderiv, O, O] [B-LOC, B-LOC, O, O, O, O, O, O, O, O, O, O, O, O] train
4 4 http://www.fr-online.de/in_und_ausland/sport/aktuell/1618625_Frings-schaut-finster-in-die-Zukunft.html [2008-10-24] [Dabei, hätte, der, tapfere, Schlussmann, allen, Grund, gehabt, ,, sich, viel, früher, aufzuregen, .] [O, O, O, O, O, O, O, O, O, O, O, O, O, O] [O, O, O, O, O, O, O, O, O, O, O, O, O, O] train
{% endraw %}

We are only going to be working with small sample from the GermEval 2014 data set ... so the results might not be all that great :).

{% raw %}
labels = sorted(list(set([lbls for sublist in germ_eval_df.labels.tolist() for lbls in sublist])))
print(labels)
['B-LOC', 'B-LOCderiv', 'B-LOCpart', 'B-ORG', 'B-ORGpart', 'B-OTH', 'B-OTHderiv', 'B-OTHpart', 'B-PER', 'B-PERderiv', 'B-PERpart', 'I-LOC', 'I-LOCderiv', 'I-ORG', 'I-ORGpart', 'I-OTH', 'I-PER', 'O']
{% endraw %} {% raw %}
task = HF_TASKS_AUTO.TokenClassification
pretrained_model_name = "bert-base-multilingual-cased"
config = AutoConfig.from_pretrained(pretrained_model_name)

config.num_labels = len(labels)
{% endraw %}

Notice above how I set the config.num_labels attribute to the number of labels we want our model to be able to predict. The model will update its last layer accordingly (this concept is essentially transfer learning).

{% raw %}
hf_arch, hf_config, hf_tokenizer, hf_model = BLURR_MODEL_HELPER.get_hf_objects(pretrained_model_name, 
                                                                               task=task, 
                                                                               config=config)
hf_arch, type(hf_config), type(hf_tokenizer), type(hf_model)
('bert',
 transformers.models.bert.configuration_bert.BertConfig,
 transformers.models.bert.tokenization_bert_fast.BertTokenizerFast,
 transformers.models.bert.modeling_bert.BertForTokenClassification)
{% endraw %} {% raw %}
test_eq(hf_config.num_labels, len(labels))
{% endraw %} {% raw %}
before_batch_tfm = HF_TokenClassBeforeBatchTransform(hf_arch, hf_config, hf_tokenizer, hf_model,
                                                     is_split_into_words=True, 
                                                     tok_kwargs={ 'return_special_tokens_mask': True })

blocks = (
    HF_TextBlock(before_batch_tfm=before_batch_tfm, input_return_type=HF_TokenClassInput), 
    HF_TokenCategoryBlock(vocab=labels)
)

def get_y(inp):
    return [ (label, len(hf_tokenizer.tokenize(str(entity)))) for entity, label in zip(inp.tokens, inp.labels) ]

dblock = DataBlock(blocks=blocks, 
                   get_x=ColReader('tokens'),
                   get_y=get_y,
                   splitter=RandomSplitter())
{% endraw %}

We have to define a get_y that creates the same number of labels as there are subtokens for a particular token. For example, my name "Wayde" gets split up into two subtokens, "Way" and "##de". The label for "Wayde" is "B-PER" and we just repeat it for the subtokens. This all get cleaned up when we show results and get predictions.

{% raw %}
dls = dblock.dataloaders(germ_eval_df, bs=2)
{% endraw %} {% raw %}
dls.show_batch(dataloaders=dls, max_n=2)
token / target label
0 [('(', 'O'), ('Standard', 'B-ORG'), ('Oil', 'I-ORG'), ('of', 'I-ORG'), ('New', 'I-ORG'), ('Jersey', 'I-ORG'), ('),', 'O'), ('die', 'O'), ('ausgesprochen', 'O'), ('„', 'O'), ('Esso', 'O'), ('ergeben', 'B-ORG'), ('(', 'O'), ('heute', 'O'), ('ExxonMobil', 'O'), (').', 'O'), (';', 'B-ORG'), ('Exxon', 'O'), (':', 'O'), ('Ein', 'O'), ('Name,', 'B-ORG'), ('der', 'O'), ('in', 'O'), ('den', 'O'), ('frühen', 'O'), ('1970ern', 'O'), ('von', 'O'), ('Esso', 'O'), ('erfunden', 'O'), ('wurde,', 'O'), ('um', 'O'), ('ein', 'B-ORG'), ('neutrales', 'O'), ('aber', 'O'), ('eindeutiges', 'O'), ('Markenzeichen', 'O'), ('für', 'O'), ('das', 'O'), ('Unternehmen', 'O'), ('zu', 'O'), ('haben.', 'O')]
1 [('12', 'O'), (':', 'O'), ('25', 'B-LOC'), ('Uhr', 'O'), ('Berlin', 'B-ORG'), ('(', 'O'), ('dpa', 'O'), (')', 'O'), ('-', 'O'), ('Die', 'O'), ('Zahl', 'O'), ('der', 'O'), ('Anbieter', 'O'), ('von', 'O'), ('neuartigen', 'O'), ('Software', 'O'), ('-', 'O'), ('und', 'O'), ('Service', 'O'), ('-', 'O'), ('Angeboten', 'O'), ('über', 'O'), ('das', 'O'), ('Internet', 'O'), ('wird', 'B-PER'), ('sich', 'I-PER'), ('nach', 'O'), ('Einschätzung', 'O'), ('von', 'O'), ('Brad', 'B-ORG'), ('Smith,', 'O'), ('Chef', 'O'), ('-', 'O'), ('Justiziar', 'O'), ('von', 'O'), ('Microsoft,', 'O'), ('vorerst', 'O'), ('auf', 'O')]
{% endraw %}

Metrics

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

{% raw %}

calculate_token_class_metrics[source]

calculate_token_class_metrics(pred_toks, targ_toks, metric_key)

{% endraw %} {% raw %}
{% endraw %}

Training

{% raw %}
 
{% endraw %} {% raw %}
 
{% endraw %} {% raw %}
 
{% endraw %} {% raw %}
 
{% endraw %} {% raw %}
 
{% endraw %} {% raw %}

class HF_TokenClassMetricsCallback[source]

HF_TokenClassMetricsCallback(tok_metrics=['accuracy', 'precision', 'recall', 'f1'], **kwargs) :: Callback

A fastai friendly callback that includes accuracy, precision, recall, and f1 metrics using the seqeval library. Additionally, this metric knows how to not include your 'ignore_token' in it's calculations.

See here for more information on seqeval.

{% endraw %} {% raw %}
{% endraw %} {% raw %}
model = HF_BaseModelWrapper(hf_model)
learn_cbs = [HF_BaseModelCallback]
fit_cbs = [HF_TokenClassMetricsCallback()]

learn = Learner(dls, model,opt_func=partial(Adam),cbs=learn_cbs,splitter=hf_splitter)

learn.create_opt()             # -> will create your layer groups based on your "splitter" function
learn.freeze()
{% endraw %} {% raw %}
 
{% endraw %} {% raw %}
b = dls.one_batch()
preds = learn.model(b[0])
len(preds),preds[0].shape
(1, torch.Size([2, 62, 18]))
{% endraw %} {% raw %}
len(b), len(b[0]), b[0]['input_ids'].shape, len(b[1]), b[1].shape
(2, 3, torch.Size([2, 62]), 2, torch.Size([2, 62]))
{% endraw %} {% raw %}
print(preds[0].view(-1, preds[0].shape[-1]).shape, b[1].view(-1).shape)
test_eq(preds[0].view(-1, preds[0].shape[-1]).shape[0], b[1].view(-1).shape[0])
torch.Size([124, 18]) torch.Size([124])
{% endraw %} {% raw %}
print(len(learn.opt.param_groups))
3
{% endraw %} {% raw %}
learn.unfreeze()
learn.lr_find(suggestions=True)
SuggestedLRs(lr_min=0.0009120108559727668, lr_steep=5.248074739938602e-05)
{% endraw %} {% raw %}
learn.fit_one_cycle(3, lr_max= 3e-5, moms=(0.8,0.7,0.8), cbs=fit_cbs)
epoch train_loss valid_loss accuracy precision recall f1 time
0 0.191001 0.196042 0.946744 0.547009 0.488550 0.516129 00:37
1 0.151665 0.122821 0.964956 0.679487 0.700441 0.689805 00:37
2 0.046475 0.121095 0.969647 0.752137 0.724280 0.737945 00:36
/home/wgilliam/anaconda3/envs/blurr/lib/python3.7/site-packages/seqeval/metrics/v1.py:57: UndefinedMetricWarning: Recall and F-score are ill-defined and being set to 0.0 in labels with no true samples. Use `zero_division` parameter to control this behavior.
  _warn_prf(average, modifier, msg_start, len(result))
{% endraw %} {% raw %}
print(learn.token_classification_report)
              precision    recall  f1-score   support

         LOC       0.79      0.73      0.76        67
    LOCderiv       0.77      0.80      0.79        30
     LOCpart       0.00      0.00      0.00         0
         ORG       0.85      0.67      0.75        42
     ORGpart       0.43      0.75      0.55         4
         OTH       0.58      0.50      0.54        36
    OTHderiv       0.00      0.00      0.00         0
     OTHpart       0.00      0.00      0.00         0
         PER       0.95      0.84      0.89        64
    PERderiv       0.00      0.00      0.00         0
     PERpart       0.00      0.00      0.00         0

   micro avg       0.75      0.72      0.74       243
   macro avg       0.40      0.39      0.39       243
weighted avg       0.80      0.72      0.76       243

{% endraw %}

Showing results

Below we'll add in additional functionality to more intuitively show the results of our model.

{% raw %}
{% endraw %} {% raw %}
learn.show_results(learner=learn, max_n=2, trunc_at=10)
token / target label / predicted label
0 [('Helbig', 'B-OTH', 'O'), ('et', 'I-OTH', 'B-PER'), ('al.', 'I-OTH', 'I-PER'), ('(', 'O', 'I-PER'), ('1994', 'O', 'O'), (')', 'O', 'I-PER'), ('S.', 'O', 'O'), ('593.', 'O', 'O'), ('Wink', 'O', 'O'), ('&', 'B-OTH', 'O')]
1 [('Erstmals', 'O', 'O'), ('Urkundlich', 'O', 'O'), ('erwähnt', 'O', 'O'), ('ist', 'O', 'O'), ('Nimburg', 'B-LOC', 'O'), ('bereits', 'O', 'O'), ('im', 'O', 'O'), ('Jahre', 'O', 'B-PER'), ('977.', 'O', 'I-PER'), ('Im', 'O', 'O')]
{% endraw %} {% raw %}
res = learn.blurr_predict('My name is Wayde and I live in San Diego'.split())
print(res[0][0])
("['O', 'O', 'O', 'O', 'B-PER', 'B-PER', 'O', 'O', 'O', 'O', 'B-LOC', 'I-LOC', 'O']",)
{% endraw %}

The default Learner.predict method returns a prediction per subtoken, including the special tokens for each architecture's tokenizer.

{% raw %}
{% endraw %} {% raw %}
{% endraw %} {% raw %}

Learner.blurr_predict_tokens[source]

Learner.blurr_predict_tokens(items, **kargs)

{% endraw %} {% raw %}
txt ="Hi! My name is Wayde Gilliam from ohmeow.com. I live in California."
txt2 = "I wish covid was over so I could go to Germany and watch Bayern Munich play in the Bundesliga."
{% endraw %} {% raw %}
res = learn.blurr_predict_tokens(txt.split())
for r in res: print(f'{[(tok, lbl) for tok,lbl in zip(r[0],r[1]) ]}\n')
[('Hi!', 'O'), ('My', 'O'), ('name', 'O'), ('is', 'O'), ('Wayde', 'B-PER'), ('Gilliam', 'I-PER'), ('from', 'O'), ('ohmeow.com.', 'B-ORG'), ('I', 'O'), ('live', 'O'), ('in', 'O'), ('California.', 'B-LOC')]

{% endraw %} {% raw %}
res = learn.blurr_predict_tokens([txt.split(), txt2.split()])
for r in res: print(f'{[(tok, lbl) for tok,lbl in zip(r[0],r[1]) ]}\n')
[('Hi!', 'O'), ('My', 'O'), ('name', 'O'), ('is', 'O'), ('Wayde', 'B-PER'), ('Gilliam', 'I-PER'), ('from', 'O'), ('ohmeow.com.', 'B-ORG'), ('I', 'O'), ('live', 'O'), ('in', 'O'), ('California.', 'B-LOC')]

[('I', 'O'), ('wish', 'O'), ('covid', 'O'), ('was', 'O'), ('over', 'O'), ('so', 'O'), ('I', 'O'), ('could', 'O'), ('go', 'O'), ('to', 'O'), ('Germany', 'B-LOC'), ('and', 'O'), ('watch', 'O'), ('Bayern', 'B-ORG'), ('Munich', 'I-ORG'), ('play', 'O'), ('in', 'O'), ('the', 'O'), ('Bundesliga.', 'B-ORG')]

{% endraw %}

It's interesting (and very cool) how well this model performs on English even thought it was trained against a German corpus.

Inference

{% raw %}
export_fname = 'tok_class_learn_export'
{% endraw %} {% raw %}
learn.export(fname=f'{export_fname}.pkl')
inf_learn = load_learner(fname=f'{export_fname}.pkl')

res = learn.blurr_predict_tokens([txt.split(), txt2.split()])
for r in res: print(f'{[(tok, lbl) for tok,lbl in zip(r[0],r[1]) ]}\n')
[('Hi!', 'O'), ('My', 'O'), ('name', 'O'), ('is', 'O'), ('Wayde', 'B-PER'), ('Gilliam', 'I-PER'), ('from', 'O'), ('ohmeow.com.', 'B-ORG'), ('I', 'O'), ('live', 'O'), ('in', 'O'), ('California.', 'B-LOC')]

[('I', 'O'), ('wish', 'O'), ('covid', 'O'), ('was', 'O'), ('over', 'O'), ('so', 'O'), ('I', 'O'), ('could', 'O'), ('go', 'O'), ('to', 'O'), ('Germany', 'B-LOC'), ('and', 'O'), ('watch', 'O'), ('Bayern', 'B-ORG'), ('Munich', 'I-ORG'), ('play', 'O'), ('in', 'O'), ('the', 'O'), ('Bundesliga.', 'B-ORG')]

{% endraw %}

... and onnx

{% raw %}

blurrONNX.predict_tokens[source]

blurrONNX.predict_tokens(items, **kargs)

{% endraw %} {% raw %}
{% endraw %} {% raw %}
learn.blurr_to_onnx(export_fname, quantize=True)
/home/wgilliam/anaconda3/envs/blurr/lib/python3.7/site-packages/transformers/models/bert/modeling_bert.py:192: TracerWarning: Converting a tensor to a Python index might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
  position_ids = self.position_ids[:, :seq_length]
/home/wgilliam/anaconda3/envs/blurr/lib/python3.7/site-packages/transformers/modeling_utils.py:1757: TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
  input_tensor.shape[chunk_dim] == tensor_shape for input_tensor in input_tensors
/home/wgilliam/anaconda3/envs/blurr/lib/python3.7/site-packages/torch/onnx/utils.py:244: UserWarning: We detected that you are modifying a dictionnary that is an input to your model. Note that dictionaries are allowed as inputs in ONNX but they should be handled with care. Usages of dictionaries is not recommended, and should not be used except for configuration use. Also note that the order and values of the keys must remain the same. 
  warnings.warn(warning)
{% endraw %} {% raw %}
onnx_inf = blurrONNX(export_fname)
{% endraw %} {% raw %}
res = onnx_inf.predict_tokens(txt.split())
for r in res: print(f'{[(tok, lbl) for tok,lbl in zip(r[0],r[1]) ]}\n')
[('Hi!', 'O'), ('My', 'O'), ('name', 'O'), ('is', 'O'), ('Wayde', 'B-PER'), ('Gilliam', 'I-PER'), ('from', 'O'), ('ohmeow.com.', 'B-ORG'), ('I', 'O'), ('live', 'O'), ('in', 'O'), ('California.', 'B-LOC')]

{% endraw %}

Tests

The tests below to ensure the token classification training code above works for all pretrained token classification 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 token classification models you are working with ... and if any of your pretrained token classification models fail, please submit a github issue (or a PR if you'd like to fix it yourself)

{% raw %}
try: del learn; torch.cuda.empty_cache()
except: pass
{% endraw %} {% raw %}
BLURR_MODEL_HELPER.get_models(task='TokenClassification')
[transformers.models.albert.modeling_albert.AlbertForTokenClassification,
 transformers.models.auto.modeling_auto.AutoModelForTokenClassification,
 transformers.models.bert.modeling_bert.BertForTokenClassification,
 transformers.models.camembert.modeling_camembert.CamembertForTokenClassification,
 transformers.models.distilbert.modeling_distilbert.DistilBertForTokenClassification,
 transformers.models.electra.modeling_electra.ElectraForTokenClassification,
 transformers.models.flaubert.modeling_flaubert.FlaubertForTokenClassification,
 transformers.models.funnel.modeling_funnel.FunnelForTokenClassification,
 transformers.models.layoutlm.modeling_layoutlm.LayoutLMForTokenClassification,
 transformers.models.longformer.modeling_longformer.LongformerForTokenClassification,
 transformers.models.mpnet.modeling_mpnet.MPNetForTokenClassification,
 transformers.models.mobilebert.modeling_mobilebert.MobileBertForTokenClassification,
 transformers.models.roberta.modeling_roberta.RobertaForTokenClassification,
 transformers.models.squeezebert.modeling_squeezebert.SqueezeBertForTokenClassification,
 transformers.models.albert.modeling_tf_albert.TFAlbertForTokenClassification,
 transformers.models.auto.modeling_tf_auto.TFAutoModelForTokenClassification,
 transformers.models.bert.modeling_tf_bert.TFBertForTokenClassification,
 transformers.models.camembert.modeling_tf_camembert.TFCamembertForTokenClassification,
 transformers.models.distilbert.modeling_tf_distilbert.TFDistilBertForTokenClassification,
 transformers.models.electra.modeling_tf_electra.TFElectraForTokenClassification,
 transformers.models.flaubert.modeling_tf_flaubert.TFFlaubertForTokenClassification,
 transformers.models.funnel.modeling_tf_funnel.TFFunnelForTokenClassification,
 transformers.models.longformer.modeling_tf_longformer.TFLongformerForTokenClassification,
 transformers.models.mpnet.modeling_tf_mpnet.TFMPNetForTokenClassification,
 transformers.models.mobilebert.modeling_tf_mobilebert.TFMobileBertForTokenClassification,
 transformers.models.roberta.modeling_tf_roberta.TFRobertaForTokenClassification,
 transformers.models.xlm.modeling_tf_xlm.TFXLMForTokenClassification,
 transformers.models.xlm_roberta.modeling_tf_xlm_roberta.TFXLMRobertaForTokenClassification,
 transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForTokenClassification,
 transformers.models.xlm.modeling_xlm.XLMForTokenClassification,
 transformers.models.xlm_roberta.modeling_xlm_roberta.XLMRobertaForTokenClassification,
 transformers.models.xlnet.modeling_xlnet.XLNetForTokenClassification]
{% endraw %} {% raw %}
pretrained_model_names = [
    'albert-base-v1',
    'bert-base-multilingual-cased',
    'camembert-base',
    'distilbert-base-uncased',
    'google/electra-small-generator',
    'flaubert/flaubert_small_cased',
    'funnel-transformer/small-base',
    'allenai/longformer-base-4096',
    'google/mobilebert-uncased',
    'roberta-base',
    'squeezebert/squeezebert-uncased',
    'xlm-mlm-ende-1024',
    'xlm-roberta-base',
    'xlnet-base-cased' 
]
{% endraw %} {% raw %}
#hide_output
task = HF_TASKS_AUTO.TokenClassification
bsz = 4
seq_sz = 64

test_results = []
for model_name in pretrained_model_names:
    error=None
    
    print(f'=== {model_name} ===\n')
    
    config = AutoConfig.from_pretrained(model_name)
    config.num_labels = len(labels)
    
    hf_arch, hf_config, hf_tokenizer, hf_model = BLURR_MODEL_HELPER.get_hf_objects(model_name, 
                                                                                   task=task, 
                                                                                   config=config)
    
    print(f'architecture:\t{hf_arch}\ntokenizer:\t{type(hf_tokenizer).__name__}\n')
    
    before_batch_tfm = HF_TokenClassBeforeBatchTransform(hf_arch, hf_config, hf_tokenizer, hf_model,
                                                         max_length=seq_sz,
                                                         padding='max_length',
                                                         is_split_into_words=True, 
                                                         tok_kwargs={ 'return_special_tokens_mask': True })

    blocks = (
        HF_TextBlock(before_batch_tfm=before_batch_tfm, input_return_type=HF_TokenClassInput), 
        HF_TokenCategoryBlock(vocab=labels)
    )

    dblock = DataBlock(blocks=blocks, 
                       get_x=ColReader('tokens'),
                       get_y= lambda inp: [ 
                           (label, len(hf_tokenizer.tokenize(str(entity)))) 
                           for entity, label in zip(inp.tokens, inp.labels) 
                       ],
                       splitter=RandomSplitter())
    
    dls = dblock.dataloaders(germ_eval_df, bs=bsz)

    model = HF_BaseModelWrapper(hf_model)
    learn = Learner(dls, 
                model,
                opt_func=partial(Adam),
                cbs=[HF_BaseModelCallback],
                splitter=hf_splitter).to_fp16()

    learn.create_opt()             # -> will create your layer groups based on your "splitter" function
    learn.freeze()
    
    b = dls.one_batch()
    
    try:
        print('*** TESTING DataLoaders ***')
        test_eq(len(b), 2)
        test_eq(len(b[0]['input_ids']), bsz)
        test_eq(b[0]['input_ids'].shape, torch.Size([bsz, seq_sz]))
        test_eq(len(b[1]), bsz)

        print('*** TESTING Training/Results ***')
        learn.fit_one_cycle(1, lr_max= 3e-5, moms=(0.8,0.7,0.8), 
                            cbs=[HF_TokenClassMetricsCallback(tok_metrics=['accuracy'])])

        test_results.append((hf_arch, type(hf_tokenizer).__name__, type(hf_model).__name__, 'PASSED', ''))
        learn.show_results(learner=learn, max_n=2, trunc_at=10)
        
    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()
{% endraw %} {% raw %}
arch tokenizer model_name result error
0 albert AlbertTokenizerFast AlbertForTokenClassification PASSED
1 bert BertTokenizerFast BertForTokenClassification PASSED
2 camembert CamembertTokenizerFast CamembertForTokenClassification PASSED
3 distilbert DistilBertTokenizerFast DistilBertForTokenClassification PASSED
4 electra ElectraTokenizerFast ElectraForTokenClassification PASSED
5 flaubert FlaubertTokenizer FlaubertForTokenClassification PASSED
6 funnel FunnelTokenizerFast FunnelForTokenClassification PASSED
7 longformer LongformerTokenizerFast LongformerForTokenClassification PASSED
8 mobilebert MobileBertTokenizerFast MobileBertForTokenClassification PASSED
9 roberta RobertaTokenizerFast RobertaForTokenClassification PASSED
10 squeezebert SqueezeBertTokenizerFast SqueezeBertForTokenClassification PASSED
11 xlm XLMTokenizer XLMForTokenClassification PASSED
12 xlm_roberta XLMRobertaTokenizerFast XLMRobertaForTokenClassification PASSED
13 xlnet XLNetTokenizerFast XLNetForTokenClassification PASSED
{% endraw %}

Cleanup