#3800·peft

FSDP2 with `reshard_after_forward=False`: `disable_adapter()` leaves LoRA frozen and `merge_adapter()` is lost at reshard

Author: hivazeCreated Sep 23, 2026Updated Sep 28, 2026

System Info

peft 0.21.0 and main (116a979), transformers 5.16.1, torch 2.11.0, Python 3.12, Linux. CPU with gloo, 2 processes. Same result on peft 0.18.1. The disable_adapter() part also reproduces on 2 GPUs with NCCL.

Who can help?

@BenjaminBossan @githubnemo

Reproduction

Follow-up to the FSDP2 point in whitecircle/halo#35. With FSDP2 and reshard_after_forward=False, the unsharded parameters stay registered on the modules from a forward until the next reshard, so disable_adapter(), merge_adapter() and unmerge_adapter() change those temporary copies instead of the sharded parameters FSDP2 keeps. Both patterns are common in LoRA RL: with model.disable_adapter(): ref_logits = model(**batch) for a KL reference, and merge, weight sync, unmerge on every step.

python
# torchrun --nproc_per_node=2 repro.py   (CPU, gloo)
import peft
import torch
import torch.distributed as dist
import transformers
from peft import LoraConfig, get_peft_model
from torch.distributed.device_mesh import init_device_mesh
from torch.distributed.fsdp import fully_shard
from torch.distributed.tensor import DTensor
from transformers import LlamaConfig, LlamaForCausalLM

dist.init_process_group("gloo")
mesh = init_device_mesh("cpu", (dist.get_world_size(),))
ids = torch.tensor([[1, 5, 9, 13, 17, 21, 25, 29]])
Q = "base_model.model.model.layers.0.self_attn.q_proj"


def build():
    torch.manual_seed(0)
    cfg = LlamaConfig(vocab_size=64, hidden_size=16, intermediate_size=32, num_hidden_layers=2,
                      num_attention_heads=2, num_key_value_heads=1)
    model = get_peft_model(LlamaForCausalLM(cfg), LoraConfig(r=4, target_modules=["q_proj", "v_proj"],
                                                             init_lora_weights=False))
    for layer in model.base_model.model.model.layers:
        fully_shard(layer, mesh=mesh, reshard_after_forward=False)
    fully_shard(model, mesh=mesh, reshard_after_forward=False)
    return model


def lora_params(model):
    return [p for n, p in model.named_parameters() if "lora_" in n]


def trainable(params):
    return f"{sum(p.requires_grad for p in params)}/{len(params)}"


def log(msg):
    if dist.get_rank() == 0:
        print(msg, flush=True)


log(f"peft {peft.__version__}, transformers {transformers.__version__}, torch {torch.__version__}")

# 1) disable_adapter(), e.g. reference logits for a KL term
model = build()
sharded = lora_params(model)  # FSDP2 sharded DTensors, held by the optimizer
opt = torch.optim.SGD(sharded, lr=0.1)
with torch.no_grad(), model.disable_adapter():
    model(input_ids=ids)
reg = lora_params(model)
log(f"after disable_adapter(): registered LoRA params DTensor={isinstance(reg[0], DTensor)} requires_grad "
    f"{trainable(reg)}; sharded LoRA params requires_grad {trainable(sharded)} (expected 8/8)")
for step in (1, 2):
    try:
        model(input_ids=ids, labels=ids).loss.backward()
        opt.step()
        opt.zero_grad()
        log(f"train step {step}: OK, LoRA params requires_grad {trainable(lora_params(model))} (expected 8/8)")
    except RuntimeError as e:
        log(f"train step {step}: RuntimeError: {e}")

# 2) merge_adapter() -> read the weights (e.g. to sync them to an inference engine) -> unmerge_adapter()
model = build()
layer = model.get_submodule(Q)
w = layer.base_layer.weight.full_tensor()
delta = layer.get_delta_weight("default").full_tensor()
with torch.no_grad():
    model(input_ids=ids)  # the unsharded params stay registered after this forward
model.merge_adapter()
sd_w = model.state_dict()[Q + ".base_layer.weight"].full_tensor()
merged_ok = torch.allclose(sd_w, w + delta, atol=1e-6)
log(f"state_dict() after merge_adapter(): q_proj == W + delta: {merged_ok} (expected True), "
    f"== W: {torch.equal(sd_w, w)}, layer.merged={layer.merged}")
model.unmerge_adapter()
w_now = layer.base_layer.weight.full_tensor()
log(f"after unmerge_adapter(): q_proj == W: {torch.allclose(w_now, w, atol=1e-6)} (expected True), "
    f"== W - delta: {torch.allclose(w_now, w - delta, atol=1e-6)}")
dist.destroy_process_group()

torchrun --nproc_per_node=2 repro.py prints:

peft 0.21.0, transformers 5.16.1, torch 2.11.0+cu130
after disable_adapter(): registered LoRA params DTensor=False requires_grad 8/8; sharded LoRA params requires_grad 0/8 (expected 8/8)
train step 1: OK, LoRA params requires_grad 0/8 (expected 8/8)
train step 2: RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
state_dict() after merge_adapter(): q_proj == W + delta: False (expected True), == W: True, layer.merged=True
after unmerge_adapter(): q_proj == W: False (expected True), == W - delta: True

FSDP2 treats the shards as the source of truth. Every unshard copies requires_grad from the shard, and every reshard (after backward, in the state_dict() pre-hook, or an explicit reshard()) drops the unsharded tensor without writing it back.

In part 1, the exit re-enables only the unsharded copies. Step 1 still trains through them, but after the reshard at the end of its backward the adapters are frozen again, so step 2 raises. With other trainable parameters there is no error and the adapters just stop updating. A loop that runs the reference forward right before every training forward happens to keep training, because each exit re-enables the fresh copies. It breaks once several training steps follow one reference pass.

In part 2, the merge goes into the unsharded copy and state_dict() reshards, so the weights read for the sync lack the LoRA delta while layer.merged stays True. unmerge_adapter() then subtracts the delta from the unmerged base weight. The reshard after the next backward, or an explicit reshard(), has the same effect.

With reshard_after_forward=True the script prints the expected values. FSDP2's default (None) doesn't reshard the root module after forward, so adapters owned by the root (a single fully_shard(model), or LoRA on lm_head with per-layer wrapping) hit both problems with the default too. set_adapter() and set_requires_grad() go through the same requires_grad helper, and their changes are reverted the same way. The nightly make tests_training doesn't cover this: its FSDP2 runs use fsdp_reshard_after_forward: true, and adapters.py only runs with the FSDP1 config.

Expected behavior

After the disable_adapter() context exits the adapters should be trainable again, and a merge should either land in the weights FSDP2 keeps (so state_dict() returns W + delta and unmerge_adapter() restores W) or be refused, whatever reshard_after_forward is.

One way to fix it: reshard the FSDP modules that own adapter parameters before PEFT toggles requires_grad or merges, e.g. at the start of BaseTuner._enable_adapter_layers (tuners_utils.py#L545), merge_adapter (#L1313) and unmerge_adapter (#L1348). Patching those three to call reshard() on every FSDPModule under the tuner's self.model makes the script print the expected values. A complete fix also has to reach a root FSDP module that wraps the PeftModel, or refuse while adapter params are unsharded.