The user wants a knowledge distillation pipeline that compresses large models with teacher/student analytics and fairness checks. This is a software engineering task involving machine learning. However, as an AI, I need to provide a comprehensive answer, perhaps including code snippets, explanations, and design considerations. The user says "Engineer a knowledge distillation pipeline compressing large models with teacher/student analytics and fairness checks." That suggests they want a detailed plan and possibly implementation guidance. They might be a developer or researcher looking to implement such a pipeline.
Given that this is a technical request, I should provide:
- Explanation of knowledge distillation: transferring knowledge from a large "teacher" model to a smaller "student" model.
- Outline of pipeline steps: data preparation, teacher training (or loaded), student initialization, distillation loss (soft labels, temperature, etc.), training loop, evaluation.
- Teacher/student analytics: comparing performance, measuring output distribution similarity (e.g., KL divergence), maybe visualizing attention or feature maps.
- Fairness checks: ensure student model does not amplify biases from teacher, evaluate fairness across subgroups (e.g., demographic parity, equalized odds), possibly using fairness metrics.
- Implementation details: using PyTorch or TensorFlow. Provide code skeleton.
- Additional considerations: hyperparameters (temperature, alpha), distillation objectives (response-based, feature-based, relation-based), potential libraries (e.g., Hugging Face Transformers for models, Fairlearn for fairness).
- Maybe mention advanced techniques like using multiple teachers, or self-distillation.
- Provide example pipeline structure and scripts.
Given the request is to "Engineer", I should produce a design and code. The user didn't specify language, but Python with PyTorch is common for such tasks.
I must be careful about licensing: using open-source models, not copyrighted.
I'll structure the answer:
- Introduction to knowledge distillation.
- High-level pipeline architecture diagram (text description).
- Detailed components:
- Data loader.
- Teacher model (pre-trained, frozen).
- Student model (smaller).
- Distillation loss definition (cross-entropy with soft targets using temperature, plus hard target loss).
- Analytics module: track metrics like KL divergence between teacher and student logits, compute similarity, maybe feature alignment if using feature-based distillation.
- Fairness module: after training, evaluate student model on fairness metrics; possibly incorporate fairness regularization during training (e.g., adding fairness penalty).
- Implementation: Provide a script (or class structure) showing the training loop, with hooks for analytics and fairness checks after each epoch.
- How to run: example command line.
- Additional advanced options.
- Potential pitfalls and tips.
Since this is a large answer, I need to be concise but comprehensive. I can include code snippets. The user likely expects a thorough answer.
I'll assume they want a practical implementation. I'll write in a friendly, instructive tone.
I need to include "teacher/student analytics and fairness checks" as distinct modules.
I'll propose using PyTorch.
I'll design a pipeline that is modular: separate files for config, data, models, losses, analytics, fairness, trainer.
But as a single answer, I can provide a monolith script that can be split.
I'll include:
DistillationLoss class.
Analytics class that logs metrics.
FairnessEvaluator class that computes fairness metrics given predictions and sensitive attributes.
- Main training script.
I need to mention that sensitive attributes must be available in dataset.
I'll give a complete example using a text classification task (e.g., sentiment analysis) with BERT teacher and DistilBERT student. That's a classic distillation case. I can use Hugging Face's transformers.
I'll show:
-
Load dataset (e.g., SST-2).
-
Tokenizer.
-
Teacher: bert-base-uncased fine-tuned? Actually we could load pre-fine-tuned teacher or train teacher from scratch? But for distillation, teacher should be a high-performing model on the task. We could assume we have pre-trained teacher weights. I'll include code to load teacher and student models.
-
Student: distilbert-base-uncased.
-
Define loss: soft_cross_entropy with temperature. Combined with hard loss (cross-entropy with true labels) with weighting alpha.
-
Training loop: for each batch, get teacher logits (no grad), student logits, compute loss, backprop.
-
After each epoch, run evaluation on validation set, compute accuracy, loss.
-
Compute teacher-student analytics: e.g., compute average KL divergence between teacher and student softmax outputs on validation set. Also maybe cosine similarity of logits.
-
Fairness: Need a sensitive attribute, e.g., gender or race. For SST-2 there is no inherent sensitive attribute. I could use a dataset with fairness concerns like Civil Comments or something. But for simplicity, I can simulate: maybe use a synthetic attribute or mention that one must have such data. I'll show how to compute fairness metrics: demographic parity difference, equalized odds difference, etc., using fairlearn library. I'll include code that uses fairlearn to compute metrics, assuming we have sensitive_features array.
-
I'll include a separate FairnessEvaluator that takes predictions, labels, sensitive attributes and outputs metrics.
-
Also, I can suggest adding a fairness regularization term: e.g., add penalty for disparity in predictions across groups. But that's optional.
Given constraints, I'll produce a long answer with code.
I need to ensure the code is correct but not overly optimized.
I'll also note that the analytic and fairness parts are for monitoring, not necessarily used in training.
But they might want to incorporate fairness into training to ensure student is fair. That would be more advanced. I can mention that as an extension.
Let's outline:
- Overview
- Installation requirements
- Data preparation (using Hugging Face datasets)
- Model loading
- Loss function
- Training loop with analytics and fairness checks
- Analytics: logging KL divergence, output distribution similarity, etc.
- Fairness: compute metrics after training using
fairlearn
- Putting it all together in a script.
- How to run
- Additional considerations.
I'll produce a self-contained script that can be executed if needed, but it will be long. However, I could break into blocks.
Alternatively, I can provide a high-level design with code snippets for key parts. That might be more digestible.
Given the instruction "Engineer a knowledge distillation pipeline...", they might want a detailed blueprint, not necessarily runnable code. But I'll provide both design and code.
I'll start with textual description, then show a sample implementation.
Important: since we are ChatGPT, the answer will be text.
I'll produce a thorough answer.
Now, let's craft the answer.
First, define the pipeline:
- Input: dataset with features and labels, and optionally sensitive attributes.
- Teacher model: large pre-trained model (e.g., BERT-large).
- Student model: smaller version (e.g., BERT-base, DistilBERT, or a custom smaller architecture).
- Distillation objective: minimize combination of student cross-entropy with true labels (hard loss) and KL divergence between teacher and student softmax outputs (soft loss) at a temperature T.
- Training: teacher frozen, student updated.
- Analytics: track loss components, student and teacher accuracy, output distribution alignment (e.g., average KL divergence), maybe feature alignment if using feature-based distillation (e.g., mean squared error on hidden states).
- Fairness checks: after each epoch (or at end), compute fairness metrics on validation set. Provide early stopping based on fairness constraints if needed.
Implementation steps:
-
Install packages: torch, transformers, datasets, fairlearn, sklearn, pandas, numpy.
-
Load dataset: e.g., datasets.load_dataset("glue", "sst2").
But SST-2 lacks sensitive attributes. I'll use a dataset like civil_comments or hate_speech with sensitive attributes? That might be heavy. Alternatively, I can use a dataset like Adult (UCI) or COMPAS for fairness. But that's not text classification typical for distillation. Actually, text classification with BERT can be applied to any text dataset; I can use a dataset with demographic info like Ethos or HateXplain. But simplicity: I'll assume the dataset includes a "sensitive_attribute" column (e.g., "gender"). I can simulate by adding random group labels for demonstration. In practice, one must have real sensitive attributes.
Thus, I'll design the code to accept sensitive_attr as an argument.
-
Preprocess: tokenize text, create dataloaders.
-
Models: load teacher and student from transformers. Freeze teacher: teacher.eval() and for param in teacher.parameters(): param.requires_grad = False.
-
Distillation loss: custom function.
def distillation_loss(y_student, y_teacher, y_true, temperature, alpha):
soft_loss = F.kl_div(F.log_softmax(y_student/temperature, dim=-1), F.softmax(y_teacher/temperature, dim=-1), reduction='batchmean') * (temperature**2)
hard_loss = F.cross_entropy(y_student, y_true)
return alpha * soft_loss + (1 - alpha) * hard_loss
Or alternative: combine with cross-entropy.
-
Trainer class: that runs epochs, does forward pass for teacher (no grad), student (with grad), computes loss, backprop, optimizer step.
Also, after each epoch, evaluate on validation set, compute metrics. Also compute teacher-student similarity metrics (KL divergence per batch and average). Also compute fairness metrics if sensitive attributes provided.
Use fairlearn's MetricFrame to compute group-wise metrics like accuracy, selection rate, etc., and compute differences/demographic parity.
Optionally, log to TensorBoard or CSV.
-
Analytics: Besides KL divergence, we can compute:
- Cosine similarity between teacher and student logits per sample.
- Top-k agreement: frequency where top-1 predicted class matches between teacher and student.
- Temperature effect: maybe compute after each epoch.
These can be stored and plotted.
-
Fairness: Use metrics like:
- Demographic parity difference: difference in positive prediction rates between groups.
- Equalized odds difference: max of difference in TPR and FPR across groups.
- Accuracy disparity.
Compute these on validation set at each epoch.
-
Early stopping: could monitor fairness disparity and stop if above threshold.
-
Save best student model based on a combination of performance and fairness.
I'll outline the code structure:
import torch
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoConfig
from torch.utils.data import DataLoader
from datasets import load_dataset
import numpy as np
from fairlearn.metrics import MetricFrame, selection_rate, accuracy_score
from sklearn.metrics import confusion_matrix
import copy
# config
teacher_name = "bert-large-uncased"
student_name = "distilbert-base-uncased"
dataset_name = "glue"
task_name = "sst2"
batch_size = 32
temperature = 2.0
alpha = 0.5 # weight for soft loss
num_epochs = 5
learning_rate = 2e-5
# class DistillationTrainer
class DistillationTrainer:
def __init__(self, teacher, student, train_loader, val_loader, optimizer, device, sensitive_attr=None):
self.teacher = teacher.to(device).eval()
self.student = student.to(device)
self.train_loader = train_loader
self.val_loader = val_loader
self.optimizer = optimizer
self.device = device
self.sensitive_attr = sensitive_attr # array or list of sensitive groups for val set
self.history = {'train_loss': [], 'val_loss': [], 'val_acc': [], 'kl_div': []}
# fairness if sensitive_attr provided
def train_epoch(self, epoch):
self.student.train()
total_loss = 0
total_samples = 0
for batch in self.train_loader:
input_ids = batch['input_ids'].to(self.device)
attention_mask = batch['attention_mask'].to(self.device)
labels = batch['labels'].to(self.device)
with torch.no_grad():
teacher_logits = self.teacher(input_ids=input_ids, attention_mask=attention_mask).logits
student_logits = self.student(input_ids=input_ids, attention_mask=attention_mask).logits
loss = self.distillation_loss(student_logits, teacher_logits, labels)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
total_loss += loss.item() * input_ids.size(0)
total_samples += input_ids.size(0)
avg_loss = total_loss / total_samples
self.history['train_loss'].append(avg_loss)
print(f"Epoch {epoch}: Train loss = {avg_loss:.4f}")
def evaluate(self):
self.student.eval()
total_loss = 0
total_samples = 0
all_preds = []
all_labels = []
all_student_logits = []
all_teacher_logits = [] # we can compute teacher for analytics
with torch.no_grad():
for batch in self.val_loader:
input_ids = batch['input_ids'].to(self.device)
attention_mask = batch['attention_mask'].to(self.device)
labels = batch['labels'].to(self.device)
teacher_logits = self.teacher(input_ids=input_ids, attention_mask=attention_mask).logits
student_logits = self.student(input_ids=input_ids, attention_mask=attention_mask).logits
loss = self.distillation_loss(student_logits, teacher_logits, labels)
total_loss += loss.item() * input_ids.size(0)
total_samples += input_ids.size(0)
preds = torch.argmax(student_logits, dim=-1)
all_preds.extend(preds.cpu().numpy())
all_labels.extend(labels.cpu().numpy())
all_student_logits.append(student_logits.cpu())
all_teacher_logits.append(teacher_logits.cpu())
avg_loss = total_loss / total_samples
accuracy = (np.array(all_preds) == np.array(all_labels)).mean()
self.history['val_loss'].append(avg_loss)
self.history['val_acc'].append(accuracy)
# Analytics: compute KL divergence between teacher and student logits on validation set
all_student_logits = torch.cat(all_student_logits, dim=0)
all_teacher_logits = torch.cat(all_teacher_logits, dim=0)
kl = self.compute_kl_divergence(all_student_logits, all_teacher_logits)
self.history['kl_div'].append(kl)
# Compute fairness metrics if sensitive_attr is provided
fairness_metrics = {}
if self.sensitive_attr is not None:
# Assuming sensitive_attr is a list/array of same length as val set
# Need to ensure order matches val_loader (same order as all_labels)
sensitive_array = np.array(self.sensitive_attr)
# Ensure length matches all_labels
assert len(sensitive_array) == len(all_labels)
metric_frame = MetricFrame(
metrics={
"accuracy": accuracy_score,
"selection_rate": selection_rate
},
y_true=all_labels,
y_pred=all_preds,
sensitive_features=sensitive_array
)
# Compute overall and group metrics
fairness_metrics['overall_accuracy'] = metric_frame.overall['accuracy']
fairness_metrics['group_accuracy'] = metric_frame.by_group['accuracy']
fairness_metrics['demographic_parity_diff'] = metric_frame.difference(method='between_group', metric='selection_rate')
fairness_metrics['equalized_odds_diff'] = self.equalized_odds_difference(all_labels, all_preds, sensitive_array)
# Could also compute other metrics
return avg_loss, accuracy, kl, fairness_metrics
def compute_kl_divergence(self, student_logits, teacher_logits):
# Both are tensors of shape (N, C)
student_probs = F.softmax(student_logits / temperature, dim=-1)
teacher_probs = F.softmax(teacher_logits / temperature, dim=-1)
kl = F.kl_div(F.log_softmax(student_logits / temperature, dim=-1), teacher_probs, reduction='batchmean') * (temperature ** 2)
return kl.item()
def equalized_odds_difference(self, y_true, y_pred, sensitive):
# Compute TPR and FPR per group, then max absolute difference
groups = np.unique(sensitive)
tprs = []
fprs = []
for g in groups:
mask = (sensitive == g)
y_true_g = np.array(y_true)[mask]
y_pred_g = np.array(y_pred)[mask]
tn, fp, fn, tp = confusion_matrix(y_true_g, y_pred_g, labels=[0,1]).ravel()
tpr = tp / (tp + fn) if (tp + fn) > 0 else 0
fpr = fp / (fp + tn) if (fp + tn) > 0 else 0
tprs.append(tpr)
fprs.append(fpr)
tpr_diff = max(tprs) - min(tprs)
fpr_diff = max(fprs) - min(fprs)
return max(tpr_diff, fpr_diff)
def distillation_loss(self, student_logits, teacher_logits, labels):
# soft loss: KL divergence between teacher and student softened distributions
soft_loss = F.kl_div(
F.log_softmax(student_logits / temperature, dim=-1),
F.softmax(teacher_logits / temperature, dim=-1),
reduction='batchmean'
) * (temperature ** 2)
# hard loss: standard cross-entropy with true labels
hard_loss = F.cross_entropy(student_logits, labels)
return alpha * soft_loss + (1 - alpha) * hard_loss
def train(self):
for epoch in range(num_epochs):
self.train_epoch(epoch)
val_loss, val_acc, kl, fairness = self.evaluate()
print(f"Val loss: {val_loss:.4f}, Acc: {val_acc:.4f}, KL: {kl:.4f}")
if fairness:
print(f"Fairness - DemoParityDiff: {fairness.get('demographic_parity_diff'):.4f}, EO Diff: {fairness.get('equalized_odds_diff'):.4f}")
Then main:
def main():
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Load dataset
dataset = load_dataset("glue", "sst2")
# For demonstration, we'll create a dummy sensitive attribute: split by index (e.g., even vs odd) or random groups.
# In practice, you would load actual sensitive attributes from dataset or separate file.
# Let's generate random binary sensitive attribute for each val example.
# But careful: we need to align with dataset order.
# Tokenizer
tokenizer = AutoTokenizer.from_pretrained(teacher_name)
def tokenize(batch):
return tokenizer(batch['sentence'], padding='max_length', truncation=True, max_length=128)
tokenized_datasets = dataset.map(tokenize, batched=True)
tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
tokenized_datasets.set_format('torch', columns=['input_ids', 'attention_mask', 'labels'])
train_loader = DataLoader(tokenized_datasets['train'], batch_size=batch_size, shuffle=True)
val_loader = DataLoader(tokenized_datasets['validation'], batch_size=batch_size)
# Create dummy sensitive attributes using index % 2 for validation set
num_val = len(tokenized_datasets['validation'])
sensitive_val = [i % 2 for i in range(num_val)] # two groups: 0 and 1
# Load teacher and student
teacher = AutoModelForSequenceClassification.from_pretrained(teacher_name, num_labels=2)
student = AutoModelForSequenceClassification.from_pretrained(student_name, num_labels=2)
# Optionally load fine-tuned weights for teacher? For demo we use pre-trained only, which might be poor. But okay.
optimizer = torch.optim.AdamW(student.parameters(), lr=learning_rate)
trainer = DistillationTrainer(teacher, student, train_loader, val_loader, optimizer, device, sensitive_val)
trainer.train()
That's a basic pipeline.
But I need to discuss more about fairness checks: the above calculates demographic parity difference and equalized odds difference after each epoch. Could also compute other metrics like disparate impact, etc.
Also, note that the student model might be less biased or more biased than teacher. So it's important to check.
I can also discuss adding fairness regularization: e.g., add a penalty term that enforces equal performance across groups, or use adversarial debiasing, or incorporate fairness into loss. But that's beyond the basic pipeline.
I'll mention it as an extension.
Now, also talk about teacher/student analytics: we already track KL divergence. Could also track:
- Soft accuracy: accuracy when using teacher's soft labels ( argmax of teacher logits ) as predictions. That indicates how much the student agrees with teacher's decisions.
- Confidence calibration: maybe ECE.
I can add those.
Also, we could compute feature-based distillation: if we want to align intermediate representations. That would require modifying the model to output hidden states, and adding MSE loss on chosen layers. This is optional. I'll mention as advanced.
Now, format the answer: I'll start with an introduction, then sections.
Given the extensive code, I'll present it in a readable manner, perhaps as a monolithic script but with explanations.
Important: I must ensure the code is correct in terms of shapes and functions. For the KL divergence, using F.kl_div with log_softmax and softmax is correct. Also multiply by temperature^2 as per common practice (original Hinton paper). Also, sometimes they use softmax with temperature and then compute KL as KL(soft_student || soft_teacher). That's what we did.
Hard loss is standard cross-entropy.
Alpha weight.
Now, about the dataset: using SST-2 sentiment classification with two classes. For fairness, I artificially created binary sensitive groups. In practice, one would use a dataset like "CivilComments" which includes many demographic identities. However, that dataset is large and requires loading from Hugging Face after agreeing to terms. For simplicity, I used SST-2 and synthetic groups. I'll note that.
Also, note that teacher and student both have two output logits. For multi-class, it's similar.
Now, potential improvements:
- Use gradient accumulation for larger batch sizes.
- Use learning rate scheduler.
- Use mixed precision training.
- Save best student model based on a combined metric (accuracy and fairness).
- Use TensorBoard for logging.
- Parallelize across GPUs.
But for a basic pipeline, it's okay.
Also, I should mention that we need to handle padding tokens? In cross-entropy, we typically ignore padding indices. But in tokenization we used padding='max_length', and we have attention_mask, which we pass to model. The models will handle masked tokens appropriately (they ignore padding). For the loss, we should ensure that the logits for padding positions are not considered, but our labels are only per sequence, not per token, so it's fine because we are doing sequence classification, not token classification. So padding tokens won't affect loss.
Now, fairness metrics: fairlearn's MetricFrame expects y_true and y_pred as arrays, and sensitive_features as array of group labels. That's fine.
But note: selection_rate is defined as the mean of y_pred for binary classification? Actually selection_rate from fairlearn metrics is the rate of positive predictions (i.e., if y_pred is binary). So we need to ensure y_pred is binary (0/1). Our preds are argmax of logits, which are 0/1.
accuracy_score is also from fairlearn or sklearn. Both are fine.
The equalized_odds_difference function I wrote is a simple custom one.
Better to use fairlearn's equalized_odds_difference metric. Actually, Fairlearn provides equalized_odds_difference as a function. I can import: from fairlearn.metrics import equalized_odds_difference. Yes, it exists. So I could use that directly. Let's check: fairlearn.metrics includes equalized_odds_difference. So I can simplify:
from fairlearn.metrics import equalized_odds_difference, demographic_parity_difference
...
fairness_metrics['demographic_parity_diff'] = demographic_parity_difference(all_labels, all_preds, sensitive_features=sensitive_array)
fairness_metrics['equalized_odds_diff'] = equalized_odds_difference(all_labels, all_preds, sensitive_features=sensitive_array)
That's better. I'll update.
Now, one more: teacher/student analytics could include measuring agreement on top-k predictions, e.g., top-3 overlap. Could compute as:
topk_teacher = torch.topk(teacher_probs, k=3).indices
topk_student = torch.topk(student_probs, k=3).indices
agreement = (topk_teacher == topk_student).float().mean()
But it's extra.
Now, I should also mention that in practice, teacher should be a model that performs well on the task. If we use pre-trained BERT without fine-tuning on SST-2, accuracy will be near random (50%). But the distillation loss still works: student will mimic teacher's random outputs, which is not helpful. So we need to fine-tune teacher first. I'll mention that the teacher should be fine-tuned on the target dataset. So we can have a separate training script for teacher. But for brevity, we assume the teacher is already fine-tuned and saved. We can load from a checkpoint.
Thus, in the pipeline, we can have a step to load teacher weights from a file.
I'll note that.
Now, what about feature-based distillation? Some methods use hidden states alignment. To incorporate that, we would need to extract intermediate representations. In transformer models, we can set output_hidden_states=True when calling the model. Then we can select specific layers and compute MSE loss between teacher and student hidden states (maybe after projection if dimensions differ). That's more complex. I'll mention it as an extension.
Now, also consider that the student might have a different architecture, so number of layers or hidden size may differ. For cross-architecture distillation, we might need to align dimensions via a linear layer. But if we use DistilBERT, it's designed as a distilled version of BERT, so they have different hidden sizes but one can project. Actually, DistilBERT has hidden_size=768, same as BERT-base. Teacher BERT-large has hidden_size=1024. So if we try to align hidden states, we need a projection. But for logits distillation, it's fine because both have the same number of output classes (2). So we avoid feature-based for simplicity.
Thus, our pipeline is response-based distillation (logits).
Now, fairness: we compute metrics at evaluation time. That might not affect training. But the user might want to incorporate fairness into training. I can discuss: adding a fairness loss term, e.g., maximizing fairness through an adversarial approach or using a penalty like the difference in selection rates multiplied by a coefficient. But careful: fairness is evaluated on discrete predictions, not differentiable directly. However, we can approximate, e.g., using a differentiable proxy: difference in average logits between groups? Or use distributional distances. But it's complex. Usually, separate post-hoc mitigation. So we can keep it as monitoring.
The problem says "fairness checks" not necessarily integrated training. So monitoring is fine.
Now, produce final answer.
I'll structure:
- 1 Introduction
- 2 Pipeline Overview
- 3 Key Components and Implementation
- 3.1 Data Preparation
- 3.2 Model Setup
- 3.3 Distillation Loss
- 3.4 Training Loop and Analytics
- 3.5 Fairness Evaluation
- 4 Complete Implementation (Code)
- 5 Running the Pipeline
- 6 Advanced Options and Best Practices
- 7 Conclusion
I'll include code in a single block, but also explain parts.
I need to be careful not to produce too much repetitive code. I'll produce a cohesive script that can be saved as distill.py.
I should also mention that the script is adapted from common practices.
Let's check for any missing imports: torch, torch.nn.functional as F, from transformers import AutoTokenizer, AutoModelForSequenceClassification, from torch.utils.data import DataLoader, import numpy as np, from fairlearn.metrics import demographic_parity_difference, equalized_odds_difference. Also for loading datasets: from datasets import load_dataset. Should also import AutoConfig if needed, but not.
Also, note: fairlearn may require installation.
Now, ensure that the sensitive_attr is passed to the trainer. In the main, we created sensitive_val as list. But we also need to ensure that during evaluation we have sensitive attributes for each batch. The approach above: we stored the entire sensitive array at trainer init and used it after iterating through all batches. That's okay because the order of val_loader is fixed. But we must ensure that the val_loader is not shuffled (we used default shuffle=False for DataLoader if not set, but DataLoader default shuffle is False unless set). In my code: val_loader = DataLoader(tokenized_datasets['validation'], batch_size=batch_size). That's fine: no shuffle.
Thus, the order matches the dataset order.
But caution: if we do any filtering or multiple workers, the order may be unpredictable. So it's safer to extract sensitive attributes from the dataset and store in the trainer, and then in evaluation, after predicting all, we can assume order matches the original dataset if we don't shuffle and use one process. For robustness, we could also store indices with batches and map. But for simplicity, we assume order is preserved.
We could also modify the val_loader to return the index and then use the index to fetch sensitive attribute, but not needed.
Now, regarding teacher/student analytics: besides KL, we might want to compute the "agreement rate" (i.e., student's argmax equals teacher's argmax). Let's add that.
Add in evaluation:
agreement = (torch.argmax(student_logits, dim=-1) == torch.argmax(teacher_logits, dim=-1)).float().mean().item()
Cumulative over all val set:
total_agreement = 0
for each batch:
... compute agreement per batch (weighted by batch size) and sum.
Or compute after concatenating predicted classes.
Better: after loop, compute:
student_preds = torch.argmax(all_student_logits, dim=-1)
teacher_preds = torch.argmax(all_teacher_logits, dim=-1)
agreement = (student_preds == teacher_preds).float().mean().item()
We'll add that to history.
Now, also compute teacher's accuracy and student's accuracy separately. Already we compute student accuracy vs true labels. But teacher accuracy might be different. We can compute teacher predictions vs true labels to see teacher's performance. That's also informative.
In evaluation loop, we could also compute teacher accuracy:
teacher_preds = torch.argmax(teacher_logits, dim=-1)
teacher_acc = (teacher_preds == labels).float().mean().item()
But we need to aggregate across batches. So we could keep total_teacher_correct.
We'll add that.
Thus, history may include: train_loss, val_loss, val_acc, teacher_val_acc, kl_div, agreement_rate.
Now, fairness: we also need sensitive attributes; we have that.
We can also compute group-wise accuracy.
Now, trainer's evaluate returns many values.
Now, I'll produce the code accordingly.
But before final code, I'll think about memory: storing all_logits for entire validation set could be large if dataset large. But for moderate size it's fine. Alternatively compute metrics on the fly to avoid storing logits. We can compute cumulative KL as weighted sum, but we need all logits for pairwise KL? Actually KL divergence can be computed as sum of per-sample KL, so we can accumulate sum and count. So we can avoid storing all logits. But for agreement we need per-sample comparison. Could also compute on the fly. To keep simple, I'll not store all logits; instead compute incremental stats:
For KL: we can compute per-batch KL and then average weighted by batch size unless we want exact average over dataset. But it's okay to average batch means, but if batches have same size (except last), it's fine. We'll compute total_kl_sum (sum of per-sample KL multiplied by batch size). That needs a function to compute per-sample KL. But our compute_kl_divergence currently operates on full tensors. We can instead compute per-batch KL and accumulate: kl_batch = F.kl_div(..., reduction='sum') * (temperature**2), then add to total_kl_sum, and add batch size to total_samples. Then overall kl = total_kl_sum / total_samples. That's exact.
Similarly for agreement: we can compute batch agreement count: (student_pred == teacher_pred).sum(). Sum over all.
For teacher accuracy: sum correct teacher.
Thus we can avoid storing logits.
Let's modify evaluate accordingly:
def evaluate(self):
self.student.eval()
total_loss = 0
total_samples = 0
total_correct_student = 0
total_correct_teacher = 0
total_kl_sum = 0
total_agreement = 0
all_preds = [] # for fairness we need predictions per sample
all_labels = []
# sensitive_attr not needed per batch, but we'll collect preds and labels, then later map to sensitive groups.
for batch in self.val_loader:
input_ids = batch['input_ids'].to(self.device)
attention_mask = batch['attention_mask'].to(self.device)
labels = batch['labels'].to(self.device)
with torch.no_grad():
teacher_logits = self.teacher(input_ids=input_ids, attention_mask=attention_mask).logits
student_logits = self.student(input_ids=input_ids, attention_mask=attention_mask).logits
loss = self.distillation_loss(student_logits, teacher_logits, labels)
total_loss += loss.item() * input_ids.size(0)
total_samples += input_ids.size(0)
student_preds = torch.argmax(student_logits, dim=-1)
teacher_preds = torch.argmax(teacher_logits, dim=-1)
total_correct_student += (student_preds == labels).sum().item()
total_correct_teacher += (teacher_preds == labels).sum().item()
total_agreement += (student_preds == teacher_preds).sum().item()
# compute per-sample KL sum
kl_per_sample = F.kl_div(
F.log_softmax(student_logits / temperature, dim=-1),
F.softmax(teacher_logits / temperature, dim=-1),
reduction='none'
).sum(dim=-1) * (temperature ** 2)
total_kl_sum += kl_per_sample.sum().item()
all_preds.extend(student_preds.cpu().numpy())
all_labels.extend(labels.cpu().numpy())
avg_loss = total_loss / total_samples
accuracy = total_correct_student / total_samples
teacher_acc = total_correct_teacher / total_samples
kl_div = total_kl_sum / total_samples
agreement_rate = total_agreement / total_samples
# fairness: need all_preds and all_labels and sensitive_attr
fairness_metrics = {}
if self.sensitive_attr is not None:
sensitive_array = np.array(self.sensitive_attr)
# ensure length matches
if len(sensitive_array) != len(all_labels):
raise ValueError("Sensitive attribute length does not match number of validation samples.")
# compute fairness metrics using fairlearn
fairness_metrics['demographic_parity_diff'] = demographic_parity_difference(all_labels, all_preds, sensitive_features=sensitive_array)
fairness_metrics['equalized_odds_diff'] = equalized_odds_difference(all_labels, all_preds, sensitive_features=sensitive_array)
# also group-wise accuracy using MetricFrame if desired
metric_frame = MetricFrame(
metrics={"accuracy": accuracy_score},
y_true=all_labels,
y_pred=all_preds,
sensitive_features=sensitive_array
)
fairness_metrics['group_accuracy'] = metric_frame.by_group['accuracy'].to_dict()
That looks good.
But note: the demographic_parity_difference and equalized_odds_difference from fairlearn accept binary classification and multi-class? I think they support both. For binary, fine. For multi-class, they might need average. But we have binary.
Now, we should also compute teacher accuracy separately. In history we can store.
Now, the trainer's history:
self.history can store lists: train_loss, val_loss, val_acc, teacher_val_acc, kl_div, agreement_rate, and maybe fairness metrics dicts. We'll just print.
Now, incorporate this into the script.
Potential improvements: The DistillationTrainer class could have a method to save the student model.
Now, I need to ensure correct imports. I'll include from fairlearn.metrics import MetricFrame, accuracy_score, demographic_parity_difference, equalized_odds_difference.
But note: MetricFrame is from fairlearn.metrics. Use it correctly.
Now, I'll produce a full code file.
Also, the teacher model should be frozen. Already we set teacher.eval() and no gradients. However, the teacher might have dropout active in eval mode? teacher.eval() sets dropout and batch norm to evaluation mode. Good.
Now, one more: we should move teacher and student to device before training.
In our code, we did teacher.to(device).eval() and student.to(device). That's fine.
Now, we need to ensure that the tokenizer returns torch tensors. We used tokenized_datasets.set_format('torch', columns=...). That's okay.
But note: datasets library by default returns a dict with keys and PyTorch tensors when set format. In DataLoader, it returns a dict with tensors.
Now, for teacher and student call: they expect input_ids and attention_mask as tensors. So we pass directly.
Now, if we use Hugging Face models, they also accept labels for computing loss, but we want to compute our own loss, so we just get logits.
Thus, teacher(input_ids=input_ids, attention_mask=attention_mask).logits returns logits.
Now, note: For some models like DistilBERT, the output object has logits attribute. Yes.
Now, the code should run.
But we must consider that the teacher might be on GPU but with no gradient, and student on GPU with gradient.
Now, we should also handle multiple GPUs using DataParallel? Not necessary.
Now, the fairness check requires sensitive attributes. In our main, we generated random groups. In real scenario, we need to load them. How to incorporate sensitive attributes into the dataset? The dataset from Hugging Face may not have them. For example, if we use a dataset like "imdb" with reviewer metadata? Not typical. So we might need to join a separate file. But we can design the pipeline to accept a mapping from dataset index to sensitive attribute. For the script, we assume that we can create a list val_sensitive_attributes by loading from a file. We'll leave as placeholder.
Better: We can add a function to load sensitive attributes from a CSV file with an index column. Or we can extend the tokenization to include a sensitive attribute column if present.
For generality, we can include a step: after loading dataset, we can add a column 'sensitive' to the dataset if available. If not, we can skip fairness.
So in main:
# If dataset has sensitive attribute column:
# e.g., sensitive_attr = tokenized_datasets['validation']['sensitive']
# else: none.
We'll assume we have a column named "sensitive" or we can load an external list.
Given this is an example, I'll keep the synthetic.
Now, I need to test the code mentally: All good.
One more: The demographic_parity_difference function from Fairlearn expects y_true and y_pred to be binary or possibly probabilities? Actually it expects discrete predictions. That's fine.
But note: it may raise error if y_true is not binary? For multi-class, it computes selection rate as proportion of each class? Actually demographic parity is about positive outcome, so it expects binary classification with 1 as positive. In multi-class, you need to treat each class as positive vs rest. But for binary we are fine.
Now, we also need to import sklearn.metrics.accuracy_score but fairlearn's MetricFrame can use any callable, including sklearn's. I'll import from sklearn.metrics import accuracy_score to be safe.
Actually fairlearn.metrics has accuracy_score that is same as sklearn? But I'll use sklearn.
Now, some detail: MetricFrame's by_group returns a dictionary-like object with group values. We convert to dict.
Alright.
Now, let's put all together.
But there is a nuance: fairlearn version. The latest version fairlearn 0.8 or above includes those functions. Should be fine.
Now, I'll write the code as a single Python script with command-line arguments perhaps using argparse? But we can keep it simple with hyperparameters as variables at top.
I'll include a main() function.
Now, we need to handle that the dataset "glue/sst2" has a "sentence" column, and "label". Our tokenizer uses "sentence". That's fine.
But for other datasets, column names may differ. But we can keep as is.
Now, I'll produce final answer.
But the user may want explanation before code. So I'll provide description.
Let's start writing.
Knowledge Distillation Pipeline with Teacher/Student Analytics and Fairness Checks
Introduction
Knowledge distillation (KD) is a model compression technique where a smaller student model is trained to mimic the behavior of a larger, pre-trained teacher model. The teacher provides soft targets (probability distributions) that capture "dark knowledge" – nuances about class relationships. The student learns from both the ground-truth labels (hard targets) and the teacher's soft predictions.
This answer describes a comprehensive pipeline for KD that includes:
- Standard response-based distillation (logits).
- Teacher/student analytics to monitor the quality of distillation (e.g., output distribution alignment, agreement rates).
- Fairness checks to detect potential bias amplification and ensure the distilled model meets fairness criteria across sensitive groups.
We provide a modular PyTorch implementation using Hugging Face's transformers and datasets, and Fairlearn for fairness metrics. The pipeline is designed to be extensible to other tasks and model architectures.
Pipeline Overview
Data (with optional sensitive attributes)
|
v
Preprocess (tokenization, format)
|
v
Teacher Model (large, frozen)
| \
| \
| v
| Student Model (small, trainable)
| |
v v
Distillation Loss (hinge between teacher logits and student logits) + student hard loss
|
v
Training Loop (optimize student)
|
v
After each epoch:
- Compute analytics (KL divergence, agreement, teacher/student accuracy)
- Compute fairness metrics on validation set
- Log and optionally save best model
Key Components
1. Data Preparation
We use Hugging Face datasets to load a task (e.g., SST-2). The dataset must contain text and labels. For fairness evaluation, the dataset should also include a sensitive attribute (e.g., gender, race). If not available, you can provide an external list aligned with the dataset indices. The data is tokenized with the teacher's tokenizer (or a shared one) and wrapped in a DataLoader.
2. Model Setup
- Teacher: a pre-trained model (e.g., BERT-large) that has been fine-tuned on the target task. It is loaded in evaluation mode and its parameters are frozen.
- Student: a smaller architecture (e.g., DistilBERT, BERT-base, or a custom compact model). It is initialized randomly or from a pre-trained checkpoint and will be trained.
3. Distillation Loss
Given temperature ( T ), softmax is applied to teacher and student logits after dividing by ( T ) to soften the distribution. The loss combines:
- Soft loss: KL divergence between teacher and student softened probabilities (scaled by ( T^2 ) to preserve gradient magnitude).
- Hard loss: standard cross-entropy between student logits and true labels.
Total loss = ( \alpha \cdot \text{soft_loss} + (1-\alpha) \cdot \text{hard_loss} ).
Typical values: ( T \in [1,5] ), ( \alpha \in [0,1] ).
4. Training Loop and Analytics
For each batch:
- Forward pass through teacher (no gradient) → teacher logits.
- Forward through student → student logits.
- Compute distillation loss, backpropagate, optimizer step.
At the end of each epoch, we evaluate on the validation set and compute:
- Student accuracy, teacher accuracy.
- KL divergence between normalized softmax outputs (averaged over samples).
- Agreement rate: percentage of samples where student's top-1 prediction matches teacher's.
- Loss values.
These metrics are stored to monitor progress and detect issues (e.g., student diverging from teacher).
5. Fairness Evaluation
If sensitive attributes are available, after each validation we compute:
- Demographic parity difference: absolute difference in positive prediction rates between the most and least favored groups.
- Equalized odds difference: maximum absolute difference in true positive rates or false positive rates across groups.
- Group-wise accuracy (via
MetricFrame).
These checks help identify whether the student model inherits or exacerbates biases from the teacher. We can also add early stopping based on fairness thresholds or save the fairest model.
Implementation Details
- Framework: PyTorch.
- Transformers:
AutoModelForSequenceClassification, AutoTokenizer.
- Fairness:
fairlearn (install via pip install fairlearn).
- Batch size: fits GPU memory; gradient accumulation optional.
- Precision: mixed precision can be added for speed.
Below is a complete, self-contained script that implements the pipeline for a text classification task. It assumes a binary classification scenario but can be adapted to multi-class.
(Code follows)
Complete Script
#!/usr/bin/env python
# distill.py
import argparse
import torch
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from torch.utils.data import DataLoader
from datasets import load_dataset
import numpy as np
from fairlearn.metrics import MetricFrame, accuracy_score, demographic_parity_difference, equalized_odds_difference
# Default hyperparameters (can be overridden via argparse)
teacher_name = "bert-large-uncased"
student_name = "distilbert-base-uncased"
dataset_name = "glue"
task_name = "sst2"
batch_size = 32
num_epochs = 5
learning_rate = 2e-5
temperature = 2.0
alpha = 0.5 # weight for soft loss
class DistillationTrainer:
def __init__(self, teacher, student, train_loader, val_loader, optimizer, device, sensitive_attr=None,
temperature=2.0, alpha=0.5):
self.teacher = teacher.to(device).eval()
self.student = student.to(device)
self.train_loader = train_loader
self.val_loader = val_loader
self.optimizer = optimizer
self.device = device
self.sensitive_attr = sensitive_attr # array of sensitive groups for val set (same order)
self.temperature = temperature
self.alpha = alpha
self.history = {
'train_loss': [],
'val_loss': [],
'val_acc': [],
'teacher_val_acc': [],
'kl_div': [],
'agreement_rate': []
}
self.fairness_history = [] # list of dicts per epoch
def distillation_loss(self, student_logits, teacher_logits, labels):
# KL divergence loss (soft)
soft_loss = F.kl_div(
F.log_softmax(student_logits / self.temperature, dim=-1),
F.softmax(teacher_logits / self.temperature, dim=-1),
reduction='batchmean'
) * (self.temperature ** 2)
# Hard loss (cross-entropy)
hard_loss = F.cross_entropy(student_logits, labels)
return self.alpha * soft_loss + (1 - self.alpha) * hard_loss
def train_epoch(self, epoch):
self.student.train()
total_loss = 0.0
total_samples = 0
for batch in self.train_loader:
input_ids = batch['input_ids'].to(self.device)
attention_mask = batch['attention_mask'].to(self.device)
labels = batch['labels'].to(self.device)
# Teacher forward (no grad)
with torch.no_grad():
teacher_logits = self.teacher(input_ids=input_ids, attention_mask=attention_mask).logits
student_logits = self.student(input_ids=input_ids, attention_mask=attention_mask).logits
loss = self.distillation_loss(student_logits, teacher_logits, labels)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
total_loss += loss.item() * input_ids.size(0)
total_samples += input_ids.size(0)
avg_loss = total_loss / total_samples
self.history['train_loss'].append(avg_loss)
print(f"Epoch {epoch}: Train loss = {avg_loss:.4f}")
def evaluate(self):
self.student.eval()
total_loss = 0.0
total_samples = 0
total_correct_student = 0
total_correct_teacher = 0
total_kl_sum = 0.0
total_agreement = 0
all_preds = []
all_labels = []
with torch.no_grad():
for batch in self.val_loader:
input_ids = batch['input_ids'].to(self.device)
attention_mask = batch['attention_mask'].to(self.device)
labels = batch['labels'].to(self.device)
teacher_logits = self.teacher(input_ids=input_ids, attention_mask=attention_mask).logits
student_logits = self.student(input_ids=input_ids, attention_mask=attention_mask).logits
loss = self.distillation_loss(student_logits, teacher_logits, labels)
total_loss += loss.item() * input_ids.size(0)
total_samples += input_ids.size(0)
student_preds = torch.argmax(student_logits, dim=-1)
teacher_preds = torch.argmax(teacher_logits, dim=-1)
total_correct_student += (student_preds == labels).sum().item()
total_correct_teacher += (teacher_preds == labels).sum().item()
total_agreement += (student_preds == teacher_preds).sum().item()
# KL per sample (batch sum)
kl_per_sample = F.kl_div(
F.log_softmax(student_logits / self.temperature, dim=-1),
F.softmax(teacher_logits / self.temperature, dim=-1),
reduction='none' # shape: (batch, classes)
).sum(dim=-1) * (self.temperature ** 2)
total_kl_sum += kl_per_sample.sum().item()
all_preds.extend(student_preds.cpu().numpy())
all_labels.extend(labels.cpu().numpy())
avg_loss = total_loss / total_samples
accuracy = total_correct_student / total_samples
teacher_acc = total_correct_teacher / total_samples
kl_div = total_kl_sum / total_samples
agreement = total_agreement / total_samples
self.history['val_loss'].append(avg_loss)
self.history['val_acc'].append(accuracy)
self.history['teacher_val_acc'].append(teacher_acc)
self.history['kl_div'].append(kl_div)
self.history['agreement_rate'].append(agreement)
# Fairness metrics if sensitive attributes are provided
fairness_metrics = {}
if self.sensitive_attr is not None:
sensitive_array = np.array(self.sensitive_attr)
if len(sensitive_array) != len(all_labels):
raise ValueError(f"Sensitive attribute length {len(sensitive_array)} does not match validation size {len(all_labels)}.")
# Convert to numpy arrays
y_true = np.array(all_labels)
y_pred = np.array(all_preds)
# Demographic parity difference
dp_diff = demographic_parity_difference(y_true, y_pred, sensitive_features=sensitive_array)
# Equalized odds difference
eo_diff = equalized_odds_difference(y_true, y_pred, sensitive_features=sensitive_array)
# Group-wise accuracy using MetricFrame
mf = MetricFrame(
metrics={"accuracy": accuracy_score},
y_true=y_true,
y_pred=y_pred,
sensitive_features=sensitive_array
)
group_acc = mf.by_group['accuracy'].to_dict() # dict: group -> accuracy
fairness_metrics = {
'demographic_parity_diff': dp_diff,
'equalized_odds_diff': eo_diff,
'group_accuracy': group_acc
}
self.fairness_history.append(fairness_metrics)
return avg_loss, accuracy, kl_div, agreement, teacher_acc, fairness_metrics
def train(self):
for epoch in range(num_epochs):
self.train_epoch(epoch)
val_loss, val_acc, kl, agreement, teacher_acc, fairness = self.evaluate()
print(f"Epoch {epoch} Val: loss={val_loss:.4f}, student_acc={val_acc:.4f}, teacher_acc={teacher_acc:.4f}")
print(f" KL_div={kl:.4f}, agreement={agreement:.4f}")
if fairness:
print(f" Fairness: DP_diff={fairness['demographic_parity_diff']:.4f}, EO_diff={fairness['equalized_odds_diff']:.4f}")
print(f" Group acc: {fairness['group_accuracy']}")
def load_data_and_preprocess(task, tokenizer, batch_size, sensitive_attribute_path=None):
"""
Load dataset, tokenize, and create DataLoaders.
Returns train_loader, val_loader, and sensitive attribute array for validation (if available).
"""
# For simplicity, we use GLUE SST-2
dataset = load_dataset("glue", task)
# Define tokenization function
def tokenize(batch):
# SST-2 has 'sentence' column; for other GLUE tasks column name may differ
return tokenizer(batch['sentence'], padding='max_length', truncation=True, max_length=128)
tokenized = dataset.map(tokenize, batched=True)
tokenized = tokenized.rename_column("label", "labels")
tokenized.set_format(type='torch', columns=['input_ids', 'attention_mask', 'labels'])
train_loader = DataLoader(tokenized['train'], batch_size=batch_size, shuffle=True)
val_loader = DataLoader(tokenized['validation'], batch_size=batch_size, shuffle=False)
# Load sensitive attributes if provided
sensitive_val = None
if sensitive_attribute_path:
# Assume a CSV with index and sensitive columns
import pandas as pd
df = pd.read_csv(sensitive_attribute_path)
# Ensure order matches validation dataset order (both should be same length)
# Usually the CSV should have a column 'sensitive' with same number of rows as validation set.
sensitive_val = df['sensitive'].tolist()
else:
# For demonstration, generate random binary groups (half 0, half 1). Replace with real data.
num_val = len(tokenized['validation'])
sensitive_val = [i % 2 for i in range(num_val)]
return train_loader, val_loader, sensitive_val
def main():
parser = argparse.ArgumentParser(description="Knowledge Distillation with Analytics and Fairness")
parser.add_argument("--teacher", type=str, default=teacher_name, help="Teacher model name or path")
parser.add_argument("--student", type=str, default=student_name, help="Student model name or path")
parser.add_argument("--task", type=str, default=task_name, help="GLUE task name")
parser.add_argument("--batch_size", type=int, default=batch_size)
parser.add_argument("--epochs", type=int, default=num_epochs)
parser.add_argument("--lr", type=float, default=learning_rate)
parser.add_argument("--temperature", type=float, default=temperature)
parser.add_argument("--alpha", type=float, default=alpha)
parser.add_argument("--sensitive_attr", type=str, default=None,
help="Path to CSV file containing sensitive attributes for validation set (optional)")
args = parser.parse_args()
# Device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# Tokenizer (using teacher's tokenizer for consistency)
tokenizer = AutoTokenizer.from_pretrained(args.teacher)
# Load data
train_loader, val_loader, sensitive_val = load_data_and_preprocess(
task=args.task,
tokenizer=tokenizer,
batch_size=args.batch_size,
sensitive_attribute_path=args.sensitive_attr
)
# Load teacher and student models
print("Loading teacher model...")
teacher = AutoModelForSequenceClassification.from_pretrained(args.teacher, num_labels=2) # adjust num_labels for your task
# For demonstration, we assume binary classification; for multi-class change to appropriate number
# If teacher is not fine-tuned, you should load fine-tuned weights. Here we use pre-trained, which may be poor for SST-2.
print("Loading student model...")
student = AutoModelForSequenceClassification.from_pretrained(args.student, num_labels=2)
# Freeze teacher explicitly (though eval mode already disables grads)
for param in teacher.parameters():
param.requires_grad = False
optimizer = torch.optim.AdamW(student.parameters(), lr=args.lr)
# Initialize trainer
trainer = DistillationTrainer(
teacher=teacher,
student=student,
train_loader=train_loader,
val_loader=val_loader,
optimizer=optimizer,
device=device,
sensitive_attr=sensitive_val,
temperature=args.temperature,
alpha=args.alpha
)
# Train
trainer.train()
if __name__ == "__main__":
main()
How to Run
- Install dependencies:
pip install torch transformers datasets fairlearn scikit-learn pandas
-
Save the script as distill.py.
-
Optional: prepare a CSV file with a sensitive column containing group labels for each validation sample. If not provided, the script will use a random split (just for demonstration).
-
Run:
python distill.py --teacher bert-large-uncased --student distilbert-base-uncased --task sst2 --epochs 3 --batch_size 32
You can adjust hyperparameters as needed. The output will show training loss, validation loss, student/teacher accuracy, KL divergence, agreement rate, and fairness metrics (if sensitive attributes are supplied).
Explanation of Key Sections
- Tokenization: Uses the teacher's tokenizer to ensure consistency.
padding='max_length' and max_length=128 work for most short text tasks. Adjust if needed.
- Model loading: The
num_labels argument should match your dataset's number of classes. Here we set to 2 for SST-2.
- Distillation loss: Implements the combination of KL and cross-entropy with temperature scaling. The teacher is kept in
eval() mode and its parameters are frozen.
- Analytics:
- KL divergence measures distributional similarity between teacher and student on validation data.
- Agreement rate measures how often the student and teacher predict the same class.
- Teacher and student accuracies are reported separately.
- Fairness: After each validation pass, if
sensitive_attr is provided, fairlearn computes demographic parity and equalized odds differences. Group-wise accuracies are also calculated and printed.
Advanced Options and Best Practices
- Teacher fine-tuning: Before distillation, the teacher should be fine-tuned on the target dataset to achieve high accuracy. Save its checkpoint and point
--teacher to that directory.
- Feature-based distillation: If the student and teacher share similar architectures (e.g., both transformers), you can align hidden states of certain layers. Modify the model classes to output
hidden_states and add an MSE loss between matched layers. For cross-architecture, you may need a projection layer.
- Adversarial fairness: To directly optimize for fairness during distillation, add an adversarial loss that penalizes the ability to predict sensitive attributes from student representations. This is more complex and outside the basic pipeline.
- Logging: Integrate TensorBoard or WandB to visualize analytics and fairness trajectories.
- Saving models: Save the best student model based on a combined metric (e.g., weighted sum of accuracy and fairness fairness). Add a checkpoint callback.
- Memory optimization: Use gradient accumulation to simulate larger batch sizes, or mixed precision with
torch.cuda.amp.
- Multiple teachers: Distillation can use an ensemble of teachers (average logits) to further boost performance.
Conclusion
This pipeline provides a solid foundation for knowledge distillation with built-in analytics and fairness monitoring. It can be extended to various tasks and model families. Regular audits of teacher-student similarity and fairness are essential to ensure the compressed model delivers both high performance and ethical integrity. Feel free to adapt the code to your specific needs.
Note: The above code assumes binary classification. For multi-class, ensure num_labels matches, and fairness metrics still work. Also, demographic_parity_difference and equalized_odds_difference from Fairlearn handle multi-class by one-vs-rest approach. Adjust accordingly.
This should fully address the user's request.
Knowledge Distillation Pipeline with Teacher/Student Analytics and Fairness Checks
Below is a comprehensive, modular pipeline for compressing large models via knowledge distillation. It includes response‑based distillation, detailed teacher/student analytics, and fairness evaluations using Fairlearn. The implementation uses PyTorch and Hugging Face Transformers and is ready to run on a variety of text classification tasks.
1. Introduction
Knowledge distillation (KD) transfers knowledge from a large, high‑performing teacher model to a smaller, efficient student model. The student learns from soft targets (probability distributions produced by the teacher at a raised temperature) that capture relationships between classes—so‑called “dark knowledge.” Optionally, the student also learns from the original hard labels.
An effective distillation pipeline should not only produce a compact model with minimal accuracy loss but also:
- Monitor the distillation process (e.g., how closely the student mimics the teacher).
- Audit fairness to detect whether the student inherits or amplifies biases present in the teacher or data.
The pipeline below addresses all these concerns.
2. Pipeline Architecture
┌─────────────────────────────────────┐
│ Input: Dataset + Optional │
│ Sensitive Attributes │
└───────────────┬─────────────────────┘
│
▼
┌──────────────────────┐
│ Data Preprocessing │
│ (tokenization, etc.) │
└──────────┬────────────┘
│
┌────────┴────────┐
│ │
▼ ▼
┌─────────┐ ┌─────────────┐
│ Teacher │ │ Student │
│ (Large) │ │ (Small) │
│ frozen │ │ trainable │
└────┬────┘ └─────┬───────┘
│ │
└────────┬───────┘
│ Distillation Loss
│ (KL + CE)
▼
┌─────────────┐
│ Optimizer │
└──────┬──────┘
│
▼
┌─────────────┐
│ Epoch Loop │
└──────┬──────┘
│
┌───────┴───────┐
│ │
▼ ▼
┌─────────────┐ ┌─────────────────┐
│ Teacher │ │ Student │
│ Analytics │ │ Analytics │
│ (KL, Acc, │ │ (Acc, etc.) │
│ Agreement)│ │ │
└──────┬──────┘ └────────┬────────┘
│ │
└────────┬────────┘
▼
┌───────────────┐
│ Fairness │
│ Check (if │
│ sensitive │
│ attr given) │
└───────┬───────┘
▼
┌─────────────────┐
│ Logging & │
│ Model Saving │
└─────────────────┘
3. Core Components
3.1 Data Preparation
We use the datasets library. The dataset must contain text and labels. For fairness, a sensitive attribute (e.g., gender, race) is optional but required for fairness metrics. If not present in the dataset, you can supply a CSV file that maps validation indices to group labels.
Tokenization uses the teacher’s tokenizer to keep embeddings consistent.
3.2 Distillation Loss
Given temperature ( T ):
soft_loss = KL( softmax(student_logits/T) || softmax(teacher_logits/T) ) * T²
hard_loss = cross_entropy(student_logits, true_labels)
total_loss = α * soft_loss + (1-α) * hard_loss
Common choices: ( T ∈ [2,5] ), ( α ∈ [0.5,1] ).
3.3 Teacher/Student Analytics
After each epoch on the validation set we compute:
| Metric | Description |
|---|
| Student accuracy | % of correct predictions |
| Teacher accuracy | % of correct predictions (for reference) |
| KL divergence | Average KL between teacher & student softened distributions |
| Agreement rate | % of samples where student and teacher top‑1 predictions match |
| Loss | Combined distillation loss |
These metrics help decide if the student is converging to the teacher’s behavior.
3.4 Fairness Checks
If sensitive attributes are provided, we use Fairlearn to compute:
- Demographic parity difference – absolute difference in positive prediction rates between the most and least favoured groups.
- Equalized odds difference – maximum absolute difference in true positive or false positive rates across groups.
- Group‑wise accuracy – performance per group.
These are calculated after each validation pass and tracked.
4. Full Implementation
Save the following as distill.py. It includes everything needed: data loading, training loop, analytics, fairness, and command‑line arguments.
#!/usr/bin/env python
# distill.py
import argparse
import torch
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from torch.utils.data import DataLoader
from datasets import load_dataset
import numpy as np
from fairlearn.metrics import MetricFrame, accuracy_score, demographic_parity_difference, equalized_odds_difference
# Default hyperparameters (overridable via CLI)
DEFAULT_TEACHER = "bert-large-uncased"
DEFAULT_STUDENT = "distilbert-base-uncased"
DEFAULT_TASK = "sst2"
DEFAULT_BATCH_SIZE = 32
DEFAULT_EPOCHS = 5
DEFAULT_LR = 2e-5
DEFAULT_TEMPERATURE = 2.0
DEFAULT_ALPHA = 0.5 # weight for soft loss
class DistillationTrainer:
"""
Handles the training loop, evaluation, analytics, and fairness checks.
"""
def __init__(self, teacher, student, train_loader, val_loader, optimizer, device,
sensitive_attr=None, temperature=2.0, alpha=0.5):
self.teacher = teacher.to(device).eval()
self.student = student.to(device)
self.train_loader = train_loader
self.val_loader = val_loader
self.optimizer = optimizer
self.device = device
self.sensitive_attr = sensitive_attr # list/array for validation set
self.temperature = temperature
self.alpha = alpha
self.history = {
'train_loss': [],
'val_loss': [],
'val_acc': [],
'teacher_val_acc': [],
'kl_div': [],
'agreement_rate': []
}
self.fairness_history = [] # one dict per epoch
def distillation_loss(self, student_logits, teacher_logits, labels):
"""Combine soft (KL) and hard (CE) losses."""
# Soft loss (KL divergence)
soft_loss = F.kl_div(
F.log_softmax(student_logits / self.temperature, dim=-1),
F.softmax(teacher_logits / self.temperature, dim=-1),
reduction='batchmean'
) * (self.temperature ** 2)
# Hard loss (cross entropy)
hard_loss = F.cross_entropy(student_logits, labels)
return self.alpha * soft_loss + (1 - self.alpha) * hard_loss
def train_epoch(self, epoch):
self.student.train()
total_loss = 0.0
total_samples = 0
for batch in self.train_loader:
input_ids = batch['input_ids'].to(self.device)
attention_mask = batch['attention_mask'].to(self.device)
labels = batch['labels'].to(self.device)
# Teacher forward (no gradient)
with torch.no_grad():
teacher_logits = self.teacher(input_ids=input_ids, attention_mask=attention_mask).logits
student_logits = self.student(input_ids=input_ids, attention_mask=attention_mask).logits
loss = self.distillation_loss(student_logits, teacher_logits, labels)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
total_loss += loss.item() * input_ids.size(0)
total_samples += input_ids.size(0)
avg_loss = total_loss / total_samples
self.history['train_loss'].append(avg_loss)
print(f"Epoch {epoch}: Train loss = {avg_loss:.4f}")
def evaluate(self):
"""Evaluate on validation set and compute analytics/fairness."""
self.student.eval()
total_loss = 0.0
total_samples = 0
total_correct_student = 0
total_correct_teacher = 0
total_kl_sum = 0.0
total_agreement = 0
all_preds = []
all_labels = []
with torch.no_grad():
for batch in self.val_loader:
input_ids = batch['input_ids'].to(self.device)
attention_mask = batch['attention_mask'].to(self.device)
labels = batch['labels'].to(self.device)
teacher_logits = self.teacher(input_ids=input_ids, attention_mask=attention_mask).logits
student_logits = self.student(input_ids=input_ids, attention_mask=attention_mask).logits
loss = self.distillation_loss(student_logits, teacher_logits, labels)
total_loss += loss.item() * input_ids.size(0)
total_samples += input_ids.size(0)
student_preds = torch.argmax(student_logits, dim=-1)
teacher_preds = torch.argmax(teacher_logits, dim=-1)
total_correct_student += (student_preds == labels).sum().item()
total_correct_teacher += (teacher_preds == labels).sum().item()
total_agreement += (student_preds == teacher_preds).sum().item()
# Per‑sample KL (no reduction)
kl_per_sample = F.kl_div(
F.log_softmax(student_logits / self.temperature, dim=-1),
F.softmax(teacher_logits / self.temperature, dim=-1),
reduction='none'
).sum(dim=-1) * (self.temperature ** 2)
total_kl_sum += kl_per_sample.sum().item()
all_preds.extend(student_preds.cpu().numpy())
all_labels.extend(labels.cpu().numpy())
avg_loss = total_loss / total_samples
student_acc = total_correct_student / total_samples
teacher_acc = total_correct_teacher / total_samples
kl_div = total_kl_sum / total_samples
agreement = total_agreement / total_samples
self.history['val_loss'].append(avg_loss)
self.history['val_acc'].append(student_acc)
self.history['teacher_val_acc'].append(teacher_acc)
self.history['kl_div'].append(kl_div)
self.history['agreement_rate'].append(agreement)
fairness_metrics = {}
if self.sensitive_attr is not None:
sensitive_array = np.array(self.sensitive_attr)
if len(sensitive_array) != len(all_labels):
raise ValueError(f"Sensitive attribute length {len(sensitive_array)} does not match validation size {len(all_labels)}.")
y_true = np.array(all_labels)
y_pred = np.array(all_preds)
dp_diff = demographic_parity_difference(y_true, y_pred, sensitive_features=sensitive_array)
eo_diff = equalized_odds_difference(y_true, y_pred, sensitive_features=sensitive_array)
mf = MetricFrame(
metrics={"accuracy": accuracy_score},
y_true=y_true,
y_pred=y_pred,
sensitive_features=sensitive_array
)
group_acc = mf.by_group['accuracy'].to_dict()
fairness_metrics = {
'demographic_parity_diff': dp_diff,
'equalized_odds_diff': eo_diff,
'group_accuracy': group_acc
}
self.fairness_history.append(fairness_metrics)
return avg_loss, student_acc, kl_div, agreement, teacher_acc, fairness_metrics
def train(self):
"""Run full training."""
for epoch in range(num_epochs):
self.train_epoch(epoch)
val_loss, student_acc, kl, agreement, teacher_acc, fairness = self.evaluate()
print(f"Epoch {epoch} Val: loss={val_loss:.4f}, student_acc={student_acc:.4f}, teacher_acc={teacher_acc:.4f}")
print(f" KL_div={kl:.4f}, agreement={agreement:.4f}")
if fairness:
print(f" Fairness: DP_diff={fairness['demographic_parity_diff']:.4f}, EO_diff={fairness['equalized_odds_diff']:.4f}")
print(f" Group acc: {fairness['group_accuracy']}")
def load_data_and_preprocess(task, tokenizer, batch_size, sensitive_attribute_path=None):
"""
Load dataset, tokenize, and create DataLoaders.
Returns: train_loader, val_loader, sensitive_val (list or None).
"""
# Load GLUE task (SST-2 by default)
dataset = load_dataset("glue", task)
# Define tokenization function (adjust column name if needed)
def tokenize(batch):
# SST‑2 uses 'sentence'; other tasks may use 'question' or 'sentence1'
text = batch.get('sentence') or batch.get('sentence1') or batch.get('question')
return tokenizer(text, padding='max_length', truncation=True, max_length=128)
tokenized = dataset.map(tokenize, batched=True)
tokenized = tokenized.rename_column("label", "labels")
tokenized.set_format(type='torch', columns=['input_ids', 'attention_mask', 'labels'])
train_loader = DataLoader(tokenized['train'], batch_size=batch_size, shuffle=True)
val_loader = DataLoader(tokenized['validation'], batch_size=batch_size, shuffle=False)
# Load sensitive attributes if a path is given
sensitive_val = None
if sensitive_attribute_path:
import pandas as pd
df = pd.read_csv(sensitive_attribute_path)
sensitive_val = df['sensitive'].tolist()
else:
# Demo: random binary groups (replace with real data in practice)
num_val = len(tokenized['validation'])
sensitive_val = [i % 2 for i in range(num_val)]
return train_loader, val_loader, sensitive_val
if __name__ == "__main__":
# Parse command‑line arguments
parser = argparse.ArgumentParser(description="Knowledge Distillation with Analytics and Fairness")
parser.add_argument("--teacher", type=str, default=DEFAULT_TEACHER,
help="Teacher model name or path (must be fine‑tuned on the task).")
parser.add_argument("--student", type=str, default=DEFAULT_STUDENT,
help="Student model name or path.")
parser.add_argument("--task", type=str, default=DEFAULT_TASK,
help="GLUE task name (e.g., sst2, mnli).")
parser.add_argument("--batch_size", type=int, default=DEFAULT_BATCH_SIZE)
parser.add_argument("--epochs", type=int, default=DEFAULT_EPOCHS)
parser.add_argument("--lr", type=float, default=DEFAULT_LR)
parser.add_argument("--temperature", type=float, default=DEFAULT_TEMPERATURE)
parser.add_argument("--alpha", type=float, default=DEFAULT_ALPHA,
help="Weight for soft loss (0‑1).")
parser.add_argument("--sensitive_attr", type=str, default=None,
help="Optional CSV with 'sensitive' column giving group labels for validation set.")
args = parser.parse_args()
# Global epochs for the training loop (used inside the class)
num_epochs = args.epochs
# Device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# Tokenizer (use teacher's tokenizer for consistency)
tokenizer = AutoTokenizer.from_pretrained(args.teacher)
# Load data
train_loader, val_loader, sensitive_val = load_data_and_preprocess(
task=args.task,
tokenizer=tokenizer,
batch_size=args.batch_size,
sensitive_attribute_path=args.sensitive_attr
)
# Load models
print("Loading teacher...")
teacher = AutoModelForSequenceClassification.from_pretrained(
args.teacher, num_labels=2) # adjust num_labels for your task
print("Loading student...")
student = AutoModelForSequenceClassification.from_pretrained(
args.student, num_labels=2)
# Freeze teacher
for param in teacher.parameters():
param.requires_grad = False
optimizer = torch.optim.AdamW(student.parameters(), lr=args.lr)
# Initialize and run training
trainer = DistillationTrainer(
teacher=teacher,
student=student,
train_loader=train_loader,
val_loader=val_loader,
optimizer=optimizer,
device=device,
sensitive_attr=sensitive_val,
temperature=args.temperature,
alpha=args.alpha
)
trainer.train()
5. How to Run
- Install dependencies:
pip install torch transformers datasets fairlearn scikit-learn pandas
-
Prepare a teacher model.
Fine‑tune a large model (e.g., BERT‑large) on your target task and save it (or reference its Hugging Face ID). The script assumes the teacher is already fine‑tuned; if not, the distillation will be ineffective.
-
Provide sensitive attributes (optional).
Create a CSV with a sensitive column containing group labels (e.g., 0/1) for each validation example, and pass its path via --sensitive_attr path.csv. If omitted, the pipeline uses a random split (only for demonstration) – replace with real data for actual fairness audits.
-
Execute the script:
python distill.py \
--teacher path/to/teacher \
--student distilbert-base-uncased \
--task sst2 \
--epochs 5 \
--batch_size 32 \
--temperature 3.0 \
--alpha 0.7
Adjust hyperparameters (temperature, alpha, lr, etc.) according to your hardware and task.
6. Advanced Options & Best Practices
| Goal | Suggested Implementation |
|---|
| Better teacher | Ensure teacher is fine‑tuned on the exact dataset. Use larger models (RoBERTa‑large, DeBERTa) for higher accuracy. |
| Feature‑based distillation | Add hidden‑state alignment: extract hidden_states from both models (output output.hidden_states), select matching layers, and add an MSE loss after possibly projecting dimensions. |
| Adversarial fairness | Add an auxiliary discriminator that tries to predict the sensitive attribute from student representations; use gradient reversal to penalize encoding of sensitive information. |
| Logging | Integrate TensorBoard or WandB to track metrics over epochs. |
| Model checkpointing | Save the student model when a combined metric (e.g., accuracy – λ*fairness_penalty) improves. |
| Mixed precision | Use torch.cuda.amp for faster training and lower memory. |
| Multiple teachers | Average soft targets from several teachers to further boost performance. |
| Early stopping | Stop if validation loss does not improve for N epochs or if fairness disparity exceeds a threshold. |
| Non‑text tasks | Replace the transformer models with your own architecture (CNNs, ResNets, etc.). The distillation loss and analytics remain the same. |
7. Conclusion
This pipeline provides a robust foundation for knowledge distillation with built‑in teacher/student diagnostics and fairness monitoring. It can be adapted to any classification task, model family, or fairness definition. Continuous analytics and fairness checks are essential to ensure the compressed model remains both accurate and ethical.
Feel free to extend the code with your own analytics or fairness constraints!