-
Notifications
You must be signed in to change notification settings - Fork 6k
[refactor] CogVideoX followups + tiled decoding support #9150
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
Merged
Merged
Changes from 5 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
06b1a97
refactor context parallel cache; update torch compile time benchmark
a-r-r-o-w d962677
add tiling support
a-r-r-o-w 2b923a8
make style
a-r-r-o-w 56d7506
Merge branch 'main' into cogvideox-followup
a-r-r-o-w e54db72
remove num_frames % 8 == 0 requirement
a-r-r-o-w 84d6416
update default num_frames to original value
a-r-r-o-w 1ed1cfb
add explanations + refactor
a-r-r-o-w 0094792
update torch compile example
a-r-r-o-w 50fa1d0
update docs
a-r-r-o-w 9de509d
update
a-r-r-o-w 7f63ee2
clean up if-statements
a-r-r-o-w 29f139e
Merge branch 'main' into cogvideox-followup
a-r-r-o-w 76dda5e
address review comments
a-r-r-o-w ea86c32
add test for vae tiling
a-r-r-o-w 878890d
update docs
a-r-r-o-w a40e8d2
update docs
a-r-r-o-w 836f5d0
update docstrings
a-r-r-o-w 661f7b8
add modeling test for cogvideox transformer
a-r-r-o-w 1b6c527
make style
a-r-r-o-w File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -118,36 +118,30 @@ def __init__( | |
self.conv_cache = None | ||
|
||
def fake_context_parallel_forward(self, inputs: torch.Tensor) -> torch.Tensor: | ||
dim = self.temporal_dim | ||
kernel_size = self.time_kernel_size | ||
if kernel_size == 1: | ||
return inputs | ||
|
||
inputs = inputs.transpose(0, dim) | ||
|
||
if self.conv_cache is not None: | ||
inputs = torch.cat([self.conv_cache.transpose(0, dim).to(inputs.device), inputs], dim=0) | ||
else: | ||
inputs = torch.cat([inputs[:1]] * (kernel_size - 1) + [inputs], dim=0) | ||
|
||
inputs = inputs.transpose(0, dim).contiguous() | ||
if kernel_size > 1: | ||
cached_inputs = ( | ||
[self.conv_cache] if self.conv_cache is not None else [inputs[:, :, :1]] * (kernel_size - 1) | ||
) | ||
inputs = torch.cat(cached_inputs + [inputs], dim=2) | ||
a-r-r-o-w marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return inputs | ||
|
||
def _clear_fake_context_parallel_cache(self): | ||
del self.conv_cache | ||
self.conv_cache = None | ||
|
||
def forward(self, inputs: torch.Tensor) -> torch.Tensor: | ||
input_parallel = self.fake_context_parallel_forward(inputs) | ||
inputs = self.fake_context_parallel_forward(inputs) | ||
|
||
self._clear_fake_context_parallel_cache() | ||
self.conv_cache = input_parallel[:, :, -self.time_kernel_size + 1 :].contiguous().detach().clone().cpu() | ||
# Note: we could move these to the cpu for a lower maximum memory usage but its only a few | ||
# hundred megabytes and so let's not do it for now | ||
self.conv_cache = inputs[:, :, -self.time_kernel_size + 1 :].clone() | ||
|
||
padding_2d = (self.width_pad, self.width_pad, self.height_pad, self.height_pad) | ||
input_parallel = F.pad(input_parallel, padding_2d, mode="constant", value=0) | ||
inputs = F.pad(inputs, padding_2d, mode="constant", value=0) | ||
|
||
output_parallel = self.conv(input_parallel) | ||
output = output_parallel | ||
output = self.conv(inputs) | ||
return output | ||
|
||
|
||
|
@@ -911,7 +905,8 @@ def __init__( | |
norm_eps: float = 1e-6, | ||
norm_num_groups: int = 32, | ||
temporal_compression_ratio: float = 4, | ||
sample_size: int = 256, | ||
sample_height: int = 480, | ||
sample_width: int = 720, | ||
scaling_factor: float = 1.15258426, | ||
shift_factor: Optional[float] = None, | ||
latents_mean: Optional[Tuple[float]] = None, | ||
|
@@ -950,25 +945,64 @@ def __init__( | |
self.use_slicing = False | ||
self.use_tiling = False | ||
|
||
self.tile_sample_min_size = self.config.sample_size | ||
sample_size = ( | ||
self.config.sample_size[0] | ||
if isinstance(self.config.sample_size, (list, tuple)) | ||
else self.config.sample_size | ||
# We make the minimum height and width of sample for tiling half that of the generally supported | ||
self.tile_sample_min_height = sample_height // 2 | ||
self.tile_sample_min_width = sample_width // 2 | ||
self.tile_latent_min_height = int( | ||
self.tile_sample_min_height / (2 ** (len(self.config.block_out_channels) - 1)) | ||
) | ||
self.tile_latent_min_size = int(sample_size / (2 ** (len(self.config.block_out_channels) - 1))) | ||
self.tile_overlap_factor = 0.25 | ||
self.tile_latent_min_width = int(self.tile_sample_min_width / (2 ** (len(self.config.block_out_channels) - 1))) | ||
self.tile_overlap_factor = 0.33 | ||
a-r-r-o-w marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
def _set_gradient_checkpointing(self, module, value=False): | ||
if isinstance(module, (CogVideoXEncoder3D, CogVideoXDecoder3D)): | ||
module.gradient_checkpointing = value | ||
|
||
def clear_fake_context_parallel_cache(self): | ||
def _clear_fake_context_parallel_cache(self): | ||
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. Better! |
||
for name, module in self.named_modules(): | ||
if isinstance(module, CogVideoXCausalConv3d): | ||
logger.debug(f"Clearing fake Context Parallel cache for layer: {name}") | ||
module._clear_fake_context_parallel_cache() | ||
|
||
def enable_tiling( | ||
self, | ||
tile_sample_min_height: Optional[int] = None, | ||
tile_sample_min_width: Optional[int] = None, | ||
) -> None: | ||
r""" | ||
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to | ||
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow | ||
processing larger images. | ||
""" | ||
self.use_tiling = True | ||
self.tile_sample_min_height = tile_sample_min_height or self.tile_sample_min_height | ||
self.tile_sample_min_width = tile_sample_min_width or self.tile_sample_min_width | ||
self.tile_latent_min_height = int( | ||
self.tile_sample_min_height / (2 ** (len(self.config.block_out_channels) - 1)) | ||
) | ||
self.tile_latent_min_width = int(self.tile_sample_min_width / (2 ** (len(self.config.block_out_channels) - 1))) | ||
|
||
def disable_tiling(self) -> None: | ||
r""" | ||
Disable tiled VAE decoding. If `enable_tiling` was previously enabled, this method will go back to computing | ||
decoding in one step. | ||
""" | ||
self.use_tiling = False | ||
|
||
def enable_slicing(self) -> None: | ||
r""" | ||
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to | ||
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes. | ||
""" | ||
self.use_slicing = True | ||
|
||
def disable_slicing(self) -> None: | ||
r""" | ||
Disable sliced VAE decoding. If `enable_slicing` was previously enabled, this method will go back to computing | ||
decoding in one step. | ||
""" | ||
self.use_slicing = False | ||
|
||
@apply_forward_hook | ||
def encode( | ||
self, x: torch.Tensor, return_dict: bool = True | ||
|
@@ -993,8 +1027,34 @@ def encode( | |
return (posterior,) | ||
return AutoencoderKLOutput(latent_dist=posterior) | ||
|
||
def _decode(self, z: torch.Tensor, return_dict: bool = True) -> Union[DecoderOutput, torch.Tensor]: | ||
if self.use_tiling and (z.shape[-1] > self.tile_latent_min_width or z.shape[-2] > self.tile_latent_min_height): | ||
return self.tiled_decode(z, return_dict=return_dict) | ||
|
||
num_latent_frames = z.shape[2] | ||
dec = [] | ||
for i in range(num_latent_frames // 2): | ||
a-r-r-o-w marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if num_latent_frames % 2 == 0: | ||
start_frame, end_frame = (2 * i, 2 * i + 2) | ||
else: | ||
start_frame, end_frame = (0, 3) if i == 0 else (2 * i + 1, 2 * i + 3) | ||
|
||
z_intermediate = z[:, :, start_frame:end_frame] | ||
if self.post_quant_conv is not None: | ||
z_intermediate = self.post_quant_conv(z_intermediate) | ||
z_intermediate = self.decoder(z_intermediate) | ||
dec.append(z_intermediate) | ||
|
||
self._clear_fake_context_parallel_cache() | ||
dec = torch.cat(dec, dim=2) | ||
|
||
if not return_dict: | ||
return (dec,) | ||
|
||
return DecoderOutput(sample=dec) | ||
|
||
@apply_forward_hook | ||
def decode(self, z: torch.FloatTensor, return_dict: bool = True) -> Union[DecoderOutput, torch.FloatTensor]: | ||
def decode(self, z: torch.Tensor, return_dict: bool = True) -> Union[DecoderOutput, torch.Tensor]: | ||
""" | ||
Decode a batch of images. | ||
|
||
|
@@ -1007,13 +1067,109 @@ def decode(self, z: torch.FloatTensor, return_dict: bool = True) -> Union[Decode | |
[`~models.vae.DecoderOutput`] or `tuple`: | ||
If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is | ||
returned. | ||
""" | ||
if self.use_slicing and z.shape[0] > 1: | ||
decoded_slices = [self._decode(z_slice).sample for z_slice in z.split(1)] | ||
decoded = torch.cat(decoded_slices) | ||
else: | ||
decoded = self._decode(z).sample | ||
|
||
if not return_dict: | ||
return (decoded,) | ||
return DecoderOutput(sample=decoded) | ||
|
||
def blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor: | ||
blend_extent = min(a.shape[3], b.shape[3], blend_extent) | ||
for y in range(blend_extent): | ||
b[:, :, :, y, :] = a[:, :, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, :, y, :] * ( | ||
y / blend_extent | ||
) | ||
return b | ||
|
||
def blend_h(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor: | ||
blend_extent = min(a.shape[4], b.shape[4], blend_extent) | ||
for x in range(blend_extent): | ||
b[:, :, :, :, x] = a[:, :, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, :, x] * ( | ||
x / blend_extent | ||
) | ||
return b | ||
|
||
def tiled_decode(self, z: torch.Tensor, return_dict: bool = True) -> Union[DecoderOutput, torch.Tensor]: | ||
r""" | ||
Decode a batch of images using a tiled decoder. | ||
|
||
Args: | ||
z (`torch.Tensor`): Input batch of latent vectors. | ||
return_dict (`bool`, *optional*, defaults to `True`): | ||
Whether or not to return a [`~models.vae.DecoderOutput`] instead of a plain tuple. | ||
|
||
Returns: | ||
[`~models.vae.DecoderOutput`] or `tuple`: | ||
If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is | ||
returned. | ||
""" | ||
if self.post_quant_conv is not None: | ||
z = self.post_quant_conv(z) | ||
dec = self.decoder(z) | ||
# Rough memory assessment: | ||
# - In CogVideoX-2B, there are a total of 24 CausalConv3d layers. | ||
# - The biggest intermediate dimensions are: [1, 128, 9, 480, 720]. | ||
# - Assume fp16 (2 bytes per value). | ||
# Memory required: 1 * 128 * 9 * 480 * 720 * 24 * 2 / 1024**3 = 17.8 GB | ||
# | ||
# Memory assessment when using tiling: | ||
# - Assume everything as above but now HxW is 240x360 by tiling in half | ||
# Memory required: 1 * 128 * 9 * 240 * 360 * 24 * 2 / 1024**3 = 4.5 GB | ||
|
||
overlap_height = int(self.tile_latent_min_height * (1 - self.tile_overlap_factor)) | ||
overlap_width = int(self.tile_latent_min_width * (1 - self.tile_overlap_factor)) | ||
blend_extent_height = int(self.tile_sample_min_height * self.tile_overlap_factor) | ||
blend_extent_width = int(self.tile_sample_min_width * self.tile_overlap_factor) | ||
row_limit_height = self.tile_sample_min_height - blend_extent_height | ||
row_limit_width = self.tile_sample_min_width - blend_extent_width | ||
|
||
# Split z into overlapping tiles and decode them separately. | ||
# The tiles have an overlap to avoid seams between tiles. | ||
rows = [] | ||
for i in range(0, z.shape[3], overlap_height): | ||
a-r-r-o-w marked this conversation as resolved.
Show resolved
Hide resolved
|
||
row = [] | ||
for j in range(0, z.shape[4], overlap_width): | ||
time = [] | ||
for k in range(z.shape[2] // 2): | ||
if z.shape[2] % 2 == 0: | ||
start_frame, end_frame = (2 * k, 2 * k + 2) | ||
else: | ||
start_frame, end_frame = (0, 3) if k == 0 else (2 * k + 1, 2 * k + 3) | ||
tile = z[ | ||
:, | ||
:, | ||
start_frame:end_frame, | ||
i : i + self.tile_latent_min_height, | ||
j : j + self.tile_latent_min_width, | ||
] | ||
if self.post_quant_conv is not None: | ||
tile = self.post_quant_conv(tile) | ||
tile = self.decoder(tile) | ||
time.append(tile) | ||
self._clear_fake_context_parallel_cache() | ||
row.append(torch.cat(time, dim=2)) | ||
rows.append(row) | ||
|
||
result_rows = [] | ||
for i, row in enumerate(rows): | ||
result_row = [] | ||
for j, tile in enumerate(row): | ||
# blend the above tile and the left tile | ||
# to the current tile and add the current tile to the result row | ||
if i > 0: | ||
tile = self.blend_v(rows[i - 1][j], tile, blend_extent_height) | ||
if j > 0: | ||
tile = self.blend_h(row[j - 1], tile, blend_extent_width) | ||
result_row.append(tile[:, :, :, :row_limit_height, :row_limit_width]) | ||
result_rows.append(torch.cat(result_row, dim=4)) | ||
|
||
dec = torch.cat(result_rows, dim=3) | ||
|
||
if not return_dict: | ||
return (dec,) | ||
|
||
return DecoderOutput(sample=dec) | ||
|
||
def forward( | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.