Route Constrained Optimization (RCO) is a knowledge distillation algorithm based on curriculum learning. Instead of supervising a student model with a fully converged teacher, RCO supervises the student using anchor points selected from the trajectory (route) the teacher model traveled in parameter space. This approach is designed to reduce the lower bound of congruence loss during distillation, hint, and mimicking learning.
To implement RCO, you use the RCO class from KD_Lib.KD. You must provide a teacher model, a student model, their respective optimizers, and the data loaders. You can control how frequently the student mimics the teacher's trajectory using the epoch_interval parameter.
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from KD_Lib.KD import RCO
# 1. Prepare Data
train_loader = torch.utils.data.DataLoader(
datasets.MNIST("mnist_data", train=True, download=True, transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=32, shuffle=True
)
test_loader = torch.utils.data.DataLoader(
datasets.MNIST("mnist_data", train=False, transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=32, shuffle=True
)
# 2. Setup Device
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# 3. Define Models
teacher_model = <your_model_instance>
student_model = <your_model_instance>
# 4. Define Optimizers
teacher_optimizer = optim.SGD(teacher_model.parameters(), lr=0.01)
student_optimizer = optim.SGD(student_model.parameters(), lr=0.01)
# 5. Initialize RCO Distiller
distiller = RCO(
teacher_model,
student_model,
train_loader,
test_loader,
teacher_optimizer,
student_optimizer,
epoch_interval=5,
device=device
)
# 6. Execute Training Workflow
distiller.train_teacher(epochs=20) # Train the teacher model
distiller.train_students(epochs=20) # Train the student model
distiller.evaluate(teacher=True) # Evaluate the teacher model
distiller.evaluate() # Evaluate the student model