-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Add generic native LoRA training support #1924
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
shahrryyar
wants to merge
2
commits into
QwenAudio:main
Choose a base branch
from
shahrryyar:lora/native-lora-pr
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.
+237
−3
Open
Changes from 1 commit
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| """Small native LoRA implementation for CosyVoice adaptation. | ||
|
|
||
| This intentionally has no PEFT dependency. It injects adapters into the Qwen | ||
| projection layers while leaving the original weights available for the | ||
| unmodified base model. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import Iterable | ||
|
|
||
| import torch | ||
| from torch import nn | ||
| from torch.nn import functional as F | ||
|
|
||
|
|
||
| class LoRALinear(nn.Module): | ||
| def __init__(self, base: nn.Linear, rank: int, alpha: float, dropout: float): | ||
| super().__init__() | ||
| if rank < 1: | ||
| raise ValueError("LoRA rank must be positive") | ||
| self.base = base | ||
| self.rank = rank | ||
| self.alpha = alpha | ||
| self.scaling = alpha / rank | ||
| self.dropout = nn.Dropout(dropout) if dropout > 0 else nn.Identity() | ||
| self.lora_A = nn.Parameter(torch.empty(rank, base.in_features)) | ||
| self.lora_B = nn.Parameter(torch.zeros(base.out_features, rank)) | ||
| nn.init.kaiming_uniform_(self.lora_A, a=5**0.5) | ||
| for parameter in self.base.parameters(): | ||
| parameter.requires_grad = False | ||
|
|
||
| def forward(self, x: torch.Tensor) -> torch.Tensor: | ||
| update = F.linear(F.linear(self.dropout(x), self.lora_A), self.lora_B) | ||
| return self.base(x) + update * self.scaling | ||
|
|
||
| @torch.no_grad() | ||
| def merge_(self) -> None: | ||
| self.base.weight.add_(self.lora_B @ self.lora_A, alpha=self.scaling) | ||
|
|
||
|
|
||
| TARGET_LINEAR_NAMES = { | ||
| "q_proj", | ||
| "k_proj", | ||
| "v_proj", | ||
| "o_proj", | ||
| "gate_proj", | ||
| "up_proj", | ||
| "down_proj", | ||
| } | ||
|
|
||
|
|
||
| def _replace_target_linears(module: nn.Module, rank: int, alpha: float, dropout: float) -> int: | ||
| count = 0 | ||
| for name, child in list(module.named_children()): | ||
| if isinstance(child, nn.Linear) and name in TARGET_LINEAR_NAMES: | ||
| setattr(module, name, LoRALinear(child, rank, alpha, dropout)) | ||
| count += 1 | ||
| else: | ||
| count += _replace_target_linears(child, rank, alpha, dropout) | ||
| return count | ||
|
|
||
|
|
||
| def inject_lora(model: nn.Module, rank: int = 16, alpha: float = 32.0, dropout: float = 0.05) -> int: | ||
| """Freeze the model and inject LoRA into Qwen projections. | ||
|
|
||
| The CosyVoice speech embedding and decoder remain trainable because they | ||
| are the language-adaptation head; all other parameters remain frozen. | ||
| """ | ||
| for parameter in model.parameters(): | ||
| parameter.requires_grad = False | ||
|
|
||
| count = _replace_target_linears(model, rank, alpha, dropout) | ||
| train_head_names = ("llm_decoder", "speech_embedding") | ||
| for name, parameter in model.named_parameters(): | ||
| if any( | ||
| name == head | ||
| or name.startswith(f"{head}.") | ||
| or f".{head}." in name | ||
| for head in train_head_names | ||
| ): | ||
| parameter.requires_grad = True | ||
|
|
||
| trainable = [parameter for parameter in model.parameters() if parameter.requires_grad] | ||
| if not trainable: | ||
| raise RuntimeError("LoRA injection produced no trainable parameters") | ||
| model._lora_enabled = True | ||
| model._lora_target_count = count | ||
| return count | ||
|
|
||
|
|
||
| def lora_state_dict(model: nn.Module) -> dict[str, torch.Tensor]: | ||
| """Return only LoRA and adaptation-head weights for a small checkpoint.""" | ||
| trainable_names = {name for name, p in model.named_parameters() if p.requires_grad} | ||
| return { | ||
| name: value.detach().cpu() | ||
| for name, value in model.state_dict().items() | ||
| if name in trainable_names | ||
| } | ||
|
|
||
|
|
||
| def load_lora_state_dict(model: nn.Module, state: dict[str, torch.Tensor]) -> None: | ||
| missing, unexpected = model.load_state_dict(state, strict=False) | ||
| unexpected = [name for name in unexpected if name not in {"step", "epoch"}] | ||
| if unexpected: | ||
| raise RuntimeError(f"Unexpected LoRA checkpoint keys: {unexpected[:8]}") | ||
| missing_trainable = [name for name in missing if name in state] | ||
| if missing_trainable: | ||
| raise RuntimeError(f"Could not load LoRA checkpoint keys: {missing_trainable[:8]}") | ||
|
|
||
|
|
||
| def trainable_parameters(model: nn.Module) -> Iterable[nn.Parameter]: | ||
| return (parameter for parameter in model.parameters() if parameter.requires_grad) | ||
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,36 @@ | ||
| # Native LoRA adaptation | ||
|
|
||
| CosyVoice can adapt its language-model stage with native LoRA adapters without | ||
| adding a PEFT dependency or changing the base checkpoint. | ||
|
|
||
| ## Training | ||
|
|
||
| Use the existing LLM training entry point and enable LoRA: | ||
|
|
||
| ```bash | ||
| PYTHONPATH=.:third_party/Matcha-TTS \ | ||
| python cosyvoice/bin/train.py \ | ||
| --train_engine torch_ddp \ | ||
| --config path/to/config.yaml \ | ||
| --train_data path/to/train.data.list \ | ||
| --cv_data path/to/dev.data.list \ | ||
| --model llm \ | ||
| --checkpoint path/to/llm.pt \ | ||
| --model_dir experiments/lora \ | ||
| --tensorboard_dir tensorboard/lora \ | ||
| --lora --lora_rank 16 --lora_alpha 32 --lora_dropout 0.05 | ||
| ``` | ||
|
|
||
| LoRA freezes the base model, injects adapters into the attention and MLP | ||
| projections, and keeps the speech embedding and decoder heads trainable. The | ||
| optimizer receives only trainable parameters. | ||
|
|
||
| To continue from an adapter checkpoint, use `--lora_checkpoint`. The adapter | ||
| checkpoint contains only trainable adapter/head weights plus `epoch` and | ||
| `step`, so the original base checkpoint is still required. | ||
|
shahrryyar marked this conversation as resolved.
Outdated
|
||
|
|
||
| ## Inference | ||
|
|
||
| Construct the matching base model, inject the same rank and alpha, and load the | ||
| adapter state with `cosyvoice.utils.lora.load_lora_state_dict`. The base model | ||
| remains available for fallback, comparison, or a later merge operation. | ||
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,56 @@ | ||
| import copy | ||
| import unittest | ||
|
|
||
| import torch | ||
| from torch import nn | ||
|
|
||
| from cosyvoice.utils.lora import ( | ||
| LoRALinear, | ||
| inject_lora, | ||
| load_lora_state_dict, | ||
| lora_state_dict, | ||
| ) | ||
|
|
||
|
|
||
| class TinyLanguageModel(nn.Module): | ||
| def __init__(self): | ||
| super().__init__() | ||
| self.q_proj = nn.Linear(4, 4) | ||
| self.ff = nn.Linear(4, 4) | ||
| self.llm_decoder = nn.Linear(4, 4) | ||
| self.speech_embedding = nn.Embedding(8, 4) | ||
|
|
||
| def forward(self, x): | ||
| return self.llm_decoder(self.q_proj(x) + self.ff(x)) | ||
|
|
||
|
|
||
| class NativeLoRATest(unittest.TestCase): | ||
| def test_injection_freezes_base_and_keeps_adaptation_heads_trainable(self): | ||
| model = TinyLanguageModel() | ||
| count = inject_lora(model, rank=2, alpha=4, dropout=0.0) | ||
|
|
||
| self.assertEqual(count, 1) | ||
| self.assertIsInstance(model.q_proj, LoRALinear) | ||
| self.assertFalse(model.q_proj.base.weight.requires_grad) | ||
| self.assertTrue(model.q_proj.lora_A.requires_grad) | ||
| self.assertTrue(model.llm_decoder.weight.requires_grad) | ||
| self.assertTrue(model.speech_embedding.weight.requires_grad) | ||
| self.assertFalse(model.ff.weight.requires_grad) | ||
|
|
||
| def test_initial_adapter_is_a_noop_and_state_round_trips(self): | ||
| model = TinyLanguageModel() | ||
| baseline = copy.deepcopy(model) | ||
| inject_lora(model, rank=2, alpha=4, dropout=0.0) | ||
| sample = torch.randn(3, 4) | ||
|
|
||
| torch.testing.assert_close(model(sample), baseline(sample)) | ||
| state = lora_state_dict(model) | ||
| restored = TinyLanguageModel() | ||
| inject_lora(restored, rank=2, alpha=4, dropout=0.0) | ||
| load_lora_state_dict(restored, state) | ||
| for name, value in state.items(): | ||
| torch.testing.assert_close(restored.state_dict()[name], value) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
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.