Skip to content

Token classification

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.

!pip install argilla
!pip install gliner==0.2.6 transformers==4.40.2 span_marker==1.5.0

Let's make the needed imports:

import re

import argilla as rg

import torch
from datasets import load_dataset, Dataset, DatasetDict
from gliner import GLiNER
from span_marker import SpanMarkerModel, Trainer
from transformers import TrainingArguments

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:

dataset = rg.Dataset(
    name="token_classification_dataset",
    settings=settings,
)
dataset.create()

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.

hf_dataset = load_dataset("tner/ontonotes5", split="test[:2100]")

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.

records = [rg.Record(fields={"text": " ".join(row["tokens"])}) for row in hf_dataset]

dataset.records.log(records)

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.

gliner_model = GLiNER.from_pretrained("urchade/gliner_mediumv2.1")

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.

def predict_gliner(model, text, labels, threshold):
    entities = model.predict_entities(text, labels, threshold)
    return [
        {k: v for k, v in ent.items() if k not in {"score", "text"}} for ent in entities
    ]

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.

data = dataset.records.to_list(flatten=True)
updated_data = [
    {
        "span_label": predict_gliner(
            model=gliner_model, text=sample["text"], labels=labels, threshold=0.70
        ),
        "id": sample["id"],
    }
    for sample in data
]
dataset.records.log(records=updated_data)

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.

dataset = client.datasets("token_classification_dataset")

In our case, we submitted 2000 annotations using the bulk view.

status_filter = rg.Query(filter=rg.Filter(("response.status", "==", "submitted")))

submitted = dataset.records(status_filter).to_list(flatten=True)

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.

tokens = []
ner_tags = []
for r in submitted:
    tags = extract_ner_tags(r["text"], r["span_label.responses"][0])
    tks = r["text"].split()
    tokens.append(tks)
    ner_tags.append(tags)

In addition, we will have to indicate the labels and they should be formatted as integers. So, we will retrieve them and map them.

labels = list(set([item for sublist in ner_tags for item in sublist]))

id2label = {i: label for i, label in enumerate(labels)}
label2id = {label: id_ for id_, label in id2label.items()}

mapped_ner_tags = [[label2id[label] for label in ner_tag] for ner_tag in ner_tags]

Finally, we will create a dataset with the train and validation sets.

records = [
    {
        "tokens": token,
        "ner_tags": ner_tag,
    }
    for token, ner_tag in zip(tokens, mapped_ner_tags)
]
span_dataset = DatasetDict(
    {
        "train": Dataset.from_list(records[:1500]),
        "validation": Dataset.from_list(records[1501:2000]),
    }
)

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.

if torch.cuda.is_available():
    device = torch.device("cuda")
    print(f"Using {torch.cuda.get_device_name(0)}")
elif torch.backends.mps.is_available():
    device = torch.device("mps")
    print("Using MPS device")
else:
    device = torch.device("cpu")
    print("No GPU available, using CPU instead.")

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.

trainer.train()
trainer.evaluate()

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.

def predict_spanmarker(model, text):
    entities = model.predict(text)
    return [
        {
            "start": ent["char_start_index"],
            "end": ent["char_end_index"],
            "label": ent["label"],
        }
        for ent in entities
    ]

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.

data = dataset.records.to_list(flatten=True)
updated_data = [
    {
        "span_label": predict_spanmarker(model=model, text=sample["text"]),
        "id": sample["id"],
    }
    for sample in data
]
dataset.records.log(records=updated_data)

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.