huggingface/accelerate · #4524

Compile checkpointed blocks across graph breaks in `compile_regions`

qgallouedec · merged Nov 13, 20262 files · 78 + / 5 −
src/accelerate/utils/other.py26 + / 4 −
@@ -18,6 +18,7 @@ import socket from codecs import encode from collections import OrderedDict+from copy import copy from functools import partial, reduce from types import MethodType from typing import Optional@@ -141,17 +142,38 @@ def compile_regions(module: torch.nn.Module, **compile_kwargs) -> torch.nn.Modul     ```     """ +    def _rebind_module_methods(module, new_module):+        # Shallow copies keep methods and partials bound to the original module.+        # Rebind them so forwards and hooks use the copy's state, including its training flag.+        def rebind(value):+            if isinstance(value, MethodType) and value.__self__ is module:+                return MethodType(value.__func__, new_module)+            if isinstance(value, partial):+                args = tuple(new_module if arg is module else arg for arg in value.args)+                kwargs = {key: new_module if arg is module else arg for key, arg in value.keywords.items()}+                rebound = partial(rebind(value.func), *args, **kwargs)+                rebound.__dict__.update(value.__dict__)+                if hasattr(value, "__wrapped__"):+                    rebound.__wrapped__ = rebind(value.__wrapped__)+                return rebound+            return value++        # Includes the partial `forward` and bound `_old_forward` installed by Accelerate hooks.+        for name, value in list(new_module.__dict__.items()):+            new_module.__dict__[name] = rebind(value)+     def _compile_regions(module: torch.nn.Module, **compile_kwargs) -> torch.nn.Module:         if is_repeated_blocks(module):             new_module = torch.nn.ModuleList()             for submodule in module:-                new_module.append(torch.compile(submodule, **compile_kwargs))+                new_submodule = copy(submodule)+                _rebind_module_methods(submodule, new_submodule)+                new_submodule.compile(**compile_kwargs)+                new_module.append(torch.compile(new_submodule, **compile_kwargs))         elif has_repeated_blocks(module):             new_module = module.__class__.__new__(module.__class__)             new_module.__dict__.update(module.__dict__)-            for name, value in list(new_module.__dict__.items()):-                if hasattr(value, "__func__") and getattr(value, "__self__", None) is module:-                    new_module.__dict__[name] = MethodType(value.__func__, new_module)+            _rebind_module_methods(module, new_module)             new_module._modules = {}             for name, submodule in module.named_children():                 new_module.add_module(name, _compile_regions(submodule, **compile_kwargs))
tests/test_compile.py52 + / 1 −
@@ -17,7 +17,9 @@  import torch from torch.utils.benchmark import Timer+from torch.utils.checkpoint import checkpoint +from accelerate.hooks import ModelHook, add_hook_to_module from accelerate.test_utils import require_huggingface_suite, require_non_cpu, require_non_hpu, slow, torch_device from accelerate.utils import compile_regions, extract_model_from_parallel, release_memory @@ -60,7 +62,8 @@ def test_regions_are_compiled(self):         # Check that the compiled_model.transformer.h[i] and compiled_model.lm_head are compiled separately         assert isinstance(compiled_model.transformer.h[0], torch._dynamo.eval_frame.OptimizedModule)         assert isinstance(compiled_model.lm_head, torch._dynamo.eval_frame.OptimizedModule)-        assert compiled_model.transformer.h[0]._orig_mod is model.transformer.h[0]+        assert compiled_model.transformer.h[0].attn.c_attn.weight is model.transformer.h[0].attn.c_attn.weight+        assert model.transformer.h[0]._compiled_call_impl is None         assert compiled_model.lm_head._orig_mod is model.lm_head      def test_extract_model_keep_torch_compile(self):@@ -157,6 +160,17 @@ def forward(self, x):         return self.linear(x)  +class CheckpointedRegionalCompilationBlock(RegionalCompilationBlock):+    # Same structure as transformers' `GradientCheckpointingLayer`+    def __call__(self, *args, **kwargs):+        return checkpoint(super().__call__, *args, use_reentrant=False, **kwargs)++    def forward(self, x):+        x = self.linear(x)+        torch._dynamo.graph_break()+        return x.sin()++ class RegionalCompilationModel(torch.nn.Module):     def __init__(self):         super().__init__()@@ -207,3 +221,40 @@ def test_no_instance_bound_methods_is_a_no_op(self):          assert not hasattr(model, "trace")         assert compiled_model.trace == ("twin", "OptimizedModule")++    def test_checkpointed_blocks_with_hooks_preserve_eval_state(self):+        class Block(CheckpointedRegionalCompilationBlock):+            def forward(self, x):+                return super().forward(x) * (2 if self.training else 1)++        model, inputs = self._get_model_and_inputs()+        model.blocks = torch.nn.ModuleList([Block(), Block()])+        for block in model.blocks:+            add_hook_to_module(block, ModelHook())+        expected = model.eval()(inputs)+        model.train()+        graphs = []++        def recording_backend(graph_module, example_inputs):+            graphs.append(graph_module)+            return graph_module.forward++        compiled_model = compile_regions(model, backend=recording_backend).eval()+        torch.testing.assert_close(compiled_model(inputs), expected)+        assert graphs++    def test_checkpointed_blocks_are_compiled_across_graph_breaks(self):+        model, inputs = self._get_model_and_inputs()+        model.blocks = torch.nn.ModuleList([CheckpointedRegionalCompilationBlock() for _ in range(2)])+        model, inputs = model.to(torch_device), inputs.to(torch_device)+        graphs = []++        def recording_backend(graph_module, example_inputs):+            graphs.append(graph_module)+            return graph_module.forward++        compiled_model = compile_regions(model, backend=recording_backend)+        output = compiled_model(inputs)++        assert graphs+        torch.testing.assert_close(output, model(inputs))