|
| 1 | +import torch |
| 2 | +from loguru import logger |
| 3 | +from torch.nn.parallel import DistributedDataParallel |
| 4 | + |
| 5 | +from lightx2v_train.runtime.distributed import is_distributed |
| 6 | + |
| 7 | + |
| 8 | +class LightX2VDistributedDataParallel(DistributedDataParallel): |
| 9 | + """DDP wrapper that keeps the denoiser usable as the original transformer. |
| 10 | +
|
| 11 | + LightX2V replaces ``model.transformer`` with this wrapper when data |
| 12 | + parallelism is enabled. The extra forwarding below lets existing model, |
| 13 | + LoRA, checkpoint, and Wan causal-mask code keep calling attributes and |
| 14 | + methods on ``model.transformer`` without having to special-case |
| 15 | + ``DistributedDataParallel.module`` everywhere. |
| 16 | + """ |
| 17 | + |
| 18 | + @property |
| 19 | + def __class__(self): |
| 20 | + # Preserve class-based checks such as isinstance(transformer, CausalWanModel) |
| 21 | + # after the transformer is wrapped by DDP. |
| 22 | + return self.module.__class__ |
| 23 | + |
| 24 | + def __getattr__(self, name): |
| 25 | + try: |
| 26 | + return super().__getattr__(name) |
| 27 | + except AttributeError as error: |
| 28 | + try: |
| 29 | + module = super().__getattr__("module") |
| 30 | + except AttributeError: |
| 31 | + raise error |
| 32 | + # Expose attributes/methods from the wrapped denoiser directly. |
| 33 | + return getattr(module, name) |
| 34 | + |
| 35 | + def __setattr__(self, name, value): |
| 36 | + modules = self.__dict__.get("_modules") |
| 37 | + wrapped = modules.get("module") if modules is not None else None |
| 38 | + if name == "block_mask" and wrapped is not None: |
| 39 | + # Causal Wan stores the attention block mask on the transformer used |
| 40 | + # by forward(), so write this field through to the wrapped module. |
| 41 | + setattr(wrapped, name, value) |
| 42 | + return |
| 43 | + super().__setattr__(name, value) |
| 44 | + |
| 45 | + def state_dict(self, *args, **kwargs): |
| 46 | + # Save plain denoiser keys instead of DDP's "module."-prefixed keys. |
| 47 | + return self.module.state_dict(*args, **kwargs) |
| 48 | + |
| 49 | + def load_state_dict(self, *args, **kwargs): |
| 50 | + # Match the plain state_dict() format used for non-DDP checkpoints. |
| 51 | + return self.module.load_state_dict(*args, **kwargs) |
| 52 | + |
| 53 | + |
| 54 | +def ddp_config(config): |
| 55 | + distributed_config = config.get("distributed", {}) |
| 56 | + config_value = distributed_config.get("dp", {}) |
| 57 | + return config_value or {} |
| 58 | + |
| 59 | + |
| 60 | +def ddp_enabled(config): |
| 61 | + return is_distributed() and ddp_config(config).get("enabled", False) |
| 62 | + |
| 63 | + |
| 64 | +def is_ddp_module(module): |
| 65 | + return isinstance(module, DistributedDataParallel) |
| 66 | + |
| 67 | + |
| 68 | +def unwrap_ddp_module(module): |
| 69 | + while is_ddp_module(module): |
| 70 | + module = module.module |
| 71 | + return module |
| 72 | + |
| 73 | + |
| 74 | +def set_ddp_gradient_sync(module, enabled): |
| 75 | + if is_ddp_module(module): |
| 76 | + module.require_backward_grad_sync = enabled |
| 77 | + |
| 78 | + |
| 79 | +def _ddp_kwargs(config): |
| 80 | + config = ddp_config(config) |
| 81 | + kwargs = { |
| 82 | + "broadcast_buffers": config.get("broadcast_buffers", False), |
| 83 | + "find_unused_parameters": config.get("find_unused_parameters", False), |
| 84 | + "static_graph": config.get("static_graph", False), |
| 85 | + "gradient_as_bucket_view": config.get("gradient_as_bucket_view", False), |
| 86 | + } |
| 87 | + if torch.cuda.is_available(): |
| 88 | + kwargs["device_ids"] = [torch.cuda.current_device()] |
| 89 | + kwargs["output_device"] = torch.cuda.current_device() |
| 90 | + return kwargs |
| 91 | + |
| 92 | + |
| 93 | +def apply_ddp(model, config): |
| 94 | + if not ddp_enabled(config) or is_ddp_module(model.denoiser_module()): |
| 95 | + return model |
| 96 | + |
| 97 | + denoiser = model.denoiser_module() |
| 98 | + |
| 99 | + if not any(param.requires_grad for param in denoiser.parameters()): |
| 100 | + logger.info("DP(DDP) skipped for {} because the denoiser has no trainable parameters.", model.__class__.__name__) |
| 101 | + return model |
| 102 | + |
| 103 | + ddp_kwargs = _ddp_kwargs(config) |
| 104 | + wrapped = LightX2VDistributedDataParallel(denoiser, **ddp_kwargs) |
| 105 | + if getattr(model, "transformer", None) is not denoiser: |
| 106 | + raise RuntimeError(f"{model.__class__.__name__} must store its trainable denoiser in self.transformer to use DP(DDP).") |
| 107 | + model.transformer = wrapped |
| 108 | + logger.info( |
| 109 | + "DP(DDP) transformer wrapped: broadcast_buffers={} find_unused_parameters={} static_graph={}", |
| 110 | + ddp_kwargs["broadcast_buffers"], |
| 111 | + ddp_kwargs["find_unused_parameters"], |
| 112 | + ddp_kwargs["static_graph"], |
| 113 | + ) |
| 114 | + return model |
0 commit comments