-
Notifications
You must be signed in to change notification settings - Fork 1
Distributed Training Template #6
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
Merged
Merged
Changes from 11 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
02dcefc
added llm fine-tuning ddp fsdp scripts.
kohankhaki b5bcf06
Updated LLM Readme.
kohankhaki 4d9a15a
added default checkpoint function.
kohankhaki aacfbf1
Merge branch 'main' of https://github.com/VectorInstitute/vec-playboo…
kohankhaki 2f80c4a
fixed typo in templates README.
kohankhaki c85d817
refactored fsdp example to set env variables directly using submitit …
kohankhaki 6119639
removed extra files.
kohankhaki 12e2c02
updated config, removed extra hyper-params.
kohankhaki 8d95dcb
added readme for llm distributed training.
kohankhaki 0a79a93
Merge origin/main into fsdp_template
kohankhaki ca0ed7c
removed distributed training detail from llm readme.
kohankhaki 32b9318
added comment to launch and config. removed output to null.
kohankhaki 06f2c81
README.md
kohankhaki 5e21787
updated model. added env vars in the setup for higher quality logging.
kohankhaki 49a8c11
changed logging to only rank 0. move training bar to hydra.
kohankhaki 9e84da7
removed slurm param as not working on killarney.
kohankhaki 4a00e43
removed extra args. updated binding code.
kohankhaki 263ae28
fixed typos in readme.
kohankhaki ce18a4b
added a comment about memory unit in config.
kohankhaki 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| ### LLM training templates | ||
| # LLM Training Templates | ||
|
|
||
| This directory includes templates for LLM training tasks: | ||
| This directory includes templates for language-model workloads: | ||
|
|
||
| - [text_classification](text_classification/): Fine-tunes a small Transformer on AG News using Hugging Face Trainer. | ||
| - [text_classification](text_classification/): fine-tunes a small LLM on AG News via Hugging Face Trainer. | ||
| - [finetune_distributed](finetune_distributed/): distributed finetuning template using DDP and FSDP. |
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,50 @@ | ||
| # LLM Distributed Fine-tuning Template | ||
|
|
||
| This template fine-tunes Hugging Face models with the **HF Trainer** and scales via **DDP** or **FSDP**. | ||
|
|
||
| ## How the code works | ||
|
|
||
| In `train.py`, we use Submitit’s helper: | ||
|
|
||
| ```python | ||
| from submitit.helpers import TorchDistributedEnvironment | ||
| TorchDistributedEnvironment().export() # sets RANK, LOCAL_RANK, WORLD_SIZE, MASTER_ADDR/PORT | ||
| ``` | ||
|
|
||
| Then the HF `Trainer` (via `TrainingArguments`) initializes distributed training; you can also explicitly call `torch.distributed.init_process_group(backend="nccl", init_method="env://")` if you need lower-level control. The helper provides the same environment variables you would otherwise set by hand so that PyTorch’s `env://` init works. This pattern is used in Submitit’s own distributed examples and in downstream guides. | ||
|
|
||
| ## Distributed environment: tasks, ranks, and GPUs (with Submitit on Slurm) | ||
|
|
||
| ### Tasks-per-node and GPUs-per-node | ||
| - One process per GPU is the common pattern. Concretely: | ||
| `hydra.launcher.tasks_per_node = compute.gpus_per_node` | ||
| This makes Slurm/Submitit spawn exactly one task per GPU. Each task becomes a rank in the job. | ||
scarere marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| ### What Submitit exports | ||
| - `submitit.helpers.TorchDistributedEnvironment().export()` populates: | ||
| - `RANK`, `LOCAL_RANK`, `WORLD_SIZE`, `MASTER_ADDR`, `MASTER_PORT` (and related fields) so that `init_method="env://"` works out of the box. | ||
|
|
||
| ### Binding each task to one GPU | ||
| - Slurm’s GRES plugin sets `CUDA_VISIBLE_DEVICES` for each task so the task “sees” only its assigned GPU(s). You can additionally enforce a 1:1 mapping with: | ||
| ```yaml | ||
| hydra.launcher.setup: | ||
| - "export CUDA_VISIBLE_DEVICES=$SLURM_LOCALID" | ||
| ``` | ||
| This ensures rank-local GPU selection is unambiguous (task 0 -> GPU 0, task 1 -> GPU 1 on that node). | ||
scarere marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| ### Quick glossary | ||
| - **WORLD_SIZE**: total number of processes across all nodes. | ||
| - **RANK**: global process id `[0 .. WORLD_SIZE-1]`. | ||
| - **LOCAL_RANK**: process id per node `[0 .. tasks_per_node-1]`. | ||
|
|
||
| ## Why not torchrun here? | ||
|
|
||
| `torchrun` is valid for distributed launches (including on Slurm), but this template uses **Hydra’s Submitit launcher** to keep **sweeps, config composition, logging, and requeue** inside Hydra, and to avoid maintaining separate bash wrappers. Submitit handles **job submission and per-task rank context**; we still initialize PyTorch distributed via the standard env-var pathway. | ||
|
|
||
| If you prefer `torchrun`, you can adapt the script and configs—but you’ll then manage the Slurm submission layer (or wrap `torchrun` inside an `sbatch` yourself) and wire up Hydra sweeps accordingly. | ||
|
|
||
| ## References | ||
|
|
||
| - PyTorch distributed environment variables: https://pytorch.org/docs/stable/distributed.html#environment-variable-initialization | ||
| - Slurm GRES guide: https://slurm.schedmd.com/gres.html | ||
| - Hugging Face FSDP / Trainer documentation: https://huggingface.co/docs/transformers/fsdp | ||
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 @@ | ||
| """LLM training template: Fine-tuning using distributed training.""" |
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,66 @@ | ||
| defaults: | ||
| - _global | ||
scarere marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| - _self_ | ||
|
|
||
| hydra: | ||
| job: | ||
| name: llm_finetune_distributed | ||
| searchpath: | ||
| - pkg://configs | ||
scarere marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| launcher: | ||
| tasks_per_node: ${compute.gpus_per_node} | ||
scarere marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| setup: | ||
| - 'export CUDA_VISIBLE_DEVICES=$SLURM_LOCALID' | ||
|
|
||
| paths: | ||
| out_dir: null | ||
scarere marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| trainer: | ||
| seed: 42 | ||
| model: | ||
| name: "EleutherAI/pythia-6.9b" | ||
| revision: null | ||
| trust_remote_code: true | ||
| torch_dtype: "float16" | ||
| data: | ||
| dataset_name: "wikitext" | ||
| dataset_config_name: "wikitext-2-raw-v1" | ||
| text_column: "text" | ||
| train_split: "train" | ||
| eval_split: "validation" | ||
| max_length: 512 | ||
| load_kwargs: | ||
| streaming: false | ||
| train: | ||
| num_train_epochs: 1 | ||
| per_device_train_batch_size: 1 | ||
| per_device_eval_batch_size: 1 | ||
| gradient_accumulation_steps: 4 | ||
| learning_rate: 1.5e-5 | ||
| weight_decay: 0.01 | ||
| warmup_steps: 200 | ||
| logging_steps: 1 | ||
| logging_first_step: true | ||
| eval_steps: 10 | ||
| save_steps: 10 | ||
| eval_strategy: "steps" | ||
| save_strategy: "steps" | ||
| save_total_limit: 2 | ||
| lr_scheduler_type: "cosine" | ||
| max_grad_norm: 1.0 | ||
| optim: "adamw_torch" | ||
| dist: | ||
scarere marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| mode: "fsdp" | ||
| fp16: true | ||
| bf16: false | ||
| fsdp: ["full_shard", "auto_wrap"] | ||
| fsdp_config: | ||
| use_orig_params: true | ||
| activation_checkpointing: false | ||
| limit_all_gathers: true | ||
| forward_prefetch: true | ||
| sync_module_states: true | ||
| fsdp_auto_wrap_policy: "SIZE_BASED_WRAP" | ||
| fsdp_min_num_params: 1000000 | ||
| logging: | ||
| report_to: [] | ||
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,42 @@ | ||
| """Launch script for checkpointable distributed finetuning with Hydra + Submitit.""" | ||
|
|
||
| import logging | ||
| import os | ||
|
|
||
| import hydra | ||
| from omegaconf import DictConfig, OmegaConf | ||
|
|
||
| from .train import FinetuneDistributedTrainer | ||
|
|
||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| @hydra.main(config_path=".", config_name="config", version_base=None) | ||
| def main(cfg: DictConfig): | ||
| """Hydra entrypoint that updates paths, saves config, and launches training.""" | ||
| # Turn of struct mode so that we can modify DictConfig | ||
| OmegaConf.set_struct(cfg, False) | ||
|
|
||
| # Add output_directory for current run | ||
| hydra_config = hydra.core.hydra_config.HydraConfig.get() | ||
| cfg.paths.out_dir = str(os.path.join(hydra_config.runtime.output_dir, "outputs")) | ||
| logger.info(f"Setting paths.out_dir to: {cfg.paths.out_dir}") | ||
|
|
||
| # Save a resolved version of the hydra config | ||
| save_path = os.path.join( | ||
| hydra_config.runtime.output_dir, | ||
| hydra_config.output_subdir, | ||
| "hydra_resolved.yaml", | ||
| ) | ||
| logger.info(f"Resolving hydra config for this run and saving to: {save_path}") | ||
| OmegaConf.set_readonly(hydra_config, False) | ||
| OmegaConf.resolve(hydra_config) | ||
| OmegaConf.save(hydra_config, save_path) | ||
|
|
||
| trainer = FinetuneDistributedTrainer() | ||
| return trainer(cfg) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
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.
Uh oh!
There was an error while loading. Please reload this page.