---
title: Fine-tune and serve a BERT text classifier with Model Serving
description: Fine-tune a DistilBERT text classifier on serverless GPU compute, serve it on a GPU Model Serving endpoint, and label a batch of texts.
canonical_url: https://docs.databricks.com/aws/en/machine-learning/model-serving/model-serving-example-bert-classifier
---

# Fine-tune and serve a BERT text classifier with Model Serving

A text classifier is a model that assigns a label to a piece of text, such as positive or negative for a review. This example fine-tunes DistilBERT, a Transformers model that's smaller than BERT, to label product reviews. It then serves the model on a GPU endpoint and labels three texts in one request.

## <a id="requirements" />Requirements

* A workspace in a [supported region](https://docs.databricks.com/aws/en/machine-learning/model-serving/model-serving-limits.md#regions).
* [AI Runtime](https://docs.databricks.com/aws/en/machine-learning/ai-runtime/index.md) serverless GPU compute for the notebook.
* The Unity Catalog privileges to register and delete models, described in [Manage model lifecycle in Unity Catalog](https://docs.databricks.com/aws/en/machine-learning/manage-model-lifecycle/index.md).

## <a id="run-the-example" />Run the example

To run every step, import the notebook. Run the cells in order, in the same notebook.

#### Fine-tune and serve a BERT text classifier notebook

[Get notebook](https://docs.databricks.com/notebooks/source/machine-learning/example-bert-classifier.html)

### <a id="check-for-gpu-compute" />Check for GPU compute

Run this notebook on serverless GPU compute, because registering the model packages the notebook's environment with it. The first cell checks for serverless GPU compute and stops with an error if it's missing. Run the following:

```python
import os

# Run this notebook on serverless GPU compute, because registration packages the notebook's environment.
if not os.environ.get("DATABRICKS_ACCELERATOR"):
    raise RuntimeError("Attach this notebook to serverless GPU compute, then run the cell again.")
```

When the check passes, the cell finishes without an error. If it raises the error, attach the notebook to serverless GPU compute and run the cell again.

### <a id="install-the-packages" />Install the packages

The cell installs MLflow 3.12 or above and the Databricks SDK for Python 0.102.0 or above, which this example needs to register the model with [`env_pack`](https://docs.databricks.com/aws/en/machine-learning/model-serving/express-deployments.md#the-env_pack-parameter). The cell also installs `transformers` to train the model, `datasets` to load the reviews, and `accelerate`, which the Hugging Face text classification guide installs before it trains. After the installs, the cell restarts Python. To install them, run the following:

```python
# Registering with env_pack requires recent MLflow and Databricks SDK versions.
%pip install -U "mlflow>=3.12" "databricks-sdk>=0.102.0"

# Install the libraries that the training cell and the model use.
%pip install transformers datasets accelerate

%restart_python
```

### <a id="fine-tune-the-model-and-save-it" />Fine-tune the model and save it

The cell fine-tunes the model for one pass over 2,000 reviews from the [Amazon reviews polarity dataset](https://huggingface.co/datasets/fancyzhx/amazon_polarity) on Hugging Face. Then it prints the test accuracy and saves the model and tokenizer to a local folder. Each review's text is in `content`, and its `label` is 0 for negative and 1 for positive. `id2label` and `label2id` name the labels, so the endpoint returns `POSITIVE` or `NEGATIVE`. To train on your own labeled texts, replace the dataset and the two label maps. To fine-tune the model, run the following:

```python
import numpy as np
from datasets import load_dataset
from transformers import (
    AutoModelForSequenceClassification,
    AutoTokenizer,
    DataCollatorWithPadding,
    Trainer,
    TrainingArguments,
)

base_model = "distilbert/distilbert-base-uncased"
id2label = {0: "NEGATIVE", 1: "POSITIVE"}
label2id = {"NEGATIVE": 0, "POSITIVE": 1}

# A small slice of the Amazon product reviews keeps training short. Replace it with your own labeled texts.
# The cell downloads one of the four training files, so it skips the check of the full split sizes.
reviews = load_dataset(
    "fancyzhx/amazon_polarity",
    data_files={
        "train": "amazon_polarity/train-00000-of-00004.parquet",
        "test": "amazon_polarity/test-00000-of-00001.parquet",
    },
    verification_mode="no_checks",
)
train_data = reviews["train"].shuffle(seed=42).select(range(2000))
eval_data = reviews["test"].shuffle(seed=42).select(range(500))

tokenizer = AutoTokenizer.from_pretrained(base_model)


def tokenize(batch):
    return tokenizer(batch["content"], truncation=True)


train_data = train_data.map(tokenize, batched=True)
eval_data = eval_data.map(tokenize, batched=True)

# id2label and label2id give the model readable label names.
model = AutoModelForSequenceClassification.from_pretrained(
    base_model, num_labels=2, id2label=id2label, label2id=label2id
)


def compute_metrics(eval_pred):
    logits, labels = eval_pred
    return {"accuracy": float((np.argmax(logits, axis=1) == labels).mean())}


trainer = Trainer(
    model=model,
    args=TrainingArguments(
        output_dir="/tmp/bert_classifier_checkpoints",
        num_train_epochs=1,
        per_device_train_batch_size=16,
        per_device_eval_batch_size=16,
        report_to="none",
    ),
    train_dataset=train_data,
    eval_dataset=eval_data,
    processing_class=tokenizer,
    data_collator=DataCollatorWithPadding(tokenizer=tokenizer),
    compute_metrics=compute_metrics,
)
trainer.train()

# Save the fine-tuned model and its tokenizer to a folder on local disk.
checkpoint_dir = "/tmp/bert_classifier"
model.save_pretrained(checkpoint_dir)
tokenizer.save_pretrained(checkpoint_dir)

print("Accuracy on 500 test reviews:", round(trainer.evaluate()["eval_accuracy"], 3))
```

The output is similar to the following:

```text
Accuracy on 500 test reviews: 0.902
```

The cell also shows progress bars and warnings.

### <a id="log-the-model" />Log the model

The cell builds a Transformers `text-classification` pipeline from the saved folder and logs it with `mlflow.transformers.log_model`. To serve a model you already fine-tuned, skip [the fine-tuning cell](https://docs.databricks.com/aws/en/machine-learning/model-serving/model-serving-example-bert-classifier.md#fine-tune-the-model-and-save-it) and set `checkpoint_dir` to the folder where you saved its model and tokenizer. MLflow infers the signature from the input example, a one-row table that has a `text` column. The signature takes a `text` string and returns a `label` string and a `score` number. The `model_config` setting truncates each text to 512 tokens, the model's input limit, so a long review still gets a label. Unity Catalog requires a signature on each new model version. To log the model, run the following:

```python
import mlflow
import pandas as pd
from transformers import pipeline

# Build the pipeline from the checkpoint folder. To serve your own fine-tuned model, use its folder.
classifier = pipeline("text-classification", model=checkpoint_dir)

model_info = mlflow.transformers.log_model(
    transformers_model=classifier,
    name="bert_classifier",
    input_example=pd.DataFrame([{"text": "This blender is powerful and easy to clean."}]),
    # Truncate each text to the model's 512-token input limit at inference, as training did.
    model_config={"truncation": True, "max_length": 512},
)
```

The cell prints only library messages, such as MLflow's link to the logged model.

### <a id="register-the-model" />Register the model

A Unity Catalog model name has three levels, `catalog.schema.model`. Replace `<catalog>` and `<schema>` with a Unity Catalog schema where you have the privileges in [Requirements](https://docs.databricks.com/aws/en/machine-learning/model-serving/model-serving-example-bert-classifier.md#requirements). The cell registers the model with `env_pack=EnvPackConfig(name="databricks_model_serving")`, which packages the notebook environment during registration. To register the model, run the following:

```python
import mlflow
from mlflow.utils.env_pack import EnvPackConfig

mlflow.set_registry_uri("databricks-uc")

model_version = mlflow.register_model(
    model_uri=model_info.model_uri,
    name="<catalog>.<schema>.bert_classifier",
    env_pack=EnvPackConfig(name="databricks_model_serving"),
)
```

The output names the new version, version 1 for a new model, and says that the version is staged for Model Serving. For more on `env_pack`, see [Express deployments for model serving endpoints](https://docs.databricks.com/aws/en/machine-learning/model-serving/express-deployments.md).

### <a id="create-the-endpoint" />Create the endpoint

The cell creates the endpoint `bert-classifier-endpoint` with `create_and_wait`. It serves the registered version as the served entity `bert-classifier` on a GPU workload type, and it turns scale to zero off. For the GPU workload types on each cloud, see [GPU workload types](https://docs.databricks.com/aws/en/machine-learning/model-serving/create-manage-serving-endpoints.md#gpu). To create the endpoint, run the following:

```python
from datetime import timedelta

from databricks.sdk import WorkspaceClient
from databricks.sdk.service.serving import (
    EndpointCoreConfigInput,
    ServedEntityInput,
    ServingModelWorkloadType,
)

endpoint_name = "bert-classifier-endpoint"

w = WorkspaceClient()
w.serving_endpoints.create_and_wait(
    name=endpoint_name,
    config=EndpointCoreConfigInput(
        name=endpoint_name,
        served_entities=[
            ServedEntityInput(
                name="bert-classifier",
                entity_name=model_version.name,
                entity_version=model_version.version,
                workload_type=ServingModelWorkloadType.GPU_SMALL,
                workload_size="Small",
                scale_to_zero_enabled=False,
            )
        ],
    ),
    timeout=timedelta(minutes=45),
)
```

Scale to zero is off, so the endpoint doesn't scale down to zero, and you're billed for each replica while it runs. To delete it, see [Delete the endpoint and the model](https://docs.databricks.com/aws/en/machine-learning/model-serving/model-serving-example-bert-classifier.md#delete-the-endpoint-and-the-model). If a later cell fails, run the delete cells anyway, so the endpoint doesn't keep running.

### <a id="label-texts" />Label texts

The request sends one row for each text, and each row holds the text in `text`. The response holds one prediction for each row, and each prediction has a `label` and a `score`. The cell prints each label, its score rounded to four decimal places, and the text. Replace the sample texts with your own, then run the following:

```python
import time
from databricks.sdk.errors import NotFound

texts = [
    "This blender is powerful and easy to clean.",
    "The charger stopped working after two days.",
    "Good sound for the price, but the case feels cheap.",
]

# Retry while the endpoint is not accepting requests yet.
for attempt in range(12):
    try:
        response = w.serving_endpoints.query(
            name=endpoint_name,
            dataframe_records=[{"text": text} for text in texts],
        )
        break
    except NotFound:
        time.sleep(10)
else:
    raise TimeoutError("The endpoint didn't accept the request after 12 tries.")

# Each prediction holds the label and the score for one text.
for text, prediction in zip(texts, response.predictions):
    print(prediction["label"], round(prediction["score"], 4), text)
```

The output is similar to the following:

```text
POSITIVE 0.9696 This blender is powerful and easy to clean.
NEGATIVE 0.9521 The charger stopped working after two days.
POSITIVE 0.8015 Good sound for the price, but the case feels cheap.
```

Your own texts get their own labels and scores.

A query sent after the endpoint reports READY can get a 404 with the error code `ENDPOINT_NOT_FOUND` for a short time, so the loop retries. It makes up to 12 tries and waits 10 seconds after each 404.

To call the endpoint over REST, see [Send a request from an application over REST](https://docs.databricks.com/aws/en/machine-learning/model-serving/score-custom-model-endpoints.md#send-a-request-from-an-application-over-rest).

### <a id="delete-the-endpoint-and-the-model" />Delete the endpoint and the model

Optionally, delete the endpoint and the model. You can't undo deleting the endpoint or the registered model. To delete the endpoint, run the following:

```python
delete_result = w.serving_endpoints.delete(name=endpoint_name)
print("delete returned:", repr(delete_result))
```

The cell prints the following:

```text
delete returned: None
```

To delete the model version that this notebook registered, run the following. When no other version of the model is left, the cell also deletes the registered model:

```python
from mlflow import MlflowClient

client = MlflowClient()
client.delete_model_version(name=model_version.name, version=model_version.version)
print("Deleted version:", model_version.version)
if not client.search_model_versions(f"name='{model_version.name}'"):
    client.delete_registered_model(name=model_version.name)
    print("Deleted registered model:", model_version.name)
```

The cell prints the following:

```text
Deleted version: 1
Deleted registered model: <catalog>.<schema>.bert_classifier
```

## Additional resources

* [Fine-tune Hugging Face models for a single GPU](https://docs.databricks.com/aws/en/machine-learning/train-model/huggingface/fine-tune-model.md)
* [Express deployments for model serving endpoints](https://docs.databricks.com/aws/en/machine-learning/model-serving/express-deployments.md)
* [Create an endpoint for custom models in Model Serving](https://docs.databricks.com/aws/en/machine-learning/model-serving/create-manage-serving-endpoints.md)
* [Query serving endpoints for custom models](https://docs.databricks.com/aws/en/machine-learning/model-serving/score-custom-model-endpoints.md)
* [Text classification](https://huggingface.co/docs/transformers/tasks/sequence_classification) in the Hugging Face documentation
