Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/gpu_unit_tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,7 @@ jobs:
# Order: cheap unit tests first to fail fast, trainer/ep2 last (multi-subprocess, ~5-10 min each).
run: |
uv run --frozen pytest -s -x tests/lora/test_target_mapping.py
uv run --frozen pytest -s -x tests/lora/test_veomni_lora_native.py
uv run --frozen pytest -s -x tests/lora/test_qwen3_5_moe_lora.py
uv run --frozen pytest -s -x tests/lora/test_dense_mlp_lora.py
uv run --frozen pytest -s -x tests/lora/test_veomni_lora_moe_native.py
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/npu_unit_tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,7 @@ jobs:
# sync needed here.
run: |
uv run --frozen pytest -v -s -x tests/lora/test_lora_trainer_saveload.py
uv run --frozen pytest -v -s -x tests/lora/test_veomni_lora_native.py
uv run --frozen pytest -v -s -x tests/lora/test_qwen3_5_moe_lora.py
- name: Run MoE-LoRA ep_sharded_stream_load (PEFT, EP=2)
# Exercises the PEFT ep_sharded adapter streaming *and* the NPU
Expand Down
18 changes: 18 additions & 0 deletions docs/key_features/lora.md
Original file line number Diff line number Diff line change
Expand Up @@ -723,3 +723,21 @@ torchrun --nproc_per_node=4 tests/lora/test_moe_lora_trainer.py \
1. Writer trains `max_steps=4`, writes DCP shards at step 2 / step 4 and the HF LoRA adapter (`adapter_config.json` with the `veomni_lora` block + `adapter_model.safetensors`, no sidecar) at the same cadence; snapshots the full LoRA tensors at `on_train_begin` and `on_train_end`.
2. DCP-resume subprocess loads the step-2 DCP shard, continues to step 4, and the resulting LoRA tensors must be **bit-exact** vs the writer's `on_train_end` snapshot (DCP ships model + optimizer + RNG + dataloader state).
3. LoRA-adapter-resume subprocess loads the step-4 HF adapter via `model.lora_config.lora_adapter`, and the resulting `on_train_begin` snapshot (= post-load, pre-train) must be bit-exact vs the writer's `on_train_end` snapshot in bf16 (the on-disk adapter dtype).

### Temporarily disabling native dense adapters

`VeOmniLoraModel.disable_adapter()` bypasses dense adapter contributions without
changing base weights, adapter parameters, or their `requires_grad` flags:

```python
with model.disable_adapter():
with torch.no_grad():
reference_output = model(input_ids=input_ids)
```

The context restores the previous state on exit, including nested contexts and
exceptions. It requires unmerged dense adapters; expert adapters are not yet
supported. To use the result as a frozen base reference policy, train with
`bias="none"` and no extra trainable base modules. Disabling adapters does not
undo updates to trainable base biases or other base parameters. Keep the context
active for any backward recomputation if using it outside inference.
30 changes: 30 additions & 0 deletions tests/lora/test_veomni_lora_native.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,3 +303,33 @@ def test_peft_bidirectional_interop(tmp_path):

if __name__ == "__main__":
raise SystemExit(pytest.main([__file__, "-v"]))


def test_disable_adapter_restores_nested_context_after_exception():
"""Reference inference bypasses nonzero adapters without changing weights."""
base = Toy()
reference = copy.deepcopy(base)
model = VeOmniLoraModel(base, _base_config())
_randomize_lora_b(model)
x = torch.randn(3, 32)
adapted = model(x).detach().clone()
expected = reference(x).detach()
assert not torch.equal(adapted, expected)
with pytest.raises(RuntimeError, match="test exception"):
with model.disable_adapter():
torch.testing.assert_close(model(x), expected, rtol=0, atol=0)
with model.disable_adapter():
torch.testing.assert_close(model(x), expected, rtol=0, atol=0)
torch.testing.assert_close(model(x), expected, rtol=0, atol=0)
raise RuntimeError("test exception")
torch.testing.assert_close(model(x), adapted, rtol=0, atol=0)


def test_disable_adapter_rejects_merged_layers_before_changing_flags():
model = VeOmniLoraModel(Toy(), _base_config())
layers = [m for m in model.modules() if isinstance(m, LoraLinear)]
layers[-1].merge()
with pytest.raises(ValueError, match="unmerged"):
with model.disable_adapter():
pytest.fail("Merged weights cannot provide the base-policy reference")
assert all(not layer.disable_adapters for layer in layers)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add a MoE rejection case alongside this merged-layer case? Assert that the unsupported call leaves existing adapter flags unchanged.

3 changes: 2 additions & 1 deletion veomni/lora/layers.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ def _init_lora_layer(self, base_layer: nn.Module) -> None:
self.lora_alpha: dict[str, int] = {}
self.use_rslora: dict[str, bool] = {}
self._merged_adapters: list[str] = []
self.disable_adapters = False

@property
def merged(self) -> bool:
Expand Down Expand Up @@ -141,7 +142,7 @@ def __init__(

def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:
result = self.base_layer(x, *args, **kwargs)
if self.merged:
if self.merged or self.disable_adapters:
return result
adapter = self.active_adapter
if adapter not in self.lora_A:
Expand Down
25 changes: 25 additions & 0 deletions veomni/lora/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@

from __future__ import annotations

from contextlib import contextmanager
from typing import Any

import torch.nn as nn
Expand Down Expand Up @@ -131,6 +132,30 @@ def get_lora_config(self, adapter_name: str | None = None) -> VeOmniLoraConfig:
def get_base_model(self) -> nn.Module:
return self.base_model.model

@contextmanager
def disable_adapter(self):
"""Temporarily bypass dense adapters for reference-policy inference.

Restores every layer's previous state, including on nested use or an
exception. Merged weights and expert adapters require separate handling
and are rejected before any layer is changed.
"""
from .layers import LoraLinear

if self.get_lora_config().has_moe:
raise NotImplementedError("disable_adapter() currently supports dense LoRA only.")
layers = [module for module in self.modules() if isinstance(module, LoraLinear)]
if any(layer.merged for layer in layers):
raise ValueError("disable_adapter() requires unmerged LoRA layers.")
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
previous = [layer.disable_adapters for layer in layers]
try:
for layer in layers:
layer.disable_adapters = True
yield
finally:
for layer, disabled in zip(layers, previous):
layer.disable_adapters = disabled

def forward(self, *args: Any, **kwargs: Any) -> Any:
return self.base_model(*args, **kwargs)

Expand Down
Loading