Repository navigation
[group offloading] Keep buffer values when offloading to disk #15333
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
8824faa
94befe5
61a2a26
ca3c1c5
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -168,6 +168,11 @@ def __init__( | |
| self.tensor_to_key = {tensor: f"tensor_{i}" for i, tensor in enumerate(all_tensors)} | ||
| self.key_to_tensor = {v: k for k, v in self.tensor_to_key.items()} | ||
| self.cpu_param_dict = {} | ||
| # Buffers can be read without calling the forward of the module that owns them (e.g. a pipeline reading a | ||
| # VAE's batch norm running statistics), so they may never be onloaded. Keep their values on the offload | ||
| # device instead of the uninitialized tensors that offloaded parameters get. | ||
| buffers = [buffer for module in self.modules for buffer in module.buffers()] + self.buffers | ||
| self.cpu_buffer_dict = {buffer: buffer.data.to(self.offload_device) for buffer in buffers} | ||
| else: | ||
| self.cpu_param_dict = self._init_cpu_param_dict() | ||
|
|
||
|
|
@@ -313,9 +318,12 @@ def _offload_to_disk(self): | |
| # The group is now considered offloaded to disk for the rest of the session. | ||
| self._is_offloaded_to_disk = True | ||
|
|
||
| # We do this to free up the RAM which is still holding the up tensor data. | ||
| # Free the RAM held by the parameters; they are reloaded from disk on onload. Buffers keep their values. | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is fine as long as buffers don't contribute too much.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Agreed. SD3's |
||
| for tensor_obj in self.tensor_to_key.keys(): | ||
| tensor_obj.data = torch.empty_like(tensor_obj.data, device=self.offload_device) | ||
| if tensor_obj in self.cpu_buffer_dict: | ||
| tensor_obj.data = self.cpu_buffer_dict[tensor_obj] | ||
| else: | ||
| tensor_obj.data = torch.empty_like(tensor_obj.data, device=self.offload_device) | ||
|
|
||
| def _offload_to_memory(self): | ||
| if self.stream is not None: | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -711,3 +711,81 @@ def test_conditional_modules_with_stream(self, offload_type: str): | |
| assert torch.allclose(out_ref_no_opt2, out_no_opt2, atol=1e-5), ( | ||
| f"[{offload_type}] Outputs do not match on third pass (back to no optional_input)." | ||
| ) | ||
|
|
||
|
|
||
| # Model whose batch norm running statistics are read directly, without calling the batch norm's forward, like | ||
| # pipelines reading `vae.bn.running_mean` / `vae.bn.running_var` of `AutoencoderKLFlux2`. | ||
| class DummyModelWithStandaloneBatchNorm(ModelMixin): | ||
| def __init__(self, in_features: int, hidden_features: int, out_features: int, num_layers: int) -> None: | ||
| super().__init__() | ||
|
|
||
| self.linear_1 = torch.nn.Linear(in_features, hidden_features) | ||
| self.blocks = torch.nn.ModuleList( | ||
| [DummyBlock(hidden_features, hidden_features, hidden_features) for _ in range(num_layers)] | ||
| ) | ||
| self.linear_2 = torch.nn.Linear(hidden_features, out_features) | ||
| self.bn = torch.nn.BatchNorm1d(out_features, affine=False, track_running_stats=True) | ||
| self.bn.running_mean.copy_(torch.linspace(-1.0, 1.0, out_features)) | ||
| self.bn.running_var.copy_(torch.linspace(0.5, 2.0, out_features)) | ||
|
|
||
| def forward(self, x: torch.Tensor) -> torch.Tensor: | ||
| x = self.linear_1(x) | ||
| for block in self.blocks: | ||
| x = block(x) | ||
| x = self.linear_2(x) | ||
| # Read the running statistics directly instead of calling `self.bn`, like the FLUX.2 pipelines do. | ||
| mean = self.bn.running_mean.to(x.device, x.dtype) | ||
| var = self.bn.running_var.to(x.device, x.dtype) | ||
| return (x - mean) / torch.sqrt(var + self.bn.eps) | ||
|
|
||
|
|
||
| @require_torch_accelerator | ||
| class TestDirectBufferAccessGroupOffload: | ||
| in_features = 64 | ||
| hidden_features = 256 | ||
| out_features = 64 | ||
| num_layers = 2 | ||
|
|
||
| def teardown_method(self): | ||
| gc.collect() | ||
| backend_empty_cache(torch_device) | ||
|
|
||
| def get_model(self): | ||
| torch.manual_seed(0) | ||
| return DummyModelWithStandaloneBatchNorm( | ||
| self.in_features, self.hidden_features, self.out_features, self.num_layers | ||
| ) | ||
|
|
||
| @pytest.mark.parametrize("offload_type", ["leaf_level", "block_level"]) | ||
| @pytest.mark.parametrize("use_stream", [False, True], ids=["no_stream", "stream"]) | ||
| @pytest.mark.parametrize("offload_to_disk", [False, True], ids=["memory", "disk"]) | ||
| def test_buffers_read_without_forward_keep_their_values( | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should also do an assert on the outputs with and without offloading.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Added. The dummy forward now reads |
||
| self, offload_type: str, use_stream: bool, offload_to_disk: bool, tmp_path | ||
| ): | ||
| """Buffers read directly, without calling the forward of the module that owns them, must hold their real | ||
| values while offloaded, and the outputs must match the model without offloading. | ||
| """ | ||
| if use_stream and torch.device(torch_device).type not in ["cuda", "xpu"]: | ||
| pytest.skip("Test requires a CUDA or XPU device for streams.") | ||
|
|
||
| model_ref = self.get_model().to(torch_device) | ||
| model = self.get_model() | ||
| running_mean = model.bn.running_mean.clone() | ||
| running_var = model.bn.running_var.clone() | ||
|
|
||
| model.enable_group_offload( | ||
| torch_device, | ||
| offload_type=offload_type, | ||
| num_blocks_per_group=1, | ||
| use_stream=use_stream, | ||
| offload_to_disk_path=str(tmp_path) if offload_to_disk else None, | ||
| ) | ||
|
|
||
| x = torch.randn(4, self.in_features).to(torch_device) | ||
| with torch.no_grad(): | ||
| out_ref = model_ref(x) | ||
| for _ in range(2): | ||
| out = model(x) | ||
| assert torch.equal(model.bn.running_mean.cpu(), running_mean) | ||
| assert torch.equal(model.bn.running_var.cpu(), running_var) | ||
| assert torch.allclose(out_ref, out, atol=1e-5), "Outputs do not match with and without offloading." | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
But this does have the risk of pressurizing the memory a little bit right?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, by the buffers' size and nothing else; parameters still get
empty_like. With a 256 MiB parameter + 256 MiB buffer model, RSS after disk offload is 1138 MiB on main vs 1394 MiB here. Buffer bytes of the models I checked (fp32 as built from config; a bf16 load halves SD3'spos_embed, which is in the checkpoint, while the Wan RoPE tables are built at init and stay fp32): FLUX.2 Klein VAE 1 KiB (the threebnbuffers); FLUX.2 Klein, FLUX.1 and Qwen-Image transformers, FLUX.1 and Wan VAEs 0; Wan2.2 transformer 1 MiB (RoPE); SD3 Mediumpos_embed216 MiB (2.8% of its parameters), SD3.5 Large 342 MiB (1.1%).