Download train.py from ZenoNing/ConsDrive: direct link, hf CLI and curl.
- Browser
- Download file 6.12 kB
-
https://huggingface.co/ZenoNing/ConsDrive/resolve/main/train.py
- Command line
-
hf download hf://ZenoNing/ConsDrive/train.py
-
curl -L -o train.py https://huggingface.co/ZenoNing/ConsDrive/resolve/main/train.py
6.12 kB
| import os | |
| os.environ["OMP_NUM_THREADS"] = "1" | |
| os.environ["MKL_NUM_THREADS"] = "1" | |
| os.environ["OPENBLAS_NUM_THREADS"] = "1" | |
| import cv2 | |
| cv2.setNumThreads(1) | |
| import hydra | |
| import pytorch_lightning as pl | |
| import torch | |
| from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint | |
| from omegaconf import OmegaConf | |
| from pytorch_lightning import Trainer | |
| from pytorch_lightning.callbacks import ModelSummary | |
| from pytorch_lightning.loggers import CSVLogger, WandbLogger | |
| from callbacks.rank_zero_output import RankZeroOutputCallback | |
| from callbacks.visualise import VisualiseCallback | |
| from config import TrainConfig | |
| from utils.logging_project import rank_zero_print, setup_logging | |
| class SamplerEpochCallback(pl.Callback): | |
| """Keep the epoch-reseeded train sampler in sync with the trainer epoch. | |
| Lightning only calls set_epoch() on the outermost sampler; under DDP the | |
| custom sampler gets wrapped in a DistributedSamplerWrapper, so we reach | |
| the original sampler through the datamodule to make each epoch's sample | |
| sequence a pure function of (seed, epoch) — including after a resume. | |
| """ | |
| def on_train_epoch_start(self, trainer, pl_module): | |
| datamodule = getattr(trainer, "datamodule", None) | |
| sampler = getattr(datamodule, "sampler_train", None) | |
| if sampler is not None and hasattr(sampler, "set_epoch"): | |
| sampler.set_epoch(trainer.current_epoch) | |
| def main(cfg: TrainConfig): | |
| torch.set_float32_matmul_precision("high") | |
| if cfg.deterministic: | |
| # Required by cuBLAS for deterministic GEMMs (CUDA >= 10.2). | |
| os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") | |
| pl.seed_everything(cfg.seed, workers=True) | |
| if cfg.debug: | |
| os.environ["WANDB_MODE"] = "offline" | |
| cfg.wandb_name = f"{cfg.wandb_name}_{cfg.name}" | |
| setup_logging(cfg, console_log_file=cfg.console_log_file) | |
| os.environ["WANDB_DISABLE_CODE"] = "True" | |
| cfg.model.vision_model.use_global_img = cfg.data_module.use_global_img | |
| rank_zero_print("Building data module...", flush=True) | |
| data_module = hydra.utils.instantiate( | |
| cfg.data_module, | |
| encoder_variant=OmegaConf.select(cfg, "model.vision_model.variant"), | |
| llm_variant=OmegaConf.select(cfg, "model.language_model.variant"), | |
| predict=False, | |
| sampler_seed=cfg.seed, | |
| ) | |
| rank_zero_print("Building model...", flush=True) | |
| model = hydra.utils.instantiate( | |
| cfg.model, | |
| route_as=cfg.data_module.route_as, | |
| ) | |
| rank_zero_print("Model ready.", flush=True) | |
| if cfg.checkpoint is not None: | |
| if os.path.isdir(cfg.checkpoint): | |
| state_dict = get_fp32_state_dict_from_zero_checkpoint(cfg.checkpoint) | |
| else: | |
| state_dict = torch.load(cfg.checkpoint, map_location="cpu") | |
| model.load_state_dict(state_dict) | |
| # print config | |
| rank_zero_print(OmegaConf.to_yaml(cfg)) | |
| if cfg.overfit > 0: | |
| overfit = cfg.overfit | |
| csv_logger = CSVLogger(save_dir=".", name="logs", version=cfg.name) | |
| loggers = [csv_logger] | |
| wandb_logger = None | |
| if not cfg.debug and cfg.enable_wandb: | |
| resume_wandb = bool(cfg.resume and cfg.resume_path and os.path.exists(cfg.resume_path)) | |
| wandb_logger = WandbLogger( | |
| project=cfg.wandb_project, | |
| id=cfg.wandb_name, | |
| name=cfg.wandb_name, | |
| config=OmegaConf.to_container(cfg, resolve=True, throw_on_missing=True), | |
| resume="allow" if resume_wandb else False, | |
| ) | |
| wandb_logger.watch(model) | |
| loggers.append(wandb_logger) | |
| # resume training | |
| resume_path = cfg.resume_path | |
| if resume_path is None or not (os.path.exists(resume_path) and cfg.resume): | |
| resume_path = None | |
| strategy = cfg.strategy | |
| if strategy == "deepspeed_stage_2": | |
| # bf16-mixed does not need loss scaling; loss_scale is only for fp16 | |
| use_bf16 = "bf16" in str(cfg.precision) | |
| strategy = pl.strategies.DeepSpeedStrategy( | |
| stage=2, | |
| logging_batch_size_per_gpu=cfg.data_module.batch_size, | |
| **({"loss_scale": cfg.fp16_loss_scale} if not use_bf16 else {}), | |
| ) | |
| checkpoint_dir = "./checkpoints" | |
| epoch_checkpoint_callback = pl.callbacks.ModelCheckpoint( | |
| save_top_k=-1, | |
| monitor=None, | |
| dirpath=checkpoint_dir, | |
| filename="{epoch:03d}", | |
| save_last=False, | |
| every_n_epochs=cfg.val_every_n_epochs, | |
| # every_n_train_steps=cfg.val_check_interval, | |
| ) | |
| last_checkpoint_callback = pl.callbacks.ModelCheckpoint( | |
| save_top_k=0, | |
| monitor=None, | |
| dirpath=checkpoint_dir, | |
| save_last=True, | |
| every_n_epochs=1, | |
| ) | |
| model_summary = ModelSummary(max_depth=3) | |
| callbacks = [ | |
| RankZeroOutputCallback(), | |
| epoch_checkpoint_callback, | |
| last_checkpoint_callback, | |
| model_summary, | |
| VisualiseCallback(interval=1000), | |
| SamplerEpochCallback(), | |
| ] | |
| rank_zero_print(f"Number of GPUS: {cfg.gpus}") | |
| overfit = 0 | |
| if cfg.gpus >= 1: | |
| trainer = Trainer( | |
| accelerator="gpu", | |
| benchmark=not cfg.deterministic, | |
| deterministic="warn" if cfg.deterministic else None, | |
| callbacks=callbacks, | |
| devices=cfg.gpus, | |
| # enable_checkpointing=False, | |
| gradient_clip_val=1.0, | |
| log_every_n_steps=20, | |
| logger=loggers, | |
| # max_steps=cfg.max_steps, | |
| precision=cfg.precision, | |
| strategy=strategy, | |
| sync_batchnorm=True, | |
| # use_distributed_sampler=False, | |
| accumulate_grad_batches=cfg.accumulate_grad_batches, | |
| max_epochs=cfg.max_epochs, | |
| overfit_batches=overfit, | |
| # val_check_interval=cfg.val_check_interval, | |
| ) | |
| trainer.fit(model, data_module, ckpt_path=resume_path) | |
| if wandb_logger is not None: | |
| import wandb | |
| wandb.finish() | |
| if __name__ == "__main__": | |
| main() | |