-
Notifications
You must be signed in to change notification settings - Fork 395
[FSDP][1/n] Support LoRA training for FSDP backend. #1140
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
GuanxingLu
wants to merge
3
commits into
THUDM:main
Choose a base branch
from
GuanxingLu:feature/fsdp_lora
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
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
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,76 @@ | ||
| import logging | ||
| import os | ||
| import shutil | ||
| from pathlib import Path | ||
|
|
||
| import torch.distributed as dist | ||
| import torch.nn as nn | ||
| from torch.distributed.checkpoint.state_dict import StateDictOptions, get_model_state_dict | ||
|
|
||
| try: | ||
| from peft import LoraConfig, PeftModel, TaskType, get_peft_model | ||
| except ImportError as err: | ||
| raise ImportError("peft library required for LoRA. Install with: pip install peft") from err | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| LORA_READY_MARKER = ".lora_ready" | ||
| LORA_ADAPTER_NAME = "slime_lora" | ||
| LORA_SUBDIR = "tmp_lora" | ||
|
|
||
|
|
||
| def apply_lora_to_model(model: nn.Module, args) -> nn.Module: | ||
| if args.lora_adapter_path: | ||
| logger.info(f"Loading LoRA adapter from {args.lora_adapter_path}") | ||
| model = PeftModel.from_pretrained(model, args.lora_adapter_path, is_trainable=True) | ||
| peft_config = model.peft_config["default"] | ||
| if isinstance(peft_config.task_type, str): | ||
| peft_config.task_type = TaskType.CAUSAL_LM | ||
| model.print_trainable_parameters() | ||
| return model | ||
|
|
||
| lora_config = LoraConfig( | ||
| task_type=TaskType.CAUSAL_LM, | ||
| r=args.lora_rank, | ||
| lora_alpha=args.lora_alpha, | ||
| target_modules=args.target_modules, | ||
| bias="none", | ||
| ) | ||
|
|
||
| model = get_peft_model(model, lora_config) # autocast_adapter_dtype=False) | ||
| model.print_trainable_parameters() | ||
| logger.info(f"Applied LoRA: rank={args.lora_rank}, alpha={args.lora_alpha}") | ||
| return model | ||
|
|
||
|
|
||
| def is_lora_model(module: nn.Module) -> bool: | ||
| unwrapped = getattr(module, "_fsdp_wrapped_module", module) | ||
| return hasattr(unwrapped, "peft_config") | ||
|
|
||
|
|
||
| def save_lora_to_disk(module: nn.Module, save_dir: str) -> str: | ||
| """Save LoRA adapter to disk with file lock mechanism.""" | ||
| options = StateDictOptions(full_state_dict=True, cpu_offload=True) | ||
| full_state_dict = get_model_state_dict(module, options=options) | ||
|
|
||
| state_dict = {name: param for name, param in full_state_dict.items() if "lora_" in name} | ||
|
|
||
| if dist.get_rank() == 0: | ||
| save_path = Path(save_dir) | ||
| save_path.mkdir(parents=True, exist_ok=True) | ||
|
|
||
| module.save_pretrained(str(save_path), state_dict=state_dict) | ||
|
|
||
| # TODO: check if file lock is needed or better way to do it | ||
| os.sync() | ||
|
|
||
| logger.info(f"Saved LoRA adapter to {save_path}") | ||
| return save_dir | ||
|
|
||
|
|
||
| def delete_lora_from_disk(save_dir: str) -> None: | ||
| """Delete LoRA adapter files from disk.""" | ||
| save_path = Path(save_dir) | ||
| if save_path.exists(): | ||
| shutil.rmtree(save_path) | ||
| logger.info(f"Deleted LoRA adapter from {save_path}") |
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
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.
I am curious how long it take for SGLang to read LoRA weights from disk. Is it possible to pass through NCCL?I am not sure about the file size
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.
And we can not assume that in distributed training, there is a shared file system for every node. So the read from disk approach may not work here