End-to-End Pipeline for Entity Recognition with ModernBERT on Databricks
This notebook provides a complete pipeline for training an entity recognition model using ModernBERT, with data loaded from S3 using PySpark and model tracking via MLflow on Databricks.
# Entity Recognition Pipeline with ModernBERT
# For Databricks Runtime with ML
import os
import numpy as np
import pandas as pd
import mlflow
import torch
from torch.utils.data import Dataset, DataLoader
from transformers import (
AutoTokenizer,
AutoModelForTokenClassification,
TrainingArguments,
Trainer,
DataCollatorForTokenClassification
)
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
from pyspark.sql import SparkSession
import logging
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# Initialize Spark session
spark = SparkSession.builder.appName("EntityRecognitionPipeline").getOrCreate()
logger.info("Spark session initialized")
# Configuration parameters
CONFIG = {
"s3_data_path": "s3://your-bucket/path/to/conll/data/",
"model_name": "bert-base-cased", # or your specific ModernBERT variant
"max_length": 128,
"batch_size": 16,
"learning_rate": 2e-5,
"epochs": 3,
"weight_decay": 0.01,
"mlflow_experiment": "/Shared/entity-recognition-experiments"
}
# Set MLflow experiment
mlflow.set_experiment(CONFIG["mlflow_experiment"])
Step 1: Load and Process CoNLL Data from S3
def load_conll_data_from_s3(s3_path):
"""
Load CoNLL formatted data from S3 using PySpark
"""
logger.info(f"Loading data from {s3_path}")
# Read the raw text files from S3
raw_data = spark.read.text(s3_path)
# Collect to driver for processing (assuming the dataset fits in memory)
# For very large datasets, consider processing in a distributed manner
raw_text = "\n".join([row.value for row in raw_data.collect()])
# Parse CoNLL format
sentences = []
tags = []
current_sentence = []
current_tags = []
for line in raw_text.split('\n'):
line = line.strip()
if line == "":
if current_sentence:
sentences.append(current_sentence)
tags.append(current_tags)
current_sentence = []
current_tags = []
else:
parts = line.split()
if len(parts) >= 2: # Ensure there's at least a token and a tag
token = parts[0]
tag = parts[-1] # Assuming the tag is the last column
current_sentence.append(token)
current_tags.append(tag)
# Add the last sentence if it exists
if current_sentence:
sentences.append(current_sentence)
tags.append(current_tags)
logger.info(f"Loaded {len(sentences)} sentences")
return sentences, tags
def create_tag_mapping(tags_list):
"""
Create mapping between tags and IDs
"""
unique_tags = set()
for tags in tags_list:
unique_tags.update(tags)
tag2id = {tag: i for i, tag in enumerate(sorted(unique_tags))}
id2tag = {i: tag for tag, i in tag2id.items()}
logger.info(f"Created tag mapping with {len(tag2id)} unique tags")
return tag2id, id2tag
# Load the data
train_sentences, train_tags = load_conll_data_from_s3(f"{CONFIG['s3_data_path']}train/")
val_sentences, val_tags = load_conll_data_from_s3(f"{CONFIG['s3_data_path']}dev/")
test_sentences, test_tags = load_conll_data_from_s3(f"{CONFIG['s3_data_path']}test/")
# Create tag mapping
tag2id, id2tag = create_tag_mapping(train_tags + val_tags + test_tags)
Step 2: Create Dataset and DataLoader
class NERDataset(Dataset):
def __init__(self, sentences, tags, tokenizer, tag2id, max_length):
self.sentences = sentences
self.tags = tags
self.tokenizer = tokenizer
self.tag2id = tag2id
self.max_length = max_length
def __len__(self):
return len(self.sentences)
def __getitem__(self, idx):
sentence = self.sentences[idx]
tags = self.tags[idx]
# Tokenize the sentence
encoding = self.tokenizer(
sentence,
is_split_into_words=True,
padding='max_length',
truncation=True,
max_length=self.max_length,
return_tensors='pt'
)
# Remove batch dimension added by tokenizer
input_ids = encoding['input_ids'].squeeze()
attention_mask = encoding['attention_mask'].squeeze()
# Create token type IDs if needed
token_type_ids = encoding.get('token_type_ids', torch.zeros_like(input_ids)).squeeze()
# Align tags with wordpiece tokens
word_ids = encoding.word_ids()
label_ids = torch.ones(self.max_length, dtype=torch.long) * -100 # -100 is ignored in loss
for i, word_idx in enumerate(word_ids):
if word_idx is not None:
# Use the tag of the first wordpiece token of each word
if i > 0 and word_ids[i-1] == word_idx:
continue
label_ids[i] = self.tag2id[tags[word_idx]]
return {
'input_ids': input_ids,
'attention_mask': attention_mask,
'token_type_ids': token_type_ids,
'labels': label_ids
}
# Initialize tokenizer
tokenizer = AutoTokenizer.from_pretrained(CONFIG["model_name"])
# Create datasets
train_dataset = NERDataset(train_sentences, train_tags, tokenizer, tag2id, CONFIG["max_length"])
val_dataset = NERDataset(val_sentences, val_tags, tokenizer, tag2id, CONFIG["max_length"])
test_dataset = NERDataset(test_sentences, test_tags, tokenizer, tag2id, CONFIG["max_length"])
logger.info("Created datasets for training, validation, and testing")
Step 3: Define Model and Training Configuration
def compute_metrics(pred):
"""
Compute metrics for evaluation
"""
predictions, labels = pred
predictions = np.argmax(predictions, axis=2)
# Remove ignored index (special tokens)
true_predictions = [
[id2tag[p] for (p, l) in zip(prediction, label) if l != -100]
for prediction, label in zip(predictions, labels)
]
true_labels = [
[id2tag[l] for (p, l) in zip(prediction, label) if l != -100]
for prediction, label in zip(predictions, labels)
]
# Flatten the predictions and labels
flat_predictions = [p for sublist in true_predictions for p in sublist]
flat_labels = [l for sublist in true_labels for l in sublist]
# Calculate metrics
accuracy = accuracy_score(flat_labels, flat_predictions)
precision, recall, f1, _ = precision_recall_fscore_support(
flat_labels, flat_predictions, average='weighted'
)
return {
'accuracy': accuracy,
'precision': precision,
'recall': recall,
'f1': f1
}
# Initialize model
model = AutoModelForTokenClassification.from_pretrained(
CONFIG["model_name"],
num_labels=len(tag2id)
)
# Define training arguments
training_args = TrainingArguments(
output_dir="./results",
evaluation_strategy="epoch",
learning_rate=CONFIG["learning_rate"],
per_device_train_batch_size=CONFIG["batch_size"],
per_device_eval_batch_size=CONFIG["batch_size"],
num_train_epochs=CONFIG["epochs"],
weight_decay=CONFIG["weight_decay"],
save_strategy="epoch",
load_best_model_at_end=True,
metric_for_best_model="f1",
report_to="mlflow",
)
# Data collator
data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer)
# Initialize trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=val_dataset,
tokenizer=tokenizer,
data_collator=data_collator,
compute_metrics=compute_metrics,
)
logger.info("Model and trainer initialized")
Step 4: Train and Evaluate the Model with MLflow Tracking
# Start MLflow run
with mlflow.start_run() as run:
# Log parameters
mlflow.log_params({
"model_name": CONFIG["model_name"],
"max_length": CONFIG["max_length"],
"batch_size": CONFIG["batch_size"],
"learning_rate": CONFIG["learning_rate"],
"epochs": CONFIG["epochs"],
"weight_decay": CONFIG["weight_decay"],
"num_labels": len(tag2id)
})
# Log tag mapping
mlflow.log_dict(tag2id, "tag2id.json")
mlflow.log_dict(id2tag, "id2tag.json")
# Train the model
logger.info("Starting model training")
trainer.train()
# Evaluate on validation set
logger.info("Evaluating on validation set")
val_results = trainer.evaluate()
# Evaluate on test set
logger.info("Evaluating on test set")
test_results = trainer.predict(test_dataset)
test_metrics = test_results.metrics
# Log metrics
mlflow.log_metrics({
"val_loss": val_results["eval_loss"],
"val_accuracy": val_results["eval_accuracy"],
"val_f1": val_results["eval_f1"],
"val_precision": val_results["eval_precision"],
"val_recall": val_results["eval_recall"],
"test_loss": test_metrics["test_loss"],
"test_accuracy": test_metrics["test_accuracy"],
"test_f1": test_metrics["test_f1"],
"test_precision": test_metrics["test_precision"],
"test_recall": test_metrics["test_recall"]
})
# Save the model with MLflow
logger.info("Saving model to MLflow")
mlflow.transformers.log_model(
transformers_model={
"model": model,
"tokenizer": tokenizer
},
artifact_path="ner_model",
task="token-classification",
registered_model_name="modernbert-ner"
)
# Log a sample prediction
sample_text = train_sentences[0]
inputs = tokenizer(sample_text, is_split_into_words=True, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
predictions = torch.argmax(outputs.logits, dim=2)
predicted_tags = [id2tag[t.item()] for t in predictions[0] if t.item() in id2tag]
sample_result = {
"tokens": sample_text,
"predicted_tags": predicted_tags[:len(sample_text)]
}
mlflow.log_dict(sample_result, "sample_prediction.json")
logger.info(f"Training completed. Run ID: {run.info.run_id}")
Step 5: Register the Model to MLflow Model Registry
# Register the model to MLflow Model Registry
client = mlflow.tracking.MlflowClient()
model_uri = f"runs:/{run.info.run_id}/ner_model"
# Register the model
model_details = mlflow.register_model(
model_uri=model_uri,
name="modernbert-ner"
)
logger.info(f"Model registered with version {model_details.version}")
# Add model description
client.update_model_version(
name="modernbert-ner",
version=model_details.version,
description="Entity Recognition model based on ModernBERT, trained on CoNLL data"
)
# Transition the model to Production if it's the best model
# In a real scenario, you might want to add validation steps before promoting to production
client.transition_model_version_stage(
name="modernbert-ner",
version=model_details.version,
stage="Production"
)
logger.info(f"Model version {model_details.version} transitioned to Production")
Step 6: Create a Simple Inference Function
def create_inference_function():
"""
Create and save an inference function that can be used for batch predictions
"""
def predict_entities(texts):
"""
Predict entities in a list of texts
Args:
texts: List of texts or list of lists of tokens
Returns:
List of dictionaries with tokens and their predicted tags
"""
results = []
for text in texts:
is_tokenized = isinstance(text, list)
# Tokenize if needed
if is_tokenized:
tokens = text
inputs = tokenizer(tokens, is_split_into_words=True, return_tensors="pt")
else:
inputs = tokenizer(text, return_tensors="pt")
tokens = tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
# Get predictions
with torch.no_grad():
outputs = model(**inputs)
predictions = torch.argmax(outputs.logits, dim=2)[0].tolist()
# Convert IDs to tags and align with tokens
predicted_tags = []
for i, pred_id in enumerate(predictions):
if inputs["attention_mask"][0][i] == 1: # Skip padding tokens
if pred_id in id2tag:
tag = id2tag[pred_id]
if tag != "O": # Only include non-O tags
token = tokens[i]
if token.startswith("##"): # Handle wordpiece tokens
token = token[2:]
predicted_tags.append({
"token": token,
"tag": tag,
"position": i
})
results.append({
"text": text,
"entities": predicted_tags
})
return results
# Save the function with the model
with open("predict_entities.py", "w") as f:
f.write(inspect.getsource(predict_entities))
mlflow.log_artifact("predict_entities.py", "inference")
return predict_entities
# Create and test the inference function
import inspect
predict_fn = create_inference_function()
# Test the function
test_texts = [
"John Smith works at Microsoft in Seattle.",
["EU", "rejects", "German", "call", "to", "boycott", "British", "lamb", "."]
]
predictions = predict_fn(test_texts)
# Log the test predictions
mlflow.log_