Token classification¶
- Goal: Show a standard workflow for a token classification task, including zero-shot suggestions and model fine-tuning.
- Dataset: ontonotes5, a large corpus comprising various genres of text that need to be classified for Named Entity Recognition.
- Libraries: datasets, gliner, transformers, spanmarker
- Components: TextField, SpanQuestion, Suggestion, Query, Filter
Getting started¶
Deploy the Argilla server¶
If you already have deployed Argilla, you can skip this step. Otherwise, you can quickly deploy Argilla following this guide.
Set up the environment¶
To complete this tutorial, you need to install the Argilla SDK and a few third-party libraries via pip
.
Let's make the needed imports:
You also need to connect to the Argilla server with the api_url
and api_key
.
# Replace api_url with your url if using Docker
# Replace api_key with your API key under "My Settings" in the UI
# Uncomment the last line and set your HF_TOKEN if your space is private
client = rg.Argilla(
api_url="https://[your-owner-name]-[your_space_name].hf.space",
api_key="[your-api-key]",
# headers={"Authorization": f"Bearer {HF_TOKEN}"}
)
Vibe check the dataset¶
We will have a look at the dataset to understand its structure and the kind of data it contains. We do this by using the embedded Hugging Face Dataset Viewer.
Configure and create the Argilla dataset¶
Now, we will need to configure the dataset. In the settings, we can specify the guidelines, fields, and questions. If needed, you can also add metadata and vectors. However, for our use case, we just need a text field and a span question, corresponding to the token
and tags
columns. We will focus on Name Entity Recognition, but this workflow can also be applied to Span Classification, which differs in that the spans are less clearly defined and often overlap.
labels = [
"CARDINAL",
"DATE",
"PERSON",
"NORP",
"GPE",
"LAW",
"PERCENT",
"ORDINAL",
"MONEY",
"WORK_OF_ART",
"FAC",
"TIME",
"QUANTITY",
"PRODUCT",
"LANGUAGE",
"ORG",
"LOC",
"EVENT",
]
settings = rg.Settings(
guidelines="Classify individual tokens according to the specified categories, ensuring that any overlapping or nested entities are accurately captured.",
fields=[
rg.TextField(
name="text",
title="Text",
use_markdown=False,
),
],
questions=[
rg.SpanQuestion(
name="span_label",
field="text",
labels=labels,
title="Classify the tokens according to the specified categories.",
allow_overlapping=False,
)
],
)
Let's create the dataset with the name and the defined settings:
Add records¶
We have created the dataset (you can check it in the UI), but we still need to add the data for annotation. In this case, we will use the ontonote5
dataset from the Hugging Face Hub. Specifically, we will use 2100 samples from the test
split.
We will iterate over the Hugging Face dataset, adding data to the corresponding field in the Record
object for the Argilla dataset. Then, we will easily add them to the dataset using log
.
Add initial model suggestions¶
The next step is to add suggestions to the dataset. This will make things easier and faster for the annotation team. Suggestions will appear as preselected options, so annotators will only need to correct them. In our case, we will generate them using a GLiNER model. However, you can use a framework or technique of your choice.
Note
For further information, you can check the GLiNER repository and the original paper.
We will start by loading the pre-trained GLiNER model. Specifically, we will use gliner_mediumv2
, available in Hugging Face Hub.
Next, we will create a function to generate predictions using this general model, which can identify the specified labels without being pre-trained on them. The function will return a dictionary formatted with the necessary schema to add entities to our Argilla dataset. This schema includes the keys 'start’ and ‘end’ to indicate the indices where the span begins and ends, as well as ‘label’ for the entity label.
To update the records, we will need to retrieve them from the server and update them with the new suggestions. The id
will always need to be provided as it is the records' identifier to update a record and avoid creating a new one.
Voilà! We have added the suggestions to the dataset and they will appear in the UI marked with ✨.
Evaluate with Argilla¶
Now, we can start the annotation process. Just open the dataset in the Argilla UI and start annotating the records. If the suggestions are correct, you can just click on Submit
. Otherwise, you can select the correct label.
Note
Check this how-to guide to know more about annotating in the UI.
Train your model¶
After the annotation, we will have a robust dataset to train our model for entity recognition. For our case, we will train a SpanMarker model, but you can select any model of your choice. So, let's start by retrieving the annotated records.
Note
Check this how-to guide to learn more about filtering and querying in Argilla. Also, you can check the Hugging Face docs on fine-tuning an token classification model.
In our case, we submitted 2000 annotations using the bulk view.
SpanMarker accepts any dataset as long as it has the tokens
and ner_tags
columns. The ner_tags
can be annotated using the IOB, IOB2, BIOES or BILOU labeling scheme, as well as regular unschemed labels. In our case, we have chosen to use the IOB format. Thus, we will define a function to extract the annotated NER tags according to this schema.
Note
For further information, you can check the SpanMarker documentation.
def get_iob_tag_for_token(token_start, token_end, ner_spans):
for span in ner_spans:
if token_start >= span["start"] and token_end <= span["end"]:
if token_start == span["start"]:
return f"B-{span['label']}"
else:
return f"I-{span['label']}"
return "O"
def extract_ner_tags(text, responses):
tokens = re.split(r"(\s+)", text)
ner_tags = []
current_position = 0
for token in tokens:
if token.strip():
token_start = current_position
token_end = current_position + len(token)
tag = get_iob_tag_for_token(token_start, token_end, responses)
ner_tags.append(tag)
current_position += len(token)
return ner_tags
Let's now extract them and save two lists with the tokens and NER tags, which will help us build our dataset to train the SpanMarker model.
In addition, we will have to indicate the labels and they should be formatted as integers. So, we will retrieve them and map them.
Finally, we will create a dataset with the train and validation sets.
Now, let's prepare to train our model. For this, it is recommended to use GPU. You can check if it is available as shown below.
We will define our model and arguments. In this case, we will use the bert-base-cased
, available in the Hugging Face Hub, but others can be applied.
Note
The training arguments are inherited from the Transformers library. You can check more information here.
encoder_id = "bert-base-cased"
model = SpanMarkerModel.from_pretrained(
encoder_id,
labels=labels,
model_max_length=256,
entity_max_length=8,
)
args = TrainingArguments(
output_dir="models/span-marker",
learning_rate=5e-5,
per_device_train_batch_size=8,
per_device_eval_batch_size=8,
num_train_epochs=1,
weight_decay=0.01,
warmup_ratio=0.1,
fp16=False, # Set to True if available
logging_first_step=True,
logging_steps=50,
evaluation_strategy="steps",
save_strategy="steps",
eval_steps=500,
save_total_limit=2,
dataloader_num_workers=2,
)
trainer = Trainer(
model=model,
args=args,
train_dataset=span_dataset["train"],
eval_dataset=span_dataset["validation"],
)
Let's train it! This time, we use a high-quality human-annotated training set, so the results are expected to have improved.
You can save it locally or push it to the Hub. And then load it from there.
# Save and load locally
# model.save_pretrained("token_classification_model")
# model = SpanMarkerModel.from_pretrained("token_classification_model")
# Push and load in HF
# model.push_to_hub("[username]/token_classification_model")
# model = SpanMarkerModel.from_pretrained("[username]/token_classification_model")
It's time to make the predictions! We will set a function that uses the predict
method to get the suggested label. The model will infer the label based on the text. The function will return the spans in the corresponding structure for the Argilla dataset.
As the training data was of better quality, we can expect a better model. So we can update the remaining non-annotated records with the new model's suggestions.
Conclusions¶
In this tutorial, we present an end-to-end example of a token classification task. This serves as the base, but it can be performed iteratively and seamlessly integrated into your workflow to ensure high-quality curation of your data and improved results.
We started by configuring the dataset, adding records, and adding suggestions based on the GLiNer predictions. After the annotation process, we trained a SpanMarker model with the annotated data and updated the remaining records with the new suggestions.