-
Notifications
You must be signed in to change notification settings - Fork 15
feat: optional multi-GPU (DDP) finetuning #21
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
evasnow1992
wants to merge
2
commits into
NVIDIA-BioNeMo:main
Choose a base branch
from
evasnow1992:evax/finetune-ddp
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
|
evasnow1992 marked this conversation as resolved.
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| """ | ||
| Multi-GPU (DistributedDataParallel) launcher for KERMT finetuning. | ||
|
|
||
| Mirrors pretrain_ddp.py: one process per GPU via torch.multiprocessing.spawn, | ||
| single-node NCCL rendezvous, data-parallel training with a DistributedSampler. | ||
| The finetune training/eval/checkpointing logic lives in task/train.py; this | ||
| file only bootstraps the process group and hands rank/world_size down through | ||
| cross_validate -> run_training. | ||
|
|
||
| Usage (data-parallel finetune across all visible GPUs): | ||
| python finetune_ddp.py --data_path train.csv --separate_val_path val.csv \ | ||
| --separate_test_path test.csv --checkpoint_path <ckpt> --save_dir <dir> \ | ||
| --dataset_type regression --... (all normal finetune args) | ||
|
|
||
| Pin the GPU count explicitly with WORLD_SIZE (defaults to all visible GPUs): | ||
| WORLD_SIZE=4 python finetune_ddp.py ... | ||
|
|
||
| Notes: | ||
| - `args.batch_size` is the PER-GPU batch size; the effective global batch is | ||
| batch_size * world_size (same convention as pretrain_ddp.py). The LR | ||
| schedule is world-size-aware. | ||
| - Single-process finetune (`python main.py finetune ...`) is unchanged and | ||
| does not go through this launcher. | ||
| """ | ||
| import os | ||
| import random | ||
| import sys | ||
|
|
||
| import numpy as np | ||
| import torch | ||
| import torch.multiprocessing as mp | ||
| from rdkit import RDLogger | ||
| from torch.distributed import destroy_process_group | ||
|
|
||
| from kermt.data.torchvocab import MolVocab | ||
| from kermt.util.ddp_utils import configure_nccl_for_topology, ddp_setup | ||
| from kermt.util.parsing import parse_args | ||
| from kermt.util.utils import create_logger | ||
| from task.cross_validate import cross_validate | ||
|
|
||
|
|
||
| def _setup_determinism(seed: int): | ||
|
evasnow1992 marked this conversation as resolved.
|
||
| """Match the single-process determinism setup in main.py:setup().""" | ||
| torch.manual_seed(seed) | ||
| torch.cuda.manual_seed_all(seed) | ||
| np.random.seed(seed) | ||
| random.seed(seed) | ||
| torch.backends.cudnn.deterministic = True | ||
| torch.use_deterministic_algorithms(mode=True) | ||
|
|
||
|
|
||
| def ddp_main(rank: int, world_size: int): | ||
| # Deterministic algorithms (enabled in _setup_determinism, matching main.py) | ||
| # require this for CuBLAS on CUDA >= 10.2. Mirrors run_finetune_local.py. | ||
| os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8") | ||
| ddp_setup(rank, world_size) | ||
|
|
||
| # Suppress RDKit logging in every worker. | ||
| lg = RDLogger.logger() | ||
| lg.setLevel(RDLogger.CRITICAL) | ||
| _ = MolVocab # ensure vocab class is imported for checkpoint (un)pickling | ||
|
|
||
| # Select the finetune subparser (mirror `main.py finetune ...`). Users invoke | ||
| # this script with the normal finetune flags but no subcommand token. | ||
| if len(sys.argv) < 2 or sys.argv[1] != 'finetune': | ||
| sys.argv.insert(1, 'finetune') | ||
| args = parse_args() | ||
|
|
||
| _setup_determinism(args.seed) | ||
|
|
||
| # Only rank 0 writes logs; other ranks stay quiet. | ||
| logger = create_logger(name='train', save_dir=args.save_dir, quiet=False) if rank == 0 else None | ||
|
|
||
| cross_validate(args, logger, rank=rank, world_size=world_size) | ||
|
|
||
| destroy_process_group() | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| configure_nccl_for_topology() | ||
|
|
||
| available_gpus = torch.cuda.device_count() | ||
| if available_gpus == 0: | ||
| raise RuntimeError('No GPUs found. DDP finetuning requires at least 1 GPU.') | ||
|
|
||
| world_size = int(os.environ.get('WORLD_SIZE', available_gpus)) | ||
| if world_size > available_gpus: | ||
| raise RuntimeError( | ||
| f'WORLD_SIZE={world_size} but only {available_gpus} GPU(s) visible. ' | ||
| f'Set WORLD_SIZE<={available_gpus} or unset it to auto-detect.' | ||
| ) | ||
|
|
||
| print(f'Launching DDP finetuning on {world_size}/{available_gpus} GPU(s)') | ||
| mp.spawn(ddp_main, args=(world_size,), nprocs=world_size) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| """ | ||
| Shared DistributedDataParallel (DDP) helpers for KERMT. | ||
|
|
||
| Used by the pretraining and finetuning DDP launchers so both share a single, | ||
| proven single-node DDP bootstrap. The logic here matches what pretraining has | ||
| used in production (localhost rendezvous, NCCL backend, per-process GPU pinning | ||
| by rank, and topology-aware NCCL P2P configuration). | ||
| """ | ||
| import os | ||
| import subprocess | ||
|
|
||
| import torch | ||
| from torch.distributed import init_process_group | ||
|
|
||
|
|
||
| def configure_nccl_for_topology(): | ||
|
evasnow1992 marked this conversation as resolved.
|
||
| """ | ||
| Auto-configure NCCL settings based on GPU topology. | ||
| This handles cases where P2P (peer-to-peer) GPU communication is not available. | ||
| Must be called BEFORE spawning processes (in main process). | ||
| """ | ||
| # Check if user has already set NCCL settings (don't override) | ||
| if "NCCL_P2P_DISABLE" in os.environ: | ||
| print(f"[INFO] Using user-provided NCCL settings: NCCL_P2P_DISABLE={os.environ['NCCL_P2P_DISABLE']}") | ||
| return | ||
|
|
||
| # Try to detect GPU topology | ||
| try: | ||
| result = subprocess.run(['nvidia-smi', 'topo', '-m'], | ||
| capture_output=True, text=True, timeout=5) | ||
| topo_output = result.stdout | ||
|
|
||
| # Check for poor GPU connectivity (SYS or NODE topology) | ||
| # These topologies typically don't support P2P well | ||
| if 'SYS' in topo_output or 'NODE' in topo_output: | ||
| print("[INFO] Detected cross-NUMA or system-level GPU topology (SYS/NODE).") | ||
| print("[INFO] Disabling P2P for stability. This is normal for multi-socket systems.") | ||
| os.environ["NCCL_P2P_DISABLE"] = "1" | ||
| os.environ["NCCL_IB_DISABLE"] = "1" | ||
| os.environ["NCCL_SHM_DISABLE"] = "0" | ||
| else: | ||
| print("[INFO] GPU topology appears to support P2P. Enabling P2P communication.") | ||
| except Exception as e: | ||
| # If detection fails, use safe defaults (disable P2P) | ||
| print(f"[WARNING] Could not detect GPU topology: {e}") | ||
| print("[INFO] Using safe default: P2P disabled. Set NCCL_P2P_DISABLE=0 to enable if your system supports it.") | ||
| os.environ["NCCL_P2P_DISABLE"] = "1" | ||
| os.environ["NCCL_IB_DISABLE"] = "1" | ||
| os.environ["NCCL_SHM_DISABLE"] = "0" | ||
|
|
||
|
|
||
| def ddp_setup(rank: int, world_size: int): | ||
|
evasnow1992 marked this conversation as resolved.
|
||
| """ | ||
| Initialize the process group for single-node DDP and pin this process to its GPU. | ||
|
|
||
| Args: | ||
| rank: Unique identifier of each process (also the GPU index it is pinned to). | ||
| world_size: Total number of processes. | ||
| """ | ||
| os.environ["MASTER_ADDR"] = "localhost" | ||
| os.environ["MASTER_PORT"] = "12355" | ||
| torch.cuda.set_device(rank) | ||
| init_process_group(backend="nccl", rank=rank, world_size=world_size) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is a similar argument
--gpuselsewhere. I think that one is mostly ignored. If so, we can remove that arg.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I may lean towards keeping it.
--gpusis used for pinning down a specific device to be used for finetune, when--num-gpusis 1. But I do find a misleading inconsistency in describing--gpusindefaults_finetune.jsonfor agent skills, which I will update it to make the function of this argument clear.