resumecheck 0.2.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- resumecheck/__init__.py +23 -0
- resumecheck/accelerate.py +499 -0
- resumecheck/artifacts.py +214 -0
- resumecheck/cli.py +80 -0
- resumecheck/compare.py +359 -0
- resumecheck/hf.py +310 -0
- resumecheck/jsoninput.py +25 -0
- resumecheck/lightning.py +338 -0
- resumecheck/optimizer_identity.py +79 -0
- resumecheck/recorder.py +264 -0
- resumecheck/validation.py +34 -0
- resumecheck-0.2.1.dist-info/METADATA +964 -0
- resumecheck-0.2.1.dist-info/RECORD +17 -0
- resumecheck-0.2.1.dist-info/WHEEL +5 -0
- resumecheck-0.2.1.dist-info/entry_points.txt +2 -0
- resumecheck-0.2.1.dist-info/licenses/LICENSE +21 -0
- resumecheck-0.2.1.dist-info/top_level.txt +1 -0
resumecheck/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""resumecheck - verify that checkpoint-and-resume matches uninterrupted training.
|
|
2
|
+
|
|
3
|
+
The question this library answers: "If my training job crashes at step k and
|
|
4
|
+
I resume from the checkpoint, do I get the same model I would have gotten by
|
|
5
|
+
training straight through?" Silent state-restoration bugs (lost dataloader
|
|
6
|
+
position, wrong RNG, stale optimizer internals) corrupt long training runs
|
|
7
|
+
without ever raising an error.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from .recorder import TrajectoryRecorder, Trajectory, StepRecord
|
|
11
|
+
from .compare import CompareReport, Divergence, compare_trajectories
|
|
12
|
+
|
|
13
|
+
__version__ = "0.2.1"
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"TrajectoryRecorder",
|
|
17
|
+
"Trajectory",
|
|
18
|
+
"StepRecord",
|
|
19
|
+
"CompareReport",
|
|
20
|
+
"Divergence",
|
|
21
|
+
"compare_trajectories",
|
|
22
|
+
"__version__",
|
|
23
|
+
]
|
|
@@ -0,0 +1,499 @@
|
|
|
1
|
+
"""Accelerate adapter: verify resume parity end to end.
|
|
2
|
+
|
|
3
|
+
Runs the same deterministic training twice:
|
|
4
|
+
1. uninterrupted to ``max_steps``
|
|
5
|
+
2. up to ``resume_at``, ``save_state``, then ``load_state`` and resume
|
|
6
|
+
to ``max_steps``
|
|
7
|
+
and compares the recorded trajectories.
|
|
8
|
+
|
|
9
|
+
Uses the documented stateful resume path:
|
|
10
|
+
``DataLoaderConfiguration(use_stateful_dataloader=True,
|
|
11
|
+
use_seedable_sampler=True)`` with ``accelerator.save_state`` /
|
|
12
|
+
``load_state`` - the configuration accelerate documents for resuming a
|
|
13
|
+
DataLoader "from where it left off".
|
|
14
|
+
|
|
15
|
+
Same scope and limitations as the other adapters: deterministic CPU
|
|
16
|
+
verification; parity covers recorded observables (loss, batch content
|
|
17
|
+
fingerprint); a PASS is scoped to the tested configuration, not a general
|
|
18
|
+
guarantee.
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any, Callable, Optional, Union
|
|
24
|
+
|
|
25
|
+
from .compare import CompareReport, compare_trajectories
|
|
26
|
+
from .recorder import Trajectory, TrajectoryRecorder, fingerprint_tensor
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _require_accelerate():
|
|
30
|
+
try:
|
|
31
|
+
import torch # noqa: F401
|
|
32
|
+
import accelerate # noqa: F401
|
|
33
|
+
import torchdata # noqa: F401
|
|
34
|
+
except ImportError as e: # pragma: no cover
|
|
35
|
+
raise ImportError(
|
|
36
|
+
"resumecheck.accelerate requires torch, accelerate and torchdata "
|
|
37
|
+
"(pip install accelerate torchdata torch)"
|
|
38
|
+
) from e
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def check_accelerate(
|
|
42
|
+
model_factory: Callable[[], Any],
|
|
43
|
+
train_dataset: Any,
|
|
44
|
+
max_steps: int,
|
|
45
|
+
resume_at: int,
|
|
46
|
+
seed: int = 1234,
|
|
47
|
+
batch_size: int = 2,
|
|
48
|
+
rtol: float = 1e-5,
|
|
49
|
+
atol: float = 1e-7,
|
|
50
|
+
boundary_set_epoch_workaround: bool = False,
|
|
51
|
+
num_workers: int = 0,
|
|
52
|
+
artifacts_dir: Optional[Union[str, Path]] = None,
|
|
53
|
+
record_model_state: bool = False,
|
|
54
|
+
isolate_dataloader_rng: bool = False,
|
|
55
|
+
record_optimizer_state: bool = False,
|
|
56
|
+
) -> CompareReport:
|
|
57
|
+
"""Verify that save_state+load_state at ``resume_at`` reproduces an
|
|
58
|
+
uninterrupted ``max_steps`` run.
|
|
59
|
+
|
|
60
|
+
``model_factory`` must return a fresh nn.Module whose forward takes the
|
|
61
|
+
dataset's batch keys and returns a scalar loss tensor (or a dict/tuple
|
|
62
|
+
with a "loss" entry); ``train_dataset`` is a map-style dataset of dicts
|
|
63
|
+
of tensors. Deterministic CPU only.
|
|
64
|
+
|
|
65
|
+
``num_workers`` (default 0): worker processes for the DataLoader.
|
|
66
|
+
NOTE: with num_workers >= 1 the verified behavior of the stateful
|
|
67
|
+
path changes fundamentally (see README): prepare() eagerly creates
|
|
68
|
+
the iterator with the original plain RandomSampler, bypassing the
|
|
69
|
+
seedable sampler, and mid-epoch resume diverges on the verified
|
|
70
|
+
stacks. ``boundary_set_epoch_workaround`` is verified only with
|
|
71
|
+
num_workers=0.
|
|
72
|
+
|
|
73
|
+
``boundary_set_epoch_workaround`` (opt-in, default off): apply the
|
|
74
|
+
verified caller-side mitigation for the known epoch-boundary replay on
|
|
75
|
+
accelerate's stateful path - after ``load_state``, call
|
|
76
|
+
``train_dataloader.set_epoch(resume_epoch_index)`` so the shard's
|
|
77
|
+
uncheckpointed iteration counter is realigned before training
|
|
78
|
+
continues. With this flag on, the check verifies that parity holds
|
|
79
|
+
WITH the mitigation applied; it does not alter or excuse the raw
|
|
80
|
+
documented-path finding, and it is not an upstream fix. Fail-closed:
|
|
81
|
+
the mitigation is only verified at exact epoch boundaries, so the flag
|
|
82
|
+
requires ``resume_at`` to be an exact multiple of the steps per epoch.
|
|
83
|
+
|
|
84
|
+
``isolate_dataloader_rng=True`` gives the loader its own seed-matched
|
|
85
|
+
Torch generator so iterator construction does not consume the model's
|
|
86
|
+
global Torch CPU RNG (for example, dropout state). This changes the
|
|
87
|
+
checked setup and does not fix the documented sampler epoch issues.
|
|
88
|
+
Default off preserves the original experiment.
|
|
89
|
+
|
|
90
|
+
``record_model_state=True`` additionally fingerprints the unwrapped model's
|
|
91
|
+
full ``state_dict()`` after each optimizer step, including buffers. This
|
|
92
|
+
exact-bit evidence can catch state changes hidden by equal losses. It is
|
|
93
|
+
opt-in because copying and hashing model state is expensive; it does not
|
|
94
|
+
verify optimizer or arbitrary application state.
|
|
95
|
+
|
|
96
|
+
``artifacts_dir`` optionally retains the completed recorded trajectories,
|
|
97
|
+
report and comparison settings in a new local directory below an existing
|
|
98
|
+
parent. Existing paths are never replaced. Exceptions produce no bundle;
|
|
99
|
+
a final manifest marks completeness. These are recorded observables, not
|
|
100
|
+
model checkpoints. Review potentially sensitive evidence before sharing.
|
|
101
|
+
|
|
102
|
+
``record_optimizer_state=True`` additionally fingerprints the complete
|
|
103
|
+
optimizer ``state_dict()`` after each recorded update (including parameter
|
|
104
|
+
groups and moments). Fingerprints are compared exactly, not with loss
|
|
105
|
+
tolerances, and persisted in schema-4 evidence. This copies optimizer tensors
|
|
106
|
+
to CPU and adds time/memory cost proportional to state size. Unsupported
|
|
107
|
+
custom values raise instead of being skipped. Default off is unchanged.
|
|
108
|
+
This observes state_dict contents, not parameter identity, scheduler/RNG,
|
|
109
|
+
sharded/distributed state or an arbitrary optimizer implementation's hidden
|
|
110
|
+
state. Compare like-for-like deterministic runs with stable group ordering.
|
|
111
|
+
|
|
112
|
+
"""
|
|
113
|
+
if type(record_optimizer_state) is not bool:
|
|
114
|
+
raise TypeError("record_optimizer_state must be boolean")
|
|
115
|
+
|
|
116
|
+
from .validation import validate_step_limits
|
|
117
|
+
|
|
118
|
+
max_steps, resume_at = validate_step_limits(max_steps, resume_at)
|
|
119
|
+
if type(record_model_state) is not bool:
|
|
120
|
+
raise TypeError("record_model_state must be boolean")
|
|
121
|
+
if type(isolate_dataloader_rng) is not bool:
|
|
122
|
+
raise TypeError("isolate_dataloader_rng must be boolean")
|
|
123
|
+
_require_accelerate()
|
|
124
|
+
import tempfile
|
|
125
|
+
|
|
126
|
+
import torch
|
|
127
|
+
from torch.utils.data import DataLoader
|
|
128
|
+
|
|
129
|
+
from accelerate import Accelerator, DataLoaderConfiguration
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
if artifacts_dir is not None:
|
|
133
|
+
from .artifacts import validate_artifacts_dir
|
|
134
|
+
|
|
135
|
+
artifacts_dir = validate_artifacts_dir(artifacts_dir)
|
|
136
|
+
|
|
137
|
+
from .validation import validate_loader_shape
|
|
138
|
+
|
|
139
|
+
dataset_size, batch_size = validate_loader_shape(train_dataset, batch_size)
|
|
140
|
+
steps_per_epoch = -(-dataset_size // batch_size) # ceil
|
|
141
|
+
if boundary_set_epoch_workaround:
|
|
142
|
+
if resume_at % steps_per_epoch != 0:
|
|
143
|
+
raise ValueError(
|
|
144
|
+
"boundary_set_epoch_workaround is verified only at exact "
|
|
145
|
+
"epoch boundaries: resume_at="
|
|
146
|
+
f"{resume_at} is not a multiple of steps_per_epoch="
|
|
147
|
+
f"{steps_per_epoch}"
|
|
148
|
+
)
|
|
149
|
+
resume_epoch_index = resume_at // steps_per_epoch
|
|
150
|
+
else:
|
|
151
|
+
resume_epoch_index = None
|
|
152
|
+
|
|
153
|
+
def _loss_of(out):
|
|
154
|
+
if isinstance(out, dict):
|
|
155
|
+
return out["loss"]
|
|
156
|
+
if isinstance(out, (tuple, list)):
|
|
157
|
+
return out[0]
|
|
158
|
+
return out
|
|
159
|
+
|
|
160
|
+
def run(
|
|
161
|
+
name: str,
|
|
162
|
+
target: int,
|
|
163
|
+
stop_and_save_at: Optional[int] = None,
|
|
164
|
+
save_dir: Optional[str] = None,
|
|
165
|
+
ckpt: Optional[str] = None,
|
|
166
|
+
set_epoch_on_start: Optional[int] = None,
|
|
167
|
+
) -> Trajectory:
|
|
168
|
+
# Model factories and num_workers=0 datasets may use Python/NumPy
|
|
169
|
+
# RNGs too. Reset the same global streams for each experiment phase.
|
|
170
|
+
from accelerate.utils import set_seed
|
|
171
|
+
|
|
172
|
+
set_seed(seed)
|
|
173
|
+
cfg = DataLoaderConfiguration(
|
|
174
|
+
use_stateful_dataloader=True,
|
|
175
|
+
use_seedable_sampler=True,
|
|
176
|
+
data_seed=seed,
|
|
177
|
+
)
|
|
178
|
+
accelerator = Accelerator(cpu=True, dataloader_config=cfg)
|
|
179
|
+
model = model_factory()
|
|
180
|
+
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
|
|
181
|
+
dl = DataLoader(
|
|
182
|
+
train_dataset,
|
|
183
|
+
batch_size=batch_size,
|
|
184
|
+
shuffle=True,
|
|
185
|
+
num_workers=num_workers,
|
|
186
|
+
**({"generator": torch.Generator().manual_seed(seed)} if isolate_dataloader_rng else {}),
|
|
187
|
+
)
|
|
188
|
+
model, optimizer, dl = accelerator.prepare(model, optimizer, dl)
|
|
189
|
+
if ckpt:
|
|
190
|
+
accelerator.load_state(ckpt)
|
|
191
|
+
if set_epoch_on_start is not None:
|
|
192
|
+
dl.set_epoch(set_epoch_on_start)
|
|
193
|
+
|
|
194
|
+
rec = TrajectoryRecorder(name, seed=seed,
|
|
195
|
+
**({"isolate_dataloader_rng": True} if isolate_dataloader_rng else {}))
|
|
196
|
+
model.train()
|
|
197
|
+
step = 0
|
|
198
|
+
done = False
|
|
199
|
+
empty_epochs = 0
|
|
200
|
+
while not done:
|
|
201
|
+
epoch_start_step = step
|
|
202
|
+
for batch in dl:
|
|
203
|
+
batch_fp = fingerprint_tensor(batch)
|
|
204
|
+
out = model(**batch)
|
|
205
|
+
loss = _loss_of(out)
|
|
206
|
+
accelerator.backward(loss)
|
|
207
|
+
optimizer.step()
|
|
208
|
+
optimizer.zero_grad()
|
|
209
|
+
step += 1
|
|
210
|
+
rec.record(step=step, loss=float(loss.detach().cpu()))
|
|
211
|
+
rec.trajectory.steps[-1].batch_fingerprint = batch_fp
|
|
212
|
+
if record_optimizer_state:
|
|
213
|
+
rec.trajectory.steps[-1].optimizer_fingerprint = fingerprint_tensor(optimizer.state_dict())
|
|
214
|
+
if record_model_state:
|
|
215
|
+
rec.trajectory.steps[-1].model_fingerprint = fingerprint_tensor(
|
|
216
|
+
accelerator.unwrap_model(model).state_dict()
|
|
217
|
+
)
|
|
218
|
+
if stop_and_save_at is not None and step >= stop_and_save_at:
|
|
219
|
+
accelerator.save_state(save_dir)
|
|
220
|
+
done = True
|
|
221
|
+
break
|
|
222
|
+
if step >= target:
|
|
223
|
+
done = True
|
|
224
|
+
break
|
|
225
|
+
if step == epoch_start_step:
|
|
226
|
+
empty_epochs += 1
|
|
227
|
+
# A restored boundary iterator can be empty once. A second
|
|
228
|
+
# complete no-progress pass cannot certify requested steps.
|
|
229
|
+
if empty_epochs >= 2:
|
|
230
|
+
raise ValueError("Accelerate training made no progress for two consecutive dataloader iterations; requested steps were not verified")
|
|
231
|
+
else:
|
|
232
|
+
empty_epochs = 0
|
|
233
|
+
return rec.trajectory
|
|
234
|
+
|
|
235
|
+
full = run("uninterrupted", max_steps)
|
|
236
|
+
|
|
237
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
238
|
+
pre = run("pre-crash", max_steps, stop_and_save_at=resume_at, save_dir=tmp)
|
|
239
|
+
post = run(
|
|
240
|
+
"resumed",
|
|
241
|
+
max_steps - resume_at,
|
|
242
|
+
ckpt=tmp,
|
|
243
|
+
set_epoch_on_start=resume_epoch_index,
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
# offset the resumed phase's step numbers so they continue the pre-crash run
|
|
247
|
+
post.steps = [
|
|
248
|
+
type(s)(
|
|
249
|
+
step=s.step + resume_at,
|
|
250
|
+
loss=s.loss,
|
|
251
|
+
batch_fingerprint=s.batch_fingerprint,
|
|
252
|
+
grad_norm=s.grad_norm,
|
|
253
|
+
extras=s.extras,
|
|
254
|
+
model_fingerprint=s.model_fingerprint,
|
|
255
|
+
optimizer_fingerprint=s.optimizer_fingerprint,
|
|
256
|
+
)
|
|
257
|
+
for s in post.steps
|
|
258
|
+
]
|
|
259
|
+
resumed = Trajectory(name="resumed", meta={"seed": seed,
|
|
260
|
+
**({"isolate_dataloader_rng": True} if isolate_dataloader_rng else {})})
|
|
261
|
+
resumed.steps = pre.steps + post.steps
|
|
262
|
+
|
|
263
|
+
report = compare_trajectories(full, resumed, rtol=rtol, atol=atol)
|
|
264
|
+
if artifacts_dir is not None:
|
|
265
|
+
from .artifacts import save_comparison_artifacts
|
|
266
|
+
|
|
267
|
+
save_comparison_artifacts(artifacts_dir, full, resumed, report, rtol=rtol, atol=atol)
|
|
268
|
+
return report
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def check_accelerate_skip_path(
|
|
272
|
+
model_factory: Callable[[], Any],
|
|
273
|
+
train_dataset: Any,
|
|
274
|
+
max_steps: int,
|
|
275
|
+
resume_at: int,
|
|
276
|
+
seed: int = 1234,
|
|
277
|
+
batch_size: int = 2,
|
|
278
|
+
rtol: float = 1e-5,
|
|
279
|
+
atol: float = 1e-7,
|
|
280
|
+
skip_path_set_epoch_workaround: bool = False,
|
|
281
|
+
artifacts_dir: Optional[Union[str, Path]] = None,
|
|
282
|
+
record_model_state: bool = False,
|
|
283
|
+
isolate_dataloader_rng: bool = False,
|
|
284
|
+
record_optimizer_state: bool = False,
|
|
285
|
+
) -> CompareReport:
|
|
286
|
+
"""Verify the documented ``skip_first_batches`` resume path: run to
|
|
287
|
+
``resume_at``, ``save_state``, then ``load_state`` and resume with
|
|
288
|
+
``skip_first_batches`` for the remainder of the resume epoch (the
|
|
289
|
+
pattern accelerate's checkpointing docs and by_feature example show),
|
|
290
|
+
comparing against an uninterrupted ``max_steps`` run.
|
|
291
|
+
|
|
292
|
+
Known divergence (verified 2026-10-30 on accelerate 1.15.0 and master
|
|
293
|
+
1.16.0.dev0 @ 90b233c, torchdata 0.11.0): the skip wrapper consumes
|
|
294
|
+
the sampler without advancing ``DataLoaderShard``'s iteration counter,
|
|
295
|
+
so every post-resume epoch is shifted back one permutation.
|
|
296
|
+
|
|
297
|
+
``skip_path_set_epoch_workaround`` (opt-in, default off): apply the
|
|
298
|
+
verified caller-side mitigation - call
|
|
299
|
+
``train_dataloader.set_epoch(epoch)`` for each epoch AFTER the resume
|
|
300
|
+
epoch. Fail-closed: the mitigation is verified only for mid-epoch
|
|
301
|
+
resumes, so the flag requires ``resume_at`` to land strictly inside an
|
|
302
|
+
epoch. Caller-side mitigation, not an upstream fix; the raw check is
|
|
303
|
+
unchanged by it.
|
|
304
|
+
|
|
305
|
+
``isolate_dataloader_rng=True`` gives the loader its own seed-matched
|
|
306
|
+
Torch generator so iterator construction does not consume the model's
|
|
307
|
+
global Torch CPU RNG (for example, dropout state). This changes the
|
|
308
|
+
checked setup and does not fix the documented sampler epoch issues.
|
|
309
|
+
Default off preserves the original experiment.
|
|
310
|
+
|
|
311
|
+
``record_model_state=True`` additionally fingerprints the unwrapped model's
|
|
312
|
+
full ``state_dict()`` after each optimizer step, including buffers. This
|
|
313
|
+
exact-bit evidence can catch state changes hidden by equal losses. It is
|
|
314
|
+
opt-in because copying and hashing model state is expensive; it does not
|
|
315
|
+
verify optimizer or arbitrary application state.
|
|
316
|
+
|
|
317
|
+
``artifacts_dir`` optionally retains the completed recorded trajectories,
|
|
318
|
+
report and comparison settings in a new local directory below an existing
|
|
319
|
+
parent. Existing paths are never replaced. Exceptions produce no bundle;
|
|
320
|
+
a final manifest marks completeness. These are recorded observables, not
|
|
321
|
+
model checkpoints. Review potentially sensitive evidence before sharing.
|
|
322
|
+
|
|
323
|
+
``record_optimizer_state=True`` additionally fingerprints the complete
|
|
324
|
+
optimizer ``state_dict()`` after each recorded update (including parameter
|
|
325
|
+
groups and moments). Fingerprints are compared exactly, not with loss
|
|
326
|
+
tolerances, and persisted in schema-4 evidence. This copies optimizer tensors
|
|
327
|
+
to CPU and adds time/memory cost proportional to state size. Unsupported
|
|
328
|
+
custom values raise instead of being skipped. Default off is unchanged.
|
|
329
|
+
This observes state_dict contents, not parameter identity, scheduler/RNG,
|
|
330
|
+
sharded/distributed state or an arbitrary optimizer implementation's hidden
|
|
331
|
+
state. Compare like-for-like deterministic runs with stable group ordering.
|
|
332
|
+
|
|
333
|
+
"""
|
|
334
|
+
if type(record_optimizer_state) is not bool:
|
|
335
|
+
raise TypeError("record_optimizer_state must be boolean")
|
|
336
|
+
|
|
337
|
+
from .validation import validate_step_limits
|
|
338
|
+
|
|
339
|
+
max_steps, resume_at = validate_step_limits(max_steps, resume_at)
|
|
340
|
+
if type(record_model_state) is not bool:
|
|
341
|
+
raise TypeError("record_model_state must be boolean")
|
|
342
|
+
if type(isolate_dataloader_rng) is not bool:
|
|
343
|
+
raise TypeError("isolate_dataloader_rng must be boolean")
|
|
344
|
+
_require_accelerate()
|
|
345
|
+
import tempfile
|
|
346
|
+
|
|
347
|
+
import torch
|
|
348
|
+
from torch.utils.data import DataLoader
|
|
349
|
+
|
|
350
|
+
from accelerate import (
|
|
351
|
+
Accelerator,
|
|
352
|
+
DataLoaderConfiguration,
|
|
353
|
+
skip_first_batches,
|
|
354
|
+
)
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
if artifacts_dir is not None:
|
|
358
|
+
from .artifacts import validate_artifacts_dir
|
|
359
|
+
|
|
360
|
+
artifacts_dir = validate_artifacts_dir(artifacts_dir)
|
|
361
|
+
|
|
362
|
+
from .validation import validate_loader_shape
|
|
363
|
+
|
|
364
|
+
dataset_size, batch_size = validate_loader_shape(train_dataset, batch_size)
|
|
365
|
+
steps_per_epoch = -(-dataset_size // batch_size) # ceil
|
|
366
|
+
resume_epoch = resume_at // steps_per_epoch
|
|
367
|
+
resume_batches_in_epoch = resume_at % steps_per_epoch
|
|
368
|
+
if skip_path_set_epoch_workaround and resume_batches_in_epoch == 0:
|
|
369
|
+
raise ValueError(
|
|
370
|
+
"skip_path_set_epoch_workaround is verified only for mid-epoch "
|
|
371
|
+
"resumes: resume_at="
|
|
372
|
+
f"{resume_at} is an exact multiple of steps_per_epoch="
|
|
373
|
+
f"{steps_per_epoch}"
|
|
374
|
+
)
|
|
375
|
+
|
|
376
|
+
def _loss_of(out):
|
|
377
|
+
if isinstance(out, dict):
|
|
378
|
+
return out["loss"]
|
|
379
|
+
if isinstance(out, (tuple, list)):
|
|
380
|
+
return out[0]
|
|
381
|
+
return out
|
|
382
|
+
|
|
383
|
+
def run(
|
|
384
|
+
name: str,
|
|
385
|
+
target: int,
|
|
386
|
+
stop_and_save_at: Optional[int] = None,
|
|
387
|
+
save_dir: Optional[str] = None,
|
|
388
|
+
ckpt: Optional[str] = None,
|
|
389
|
+
start_epoch: int = 0,
|
|
390
|
+
skip_batches: int = 0,
|
|
391
|
+
) -> Trajectory:
|
|
392
|
+
# Model factories and num_workers=0 datasets may use Python/NumPy
|
|
393
|
+
# RNGs too. Reset the same global streams for each experiment phase.
|
|
394
|
+
from accelerate.utils import set_seed
|
|
395
|
+
|
|
396
|
+
set_seed(seed)
|
|
397
|
+
cfg = DataLoaderConfiguration(
|
|
398
|
+
use_stateful_dataloader=False,
|
|
399
|
+
use_seedable_sampler=True,
|
|
400
|
+
data_seed=seed,
|
|
401
|
+
)
|
|
402
|
+
accelerator = Accelerator(cpu=True, dataloader_config=cfg)
|
|
403
|
+
model = model_factory()
|
|
404
|
+
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
|
|
405
|
+
dl = DataLoader(train_dataset, batch_size=batch_size, shuffle=True,
|
|
406
|
+
**({"generator": torch.Generator().manual_seed(seed)} if isolate_dataloader_rng else {}))
|
|
407
|
+
model, optimizer, dl = accelerator.prepare(model, optimizer, dl)
|
|
408
|
+
if ckpt:
|
|
409
|
+
accelerator.load_state(ckpt)
|
|
410
|
+
|
|
411
|
+
rec = TrajectoryRecorder(name, seed=seed,
|
|
412
|
+
**({"isolate_dataloader_rng": True} if isolate_dataloader_rng else {}))
|
|
413
|
+
model.train()
|
|
414
|
+
step = 0
|
|
415
|
+
epoch = start_epoch
|
|
416
|
+
first_epoch = True
|
|
417
|
+
done = False
|
|
418
|
+
empty_epochs = 0
|
|
419
|
+
while not done:
|
|
420
|
+
epoch_start_step = step
|
|
421
|
+
if first_epoch and skip_batches:
|
|
422
|
+
active = skip_first_batches(dl, skip_batches)
|
|
423
|
+
else:
|
|
424
|
+
if (
|
|
425
|
+
not first_epoch
|
|
426
|
+
and ckpt
|
|
427
|
+
and skip_path_set_epoch_workaround
|
|
428
|
+
):
|
|
429
|
+
dl.set_epoch(epoch)
|
|
430
|
+
active = dl
|
|
431
|
+
first_epoch = False
|
|
432
|
+
for batch in active:
|
|
433
|
+
batch_fp = fingerprint_tensor(batch)
|
|
434
|
+
out = model(**batch)
|
|
435
|
+
loss = _loss_of(out)
|
|
436
|
+
accelerator.backward(loss)
|
|
437
|
+
optimizer.step()
|
|
438
|
+
optimizer.zero_grad()
|
|
439
|
+
step += 1
|
|
440
|
+
rec.record(step=step, loss=float(loss.detach().cpu()))
|
|
441
|
+
rec.trajectory.steps[-1].batch_fingerprint = batch_fp
|
|
442
|
+
if record_optimizer_state:
|
|
443
|
+
rec.trajectory.steps[-1].optimizer_fingerprint = fingerprint_tensor(optimizer.state_dict())
|
|
444
|
+
if record_model_state:
|
|
445
|
+
rec.trajectory.steps[-1].model_fingerprint = fingerprint_tensor(
|
|
446
|
+
accelerator.unwrap_model(model).state_dict()
|
|
447
|
+
)
|
|
448
|
+
if stop_and_save_at is not None and step >= stop_and_save_at:
|
|
449
|
+
accelerator.save_state(save_dir)
|
|
450
|
+
done = True
|
|
451
|
+
break
|
|
452
|
+
if step >= target:
|
|
453
|
+
done = True
|
|
454
|
+
break
|
|
455
|
+
epoch += 1
|
|
456
|
+
if step == epoch_start_step:
|
|
457
|
+
empty_epochs += 1
|
|
458
|
+
# A restored boundary iterator can be empty once. A second
|
|
459
|
+
# complete no-progress pass cannot certify requested steps.
|
|
460
|
+
if empty_epochs >= 2:
|
|
461
|
+
raise ValueError("Accelerate training made no progress for two consecutive dataloader iterations; requested steps were not verified")
|
|
462
|
+
else:
|
|
463
|
+
empty_epochs = 0
|
|
464
|
+
return rec.trajectory
|
|
465
|
+
|
|
466
|
+
full = run("uninterrupted", max_steps)
|
|
467
|
+
|
|
468
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
469
|
+
pre = run("pre-crash", max_steps, stop_and_save_at=resume_at, save_dir=tmp)
|
|
470
|
+
post = run(
|
|
471
|
+
"resumed",
|
|
472
|
+
max_steps - resume_at,
|
|
473
|
+
ckpt=tmp,
|
|
474
|
+
start_epoch=resume_epoch,
|
|
475
|
+
skip_batches=resume_batches_in_epoch,
|
|
476
|
+
)
|
|
477
|
+
|
|
478
|
+
post.steps = [
|
|
479
|
+
type(s)(
|
|
480
|
+
step=s.step + resume_at,
|
|
481
|
+
loss=s.loss,
|
|
482
|
+
batch_fingerprint=s.batch_fingerprint,
|
|
483
|
+
grad_norm=s.grad_norm,
|
|
484
|
+
extras=s.extras,
|
|
485
|
+
model_fingerprint=s.model_fingerprint,
|
|
486
|
+
optimizer_fingerprint=s.optimizer_fingerprint,
|
|
487
|
+
)
|
|
488
|
+
for s in post.steps
|
|
489
|
+
]
|
|
490
|
+
resumed = Trajectory(name="resumed", meta={"seed": seed,
|
|
491
|
+
**({"isolate_dataloader_rng": True} if isolate_dataloader_rng else {})})
|
|
492
|
+
resumed.steps = pre.steps + post.steps
|
|
493
|
+
|
|
494
|
+
report = compare_trajectories(full, resumed, rtol=rtol, atol=atol)
|
|
495
|
+
if artifacts_dir is not None:
|
|
496
|
+
from .artifacts import save_comparison_artifacts
|
|
497
|
+
|
|
498
|
+
save_comparison_artifacts(artifacts_dir, full, resumed, report, rtol=rtol, atol=atol)
|
|
499
|
+
return report
|