File size: 10,257 Bytes
cbc5e69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Loss logging and visualization utilities for SLTUNET training.
Automatically saves training loss and generates plots.
"""

import os
import csv
from datetime import datetime
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np


class LossLogger:
    """Logger for training loss with automatic visualization."""

    def __init__(self, output_dir, plot_freq=10):
        """
        Args:
            output_dir: Directory to save loss logs and plots
            plot_freq: Frequency to update plots (in steps)
        """
        self.output_dir = output_dir
        self.plot_freq = plot_freq

        # CSV file for training loss
        self.train_loss_file = os.path.join(output_dir, 'train_loss.csv')
        self.eval_loss_file = os.path.join(output_dir, 'eval_loss.csv')

        # Initialize CSV files
        self._init_csv_files()

        # Cache for plotting
        self.train_losses = []
        self.train_steps = []
        self.eval_losses = []
        self.eval_steps = []
        self.eval_bleus = []

    def _init_csv_files(self):
        """Initialize CSV files with headers."""
        # Training loss CSV
        if not os.path.exists(self.train_loss_file):
            with open(self.train_loss_file, 'w', newline='') as f:
                writer = csv.writer(f)
                writer.writerow(['timestamp', 'step', 'epoch', 'loss', 'gnorm', 'pnorm', 'lr'])

        # Evaluation loss CSV
        if not os.path.exists(self.eval_loss_file):
            with open(self.eval_loss_file, 'w', newline='') as f:
                writer = csv.writer(f)
                writer.writerow(['timestamp', 'step', 'eval_loss', 'bleu4', 'bleu1', 'bleu2', 'bleu3', 'otem2', 'utem4'])

    def log_train_step(self, step, epoch, loss, gnorm, pnorm, lr):
        """Log training step information."""
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        # Append to CSV
        with open(self.train_loss_file, 'a', newline='') as f:
            writer = csv.writer(f)
            writer.writerow([timestamp, step, epoch, loss, gnorm, pnorm, lr])

        # Update cache
        self.train_steps.append(step)
        self.train_losses.append(loss)

        # Generate plot if needed
        if step % self.plot_freq == 0:
            self.generate_plots()

    def log_eval_step(self, step, eval_loss, bleu_score, metrics_dict=None):
        """Log evaluation step information with multiple metrics."""
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        # Extract metrics
        bleu1 = metrics_dict.get('bleu1', 0.0) if metrics_dict else 0.0
        bleu2 = metrics_dict.get('bleu2', 0.0) if metrics_dict else 0.0
        bleu3 = metrics_dict.get('bleu3', 0.0) if metrics_dict else 0.0
        bleu4 = metrics_dict.get('bleu4', bleu_score) if metrics_dict else bleu_score
        otem2 = metrics_dict.get('otem2', 0.0) if metrics_dict else 0.0
        utem4 = metrics_dict.get('utem4', 0.0) if metrics_dict else 0.0

        # Append to CSV
        with open(self.eval_loss_file, 'a', newline='') as f:
            writer = csv.writer(f)
            writer.writerow([timestamp, step, eval_loss, bleu4, bleu1, bleu2, bleu3, otem2, utem4])

        # Update cache
        self.eval_steps.append(step)
        self.eval_losses.append(eval_loss)
        self.eval_bleus.append(bleu4)

        # Always generate plot after evaluation
        self.generate_plots()

    def load_history(self):
        """Load historical data from CSV files."""
        # Load training loss
        if os.path.exists(self.train_loss_file):
            with open(self.train_loss_file, 'r') as f:
                reader = csv.DictReader(f)
                for row in reader:
                    self.train_steps.append(int(row['step']))
                    self.train_losses.append(float(row['loss']))

        # Load evaluation loss
        if os.path.exists(self.eval_loss_file):
            with open(self.eval_loss_file, 'r') as f:
                reader = csv.DictReader(f)
                for row in reader:
                    self.eval_steps.append(int(row['step']))
                    self.eval_losses.append(float(row['eval_loss']))
                    # Backward compatibility: older CSVs used different BLEU column names
                    bleu_val = row.get('bleu_score', None)
                    if bleu_val is None or bleu_val == '':
                        bleu_val = row.get('bleu4', 0.0)
                    self.eval_bleus.append(float(bleu_val))

    def generate_plots(self):
        """Generate loss and BLEU plots."""
        if not self.train_steps:
            return

        # Create figure with 3 subplots
        fig = plt.figure(figsize=(14, 10))
        gs = fig.add_gridspec(3, 1, hspace=0.3)

        # Plot 1: Training loss
        ax1 = fig.add_subplot(gs[0])
        if self.train_steps:
            ax1.plot(self.train_steps, self.train_losses, 'b-', linewidth=1, alpha=0.6, label='Train Loss')

            # Add moving average
            if len(self.train_losses) > 20:
                window = 20
                ma = np.convolve(self.train_losses, np.ones(window)/window, mode='valid')
                ma_steps = self.train_steps[window-1:]
                ax1.plot(ma_steps, ma, 'r-', linewidth=2, label=f'Moving Avg ({window} steps)')

        ax1.set_xlabel('Training Step', fontsize=12, fontweight='bold')
        ax1.set_ylabel('Training Loss', fontsize=12, fontweight='bold')
        ax1.set_title(f'SLTUNET Training Loss (Current Step: {self.train_steps[-1] if self.train_steps else 0})',
                     fontsize=14, fontweight='bold')
        ax1.grid(True, alpha=0.3, linestyle='--')
        ax1.legend(loc='upper right')

        # Plot 2: Evaluation loss
        ax2 = fig.add_subplot(gs[1])
        if self.eval_steps:
            ax2.plot(self.eval_steps, self.eval_losses, 'go-', linewidth=2, markersize=6, label='Eval Loss')

            # Mark best
            if self.eval_losses:
                min_loss = min(self.eval_losses)
                min_idx = self.eval_losses.index(min_loss)
                ax2.plot(self.eval_steps[min_idx], min_loss, 'r*', markersize=15)
                ax2.annotate(f'Best: {min_loss:.4f}',
                           xy=(self.eval_steps[min_idx], min_loss),
                           xytext=(10, 10), textcoords='offset points',
                           bbox=dict(boxstyle='round', facecolor='yellow', alpha=0.8),
                           arrowprops=dict(arrowstyle='->', color='red'))

        ax2.set_xlabel('Training Step', fontsize=12, fontweight='bold')
        ax2.set_ylabel('Validation Loss', fontsize=12, fontweight='bold')
        ax2.set_title('Validation Loss', fontsize=14, fontweight='bold')
        ax2.grid(True, alpha=0.3, linestyle='--')
        ax2.legend(loc='upper right')

        # Plot 3: BLEU score
        ax3 = fig.add_subplot(gs[2])
        if self.eval_steps:
            ax3.plot(self.eval_steps, self.eval_bleus, 'mo-', linewidth=2, markersize=6, label='BLEU Score')

            # Mark best
            if self.eval_bleus:
                max_bleu = max(self.eval_bleus)
                max_idx = self.eval_bleus.index(max_bleu)
                ax3.plot(self.eval_steps[max_idx], max_bleu, 'r*', markersize=15)
                ax3.annotate(f'Best: {max_bleu:.6f}',
                           xy=(self.eval_steps[max_idx], max_bleu),
                           xytext=(10, -20), textcoords='offset points',
                           bbox=dict(boxstyle='round', facecolor='lightgreen', alpha=0.8),
                           arrowprops=dict(arrowstyle='->', color='green'))

        ax3.set_xlabel('Training Step', fontsize=12, fontweight='bold')
        ax3.set_ylabel('BLEU Score', fontsize=12, fontweight='bold')
        ax3.set_title('BLEU Score (Higher is Better)', fontsize=14, fontweight='bold')
        ax3.grid(True, alpha=0.3, linestyle='--')
        ax3.legend(loc='lower right')

        # Add timestamp
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        fig.text(0.99, 0.01, f'Updated: {timestamp}', ha='right', fontsize=9, style='italic')

        # Save plot
        plot_path = os.path.join(self.output_dir, 'training_curves.png')
        plt.savefig(plot_path, dpi=150, bbox_inches='tight')
        plt.close()

        # Also generate a summary text
        self._generate_summary()

    def _generate_summary(self):
        """Generate text summary of training."""
        summary_path = os.path.join(self.output_dir, 'training_summary.txt')

        with open(summary_path, 'w') as f:
            f.write("=" * 70 + "\n")
            f.write("  SLTUNET Training Summary\n")
            f.write(f"  Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
            f.write("=" * 70 + "\n\n")

            if self.train_steps:
                f.write(f"Training Progress:\n")
                f.write(f"  Current Step:     {self.train_steps[-1]}\n")
                f.write(f"  Total Steps:      {len(self.train_steps)}\n")
                f.write(f"  Latest Loss:      {self.train_losses[-1]:.6f}\n")

                if len(self.train_losses) > 10:
                    recent_avg = np.mean(self.train_losses[-10:])
                    f.write(f"  Recent Avg Loss:  {recent_avg:.6f} (last 10 steps)\n")

                f.write("\n")

            if self.eval_steps:
                f.write(f"Evaluation Results:\n")
                f.write(f"  Total Evaluations: {len(self.eval_steps)}\n")
                f.write(f"  Best Eval Loss:    {min(self.eval_losses):.6f} (step {self.eval_steps[self.eval_losses.index(min(self.eval_losses))]})\n")
                f.write(f"  Best BLEU Score:   {max(self.eval_bleus):.6f} (step {self.eval_steps[self.eval_bleus.index(max(self.eval_bleus))]})\n")
                f.write(f"  Latest Eval Loss:  {self.eval_losses[-1]:.6f}\n")
                f.write(f"  Latest BLEU:       {self.eval_bleus[-1]:.6f}\n")
                f.write("\n")

            f.write("=" * 70 + "\n")
            f.write(f"Loss logs saved to:\n")
            f.write(f"  - {self.train_loss_file}\n")
            f.write(f"  - {self.eval_loss_file}\n")
            f.write("=" * 70 + "\n")