BERT Model Training with Intel Gaudi#
In this notebook, we will train a BERT model for sequence classification using the Yelp review full dataset. We will use the transformers and datasets libraries from Hugging Face, along with ray.train for distributed training.
Intel Gaudi AI Processors (HPUs) are AI hardware accelerators designed by Intel Habana Labs. For more information, see Gaudi Architecture and Gaudi Developer Docs.
Configuration#
A node with Gaudi/Gaudi2 installed is required to run this example. Both Gaudi and Gaudi2 have 8 HPUs. We will use 2 workers to train the model, each using 1 HPU.
We recommend using a prebuilt container to run these examples. To run a container, you need Docker. See Install Docker Engine for installation instructions.
Next, follow Run Using Containers to install the Gaudi drivers and container runtime.
Next, start the Gaudi container:
docker pull vault.habana.ai/gaudi-docker/1.22.1/ubuntu24.04/habanalabs/pytorch-installer-2.7.1:latest
docker run -it --runtime=habana -e HABANA_VISIBLE_DEVICES=all -e OMPI_MCA_btl_vader_single_copy_mechanism=none --cap-add=sys_nice --net=host --ipc=host vault.habana.ai/gaudi-docker/1.22.1/ubuntu24.04/habanalabs/pytorch-installer-2.7.1:latest
Inside the container, install the following dependencies to run this notebook.
pip install ray[train] notebook transformers datasets evaluate scikit-learn
# Import necessary libraries
import os
from typing import Dict
import torch
from torch import nn
from torch.utils.data import DataLoader
from tqdm import tqdm
import numpy as np
import evaluate
from datasets import load_dataset
import transformers
from transformers import (
Trainer,
TrainingArguments,
AutoTokenizer,
AutoModelForSequenceClassification,
)
import ray.train
from ray.train import ScalingConfig
from ray.train.torch import TorchTrainer
from ray.train.torch import TorchConfig
from ray.runtime_env import RuntimeEnv
import habana_frameworks.torch.core as htcore
Metrics Setup#
We will use accuracy as our evaluation metric. The compute_metrics function will calculate the accuracy of our model’s predictions.
# Metrics
metric = evaluate.load("accuracy")
def compute_metrics(eval_pred):
logits, labels = eval_pred
predictions = np.argmax(logits, axis=-1)
return metric.compute(predictions=predictions, references=labels)
Training Function#
This function will be executed by each worker during training. It handles data loading, tokenization, model initialization, and the training loop. Compared to a training function for GPU, no changes are needed to port to HPU. Internally, Ray Train does these things:
Detect HPU and set the device.
Initializes the habana PyTorch backend.
Initializes the habana distributed backend.
def train_func_per_worker(config: Dict):
# Datasets
dataset = load_dataset("yelp_review_full")
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
def tokenize_function(examples):
return tokenizer(examples["text"], padding="max_length", truncation=True)
lr = config["lr"]
epochs = config["epochs"]
batch_size = config["batch_size_per_worker"]
train_dataset = dataset["train"].select(range(1000)).map(tokenize_function, batched=True)
eval_dataset = dataset["test"].select(range(1000)).map(tokenize_function, batched=True)
# Prepare dataloader for each worker
dataloaders = {}
dataloaders["train"] = torch.utils.data.DataLoader(
train_dataset,
shuffle=True,
collate_fn=transformers.default_data_collator,
batch_size=batch_size
)
dataloaders["test"] = torch.utils.data.DataLoader(
eval_dataset,
shuffle=True,
collate_fn=transformers.default_data_collator,
batch_size=batch_size
)
# Obtain HPU device automatically
device = ray.train.torch.get_device()
# Prepare model and optimizer
model = AutoModelForSequenceClassification.from_pretrained(
"bert-base-cased", num_labels=5
)
model = model.to(device)
optimizer = torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9)
# Start training loops
for epoch in range(epochs):
# Each epoch has a training and validation phase
for phase in ["train", "test"]:
if phase == "train":
model.train() # Set model to training mode
else:
model.eval() # Set model to evaluate mode
# breakpoint()
for batch in dataloaders[phase]:
batch = {k: v.to(device) for k, v in batch.items()}
# zero the parameter gradients
optimizer.zero_grad()
# forward
with torch.set_grad_enabled(phase == "train"):
# Get model outputs and calculate loss
outputs = model(**batch)
loss = outputs.loss
# backward + optimize only if in training phase
if phase == "train":
loss.backward()
optimizer.step()
print(f"train epoch:[{epoch}]\tloss:{loss:.6f}")
Main Training Function#
The train_bert function sets up the distributed training environment using Ray and starts the training process. To enable training using HPU, we only need to make the following changes:
Require an HPU for each worker in ScalingConfig
Set backend to “hccl” in TorchConfig
def train_bert(num_workers=2):
global_batch_size = 8
train_config = {
"lr": 1e-3,
"epochs": 10,
"batch_size_per_worker": global_batch_size // num_workers,
}
# Configure computation resources
# In ScalingConfig, require an HPU for each worker
scaling_config = ScalingConfig(num_workers=num_workers, resources_per_worker={"CPU": 1, "HPU": 1})
# Set backend to hccl in TorchConfig
torch_config = TorchConfig(backend = "hccl")
# Start your ray cluster
# Workaround https://github.com/ray-project/ray/issues/45302 by explictly setting HPU resource
ray.init(resources={"HPU": 8})
# Initialize a Ray TorchTrainer
trainer = TorchTrainer(
train_loop_per_worker=train_func_per_worker,
train_loop_config=train_config,
torch_config=torch_config,
scaling_config=scaling_config,
)
result = trainer.fit()
print(f"Training result: {result}")
Start Training#
Finally, we call the train_bert function to start the training process. You can adjust the number of workers to use.
%env PT_HPU_LAZY_MODE=1
train_bert(num_workers=2)
Possible outputs#
env: PT_HPU_LAZY_MODE=1
2025-11-19 23:15:51,716 INFO worker.py:2012 -- Started a local Ray instance.
/usr/local/lib/python3.12/dist-packages/ray/_private/worker.py:2051: FutureWarning: Tip: In future versions of Ray, Ray will no longer override accelerator visible devices env var if num_gpus=0 or num_gpus=None (default). To enable this behavior and turn off this error message, set RAY_ACCEL_ENV_VAR_OVERRIDE_ON_ZERO=0
warnings.warn(
(TrainController pid=10091) Attempting to start training worker group of size 2 with the following resources: [{'CPU': 1, 'HPU': 1}] * 2
(RayTrainWorker pid=10545) Setting up process group for: env:// [rank=0, world_size=2]
(TrainController pid=10091) Started training worker group of size 2:
(TrainController pid=10091) - (ip=100.83.67.100, pid=10545) world_rank=0, local_rank=0, node_rank=0
(TrainController pid=10091) - (ip=100.83.67.100, pid=10544) world_rank=1, local_rank=1, node_rank=0
Generating train split: 0%| | 0/650000 [00:00<?, ? examples/s]
Generating train split: 8%|▊ | 50000/650000 [00:00<00:01, 492099.76 examples/s]
Generating train split: 17%|█▋ | 110000/650000 [00:00<00:00, 548517.46 examples/s]
Generating train split: 25%|██▌ | 165000/650000 [00:00<00:00, 547550.35 examples/s]
Generating train split: 38%|███▊ | 249000/650000 [00:00<00:00, 548226.23 examples/s]
Generating train split: 47%|████▋ | 307000/650000 [00:00<00:00, 553824.69 examples/s]
Generating train split: 56%|█████▌ | 364000/650000 [00:00<00:00, 555108.99 examples/s]
Generating train split: 65%|██████▌ | 424000/650000 [00:00<00:00, 568062.06 examples/s]
Generating train split: 87%|████████▋ | 567000/650000 [00:01<00:00, 563047.56 examples/s]
Generating train split: 96%|█████████▌| 624000/650000 [00:01<00:00, 562029.65 examples/s]
Generating train split: 100%|██████████| 650000/650000 [00:01<00:00, 557805.34 examples/s]
Generating test split: 0%| | 0/50000 [00:00<?, ? examples/s]
Generating test split: 100%|██████████| 50000/50000 [00:00<00:00, 539501.96 examples/s]
(pid=gcs_server) [2025-11-19 23:16:19,888 E 219 219] (gcs_server) gcs_server.cc:302: Failed to establish connection to the event+metrics exporter agent. Events and metrics will not be exported. Exporter agent status: RpcError: Running out of retries to initialize the metrics agent. rpc_code: 14
(RayTrainWorker pid=10545) 0 COPY_FREE_VARS 1
(RayTrainWorker pid=10545)
(RayTrainWorker pid=10545) 7 2 RESUME 0
(RayTrainWorker pid=10545)
(RayTrainWorker pid=10545) 8 4 PUSH_NULL
(RayTrainWorker pid=10545) 6 LOAD_DEREF 1 (tokenizer)
(RayTrainWorker pid=10545) 8 LOAD_FAST 0 (examples)
(RayTrainWorker pid=10545) 10 LOAD_CONST 1 ('text')
(RayTrainWorker pid=10545) 12 BINARY_SUBSCR
(RayTrainWorker pid=10545) 16 LOAD_CONST 2 ('max_length')
(RayTrainWorker pid=10545) 18 LOAD_CONST 3 (True)
(RayTrainWorker pid=10545) 20 KW_NAMES 4 (('padding', 'truncation'))
(RayTrainWorker pid=10545) 22 CALL 3
(RayTrainWorker pid=10545) 30 RETURN_VALUE
Map: 0%| | 0/1000 [00:00<?, ? examples/s]
(RayTrainWorker pid=10544)
(RayTrainWorker pid=10544)
Map: 100%|██████████| 1000/1000 [00:00<00:00, 4095.16 examples/s]
(RayTrainWorker pid=10545)
(RayTrainWorker pid=10545)
(RayTrainWorker pid=10544)
(RayTrainWorker pid=10544)
Map: 100%|██████████| 1000/1000 [00:00<00:00, 5131.72 examples/s]
Map: 100%|██████████| 1000/1000 [00:00<00:00, 4987.91 examples/s]
(raylet) [2025-11-19 23:16:21,635 E 512 512] (raylet) main.cc:975: Failed to establish connection to the metrics exporter agent. Metrics will not be exported. Exporter agent status: RpcError: Running out of retries to initialize the metrics agent. rpc_code: 14
(RayTrainWorker pid=10544) Some weights of BertForSequenceClassification were not initialized from the model checkpoint at bert-base-cased and are newly initialized: ['classifier.bias', 'classifier.weight']
(RayTrainWorker pid=10544) You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
(pid=643) [2025-11-19 23:16:25,410 E 643 1019] core_worker_process.cc:825: Failed to establish connection to the metrics exporter agent. Metrics will not be exported. Exporter agent status: RpcError: Running out of retries to initialize the metrics agent. rpc_code: 14
(RayTrainWorker pid=10545) ============================= HPU PT BRIDGE CONFIGURATION ON RANK = 0 =============
(RayTrainWorker pid=10545) PT_HPU_LAZY_MODE = 1
(RayTrainWorker pid=10545) PT_HPU_RECIPE_CACHE_CONFIG = ,false,1024,false
(RayTrainWorker pid=10545) PT_HPU_MAX_COMPOUND_OP_SIZE = 9223372036854775807
(RayTrainWorker pid=10545) PT_HPU_LAZY_ACC_PAR_MODE = 1
(RayTrainWorker pid=10545) PT_HPU_ENABLE_REFINE_DYNAMIC_SHAPES = 0
(RayTrainWorker pid=10545) PT_HPU_EAGER_PIPELINE_ENABLE = 1
(RayTrainWorker pid=10545) PT_HPU_EAGER_COLLECTIVE_PIPELINE_ENABLE = 1
(RayTrainWorker pid=10545) PT_HPU_ENABLE_LAZY_COLLECTIVES = 0
(RayTrainWorker pid=10545) ---------------------------: System Configuration :---------------------------
(RayTrainWorker pid=10545) Num CPU Cores : 160
(RayTrainWorker pid=10545) CPU RAM : 1007 GB
(RayTrainWorker pid=10545) ------------------------------------------------------------------------------
(RayTrainWorker pid=10544) 0 COPY_FREE_VARS 1 [repeated 3x across cluster] (Ray deduplicates logs by default. Set RAY_DEDUP_LOGS=0 to disable log deduplication, or see https://docs.ray.io/en/master/ray-observability/user-guides/configure-logging.html#log-deduplication for more options.)
(RayTrainWorker pid=10544) 7 2 RESUME 0 [repeated 3x across cluster]
(RayTrainWorker pid=10544) 8 4 PUSH_NULL [repeated 3x across cluster]
(RayTrainWorker pid=10544) 6 LOAD_DEREF 1 (tokenizer) [repeated 3x across cluster]
(RayTrainWorker pid=10544) 8 LOAD_FAST 0 (examples) [repeated 3x across cluster]
(RayTrainWorker pid=10544) 10 LOAD_CONST 1 ('text') [repeated 3x across cluster]
(RayTrainWorker pid=10544) 12 BINARY_SUBSCR [repeated 3x across cluster]
(RayTrainWorker pid=10544) 16 LOAD_CONST 2 ('max_length') [repeated 3x across cluster]
(RayTrainWorker pid=10544) 18 LOAD_CONST 3 (True) [repeated 3x across cluster]
(RayTrainWorker pid=10544) 20 KW_NAMES 4 (('padding', 'truncation')) [repeated 3x across cluster]
(RayTrainWorker pid=10544) 22 CALL 3 [repeated 3x across cluster]
(RayTrainWorker pid=10544) 30 RETURN_VALUE [repeated 3x across cluster]
Map: 0%| | 0/1000 [00:00<?, ? examples/s] [repeated 3x across cluster]
Map: 100%|██████████| 1000/1000 [00:00<00:00, 4248.34 examples/s] [repeated 2x across cluster]
[2025-11-19 23:16:26,744 E 58 639] core_worker_process.cc:825: Failed to establish connection to the metrics exporter agent. Metrics will not be exported. Exporter agent status: RpcError: Running out of retries to initialize the metrics agent. rpc_code: 14
(RayTrainWorker pid=10545) Some weights of BertForSequenceClassification were not initialized from the model checkpoint at bert-base-cased and are newly initialized: ['classifier.bias', 'classifier.weight']
(RayTrainWorker pid=10545) You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
(RayTrainWorker pid=10544) train epoch:[0] loss:1.583929
(TrainController pid=10091) [2025-11-19 23:16:29,533 E 10091 10131] core_worker_process.cc:825: Failed to establish connection to the metrics exporter agent. Metrics will not be exported. Exporter agent status: RpcError: Running out of retries to initialize the metrics agent. rpc_code: 14 [repeated 157x across cluster]
(RayTrainWorker pid=10544) train epoch:[0] loss:2.180594 [repeated 74x across cluster]
(bundle_reservation_check_func pid=10360) [2025-11-19 23:16:36,047 E 10360 10479] core_worker_process.cc:825: Failed to establish connection to the metrics exporter agent. Metrics will not be exported. Exporter agent status: RpcError: Running out of retries to initialize the metrics agent. rpc_code: 14
(SynchronizationActor pid=10543) [2025-11-19 23:16:38,931 E 10543 10733] core_worker_process.cc:825: Failed to establish connection to the metrics exporter agent. Metrics will not be exported. Exporter agent status: RpcError: Running out of retries to initialize the metrics agent. rpc_code: 14
(RayTrainWorker pid=10544) train epoch:[0] loss:1.495260 [repeated 175x across cluster]
(RayTrainWorker pid=10545) [2025-11-19 23:16:38,930 E 10545 10685] core_worker_process.cc:825: Failed to establish connection to the metrics exporter agent. Metrics will not be exported. Exporter agent status: RpcError: Running out of retries to initialize the metrics agent. rpc_code: 14 [repeated 2x across cluster]
(RayTrainWorker pid=10544) train epoch:[0] loss:0.998758 [repeated 170x across cluster]
(RayTrainWorker pid=10544) train epoch:[1] loss:1.170934 [repeated 82x across cluster]
(RayTrainWorker pid=10544) train epoch:[1] loss:1.383039 [repeated 160x across cluster]
(RayTrainWorker pid=10544) train epoch:[1] loss:1.847730 [repeated 166x across cluster]
(RayTrainWorker pid=10544) train epoch:[1] loss:0.685345 [repeated 157x across cluster]
(RayTrainWorker pid=10544) train epoch:[2] loss:1.127744 [repeated 16x across cluster]
(RayTrainWorker pid=10544) train epoch:[2] loss:0.922426 [repeated 162x across cluster]
(RayTrainWorker pid=10544) train epoch:[2] loss:0.439891 [repeated 166x across cluster]
(RayTrainWorker pid=10544) train epoch:[2] loss:1.158258 [repeated 170x across cluster]
(RayTrainWorker pid=10545) train epoch:[3] loss:1.002946 [repeated 7x across cluster]
(RayTrainWorker pid=10544) train epoch:[3] loss:0.846594 [repeated 174x across cluster]
(RayTrainWorker pid=10544) train epoch:[3] loss:0.873339 [repeated 184x across cluster]
(RayTrainWorker pid=10545) train epoch:[4] loss:0.574767 [repeated 137x across cluster]
(RayTrainWorker pid=10544) train epoch:[4] loss:0.589236 [repeated 159x across cluster]
(RayTrainWorker pid=10544) train epoch:[4] loss:0.984469 [repeated 190x across cluster]
(RayTrainWorker pid=10545) train epoch:[5] loss:1.293336 [repeated 152x across cluster]
(RayTrainWorker pid=10544) train epoch:[5] loss:0.899560 [repeated 157x across cluster]
(RayTrainWorker pid=10544) train epoch:[5] loss:1.185992 [repeated 191x across cluster]
(RayTrainWorker pid=10545) train epoch:[6] loss:1.616954 [repeated 152x across cluster]
(RayTrainWorker pid=10544) train epoch:[6] loss:0.527374 [repeated 151x across cluster]
(RayTrainWorker pid=10544) train epoch:[6] loss:0.891688 [repeated 190x across cluster]
(RayTrainWorker pid=10544) train epoch:[6] loss:1.358030 [repeated 155x across cluster]
(RayTrainWorker pid=10544) train epoch:[7] loss:0.663066 [repeated 40x across cluster]
(RayTrainWorker pid=10544) train epoch:[7] loss:0.988223 [repeated 190x across cluster]
(RayTrainWorker pid=10544) train epoch:[7] loss:1.528751 [repeated 190x across cluster]
(RayTrainWorker pid=10545) train epoch:[8] loss:1.561732 [repeated 83x across cluster]
(RayTrainWorker pid=10544) train epoch:[8] loss:1.444829 [repeated 153x across cluster]
(RayTrainWorker pid=10544) train epoch:[8] loss:0.417297 [repeated 190x across cluster]
(RayTrainWorker pid=10544) train epoch:[8] loss:1.656665 [repeated 155x across cluster]
(RayTrainWorker pid=10544) train epoch:[9] loss:2.175095 [repeated 40x across cluster]
(RayTrainWorker pid=10544) train epoch:[9] loss:3.506782 [repeated 188x across cluster]
(RayTrainWorker pid=10544) train epoch:[9] loss:1.975726 [repeated 190x across cluster]
Training result: Result(metrics=None, checkpoint=None, error=None, path='/root/ray_results/ray_train_run-2025-11-19_23-15-56', metrics_dataframe=None, best_checkpoints=[], _storage_filesystem=<pyarrow._fs.LocalFileSystem object at 0x7fb5c2e3fdb0>)