code-HFD / scripts /train.py
Tinghong-Ye22's picture
Add files using upload-large-folder tool
9fc9873 verified
Raw History Blame Contribute Delete
33.6 kB
from __future__ import annotations
from dotenv import load_dotenv
assert load_dotenv(), "Failed to load .env file. Make sure it exists and is properly formatted."
import os
import re
import torch
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 (
DistributedDataParallelKwargs,
ProjectConfiguration,
set_seed as accelerate_set_seed,
)
import random, numpy as np
MAX_TRAINING_EPOCHS = 1_000_000
SPEED_METRIC_NAMES = (
"data_wait_seconds",
"source_step_seconds",
"active_windows_per_second",
"sources_per_second",
"source_refills_per_second",
)
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)
kwargs_handlers = []
manual_ddp_sync = bool(
getattr(trainer, "requires_manual_ddp_sync", False)
) or os.environ.get("HFD_MANUAL_DDP_SYNC", "0").strip().lower() in {
"1",
"true",
"yes",
"on",
}
if manual_ddp_sync:
# Full-duplex ranks execute different numbers of recurrent forwards.
# Buffer broadcasts would introduce a collective on every forward;
# gradients are synchronized once by its dedicated trainer instead.
kwargs_handlers.append(
DistributedDataParallelKwargs(
broadcast_buffers=False,
find_unused_parameters=bool(
getattr(
trainer,
"ddp_find_unused_parameters",
False,
)
),
)
)
accelerator = Accelerator(
gradient_accumulation_steps=trainer.cfg.train.gradient_accumulation_steps,
mixed_precision=trainer.cfg.train.mixed_precision,
# downcast_bf16=True,
log_with=trainer.cfg.log.report_to,
project_config=accelerator_project_config,
fsdp_plugin=fsdp_plugin,
deepspeed_plugin=deepspeed_plugin,
kwargs_handlers=kwargs_handlers,
)
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"] = (
wandb_config.get("group") or 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)
if bool(getattr(trainer, "single_pass_training", False)):
overwatch.info(
"Stage 2 single pass: max steps is a cap; stop after unique windows "
"are exhausted. Exact update count depends on runtime strata and rank tails.",
ctx_level=2,
)
else:
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:.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")
single_pass = bool(getattr(trainer, "single_pass_training", False))
epoch_start = 0 if single_pass else 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
or bool(getattr(trainer, "training_data_exhausted", False))
)
# skip_resumed_steps = False
skip = 0
progress_bar = None
first_batch_prefetched = False
checkpoint_pending = False
validation_pending = False
for epoch in range(epoch_start, MAX_TRAINING_EPOCHS):
if is_max_train_steps_reached:
break
trainer.next_epoch(epoch)
accelerator.wait_for_everyone()
if not first_batch_prefetched:
overwatch.info("Fetch first training batch ...")
first_batch_wait_done, first_batch_wait_thread = _start_wait_progress(
"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)
first_batch_fetch_seconds = time.time() - first_batch_start
overwatch.info(f"First batch fetched in {first_batch_fetch_seconds:.1f}s")
epoch_batches = itertools.chain([first_batch], train_iter)
first_batch_prefetched = True
else:
epoch_batches = trainer.train_dataloader
first_batch_fetch_seconds = None
batch_wait_started = time.perf_counter()
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,
)
for local_step, batch in enumerate(epoch_batches):
batch_fetch_seconds = (
float(first_batch_fetch_seconds)
if local_step == 0 and first_batch_fetch_seconds is not None
else time.perf_counter() - batch_wait_started
)
# breakpoint()
if (
config.train.skip_resumed_steps
and not single_pass
and skip < initial_global_step % trainer.num_steps_per_epoch
):
# skip to inital global step
skip += 1
batch_wait_started = time.perf_counter()
continue
tensor_batch = batch_str_to_tensor(batch)
iter_optimizer_steps = getattr(trainer, "iter_optimizer_steps", None)
if callable(iter_optimizer_steps):
local_data_wait = torch.tensor(
batch_fetch_seconds,
device=accelerator.device,
dtype=torch.float64,
)
data_wait_seconds = float(
accelerator.gather(local_data_wait).max().item()
)
remaining_optimizer_steps = max(
trainer.max_training_steps - global_step,
0,
)
optimizer_events = iter_optimizer_steps(
tensor_batch,
global_step_start=global_step,
local_step=local_step,
max_optimizer_events=remaining_optimizer_steps,
)
else:
data_wait_seconds = 0.0
sync_gradients, losses = trainer.step(
tensor_batch, global_step, local_step
)
optimizer_events = iter(((sync_gradients, losses, True),))
pending_data_wait_seconds = data_wait_seconds
for sync_gradients, losses, source_group_end in optimizer_events:
if not sync_gradients:
continue
# Fetching happened once before this source group, not once
# per dense optimizer event. Repeating the same value across
# thousands of steps made the W&B curve overstate I/O stalls
# by the group length and obscured the actual boundary spike.
losses["data_wait_seconds"] = pending_data_wait_seconds
pending_data_wait_seconds = 0.0
completed_step = global_step + 1
# Start rank-local CPU validation workers shortly before an
# eval boundary. Their prefetched batches overlap training, but
# validation itself is deferred to a source boundary.
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
and completed_step < trainer.max_training_steps
):
validation_interval = int(config.train.validation_steps)
regular_distance = (-completed_step) % validation_interval
if regular_distance == 0:
regular_distance = validation_interval
final_distance = trainer.max_training_steps - completed_step
targets = [
(regular_distance, completed_step + regular_distance)
]
if final_distance > 0:
targets.append((final_distance, trainer.max_training_steps))
distance, target_step = min(targets)
if distance <= eval_prefetch_lead:
prefetch_evaluation(target_step)
speed_metrics = {
name: losses[name]
for name in SPEED_METRIC_NAMES
if name in losses
}
train_metrics = {
name: value
for name, value in losses.items()
if name not in SPEED_METRIC_NAMES
}
wandb_metrics = flatten(
{**train_metrics, "epoch": epoch},
parent_key="train",
)
wandb_metrics.update(
flatten(speed_metrics, parent_key="speed")
)
trainer.log(wandb_metrics)
checkpoint_due = (
completed_step % config.train.checkpointing_steps == 0
or completed_step >= trainer.max_training_steps
or bool(getattr(trainer, "training_data_exhausted", False))
)
checkpoint_pending = checkpoint_pending or checkpoint_due
validation_due = (
config.train.validation_steps > 0
and (
completed_step % config.train.validation_steps == 0
or completed_step >= trainer.max_training_steps
or bool(getattr(trainer, "training_data_exhausted", False))
)
)
validation_pending = validation_pending or validation_due
if source_group_end and checkpoint_pending:
accelerator.wait_for_everyone()
checkpoint_started = time.perf_counter()
save_path = trainer.save_checkpoint(completed_step)
accelerator.wait_for_everyone()
checkpoint_wall_seconds = (
time.perf_counter() - checkpoint_started
)
trainer.log(
{
"speed/checkpoint_wall_seconds": (
checkpoint_wall_seconds
)
}
)
checkpoint_pending = False
if overwatch.is_rank_zero():
tqdm.write(f"Saved state to {save_path}")
if source_group_end and validation_pending:
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, completed_step
)
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()
validation_pending = False
""" 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 = completed_step
# Plain-text heartbeat. WandB's wrap_raw output capture
# forwards terminal output line-buffered, so the \r-only
# tqdm bar above only reaches remote consoles when a
# newline-terminated message flushes it.
if overwatch.is_rank_zero():
console_steps = max(
int(os.environ.get("PSI_CONSOLE_LOG_STEPS", "10")), 1
)
if (
global_step % console_steps == 0
or global_step >= trainer.max_training_steps
):
bar_stats = progress_bar.format_dict
rate = bar_stats.get("rate") or 0.0
source_seconds = float(
losses.get("source_step_seconds", 0.0)
)
active_window_rate = float(
losses.get("active_windows_per_second", 0.0)
)
max_gpu_memory_gb = float(
losses.get("max_gpu_memory_gb", 0.0)
)
data_wait = float(
losses.get("data_wait_seconds", 0.0)
)
tqdm.write(
f"[{time.strftime('%H:%M:%S')}] "
f"step {global_step}/{bar_stats['total']} "
f"loss={losses['loss']:.4g} "
f"lr={nice(trainer.lr)} "
f"{(1.0 / rate) if rate else 0.0:.2f}s/it "
f"data_wait={data_wait:.2f}s "
f"source_compute={source_seconds:.2f}s "
f"windows={active_window_rate:.1f}/s "
f"peak_mem={max_gpu_memory_gb:.1f}GiB "
f"elapsed={bar_stats['elapsed']:.0f}s"
)
if source_group_end and (
global_step >= trainer.max_training_steps
or bool(getattr(trainer, "training_data_exhausted", False))
):
close_optimizer_events = getattr(
optimizer_events,
"close",
None,
)
if callable(close_optimizer_events):
close_optimizer_events()
if overwatch.is_rank_zero():
tqdm.write(
"Training reached its step cap or exhausted the single pass at a "
f"cache-free optimizer boundary (step {global_step})."
)
is_max_train_steps_reached = True
break
if is_max_train_steps_reached:
break
batch_wait_started = time.perf_counter()
if single_pass or 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 train(config: LaunchConfig):
from contextlib import nullcontext
architecture = getattr(config.model, "interaction_architecture", "legacy")
if architecture == "a1_c_deferred":
if not getattr(config.model, "swa_visual_qa_enabled", False):
raise ValueError("A1/C needs the joint AV/QA model. For the legacy audio-only model set HFD_INTERACTION_ARCHITECTURE=legacy.")
from psi.models.interaction_arch.runtime import ArchitectureSpec, trainer_architecture
scope = trainer_architecture(ArchitectureSpec("a1", interaction="cross"))
elif architecture == "legacy":
scope = nullcontext()
else:
raise ValueError(f"Unknown interaction architecture: {architecture}")
with scope:
return _train(config)
def _is_slurm_job_process() -> bool:
return "SLURM_JOB_ID" in os.environ and not os.isatty(sys.stdout.fileno())
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 = importlib.import_module(f"psi.config.train.{sys.argv[1]}")
DynamicLaunchConfigClass = getattr(module, "DynamicLaunchConfig")
config = tyro.cli(DynamicLaunchConfigClass, config=(tyro.conf.ConsolidateSubcommandArgs,), args=sys.argv[2:])
# 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")
train(config) # type: ignore