Skip to content
Merged
Changes from 3 commits
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
9 changes: 9 additions & 0 deletions swift/model/npu_patch/fsdp.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,16 @@ def _cast_module_to_fp32_for_npu_if_needed(module: torch.nn.Module, accelerator:
# entering that path with bf16/fp16 parameters can fail before mixed
# precision policy has a chance to manage runtime compute dtype. Cast early
# while parameters are still on CPU or meta, so only dtype changes here.

# GRPO with vLLM colocate mode may preload the model onto NPU before
# Accelerator.prepare() is called. In that case, casting fp32 on NPU
# would temporarily duplicate the full model (bf16 + fp32), causing OOM.
# We move the model back to CPU first to free NPU memory, then cast.
try:
import torch_npu
module = module.cpu()
torch_npu.npu.synchronize()
torch_npu.npu.empty_cache()
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

It is recommended to only move the module to CPU and clear the NPU cache if the parameters are currently residing on the NPU. This avoids unnecessary synchronization and cache clearing overhead for standard training paths (like SFT or LoRA) where the model is already on the CPU or meta device. It also ensures better compatibility with meta-device initialization, as calling .cpu() on meta-parameters might lead to unexpected behavior depending on the PyTorch version.

Suggested change
import torch_npu
module = module.cpu()
torch_npu.npu.synchronize()
torch_npu.npu.empty_cache()
if param.device.type == 'npu':
import torch_npu
module = module.cpu()
torch_npu.npu.synchronize()
torch_npu.npu.empty_cache()

return module.to(torch.float32)
except Exception as exc:
raise NPUCastError(f'Failed to cast {module.__class__.__name__} to fp32.') from exc
Expand Down
Loading