File size: 10,057 Bytes
0edf333
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Lightning execution with explicit, audited manual optimization.

The stages retain their domain-specific batches, token-weighted accumulation,
source-bound checkpoint payloads and W&B records. Lightning owns the fit loop,
device/precision strategy, backward calls, clipping, and optimizer steps. Manual
optimization is required because unequal MLM microbatches must be weighted by
their selected target counts rather than averaged as equally sized batches.
"""

import math
import random

import lightning.pytorch as pl
import torch
from torch.utils.data import DataLoader, IterableDataset


def _global_gradient_norm(model):
    squares = []
    for name, parameter in model.named_parameters():
        if parameter.grad is None:
            continue
        gradient = parameter.grad.detach().float()
        if not torch.isfinite(gradient).all():
            raise RuntimeError(f"Nonfinite gradient in {name}")
        squares.append(float(gradient.square().sum().item()))
    norm = math.sqrt(sum(squares))
    if not math.isfinite(norm) or norm <= 0:
        raise RuntimeError("Optimizer update has no finite nonzero gradient")
    return norm


class AuditedLightningModule(pl.LightningModule):
    """A real LightningModule whose callbacks describe one native training stage."""

    automatic_optimization = False

    def __init__(
        self, model, optimizer, *, step_fn, epoch_start_fn=None,
        epoch_end_fn=None, fit_start_fn=None, max_norm=1.0,
    ):
        super().__init__()
        if not math.isfinite(max_norm) or max_norm <= 0:
            raise ValueError("Gradient clipping max_norm must be finite and positive")
        self.model = model
        self._optimizer = optimizer
        self._step_fn = step_fn
        self._epoch_start_fn = epoch_start_fn
        self._epoch_end_fn = epoch_end_fn
        self._fit_start_fn = fit_start_fn
        self.max_norm = float(max_norm)
        self._pending_update = False
        self._backwards = 0
        self._fit_rng = None
        self.runtime_report = {
            "framework": "lightning.pytorch",
            "lightning_version": pl.__version__,
            "trainer": "lightning.pytorch.Trainer",
            "optimization": "manual; Lightning manual_backward, clip_gradients and LightningOptimizer.step",
            "precision": "32-true",
            "optimizer_class": f"{type(optimizer).__module__}.{type(optimizer).__qualname__}",
            "gradient_clipping_algorithm": "global L2 norm",
            "gradient_clip_max_norm": self.max_norm,
            "optimizer_updates": 0,
            "backward_calls": 0,
            "clipped_updates": 0,
            "maximum_pre_clip_global_l2": 0.0,
            "maximum_post_clip_global_l2": 0.0,
            "all_post_clip_norms_within_limit": True,
        }

    def configure_optimizers(self):
        return self._optimizer

    def transfer_batch_to_device(self, batch, device, dataloader_idx):
        # Domain code transfers only the active tensor microbatch. Eager transfer
        # would defeat the original memory bound and move metadata unnecessarily.
        return batch

    def on_train_start(self):
        actual_device = torch.device(self.trainer.strategy.root_device)
        parameter_devices = sorted({str(parameter.device) for parameter in self.model.parameters()})
        requested_device = torch.device(self.runtime_report["requested_device"])
        if (actual_device.type != requested_device.type
                or (requested_device.index is not None and actual_device.index != requested_device.index)
                or parameter_devices != [str(actual_device)]):
            raise RuntimeError(
                f"Lightning device mismatch: requested {requested_device}, strategy {actual_device}, "
                f"parameter devices {parameter_devices}"
            )
        self.runtime_report.update({
            "actual_root_device": str(actual_device),
            "actual_parameter_devices": parameter_devices,
            "accelerator_class": (
                f"{type(self.trainer.accelerator).__module__}."
                f"{type(self.trainer.accelerator).__qualname__}"
            ),
            "all_parameters_on_requested_accelerator": True,
        })
        # Trainer setup and DataLoader initialization must not perturb the native
        # model/dropout RNG stream, including legacy epoch-boundary resumes.
        state = self._fit_rng
        if state is not None:
            torch.set_rng_state(state["torch"])
            random.setstate(state["python"])
            if "cuda" in state:
                torch.cuda.set_rng_state_all(state["cuda"])
            if "mps" in state:
                torch.mps.set_rng_state(state["mps"])
        if self._fit_start_fn is not None:
            self._fit_start_fn(self)

    def on_train_epoch_start(self):
        self.model.train()
        if self._epoch_start_fn is not None:
            self._epoch_start_fn(self)

    def on_train_epoch_end(self):
        if self._epoch_end_fn is not None:
            self._epoch_end_fn(self)

    def training_step(self, batch, batch_idx):
        return self._step_fn(self, batch, batch_idx)

    def begin_update(self):
        if self._pending_update:
            raise RuntimeError("Previous optimizer update was not completed")
        optimizer = self.optimizers()
        optimizer.zero_grad(set_to_none=True)
        self._pending_update = True
        self._backwards = 0
        return optimizer

    def backward_loss(self, loss):
        if not self._pending_update:
            raise RuntimeError("begin_update must precede backward")
        if not torch.isfinite(loss).all():
            raise RuntimeError("Nonfinite training loss")
        self.manual_backward(loss)
        self._backwards += 1

    def finish_update(self, gradient_metrics_fn):
        if not self._pending_update or self._backwards < 1:
            raise RuntimeError("Optimizer update requires at least one backward call")
        metrics = gradient_metrics_fn(self.model)
        pre_norm = _global_gradient_norm(self.model)
        optimizer = self.optimizers()
        # Trainer.gradient_clip_val is deliberately unset: Lightning requires
        # explicit clipping inside a manual-optimization training_step.
        self.clip_gradients(
            optimizer, gradient_clip_val=self.max_norm, gradient_clip_algorithm="norm"
        )
        post_norm = _global_gradient_norm(self.model)
        tolerance = max(1e-6, self.max_norm * 1e-5)
        if post_norm > self.max_norm + tolerance:
            raise RuntimeError(
                f"Gradient clipping failed: norm {post_norm} exceeds {self.max_norm}"
            )
        optimizer.step()
        clipped = pre_norm > self.max_norm
        metrics.update({
            "gradients/pre_clip_global_l2": pre_norm,
            "gradients/post_clip_global_l2": post_norm,
            "gradients/clip_max_norm": self.max_norm,
            "gradients/clipping_applied": int(clipped),
        })
        report = self.runtime_report
        report["optimizer_updates"] += 1
        report["backward_calls"] += self._backwards
        report["clipped_updates"] += int(clipped)
        report["maximum_pre_clip_global_l2"] = max(
            report["maximum_pre_clip_global_l2"], pre_norm
        )
        report["maximum_post_clip_global_l2"] = max(
            report["maximum_post_clip_global_l2"], post_norm
        )
        self._pending_update = False
        return metrics


class _EpochBatches(IterableDataset):
    def __init__(self, module, factory, size):
        self.module, self.factory, self.size = module, factory, size

    def __iter__(self):
        return iter(self.factory(self.module))

    def __len__(self):
        return self.size


def _identity(value):
    return value


def fit_audited(module, batch_factory, *, epochs, device, batches_per_epoch):
    """Execute complete epochs through Trainer.fit without changing batch order.

    Existing epoch-boundary checkpoints remain plain, source-bound model and
    optimizer payloads. They are restored before this call rather than treated as
    Lightning checkpoints; their architecture/state keys stay backward compatible.
    """
    if epochs < 1 or batches_per_epoch < 1:
        raise ValueError("Lightning fit needs positive epochs and batches_per_epoch")
    device = torch.device(device)
    module.runtime_report["requested_device"] = str(device)
    module._fit_rng = {"torch": torch.get_rng_state(), "python": random.getstate()}
    if device.type == "cuda":
        module._fit_rng["cuda"] = torch.cuda.get_rng_state_all()
    elif device.type == "mps":
        module._fit_rng["mps"] = torch.mps.get_rng_state()
    loader = DataLoader(
        _EpochBatches(module, batch_factory, batches_per_epoch),
        batch_size=None, num_workers=0, collate_fn=_identity,
        generator=torch.Generator().manual_seed(0),
    )
    trainer = pl.Trainer(
        accelerator=device.type,
        devices=[device.index] if device.type == "cuda" and device.index is not None else 1,
        precision="32-true", max_epochs=int(epochs),
        logger=False, enable_checkpointing=False, enable_progress_bar=False,
        enable_model_summary=False, num_sanity_val_steps=0,
        use_distributed_sampler=False, inference_mode=False,
    )
    module.train()
    trainer.fit(module, train_dataloaders=loader)
    # Lightning tears its strategy down by moving the module to CPU. Public stage
    # functions continue with their established evaluation/export device, so make
    # that placement explicit after fit (optimizer state is no longer stepped).
    module.model.to(device)
    if module._pending_update:
        raise RuntimeError("Training ended with an incomplete optimizer update")
    module.runtime_report["trainer_global_step"] = trainer.global_step
    if trainer.global_step != module.runtime_report["optimizer_updates"]:
        raise RuntimeError("Lightning optimizer steps differ from audited update count")
    return trainer