-
Notifications
You must be signed in to change notification settings - Fork 559
feat(fsdp): add memory_efficient_load option for large model initialization #862
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 all commits
Commits
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
Some comments aren't visible on the classic Files Changed page.
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
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,41 @@ | ||
| import subprocess | ||
|
|
||
| import pytest | ||
|
|
||
| from areal.api.alloc_mode import AllocationMode | ||
| from areal.platforms import current_platform | ||
| from areal.utils.network import find_free_ports | ||
|
|
||
|
|
||
| def _run_test_with_torchrun(alloc_mode: str, output: str): | ||
| port = find_free_ports(1)[0] | ||
| n_gpus = AllocationMode.from_str(alloc_mode).train.world_size | ||
| try: | ||
| subprocess.run( | ||
| [ | ||
| "torchrun", | ||
| f"--nproc_per_node={n_gpus}", | ||
| "--nnodes=1", | ||
| "--master-addr=localhost", | ||
| f"--master_port={port}", | ||
| "areal/tests/torchrun/run_fsdp_memory_efficient_lora.py", | ||
| f"--allocation_mode={alloc_mode}", | ||
| f"--output={output}", | ||
| ], | ||
| check=True, | ||
| capture_output=True, | ||
| text=True, | ||
| ) | ||
| except subprocess.CalledProcessError as e: | ||
| pytest.fail(f"Test failed with error: {e.stderr}, {e.stdout}") | ||
| with open(output) as f: | ||
| result = f.read().strip() | ||
| assert result == "Passed", f"Test failed: {result}" | ||
|
|
||
|
|
||
| @pytest.mark.slow | ||
| def test_fsdp_memory_efficient_lora(tmp_path_factory): | ||
| if current_platform.device_count() < 1: | ||
| pytest.skip("Test requires at least 1 GPU") | ||
| output = tmp_path_factory.mktemp("test_output") / "fsdp_memory_efficient_lora.out" | ||
| _run_test_with_torchrun("d1t1c1", str(output)) |
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,151 @@ | ||
| """Test memory_efficient_load with LoRA configuration.""" | ||
|
|
||
| import argparse | ||
| import os | ||
|
|
||
| import torch | ||
| import torch.distributed as dist | ||
|
|
||
| from areal.api.alloc_mode import AllocationMode | ||
| from areal.api.cli_args import ( | ||
| FSDPEngineConfig, | ||
| MicroBatchSpec, | ||
| OptimizerConfig, | ||
| TrainEngineConfig, | ||
| ) | ||
| from areal.api.io_struct import FinetuneSpec | ||
| from areal.engine.fsdp_engine import FSDPEngine | ||
| from areal.platforms import current_platform | ||
| from areal.tests.utils import get_model_path | ||
|
|
||
| MODEL_PATH = get_model_path( | ||
| "/storage/openpsi/models/Qwen__Qwen3-0.6B/", "Qwen/Qwen3-0.6B" | ||
| ) | ||
|
|
||
|
|
||
| def write_result(out: str, succ: bool): | ||
| with open(out, "w") as f: | ||
| if succ: | ||
| f.write("Passed") | ||
| else: | ||
| f.write("Failed") | ||
|
|
||
|
|
||
| def make_fsdp_engine_with_lora( | ||
| allocation_mode: str, | ||
| memory_efficient_load: bool, | ||
| ): | ||
| """Create FSDPEngine with LoRA and optionally memory_efficient_load.""" | ||
| config = TrainEngineConfig( | ||
| experiment_name="test_fsdp_memory_efficient_lora", | ||
| trial_name="test", | ||
| mb_spec=MicroBatchSpec(max_tokens_per_mb=256), | ||
| path=MODEL_PATH, | ||
| optimizer=OptimizerConfig(), | ||
| fsdp=FSDPEngineConfig(memory_efficient_load=memory_efficient_load), | ||
| # LoRA config | ||
| use_lora=True, | ||
| lora_rank=8, | ||
| lora_alpha=16, | ||
| peft_type="lora", | ||
| ) | ||
| alloc_mode = AllocationMode.from_str(allocation_mode) | ||
| engine = FSDPEngine(config) | ||
| ft_spec = FinetuneSpec(total_train_epochs=1, dataset_size=128, train_batch_size=8) | ||
| engine.create_process_group(parallel_strategy=alloc_mode.train) | ||
| engine.initialize(None, ft_spec) | ||
| return engine | ||
|
|
||
|
|
||
| def test_memory_efficient_lora(alloc_mode: str, output: str | None = None): | ||
| """Test that memory_efficient_load works correctly with LoRA. | ||
|
|
||
| This test verifies: | ||
| 1. Engine initializes successfully with memory_efficient_load=True and use_lora=True | ||
| 2. LoRA layers are properly applied | ||
| 3. Model can perform a forward pass | ||
| """ | ||
| rank = int(os.environ["RANK"]) | ||
| print(f"Running memory_efficient_load + LoRA test on rank {rank}") | ||
|
|
||
| succ = True | ||
|
|
||
| # Test 1: Create engine with memory_efficient_load=True | ||
| print(f"Rank {rank}: Creating engine with memory_efficient_load=True") | ||
| engine = make_fsdp_engine_with_lora(alloc_mode, memory_efficient_load=True) | ||
|
|
||
| # Test 2: Verify LoRA layers exist | ||
| lora_params = [ | ||
| name for name, _ in engine.model.named_parameters() if "lora" in name.lower() | ||
| ] | ||
| if not lora_params: | ||
| print(f"Rank {rank}: ERROR - No LoRA parameters found!") | ||
| succ = False | ||
| else: | ||
| print(f"Rank {rank}: Found {len(lora_params)} LoRA parameters") | ||
|
|
||
| # Test 3: Verify trainable params are only LoRA params | ||
| trainable_params = [ | ||
| name for name, p in engine.model.named_parameters() if p.requires_grad | ||
| ] | ||
| non_lora_trainable = [p for p in trainable_params if "lora" not in p.lower()] | ||
| if non_lora_trainable: | ||
| print( | ||
| f"Rank {rank}: WARNING - Found non-LoRA trainable params: {non_lora_trainable[:5]}" | ||
| ) | ||
|
|
||
| # Test 4: Simple forward pass to verify model works | ||
| print(f"Rank {rank}: Testing forward pass") | ||
| try: | ||
| with torch.no_grad(): | ||
| engine.eval() | ||
| # Create simple input | ||
| input_ids = torch.randint( | ||
| 100, 1000, (2, 32), dtype=torch.long, device=engine.device | ||
| ) | ||
| attention_mask = torch.ones_like(input_ids, dtype=torch.bool) | ||
|
|
||
| # Get logits through the model | ||
| outputs = engine.model( | ||
| input_ids=input_ids, attention_mask=attention_mask, use_cache=False | ||
| ) | ||
| logits = outputs.logits | ||
| print(f"Rank {rank}: Forward pass successful, logits shape: {logits.shape}") | ||
| except Exception as e: | ||
| print(f"Rank {rank}: ERROR - Forward pass failed: {e}") | ||
| succ = False | ||
|
|
||
| current_platform.synchronize() | ||
| dist.barrier() | ||
|
|
||
| engine.destroy() | ||
|
|
||
| if rank == 0 and output: | ||
| write_result(output, succ) | ||
|
|
||
| print( | ||
| f"Rank {rank}: memory_efficient_load + LoRA test {'PASSED' if succ else 'FAILED'}" | ||
| ) | ||
|
|
||
|
|
||
| def main(): | ||
| parser = argparse.ArgumentParser(description="Test memory_efficient_load with LoRA") | ||
| parser.add_argument( | ||
| "--output", | ||
| type=str, | ||
| default=None, | ||
| help="Optional path to save the output result", | ||
| ) | ||
| parser.add_argument( | ||
| "--allocation_mode", | ||
| type=str, | ||
| default="d1t1c1", | ||
| help="Allocation mode for the model", | ||
| ) | ||
| args = parser.parse_args() | ||
|
|
||
| test_memory_efficient_lora(alloc_mode=args.allocation_mode, output=args.output) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
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
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.