Merged
[fix] Restore DeepSeek LoRA startup #1243
leedongkun30-archAdd on 25 days ago
[fix] Restore DeepSeek LoRA startup #1243
Merged
Total: 4 files changed+178-1
| @@ -0,0 +1,90 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# | ||
| 3 | +# This source code is licensed under the BSD-style license found in the | ||
| 4 | +# LICENSE file in the root directory of this source tree. | ||
| 5 | + | ||
| 6 | +import dataclasses | ||
| 7 | + | ||
| 8 | +import pytest | ||
| 9 | +import torch | ||
| 10 | +from torchtitan.config import derive | ||
| 11 | +from torchtitan.config.override import apply_overrides | ||
| 12 | +from torchtitan.models.common.rope import ComplexRoPE | ||
| 13 | + | ||
| 14 | +from torchtitan_npu.models.common.deepseek_lora import deepseek_v4_lora_transform | ||
| 15 | +from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_flash, deepseek_v4_flash_lora_compiled | ||
| 16 | +from torchtitan_npu.models.deepseek_v4_1.config_registry import ( | ||
| 17 | + deepseek_v4_1_flash_lora, | ||
| 18 | + deepseek_v4_1_flash_text_lora, | ||
| 19 | +) | ||
| 20 | +from torchtitan_npu.override.common.rope import AscComplexRoPE, AscPartialComplexRoPE, WorkaroundComplexRoPE | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +class CustomComplexRoPE(ComplexRoPE): | ||
| 24 | + @dataclasses.dataclass(kw_only=True, slots=True) | ||
| 25 | + class Config(ComplexRoPE.Config): | ||
| 26 | + pass | ||
| 27 | + | ||
| 28 | + def __init__(self, config): | ||
| 29 | + super().__init__(config) | ||
| 30 | + self.scale = torch.nn.Parameter(torch.ones(())) | ||
| 31 | + | ||
| 32 | + | ||
| 33 | +@pytest.mark.parametrize( | ||
| 34 | + "factory", | ||
| 35 | + [deepseek_v4_flash_lora_compiled, deepseek_v4_1_flash_lora, deepseek_v4_1_flash_text_lora], | ||
| 36 | + ids=["v4-compiled", "v4.1-multimodal", "v4.1-text"], | ||
| 37 | +) | ||
| 38 | +@pytest.mark.parametrize( | ||
| 39 | + "variant,rope_cls", | ||
| 40 | + [("workaround", WorkaroundComplexRoPE), ("asc_complex", AscComplexRoPE), ("asc_partial", AscPartialComplexRoPE)], | ||
| 41 | + ids=["workaround", "asc-complex", "asc-partial"], | ||
| 42 | +) | ||
| 43 | +def test_lora_recipe_selects_requested_rope_override(factory, variant, rope_cls): | ||
| 44 | + config = factory() | ||
| 45 | + config.model.update_from_config(config=config) | ||
| 46 | + original = { | ||
| 47 | + fqn: dataclasses.asdict(cfg) | ||
| 48 | + for fqn, cfg, _, _ in config.model.traverse(ComplexRoPE.Config, recurse=True) | ||
| 49 | + } | ||
| 50 | + assert original | ||
| 51 | + assert all( | ||
| 52 | + type(cfg) is ComplexRoPE.Config | ||
| 53 | + for _, cfg, _, _ in config.model.traverse(ComplexRoPE.Config, recurse=True) | ||
| 54 | + ) | ||
| 55 | + with torch.device("meta"): | ||
| 56 | + original_model = config.model.build() | ||
| 57 | + original_trainable = {name for name, parameter in original_model.named_parameters() if parameter.requires_grad} | ||
| 58 | + assert original_trainable | ||
| 59 | + config.override.imports = [f"torchtitan_npu.override.common.rope.{variant}"] | ||
| 60 | + | ||
| 61 | + apply_overrides(config.override, config) | ||
| 62 | + | ||
| 63 | + selected = {fqn: cfg for fqn, cfg, _, _ in config.model.traverse(ComplexRoPE.Config, recurse=True)} | ||
| 64 | + assert selected.keys() == original.keys() | ||
| 65 | + for fqn, cfg in selected.items(): | ||
| 66 | + assert type(cfg) is rope_cls.Config | ||
| 67 | + assert dataclasses.asdict(cfg) == original[fqn] | ||
| 68 | + with torch.device("meta"): | ||
| 69 | + model = config.model.build() | ||
| 70 | + trainable = {name for name, parameter in model.named_parameters() if parameter.requires_grad} | ||
| 71 | + assert trainable == original_trainable | ||
| 72 | + assert all(type(model.get_submodule(fqn)) is rope_cls for fqn in selected) | ||
| 73 | + | ||
| 74 | + | ||
| 75 | +@pytest.mark.parametrize("variant", ["workaround", "asc_complex", "asc_partial"]) | ||
| 76 | +def test_lora_rope_override_preserves_custom_subclass_and_its_frozen_parameter(variant): | ||
| 77 | + config = deepseek_v4_flash() | ||
| 78 | + fqn, cfg, parent, attr = next(config.model.traverse(ComplexRoPE.Config, recurse=True)) | ||
| 79 | + assert parent is not None and isinstance(attr, str) | ||
| 80 | + setattr(parent, attr, derive(cfg, CustomComplexRoPE.Config)) | ||
| 81 | + config.model = deepseek_v4_lora_transform().transform(config.model) | ||
| 82 | + config.override.imports = [f"torchtitan_npu.override.common.rope.{variant}"] | ||
| 83 | + | ||
| 84 | + apply_overrides(config.override, config) | ||
| 85 | + | ||
| 86 | + with torch.device("meta"): | ||
| 87 | + model = config.model.build() | ||
| 88 | + custom_rope = model.get_submodule(fqn) | ||
| 89 | + assert type(custom_rope) is CustomComplexRoPE | ||
| 90 | + assert not custom_rope.scale.requires_grad | ||
| @@ -234,6 +234,78 @@ def test_peft_retention_preserves_native_resume_when_newer_dcp_lacks_adapters(tm | |||
| 234 | assert {path.name for path in root.iterdir()} == {"step-1", "step-2", "step-3"} | 234 | assert {path.name for path in root.iterdir()} == {"step-1", "step-2", "step-3"} |
| 235 | 235 | ||
| 236 | 236 | ||
| 237 | +@pytest.mark.parametrize("family", ["v4", "v41"]) | ||
| 238 | +@pytest.mark.parametrize("load_step", [-1, 0]) | ||
| 239 | +def test_native_step_zero_seed_initializes_base_without_overwriting_adapters(tmp_path, monkeypatch, family, load_step): | ||
| 240 | + config = _model_config(monkeypatch, family) | ||
| 241 | + root = tmp_path / "checkpoints" | ||
| 242 | + seed = root / "step-0" | ||
| 243 | + original = _model(config) | ||
| 244 | + _write_native_base(seed, original) | ||
| 245 | + expected = {name: value for name, value in _clone_state(original).items() if not is_lora_parameter(name)} | ||
| 246 | + model = _model(config) | ||
| 247 | + with torch.no_grad(): | ||
| 248 | + for parameter in model.parameters(): | ||
| 249 | + parameter.fill_(0.75) | ||
| 250 | + model.resume_probe.zero_() | ||
| 251 | + adapters = {name: value for name, value in _clone_state(model).items() if is_lora_parameter(name)} | ||
| 252 | + | ||
| 253 | + with closing(_manager(root, seed, config, family, model, initial_hf=False, verify=True)) as manager: | ||
| 254 | + assert manager.load(step=load_step) | ||
| 255 | + | ||
| 256 | + actual = model.state_dict() | ||
| 257 | + _assert_state({name: actual[name] for name in expected}, expected) | ||
| 258 | + _assert_state({name: actual[name] for name in adapters}, adapters) | ||
| 259 | + | ||
| 260 | + | ||
| 261 | +@pytest.mark.parametrize("family", ["v4", "v41"]) | ||
| 262 | +@pytest.mark.parametrize("keep,full_save", [(2, False), (3, False), (2, True)]) | ||
| 263 | +def test_adapter_only_retention_keeps_initial_seed_and_resumes_latest_state( | ||
| 264 | + tmp_path, monkeypatch, family, keep, full_save | ||
| 265 | +): | ||
| 266 | + config = _model_config(monkeypatch, family) | ||
| 267 | + root = tmp_path / "checkpoints" | ||
| 268 | + seed = root / "step-0" | ||
| 269 | + _write_native_base(seed, _model(config)) | ||
| 270 | + monkeypatch.setattr(torch.distributed, "get_rank", lambda: 0) | ||
| 271 | + | ||
| 272 | + with closing(_manager(root, seed, config, family, _model(config), initial_hf=False, keep=keep)) as manager: | ||
| 273 | + assert manager.load(step=0) | ||
| 274 | + for step in (1, 2, 3): | ||
| 275 | + if step == 3 and full_save: | ||
| 276 | + manager.periodic_save_adapter_only = False | ||
| 277 | + with torch.no_grad(): | ||
| 278 | + for parameter in manager.states["model"].model[0].parameters(): | ||
| 279 | + if parameter.requires_grad: | ||
| 280 | + parameter.add_(0.25) | ||
| 281 | + manager.states["train_state"].step = manager.states["dataloader"].step = step | ||
| 282 | + assert manager.save(step) | ||
| 283 | + expected = _clone_state(manager.states["model"].model[0]) | ||
| 284 | + | ||
| 285 | + assert (seed / ".metadata").is_file() | ||
| 286 | + with closing(_manager(root, seed, config, family, _model(config), initial_hf=False, keep=keep)) as manager: | ||
| 287 | + assert manager._find_load_step() == 3 | ||
| 288 | + assert manager.load() | ||
| 289 | + assert manager.states["train_state"].step == manager.states["dataloader"].step == 3 | ||
| 290 | + _assert_state(manager.states["model"].state_dict(), expected) | ||
| 291 | + | ||
| 292 | + | ||
| 293 | +@pytest.mark.parametrize("family", ["v4", "v41"]) | ||
| 294 | +def test_automatic_selection_rejects_step_zero_without_adapters_unless_it_is_initial_base( | ||
| 295 | + tmp_path, monkeypatch, family | ||
| 296 | +): | ||
| 297 | + config = _model_config(monkeypatch, family) | ||
| 298 | + model = _model(config) | ||
| 299 | + root = tmp_path / "checkpoints" | ||
| 300 | + base = tmp_path / "base" | ||
| 301 | + _write_native_base(base, model) | ||
| 302 | + _write_native_base(root / "step-0", model) | ||
| 303 | + | ||
| 304 | + with closing(_manager(root, base, config, family, model, initial_hf=False)) as manager: | ||
| 305 | + with pytest.raises(ValueError, match="requires adapter tensors"): | ||
| 306 | + manager.load() | ||
| 307 | + | ||
| 308 | + | ||
| 237 | def _clone_state(model): | 309 | def _clone_state(model): |
| 238 | return {key: value.detach().clone() for key, value in model.state_dict().items()} | 310 | return {key: value.detach().clone() for key, value in model.state_dict().items()} |
| 239 | 311 | ||
| @@ -22,6 +22,7 @@ from torchtitan.models.common.lora import ( | |||
| 22 | get_lora_grouped_linear, | 22 | get_lora_grouped_linear, |
| 23 | get_lora_linear, | 23 | get_lora_linear, |
| 24 | ) | 24 | ) |
| 25 | +from torchtitan.models.common.rope import ComplexRoPE | ||
| 25 | from torchtitan.protocols.module import Module | 26 | from torchtitan.protocols.module import Module |
| 26 | from torchtitan.protocols.sharding import ShardingConfig | 27 | from torchtitan.protocols.sharding import ShardingConfig |
| 27 | 28 | ||
| @@ -152,8 +153,11 @@ class DeepSeekLoRATransform(LoRATransform): | |||
| 152 | 153 | ||
| 153 | def transform(self, model): | 154 | def transform(self, model): |
| 154 | frozen_indexers = {} | 155 | frozen_indexers = {} |
| 156 | + original_ropes = {} | ||
| 155 | freeze = LoRATransform(handlers=(), target_modules=[]) | 157 | freeze = LoRATransform(handlers=(), target_modules=[]) |
| 156 | for fqn, cfg, _, attr in model.traverse(Module.Config, recurse=True): | 158 | for fqn, cfg, _, attr in model.traverse(Module.Config, recurse=True): |
| 159 | + if type(cfg) is ComplexRoPE.Config: | ||
| 160 | + original_ropes[fqn] = cfg | ||
| 157 | if attr == "indexer": | 161 | if attr == "indexer": |
| 158 | frozen_indexers[fqn] = freeze.transform(copy.deepcopy(cfg)) | 162 | frozen_indexers[fqn] = freeze.transform(copy.deepcopy(cfg)) |
| 159 | transformed = LoRATransform.transform(self, model) | 163 | transformed = LoRATransform.transform(self, model) |
| @@ -161,6 +165,10 @@ class DeepSeekLoRATransform(LoRATransform): | |||
| 161 | if fqn in frozen_indexers: | 165 | if fqn in frozen_indexers: |
| 162 | assert parent is not None and isinstance(attr, str) | 166 | assert parent is not None and isinstance(attr, str) |
| 163 | setattr(parent, attr, frozen_indexers[fqn]) | 167 | setattr(parent, attr, frozen_indexers[fqn]) |
| 168 | + # Base RoPE has only buffers; retain its concrete config for exact overrides. | ||
| 169 | + for fqn, _, parent, attr in transformed.traverse(ComplexRoPE.Config): | ||
| 170 | + if fqn in original_ropes and isinstance(attr, str): | ||
| 171 | + setattr(parent, attr, original_ropes[fqn]) | ||
| 164 | return transformed | 172 | return transformed |
| 165 | 173 | ||
| 166 | 174 | ||
| @@ -118,6 +118,9 @@ class DeepSeekV4PEFTCheckpointManager(NPUCheckpointManager): | |||
| 118 | # A preceding retention pass may still be deleting this directory. | 118 | # A preceding retention pass may still be deleting this directory. |
| 119 | continue | 119 | continue |
| 120 | saved_keys = set(metadata.state_dict_metadata) | 120 | saved_keys = set(metadata.state_dict_metadata) |
| 121 | + if step == 0 and not self.initial_load_in_hf and directory == self.initial_load_path: | ||
| 122 | + # A configured base seed initializes adapters rather than resuming them. | ||
| 123 | + return latest_native if latest_native != -1 else 0 | ||
| 121 | try: | 124 | try: |
| 122 | self._validate_native_resume(saved_keys) | 125 | self._validate_native_resume(saved_keys) |
| 123 | except ValueError as error: | 126 | except ValueError as error: |
| @@ -154,7 +157,11 @@ class DeepSeekV4PEFTCheckpointManager(NPUCheckpointManager): | |||
| 154 | 157 | ||
| 155 | def _is_purge_exempt(self, step: int) -> bool: | 158 | def _is_purge_exempt(self, step: int) -> bool: |
| 156 | # Exports can occupy retention slots without replacing a training resume point. | 159 | # Exports can occupy retention slots without replacing a training resume point. |
| 157 | - return super()._is_purge_exempt(step) or step == self._purge_resume_step | 160 | + return ( |
| 161 | + super()._is_purge_exempt(step) | ||
| 162 | + or step == self._purge_resume_step | ||
| 163 | + or filesystem.join(self.folder, f"step-{step}") == self.initial_load_path | ||
| 164 | + ) | ||
| 158 | 165 | ||
| 159 | def save(self, curr_step: int, last_step: bool = False) -> bool: | 166 | def save(self, curr_step: int, last_step: bool = False) -> bool: |
| 160 | if last_step and self.last_save_in_peft and self._should_save(curr_step, last_step): | 167 | if last_step and self.last_save_in_peft and self._should_save(curr_step, last_step): |
I reproduced a LoRA cold-start failure with a native DCP containing only base model weights. The output checkpoint directory contains just
<checkpoint_folder>/step-0,initial_load_pathpoints to that seed, andload_step=-1enables automatic selection._find_load_step()checks the seed for adapter tensors before base initialization and raisesLoRA resume requires adapter tensors. The same seed loads with--checkpointer.load-step=0.Please let automatic selection fall back to the configured
step-0for base initialization when there is no newer valid resume checkpoint. Retention should preserve the seed while adapter-only checkpoints depend on it.