import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader, Dataset
import numpy as np
import pandas as pd
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
# ==========================================
# 1. Model Definitions (Teacher & Student)
# ==========================================
class TeacherModel(nn.Module):
"""A larger, deeper model."""
def __init__(self, input_dim, hidden_dim=128, output_dim=2):
super(TeacherModel, self).__init__()
self.network = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, output_dim)
)
def forward(self, x):
return self.network(x)
class StudentModel(nn.Module):
"""A smaller, compressed model."""
def __init__(self, input_dim, hidden_dim=16, output_dim=2):
super(StudentModel, self).__init__()
self.network = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, output_dim)
)
def forward(self, x):
return self.network(x)
# ==========================================
# 2. Fairness & Analytics Utilities
# ==========================================
class FairnessAnalyzer:
"""
Calculates fairness metrics based on sensitive attributes
(e.g., gender, age group).
"""
@staticmethod
def calculate_demographic_parity(y_pred, sensitive_attribute):
"""
Measures the difference in positive prediction rates
between groups.
"""
group_0_mask = (sensitive_attribute == 0)
group_1_mask = (sensitive_attribute == 1)
if group_0_mask.sum() == 0 or group_1_mask.sum() == 0:
return 0.0
rate_0 = y_pred[group_0_mask].mean()
rate_1 = y_pred[group_1_mask].mean()
return abs(rate_0 - rate_1)
@staticmethod
def calculate_logit_alignment(teacher_logits, student_logits):
"""
Analytics: How well do student probabilities align with teacher?
Uses Cosine Similarity.
"""
t_probs = F.softmax(teacher_logits, dim=1)
s_probs = F.softmax(student_logits, dim=1)
# Flatten and calculate cosine similarity
cos = nn.CosineSimilarity(dim=0)
return cos(t_probs.view(-1), s_probs.view(-1)).item()
# ==========================================
# 3. Distillation Pipeline Core
# ==========================================
class KDPipeline:
def __init__(self, teacher, student, train_loader, val_loader, device='cpu', lr=0.01):
self.teacher = teacher.to(device)
self.student = student.to(device)
self.train_loader = train_loader
self.val_loader = val_loader
self.device = device
self.optimizer = optim.Adam(self.student.parameters(), lr=lr)
self.criterion_hard = nn.CrossEntropyLoss()
self.criterion_soft = nn.KLDivLoss(reduction='batchmean')
self.analyzer = FairnessAnalyzer()
# History for Analytics
self.history = {
'train_loss': [], 'val_acc': [],
'fairness_dp': [], 'logit_alignment': []
}
def distill(self, epochs=10, temp=5.0, alpha=0.7):
"""
alpha: Weight for soft loss (KD). (1-alpha) is weight for hard labels.
temp: Temperature for softening probabilities.
"""
print(f"{'Epoch':<6} | {'Loss':<10} | {'Val Acc':<8} | {'Fairness (DP)':<12} | {'Alignment':<10}")
print("-" * 60)
for epoch in range(epochs):
self.student.train()
self.teacher.eval() # Teacher is frozen
total_loss = 0
for X_batch, y_batch, sensitive_batch in self.train_loader:
X_batch = X_batch.to(self.device)
y_batch = y_batch.to(self.device)
self.optimizer.zero_grad()
# 1. Get Teacher outputs (no grad)
with torch.no_grad():
teacher_logits = self.teacher(X_batch)
# 2. Get Student outputs
student_logits = self.student(X_batch)
# 3. Calculate Combined Loss
# Soft Loss (KL Div on softened probs)
soft_loss = self.criterion_soft(
F.log_softmax(student_logits / temp, dim=1),
F.softmax(teacher_logits / temp, dim=1)
)
# Hard Loss (Standard Cross Entropy)
hard_loss = self.criterion_hard(student_logits, y_batch)
loss = alpha * soft_loss + (1 - alpha) * hard_loss
loss.backward()
self.optimizer.step()
total_loss += loss.item()
# --- Analytics & Fairness Check Phase ---
val_metrics = self.validate()
avg_loss = total_loss / len(self.train_loader)
self.history['train_loss'].append(avg_loss)
self.history['val_acc'].append(val_metrics['acc'])
self.history['fairness_dp'].append(val_metrics['fairness_dp'])
self.history['logit_alignment'].append(val_metrics['alignment'])
print(f"{epoch+1:<6} | {avg_loss:<10.4f} | {val_metrics['acc']:<8.4f} | "
f"{val_metrics['fairness_dp']:<12.4f} | {val_metrics['alignment']:<10.4f}")
# Early stopping based on fairness degradation (Optional engineering logic)
if val_metrics['fairness_dp'] > 0.20: # Threshold example
print(" [!] Warning: Fairness metric exceeding threshold.")
def validate(self):
self.student.eval()
all_preds = []
all_labels = []
all_sensitive = []
all_t_logits = []
all_s_logits = []
with torch.no_grad():
for X_batch, y_batch, sensitive_batch in self.val_loader:
X_batch = X_batch.to(self.device)
logits = self.student(X_batch)
t_logits = self.teacher(X_batch)
preds = torch.argmax(logits, dim=1)
all_preds.extend(preds.cpu().numpy())
all_labels.extend(y_batch.numpy())
all_sensitive.extend(sensitive_batch.numpy())
all_s_logits.append(logits.cpu())
all_t_logits.append(t_logits.cpu())
all_preds = np.array(all_preds)
all_sensitive = np.array(all_sensitive)
# Calculate Metrics
acc = accuracy_score(all_labels, all_preds)
fairness_dp = self.analyzer.calculate_demographic_parity(all_preds, all_sensitive)
alignment = self.analyzer.calculate_logit_alignment(
torch.cat(all_t_logits), torch.cat(all_s_logits)
)
return {'acc': acc, 'fairness_dp': fairness_dp, 'alignment': alignment}
# ==========================================
# 4. Synthetic Data Generation & Execution
# ==========================================
class SyntheticFairnessDataset(Dataset):
"""
Generates data where y is somewhat correlated with x,
and we include a sensitive attribute for fairness checking.
"""
def __init__(self, num_samples=1000, input_dim=20):
self.X = torch.randn(num_samples, input_dim)
# Binary classification target
self.y = (self.X[:, 0] + self.X[:, 1] > 0).long()
# Sensitive attribute (e.g., 0 or 1) - Randomly assigned
self.sensitive = torch.randint(0, 2, (num_samples,))
def __len__(self):
return len(self.y)
def __getitem__(self, idx):
return self.X[idx], self.y[idx], self.sensitive[idx]
def run_engineering_pipeline():
# Setup
input_dim = 20
device = 'cuda' if torch.cuda.is_available() else 'cpu'
# Data
train_data = SyntheticFairnessDataset(2000, input_dim)
val_data = SyntheticFairnessDataset(500, input_dim)
train_loader = DataLoader(train_data, batch_size=32, shuffle=True)
val_loader = DataLoader(val_data, batch_size=32, shuffle=False)
# Models
teacher = TeacherModel(input_dim, hidden_dim=128)
student = StudentModel(input_dim, hidden_dim=16)
# Pre-train Teacher (Simulating a pre-existing large model)
print("Pre-training Teacher model...")
# (Omitted for brevity: standard training loop for teacher)
# Assume teacher is trained for this example
# Run KD Pipeline
pipeline = KDPipeline(teacher, student, train_loader, val_loader, device=device)
pipeline.distill(epochs=15, temp=5.0, alpha=0.8)
# Report
report_results(pipeline)
def report_results(pipeline):
print("\n--- Compression & Fairness Report ---")
# 1. Compression Ratio
t_params = sum(p.numel() for p in pipeline.teacher.parameters())
s_params = sum(p.numel() for p in pipeline.student.parameters())
print(f"Parameter Reduction: {t_params} -> {s_params} ({(1 - s_params/t_params)*100:.2f}% reduction)")
# 2. Analytics Plot
fig, axs = plt.subplots(1, 3, figsize=(15, 4))
axs[0].plot(pipeline.history['val_acc'], label='Student Acc', color='green')
axs[0].set_title('Accuracy')
axs[1].plot(pipeline.history['fairness_dp'], label='Demographic Parity Diff', color='red')
axs[1].set_title('Fairness (Lower is Better)')
axs[2].plot(pipeline.history['logit_alignment'], label='Logit Alignment', color='blue')
axs[2].set_title('Knowledge Transfer (Higher is Better)')
plt.show()
if __name__ == "__main__":
run_engineering_pipeline()