File size: 13,895 Bytes
518db7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
PyTorch Lightning callbacks for validation during training.

Provides non-blocking validation callbacks that integrate with TensorBoard
and respect the 100s training budget.

Key optimization: CUDA streams for validation prefetch to overlap with training.
"""

__all__ = [
    "ValidationCallback",
    "CombinedValidationCallback",
]

# Standard library
import logging
from typing import Any, Optional

# Third-party
import pytorch_lightning as pl
import torch
from torch.cuda import Stream

# Local
from .validators import Validator
from .constants import (
    VALIDATION_MAX_LENGTH,
    VALIDATION_TEMPERATURE,
    LOW_GRAMMAR_SCORE_THRESHOLD,
    TARGET_GRAMMAR_SCORE,
    MAX_TENSORBOARD_SAMPLES,
    GRAMMAR_VALIDATION_FREQUENCY,
)

logger = logging.getLogger(__name__)

class ValidationCallback(pl.Callback):
    """
    Generic validation callback that delegates to a validator.

    Runs validation at specified frequency with proper GPU memory management
    and non-blocking execution.

    CUDA streams optimization: Validation runs in a separate stream to overlap
    with training, reducing validation overhead by 10-20%.
    """

    def __init__(self, validator: Validator, frequency: int, name: str) -> None:
        """
        Initialize ValidationCallback.

        Args:
            validator: Validator instance (FastValidator, GrammarValidator, etc.)
            frequency: Run validation every N steps
            name: Name for logging (e.g., "fast", "grammar")
        """
        super().__init__()
        self.validator = validator
        self.frequency = frequency
        self.name = name

        # CUDA stream for async validation (if GPU available)
        self.stream: Optional[Stream]
        if torch.cuda.is_available():
            self.stream = torch.cuda.Stream()  # type: ignore[no-untyped-call]
            logger.info(f"ValidationCallback[{name}]: CUDA stream created for async validation")
        else:
            self.stream = None
            logger.warning(f"ValidationCallback[{name}]: CUDA not available, stream disabled")

    def on_train_batch_end(
        self,
        trainer: pl.Trainer,
        pl_module: pl.LightningModule,
        outputs: Any,
        batch: Any,
        batch_idx: int
    ) -> None:
        """
        Run validation at specified frequency.

        Uses CUDA streams to overlap validation with training:
        1. Launch validation in separate stream
        2. Training continues in default stream
        3. Sync before logging to ensure results are ready
        """
        if pl_module.global_step % self.frequency != 0:
            return

        if pl_module.global_step == 0:
            return  # Skip step 0

        try:
            # Run validation in separate CUDA stream if available
            if self.stream is not None:
                with torch.cuda.stream(self.stream):
                    results = self.validator.validate(pl_module.model, pl_module.global_step)

                # Training continues in default stream while validation runs
                # Sync before logging to ensure validation completed
                torch.cuda.current_stream().wait_stream(self.stream)
            else:
                # CPU fallback (no stream)
                results = self.validator.validate(pl_module.model, pl_module.global_step)

            # Log to TensorBoard
            self._log_results(pl_module, results)

            # Alert if quality issues detected
            self._check_alerts(pl_module.global_step, results)

        except Exception as e:
            logger.error(
                "Validation failed",
                extra={
                    "validator": self.name,
                    "step": pl_module.global_step,
                    "error": str(e)
                }
            )

    def _log_results(self, pl_module: pl.LightningModule, results: dict[str, Any]) -> None:
        """Log validation results to TensorBoard."""
        # Log scalar metrics
        for key, value in results.items():
            if isinstance(value, (int, float, bool)):
                pl_module.log(f"{self.name}_{key}", float(value))

        # Log text samples if available
        if "samples" in results and results["samples"]:
            try:
                sample_text = "\n\n".join(
                    f"**Sample {i+1}:** {sample}"
                    for i, sample in enumerate(results["samples"][:MAX_TENSORBOARD_SAMPLES])
                )
                if pl_module.logger is not None:
                    pl_module.logger.experiment.add_text(  # type: ignore[attr-defined]
                        f"{self.name}_samples",
                        sample_text,
                        pl_module.global_step
                    )
            except Exception as e:
                logger.warning(
                    "Failed to log samples",
                    extra={"error": str(e)}
                )

    def _check_alerts(self, step: int, results: dict[str, Any]) -> None:
        """Check for quality issues and alert."""
        if self.name == "fast" and results.get("is_garbage"):
            logger.warning(
                "GARBAGE OUTPUT detected",
                extra={
                    "step": step,
                    "ascii_ratio": results.get('ascii_ratio', 0),
                    "avg_length": results.get('avg_length', 0),
                    "repetition_ratio": results.get('repetition_ratio', 0)
                }
            )

        if self.name == "grammar":
            score = results.get("grammar_score", 0.0)
            if score < LOW_GRAMMAR_SCORE_THRESHOLD:
                logger.warning(
                    "LOW GRAMMAR SCORE",
                    extra={
                        "step": step,
                        "score": score,
                        "target": TARGET_GRAMMAR_SCORE,
                        "is_fallback": results.get('is_fallback', False)
                    }
                )

            # Check for degrading trend
            if hasattr(self.validator, 'get_trend'):
                trend = self.validator.get_trend()
                if trend == "degrading":
                    logger.warning(
                        "GRAMMAR DEGRADING",
                        extra={"step": step, "trend": trend}
                    )

class CombinedValidationCallback(pl.Callback):
    """
    Combined validation callback that shares samples between validators.

    Generates samples once and passes them to both FastValidator and
    GrammarValidator, reducing generation cost by 50%.

    Runs at the frequency of the slower validator (grammar every 200 steps).

    CUDA streams optimization: Sample generation runs in separate stream to
    overlap with training.
    """

    def __init__(
        self,
        fast_validator: Validator,
        grammar_validator: Validator,
        test_prompts: list[str],
        frequency: int = GRAMMAR_VALIDATION_FREQUENCY
    ) -> None:
        """
        Initialize CombinedValidationCallback.

        Args:
            fast_validator: FastValidator instance
            grammar_validator: GrammarValidator instance
            test_prompts: List of prompts to generate samples from
            frequency: Run validation every N steps (default: 200)
        """
        super().__init__()
        self.fast_validator = fast_validator
        self.grammar_validator = grammar_validator
        self.test_prompts = test_prompts
        self.frequency = frequency

        # CUDA stream for async validation (if GPU available)
        self.stream: Optional[Stream]
        if torch.cuda.is_available():
            self.stream = torch.cuda.Stream()  # type: ignore[no-untyped-call]
            logger.info("CombinedValidationCallback: CUDA stream created for async validation")
        else:
            self.stream = None
            logger.warning("CombinedValidationCallback: CUDA not available, stream disabled")

    def on_train_batch_end(
        self,
        trainer: pl.Trainer,
        pl_module: pl.LightningModule,
        outputs: Any,
        batch: Any,
        batch_idx: int
    ) -> None:
        """
        Run combined validation at specified frequency.

        Uses CUDA streams to overlap validation with training:
        1. Launch sample generation + validation in separate stream
        2. Training continues in default stream
        3. Sync before logging to ensure results are ready
        """
        if pl_module.global_step % self.frequency != 0:
            return

        if pl_module.global_step == 0:
            return  # Skip step 0

        try:
            # Run validation in separate CUDA stream if available
            if self.stream is not None:
                with torch.cuda.stream(self.stream):
                    samples = self._generate_samples(pl_module)
                    fast_results = self.fast_validator.validate_samples(
                        samples, pl_module.global_step
                    )
                    grammar_results = self.grammar_validator.validate_samples(
                        samples, pl_module.global_step
                    )

                # Training continues in default stream while validation runs
                # Sync before logging to ensure validation completed
                torch.cuda.current_stream().wait_stream(self.stream)
            else:
                # CPU fallback (no stream)
                samples = self._generate_samples(pl_module)
                fast_results = self.fast_validator.validate_samples(
                    samples, pl_module.global_step
                )
                grammar_results = self.grammar_validator.validate_samples(
                    samples, pl_module.global_step
                )

            # Log results for both validators
            self._log_results(pl_module, "fast", fast_results)
            self._log_results(pl_module, "grammar", grammar_results)

            # Check alerts for both
            self._check_fast_alerts(pl_module.global_step, fast_results)
            self._check_grammar_alerts(pl_module.global_step, grammar_results)

        except Exception as e:
            logger.error(
                "Combined validation failed",
                extra={
                    "step": pl_module.global_step,
                    "error": str(e)
                }
            )

    def _generate_samples(self, pl_module: pl.LightningModule) -> list[str]:
        """
        Generate samples for validation.

        Args:
            pl_module: LightningModule with model

        Returns:
            List of generated text samples
        """
        samples = []
        with torch.inference_mode():
            for prompt in self.test_prompts:
                try:
                    sample = pl_module.model.generate_text(
                        prompt,
                        max_length=VALIDATION_MAX_LENGTH,
                        temperature=VALIDATION_TEMPERATURE
                    )
                    samples.append(sample)
                except Exception as e:
                    logger.warning(
                        "Generation failed for prompt",
                        extra={"prompt": prompt, "error": str(e)}
                    )
                    samples.append("")
        return samples

    def _log_results(self, pl_module: pl.LightningModule, name: str, results: dict[str, Any]) -> None:
        """Log validation results to TensorBoard."""
        # Log scalar metrics
        for key, value in results.items():
            if isinstance(value, (int, float, bool)):
                pl_module.log(f"{name}_{key}", float(value))

        # Log text samples if available
        if "samples" in results and results["samples"]:
            try:
                sample_text = "\n\n".join(
                    f"**Sample {i+1}:** {sample}"
                    for i, sample in enumerate(results["samples"][:MAX_TENSORBOARD_SAMPLES])
                )
                if pl_module.logger is not None:
                    pl_module.logger.experiment.add_text(  # type: ignore[attr-defined]
                        f"{name}_samples",
                        sample_text,
                        pl_module.global_step
                    )
            except Exception as e:
                logger.warning(
                    "Failed to log samples",
                    extra={"error": str(e)}
                )

    def _check_fast_alerts(self, step: int, results: dict[str, Any]) -> None:
        """Check for fast validation quality issues."""
        if results.get("is_garbage"):
            logger.warning(
                "GARBAGE OUTPUT detected",
                extra={
                    "step": step,
                    "ascii_ratio": results.get('ascii_ratio', 0),
                    "avg_length": results.get('avg_length', 0),
                    "repetition_ratio": results.get('repetition_ratio', 0)
                }
            )

    def _check_grammar_alerts(self, step: int, results: dict[str, Any]) -> None:
        """Check for grammar validation quality issues."""
        score = results.get("grammar_score", 0.0)
        if score < LOW_GRAMMAR_SCORE_THRESHOLD:
            logger.warning(
                "LOW GRAMMAR SCORE",
                extra={
                    "step": step,
                    "score": score,
                    "target": TARGET_GRAMMAR_SCORE,
                    "is_fallback": results.get('is_fallback', False)
                }
            )

        # Check for degrading trend
        if hasattr(self.grammar_validator, 'get_trend'):
            trend = self.grammar_validator.get_trend()
            if trend == "degrading":
                logger.warning(
                    "GRAMMAR DEGRADING",
                    extra={"step": step, "trend": trend}
                )