|
| 1 | +"""Module for evaluating models.""" |
| 2 | + |
| 3 | +import csv |
| 4 | +import os |
| 5 | +import sys |
| 6 | +from pathlib import Path |
| 7 | +from typing import Dict, Optional |
| 8 | + |
| 9 | +import torch |
| 10 | +from accelerate.logging import get_logger |
| 11 | + |
| 12 | +from axolotl.common.cli import TrainerCliArgs |
| 13 | +from axolotl.logging_config import configure_logging |
| 14 | +from axolotl.train import TrainDatasetMeta |
| 15 | +from axolotl.utils.dict import DictDefault |
| 16 | +from axolotl.utils.models import load_model, load_processor, load_tokenizer |
| 17 | +from axolotl.utils.trainer import set_pytorch_cuda_alloc_conf, setup_trainer |
| 18 | + |
| 19 | +project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) |
| 20 | +src_dir = os.path.join(project_root, "src") |
| 21 | +sys.path.insert(0, src_dir) |
| 22 | + |
| 23 | +configure_logging() |
| 24 | +LOG = get_logger("axolotl.evaluate") |
| 25 | + |
| 26 | + |
| 27 | +def evaluate_dataset( |
| 28 | + trainer, dataset, dataset_type: str, flash_optimum: bool = False |
| 29 | +) -> Optional[Dict[str, float]]: |
| 30 | + """Helper function to evaluate a single dataset safely. |
| 31 | +
|
| 32 | + Args: |
| 33 | + trainer: The trainer instance |
| 34 | + dataset: Dataset to evaluate |
| 35 | + dataset_type: Type of dataset ('train' or 'eval') |
| 36 | + flash_optimum: Whether to use flash optimum |
| 37 | +
|
| 38 | + Returns: |
| 39 | + Dictionary of metrics or None if dataset is None |
| 40 | + """ |
| 41 | + if dataset is None: |
| 42 | + return None |
| 43 | + |
| 44 | + LOG.info(f"Starting {dataset_type} set evaluation...") |
| 45 | + |
| 46 | + if flash_optimum: |
| 47 | + with torch.backends.cuda.sdp_kernel( |
| 48 | + enable_flash=True, |
| 49 | + enable_math=True, |
| 50 | + enable_mem_efficient=True, |
| 51 | + ): |
| 52 | + metrics = trainer.evaluate(dataset, metric_key_prefix=dataset_type) |
| 53 | + else: |
| 54 | + metrics = trainer.evaluate(dataset, metric_key_prefix=dataset_type) |
| 55 | + |
| 56 | + LOG.info(f"{dataset_type.capitalize()} set evaluation completed!") |
| 57 | + LOG.info(f"{dataset_type.capitalize()} Metrics:") |
| 58 | + for key, value in metrics.items(): |
| 59 | + LOG.info(f"{key}: {value}") |
| 60 | + |
| 61 | + return metrics |
| 62 | + |
| 63 | + |
| 64 | +def evaluate( |
| 65 | + *, cfg: DictDefault, cli_args: TrainerCliArgs, dataset_meta: TrainDatasetMeta |
| 66 | +) -> Dict[str, float]: |
| 67 | + """ |
| 68 | + Evaluate a model on training and validation datasets |
| 69 | +
|
| 70 | + Args: |
| 71 | + cfg: Configuration dictionary |
| 72 | + cli_args: Command line arguments |
| 73 | + dataset_meta: Dataset metadata containing training and evaluation datasets |
| 74 | +
|
| 75 | + Returns: |
| 76 | + Tuple containing: |
| 77 | + - The model (either PeftModel or PreTrainedModel) |
| 78 | + - The tokenizer |
| 79 | + - Dictionary of evaluation metrics |
| 80 | + """ |
| 81 | + # pylint: disable=duplicate-code |
| 82 | + # Enable expandable segments for cuda allocation to improve VRAM usage |
| 83 | + set_pytorch_cuda_alloc_conf() |
| 84 | + |
| 85 | + # Load tokenizer |
| 86 | + LOG.debug( |
| 87 | + f"loading tokenizer... {cfg.tokenizer_config or cfg.base_model_config}", |
| 88 | + main_process_only=True, |
| 89 | + ) |
| 90 | + tokenizer = load_tokenizer(cfg) |
| 91 | + |
| 92 | + # Load processor for multimodal models if needed |
| 93 | + processor = None |
| 94 | + if cfg.is_multimodal: |
| 95 | + processor = load_processor(cfg, tokenizer) |
| 96 | + |
| 97 | + # Get datasets |
| 98 | + train_dataset = dataset_meta.train_dataset |
| 99 | + eval_dataset = dataset_meta.eval_dataset |
| 100 | + total_num_steps = dataset_meta.total_num_steps |
| 101 | + |
| 102 | + # Load model |
| 103 | + LOG.debug("loading model for evaluation...") |
| 104 | + model, _ = load_model( |
| 105 | + cfg, tokenizer, processor=processor, inference=cli_args.inference |
| 106 | + ) |
| 107 | + |
| 108 | + # Set up trainer |
| 109 | + trainer = setup_trainer( |
| 110 | + cfg, |
| 111 | + train_dataset=train_dataset, |
| 112 | + eval_dataset=eval_dataset, |
| 113 | + model=(model, None, None), # No need for model_ref or peft_config |
| 114 | + tokenizer=tokenizer, |
| 115 | + processor=processor, |
| 116 | + total_num_steps=total_num_steps, |
| 117 | + ) |
| 118 | + |
| 119 | + # Evaluate datasets |
| 120 | + all_metrics = {} |
| 121 | + train_metrics = evaluate_dataset(trainer, train_dataset, "train", cfg.flash_optimum) |
| 122 | + eval_metrics = evaluate_dataset(trainer, eval_dataset, "eval", cfg.flash_optimum) |
| 123 | + |
| 124 | + if train_metrics: |
| 125 | + all_metrics.update(train_metrics) |
| 126 | + if eval_metrics: |
| 127 | + all_metrics.update(eval_metrics) |
| 128 | + |
| 129 | + # Save metrics to CSV if output directory is specified and we have metrics |
| 130 | + if cfg.output_dir and (train_metrics or eval_metrics): |
| 131 | + output_dir = Path(cfg.output_dir) |
| 132 | + output_dir.mkdir(parents=True, exist_ok=True) |
| 133 | + |
| 134 | + metrics_file = output_dir / "eval_summary.csv" |
| 135 | + with metrics_file.open("w", newline="", encoding="utf-8") as file: |
| 136 | + writer = csv.writer(file) |
| 137 | + writer.writerow(["metric", "training", "validation"]) |
| 138 | + |
| 139 | + # Get unique metric names (removing prefixes) from available metrics |
| 140 | + train_metric_names = { |
| 141 | + k.replace("train_", ""): k for k in (train_metrics or {}) |
| 142 | + } |
| 143 | + eval_metric_names = { |
| 144 | + k.replace("eval_", ""): k for k in (eval_metrics or {}) |
| 145 | + } |
| 146 | + all_metric_names = sorted( |
| 147 | + set(train_metric_names.keys()) | set(eval_metric_names.keys()) |
| 148 | + ) |
| 149 | + |
| 150 | + for metric_name in all_metric_names: |
| 151 | + train_value = ( |
| 152 | + train_metrics.get(train_metric_names.get(metric_name, ""), "") |
| 153 | + if train_metrics |
| 154 | + else "" |
| 155 | + ) |
| 156 | + eval_value = ( |
| 157 | + eval_metrics.get(eval_metric_names.get(metric_name, ""), "") |
| 158 | + if eval_metrics |
| 159 | + else "" |
| 160 | + ) |
| 161 | + writer.writerow([metric_name, train_value, eval_value]) |
| 162 | + |
| 163 | + LOG.info(f"Evaluation results saved to {metrics_file}") |
| 164 | + |
| 165 | + del model |
| 166 | + del tokenizer |
| 167 | + |
| 168 | + return all_metrics |
0 commit comments