8000 verl/verl/utils/fsdp_utils.py at laminar · tongyx361/verl · GitHub
[go: up one dir, main page]

Skip to content

Latest commit

 

History

History
1234 lines (1021 loc) · 51 KB

fsdp_utils.py

File metadata and controls

1234 lines (1021 loc) · 51 KB
old_register_parameter(module, name, param)
# we will skip register shared parameters as it
# is already registered previously
if param is not None and param not in registered:
param_cls = type(module._parameters[name])
kwargs = module._parameters[name].__dict__
kwargs["requires_grad"] = param.requires_grad
module._parameters[name] = param_cls(module._parameters[name].to(device), **kwargs)
registered.add(module._parameters[name])
try:
nn.Module.register_parameter = register_empty_parameter
yield
finally:
registered.clear()
nn.Module.register_parameter = old_register_parameter
def parallel_load_safetensors(filepath):
"""
Parallel load safetensors from huggingface checkpoint
Huggingface checkpoint contains:
- config.json: a json file for model configuration
- model.safetensor.index.json: a json file for safetensors (parameters & buffers) index
- model-000x-of-ooxx.safetensors: a binary file for safetensors (parameters & buffers) chunks
Or (when model is small),
- model.safetensors: a binary file for all parameters and buffers
Each rank will own a part of model chunks and load them directly into GPU memory.
"""
from safetensors.torch import load_file
safetensors2param = {}
index_file = os.path.join(filepath, "model.safetensors.index.json")
if os.path.exists(index_file):
index = json.load(open(index_file, "rb"))
for param_name, filename in index["weight_map"].items():
safetensors2param.setdefault(filename, []).append(param_name)
else:
# in this case, the model is small and we can load it all at once
param_file = os.path.join(filepath, "model.safetensors")
assert os.path.exists(param_file), f"Cannot find {param_file}"
states = load_file(param_file)
for param_name in states:
safetensors2param.setdefault("model.safetensors", []).append(param_name)
del states
total_files = len(safetensors2param)
ckpt_chunks = sorted(safetensors2param.keys())
world_size = dist.get_world_size()
size = int(math.ceil(total_files / world_size))
ckpt_chunks = [ckpt_chunks[rank * size : rank * size + size] for rank in range(world_size)]
shard_states = {}
device = get_device_id()
for rank, files in enumerate(ckpt_chunks):
if rank == dist.get_rank():
for file in files:
file = os.path.join(filepath, file)
states = load_file(file, device=device)
# print(f"rank {rank} loading {file}...")
shard_states.update(states)
else:
for file in files:
for param_name in safetensors2param[file]:
shard_states[param_name] = rank
return shard_states
def parallel_init_module_fn(module: torch.nn.Module, shard_states: dict[str, torch.nn.Parameter]):
"""
Generate a function to initialize sub-modules in the `module` with `shard_states`
from huggingface checkpoint.
Args:
module (torch.nn.Module): the global module to be initialized
shard_states (Dict[str, torch.nn.Parameter]): the shard states from huggingface checkpoint
Returns:
init_fn (Callable): a function to initialize sub-modules in the `module` with `shard_states`
"""
state2fqn = {}
for name, state in itertools.chain(
module.named_parameters(remove_duplicate=False), module.named_buffers(remove_duplicate=False)
):
state2fqn.setdefault(state, []).append(name)
# remove standalone parameters and buffers
shared = {s for s, names in state2fqn.items() if len(names) > 1}
materialized_states = {}
@torch.no_grad()
def create_and_sync_state(param_name, state, is_param):
assert param_name in shard_states, f"{param_name} not loaded"
device = get_device_id()
if is_param:
param = torch.nn.Parameter(torch.empty_like(state.data, device=device), requires_grad=state.requires_grad)
else: # buffer
param = torch.empty_like(state.data, device=device)
loaded = shard_states[param_name]
if isinstance(loaded, torch.nn.Parameter | torch.Tensor):
# NOTE: loaded.dtype can be different with param.dtype
param.data.copy_(loaded.data)
dist.broadcast(param.data, src=dist.get_rank())
else:
assert isinstance(loaded, int) # the rank that holds the state
dist.broadcast(param.data, src=loaded)
shard_states.pop(param_name)
del loaded
return param
def init_fn(sub_mod: torch.nn.Module, recurse: bool = True):
param_and_buffers = tuple(sub_mod.named_parameters(recurse=False)) + tuple(sub_mod.named_buffers(recurse=False))
# param_and_buffers = sorted(sub_mod.named_parameters(recurse=False), key=lambda x: x[0])
for name, state in param_and_buffers:
if not state.is_meta:
continue
is_param = name in sub_mod._parameters
fqn = state2fqn[state].pop(0)
# non-persistent buffers will not be saved in state dict, we can safely skip it
if (not is_param) and fqn not in shard_states:
if state.is_meta:
raise RuntimeError(
f"find a non-persistent buffer ({fqn}) initiated with device meta. Such buffer is not saved "
f"in checkpoint and user should guarantee to init in CPU / GPU device."
)
continue
# for shared parameter, we get it from the first time it is created
if state in shared:
if state not in materialized_states:
materialized_states[state] = create_and_sync_state(fqn, state, is_param)
else:
if fqn in shard_states:
shard_states.pop(fqn)
materialize_state = materialized_states[state]
# for not shared parameter, we create it directly
else:
materialize_state = create_and_sync_state(fqn, state, is_param)
if is_param:
sub_mod._parameters[name] = materialize_state
else:
sub_mod._buffers[name] = materialize_state
if recurse:
for module in sub_mod.children():
init_fn(module, recurse=True)
# for debug
# if len(shard_states) == 0: print("clear")
return sub_mod
return init_fn
def fsdp_version(model):
if isinstance(model, FSDP):
return 1
elif isinstance(model, FSDPModule):
return 2
else:
return 0
def get_fsdp_state_ctx(model, state_type, state_cfg, optim_cfg):
if fsdp_version(model) == 1:
return FSDP.state_dict_type(model, state_type, state_cfg, optim_cfg)
else:
return nullcontext()
def get_fsdp_full_state_dict(model: torch.nn.Module, offload_to_cpu: bool = True, rank0_only: bool = True):
"""
Get the full state dict from an FSDP model.
Args:
model (torch.nn.Module): The FSDP model to get state dict from
offload_to_cpu (bool, optional): Whether to offload the state dict to CPU. Defaults to True.
rank0_only (bool, optional): Whether to only get state dict on rank 0. Defaults to True.
Returns:
dict: The full state dict of the model
Raises:
NotImplementedError: If the FSDP version is unknown
"""
if fsdp_version(model) == 1:
from torch.distributed.fsdp import FullStateDictConfig, StateDictType
state_dict_config = FullStateDictConfig(offload_to_cpu=offload_to_cpu, rank0_only=rank0_only)
with get_fsdp_state_ctx(
model, state_type=StateDictType.FULL_STATE_DICT, state_cfg=state_dict_config, optim_cfg=None
):
state_dict = model.state_dict()
return state_dict
elif fsdp_version(model) == 2 or fsdp_version(model) == 0:
from torch.distributed.checkpoint.state_dict import StateDictOptions, get_model_state_dict
state_dict_config = StateDictOptions(
full_state_dict=True, cpu_offload=offload_to_cpu, broadcast_from_rank0=not rank0_only
)
state_dict = get_model_state_dict(model, options=state_dict_config)
return state_dict
else:
raise NotImplementedError(f"Unknown FSDP version {fsdp_version}")
def fsdp2_load_full_state_dict(model: torch.nn.Module, full_state: dict, device_mesh=None, cpu_offload=None):
"""
Loads the full state dict (could be only on rank 0) into the sharded model. This is done by broadcasting the
parameters from rank 0 to all other ranks. This function modifies the model in-place.
Args:
model (`torch.nn.Module`): The model to load the state dict into
full_state (`dict`): The full state dict to load, can only be on rank 0
"""
if version.parse(torch.__version__) >= version.parse("2.7.0"):
from torch.distributed.checkpoint.state_dict import StateDictOptions, set_model_state_dict
else:
# official torch 2.6.0 set_model_state_dict API leads to OOM
# use torch 2.7.0 copy from verl/third_party/torch/distributed/checkpoint
from verl.third_party.torch.distributed.checkpoint.state_dict import StateDictOptions, set_model_state_dict
# To broadcast, it needs to be instantiated in the GPU.
if dist.get_rank() == 0:
model = model.to(device=get_device_id(), non_blocking=True)
else:
model = model.to_empty(device=get_device_id())
cpu_offload = cpu_offload is not None
options = StateDictOptions(full_state_dict=True, cpu_offload=cpu_offload, broadcast_from_rank0=True)
set_model_state_dict(model, full_state, options=options)
# rotary_emb is not in state_dict, so we need to broadcast it manually
# Sort by name to ensure deterministic order across ranks. FSDP2 can return
# named_buffers() in different order on different ranks. Gemma4 has heterogeneous
# rotary embedding buffers (256 vs 128 elements) so mismatched order = size
# mismatch on the same broadcast collective = NCCL deadlock.
bufs = sorted(model.named_buffers(), key=lambda x: x[0])
for name, buf in bufs:
dist.broadcast(buf, src=0)
if cpu_offload:
offload_fsdp2_model_to_cpu(model, empty_cache=False)
for buf in model.buffers():
buf.data = buf.data.to(get_device_id())
@contextmanager
def maybe_patch_fsdp_module(model):
if fully_shard_module is None:
yield
return
orig_fsdp_module = fully_shard_module.FSDPModule
class FSDPModuleABC(ABC, orig_fsdp_module):
pass
try:
if isinstance(model, ABC):
fully_shard_module.FSDPModule = FSDPModuleABC
yield
finally:
fully_shard_module.FSDPModule = orig_fsdp_module
def _select_fsdp2_wrap_targets(model, fsdp_transformer_layer_cls_to_wrap):
"""Select modules to wrap individually with fully_shard in FSDP2.
Matches transformer layers by class name, and embed_tokens/lm_head by name
(with isinstance fallback). Name-based matching is needed because peft wraps
embed_tokens in ModulesToSaveWrapper, breaking isinstance(module, nn.Embedding).
When tie_word_embeddings is True, embed_tokens and lm_head share weights and
must not be wrapped separately.
"""
_tie = getattr(model.config, "tie_word_embeddings", False)
_wrap_by_name = set() if _tie else {"embed_tokens", "lm_head"}
modules = []
for name, module in model.named_modules():
leaf_name = name.rsplit(".", 1)[-1] if "." in name else name
if (
module.__class__.__name__ in fsdp_transformer_layer_cls_to_wrap
or (isinstance(module, nn.Embedding) and not _tie)
or (leaf_name in _wrap_by_name and hasattr(module, "weight"))
):
modules.append(module)
return modules
def apply_fsdp2(model, fsdp_kwargs, config):
"""model: AutoModelForCausalLM"""
assert CPUOffloadPolicy is not None, "PyTorch version >= 2.4 is required for using fully_shard API (FSDP2)"
default_transformer_cls_names_to_wrap = getattr(model, "_no_split_modules", None)
fsdp_transformer_layer_cls_to_wrap = config.get("wrap_policy", {}).get(
"transformer_layer_cls_to_wrap", default_transformer_cls_names_to_wrap
)
if isinstance(fsdp_transformer_layer_cls_to_wrap, str):
fsdp_transformer_layer_cls_to_wrap = [fsdp_transformer_layer_cls_to_wrap]
if isinstance(fsdp_transformer_layer_cls_to_wrap, set):
fsdp_transformer_layer_cls_to_wrap = list(fsdp_transformer_layer_cls_to_wrap)
assert len(fsdp_transformer_layer_cls_to_wrap) > 0 and fsdp_transformer_layer_cls_to_wrap[0] is not None
modules = _select_fsdp2_wrap_targets(model, fsdp_transformer_layer_cls_to_wrap)
for idx, module in enumerate(modules):
# if torch.distributed.is_initialized() and torch.distributed.get_rank() == 0:
# print(f"wrap module {module.__class__.__name__}")
with maybe_patch_fsdp_module(module):
fully_shard(module, **fsdp_kwargs)
# if torch.distributed.is_initialized() and torch.distributed.get_rank() == 0:
# print(f"wrap module {model.__class__.__name__}")
with maybe_patch_fsdp_module(model):
fully_shard(model, **fsdp_kwargs) # fsdp2 will not reshard_after_forward for root module
# Honor `forward_prefetch` config to match the FSDP1 path. Depth=1 mirrors
# PyTorch FSDP1's hardcoded `forward_prefetch_limit=1`. Static-graph models
# only (see PyTorch FSDP1's docstring on `forward_prefetch`).
# `set_modules_to_forward_prefetch` was introduced in PyTorch 2.5; guard with
# `hasattr` so users on PyTorch 2.4 silently fall back to the no-prefetch
# behavior (same as before this PR — no regression).
if config.get("forward_prefetch", False):
fsdp_modules = [m for m in modules if isinstance(m, FSDPModule)]
for i, m in enumerate(fsdp_modules):
next_targets = fsdp_modules[i + 1 : i + 2] # depth=1, mirrors FSDP1's forward_prefetch_limit=1
if next_targets and hasattr(m, "set_modules_to_forward_prefetch"):
m.set_modules_to_forward_prefetch(next_targets)
def get_shard_placement_fn(fsdp_size):
"""Choose the dimension that can divide fsdp_size to avoid padding"""
def shard_placement_fn(param):
shape = list(param.shape)
for i in range(len(shape)):
if shape[i] % fsdp_size == 0:
return Shard(i)
return Shard(0)
return shard_placement_fn
def fsdp2_clip_grad_norm_(parameters, max_norm, norm_type=2.0, error_if_nonfinite=False, foreach=None):
"""torch.nn.utils.clip_grad_norm_ cann't run on cpu parameter DTensor"""
from torch.nn.utils.clip_grad import _clip_grads_with_norm_, _get_total_norm
if isinstance(parameters, torch.Tensor):
parameters = [parameters]
else:
# prevent generators from being exhausted
parameters = list(parameters)
grads = [p.grad for p in parameters if p.grad is not None]
total_norm = _get_total_norm(grads, norm_type, error_if_nonfinite, foreach)
total_norm = total_norm.to(get_device_id(), non_blocking=True)
_clip_grads_with_norm_(parameters, max_norm, total_norm, foreach)
return total_norm
def layered_summon_lora_params(fsdp_module) -> OrderedDict:
"""Collect LoRA params one FSDP unit at a time to keep peak GPU memory low.
Iterates every FSDP unit (parent before child via named_modules order) and
summons each one individually. Works for any wrap granularity (layer, MLP,
expert) — including MoE models where wrap typically lands at
``layers.<i>.mlp`` rather than the transformer-layer level.
Safe with nested units: ``submodule.state_dict()`` returns gathered tensors
for the unit being summoned but only sharded tensors for nested children.
Sharded entries collected first get overwritten when the child unit is
summoned later, so every LoRA tensor is ga 10BC8 thered exactly once.
"""
lora_params = OrderedDict()
peft_model = getattr(fsdp_module, "_fsdp_wrapped_module", fsdp_module)
for name, submodule in fsdp_module.named_modules():
if name == "":
# Skip root: full summon defeats the purpose.
continue
if fsdp_version(submodule) == 0:
continue
# Strip every ``_fsdp_wrapped_module.`` segment to match the names
# downstream consumers (vllm LoRA loader, peft state_dict) expect.
clean_prefix = name.replace("_fsdp_wrapped_module.", "")
if clean_prefix.endswith(".model") or clean_prefix.endswith(".layers"):
continue
# FSDP1 needs the explicit summon context; FSDP2 ``DTensor`` params
# all-gather on demand via ``param.full_tensor()``, so no context.
is_fsdp1 = fsdp_version(submodule) == 1
# Exclude nested FSDP children from both the pre-check and the state_dict so
# their params are not gathered here and again when their own unit is visited.
nested_fsdp_names = {n for n, m in submodule.named_modules() if n != "" and fsdp_version(m) > 0}
if not any(
"lora_" in n
for n, _ in submodule.named_parameters()
if not any(n.startswith(f"{nn}.") for nn in nested_fsdp_names)
):
continue
if is_fsdp1:
submodule._is_root = True
summon_ctx = FSDP.summon_full_params(submodule, writeback=False) if is_fsdp1 else nullcontext()
with summon_ctx:
sub_state_dict = {
n: p
for n, p in submodule.named_parameters()
if not any(n.startswith(f"{nn}.") for nn in nested_fsdp_names)
}
sub_lora_params = get_peft_model_state_dict(peft_model, state_dict=sub_state_dict)
if not sub_lora_params:
continue
sub_lora_params = {
f"{clean_prefix}.{key}": (
param.full_tensor().detach().cpu() if hasattr(param, "full_tensor") else param.detach().cpu()
)
for key, param in sub_lora_params.items()
}
lora_params.update(sub_lora_params)
if is_fsdp1:
submodule._is_root = False
get_torch_device().empty_cache()
return lora_params
def collect_lora_params(module: FSDP, layered_summon: bool, base_sync_done: bool) -> OrderedDict:
"""
collect lora params or full params if base model is not ready in vllm
work with if isinstance(self.module._fsdp_wrapped_module, PeftModel)
"""
from peft.utils.save_and_load import get_peft_model_state_dict
lora_params = OrderedDict()
peft_model = getattr(module, "_fsdp_wrapped_module", module)
if fsdp_version(module) > 0:
if layered_summon:
if not base_sync_done:
raise ValueError(
"To use layered_summon, you must make sure base-model is preloaded in vllm, e.g. let "
"rollout.load_format=safetensors"
)
lora_params = layered_summon_lora_params(module)
if not lora_params:
import logging
logging.getLogger(__name__).warning("layered_summon returned empty, falling back to full summon")
# FSDP2 ``DTensor`` params all-gather via ``param.full_tensor()``;
# only FSDP1 needs the explicit summon context.
is_fsdp1 = fsdp_version(module) == 1
summon_ctx = (
FSDP.summon_full_params(module, writeback=False, offload_to_cpu=True) if is_fsdp1 else nullcontext()
)
with summon_ctx:
lora_params = get_peft_model_state_dict(peft_model)
lora_params = {
name: param.full_tensor().detach().cpu()
if hasattr(param, "full_tensor")
else param.detach().cpu()
for name, param in lora_params.items()
}
get_torch_device().empty_cache()
else:
with FSDP.summon_full_params(module, writeback=False):
if base_sync_done:
lora_params = get_peft_model_state_dict(peft_model)
lora_params = {
name: param.full_tensor().detach().cpu()
if hasattr(param, "full_tensor")
else param.detach().cpu()
for name, param in lora_params.items()
}
else:
model = peft_model.base_model.model
orig_dev = "cpu" if "cpu" in str(next(model.parameters()).device) else get_device_name()
model = model.to("cpu")
for name, param in model.state_dict().items():
if any(x in name for x in ["_flat_param", "lora_"]):
continue
name = name.replace("_fsdp_wrapped_module.", "").replace(".base_layer", "")
lora_params[name] = (
param.full_tensor().detach().cpu()
if hasattr(param, "full_tensor")
else param.detach().cpu()
)
model = model.to(orig_dev)
get_torch_device().empty_cache()
else:
if base_sync_done:
lora_params = get_peft_model_state_dict(peft_model)
else:
model = peft_model.base_model.model
orig_dev = "cpu" if "cpu" in str(next(model.parameters()).device) else get_device_name()
model = model.to("cpu")
for name, param in model.state_dict().items():
if any(x in name for x in ["_flat_param", "lora_"]):
continue
name = name.replace("_fsdp_wrapped_module.", "").replace(".base_layer", "")
lora_params[name] = param.detach().cpu()
model = model.to(orig_dev)
return lora_params
def replace_lora_wrapper(k, peft_config):
"""Replace LoRA parameter keys with base layer equivalents.
Transforms LoRA parameter names to their corresponding base layer
names for proper weight loading in vLLM when base model sync is not done.
Args:
k (str): Original parameter key name.
Returns:
str: Transformed parameter key for base layer.
"""
stacked_params = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
if k.endswith(".weight"):
module_k = k[: -len(".weight")]
if check_exclude_modules(peft_config, module_k):
return k
elif any([module_k.endswith(s) for s in stacked_params]) or check_target_modules(peft_config, module_k):
return f"{module_k}.base_layer.weight"
if k.endswith(".bias"):
module_k = k[: -len(".bias")]
if check_exclude_modules(peft_config, module_k):
return k
elif any([module_k.endswith(s) for s in stacked_params]) or check_target_modules(peft_config, module_k):
return f"{module_k}.base_layer.bias"
return k
def set_reshard_after_forward(module: FSDPModule, reshard_after_forward: bool, recurse: bool = True) -> None:
"""
Sets if the module should reshard parameters after forward. This can be
used to change the ``reshard_after_forward`` FSDP arg at runtime. For
example, this can be used to set the FSDP root module's value to
``True`` (since it is otherwise specially set to ``False``), or it can
set an FSDP module's value to ``False`` for running evals and set back
to ``True`` for training.
Args:
reshard_after_forward (bool): Whether to reshard parameters after
forward.
recurse (bool): Whether to set for all FSDP submodules or just the
passed-in module.
---
Copied from https://github.com/pytorch/pytorch/blob/main/torch/distributed/fsdp/_fully_shard/_fully_shard.py to
address the absence of the set_reshard_after_forward function in torch versions earlier than 2.8.0.
"""
if not isinstance(reshard_after_forward, bool):
raise ValueError(f"reshard_after_forward should be a bool, got {type(reshard_after_forward)}")
self_module = cast(nn.Module, module)
modules = list(self_module.modules()) if recurse else [self_module]
for module in modules:
if isinstance(module, FSDPModule):
state = module._get_fsdp_state()
state._auto_reshard_after_forward = False
if fsdp_param_group := state._fsdp_param_group:
fsdp_param_group.post_forward_mesh_info = _get_post_forward_mesh_info(
reshard_after_forward, fsdp_param_group.mesh_info
)
def normalize_peft_param_name(params: dict) -> dict:
"""
Converts peft model parameter name to base parameter name
For example,
base_model.model.model.embed_tokens.weight -> model.embed_tokens.weight
base_model.model.model.layers.0.self_attn.q_proj.base_layer.weight -> model.layers.0.self_attn.q_proj.weight
and remove params such as base_model.model.model.layers.0.self_attn.q_proj.lora_A.default.weight,
base_model.model.model.layers.0.self_attn.q_proj.lora_B.default.weight
"""
def _normalize_peft_name(name: str) -> str:
return name.replace("base_model.model.", "").replace("base_model.", "").replace(".base_layer", "")
def _is_lora_key(name: str) -> bool:
# catch typical PEFT keys
return ("lora_" in name) or (".adapter_" in name)
params = [(_normalize_peft_name(k), v) for k, v in params.items()]
# strip any residual LoRA tensors
params = {k: v for k, v in params if not _is_lora_key(k)}
return params
def _merge_or_unmerge_lora_(module, merge: bool):
"""Merge or unmerge LoRA adapters in a module.
Args:
module: The module containing LoRA layers
merge: If True, merge LoRA into base model; if False, unmerge LoRA
"""
from peft.tuners.lora import LoraLayer
with torch.no_grad():
for m in module.modules():
if isinstance(m, LoraLayer):
is_merged = getattr(m, "merged", False)
if merge and not is_merged:
m.merge()
elif (not merge) and is_merged:
m.unmerge()
# merged_adapters
def _clean_merged_lora_(module):
"""Cleans the merged lora adapters"""
from peft.tuners.lora import LoraLayer
with torch.no_grad():
for m in module.modules():
if isinstance(m, LoraLayer):
merged_adapters = getattr(m, "merged_adapters", False)
if merged_adapters:
m.merged_adapters = []
def fsdp_merge_unmerge(module: nn.Module, do_merge: bool):
"""Merge or unmerge LoRA adapters in FSDP module.
For FSDP (v1), it gathers all model parameters to each device, which may cause OOM.
For FSDP2, it gathers model parameters layer-by-layer to reduce memory footprint.
Args:
module: The FSDP module to merge/unmerge LoRA adapters
do_merge: If True, merge LoRA into base model; if False, unmerge LoRA
"""
version = fsdp_version(module)
assert version in [1, 2], f"fsdp_merge_unmerge requires FSDP module, got version {version}"
if version == 1:
# Unshard → merge → Reshard
with FSDP.summon_full_params(module, writeback=True, with_grads=False):
_merge_or_unmerge_lora_(module, merge=do_merge)
else:
# FSDP2: Unshard → merge → Reshard layer-by-layer
for name, submodule in module.named_modules():
if isinstance(submodule, FSDPModule) and name != "": # skip root model
with FSDP.summon_full_params(submodule, writeback=True, with_grads=False):
_merge_or_unmerge_lora_(submodule, merge=do_merge)
def collect_merged_lora_params(module: nn.Module) -> OrderedDict:
"""Merge LoRA into base weights and extract full state dict with HF key names.
For rollout backends (e.g. SGLang) whose load_weights() expects standard
HuggingFace parameter names and handles QKV/gate_up fusion internally.
Sending LoRA delta keys to these backends fails with KeyError.
This function:
1. Merges LoRA adapters into base weights (layer-by-layer for FSDP2)
2. Extracts the full merged state dict with clean HF key names
3. Unmerges LoRA adapters to restore training state
For FSDP2, extraction is done layer-by-layer to avoid OOM from
all-gathering the entire model at once.
Args:
module: The FSDP-wrapped PeftModel to extract merged weights from.
Returns:
OrderedDict mapping HF parameter names to CPU tensors.
"""
ver = fsdp_version(module)
assert ver in [1, 2], f"collect_merged_lora_params requires FSDP module, got version {ver}"
merged_params = OrderedDict()
peft_model = getattr(module, "_fsdp_wrapped_module", module)
from peft.tuners.lora import LoraLayer
def _backup_base_weights(mod):
"""Clone base weights of LoRA target modules before merge."""
backups = {}
for mname, m in mod.named_modules():
if isinstance(m, LoraLayer):
base = m.get_base_layer()
backups[mname] = base.weight.data.clone()
return backups
def _restore_base_weights(mod, backups):
"""Restore base weights from backup, avoiding merge/unmerge drift."""
for mname, m in mod.named_modules():
if isinstance(m, LoraLayer) and mname in backups:
base = m.get_base_layer()
base.weight.data.copy_(backups[mname])
_clean_merged_lora_(mod)
def _clean_key(key):
key = key.replace("_fsdp_wrapped_module.", "")
key = key.replace("base_model.model.", "")
key = key.replace(".base_layer", "")
return key
if ver == 1:
with FSDP.summon_full_params(module, writeback=True, with_grads=False):
backups = _backup_base_weights(module)
_merge_or_unmerge_lora_(module, merge=True)
model = peft_model.base_model.model
for name, param in model.state_dict().items():
if any(x in name for x in ["_flat_param", "lora_"]):
continue
name = name.replace("_fsdp_wrapped_module.", "").replace(".base_layer", "")
merged_params[name] = (
param.full_tensor().detach().cpu() if hasattr(param, "full_tensor") else param.detach().cpu()
)
_restore_base_weights(module, backups)
get_torch_device().empty_cache()
else:
# FSDP2: backup sharded weights, merge per-leaf, extract via full_tensor(), restore.
# We use backup_base_model_weights (which works with DTensor shards) instead of
# extracting inside summon_full_params, because submodule.state_dict() inside summon
# can return local shards instead of full tensors for some parameters.
base_weights_backup = backup_base_model_weights(module)
fsdp_merge_unmerge(module, do_merge=True)
for pname, param in module.named_parameters():
if any(x in pname for x in ["_flat_param", "lora_"]):
0