|
6 | 6 | # ----------------------------------------------------------------------------- |
7 | 7 |
|
8 | 8 | import json |
| 9 | +import logging |
| 10 | +import math |
9 | 11 | import os |
| 12 | +import time |
| 13 | +from pathlib import Path |
10 | 14 | from typing import Any, Dict, Optional |
11 | 15 |
|
| 16 | +import torch.distributed as dist |
12 | 17 | from transformers import ( |
13 | 18 | DefaultFlowCallback, |
14 | 19 | EarlyStoppingCallback, |
|
20 | 25 | from transformers.trainer_callback import TrainerCallback, TrainerControl, TrainerState |
21 | 26 |
|
22 | 27 | from QEfficient.finetune.experimental.core.component_registry import ComponentFactory, registry |
| 28 | +from QEfficient.finetune.experimental.core.config_manager import ConfigManager |
| 29 | +from QEfficient.finetune.experimental.core.logger import Logger |
23 | 30 | from QEfficient.finetune.experimental.core.utils.profiler_utils import ( |
24 | 31 | get_op_verifier_ctx, |
25 | 32 | init_qaic_profiling, |
|
32 | 39 | registry.callback("tensorboard")(TensorBoardCallback) |
33 | 40 |
|
34 | 41 |
|
| 42 | +# Making the rank 0 as default process to log information |
| 43 | +def is_main_process() -> bool: |
| 44 | + return not dist.is_initialized() or dist.get_rank() == 0 |
| 45 | + |
| 46 | + |
| 47 | +logger = Logger(__name__) |
| 48 | +# Extracting the user input name for the log file |
| 49 | +log_file_name = ConfigManager().config.training["log_file_name"] |
| 50 | + |
| 51 | + |
| 52 | +@registry.callback("train_logger") |
| 53 | +class TrainingLogger(TrainerCallback): |
| 54 | + """ |
| 55 | + A [`TrainerCallback`] that logs per epoch time, training metric (perplexity),training loss, evaluation metrics and loss etc. |
| 56 | + These are only logged for rank = 0. |
| 57 | + """ |
| 58 | + |
| 59 | + def __init__(self, log_file: str | None = log_file_name): |
| 60 | + # Log file setup |
| 61 | + output_dir = Path(ConfigManager().config.training["output_dir"]) |
| 62 | + self.log_file = os.path.join(output_dir, log_file) |
| 63 | + # Ensure directory exists |
| 64 | + os.makedirs(os.path.dirname(self.log_file), exist_ok=True) |
| 65 | + self.epoch_start_time = None |
| 66 | + self.best_eval_loss = float("inf") |
| 67 | + |
| 68 | + # ---------------------------------------------------- |
| 69 | + # Safe write to log (only rank 0) |
| 70 | + # ---------------------------------------------------- |
| 71 | + def write(self, text): |
| 72 | + if not is_main_process(): |
| 73 | + return |
| 74 | + logger.log_rank_zero(text) |
| 75 | + try: |
| 76 | + with open(self.log_file, "a") as f: |
| 77 | + f.write(text + "\n") |
| 78 | + f.flush() |
| 79 | + os.fsync(f.fileno()) |
| 80 | + |
| 81 | + except OSError: |
| 82 | + logging.exception("Failed to write to log file: %s", self.log_file) |
| 83 | + |
| 84 | + # ---------------------------------------------------- |
| 85 | + # EPOCH BEGIN |
| 86 | + # ---------------------------------------------------- |
| 87 | + def on_epoch_begin(self, args, state, control, **kwargs): |
| 88 | + if not is_main_process(): |
| 89 | + return |
| 90 | + |
| 91 | + epoch = int(state.epoch) + 1 |
| 92 | + self.epoch_start_time = time.time() |
| 93 | + if state.is_world_process_zero: |
| 94 | + self.write(f"TRAINING INFO: Starting epoch {epoch}/{int(args.num_train_epochs)}") |
| 95 | + |
| 96 | + # ---------------------------------------------------- |
| 97 | + # EVALUATION |
| 98 | + # ---------------------------------------------------- |
| 99 | + def on_evaluate(self, args, state, control, metrics, **kwargs): |
| 100 | + if not is_main_process(): |
| 101 | + return |
| 102 | + |
| 103 | + epoch = int(state.epoch) |
| 104 | + eval_loss = None |
| 105 | + eval_metric = None |
| 106 | + |
| 107 | + for entry in reversed(state.log_history): |
| 108 | + if "eval_loss" in entry: |
| 109 | + eval_loss = entry["eval_loss"] |
| 110 | + break |
| 111 | + if eval_loss is not None: |
| 112 | + eval_metric = math.exp(eval_loss) |
| 113 | + # Track best eval loss |
| 114 | + if eval_loss is not None and eval_loss < self.best_eval_loss: |
| 115 | + self.best_eval_loss = eval_loss |
| 116 | + if state.is_world_process_zero: |
| 117 | + self.write(f"EVALUATION INFO: Best eval loss on epoch {epoch} is {eval_loss:.4f}") |
| 118 | + if state.is_world_process_zero: |
| 119 | + self.write(f"EVALUATION INFO: Epoch {epoch}: Eval Loss: {eval_loss:.4f} || Eval metric: {eval_metric:.4f}") |
| 120 | + |
| 121 | + # ---------------------------------------------------- |
| 122 | + # EPOCH END — TRAIN LOSS + METRIC + TIME |
| 123 | + # ---------------------------------------------------- |
| 124 | + def on_epoch_end(self, args, state, control, **kwargs): |
| 125 | + if not is_main_process(): |
| 126 | + return |
| 127 | + |
| 128 | + epoch = int(state.epoch) |
| 129 | + epoch_time = time.time() - self.epoch_start_time |
| 130 | + |
| 131 | + # Extract the last recorded train loss |
| 132 | + train_loss = None |
| 133 | + for entry in reversed(state.log_history): |
| 134 | + if "loss" in entry: |
| 135 | + train_loss = entry["loss"] |
| 136 | + break |
| 137 | + # Compute perplexity safely |
| 138 | + train_metric = None |
| 139 | + if train_loss is not None: |
| 140 | + train_metric = math.exp(train_loss) |
| 141 | + |
| 142 | + if state.is_world_process_zero: |
| 143 | + self.write( |
| 144 | + f"TRAINING INFO: Epoch {epoch}: " |
| 145 | + f" Train epoch loss: {train_loss:.4f} || " |
| 146 | + f" Train metric: {train_metric} || " |
| 147 | + f" Epoch time {epoch_time:.2f} sec" |
| 148 | + ) |
| 149 | + state.log_history.append({"train/epoch_time_sec": epoch_time, "epoch": state.epoch}) |
| 150 | + control.should_log = True |
| 151 | + |
| 152 | + |
35 | 153 | @registry.callback("enhanced_progressbar") |
36 | 154 | class EnhancedProgressCallback(ProgressCallback): |
37 | 155 | """ |
@@ -233,3 +351,14 @@ def replace_progress_callback(trainer: Any, callbacks: list[Any], logger: Any = |
233 | 351 | import warnings |
234 | 352 |
|
235 | 353 | warnings.warn(f"Could not add enhanced progress callback: {e}") |
| 354 | + try: |
| 355 | + # Add Train Logger |
| 356 | + train_logger = ComponentFactory.create_callback("train_logger") |
| 357 | + trainer.add_callback(train_logger) |
| 358 | + except Exception as e: |
| 359 | + if logger: |
| 360 | + logger.log_rank_zero(f"Warning: Could not add train logger callback: {e}", level="warning") |
| 361 | + else: |
| 362 | + import warnings |
| 363 | + |
| 364 | + warnings.warn(f"Could not add train warning callback: {e}") |
0 commit comments