File size: 25,723 Bytes
c8b77b5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 | """
LoRA Knowledge Distillation Trainer for MangoMAS Local
This module implements the main training loop for knowledge distillation
with LoRA fine-tuning optimized for Mac Mini hardware constraints.
"""
import argparse
import json
import logging
import os
import sys
from datetime import datetime
from pathlib import Path
from typing import Dict, List
import torch
import torch.nn as nn
import yaml
from peft import LoraConfig, TaskType, get_peft_model
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from transformers import (AutoModelForCausalLM, AutoTokenizer,
get_linear_schedule_with_warmup)
# Try to import context7 for enhanced training
try:
from context7 import Context7
CONTEXT7_AVAILABLE = True
except ImportError:
CONTEXT7_AVAILABLE = False
Context7 = None
# Try to import MLflow for experiment tracking
try:
import mlflow
MLFLOW_AVAILABLE = True
except ImportError:
MLFLOW_AVAILABLE = False
mlflow = None
# Fix import path issues for distillation loss
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
try:
from distillation_loss import AdaptiveDistillationLoss, DistillationLoss
except ImportError:
try:
from training.distillation_loss import (AdaptiveDistillationLoss,
DistillationLoss)
except ImportError:
# Fallback: create minimal distillation loss if not available
class DistillationLoss:
def __init__(self, alpha=0.5, temperature=2.0):
self.alpha = alpha
self.temperature = temperature
self.task_loss = nn.CrossEntropyLoss()
def compute_loss(
self, student_logits, teacher_logits, labels, attention_mask=None
):
# Task loss (standard cross-entropy)
shift_logits = student_logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
task_loss = self.task_loss(
shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)
)
# Distillation loss (KL divergence)
if teacher_logits is not None:
student_probs = nn.functional.log_softmax(
student_logits / self.temperature, dim=-1
)
teacher_probs = nn.functional.softmax(
teacher_logits / self.temperature, dim=-1
)
distill_loss = nn.functional.kl_div(
student_probs, teacher_probs, reduction="batchmean"
)
distill_loss *= self.temperature**2
else:
distill_loss = torch.tensor(0.0)
# Combined loss
total_loss = (1 - self.alpha) * task_loss + self.alpha * distill_loss
return total_loss, {
"total_loss": total_loss.item(),
"task_loss": task_loss.item(),
"distillation_loss": (
distill_loss.item()
if isinstance(distill_loss, torch.Tensor)
else 0.0
),
}
AdaptiveDistillationLoss = DistillationLoss # Fallback
logger = logging.getLogger(__name__)
class ConversationDataset:
"""Dataset class for conversation-based training data."""
def __init__(self, data_path: str, tokenizer, max_length: int = 512):
self.tokenizer = tokenizer
self.max_length = max_length
self.data = self._load_data(data_path)
def _load_data(self, data_path: str) -> List[Dict]:
"""Load conversation data from JSONL file."""
data = []
with open(data_path, "r", encoding="utf-8") as f:
for line in f:
data.append(json.loads(line.strip()))
return data
def __len__(self) -> int:
return len(self.data)
def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:
"""Get tokenized conversation item."""
item = self.data[idx]
# Handle different data formats
if "messages" in item:
# Chat format with messages
conversation_text = ""
for message in item["messages"]:
role = message["role"]
content = message["content"]
conversation_text += f"<{role}>\n{content}\n</{role}>\n\n"
elif "instruction" in item and "response" in item:
# Instruction-response format
instruction = item["instruction"]
response = item["response"]
conversation_text = f"<user>\n{instruction}\n</user>\n\n<assistant>\n{response}\n</assistant>\n\n"
elif "prompt" in item and "completion" in item:
# Prompt-completion format
prompt = item["prompt"]
completion = item["completion"]
conversation_text = f"<user>\n{prompt}\n</user>\n\n<assistant>\n{completion}\n</assistant>\n\n"
else:
# Fallback - try to extract any text
conversation_text = str(item)
# Tokenize
encoding = self.tokenizer(
conversation_text,
truncation=True,
padding="max_length",
max_length=self.max_length,
return_tensors="pt",
)
return {
"input_ids": encoding["input_ids"].squeeze(),
"attention_mask": encoding["attention_mask"].squeeze(),
"labels": encoding["input_ids"].squeeze().clone(),
"agent_type": item.get("agent_type", "unknown"),
}
class LoRADistillationTrainer:
"""Main trainer class for LoRA knowledge distillation."""
def __init__(self, config_path: str):
"""Initialize trainer with configuration."""
with open(config_path, "r") as f:
self.config = yaml.safe_load(f)
self.setup_logging()
self.setup_device()
self.setup_monitoring()
logger.info("Initialized LoRA Distillation Trainer")
logger.info(f"Device: {self.device}")
logger.info(f"Config: {config_path}")
def setup_logging(self) -> None:
"""Set up logging configuration."""
log_dir = Path("logs")
log_dir.mkdir(exist_ok=True)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
handlers=[
logging.FileHandler(log_dir / "training.log"),
logging.StreamHandler(),
],
)
def setup_device(self) -> None:
"""Set up compute device (MPS for Mac Mini)."""
device_config = self.config["hardware"]["device"]
if device_config == "mps" and torch.backends.mps.is_available():
self.device = torch.device("mps")
logger.info("Using Apple Metal Performance Shaders (MPS)")
elif device_config == "cuda" and torch.cuda.is_available():
self.device = torch.device("cuda")
logger.info(f"Using CUDA: {torch.cuda.get_device_name()}")
else:
self.device = torch.device("cpu")
logger.warning("Using CPU - training will be slow")
def setup_monitoring(self) -> None:
"""Set up experiment tracking and monitoring."""
self.use_tensorboard = self.config["monitoring"]["use_tensorboard"]
self.use_mlflow = self.config["monitoring"]["use_mlflow"]
if self.use_tensorboard:
log_dir = self.config["monitoring"]["log_dir"]
Path(log_dir).mkdir(parents=True, exist_ok=True)
self.tb_writer = SummaryWriter(log_dir)
logger.info(f"TensorBoard logging to: {log_dir}")
if self.use_mlflow:
try:
import mlflow
experiment_name = self.config["monitoring"]["experiment_name"]
mlflow.set_experiment(experiment_name)
logger.info(f"MLflow experiment: {experiment_name}")
except (ImportError, AttributeError) as e:
logger.warning(
f"MLflow not available or not properly initialized, disabling: {e}"
)
self.use_mlflow = False
def load_models(self) -> None:
"""Load teacher and student models."""
# Load tokenizer
model_name = self.config["models"]["student"]["base_model"]
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
# Add pad token if it doesn't exist
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
# Load student model - fix deprecated torch_dtype
dtype = (
torch.float16
if self.config["optimization"]["use_fp16"] and self.device.type == "cuda"
else torch.float32
)
self.student_model = AutoModelForCausalLM.from_pretrained(
model_name,
dtype=dtype, # Use dtype instead of torch_dtype
device_map="auto" if self.device.type == "cuda" else None,
trust_remote_code=True,
)
# Apply LoRA to student model - fix target modules for DialoGPT
target_modules = self.config["lora"]["target_modules"]
# If using default transformer modules but this is DialoGPT, adjust
if target_modules == ["q_proj", "v_proj", "k_proj", "o_proj"]:
target_modules = ["c_attn", "c_proj", "c_fc"] # DialoGPT modules
logger.info("Adjusted LoRA target modules for DialoGPT architecture")
lora_config = LoraConfig(
r=self.config["lora"]["r"],
lora_alpha=self.config["lora"]["lora_alpha"],
target_modules=target_modules,
lora_dropout=self.config["lora"]["lora_dropout"],
bias=self.config["lora"]["bias"],
task_type=TaskType.CAUSAL_LM,
)
self.student_model = get_peft_model(self.student_model, lora_config)
self.student_model.to(self.device)
# Setup teacher model
self.teacher_manager = TeacherModelManager(
self.config["models"]["teacher"], self.tokenizer
)
logger.info("Loaded student model with LoRA")
logger.info(
f"Trainable parameters: {self.student_model.num_parameters(only_trainable=True):,}"
)
logger.info("Loaded teacher model")
def load_datasets(self, agent_type: str) -> tuple:
"""Load training and validation datasets for specific agent."""
data_dir = Path("data/processed")
train_path = data_dir / f"{agent_type}_train.jsonl"
val_path = data_dir / f"{agent_type}_validation.jsonl"
if not train_path.exists():
raise FileNotFoundError(f"Training data not found: {train_path}")
if not val_path.exists():
raise FileNotFoundError(f"Validation data not found: {val_path}")
max_length = self.config["data"]["max_sequence_length"]
train_dataset = ConversationDataset(train_path, self.tokenizer, max_length)
val_dataset = ConversationDataset(val_path, self.tokenizer, max_length)
logger.info(
f"Loaded datasets: {len(train_dataset)} train, {len(val_dataset)} val"
)
return train_dataset, val_dataset
def create_data_loaders(self, train_dataset, val_dataset) -> tuple:
"""Create data loaders for training and validation."""
batch_size = self.config["training"]["batch_size"]
num_workers = self.config["optimization"]["dataloader_num_workers"]
pin_memory = self.config["optimization"]["pin_memory"]
train_loader = DataLoader(
train_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=num_workers,
pin_memory=pin_memory,
drop_last=True,
)
val_loader = DataLoader(
val_dataset,
batch_size=batch_size,
shuffle=False,
num_workers=num_workers,
pin_memory=pin_memory,
drop_last=False,
)
return train_loader, val_loader
def setup_training(self, train_dataset_size: int) -> None:
"""Set up optimizer, scheduler, and loss function."""
# Calculate training steps
batch_size = self.config["training"]["batch_size"]
gradient_accumulation_steps = self.config["training"][
"gradient_accumulation_steps"
]
num_epochs = self.config["training"]["num_epochs"]
steps_per_epoch = train_dataset_size // (
batch_size * gradient_accumulation_steps
)
self.total_steps = steps_per_epoch * num_epochs
# Setup optimizer
self.optimizer = torch.optim.AdamW(
self.student_model.parameters(),
lr=self.config["training"]["learning_rate"],
weight_decay=0.01,
)
# Setup scheduler
self.scheduler = get_linear_schedule_with_warmup(
self.optimizer,
num_warmup_steps=self.config["training"]["warmup_steps"],
num_training_steps=self.total_steps,
)
# Setup loss function
self.distill_loss = DistillationLoss(
alpha=self.config["distillation"]["alpha"],
temperature=self.config["distillation"]["temperature"],
)
logger.info(f"Setup training: {self.total_steps} total steps")
def train_epoch(self, train_loader: DataLoader, epoch: int) -> Dict[str, float]:
"""Train for one epoch."""
self.student_model.train()
total_loss = 0.0
total_task_loss = 0.0
total_distill_loss = 0.0
num_batches = 0
progress_bar = tqdm(train_loader, desc=f"Epoch {epoch+1}", disable=False)
for batch_idx, batch in enumerate(progress_bar):
# Move batch to device
input_ids = batch["input_ids"].to(self.device)
attention_mask = batch["attention_mask"].to(self.device)
labels = batch["labels"].to(self.device)
# Get student outputs
student_outputs = self.student_model(
input_ids=input_ids, attention_mask=attention_mask
)
student_logits = student_outputs.logits
# Get teacher outputs
with torch.no_grad():
teacher_logits = self.teacher_manager.get_logits(
input_ids, attention_mask
)
# Compute distillation loss
loss, loss_dict = self.distill_loss.compute_loss(
student_logits, teacher_logits, labels, attention_mask
)
# Backward pass with gradient accumulation
loss = loss / self.config["training"]["gradient_accumulation_steps"]
loss.backward()
# Update model
if (batch_idx + 1) % self.config["training"][
"gradient_accumulation_steps"
] == 0:
torch.nn.utils.clip_grad_norm_(
self.student_model.parameters(),
self.config["training"]["max_grad_norm"],
)
self.optimizer.step()
self.scheduler.step()
self.optimizer.zero_grad()
# Track metrics
total_loss += loss_dict["total_loss"]
total_task_loss += loss_dict["task_loss"]
total_distill_loss += loss_dict["distillation_loss"]
num_batches += 1
# Update progress bar
progress_bar.set_postfix(
{
"loss": f"{loss_dict['total_loss']:.4f}",
"task": f"{loss_dict['task_loss']:.4f}",
"distill": f"{loss_dict['distillation_loss']:.4f}",
}
)
# Log to tensorboard
if (
self.use_tensorboard
and batch_idx % self.config["training"]["logging_steps"] == 0
):
step = epoch * len(train_loader) + batch_idx
self.tb_writer.add_scalar(
"train/total_loss", loss_dict["total_loss"], step
)
self.tb_writer.add_scalar(
"train/task_loss", loss_dict["task_loss"], step
)
self.tb_writer.add_scalar(
"train/distillation_loss", loss_dict["distillation_loss"], step
)
# Calculate epoch averages
epoch_metrics = {
"avg_loss": total_loss / num_batches,
"avg_task_loss": total_task_loss / num_batches,
"avg_distill_loss": total_distill_loss / num_batches,
}
return epoch_metrics
def evaluate(self, val_loader: DataLoader) -> Dict[str, float]:
"""Evaluate model on validation set."""
self.student_model.eval()
total_loss = 0.0
total_task_loss = 0.0
total_distill_loss = 0.0
num_batches = 0
with torch.no_grad():
for batch in tqdm(val_loader, desc="Evaluating"):
# Move batch to device
input_ids = batch["input_ids"].to(self.device)
attention_mask = batch["attention_mask"].to(self.device)
labels = batch["labels"].to(self.device)
# Get model outputs
student_outputs = self.student_model(
input_ids=input_ids, attention_mask=attention_mask
)
student_logits = student_outputs.logits
# Get teacher outputs
teacher_logits = self.teacher_manager.get_logits(
input_ids, attention_mask
)
# Compute loss
loss, loss_dict = self.distill_loss.compute_loss(
student_logits, teacher_logits, labels, attention_mask
)
total_loss += loss_dict["total_loss"]
total_task_loss += loss_dict["task_loss"]
total_distill_loss += loss_dict["distillation_loss"]
num_batches += 1
val_metrics = {
"val_loss": total_loss / num_batches,
"val_task_loss": total_task_loss / num_batches,
"val_distill_loss": total_distill_loss / num_batches,
}
return val_metrics
def save_model(self, output_dir: str, agent_type: str, epoch: int) -> None:
"""Save model checkpoint."""
output_path = Path(output_dir) / agent_type / f"epoch_{epoch}"
output_path.mkdir(parents=True, exist_ok=True)
# Save LoRA adapter
self.student_model.save_pretrained(output_path)
# Save tokenizer
self.tokenizer.save_pretrained(output_path)
# Save training config
config_path = output_path / "training_config.yaml"
with open(config_path, "w") as f:
yaml.dump(self.config, f)
logger.info(f"Saved model to: {output_path}")
def train_agent(self, agent_type: str) -> None:
"""Train a specific agent with knowledge distillation."""
logger.info(f"Starting training for {agent_type} agent")
# Load models if not already loaded
if not hasattr(self, "student_model"):
self.load_models()
# Load datasets
train_dataset, val_dataset = self.load_datasets(agent_type)
train_loader, val_loader = self.create_data_loaders(train_dataset, val_dataset)
# Setup training components
self.setup_training(len(train_dataset))
# Start MLflow run
if self.use_mlflow:
mlflow.start_run(
run_name=f"{agent_type}_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
)
mlflow.log_params(
{
"agent_type": agent_type,
"model_name": self.config["models"]["student"]["base_model"],
"lora_r": self.config["lora"]["r"],
"lora_alpha": self.config["lora"]["lora_alpha"],
"batch_size": self.config["training"]["batch_size"],
"learning_rate": self.config["training"]["learning_rate"],
"distillation_alpha": self.config["distillation"]["alpha"],
"temperature": self.config["distillation"]["temperature"],
}
)
try:
# Training loop
best_val_loss = float("inf")
num_epochs = self.config["training"]["num_epochs"]
for epoch in range(num_epochs):
logger.info(f"Epoch {epoch+1}/{num_epochs}")
# Train
train_metrics = self.train_epoch(train_loader, epoch)
logger.info(
f"Train - Loss: {train_metrics['avg_loss']:.4f}, "
f"Task: {train_metrics['avg_task_loss']:.4f}, "
f"Distill: {train_metrics['avg_distill_loss']:.4f}"
)
# Evaluate
val_metrics = self.evaluate(val_loader)
logger.info(
f"Val - Loss: {val_metrics['val_loss']:.4f}, "
f"Task: {val_metrics['val_task_loss']:.4f}, "
f"Distill: {val_metrics['val_distill_loss']:.4f}"
)
# Log to MLflow
if self.use_mlflow:
mlflow.log_metrics({**train_metrics, **val_metrics}, step=epoch)
# Log to TensorBoard
if self.use_tensorboard:
for key, value in train_metrics.items():
self.tb_writer.add_scalar(f"epoch/{key}", value, epoch)
for key, value in val_metrics.items():
self.tb_writer.add_scalar(f"epoch/{key}", value, epoch)
# Save checkpoint if best model
if val_metrics["val_loss"] < best_val_loss:
best_val_loss = val_metrics["val_loss"]
self.save_model(
self.config["output"]["base_dir"], agent_type, epoch
)
logger.info(f"New best model saved (val_loss: {best_val_loss:.4f})")
finally:
if self.use_mlflow:
mlflow.end_run()
logger.info(f"Training completed for {agent_type} agent")
class TeacherModelManager:
"""Manages teacher model interactions (API or local)."""
def __init__(self, teacher_config: Dict, tokenizer):
self.config = teacher_config
self.tokenizer = tokenizer
if teacher_config["type"] == "api":
self.setup_api_teacher()
else:
self.setup_local_teacher()
def setup_api_teacher(self) -> None:
"""Set up API-based teacher model."""
self.model_name = self.config["model_name"]
logger.info(f"Using API teacher model: {self.model_name}")
# This would integrate with OpenAI/Anthropic APIs
# For now, we'll use a placeholder that returns random logits
# In production, you'd implement actual API calls here
def setup_local_teacher(self) -> None:
"""Set up local teacher model."""
model_path = self.config.get("local_model_path", "microsoft/DialoGPT-large")
self.teacher_model = AutoModelForCausalLM.from_pretrained(
model_path, torch_dtype=torch.float16, device_map="auto"
)
logger.info(f"Loaded local teacher model: {model_path}")
def get_logits(
self, input_ids: torch.Tensor, attention_mask: torch.Tensor
) -> torch.Tensor:
"""Get teacher model logits."""
if self.config["type"] == "api":
# Placeholder for API-based teacher
# In practice, you'd call the API and convert responses to logits
batch_size, seq_len = input_ids.shape
vocab_size = self.tokenizer.vocab_size
return torch.randn(batch_size, seq_len, vocab_size).to(input_ids.device)
else:
# Local teacher model
with torch.no_grad():
outputs = self.teacher_model(
input_ids=input_ids, attention_mask=attention_mask
)
return outputs.logits
def main():
parser = argparse.ArgumentParser(
description="Train MangoMAS agents with LoRA and knowledge distillation"
)
parser.add_argument(
"--config",
type=str,
default="config/training/distillation.yaml",
help="Path to training configuration file",
)
parser.add_argument(
"--agent",
type=str,
choices=["infrastructure", "devsecops", "risk_assessment", "all"],
default="all",
help="Which agent to train",
)
parser.add_argument("--data", type=str, help="Path to training data file")
args = parser.parse_args()
# Initialize trainer
trainer = LoRADistillationTrainer(args.config)
# If data path is provided, update the trainer to use it
if args.data:
trainer.custom_data_path = args.data
# Train specified agent(s)
if args.agent == "all":
agents = ["infrastructure", "devsecops", "risk_assessment"]
else:
agents = [args.agent]
for agent_type in agents:
trainer.train_agent(agent_type)
if __name__ == "__main__":
main()
|