AI Hints
Home›Fine-Tuning LLMs Tutorial›Classification Fine-Tuning
Fine-Tuning LLMs · Lesson 29 of 120

Tokenize the Dataset

Labels and token IDs.

⏱ 2 min read▶ Video at 47:01🎓 Free
Watch this lesson in the Fine-Tuning LLMs courseWatch on YouTube ↗Full Fine-Tuning LLMs course

A model can't read the word complaint. Labels must be numbers, and messages must be token IDs. Let's write one small file that prepares everything.

  • Labels must be numbers
  • Messages must be token IDs
  • One small file

prep.py

Here's prep dot p y. First, the list of intents. Label to ID maps each name to a number, and ID to label maps it back. We load the Distil BERT tokenizer. The prepare function tokenizes one message, cut to thirty two tokens, and adds its label number. Finally, we load both files, and map prepare over every row. Remove columns drops the text columns we no longer need.

prep.pypython
from datasets import load_dataset
from transformers import AutoTokenizer

INTENTS = ["order_status", "return", "price", "stock", "complaint"]
label2id = {name: i for i, name in enumerate(INTENTS)}
id2label = {i: name for i, name in enumerate(INTENTS)}
MODEL = "distilbert/distilbert-base-uncased"
tok = AutoTokenizer.from_pretrained(MODEL)

def prepare(row):
    enc = tok(row["message"], truncation=True, max_length=32)
    enc["label"] = label2id[row["intent"]]
    return enc

data = load_dataset("json", data_files={"train": "tickets_train.jsonl",
                                        "test": "tickets_test.jsonl"})
data = data.map(prepare, remove_columns=["message", "intent", "book"])

One prepared row

Let's look at one prepared row. Then we decode its token IDs, back into text. Run it. Instead of text, the row now has input IDs, an attention mask, and a label number. Four means complaint. And decoding shows two special tokens. CLS at the start, and SEP at the end. Distil BERT always adds them. Notice the text is lower case too. This model ignores capitals.

app.pypython
from prep import data, tok

row = data["train"][0]
print(row)
print(tok.decode(row["input_ids"]))
Output
{'input_ids': [101, 7592, 999, 1996, 4062, 2001, 12726, 2043, 12771, 21643, 1012, 102],
'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'attention_mask': [1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1], 'label': 4}
[CLS] hello! the driver was rude when delivering dune. [SEP]
Also uses prep.py
from datasets import load_dataset
from transformers import AutoTokenizer

INTENTS = ["order_status", "return", "price", "stock", "complaint"]
label2id = {name: i for i, name in enumerate(INTENTS)}
id2label = {i: name for i, name in enumerate(INTENTS)}
MODEL = "distilbert/distilbert-base-uncased"
tok = AutoTokenizer.from_pretrained(MODEL)

def prepare(row):
    enc = tok(row["message"], truncation=True, max_length=32)
    enc["label"] = label2id[row["intent"]]
    return enc

data = load_dataset("json", data_files={"train": "tickets_train.jsonl",
                                        "test": "tickets_test.jsonl"})
data = data.map(prepare, remove_columns=["message", "intent", "book"])
Also uses train.py
import numpy as np
from transformers import (AutoModelForSequenceClassification, DataCollatorWithPadding,
                          Trainer, TrainingArguments)
from prep import tok, data, MODEL, label2id, id2label

model = AutoModelForSequenceClassification.from_pretrained(
    MODEL, num_labels=5, id2label=id2label, label2id=label2id)
args = TrainingArguments(output_dir="intent-model", num_train_epochs=2,
                         per_device_train_batch_size=16, learning_rate=5e-5,
                         eval_strategy="epoch", logging_strategy="epoch",
                         save_strategy="no", report_to="none")

def accuracy(pred):
    return {"accuracy": (np.argmax(pred.predictions, -1) == pred.label_ids).mean()}

trainer = Trainer(model=model, args=args, train_dataset=data["train"],
                  eval_dataset=data["test"], data_collator=DataCollatorWithPadding(tok),
                  compute_metrics=accuracy)

Summary

Let's recap. Labels become numbers, with label to ID. The prepare function tokenizes each message, and adds its label. And map runs it over the whole dataset. Next, the model itself.

Key takeaways
  • label2id / id2label
  • prepare(row)
  • data.map(prepare)
Next up: A Classification Model — DistilBERT with a new head