From 9dc45bd56171c0e0053718e230887fa8827ffc35 Mon Sep 17 00:00:00 2001 From: Mark Colley <39366189+M-Colley@users.noreply.github.com> Date: Sat, 28 Nov 2026 10:16:40 +0000 Subject: [PATCH] Fix LuminaNextDiT2DModel gradient checkpointing for diffusers >= 0.31 Support both the (enable, gradient_checkpointing_func) signature and the legacy (module, value) signature in LuminaNextDiT2DModel._set_gradient_checkpointing. Fixes #321. Signed-off-by: Mark Colley <39366189+M-Colley@users.noreply.github.com> --- .../basemodel/internvla_n1/nextdit_traj.py | 28 +- .../test_nextdit_gradient_checkpointing.py | 305 ++++++++++++++++++ 2 files changed, 328 insertions(+), 5 deletions(-) create mode 100644 tests/unit_test/test_nextdit_gradient_checkpointing.py diff --git a/internnav/model/basemodel/internvla_n1/nextdit_traj.py b/internnav/model/basemodel/internvla_n1/nextdit_traj.py index 1c18a63f..1d33d5d1 100644 --- a/internnav/model/basemodel/internvla_n1/nextdit_traj.py +++ b/internnav/model/basemodel/internvla_n1/nextdit_traj.py @@ -255,6 +255,7 @@ def __init__( self.head_dim = hidden_size // num_attention_heads self.scaling_factor = scaling_factor self.gradient_checkpointing = False + self._gradient_checkpointing_func = None self.caption_projection = PixArtAlphaTextProjection(in_features=cross_attention_dim, hidden_size=hidden_size) self.patch_embedder = LuminaPatchEmbed( @@ -292,9 +293,23 @@ def __init__( assert (hidden_size // num_attention_heads) % 4 == 0, "2d rope needs head dim to be divisible by 4" - def _set_gradient_checkpointing(self, module, value=False): - if hasattr(module, "gradient_checkpointing"): + def _set_gradient_checkpointing(self, module=None, value=False, enable=None, gradient_checkpointing_func=None): + if enable is not None: + self.gradient_checkpointing = enable + if enable and gradient_checkpointing_func is not None: + self._gradient_checkpointing_func = gradient_checkpointing_func + elif not enable: + self._gradient_checkpointing_func = None + elif isinstance(module, bool): + self.gradient_checkpointing = module + if module and callable(value): + self._gradient_checkpointing_func = value + elif not module: + self._gradient_checkpointing_func = None + elif module is not None and hasattr(module, "gradient_checkpointing"): module.gradient_checkpointing = value + if not value and hasattr(module, "_gradient_checkpointing_func"): + module._gradient_checkpointing_func = None def forward( self, @@ -336,8 +351,7 @@ def custom_forward(*inputs): return custom_forward - ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {} - hidden_states = torch.utils.checkpoint.checkpoint( + ckpt_args = ( create_custom_forward(layer), hidden_states, mask, @@ -346,8 +360,12 @@ def custom_forward(*inputs): encoder_mask, temb, cross_attention_kwargs, - **ckpt_kwargs, ) + if self._gradient_checkpointing_func is not None: + hidden_states = self._gradient_checkpointing_func(*ckpt_args) + else: + ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {} + hidden_states = torch.utils.checkpoint.checkpoint(*ckpt_args, **ckpt_kwargs) else: hidden_states = layer( hidden_states, diff --git a/tests/unit_test/test_nextdit_gradient_checkpointing.py b/tests/unit_test/test_nextdit_gradient_checkpointing.py new file mode 100644 index 00000000..af23d1b5 --- /dev/null +++ b/tests/unit_test/test_nextdit_gradient_checkpointing.py @@ -0,0 +1,305 @@ +import importlib +import sys +import types +from contextlib import contextmanager +from unittest.mock import patch + + +def _has_real_runtime(): + for module_name in ("diffusers", "torch", "transformers"): + try: + importlib.import_module(module_name) + except Exception: + return False + return True + + +class _FakeTensor: + def __init__(self, shape=(1, 4, 8), dtype=None, device="cpu"): + self.shape = shape + self.dtype = dtype + self.device = device + + def tanh(self): + return self + + def view(self, *args): + return self + + def flatten(self, *args): + return self + + def unsqueeze(self, *args): + return self + + def bool(self): + return self + + def __add__(self, other): + return self + + def __radd__(self, other): + return self + + def __mul__(self, other): + return self + + def __rmul__(self, other): + return self + + +class _FakeModule: + def __init__(self, *args, **kwargs): + self.training = True + + def train(self, mode=True): + self.training = mode + return self + + def eval(self): + return self.train(False) + + def __call__(self, *args, **kwargs): + return self.forward(*args, **kwargs) + + def forward(self, *args, **kwargs): + if args: + return args[0] + return _FakeTensor() + + +class _FakeCheckpoint: + @staticmethod + def checkpoint(func, *args, **kwargs): + return func(*args) + + +class _FakeModelMixin(_FakeModule): + def enable_gradient_checkpointing(self, gradient_checkpointing_func=None): + if gradient_checkpointing_func is None: + + def _default_gc_func(module, *args): + return module(*args) + + gradient_checkpointing_func = _default_gc_func + self._set_gradient_checkpointing( + enable=True, + gradient_checkpointing_func=gradient_checkpointing_func, + ) + + def disable_gradient_checkpointing(self): + self._set_gradient_checkpointing(enable=False) + + +class _FakeAttention(_FakeModule): + def __init__(self, *args, **kwargs): + super().__init__() + self.to_out = [_FakeModule()] + + +class _FakeRMSNormZero(_FakeModule): + def forward(self, *args, **kwargs): + tensor = _FakeTensor() + return tensor, tensor, tensor, tensor + + +class _FakePretrainedConfig: + def __init__(self, **kwargs): + for key, value in kwargs.items(): + setattr(self, key, value) + + +class _FakePreTrainedModel(_FakeModule): + def __init__(self, config): + super().__init__() + self.config = config + + +def _build_stub_modules(): + nn_mod = types.ModuleType("torch.nn") + nn_mod.Module = _FakeModule + nn_mod.ModuleList = list + nn_mod.Identity = _FakeModule + nn_mod.Parameter = _FakeTensor + + torch_mod = types.ModuleType("torch") + torch_mod.Tensor = _FakeTensor + torch_mod.int32 = "int32" + torch_mod.nn = nn_mod + torch_mod.utils = types.SimpleNamespace(checkpoint=_FakeCheckpoint) + torch_mod.zeros = lambda shape: _FakeTensor(shape) + torch_mod.ones = lambda *args, **kwargs: _FakeTensor() + + diffusers_mod = types.ModuleType("diffusers") + diffusers_cfg_mod = types.ModuleType("diffusers.configuration_utils") + diffusers_cfg_mod.ConfigMixin = object + diffusers_cfg_mod.register_to_config = lambda init: init + + diffusers_models_mod = types.ModuleType("diffusers.models") + diffusers_attn_mod = types.ModuleType("diffusers.models.attention") + diffusers_attn_mod.LuminaFeedForward = _FakeModule + diffusers_attn_proc_mod = types.ModuleType("diffusers.models.attention_processor") + diffusers_attn_proc_mod.Attention = _FakeAttention + diffusers_attn_proc_mod.LuminaAttnProcessor2_0 = _FakeModule + diffusers_emb_mod = types.ModuleType("diffusers.models.embeddings") + diffusers_emb_mod.LuminaCombinedTimestepCaptionEmbedding = _FakeModule + diffusers_emb_mod.LuminaPatchEmbed = _FakeModule + diffusers_emb_mod.PixArtAlphaTextProjection = _FakeModule + diffusers_emb_mod.get_2d_rotary_pos_embed_lumina = lambda *args, **kwargs: _FakeTensor() + diffusers_out_mod = types.ModuleType("diffusers.models.modeling_outputs") + diffusers_out_mod.Transformer2DModelOutput = lambda sample: types.SimpleNamespace(sample=sample) + diffusers_utils_model_mod = types.ModuleType("diffusers.models.modeling_utils") + diffusers_utils_model_mod.ModelMixin = _FakeModelMixin + diffusers_norm_mod = types.ModuleType("diffusers.models.normalization") + diffusers_norm_mod.LuminaLayerNormContinuous = _FakeModule + diffusers_norm_mod.LuminaRMSNormZero = _FakeRMSNormZero + diffusers_norm_mod.RMSNorm = _FakeModule + diffusers_utils_mod = types.ModuleType("diffusers.utils") + diffusers_utils_mod.is_torch_version = lambda *args, **kwargs: True + diffusers_utils_mod.logging = types.SimpleNamespace(get_logger=lambda name: object()) + + transformers_mod = types.ModuleType("transformers") + transformers_mod.PretrainedConfig = _FakePretrainedConfig + transformers_mod.PreTrainedModel = _FakePreTrainedModel + + return { + "torch": torch_mod, + "torch.nn": nn_mod, + "diffusers": diffusers_mod, + "diffusers.configuration_utils": diffusers_cfg_mod, + "diffusers.models": diffusers_models_mod, + "diffusers.models.attention": diffusers_attn_mod, + "diffusers.models.attention_processor": diffusers_attn_proc_mod, + "diffusers.models.embeddings": diffusers_emb_mod, + "diffusers.models.modeling_outputs": diffusers_out_mod, + "diffusers.models.modeling_utils": diffusers_utils_model_mod, + "diffusers.models.normalization": diffusers_norm_mod, + "diffusers.utils": diffusers_utils_mod, + "transformers": transformers_mod, + } + + +@contextmanager +def _load_nextdit_modules(): + if _has_real_runtime(): + nextdit_traj = importlib.import_module("internnav.model.basemodel.internvla_n1.nextdit_traj") + nextdit_crossattn_traj = importlib.import_module( + "internnav.model.basemodel.internvla_n1.nextdit_crossattn_traj" + ) + yield nextdit_traj, nextdit_crossattn_traj + return + + stubs = _build_stub_modules() + mod_names = [ + "internnav.model.basemodel.internvla_n1.nextdit_traj", + "internnav.model.basemodel.internvla_n1.nextdit_crossattn_traj", + ] + saved_modules = {name: sys.modules.pop(name, None) for name in mod_names} + try: + with patch.dict(sys.modules, stubs): + nextdit_traj = importlib.import_module(mod_names[0]) + nextdit_crossattn_traj = importlib.import_module(mod_names[1]) + yield nextdit_traj, nextdit_crossattn_traj + finally: + for name, mod in saved_modules.items(): + sys.modules.pop(name, None) + if mod is not None: + sys.modules[name] = mod + + +def _make_small_lumina_model(nextdit_traj): + return nextdit_traj.LuminaNextDiT2DModel( + sample_size=8, + patch_size=1, + in_channels=8, + hidden_size=32, + num_layers=1, + num_attention_heads=4, + num_kv_heads=4, + multiple_of=8, + learn_sigma=False, + cross_attention_dim=16, + ) + + +def test_nextdit_crossattn_init_with_gradient_checkpointing(): + with _load_nextdit_modules() as (_, nextdit_crossattn_traj): + config = nextdit_crossattn_traj.NextDiTCrossAttnConfig(n_layers=1, _gradient_checkpointing=True) + model = nextdit_crossattn_traj.NextDiTCrossAttn(config) + assert model.model.gradient_checkpointing is True + + +def test_lumina_enable_and_disable_gradient_checkpointing(): + with _load_nextdit_modules() as (nextdit_traj, _): + model = _make_small_lumina_model(nextdit_traj) + assert model.gradient_checkpointing is False + + def custom_gc(module, *args): + return module(*args) + + model.enable_gradient_checkpointing(gradient_checkpointing_func=custom_gc) + assert model.gradient_checkpointing is True + assert model._gradient_checkpointing_func is custom_gc + + model.disable_gradient_checkpointing() + assert model.gradient_checkpointing is False + assert model._gradient_checkpointing_func is None + + +def test_lumina_set_gradient_checkpointing_legacy_and_positional_signatures(): + with _load_nextdit_modules() as (nextdit_traj, _): + model = _make_small_lumina_model(nextdit_traj) + + def custom_gc(module, *args): + return module(*args) + + model._set_gradient_checkpointing(True, custom_gc) + assert model.gradient_checkpointing is True + assert model._gradient_checkpointing_func is custom_gc + + model._set_gradient_checkpointing(model, value=False) + assert model.gradient_checkpointing is False + assert model._gradient_checkpointing_func is None + + model._set_gradient_checkpointing(model, value=True) + assert model.gradient_checkpointing is True + + +def test_lumina_forward_uses_gradient_checkpointing_only_in_training(): + with _load_nextdit_modules() as (nextdit_traj, _): + model = _make_small_lumina_model(nextdit_traj) + gc_calls = [] + + def custom_gc(module, *args): + gc_calls.append(len(args)) + return module(*args) + + model.enable_gradient_checkpointing(gradient_checkpointing_func=custom_gc) + + torch_mod = sys.modules["torch"] + hidden_states = torch_mod.zeros((1, 4, 32)) + timestep = torch_mod.zeros((1,)) + encoder_hidden_states = torch_mod.zeros((1, 2, 16)) + encoder_mask = torch_mod.ones((1, 2)) + + model.eval() + model( + hidden_states=hidden_states, + timestep=timestep, + encoder_hidden_states=encoder_hidden_states, + encoder_mask=encoder_mask, + image_rotary_emb=None, + cross_attention_kwargs={}, + ) + assert gc_calls == [] + + model.train() + model( + hidden_states=hidden_states, + timestep=timestep, + encoder_hidden_states=encoder_hidden_states, + encoder_mask=encoder_mask, + image_rotary_emb=None, + cross_attention_kwargs={}, + ) + assert len(gc_calls) == 1