#!/usr/bin/env python3 """ Comprehensive LLM Fine-Tuning Script for Verilog QA Implements full logging, evaluation metrics from papers, and multi-GPU training. Based on analysis from: - AnalogSeeker: NSC-SFT approach (Qwen2.5-32B) - ChipNeMo: DAPT + SteerLM (LLaMA2-70B) - ChipExpert: Fine-tuned LLaMA3-8B """ import os import sys import json import time import logging import argparse import traceback import pprint from datetime import datetime from pathlib import Path from typing import Dict, List, Optional, Any from dataclasses import dataclass, field, asdict from collections import defaultdict import warnings warnings.filterwarnings("ignore") # ============================================================================= # DEBUG LOGGING CONFIGURATION # ============================================================================= def setup_debug_logging(log_file: str = "training/logs/training_debug.log"): """Setup comprehensive debug logging to file and console.""" # Create logs directory log_path = Path(log_file) log_path.parent.mkdir(parents=True, exist_ok=True) # Configure logging with no truncation logging.basicConfig( level=logging.DEBUG, format='%(asctime)s | %(levelname)s | %(message)s', datefmt='%Y-%m-%d %H:%M:%S', handlers=[ logging.FileHandler(log_file, mode='w'), logging.StreamHandler(sys.stdout) ] ) # Disable truncation for pprint pprint._MAX_LENGTH = None return logging.getLogger(__name__) # Global logger - will be initialized in main() debug_logger = None def log_section(title: str): """Log a section header.""" if debug_logger: separator = "=" * 70 debug_logger.info(f"\n{separator}") debug_logger.info(f"=== {title} ===") debug_logger.info(f"{separator}") def log_var(name: str, value: Any, max_str_len: int = None): """Log a variable with its type and full value.""" if debug_logger: var_type = type(value).__name__ if isinstance(value, (dict, list)): formatted = pprint.pformat(value, width=120) debug_logger.debug(f"{name} ({var_type}):\n{formatted}") elif isinstance(value, str): if max_str_len and len(value) > max_str_len: debug_logger.debug(f"{name} ({var_type}, len={len(value)}): {value[:max_str_len]}...") else: debug_logger.debug(f"{name} ({var_type}, len={len(value)}): {value}") else: debug_logger.debug(f"{name} ({var_type}): {value}") def log_sample(name: str, sample: dict, show_keys: bool = True): """Log a data sample with all its fields.""" if debug_logger: debug_logger.info(f"\n--- {name} ---") if show_keys: debug_logger.info(f"Keys: {list(sample.keys())}") for key, value in sample.items(): if isinstance(value, str) and len(value) > 500: debug_logger.debug(f" {key}: ({len(value)} chars) {value[:500]}...") else: debug_logger.debug(f" {key}: {value}") def log_gpu_memory(label: str = ""): """Log GPU memory usage.""" if debug_logger and torch.cuda.is_available(): for i in range(torch.cuda.device_count()): allocated = torch.cuda.memory_allocated(i) / 1024**3 reserved = torch.cuda.memory_reserved(i) / 1024**3 debug_logger.info(f"GPU {i} {label}: {allocated:.2f}GB allocated, {reserved:.2f}GB reserved") def log_error(msg: str, exc: Exception = None): """Log an error with full stack trace.""" if debug_logger: debug_logger.error(f"ERROR: {msg}") if exc: debug_logger.error(f"Exception: {exc}") debug_logger.error(f"Stack trace:\n{traceback.format_exc()}") import torch import torch.nn as nn from torch.utils.data import Dataset, DataLoader import numpy as np # Hugging Face imports from transformers import ( AutoModelForCausalLM, AutoTokenizer, TrainingArguments, Trainer, TrainerCallback, DataCollatorForSeq2Seq, BitsAndBytesConfig, set_seed, ) from peft import ( LoraConfig, get_peft_model, prepare_model_for_kbit_training, TaskType, ) from datasets import load_dataset, Dataset as HFDataset from trl import SFTTrainer, SFTConfig # Metrics from nltk.translate.bleu_score import sentence_bleu, SmoothingFunction from rouge_score import rouge_scorer import evaluate # Logging and monitoring try: import wandb WANDB_AVAILABLE = True except ImportError: WANDB_AVAILABLE = False try: from torch.utils.tensorboard import SummaryWriter TENSORBOARD_AVAILABLE = True except ImportError: TENSORBOARD_AVAILABLE = False # ============================================================================ # Configuration Classes # ============================================================================ @dataclass class ModelConfig: """Model configuration.""" model_name: str = "Qwen/Qwen2.5-Coder-7B-Instruct" use_flash_attention: bool = False # Disabled - flash_attn not installed torch_dtype: str = "bfloat16" trust_remote_code: bool = True # Quantization (set use_quantization=False for A100s with enough VRAM) use_quantization: bool = False load_in_4bit: bool = True bnb_4bit_compute_dtype: str = "bfloat16" bnb_4bit_quant_type: str = "nf4" bnb_4bit_use_double_quant: bool = True @dataclass class LoRAConfig: """LoRA configuration based on paper recommendations.""" r: int = 64 # LoRA rank (higher for more capacity) lora_alpha: int = 128 # LoRA alpha (typically 2x rank) lora_dropout: float = 0.05 bias: str = "none" task_type: str = "CAUSAL_LM" target_modules: List[str] = field(default_factory=lambda: [ "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj" ]) @dataclass class TrainConfig: """Training configuration based on AnalogSeeker and ChipNeMo papers.""" output_dir: str = "./outputs/verilog_qa_model" # Training hyperparameters num_train_epochs: int = 3 per_device_train_batch_size: int = 4 per_device_eval_batch_size: int = 4 gradient_accumulation_steps: int = 4 # Learning rate (2e-5) learning_rate: float = 2e-5 weight_decay: float = 0.01 warmup_ratio: float = 0.03 lr_scheduler_type: str = "cosine" # Sequence length max_seq_length: int = 2048 # Precision bf16: bool = True fp16: bool = False # Saving and evaluation save_strategy: str = "steps" save_steps: int = 500 eval_strategy: str = "steps" eval_steps: int = 500 logging_steps: int = 10 # Gradient checkpointing for memory efficiency gradient_checkpointing: bool = True # DeepSpeed (optional, for multi-GPU) deepspeed: Optional[str] = None # Other seed: int = 42 dataloader_num_workers: int = 0 remove_unused_columns: bool = False @dataclass class LoggingConfig: """Logging configuration for comprehensive observability.""" log_dir: str = "./outputs/logs" log_level: str = "INFO" # Sample logging log_samples_every_n_steps: int = 100 num_samples_to_log: int = 5 max_sample_length: int = 2000 # No truncation for debugging # Wandb use_wandb: bool = True wandb_project: str = "verilog-qa-finetuning" wandb_run_name: Optional[str] = None # Tensorboard use_tensorboard: bool = True # ============================================================================ # Metrics Calculator (Based on Papers Comparison Table) # ============================================================================ class MetricsCalculator: """ Comprehensive metrics calculator implementing metrics from: - AMSBench: ACC, F1, MSE, NED, pass@k - AnalogSeeker: ACC on AMSBench-TQA - ChipNeMo: Pass@5, Likert scale - MMCircuitEval: BLEU, ROUGE, Embedding similarity """ def __init__(self): self.rouge_scorer = rouge_scorer.RougeScorer(['rouge1', 'rouge2', 'rougeL'], use_stemmer=True) self.smoothing = SmoothingFunction().method1 def calculate_accuracy(self, predictions: List[str], references: List[str]) -> float: """Exact match accuracy.""" correct = sum(1 for p, r in zip(predictions, references) if p.strip().lower() == r.strip().lower()) return correct / len(predictions) if predictions else 0.0 def calculate_bleu(self, predictions: List[str], references: List[str]) -> Dict[str, float]: """BLEU scores (1-4 gram).""" bleu_scores = {"bleu_1": [], "bleu_2": [], "bleu_3": [], "bleu_4": []} for pred, ref in zip(predictions, references): ref_tokens = ref.split() pred_tokens = pred.split() for n in range(1, 5): weights = tuple([1.0/n] * n + [0.0] * (4-n)) try: score = sentence_bleu([ref_tokens], pred_tokens, weights=weights, smoothing_function=self.smoothing) except: score = 0.0 bleu_scores[f"bleu_{n}"].append(score) return {k: np.mean(v) for k, v in bleu_scores.items()} def calculate_rouge(self, predictions: List[str], references: List[str]) -> Dict[str, float]: """ROUGE scores.""" rouge_scores = {"rouge1": [], "rouge2": [], "rougeL": []} for pred, ref in zip(predictions, references): scores = self.rouge_scorer.score(ref, pred) for key in rouge_scores: rouge_scores[key].append(scores[key].fmeasure) return {k: np.mean(v) for k, v in rouge_scores.items()} def calculate_f1(self, predictions: List[str], references: List[str]) -> float: """Token-level F1 score.""" f1_scores = [] for pred, ref in zip(predictions, references): pred_tokens = set(pred.lower().split()) ref_tokens = set(ref.lower().split()) if not pred_tokens or not ref_tokens: f1_scores.append(0.0) continue common = pred_tokens & ref_tokens precision = len(common) / len(pred_tokens) recall = len(common) / len(ref_tokens) if precision + recall > 0: f1 = 2 * precision * recall / (precision + recall) else: f1 = 0.0 f1_scores.append(f1) return np.mean(f1_scores) def calculate_all_metrics(self, predictions: List[str], references: List[str], categories: Optional[List[str]] = None) -> Dict[str, Any]: """Calculate all metrics including per-category breakdown.""" metrics = { "accuracy": self.calculate_accuracy(predictions, references), "f1": self.calculate_f1(predictions, references), **self.calculate_bleu(predictions, references), **self.calculate_rouge(predictions, references), "num_samples": len(predictions), } # Per-category metrics if categories: cat_metrics = defaultdict(lambda: {"preds": [], "refs": []}) for pred, ref, cat in zip(predictions, references, categories): cat_metrics[cat]["preds"].append(pred) cat_metrics[cat]["refs"].append(ref) metrics["per_category"] = {} for cat, data in cat_metrics.items(): metrics["per_category"][cat] = { "accuracy": self.calculate_accuracy(data["preds"], data["refs"]), "f1": self.calculate_f1(data["preds"], data["refs"]), "count": len(data["preds"]), } return metrics # ============================================================================ # Custom Dataset # ============================================================================ class VerilogQADataset(Dataset): """Dataset for Verilog QA pairs.""" def __init__(self, data_path: str, tokenizer, max_length: int = 2048): self.tokenizer = tokenizer self.max_length = max_length self.data = self._load_data(data_path) def _load_data(self, path: str) -> List[Dict]: data = [] with open(path, 'r') as f: for line in f: if line.strip(): data.append(json.loads(line)) return data def __len__(self): return len(self.data) def __getitem__(self, idx) -> Dict: item = self.data[idx] messages = item["messages"] # Format as chat template text = self.tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=False ) return { "text": text, "category": item.get("category", "unknown"), "difficulty": item.get("difficulty", "unknown"), "question": messages[1]["content"], "answer": messages[2]["content"], } # ============================================================================ # Comprehensive Logging Callback # ============================================================================ class ComprehensiveLoggingCallback(TrainerCallback): """ Custom callback for comprehensive logging as specified: - Full input/output logging (no truncation) - Per-step metrics - Sample predictions at regular intervals - Error analysis """ def __init__(self, config: LoggingConfig, tokenizer, metrics_calc: MetricsCalculator): self.config = config self.tokenizer = tokenizer self.metrics_calc = metrics_calc # Setup logging self.log_dir = Path(config.log_dir) self.log_dir.mkdir(parents=True, exist_ok=True) # Separate log files self.train_log = open(self.log_dir / "train.log", "w") self.val_log = open(self.log_dir / "val.log", "w") self.debug_samples = open(self.log_dir / "debug_samples.jsonl", "w") # Step counter self.global_step = 0 self.samples_logged = 0 def _log_json(self, file, data: Dict): """Write JSON line to log file.""" file.write(json.dumps(data, ensure_ascii=False, default=str) + "\n") file.flush() def on_log(self, args, state, control, logs=None, **kwargs): """Log training metrics.""" if logs: log_entry = { "timestamp": datetime.now().isoformat(), "step": state.global_step, "epoch": state.epoch, **logs } self._log_json(self.train_log, log_entry) # Print to console (handle both float and string values safely) loss_val = logs.get('loss', 'N/A') lr_val = logs.get('learning_rate', 'N/A') loss_str = f"{loss_val:.4f}" if isinstance(loss_val, (int, float)) else str(loss_val) lr_str = f"{lr_val:.2e}" if isinstance(lr_val, (int, float)) else str(lr_val) print(f"[Step {state.global_step}] loss={loss_str}, lr={lr_str}") def on_step_end(self, args, state, control, model=None, **kwargs): """Log sample predictions at regular intervals.""" self.global_step = state.global_step if state.global_step % self.config.log_samples_every_n_steps == 0: self._log_sample_predictions(model, kwargs.get('train_dataloader')) def _log_sample_predictions(self, model, dataloader): """Generate and log sample predictions.""" if model is None or dataloader is None: return model.eval() samples = [] try: batch = next(iter(dataloader)) for i in range(min(self.config.num_samples_to_log, len(batch.get('input_ids', [])))): sample_entry = { "step": self.global_step, "sample_id": self.samples_logged, "timestamp": datetime.now().isoformat(), } # Get input text (full, no truncation) if 'input_ids' in batch: input_text = self.tokenizer.decode(batch['input_ids'][i], skip_special_tokens=True) sample_entry["input_full"] = input_text[:self.config.max_sample_length] self._log_json(self.debug_samples, sample_entry) self.samples_logged += 1 except Exception as e: print(f"Warning: Could not log samples at step {self.global_step}: {e}") model.train() def on_evaluate(self, args, state, control, metrics=None, **kwargs): """Log evaluation metrics.""" if metrics: log_entry = { "timestamp": datetime.now().isoformat(), "step": state.global_step, "epoch": state.epoch, "type": "evaluation", **metrics } self._log_json(self.val_log, log_entry) def close(self): """Close log files.""" self.train_log.close() self.val_log.close() self.debug_samples.close() # ============================================================================ # Main Training Function # ============================================================================ def setup_model_and_tokenizer(model_config: ModelConfig, lora_config: LoRAConfig): """Setup model and tokenizer with optional quantization.""" print(f"\n{'='*60}") print(f"Loading model: {model_config.model_name}") print(f"{'='*60}") # Tokenizer tokenizer = AutoTokenizer.from_pretrained( model_config.model_name, trust_remote_code=model_config.trust_remote_code, padding_side="right", ) if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token # Model loading kwargs # Note: Don't use device_map='auto' with distributed training (accelerate) # The accelerator will handle device placement model_kwargs = { "trust_remote_code": model_config.trust_remote_code, "torch_dtype": getattr(torch, model_config.torch_dtype), } # Flash attention if model_config.use_flash_attention: model_kwargs["attn_implementation"] = "flash_attention_2" # Quantization config (optional - not needed for A100s) if model_config.use_quantization: bnb_config = BitsAndBytesConfig( load_in_4bit=model_config.load_in_4bit, bnb_4bit_compute_dtype=getattr(torch, model_config.bnb_4bit_compute_dtype), bnb_4bit_quant_type=model_config.bnb_4bit_quant_type, bnb_4bit_use_double_quant=model_config.bnb_4bit_use_double_quant, ) model_kwargs["quantization_config"] = bnb_config # Load model model = AutoModelForCausalLM.from_pretrained(model_config.model_name, **model_kwargs) # Prepare for k-bit training if quantized if model_config.use_quantization: model = prepare_model_for_kbit_training(model) # Enable gradient checkpointing with use_reentrant=False for DDP compatibility # This is required to avoid "Parameter marked as ready twice" error with LoRA + DDP model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False}) # Apply LoRA peft_config = LoraConfig( r=lora_config.r, lora_alpha=lora_config.lora_alpha, lora_dropout=lora_config.lora_dropout, bias=lora_config.bias, task_type=TaskType.CAUSAL_LM, target_modules=lora_config.target_modules, ) if os.environ.get("CQA_INIT_ADAPTER"): from peft import PeftModel as _PM model = _PM.from_pretrained(model, os.environ["CQA_INIT_ADAPTER"], is_trainable=True) print(f"continued training from adapter {os.environ['CQA_INIT_ADAPTER']}") else: model = get_peft_model(model, peft_config) # Print trainable parameters trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad) total_params = sum(p.numel() for p in model.parameters()) print(f"Trainable parameters: {trainable_params:,} ({100*trainable_params/total_params:.2f}%)") return model, tokenizer def main(): """Main training function for CircuitQA-Tool methodology.""" parser = argparse.ArgumentParser(description="Fine-tune LLM for CircuitQA-Tool") # Data arguments parser.add_argument("--train_data", type=str, default="training/data/train.jsonl") parser.add_argument("--val_data", type=str, default="training/data/val.jsonl") parser.add_argument("--output_dir", type=str, default="./outputs/verilog_qa_model") # Model arguments parser.add_argument("--model_name", type=str, default="Qwen/Qwen2.5-Coder-7B-Instruct") # Training arguments parser.add_argument("--epochs", type=int, default=3) parser.add_argument("--batch_size", type=int, default=4) parser.add_argument("--gradient_accumulation", type=int, default=4) parser.add_argument("--learning_rate", type=float, default=2e-5) parser.add_argument("--warmup_ratio", type=float, default=0.1) parser.add_argument("--weight_decay", type=float, default=0.01) # LoRA arguments parser.add_argument("--lora_r", type=int, default=64) parser.add_argument("--lora_alpha", type=int, default=128) parser.add_argument("--max_seq_length", type=int, default=2048) # CircuitQA-Tool specific parser.add_argument("--training_mode", type=str, default="unified", choices=["unified", "stage1", "stage2"], help="Training mode: unified (combined), stage1 (tool selection), stage2 (answer gen)") # Logging arguments parser.add_argument("--use_wandb", action="store_true") parser.add_argument("--wandb_project", type=str, default="circuitqa-tool-finetuning") parser.add_argument("--log_file", type=str, default=None) parser.add_argument("--metrics_log", type=str, default=None) # Other parser.add_argument("--seed", type=int, default=42) parser.add_argument("--debug", action="store_true", help="Debug mode with fewer samples") parser.add_argument("--local_rank", type=int, default=-1) # For distributed training args = parser.parse_args() # Set seed set_seed(args.seed) # Create output directory output_dir = Path(args.output_dir) output_dir.mkdir(parents=True, exist_ok=True) # ========================================================================== # INITIALIZE DEBUG LOGGING # ========================================================================== global debug_logger log_file = args.log_file or str(output_dir / "logs" / "training_debug.log") debug_logger = setup_debug_logging(log_file) log_section("STEP 1: INITIALIZATION") debug_logger.info(f"Python version: {sys.version}") debug_logger.info(f"PyTorch version: {torch.__version__}") debug_logger.info(f"CUDA available: {torch.cuda.is_available()}") if torch.cuda.is_available(): debug_logger.info(f"CUDA device count: {torch.cuda.device_count()}") for i in range(torch.cuda.device_count()): debug_logger.info(f" GPU {i}: {torch.cuda.get_device_name(i)}") log_section("STEP 2: ARGUMENTS") debug_logger.info("All command-line arguments:") for key, value in vars(args).items(): log_var(f"args.{key}", value) log_gpu_memory("before model loading") print(f"\n{'='*60}") print(f"CircuitQA-Tool Fine-Tuning") print(f"Training Mode: {args.training_mode}") print(f"{'='*60}") # Initialize configs log_section("STEP 3: CONFIGURATION") model_config = ModelConfig(model_name=args.model_name, use_quantization=False) lora_config = LoRAConfig(r=args.lora_r, lora_alpha=args.lora_alpha) train_config = TrainConfig( output_dir=args.output_dir, num_train_epochs=args.epochs, per_device_train_batch_size=args.batch_size, gradient_accumulation_steps=args.gradient_accumulation, learning_rate=args.learning_rate, warmup_ratio=args.warmup_ratio, weight_decay=args.weight_decay, max_seq_length=args.max_seq_length, ) logging_config = LoggingConfig( log_dir=str(output_dir / "logs"), use_wandb=args.use_wandb, wandb_project=args.wandb_project, ) debug_logger.info("Model Config:") log_var("model_config", asdict(model_config)) debug_logger.info("LoRA Config:") log_var("lora_config", asdict(lora_config)) debug_logger.info("Training Config:") log_var("train_config", asdict(train_config)) # Save configs training_info = { "methodology": "CircuitQA-Tool", "training_mode": args.training_mode, "model": asdict(model_config), "lora": asdict(lora_config), "training": asdict(train_config), "logging": asdict(logging_config), "args": vars(args), "timestamp": datetime.now().isoformat(), } with open(output_dir / "training_config.json", "w") as f: json.dump(training_info, f, indent=2, default=str) print(f"\nTraining configuration:") print(f" - Mode: {args.training_mode}") print(f" - Model: {args.model_name}") print(f" - LoRA rank: {args.lora_r}, alpha: {args.lora_alpha}") print(f" - Epochs: {args.epochs}") print(f" - Batch: {args.batch_size} x {args.gradient_accumulation} accumulation") print(f" - Learning rate: {args.learning_rate}") print(f" - Max seq length: {args.max_seq_length}") # Setup model and tokenizer log_section("STEP 4: MODEL LOADING") log_gpu_memory("before model loading") model, tokenizer = setup_model_and_tokenizer(model_config, lora_config) log_gpu_memory("after model loading") debug_logger.info(f"Model dtype: {model.dtype}") debug_logger.info(f"Tokenizer vocab size: {len(tokenizer)}") debug_logger.info(f"Tokenizer pad token: {tokenizer.pad_token}") # Load datasets log_section("STEP 5: DATASET LOADING") debug_logger.info(f"Train data path: {args.train_data}") debug_logger.info(f"Val data path: {args.val_data}") print(f"\nLoading training data from {args.train_data}...") train_dataset = load_dataset("json", data_files=args.train_data, split="train") print(f"Loaded {len(train_dataset):,} training samples") debug_logger.info(f"Train dataset size: {len(train_dataset)}") debug_logger.info(f"Train dataset columns: {train_dataset.column_names}") # Log first 3 samples from training data debug_logger.info("\n=== FIRST 3 TRAINING SAMPLES ===") for i in range(min(3, len(train_dataset))): log_sample(f"Train Sample {i}", dict(train_dataset[i])) print(f"Loading validation data from {args.val_data}...") val_dataset = load_dataset("json", data_files=args.val_data, split="train") print(f"Loaded {len(val_dataset):,} validation samples") debug_logger.info(f"Val dataset size: {len(val_dataset)}") debug_logger.info(f"Val dataset columns: {val_dataset.column_names}") # Initialize wandb if requested if args.use_wandb and WANDB_AVAILABLE: wandb.init( project=args.wandb_project, name=f"verilog-qa-{datetime.now().strftime('%Y%m%d_%H%M%S')}", config=vars(args), ) # Metrics calculator metrics_calc = MetricsCalculator() # Logging callback logging_callback = ComprehensiveLoggingCallback(logging_config, tokenizer, metrics_calc) # Format function for SFTTrainer - handles both V7 sanitized and legacy formats # Track if we've logged first batch for debugging formatting_logged = [False] # Use list to allow modification in nested function def formatting_prompts_func(examples): """Build chat messages from V7 sanitized data or use existing messages field.""" texts = [] # Debug: Log input structure on first call if not formatting_logged[0]: log_section("STEP 6: FORMATTING FUNCTION (First Batch)") debug_logger.info(f"Input keys: {list(examples.keys())}") debug_logger.info(f"Sample counts per key:") for key in examples.keys(): if isinstance(examples[key], list): debug_logger.info(f" {key}: {len(examples[key])} items") # Determine batch size from available keys if "question" in examples: batch_size = len(examples["question"]) elif "messages" in examples: batch_size = len(examples["messages"]) else: log_error(f"Neither 'question' nor 'messages' found in examples. Keys: {list(examples.keys())}") raise KeyError(f"Required field not found. Available keys: {list(examples.keys())}") if not formatting_logged[0]: debug_logger.info(f"Batch size: {batch_size}") for i in range(batch_size): try: # Check if we have pre-built messages (legacy format) if "messages" in examples and examples["messages"][i]: messages = examples["messages"][i] if not formatting_logged[0] and i == 0: debug_logger.info(f"Using pre-built messages format") log_var("messages[0]", messages) else: # Build messages from V7 sanitized fields question = examples["question"][i] answer = examples["answer"][i] verilog_code = examples.get("verilog_code", [""] * batch_size)[i] if not verilog_code and examples.get("source"): # released records reference the design _src = examples["source"][i] _path = os.path.join(os.environ.get("CIRCUITQA_SOURCES", "sources"), _src["sha256"] + ".v") if not os.path.exists(_path): raise SystemExit(f"design source {_path} not found: run scripts/fetch_sources.py first") verilog_code = open(_path, encoding="utf-8").read()[:3000] category = examples.get("category", [""] * batch_size)[i] tool_name = examples.get("tool_name", [""] * batch_size)[i] if not formatting_logged[0] and i == 0: debug_logger.info("Building messages from V7 sanitized fields") log_var("question", question, max_str_len=200) log_var("answer", answer, max_str_len=200) log_var("category", category) log_var("tool_name", tool_name) log_var("verilog_code (first 500 chars)", verilog_code[:500] if verilog_code else "EMPTY") # System prompt based on training mode if args.training_mode == "stage1": # Stage 1: Tool selection system_prompt = """You are an expert Verilog design analyzer. Given a question about Verilog code, determine which EDA tool to use and what parameters to pass. Available tools: - synthesis_tool: For PPA metrics (area, delay, power, gate count) - simulation_tool: For functional behavior, toggle rates, timing - graph_extractor: For structural analysis (CDFG, AIG, DFG extraction) - static_analyzer: For code quality, complexity, style analysis - optimization_advisor: For synthesis optimization recommendations - cross_stage_mapper: For RTL-to-netlist alignment analysis Output format: JSON with tool_name, parameters, and reasoning.""" stage1_target = examples.get("stage1_target", [""] * batch_size)[i] user_content = f"Verilog Code:\n```verilog\n{verilog_code[:2000]}\n```\n\nQuestion: {question}" assistant_content = stage1_target if stage1_target else answer elif args.training_mode == "stage2": # Stage 2: Answer generation with tool results system_prompt = """You are an expert Verilog design analyzer. Using the provided tool analysis results, answer the question about the Verilog design accurately and concisely.""" stage2_context = examples.get("stage2_context", [""] * batch_size)[i] user_content = f"Verilog Code:\n```verilog\n{verilog_code[:1500]}\n```\n\nTool Analysis:\n{stage2_context[:500]}\n\nQuestion: {question}" assistant_content = answer else: # Unified mode: Combined training WITH tool context # FIX: Include tool outputs so model learns to use exact values stage2_context = examples.get("stage2_context", [""] * batch_size)[i] system_prompt = f"""You are an expert Verilog design analyzer specializing in {category.replace('_', ' ')}. Use the provided tool analysis results to answer accurately. Always use the EXACT values from the tool output - do not estimate or approximate.""" # Include tool context in user prompt (same as stage2 mode) # per-record code cap (default 1500 as before; the auxiliary # explanation records set code_cap=3000 because their answers # refer to the whole module) _cc = examples.get("code_cap", [None] * batch_size)[i] code_cap = int(_cc) if _cc else 1500 if stage2_context: user_content = f"Verilog Code:\n```verilog\n{verilog_code[:code_cap]}\n```\n\nTool Analysis ({tool_name}):\n{stage2_context[:(int(examples.get('ctx_cap', [None]*batch_size)[i] or 600))]}\n\nQuestion: {question}" else: user_content = f"Verilog Code:\n```verilog\n{verilog_code[:2000]}\n```\n\nQuestion: {question}" assistant_content = answer messages = [ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_content}, {"role": "assistant", "content": assistant_content} ] if not formatting_logged[0] and i == 0: debug_logger.info(f"Built messages array with {len(messages)} entries") for j, msg in enumerate(messages): debug_logger.info(f" Message {j}: role={msg['role']}, content_len={len(msg['content'])}") text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False) texts.append(text) if not formatting_logged[0] and i == 0: debug_logger.info(f"\n=== FORMATTED TEXT (First Sample) ===") debug_logger.info(f"Text length: {len(text)} chars") debug_logger.debug(f"Full text:\n{text[:2000]}...") except Exception as e: log_error(f"Error formatting sample {i}", e) debug_logger.error(f"Problematic sample data:") for key in examples.keys(): if isinstance(examples[key], list) and i < len(examples[key]): val = examples[key][i] debug_logger.error(f" {key}: {type(val).__name__} = {str(val)[:200]}") raise if not formatting_logged[0]: debug_logger.info(f"Successfully formatted {len(texts)} samples") formatting_logged[0] = True return {"text": texts} # Training arguments log_section("STEP 7: TRAINING CONFIGURATION") import dataclasses as _dc _allowed = {f.name for f in _dc.fields(SFTConfig)} def _SFTConfig(**kw): dropped = sorted(set(kw) - _allowed) if dropped: print(f"[compat] SFTConfig does not accept {dropped}; dropping", flush=True) return SFTConfig(**{k: v for k, v in kw.items() if k in _allowed}) training_args = _SFTConfig( output_dir=args.output_dir, num_train_epochs=train_config.num_train_epochs, per_device_train_batch_size=train_config.per_device_train_batch_size, per_device_eval_batch_size=train_config.per_device_eval_batch_size, gradient_accumulation_steps=train_config.gradient_accumulation_steps, learning_rate=train_config.learning_rate, weight_decay=train_config.weight_decay, warmup_steps=int(train_config.warmup_ratio * 1000), # TRL 1.16 dropped warmup_ratio lr_scheduler_type=train_config.lr_scheduler_type, max_length=train_config.max_seq_length, # TRL 0.25+ uses max_length instead of max_seq_length bf16=train_config.bf16, fp16=train_config.fp16, save_strategy=train_config.save_strategy, save_steps=train_config.save_steps, eval_strategy=train_config.eval_strategy, eval_steps=train_config.eval_steps, logging_steps=train_config.logging_steps, gradient_checkpointing=train_config.gradient_checkpointing, gradient_checkpointing_kwargs={"use_reentrant": False}, # Required for DDP + LoRA seed=train_config.seed, dataloader_num_workers=train_config.dataloader_num_workers, report_to=["wandb", "tensorboard"] if args.use_wandb else ["tensorboard"], load_best_model_at_end=True, metric_for_best_model="eval_loss", greater_is_better=False, save_total_limit=3, logging_dir=str(output_dir / "tensorboard"), ddp_find_unused_parameters=False, # Disable unused parameter search for better performance ) debug_logger.info("SFTConfig parameters:") log_var("num_train_epochs", training_args.num_train_epochs) log_var("per_device_train_batch_size", training_args.per_device_train_batch_size) log_var("gradient_accumulation_steps", training_args.gradient_accumulation_steps) log_var("learning_rate", training_args.learning_rate) log_var("warmup_steps", training_args.warmup_steps) log_var("max_length", training_args.max_length) log_var("bf16", training_args.bf16) log_var("fp16", training_args.fp16) # Apply formatting function to datasets log_section("STEP 8: DATASET FORMATTING") debug_logger.info("Applying formatting function to datasets...") debug_logger.info(f"Train columns before formatting: {train_dataset.column_names}") print("Formatting datasets for training...") train_dataset = train_dataset.map( formatting_prompts_func, batched=True, remove_columns=[c for c in train_dataset.column_names if c != "text"], desc="Formatting train dataset" ) debug_logger.info(f"Train columns after formatting: {train_dataset.column_names}") debug_logger.info(f"Train dataset size after formatting: {len(train_dataset)}") # Log first formatted sample if len(train_dataset) > 0: first_formatted = train_dataset[0] debug_logger.info("\n=== FIRST FORMATTED TRAIN SAMPLE ===") debug_logger.info(f"Keys: {list(first_formatted.keys())}") if "text" in first_formatted: text_sample = first_formatted["text"] debug_logger.info(f"Text length: {len(text_sample)} chars") debug_logger.debug(f"Text (first 2000 chars):\n{text_sample[:2000]}") # Reset formatting logged flag for val dataset formatting_logged[0] = False val_dataset = val_dataset.map( formatting_prompts_func, batched=True, remove_columns=[c for c in val_dataset.column_names if c != "text"], desc="Formatting val dataset" ) print(f"Train dataset: {len(train_dataset):,} samples") print(f"Val dataset: {len(val_dataset):,} samples") debug_logger.info(f"Final train dataset size: {len(train_dataset)}") debug_logger.info(f"Final val dataset size: {len(val_dataset)}") # Create trainer log_section("STEP 9: TRAINER INITIALIZATION") log_gpu_memory("before trainer creation") trainer = SFTTrainer( model=model, args=training_args, train_dataset=train_dataset, eval_dataset=val_dataset, processing_class=tokenizer, callbacks=[logging_callback], ) log_gpu_memory("after trainer creation") debug_logger.info("SFTTrainer created successfully") # Train log_section("STEP 10: TRAINING START") print(f"\n{'='*60}") print("Starting training...") print(f"{'='*60}") debug_logger.info("Beginning training loop...") debug_logger.info(f"Total training steps: {trainer.state.max_steps if hasattr(trainer.state, 'max_steps') else 'unknown'}") log_gpu_memory("at training start") train_result = trainer.train() # Save final model log_section("STEP 11: TRAINING COMPLETE") debug_logger.info("Training completed successfully!") debug_logger.info(f"Training metrics: {train_result.metrics}") log_gpu_memory("after training") print(f"\nSaving final model to {args.output_dir}...") trainer.save_model() tokenizer.save_pretrained(args.output_dir) # Save training metrics with open(output_dir / "train_results.json", "w") as f: json.dump(train_result.metrics, f, indent=2) # Close logging logging_callback.close() if args.use_wandb and WANDB_AVAILABLE: wandb.finish() debug_logger.info("All logs saved successfully") debug_logger.info(f"Log file: {log_file}") print(f"\n{'='*60}") print("Training complete!") print(f"Model saved to: {args.output_dir}") print(f"Debug log: {log_file}") print(f"{'='*60}") if __name__ == "__main__": main()