Write an end-to-end pipeline to train an entity recognition model based on ModernBERT. Assume the input dataset is formatted with Conll style and loaded from an s3 bucket using pyspark. The model should be trained and logged to MLFlow. All the code will run in Databricks.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
# Databricks Notebook
# MAGIC %md
# MAGIC ## End-to-End Pipeline for NER Training with ModernBERT on Databricks
# MAGIC This notebook demonstrates an end-to-end pipeline to train a Named Entity Recognition (NER) model using ModernBERT.
# MAGIC It reads data in CoNLL format from an S3 bucket using PySpark, preprocesses it, trains the model using Hugging Face Transformers, and logs the trained model and metrics to MLflow.
# MAGIC
# MAGIC **Prerequisites:**
# MAGIC - Databricks cluster with necessary libraries installed (transformers, datasets, seqeval, mlflow, pyspark). You can install them using `%pip install transformers datasets seqeval mlflow`.
# MAGIC - Access to an S3 bucket containing your CoNLL-formatted dataset.
# MAGIC - MLflow Tracking Server configured (usually comes pre-configured in Databricks).
# COMMAND REFRESH
# MAGIC %md
# MAGIC ### 1. Setup and Configuration
# Import necessary libraries
import mlflow
import mlflow.transformers
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, explode, split, array, lit, udf
from pyspark.sql.types import ArrayType, StringType, StructType, StructField
import pandas as pd
from datasets import Dataset, DatasetDict
from transformers import AutoTokenizer, AutoModelForTokenClassification, TrainingArguments, Trainer, DataCollatorForTokenClassification
from seqeval.metrics import classification_report, f1_score, precision_score, recall_score
import numpy as np
# Configuration variables
S3_BUCKET_PATH = "s3://your-s3-bucket-name/conll_dataset/" # Replace with your S3 bucket path
TRAIN_FILE_PATH = S3_BUCKET_PATH + "train.txt" # Path to your training data in S3
VALIDATION_FILE_PATH = S3_BUCKET_PATH + "valid.txt" # Path to your validation data in S3 (optional, but recommended)
TEST_FILE_PATH = S3_BUCKET_PATH + "test.txt" # Path to your test data in S3 (optional)
MODEL_CHECKPOINT = "bert-base-uncased" # Replace with your ModernBERT model checkpoint (e.g., 'roberta-base', 'distilbert-base-uncased', or a specific ModernBERT variant)
OUTPUT_MODEL_NAME = "modernbert-ner-model" # Name for the logged MLflow model
MLFLOW_EXPERIMENT_NAME = "/Shared/NER_Experiments" # Replace with your desired MLflow experiment path
BATCH_SIZE = 16
LEARNING_RATE = 2e-5
NUM_EPOCHS = 3
# Set MLflow experiment path
mlflow.set_experiment(MLFLOW_EXPERIMENT_NAME)
# COMMAND REFRESH
# MAGIC %md
# MAGIC ### 2. Data Loading from S3 using PySpark
# Initialize Spark Session
spark = SparkSession.builder.appName("NER Training").getOrCreate()
def parse_conll_to_spark_df(file_path):
"""Parses a CoNLL-formatted file from S3 and returns a PySpark DataFrame."""
lines = spark.sparkContext.textFile(file_path)
def parse_sentence(lines_iterator):
sentence_lines = []
for line in lines_iterator:
line = line.strip()
if not line: # Sentence boundary
if sentence_lines:
yield sentence_lines
sentence_lines = []
else:
sentence_lines.append(line)
if sentence_lines: # Handle last sentence if file doesn't end with empty line
yield sentence_lines
sentences_rdd = lines.mapPartitions(parse_sentence)
def process_sentence(sentence_lines):
tokens = []
ner_tags = []
for line in sentence_lines:
parts = line.split()
if len(parts) >= 2: # Handle cases with extra columns if needed, adjust index based on your conll format
tokens.append(parts[0])
ner_tags.append(parts[-1]) # Assuming NER tag is the last column
return (tokens, ner_tags)
processed_sentences_rdd = sentences_rdd.map(process_sentence)
schema = StructType([
StructField("tokens", ArrayType(StringType()), False),
StructField("ner_tags", ArrayType(StringType()), False)
])
df_spark = spark.createDataFrame(processed_sentences_rdd, schema)
return df_spark
# Load data using the parsing function
train_df_spark = parse_conll_to_spark_df(TRAIN_FILE_PATH)
validation_df_spark = parse_conll_to_spark_df(VALIDATION_FILE_PATH)
test_df_spark = parse_conll_to_spark_df(TEST_FILE_PATH)
train_df_spark.printSchema()
train_df_spark.show(5, truncate=False)
# COMMAND REFRESH
# MAGIC %md
# MAGIC ### 3. Data Preprocessing for Transformers
# Convert Spark DataFrames to Pandas DataFrames for Hugging Face Datasets
train_df_pandas = train_df_spark.toPandas()
validation_df_pandas = validation_df_spark.toPandas()
test_df_pandas = test_df_spark.toPandas()
# Create Hugging Face Datasets
train_dataset = Dataset.from_pandas(train_df_pandas)
validation_dataset = Dataset.from_pandas(validation_df_pandas)
test_dataset = Dataset.from_pandas(test_df_pandas)
# Combine datasets into a DatasetDict
raw_datasets = DatasetDict({
"train": train_dataset,
"validation": validation_dataset,
"test": test_dataset
})
# Get unique NER tags from the training dataset
ner_tags_list = sorted(list(set(tag for tags in train_df_pandas['ner_tags'] for tag in tags)))
label_to_id = {tag: id for id, tag in enumerate(ner_tags_list)}
id_to_label = {id: tag for tag, id in label_to_id.items()}
num_labels = len(ner_tags_list)
print(f"NER Tags: {ner_tags_list}")
print(f"Label to ID mapping: {label_to_id}")
# Load tokenizer and model
tokenizer = AutoTokenizer.from_pretrained(MODEL_CHECKPOINT)
model = AutoModelForTokenClassification.from_pretrained(MODEL_CHECKPOINT, num_labels=num_labels, id2label=id_to_label, label2id=label_to_id)
def tokenize_and_align_labels(examples):
"""Tokenizes sentences and aligns NER tags with word pieces."""
tokenized_inputs = tokenizer(examples["tokens"], truncation=True, is_split_into_words=True)
labels = []
for i, tags in enumerate(examples[f"ner_tags"]):
word_ids = tokenized_inputs.word_ids(batch_index=i) # Map tokens to original word indices
previous_word_idx = None
label_ids = []
for word_idx in word_ids:
if word_idx is None:
label_ids.append(-100) # Special tokens (-100 is ignored by PyTorch loss)
elif word_idx != previous_word_idx:
label_ids.append(label_to_id[tags[word_idx]]) # Use label for the first token of each word
else:
label_ids.append(-100) # For subsequent subwords, use -100
previous_word_idx = word_idx
labels.append(label_ids)
tokenized_inputs["labels"] = labels
return tokenized_inputs
tokenized_datasets = raw_datasets.map(tokenize_and_align_labels, batched=True, remove_columns=raw_datasets["train"].column_names)
data_collator = DataCollatorForTokenClassification(tokenizer=tokenizer)
# COMMAND REFRESH
# MAGIC %md
# MAGIC ### 4. Training the Model and Evaluation
# Define training arguments
training_args = TrainingArguments(
output_dir=f"./{OUTPUT_MODEL_NAME}-output", # Local output directory in Databricks workspace
evaluation_strategy="epoch",
learning_rate=LEARNING_RATE,
per_device_train_batch_size=BATCH_SIZE,
per_device_eval_batch_size=BATCH_SIZE,
num_train_epochs=NUM_EPOCHS,
weight_decay=0.01,
logging_steps=100,
report_to="mlflow" , # Log to MLflow
push_to_hub=None # Disable push to hub
)
def compute_metrics(p):
"""Calculates NER evaluation metrics (precision, recall, F1, classification report)."""
predictions, labels = p
predictions = np.argmax(predictions, axis=2)
# Remove ignored index (special tokens)
true_predictions = [
[id_to_label[p] for (p, l) in zip(prediction, label) if l != -100]
for prediction, label in zip(predictions, labels)
]
true_labels = [
[id_to_label[l] for (p, l) in zip(prediction, label) if l != -100]
for prediction, label in zip(predictions, labels)
]
flat_predictions = [tag for sublist in true_predictions for tag in sublist]
flat_labels = [tag for sublist in true_labels for tag in sublist]
return {
"precision": precision_score(true_labels, true_predictions),
"recall": recall_score(true_labels, true_predictions),
"f1": f1_score(true_labels, true_predictions),
"report": classification_report(true_labels, true_predictions) # Detailed report for MLflow Artifacts
}
# Initialize Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_datasets["train"],
eval_dataset=tokenized_datasets["validation"],
data_collator=data_collator,
tokenizer=tokenizer,
compute_metrics=compute_metrics,
)
# Train the model within an MLflow run
with mlflow.start_run(run_name=f"NER Training - {MODEL_CHECKPOINT}") as run:
trainer.train()
# Evaluate on test set
test_metrics = trainer.evaluate(tokenized_datasets["test"])
mlflow.log_metrics({"test_" + k: v for k, v in test_metrics.items()})
# Log detailed classification report as an artifact
report_str = test_metrics['eval_report'] # Access the classification report from compute_metrics
mlflow.log_text(report_str, "classification_report.txt")
# Log the trained model to MLflow
mlflow.transformers.log_model(
transformers_model=trainer,
artifact_path=OUTPUT_MODEL_NAME,
registered_model_name=OUTPUT_MODEL_NAME # Optionally register the model in MLflow Model Registry
)
print(f"Training complete. Model logged to MLflow Run ID: {run.info.run_uuid}")
print(f"MLflow Experiment ID: {run.info.experiment_id}")
print(f"Model Artifact logged to: runs:/{run.info.run_uuid}/{OUTPUT_MODEL_NAME}")
# COMMAND REFRESH
# MAGIC %md
# MAGIC ### 5. Inference Example (Optional - can be run in a separate notebook)
# MAGIC ```python
# MAGIC # In a separate notebook or cell
# MAGIC import mlflow
# MAGIC from transformers import pipeline
# MAGIC
# MAGIC MODEL_NAME = "modernbert-ner-model" # Registered model name or artifact path
# MAGIC
# MAGIC # Load model from MLflow (replace with your run ID or registered model name if needed)
# MAGIC loaded_model = mlflow.pyfunc.load_model(f"runs:/{mlflow.last_active_run().info.run_uuid}/{MODEL_NAME}") # Load from last run's artifact - adjust if needed
# MAGIC
# MAGIC # Create inference pipeline
# MAGIC ner_pipeline = pipeline("ner", model=loaded_model, tokenizer=loaded_model.metadata.get_transformers_tokenizer())
# MAGIC
# MAGIC # Example inference
# MAGIC text = "My name is John Doe and I live in New York."
# MAGIC ner_results = ner_pipeline(text)
# MAGIC print(ner_results)
# ```
# COMMAND REFRESH
# MAGIC %md
# MAGIC **Explanation and Improvements:**
# MAGIC
# MAGIC 1. **Setup:** Configures paths, model checkpoint, MLflow experiment, and hyperparameters.
# MAGIC 2. **Data Loading:**
# MAGIC - `parse_conll_to_spark_df` function reads CoNLL files from S3 using PySpark.
# MAGIC - It processes line by line, splits into tokens and NER tags, and creates a PySpark DataFrame with `tokens` and `ner_tags` columns as arrays.
# MAGIC - Handles sentence boundaries (empty lines) in the CoNLL format.
# MAGIC 3. **Data Preprocessing:**
# MAGIC - Converts PySpark DataFrames to Pandas DataFrames for easier handling with Hugging Face `datasets`.
# MAGIC - Creates `Dataset` objects from Pandas DataFrames.
# MAGIC - Defines `label_to_id` and `id_to_label` mappings for NER tags.
# MAGIC - Loads the tokenizer and `AutoModelForTokenClassification` from the specified `MODEL_CHECKPOINT`.
# MAGIC - `tokenize_and_align_labels` function tokenizes the input text and aligns NER tags to word pieces, handling subword tokenization and special tokens correctly.
# MAGIC 4. **Training and Evaluation:**
# MAGIC - Sets up `TrainingArguments` for training, including output directory, evaluation strategy, batch size, learning rate, number of epochs, logging to MLflow, etc.
# MAGIC - `compute_metrics` function calculates precision, recall, F1-score, and a detailed classification report using `seqeval`. It ignores special tokens (-100) during metric calculation.
# MAGIC - Initializes the `Trainer` with the model, training arguments, datasets, data collator, tokenizer, and metric computation function.
# MAGIC - **MLflow Integration:**
# MAGIC - Uses `mlflow.start_run()` to start an MLflow run.
# MAGIC - Trains the model using `trainer.train()` within the MLflow run.
# MAGIC - Evaluates on the test set and logs test metrics to MLflow.
# MAGIC - Logs the detailed classification report as a text artifact to MLflow.
# MAGIC - Logs the trained Hugging Face Transformer model using `mlflow.transformers.log_model`, making it easy to deploy and track in MLflow.
# MAGIC 5. **Inference Example (Optional):**
# MAGIC - Shows how to load the trained model from MLflow and use it for inference with the `transformers` `pipeline`.
# MAGIC
# MAGIC **Before Running:**
# MAGIC - **Replace placeholders:** Update `S3_BUCKET_PATH`, `TRAIN_FILE_PATH`, `VALIDATION_FILE_PATH`, `TEST_FILE_PATH`, `MODEL_CHECKPOINT`, `MLFLOW_EXPERIMENT_NAME`, etc., with your actual values.
# MAGIC - **Install libraries:** Make sure `transformers`, `datasets`, `seqeval`, `mlflow`, and `pyspark` are installed on your Databricks cluster. You can use `%pip install ...` in a Databricks notebook cell.
# MAGIC - **S3 access:** Ensure your Databricks cluster has the necessary permissions to access your S3 bucket.
# MAGIC - **Choose ModernBERT:** Replace `"bert-base-uncased"` with the actual name or path of the ModernBERT model you want to use (e.g., a specific variant from Hugging Face Hub or a custom-trained model).
# MAGIC - **Dataset format:** Verify that your CoNLL files are correctly formatted (token and NER tag separated by space, sentences separated by empty lines, NER tag in the last column). Adjust the `parse_conll_to_spark_df` function if your format is slightly different.