File size: 28,743 Bytes
980282b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
from __future__ import annotations

from dotenv import load_dotenv
# <modify> Credentials are not copied; an optional project-local .env must not be required.
# assert load_dotenv(), "Failed to load .env file. Make sure it exists and is properly formatted."
from pathlib import Path
load_dotenv(Path(__file__).resolve().parents[1] / ".env", override=False)
import os
import re
import torch
from torch.distributed.elastic.multiprocessing.errors import record
import gc
from tqdm import tqdm
import shutil
import json
import datetime
import sys
import itertools
import threading
import tyro
import importlib
from typing import TYPE_CHECKING
import time
if TYPE_CHECKING:
    from psi.config.config import LaunchConfig
from psi.utils import batch_str_to_tensor, seed_everything, initialize_overwatch, nice, flatten
from psi.trainers import Trainer

overwatch = initialize_overwatch(__name__)

from accelerate import Accelerator, DeepSpeedPlugin
from accelerate.data_loader import (
    DataLoaderStateMixin as AcceleratorDataLoaderStateMixin,
)
from accelerate.utils import ProjectConfiguration, set_seed as accelerate_set_seed
import random, numpy as np

MAX_TRAINING_EPOCHS = 1_000_000


def _wait_for_first_batch_readiness(epoch: int) -> None:
    """Align all ranks through the CPU store after each epoch's first read.

    A rank may lazily initialize a different modality at an epoch boundary and
    spend minutes in OSS I/O.  Waiting with the default TCPStore keeps faster
    ranks from entering forward/backward (and therefore NCCL collectives)
    until every rank owns its first batch.  The epoch is part of the key so a
    later boundary cannot accidentally reuse an earlier readiness signal.
    """
    if not torch.distributed.is_available() or not torch.distributed.is_initialized():
        return
    store = torch.distributed.distributed_c10d._get_default_store()
    rank = torch.distributed.get_rank()
    world_size = torch.distributed.get_world_size()
    namespace = f"psi0/first_batch_ready/epoch_{int(epoch)}"
    keys = [f"{namespace}/rank_{index}" for index in range(world_size)]
    store.set(keys[rank], "1")
    timeout_seconds = max(
        int(os.environ.get("PSI_FIRST_BATCH_READY_TIMEOUT", "1200")),
        1,
    )
    store.wait(keys, datetime.timedelta(seconds=timeout_seconds))


def _start_wait_progress(desc: str, *, position: int = 0) -> tuple[threading.Event, threading.Thread | None]:
    done = threading.Event()
    if not overwatch.is_rank_zero():
        return done, None

    def _run() -> None:
        bar = tqdm(
            total=None,
            desc=desc,
            unit="s",
            position=position,
            leave=True,
            dynamic_ncols=True,
            bar_format="{desc}: {n}s elapsed [{elapsed}]",
        )
        try:
            while not done.wait(1.0):
                bar.update(1)
        finally:
            bar.close()

    thread = threading.Thread(target=_run, name=f"wait-progress-{desc}", daemon=True)
    thread.start()
    return done, thread

def _auto_tag_run(run_name: str):
    """commit the code and tag the run with the run name"""
    import subprocess

    subprocess.run(["git", "add", "."], check=False)
    subprocess.run(["git", "commit", "-m", f"Auto-commit for {run_name}"], check=False)
    subprocess.run(["git", "tag", run_name], check=False)
    # subprocess.run(["git", "push", "--tags"], check=True)

def _initialize_accelerator(trainer: Trainer) -> Accelerator:
    os.makedirs(trainer.project_dir, exist_ok=True)
    logging_dir = os.path.join(trainer.project_dir, trainer.cfg.log.logging_dir)
    accelerator_project_config = ProjectConfiguration(
        project_dir=trainer.project_dir, logging_dir=logging_dir
    )

    # setup FSDP training strategy if needed
    fsdp_plugin = None
    if trainer.cfg.train.data_parallel == "fsdp":
        fsdp_plugin = trainer.get_fsdp_plugin()
    
    deepspeed_plugin = None
    if trainer.cfg.train.data_parallel == "deepspeed":
        # SONGLIN: use accelerate launch config instead
        ds_config_path = trainer.cfg.train.deepspeed_config 
        deepspeed_plugin = DeepSpeedPlugin(zero_stage=3, hf_ds_config=ds_config_path)
    

    report_to = trainer.cfg.log.report_to
    if isinstance(report_to, str) and report_to.strip().lower() in {
        "none",
        "null",
        "off",
        "disabled",
    }:
        report_to = None

    accelerator = Accelerator(
        gradient_accumulation_steps=trainer.cfg.train.gradient_accumulation_steps,
        mixed_precision=trainer.cfg.train.mixed_precision,
        # downcast_bf16=True,
        log_with=report_to,
        project_config=accelerator_project_config,
        fsdp_plugin=fsdp_plugin,
        deepspeed_plugin=deepspeed_plugin
    )

    if trainer.cfg.train.data_parallel == "deepspeed":
        # When using DeepSpeed, accelerate.prepare() requires you 
        # to pass at least one of training or evaluation dataloaders 
        # with batch_size attribute returning an integer value or alternatively 
        # set an integer value in train_micro_batch_size_per_gpu 
        # in the deepspeed config file or assign integer value to
        accelerator.deepspeed_plugin.deepspeed_config["train_micro_batch_size_per_gpu"] = trainer.device_train_batch_size # type: ignore

    # Initialize the trackers unless in eval or debug mode
    if overwatch.is_rank_zero() and not trainer.cfg.eval:
        if trainer.cfg.auto_tag_run:
            _auto_tag_run(trainer.run_name)

        if trainer.cfg.log.report_to == "wandb":
            tracker_config = (
                trainer.cfg.model_dump()
            )  # cfg.model_dump() # dict(vars(cfg.task))
            
            # Add environment variables to tracker config for wandb logging
            if "_ENV_INFO_JSON" in os.environ:
                env_info = json.loads(os.environ["_ENV_INFO_JSON"])
                tracker_config["environment_variables"] = env_info
            
            wandb_config = dict(
                trainer.cfg.wandb
            )  # cfg.wandb.model_dump() #vars(copy.deepcopy(cfg.wandb))
            wandb_config["name"] = trainer.run_name
            wandb_config["dir"] = os.path.abspath(
                os.path.expanduser(trainer.project_dir)
            )
            wandb_config["group"] = trainer.cfg.train.name
            project = wandb_config.pop("project", "default")

            # wandb resume with old hisotry
            if trainer.cfg.train.resume_from_checkpoint is not None and trainer.cfg.wandb.resume != "never":
                run_id = wandb_config.get("id") or getattr(trainer.cfg.wandb, "id", None)
                if not run_id :
                    run_dir = os.path.join(*trainer.cfg.train.resume_from_checkpoint.split("/")[:3])
                    if os.path.exists(os.path.join(run_dir, "run_config.json")):
                        with open(os.path.join(run_dir, "run_config.json")) as f:
                            run_id = (json.load(f).get("wandb") or {}).get("id")
                            overwatch.info(f"resume wandb with run id: {run_id}")
                        wandb_config["id"] = run_id
                        
            accelerator.init_trackers(project, tracker_config, {"wandb": wandb_config})
            for tracker in accelerator.trackers:
                if tracker.name == "wandb":
                    trainer.cfg.wandb.id = tracker.run.id
                    trainer.cfg.wandb.name = tracker.run.name
                    trainer.cfg.wandb.entity = tracker.run.entity
                    trainer.cfg.wandb.group = tracker.run.group

        # Log the configuration
        os.makedirs(trainer.project_dir, exist_ok=True)
        # draccus.dump(cfg, open(f'{project_dir}/run_config.yaml','w'))
        with open(f"{trainer.project_dir}/run_config.json", "w") as f:
             f.write(trainer.cfg.model_dump_json(indent=4))
        overwatch.info(f"Saved configuration to {trainer.project_dir}")

        # Write down the sys.argv to argv.txt
        argv_path = os.path.join(trainer.project_dir, "argv.txt")
        with open(argv_path, "w") as f:
            i = 0
            while i < len(sys.argv):
                arg = sys.argv[i]
                if arg.startswith('--'):
                    # Start of a key, check for list values
                    line = [arg]
                    j = i + 1
                    # Collect all following args that do not start with '--'
                    while j < len(sys.argv) and not sys.argv[j].startswith('--'):
                        line.append(sys.argv[j])
                        j += 1
                    f.write(' '.join(line) + '\n')
                    i = j
                else:
                    f.write(arg + '\n')
                    i += 1

        # write system envs to envs.txt
        if "_ENV_INFO_JSON" in os.environ:
            env_info = json.loads(os.environ["_ENV_INFO_JSON"])
            envs_path = os.path.join(trainer.project_dir, "envs.txt")
            with open(envs_path, "w") as f:
                for k, v in env_info.items():
                    f.write(f"{k}={v}\n")

        # copy dataset statistics file if exists
        if hasattr(trainer.cfg.data.transform.field, "stat_path"):
            from psi.utils import resolve_path
            stat_path = resolve_path(trainer.cfg.data.transform.field.stat_path) # type: ignore
            if os.path.exists(stat_path):
                dst_stat_path = os.path.join(trainer.project_dir, "dataset_statistics.json")
                shutil.copy2(stat_path, dst_stat_path)
    trainer.accelerator = accelerator
    return accelerator


def train(config: LaunchConfig):
    torch.cuda.set_device(device_id := overwatch.local_rank())
    torch.cuda.empty_cache()
    startup_bar = tqdm(
        total=5,
        desc="Startup",
        disable=not overwatch.is_rank_zero(),
        position=0,
        leave=False,
    )

    if config.seed:
        overwatch.info(f"Seed everything with {config.seed}")
        seed_everything(config.seed)
        
    trainer = Trainer.instantiate(config, device_id)  # PosttrainTrainer
    overwatch.info("Initialize models ... ")
    trainer.init_models()
    startup_bar.set_postfix_str("models ready")
    startup_bar.update(1)
    accelerator = _initialize_accelerator(trainer)  # 分布式训练框架,先不看了
    startup_bar.set_postfix_str("accelerator ready")
    startup_bar.update(1)
    overwatch.info(f"Training configurations:")
    overwatch.info(f"training task: '{config.train.name}'", ctx_level=1)
    overwatch.info(f"run name: {trainer.run_name}", ctx_level=1)
    overwatch.info(f"seed: {config.seed}", ctx_level=1)
    overwatch.info(f"mixed precision: {trainer.dtype}", ctx_level=1)
    overwatch.info(f"warmup steps: {trainer.num_warmup_steps}", ctx_level=1)
    overwatch.info(f"validation steps: {config.train.validation_steps}", ctx_level=1)
    overwatch.info(f"checkpoint steps: {config.train.checkpointing_steps}", ctx_level=1)
    overwatch.info(f"max gradient norm: {config.train.max_grad_norm}", ctx_level=1)

    overwatch.info("Build datasets ...")
    train_dataset, val_dataset = trainer.create_datasets()
    startup_bar.set_postfix_str("datasets ready")
    startup_bar.update(1)
    overwatch.info(f"Num training samples:", ctx_level=1)
    overwatch.info(f"Training dataset size: {trainer.len_train_dataset:,}", ctx_level=2)  # type: ignore
    if val_dataset:
        overwatch.info(f"Val dataset size: {trainer.len_val_dataset:,}", ctx_level=2)  # type: ignore
    overwatch.info("Build dataloaders ...")
    trainer.create_dataloaders(train_dataset, val_dataset)
    startup_bar.set_postfix_str("dataloaders ready")
    startup_bar.update(1)
    
    overwatch.info("Initialize optimizers and schedulers...")
    trainer.create_optimizer_and_scheduler(trainer.max_training_steps)
    startup_bar.set_postfix_str("optim ready")
    startup_bar.update(1)
    startup_bar.close()

    # fmt: off
    overwatch.info("***** Running training *****")
    overwatch.info(f"Num training examples = {trainer.len_train_dataset}", ctx_level=1)
    overwatch.info(f"Max training Epochs = {trainer.max_training_epochs}", ctx_level=1)
    overwatch.info(f"Total optimization steps = {trainer.max_training_steps}", ctx_level=2)
    overwatch.info(f"Num steps Per Epoch = {trainer.num_steps_per_epoch}", ctx_level=2)
    overwatch.info(f"Effective training epochs = {trainer.max_training_steps/trainer.num_steps_per_epoch*trainer.world_size:.2f}", ctx_level=2)
    overwatch.info(f"Global train batch size (w. parallel, distributed & accumulation) = {trainer.global_train_batch_size}", ctx_level=1)
    overwatch.info(f"Device train batch size = {trainer.device_train_batch_size}", ctx_level=2)
    overwatch.info(f"Gradient Accumulation steps = {trainer.gradient_accumulation_steps}", ctx_level=2)
    overwatch.info(f"Num processes (GPUs) = {trainer.world_size}", ctx_level=2)
    # fmt: on

    overwatch.info("Prepare accelerator / DeepSpeed ...")
    prepare_start = time.time()
    trainer.prepare(accelerator)
    overwatch.info(f"Accelerator prepare took {time.time() - prepare_start:.1f}s")
    # Keep model construction identical on every rank, then split the runtime
    # random streams after DDP/DeepSpeed has synchronized model state.  A
    # resumed checkpoint restores its saved per-rank RNG state immediately
    # below, so fresh and resumed runs are both reproducible.
    if config.seed:
        accelerate_set_seed(int(config.seed), device_specific=True)
        overwatch.info(
            f"Rank-specific training RNG seed: base={config.seed} "
            f"process_index={accelerator.process_index}"
        )
    overwatch.info("Resume checkpoint state ...")
    resume_start = time.time()
    global_step = initial_global_step = trainer.resume_from_checkpoint()[0]
    overwatch.info(f"Resume state took {time.time() - resume_start:.1f}s")
    epoch_start = global_step // trainer.num_steps_per_epoch

    eval_prewarm_enabled = os.environ.get(
        "PSI_OMNI_OSS_EVAL_PREWARM", "0"
    ).strip().lower() in {"1", "true", "yes", "on"}
    prepare_evaluation_cache = getattr(trainer, "prepare_evaluation_cache", None)
    if (
        eval_prewarm_enabled
        and config.train.validation_steps > 0
        and callable(prepare_evaluation_cache)
    ):
        eval_prewarm_start = time.time()
        overwatch.info("Prewarm fixed validation batches before training ...")
        cache_ready = prepare_evaluation_cache(int(config.train.validation_steps))
        overwatch.info(
            f"Validation batch prewarm ready={int(bool(cache_ready))} "
            f"in {time.time() - eval_prewarm_start:.1f}s"
        )

    overwatch.info(f"Accelerator runs in: {trainer.project_dir}")
    trainer.set_train()

    is_max_train_steps_reached = (initial_global_step >= trainer.max_training_steps)
    # skip_resumed_steps = False
    skip = 0
    resume_batches_to_skip = (
        initial_global_step % trainer.num_steps_per_epoch
        if config.train.skip_resumed_steps
        else 0
    )
    progress_bar = None

    for epoch in range(epoch_start, MAX_TRAINING_EPOCHS):
        trainer.next_epoch(epoch)
        accelerator.wait_for_everyone()
        resume_local_step = 0
        if skip < resume_batches_to_skip and resume_batches_to_skip > 0:
            sampler_fast_forward = getattr(
                getattr(trainer, "train_sampler", None),
                "fast_forward",
                None,
            )
            if callable(sampler_fast_forward):
                overwatch.info(
                    f"Fast-forward sampler by {resume_batches_to_skip:,} batches "
                    "without loading already-trained tensors ..."
                )
                seek_start = time.time()
                seek_bar = tqdm(
                    total=resume_batches_to_skip,
                    initial=skip,
                    desc="Resume sampler seek",
                    unit="batch",
                    disable=not overwatch.is_rank_zero(),
                    position=0,
                )

                def _update_seek_bar(completed: int) -> None:
                    seek_bar.update(max(int(completed) - int(seek_bar.n), 0))

                try:
                    sampler_fast_forward(
                        resume_batches_to_skip,
                        progress_callback=_update_seek_bar,
                    )
                finally:
                    seek_bar.close()
                skip = resume_batches_to_skip
                resume_local_step = resume_batches_to_skip
                overwatch.info(
                    f"Sampler fast-forward completed: {skip:,} batches in "
                    f"{time.time() - seek_start:.1f}s; no dataset tensors were loaded"
                )
        overwatch.info(f"Fetch first training batch for epoch {epoch} ...")
        first_batch_wait_done, first_batch_wait_thread = _start_wait_progress(
            f"Epoch {epoch} first batch wait",
            position=0,
        )
        first_batch_start = time.time()
        train_iter = iter(trainer.train_dataloader)
        try:
            first_batch = next(train_iter)
        finally:
            first_batch_wait_done.set()
            if first_batch_wait_thread is not None:
                first_batch_wait_thread.join(timeout=2.0)
        overwatch.info(
            f"Epoch {epoch} first batch fetched in "
            f"{time.time() - first_batch_start:.1f}s"
        )
        _wait_for_first_batch_readiness(epoch)
        overwatch.info(f"All ranks fetched epoch {epoch} first batch; starting training")
        epoch_batches = itertools.chain([first_batch], train_iter)

        if progress_bar is None:
            progress_bar = tqdm(
                range(0, trainer.max_training_steps),
                initial=initial_global_step,
                desc="Traing steps",
                disable=not overwatch.is_rank_zero(),
                position=0,
            )
        resume_replay_bar = None
        if skip < resume_batches_to_skip and resume_batches_to_skip > 0:
            resume_replay_bar = tqdm(
                total=resume_batches_to_skip,
                initial=skip,
                desc="Resume sampler replay",
                unit="batch",
                disable=not overwatch.is_rank_zero(),
                position=1,
            )

        for local_step, batch in enumerate(epoch_batches, start=resume_local_step):
            # breakpoint()
            if (
                config.train.skip_resumed_steps
                and skip < initial_global_step % trainer.num_steps_per_epoch
            ):
                # skip to inital global step
                skip += 1
                if resume_replay_bar is not None:
                    resume_replay_bar.update(1)
                    if skip == resume_batches_to_skip:
                        resume_replay_bar.close()
                        resume_replay_bar = None
                        overwatch.info(
                            f"Resume sampler replay completed: {skip:,} batches"
                        )
                continue
            sync_gradients, losses = trainer.step(batch_str_to_tensor(batch), global_step, local_step)
            
            if sync_gradients:
                # Start rank-local CPU validation workers shortly before an
                # eval boundary. Their prefetched batches overlap the final
                # training steps; no CUDA work is issued by this path.
                eval_prefetch_lead = max(
                    int(os.environ.get("PSI_OMNI_OSS_EVAL_PREFETCH_LEAD_STEPS", "0")),
                    0,
                )
                prefetch_evaluation = getattr(trainer, "prefetch_evaluation", None)
                if (
                    eval_prefetch_lead > 0
                    and callable(prefetch_evaluation)
                    and config.train.validation_steps > 0
                ):
                    validation_interval = int(config.train.validation_steps)
                    regular_distance = (-global_step) % validation_interval
                    if regular_distance == 0:
                        regular_distance = validation_interval
                    final_distance = trainer.max_training_steps - 1 - global_step
                    targets = [(regular_distance, global_step + regular_distance)]
                    if final_distance > 0:
                        targets.append((final_distance, trainer.max_training_steps - 1))
                    distance, target_step = min(targets)
                    if distance <= eval_prefetch_lead:
                        prefetch_evaluation(target_step)

                # log metrics
                trainer.log(flatten({**losses, "epoch": epoch}, parent_key="train")) 

                # save checkpoints
                if (global_step + 1) % config.train.checkpointing_steps == 0 or global_step == trainer.max_training_steps - 1:
                    accelerator.wait_for_everyone() # ensures fsdp checkpointing without deadlock
                    save_path = trainer.save_checkpoint(global_step+1)
                    accelerator.wait_for_everyone()
                    
                    if overwatch.is_rank_zero():
                        tqdm.write(f"Saved state to {save_path}")

                # validation
                if config.train.validation_steps > 0 and global_step > 0 and (
                        global_step % config.train.validation_steps == 0 or 
                        global_step == trainer.max_training_steps - 1
                    ) :
                    gc.collect()
                    torch.cuda.empty_cache()
                    trainer.set_eval()
                    with torch.inference_mode(), torch.autocast(
                        device_type="cuda", dtype=trainer.dtype
                    ):
                        eval_losses = trainer.evaluate()
                        if eval_losses is not None: # FIXME
                            trainer.log(flatten(eval_losses, parent_key="eval")) 
                            # <modify> eval loss更低时额外保存best ckpt,路径固定为checkpoints/best_ckpt。
                            best_save_path = trainer.save_best_checkpoint(eval_losses, global_step + 1)
                            if best_save_path is not None and overwatch.is_rank_zero():
                                tqdm.write(f"Saved best eval checkpoint to {best_save_path}")
                    trainer.set_train()
                    """ NOTE:
                        This is a workaround for iterating over val_dataloader in the middle of training_dataloader.
                        When val dataloader dost not end explicitly, eg., the val dataloader is wrapped in a tqdm progress bar,
                        and the bar is closed before the end of the dataloader, it will cause an inconsistent accelerate gradient state
                    """
                    val_dataloaders = getattr(trainer, "val_dataloader", None)
                    used_cpu_prefetch = bool(
                        getattr(trainer, "_last_eval_used_cpu_prefetch", False)
                    )
                    if used_cpu_prefetch:
                        # The raw rank-sharded CPU loaders never call
                        # DataLoaderShard.begin(), so there is no Accelerate
                        # validation state to end.
                        val_dataloaders_to_end = []
                        trainer._last_eval_used_cpu_prefetch = False
                    elif isinstance(val_dataloaders, dict):
                        val_dataloaders_to_end = list(val_dataloaders.values())
                    elif val_dataloaders is not None:
                        val_dataloaders_to_end = [val_dataloaders]
                    else:
                        val_dataloaders_to_end = []
                    for val_dataloader in val_dataloaders_to_end:
                        if isinstance(val_dataloader, AcceleratorDataLoaderStateMixin):
                            # ``end`` only resets Accelerate's gradient-state
                            # bookkeeping; it does not tear down persistent
                            # PyTorch workers or their worker-local OSS cache.
                            if (
                                accelerator.gradient_state.active_dataloader
                                != trainer.train_dataloader
                            ):
                                try:
                                    val_dataloader.end()
                                    overwatch.warning_once(
                                        "Warning only Once: "
                                        "Val dataloader does not end after evaluation. I killed it for you."
                                    )
                                except ValueError:
                                    overwatch.warning_once("Even I can not save you.")

                # Avoid writing the same progress row twice for one optimizer
                # step: update() performs the single terminal refresh.
                progress_bar.set_postfix(
                    dict(loss=losses["loss"], lr=nice(trainer.lr)),
                    refresh=False,
                )
                progress_bar.update()
                global_step += 1

            if global_step >= trainer.max_training_steps:
                if overwatch.is_rank_zero():
                    tqdm.write("Training has reached maximum steps.")
                is_max_train_steps_reached = True  # set to break outer loop
                break

        if is_max_train_steps_reached:
            break

    accelerator.wait_for_everyone()
    trainer.finalize()
    overwatch.info("Happy Ending!")
    accelerator.end_training()
    
    if torch.distributed.is_initialized():
        torch.distributed.destroy_process_group()

def _is_slurm_job_process() -> bool:
    return "SLURM_JOB_ID" in os.environ and not os.isatty(sys.stdout.fileno())


@record
def _run_training_with_error_record(config: LaunchConfig) -> None:
    """Preserve the original per-rank traceback in torchrun error reports."""
    train(config)

if __name__ == "__main__":
    if _is_slurm_job_process():
        overwatch.info("SLURM job detected. Setting up distributed environment variables...")
        os.environ["LOCAL_WORLD_SIZE"] = str(
            int(os.environ["WORLD_SIZE"]) // int(os.environ["SLURM_JOB_NUM_NODES"])
        )

    # Print and log important environment variables
    env_vars_to_track = [
        "OMP_NUM_THREADS", "HF_HOME", "TORCH_HOME", "HF_TOKEN", "HF_LEROBOT_HOME",
        "DATA_HOME", "UV_CACHE_DIR", "WANDB_API_KEY",
        "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION", "CUDA_VISIBLE_DEVICES",
        "WORLD_SIZE", "LOCAL_WORLD_SIZE", "RANK", "LOCAL_RANK", "MASTER_ADDR", "MASTER_PORT"
    ]

    env_info = {}
    overwatch.info("=== Environment Variables ===")
    for var in env_vars_to_track:
        value = os.environ.get(var, "Not Set")
        # Mask sensitive tokens for logging
        if "TOKEN" in var or "KEY" in var:
            display_value = f"{value[:3]}...{value[-4:]}" if value != "Not Set" and len(value) > 7 else value
        else:
            display_value = value
        
        env_info[var] = display_value
        overwatch.info(f"{var}: {display_value}")
    
    # Store env info for wandb logging later
    os.environ["_ENV_INFO_JSON"] = json.dumps(env_info)

    start = datetime.datetime.now()
    overwatch.info("Parsing configuration...")
    try:
        # By convention, the first argument after the script name is the config module name, 
        # eg., {trainer}_{data}_{model}_config, which corresponds to psi.config.train.pretrain_egodex_qwen3vl_config
        module_start = time.monotonic()
        module = importlib.import_module(f"psi.config.train.{sys.argv[1]}")
        DynamicLaunchConfigClass = getattr(module, "DynamicLaunchConfig")
        overwatch.info(
            f"Config module import took {time.monotonic() - module_start:.2f}s"
        )
        cli_start = time.monotonic()
        config = tyro.cli(DynamicLaunchConfigClass, config=(tyro.conf.ConsolidateSubcommandArgs,), args=sys.argv[2:])
        overwatch.info(f"Config CLI parsing took {time.monotonic() - cli_start:.2f}s")
        # breakpoint()
    except Exception as e:
        overwatch.error(f"Failed to import config module 'psi.config.train.{sys.argv[1]}'")
        raise e

    end = datetime.datetime.now()
    overwatch.info(f"Config parsing took {(end - start).total_seconds():.2f}s") 
    _run_training_with_error_record(config) # type: ignore