diff --git a/src/diffusers/pipelines/ltx2/pipeline_ltx2.py b/src/diffusers/pipelines/ltx2/pipeline_ltx2.py index 55ed58e3e040..3fb80811cbd3 100644 --- a/src/diffusers/pipelines/ltx2/pipeline_ltx2.py +++ b/src/diffusers/pipelines/ltx2/pipeline_ltx2.py @@ -36,7 +36,7 @@ from ...models.transformers import LTX2VideoTransformer3DModel from ...schedulers import FlowMatchEulerDiscreteScheduler from ...utils import is_torch_xla_available, logging, replace_example_docstring -from ...utils.torch_utils import randn_tensor +from ...utils.torch_utils import get_module_execution_device, randn_tensor from ...video_processor import VideoProcessor from ..pipeline_utils import DiffusionPipeline from .duration_head import LTX2DurationHead @@ -343,15 +343,17 @@ def _get_gemma_prompt_embeds( ) text_input_ids = text_inputs.input_ids prompt_attention_mask = text_inputs.attention_mask - text_input_ids = text_input_ids.to(device) - prompt_attention_mask = prompt_attention_mask.to(device) + model_device = get_module_execution_device(self.text_encoder) text_encoder_outputs = self.text_encoder( - input_ids=text_input_ids, attention_mask=prompt_attention_mask, output_hidden_states=True + input_ids=text_input_ids.to(model_device), + attention_mask=prompt_attention_mask.to(model_device), + output_hidden_states=True, ) text_encoder_hidden_states = text_encoder_outputs.hidden_states text_encoder_hidden_states = torch.stack(text_encoder_hidden_states, dim=-1) - prompt_embeds = text_encoder_hidden_states.flatten(2, 3).to(dtype=dtype) # Pack to 3D + prompt_embeds = text_encoder_hidden_states.flatten(2, 3).to(device=device, dtype=dtype) # Pack to 3D + prompt_attention_mask = prompt_attention_mask.to(device) # duplicate text embeddings for each generation per prompt, using mps friendly method _, seq_len, _ = prompt_embeds.shape @@ -1247,8 +1249,14 @@ def __call__( tokenizer_padding_side = "left" # Padding side for the default Gemma text encoder if getattr(self, "tokenizer", None) is not None: tokenizer_padding_side = getattr(self.tokenizer, "padding_side", "left") - connector_prompt_embeds, connector_audio_prompt_embeds, connector_attention_mask = self.connectors( - prompt_embeds, prompt_attention_mask, padding_side=tokenizer_padding_side + connectors_device = get_module_execution_device(self.connectors) + connector_outputs = self.connectors( + prompt_embeds.to(connectors_device), + prompt_attention_mask.to(connectors_device), + padding_side=tokenizer_padding_side, + ) + connector_prompt_embeds, connector_audio_prompt_embeds, connector_attention_mask = ( + output.to(device) for output in connector_outputs ) if auto_duration: @@ -1258,9 +1266,10 @@ def __call__( video_tokens = video_tokens.chunk(2, dim=0)[1] audio_tokens = audio_tokens.chunk(2, dim=0)[1] # Rows past the first are `num_videos_per_prompt` duplicates of the same prompt. + duration_head_device = get_module_execution_device(self.duration_head) num_frames = self.duration_head.predict_num_frames( - video_tokens[:1], - audio_tokens[:1], + video_tokens[:1].to(duration_head_device), + audio_tokens[:1].to(duration_head_device), frame_rate=frame_rate, temporal_compression_ratio=self.vae_temporal_compression_ratio, min_seconds=min_seconds, @@ -1654,13 +1663,15 @@ def __call__( latents, self.vae.latents_mean, self.vae.latents_std, self.vae.config.scaling_factor ) - latents = latents.to(self.vae.dtype) + latents = latents.to(device=get_module_execution_device(self.vae), dtype=self.vae.dtype) video = self.vae.decode(latents, timestep, return_dict=False)[0] video = self.video_processor.postprocess_video(video, output_type=output_type) - audio_latents = audio_latents.to(self.audio_vae.dtype) + audio_latents = audio_latents.to( + device=get_module_execution_device(self.audio_vae), dtype=self.audio_vae.dtype + ) generated_mel_spectrograms = self.audio_vae.decode(audio_latents, return_dict=False)[0] - audio = self.vocoder(generated_mel_spectrograms) + audio = self.vocoder(generated_mel_spectrograms.to(get_module_execution_device(self.vocoder))) # Offload all models self.maybe_free_model_hooks() diff --git a/src/diffusers/pipelines/ltx2/pipeline_ltx2_condition.py b/src/diffusers/pipelines/ltx2/pipeline_ltx2_condition.py index f9d550b7784e..40c7f6eae326 100644 --- a/src/diffusers/pipelines/ltx2/pipeline_ltx2_condition.py +++ b/src/diffusers/pipelines/ltx2/pipeline_ltx2_condition.py @@ -38,7 +38,7 @@ from ...models.transformers import LTX2VideoTransformer3DModel from ...schedulers import FlowMatchEulerDiscreteScheduler from ...utils import is_torch_xla_available, logging, replace_example_docstring -from ...utils.torch_utils import randn_tensor +from ...utils.torch_utils import get_module_execution_device, randn_tensor from ...video_processor import VideoProcessor from ..pipeline_utils import DiffusionPipeline from .duration_head import LTX2DurationHead @@ -394,15 +394,17 @@ def _get_gemma_prompt_embeds( ) text_input_ids = text_inputs.input_ids prompt_attention_mask = text_inputs.attention_mask - text_input_ids = text_input_ids.to(device) - prompt_attention_mask = prompt_attention_mask.to(device) + model_device = get_module_execution_device(self.text_encoder) text_encoder_outputs = self.text_encoder( - input_ids=text_input_ids, attention_mask=prompt_attention_mask, output_hidden_states=True + input_ids=text_input_ids.to(model_device), + attention_mask=prompt_attention_mask.to(model_device), + output_hidden_states=True, ) text_encoder_hidden_states = text_encoder_outputs.hidden_states text_encoder_hidden_states = torch.stack(text_encoder_hidden_states, dim=-1) - prompt_embeds = text_encoder_hidden_states.flatten(2, 3).to(dtype=dtype) # Pack to 3D + prompt_embeds = text_encoder_hidden_states.flatten(2, 3).to(device=device, dtype=dtype) # Pack to 3D + prompt_attention_mask = prompt_attention_mask.to(device) # duplicate text embeddings for each generation per prompt, using mps friendly method _, seq_len, _ = prompt_embeds.shape @@ -1137,7 +1139,7 @@ def prepare_latents( ) condition_frames, condition_strengths, condition_indices, condition_pixel_frames = self.preprocess_conditions( - conditions, height, width, num_frames, device=device + conditions, height, width, num_frames, device=get_module_execution_device(self.vae) ) # Encode each condition through the VAE. We keep both the 5D latent (for coord computation) and the packed # 3D latent (for first-frame replacement or keyframe append). @@ -1692,8 +1694,14 @@ def __call__( prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0) prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask], dim=0) - connector_prompt_embeds, connector_audio_prompt_embeds, connector_attention_mask = self.connectors( - prompt_embeds, prompt_attention_mask, padding_side=self.tokenizer_padding_side + connectors_device = get_module_execution_device(self.connectors) + connector_outputs = self.connectors( + prompt_embeds.to(connectors_device), + prompt_attention_mask.to(connectors_device), + padding_side=self.tokenizer_padding_side, + ) + connector_prompt_embeds, connector_audio_prompt_embeds, connector_attention_mask = ( + output.to(device) for output in connector_outputs ) if auto_duration: @@ -1703,9 +1711,10 @@ def __call__( video_tokens = video_tokens.chunk(2, dim=0)[1] audio_tokens = audio_tokens.chunk(2, dim=0)[1] # Rows past the first are `num_videos_per_prompt` duplicates of the same prompt. + duration_head_device = get_module_execution_device(self.duration_head) num_frames = self.duration_head.predict_num_frames( - video_tokens[:1], - audio_tokens[:1], + video_tokens[:1].to(duration_head_device), + audio_tokens[:1].to(duration_head_device), frame_rate=frame_rate, temporal_compression_ratio=self.vae_temporal_compression_ratio, min_seconds=min_seconds, @@ -2108,13 +2117,15 @@ def __call__( latents, self.vae.latents_mean, self.vae.latents_std, self.vae.config.scaling_factor ) - latents = latents.to(self.vae.dtype) + latents = latents.to(device=get_module_execution_device(self.vae), dtype=self.vae.dtype) video = self.vae.decode(latents, timestep, return_dict=False)[0] video = self.video_processor.postprocess_video(video, output_type=output_type) - audio_latents = audio_latents.to(self.audio_vae.dtype) + audio_latents = audio_latents.to( + device=get_module_execution_device(self.audio_vae), dtype=self.audio_vae.dtype + ) generated_mel_spectrograms = self.audio_vae.decode(audio_latents, return_dict=False)[0] - audio = self.vocoder(generated_mel_spectrograms) + audio = self.vocoder(generated_mel_spectrograms.to(get_module_execution_device(self.vocoder))) # Offload all models self.maybe_free_model_hooks() diff --git a/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr.py b/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr.py index ea232a3a331e..cdba5890394f 100644 --- a/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr.py +++ b/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr.py @@ -36,7 +36,7 @@ from ...models.transformers import LTX2VideoTransformer3DModel from ...schedulers import FlowMatchEulerDiscreteScheduler, LTXEulerAncestralRFScheduler from ...utils import is_torch_xla_available, logging, replace_example_docstring -from ...utils.torch_utils import randn_tensor +from ...utils.torch_utils import get_module_execution_device, randn_tensor from ...video_processor import VideoProcessor from ..pipeline_utils import DiffusionPipeline from .dfr_layout import LTX2DFREpilogueTile, resolve_canvas, video_tile_plan @@ -505,15 +505,17 @@ def _get_gemma_prompt_embeds( ) text_input_ids = text_inputs.input_ids prompt_attention_mask = text_inputs.attention_mask - text_input_ids = text_input_ids.to(device) - prompt_attention_mask = prompt_attention_mask.to(device) + model_device = get_module_execution_device(self.text_encoder) text_encoder_outputs = self.text_encoder( - input_ids=text_input_ids, attention_mask=prompt_attention_mask, output_hidden_states=True + input_ids=text_input_ids.to(model_device), + attention_mask=prompt_attention_mask.to(model_device), + output_hidden_states=True, ) text_encoder_hidden_states = text_encoder_outputs.hidden_states text_encoder_hidden_states = torch.stack(text_encoder_hidden_states, dim=-1) - prompt_embeds = text_encoder_hidden_states.flatten(2, 3).to(dtype=dtype) # Pack to 3D + prompt_embeds = text_encoder_hidden_states.flatten(2, 3).to(device=device, dtype=dtype) # Pack to 3D + prompt_attention_mask = prompt_attention_mask.to(device) # duplicate text embeddings for each generation per prompt, using mps friendly method _, seq_len, _ = prompt_embeds.shape @@ -1206,7 +1208,7 @@ def encode_conditions( The returned index is on `num_frames`' own pixel grid; carrying it onto a refined canvas is the caller's job. """ condition_frames, condition_strengths, condition_indices, condition_pixel_frames = self.preprocess_conditions( - conditions, height, width, num_frames, device=device + conditions, height, width, num_frames, device=get_module_execution_device(self.vae) ) encoded = [] for pixels, strength, latent_index, num_pixel_frames in zip( @@ -1505,7 +1507,11 @@ def rebuild_epilogue_keyframes( ) plane = (1 - decode_noise_scale) * plane + decode_noise_scale * noise timestep = torch.full((plane.shape[0],), decode_timestep, device=device, dtype=plane.dtype) - frames = self.vae.decode(plane.to(self.vae.dtype), timestep, return_dict=False)[0] + frames = self.vae.decode( + plane.to(device=get_module_execution_device(self.vae), dtype=self.vae.dtype), + timestep, + return_dict=False, + )[0] # PIL is the reference's Lanczos, and it wants one 8-bit channels-last image at a time. stretched_batch = [] @@ -1515,7 +1521,9 @@ def rebuild_epilogue_keyframes( image = image.resize((image.width * 2, image.height * 2), resample=PIL.Image.Resampling.LANCZOS) stretched = torch.from_numpy(np.asarray(image, dtype=np.float32) / 127.5 - 1.0) stretched_batch.append(stretched.permute(2, 0, 1).unsqueeze(1)) - stretched = torch.stack(stretched_batch).to(device=device, dtype=self.vae.dtype) + stretched = torch.stack(stretched_batch).to( + device=get_module_execution_device(self.vae), dtype=self.vae.dtype + ) encoded.append(retrieve_latents(self.vae.encode(stretched), sample_mode="argmax")) return torch.cat(encoded, dim=2).to(device=device, dtype=dtype) @@ -1763,8 +1771,14 @@ def __call__( max_sequence_length=max_sequence_length, device=device, ) - video_prompt_embeds, audio_prompt_embeds, connector_attention_mask = self.connectors( - prompt_embeds, prompt_attention_mask, padding_side=self.tokenizer_padding_side + connectors_device = get_module_execution_device(self.connectors) + connector_outputs = self.connectors( + prompt_embeds.to(connectors_device), + prompt_attention_mask.to(connectors_device), + padding_side=self.tokenizer_padding_side, + ) + video_prompt_embeds, audio_prompt_embeds, connector_attention_mask = ( + output.to(device) for output in connector_outputs ) if num_frames is None: @@ -1772,9 +1786,10 @@ def __call__( raise ValueError( "`num_frames` must be supplied when the pipeline has no `duration_head` component to predict it." ) + duration_head_device = get_module_execution_device(self.duration_head) num_frames = self.duration_head.predict_num_frames( - video_prompt_embeds[:1], - audio_prompt_embeds[:1], + video_prompt_embeds[:1].to(duration_head_device), + audio_prompt_embeds[:1].to(duration_head_device), frame_rate=frame_rate, temporal_compression_ratio=self.vae_temporal_compression_ratio, min_seconds=min_seconds, @@ -1943,10 +1958,15 @@ def __call__( video_latents = self._denormalize_latents( video_latents, self.vae.latents_mean, self.vae.latents_std, self.vae.config.scaling_factor ) - video = self.vae.decode(video_latents.to(self.vae.dtype), timestep, return_dict=False)[0] + video_latents = video_latents.to(device=get_module_execution_device(self.vae), dtype=self.vae.dtype) + video = self.vae.decode(video_latents, timestep, return_dict=False)[0] video = self.video_processor.postprocess_video(video, output_type=output_type) - audio = self.vocoder(self.audio_vae.decode(public_audio.to(self.audio_vae.dtype), return_dict=False)[0]) + public_audio = public_audio.to( + device=get_module_execution_device(self.audio_vae), dtype=self.audio_vae.dtype + ) + generated_mel_spectrograms = self.audio_vae.decode(public_audio, return_dict=False)[0] + audio = self.vocoder(generated_mel_spectrograms.to(get_module_execution_device(self.vocoder))) audio_samples = min( audio.shape[-1], round(requested_frames / frame_rate * self.vocoder.config.output_sampling_rate) ) diff --git a/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr_temporal_refine.py b/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr_temporal_refine.py index 7a46047760c9..b4ff68eae31d 100644 --- a/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr_temporal_refine.py +++ b/src/diffusers/pipelines/ltx2/pipeline_ltx2_dfr_temporal_refine.py @@ -34,7 +34,7 @@ from ...models.transformers import LTX2VideoTransformer3DModel from ...schedulers import LTXEulerAncestralRFScheduler from ...utils import is_torch_xla_available, logging, replace_example_docstring -from ...utils.torch_utils import randn_tensor +from ...utils.torch_utils import get_module_execution_device, randn_tensor from ...video_processor import VideoProcessor from ..pipeline_utils import DiffusionPipeline from .dfr_layout import temporal_tile_plan @@ -445,15 +445,17 @@ def _get_gemma_prompt_embeds( ) text_input_ids = text_inputs.input_ids prompt_attention_mask = text_inputs.attention_mask - text_input_ids = text_input_ids.to(device) - prompt_attention_mask = prompt_attention_mask.to(device) + model_device = get_module_execution_device(self.text_encoder) text_encoder_outputs = self.text_encoder( - input_ids=text_input_ids, attention_mask=prompt_attention_mask, output_hidden_states=True + input_ids=text_input_ids.to(model_device), + attention_mask=prompt_attention_mask.to(model_device), + output_hidden_states=True, ) text_encoder_hidden_states = text_encoder_outputs.hidden_states text_encoder_hidden_states = torch.stack(text_encoder_hidden_states, dim=-1) - prompt_embeds = text_encoder_hidden_states.flatten(2, 3).to(dtype=dtype) # Pack to 3D + prompt_embeds = text_encoder_hidden_states.flatten(2, 3).to(device=device, dtype=dtype) # Pack to 3D + prompt_attention_mask = prompt_attention_mask.to(device) # duplicate text embeddings for each generation per prompt, using mps friendly method _, seq_len, _ = prompt_embeds.shape @@ -1118,7 +1120,7 @@ def encode_conditions( The returned index is on `num_frames`' own pixel grid; carrying it onto a refined canvas is the caller's job. """ condition_frames, condition_strengths, condition_indices, condition_pixel_frames = self.preprocess_conditions( - conditions, height, width, num_frames, device=device + conditions, height, width, num_frames, device=get_module_execution_device(self.vae) ) encoded = [] for pixels, strength, latent_index, num_pixel_frames in zip( @@ -1528,8 +1530,14 @@ def __call__( max_sequence_length=max_sequence_length, device=device, ) - video_prompt_embeds, audio_prompt_embeds, connector_attention_mask = self.connectors( - prompt_embeds, prompt_attention_mask, padding_side=self.tokenizer_padding_side + connectors_device = get_module_execution_device(self.connectors) + connector_outputs = self.connectors( + prompt_embeds.to(connectors_device), + prompt_attention_mask.to(connectors_device), + padding_side=self.tokenizer_padding_side, + ) + video_prompt_embeds, audio_prompt_embeds, connector_attention_mask = ( + output.to(device) for output in connector_outputs ) num_channels_latents = self.transformer.config.in_channels @@ -1740,10 +1748,15 @@ def __call__( video_latents = self._denormalize_latents( video_latents, self.vae.latents_mean, self.vae.latents_std, self.vae.config.scaling_factor ) - video = self.vae.decode(video_latents.to(self.vae.dtype), timestep, return_dict=False)[0] + video_latents = video_latents.to(device=get_module_execution_device(self.vae), dtype=self.vae.dtype) + video = self.vae.decode(video_latents, timestep, return_dict=False)[0] video = self.video_processor.postprocess_video(video, output_type=output_type) - audio = self.vocoder(self.audio_vae.decode(public_audio.to(self.audio_vae.dtype), return_dict=False)[0]) + public_audio = public_audio.to( + device=get_module_execution_device(self.audio_vae), dtype=self.audio_vae.dtype + ) + generated_mel_spectrograms = self.audio_vae.decode(public_audio, return_dict=False)[0] + audio = self.vocoder(generated_mel_spectrograms.to(get_module_execution_device(self.vocoder))) audio_samples = min( audio.shape[-1], round(canvas_frames / playback_fps * self.vocoder.config.output_sampling_rate) ) diff --git a/src/diffusers/pipelines/ltx2/pipeline_ltx2_hdr_lora.py b/src/diffusers/pipelines/ltx2/pipeline_ltx2_hdr_lora.py index 018dd5dbeeec..a552d1dff176 100644 --- a/src/diffusers/pipelines/ltx2/pipeline_ltx2_hdr_lora.py +++ b/src/diffusers/pipelines/ltx2/pipeline_ltx2_hdr_lora.py @@ -34,7 +34,7 @@ from ...models.transformers import LTX2VideoTransformer3DModel from ...schedulers import FlowMatchEulerDiscreteScheduler from ...utils import is_torch_xla_available, logging, replace_example_docstring -from ...utils.torch_utils import randn_tensor +from ...utils.torch_utils import get_module_execution_device, randn_tensor from ..pipeline_utils import DiffusionPipeline from .image_processor import LTX2VideoHDRProcessor from .pipeline_output import LTX2PipelineOutput @@ -404,15 +404,17 @@ def _get_gemma_prompt_embeds( ) text_input_ids = text_inputs.input_ids prompt_attention_mask = text_inputs.attention_mask - text_input_ids = text_input_ids.to(device) - prompt_attention_mask = prompt_attention_mask.to(device) + model_device = get_module_execution_device(self.text_encoder) text_encoder_outputs = self.text_encoder( - input_ids=text_input_ids, attention_mask=prompt_attention_mask, output_hidden_states=True + input_ids=text_input_ids.to(model_device), + attention_mask=prompt_attention_mask.to(model_device), + output_hidden_states=True, ) text_encoder_hidden_states = text_encoder_outputs.hidden_states text_encoder_hidden_states = torch.stack(text_encoder_hidden_states, dim=-1) - prompt_embeds = text_encoder_hidden_states.flatten(2, 3).to(dtype=dtype) # Pack to 3D + prompt_embeds = text_encoder_hidden_states.flatten(2, 3).to(device=device, dtype=dtype) # Pack to 3D + prompt_attention_mask = prompt_attention_mask.to(device) # duplicate text embeddings for each generation per prompt, using mps friendly method _, seq_len, _ = prompt_embeds.shape @@ -895,7 +897,7 @@ def _encode_reference_conditions( # standard [-1, 1] normalization since LogC3's `compress_ldr` is an identity clamp. ref_pixels = self.hdr_video_processor.preprocess_reference_video_hdr(video_like, ref_height, ref_width) ref_pixels = ref_pixels[:, :, :num_frames] - ref_pixels = ref_pixels.to(dtype=self.vae.dtype, device=device) + ref_pixels = ref_pixels.to(dtype=self.vae.dtype, device=get_module_execution_device(self.vae)) ref_latent = retrieve_latents(self.vae.encode(ref_pixels), generator=generator, sample_mode="argmax") ref_latent = self._normalize_latents(ref_latent, self.vae.latents_mean, self.vae.latents_std).to( @@ -1238,8 +1240,14 @@ def __call__( prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0) prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask], dim=0) - connector_prompt_embeds, connector_audio_prompt_embeds, connector_attention_mask = self.connectors( - prompt_embeds, prompt_attention_mask, padding_side=self.tokenizer_padding_side + connectors_device = get_module_execution_device(self.connectors) + connector_outputs = self.connectors( + prompt_embeds.to(connectors_device), + prompt_attention_mask.to(connectors_device), + padding_side=self.tokenizer_padding_side, + ) + connector_prompt_embeds, connector_audio_prompt_embeds, connector_attention_mask = ( + output.to(device) for output in connector_outputs ) else: connector_prompt_embeds = connector_video_embeds.to(device=device, dtype=self.transformer.dtype) @@ -1599,7 +1607,7 @@ def __call__( latents = self._denormalize_latents( latents, self.vae.latents_mean, self.vae.latents_std, self.vae.config.scaling_factor ) - latents = latents.to(self.vae.dtype) + latents = latents.to(device=get_module_execution_device(self.vae), dtype=self.vae.dtype) # VAE decode returns a video tensor in the VAE's native range ([-1, 1]). decoded = self.vae.decode(latents, timestep, return_dict=False)[0] diff --git a/src/diffusers/pipelines/ltx2/pipeline_ltx2_ic_lora.py b/src/diffusers/pipelines/ltx2/pipeline_ltx2_ic_lora.py index 5f6253589525..4a05ae947fd6 100644 --- a/src/diffusers/pipelines/ltx2/pipeline_ltx2_ic_lora.py +++ b/src/diffusers/pipelines/ltx2/pipeline_ltx2_ic_lora.py @@ -38,7 +38,7 @@ from ...models.transformers import LTX2VideoTransformer3DModel from ...schedulers import FlowMatchEulerDiscreteScheduler from ...utils import is_torch_xla_available, logging, replace_example_docstring -from ...utils.torch_utils import randn_tensor +from ...utils.torch_utils import get_module_execution_device, randn_tensor from ...video_processor import VideoProcessor from ..pipeline_utils import DiffusionPipeline from .pipeline_ltx2_condition import LTX2VideoCondition @@ -416,15 +416,17 @@ def _get_gemma_prompt_embeds( ) text_input_ids = text_inputs.input_ids prompt_attention_mask = text_inputs.attention_mask - text_input_ids = text_input_ids.to(device) - prompt_attention_mask = prompt_attention_mask.to(device) + model_device = get_module_execution_device(self.text_encoder) text_encoder_outputs = self.text_encoder( - input_ids=text_input_ids, attention_mask=prompt_attention_mask, output_hidden_states=True + input_ids=text_input_ids.to(model_device), + attention_mask=prompt_attention_mask.to(model_device), + output_hidden_states=True, ) text_encoder_hidden_states = text_encoder_outputs.hidden_states text_encoder_hidden_states = torch.stack(text_encoder_hidden_states, dim=-1) - prompt_embeds = text_encoder_hidden_states.flatten(2, 3).to(dtype=dtype) # Pack to 3D + prompt_embeds = text_encoder_hidden_states.flatten(2, 3).to(device=device, dtype=dtype) # Pack to 3D + prompt_attention_mask = prompt_attention_mask.to(device) # duplicate text embeddings for each generation per prompt, using mps friendly method _, seq_len, _ = prompt_embeds.shape @@ -1182,7 +1184,7 @@ def prepare_latents( ) condition_frames, condition_strengths, condition_indices, condition_pixel_frames = self.preprocess_conditions( - conditions, height, width, num_frames, device=device + conditions, height, width, num_frames, device=get_module_execution_device(self.vae) ) # Encode each condition through the VAE. We keep both the 5D latent (for coord computation) and the packed # 3D latent (for first-frame replacement or keyframe append). @@ -1426,7 +1428,7 @@ def _encode_reference_conditions( ref_pixels = self.video_processor.preprocess_video(video_like, ref_height, ref_width, resize_mode="crop") # Trim to num_frames ref_pixels = ref_pixels[:, :, :num_frames] - ref_pixels = ref_pixels.to(dtype=self.vae.dtype, device=device) + ref_pixels = ref_pixels.to(dtype=self.vae.dtype, device=get_module_execution_device(self.vae)) # Encode through VAE ref_latent = retrieve_latents(self.vae.encode(ref_pixels), generator=generator, sample_mode="argmax") @@ -2076,8 +2078,14 @@ def __call__( prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0) prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask], dim=0) - connector_prompt_embeds, connector_audio_prompt_embeds, connector_attention_mask = self.connectors( - prompt_embeds, prompt_attention_mask, padding_side=self.tokenizer_padding_side + connectors_device = get_module_execution_device(self.connectors) + connector_outputs = self.connectors( + prompt_embeds.to(connectors_device), + prompt_attention_mask.to(connectors_device), + padding_side=self.tokenizer_padding_side, + ) + connector_prompt_embeds, connector_audio_prompt_embeds, connector_attention_mask = ( + output.to(device) for output in connector_outputs ) # 4. Prepare latent variables @@ -2541,13 +2549,15 @@ def __call__( latents, self.vae.latents_mean, self.vae.latents_std, self.vae.config.scaling_factor ) - latents = latents.to(self.vae.dtype) + latents = latents.to(device=get_module_execution_device(self.vae), dtype=self.vae.dtype) video = self.vae.decode(latents, timestep, return_dict=False)[0] video = self.video_processor.postprocess_video(video, output_type=output_type) - audio_latents = audio_latents.to(self.audio_vae.dtype) + audio_latents = audio_latents.to( + device=get_module_execution_device(self.audio_vae), dtype=self.audio_vae.dtype + ) generated_mel_spectrograms = self.audio_vae.decode(audio_latents, return_dict=False)[0] - audio = self.vocoder(generated_mel_spectrograms) + audio = self.vocoder(generated_mel_spectrograms.to(get_module_execution_device(self.vocoder))) # Offload all models self.maybe_free_model_hooks() diff --git a/src/diffusers/pipelines/ltx2/pipeline_ltx2_image2video.py b/src/diffusers/pipelines/ltx2/pipeline_ltx2_image2video.py index a69e5686148c..ac28b5d00a55 100644 --- a/src/diffusers/pipelines/ltx2/pipeline_ltx2_image2video.py +++ b/src/diffusers/pipelines/ltx2/pipeline_ltx2_image2video.py @@ -36,7 +36,7 @@ from ...models.transformers import LTX2VideoTransformer3DModel from ...schedulers import FlowMatchEulerDiscreteScheduler from ...utils import is_torch_xla_available, logging, replace_example_docstring -from ...utils.torch_utils import randn_tensor +from ...utils.torch_utils import get_module_execution_device, randn_tensor from ...video_processor import VideoProcessor from ..pipeline_utils import DiffusionPipeline from .duration_head import LTX2DurationHead @@ -347,15 +347,17 @@ def _get_gemma_prompt_embeds( ) text_input_ids = text_inputs.input_ids prompt_attention_mask = text_inputs.attention_mask - text_input_ids = text_input_ids.to(device) - prompt_attention_mask = prompt_attention_mask.to(device) + model_device = get_module_execution_device(self.text_encoder) text_encoder_outputs = self.text_encoder( - input_ids=text_input_ids, attention_mask=prompt_attention_mask, output_hidden_states=True + input_ids=text_input_ids.to(model_device), + attention_mask=prompt_attention_mask.to(model_device), + output_hidden_states=True, ) text_encoder_hidden_states = text_encoder_outputs.hidden_states text_encoder_hidden_states = torch.stack(text_encoder_hidden_states, dim=-1) - prompt_embeds = text_encoder_hidden_states.flatten(2, 3).to(dtype=dtype) # Pack to 3D + prompt_embeds = text_encoder_hidden_states.flatten(2, 3).to(device=device, dtype=dtype) # Pack to 3D + prompt_attention_mask = prompt_attention_mask.to(device) # duplicate text embeddings for each generation per prompt, using mps friendly method _, seq_len, _ = prompt_embeds.shape @@ -841,7 +843,7 @@ def prepare_latents( retrieve_latents(self.vae.encode(img.unsqueeze(0).unsqueeze(2)), generator, "argmax") for img in image ] - init_latents = torch.cat(init_latents, dim=0).to(dtype) + init_latents = torch.cat(init_latents, dim=0).to(device=device, dtype=dtype) init_latents = self._normalize_latents(init_latents, self.vae.latents_mean, self.vae.latents_std) init_latents = init_latents.repeat(1, 1, num_frames, 1, 1) @@ -1313,8 +1315,14 @@ def __call__( tokenizer_padding_side = "left" # Padding side for default Gemma3-12B text encoder if getattr(self, "tokenizer", None) is not None: tokenizer_padding_side = getattr(self.tokenizer, "padding_side", "left") - connector_prompt_embeds, connector_audio_prompt_embeds, connector_attention_mask = self.connectors( - prompt_embeds, prompt_attention_mask, padding_side=tokenizer_padding_side + connectors_device = get_module_execution_device(self.connectors) + connector_outputs = self.connectors( + prompt_embeds.to(connectors_device), + prompt_attention_mask.to(connectors_device), + padding_side=tokenizer_padding_side, + ) + connector_prompt_embeds, connector_audio_prompt_embeds, connector_attention_mask = ( + output.to(device) for output in connector_outputs ) if auto_duration: @@ -1324,9 +1332,10 @@ def __call__( video_tokens = video_tokens.chunk(2, dim=0)[1] audio_tokens = audio_tokens.chunk(2, dim=0)[1] # Rows past the first are `num_videos_per_prompt` duplicates of the same prompt. + duration_head_device = get_module_execution_device(self.duration_head) num_frames = self.duration_head.predict_num_frames( - video_tokens[:1], - audio_tokens[:1], + video_tokens[:1].to(duration_head_device), + audio_tokens[:1].to(duration_head_device), frame_rate=frame_rate, temporal_compression_ratio=self.vae_temporal_compression_ratio, min_seconds=min_seconds, @@ -1361,7 +1370,7 @@ def __call__( if crf != 0: image = PIL.Image.fromarray(apply_image_conditioning_crf(np.array(image.convert("RGB")), crf)) image = self.video_processor.preprocess(image, height=height, width=width) - image = image.to(device=device, dtype=prompt_embeds.dtype) + image = image.to(device=get_module_execution_device(self.vae), dtype=prompt_embeds.dtype) num_channels_latents = self.transformer.config.in_channels latents, conditioning_mask = self.prepare_latents( @@ -1758,13 +1767,15 @@ def __call__( latents, self.vae.latents_mean, self.vae.latents_std, self.vae.config.scaling_factor ) - latents = latents.to(self.vae.dtype) + latents = latents.to(device=get_module_execution_device(self.vae), dtype=self.vae.dtype) video = self.vae.decode(latents, timestep, return_dict=False)[0] video = self.video_processor.postprocess_video(video, output_type=output_type) - audio_latents = audio_latents.to(self.audio_vae.dtype) + audio_latents = audio_latents.to( + device=get_module_execution_device(self.audio_vae), dtype=self.audio_vae.dtype + ) generated_mel_spectrograms = self.audio_vae.decode(audio_latents, return_dict=False)[0] - audio = self.vocoder(generated_mel_spectrograms) + audio = self.vocoder(generated_mel_spectrograms.to(get_module_execution_device(self.vocoder))) # Offload all models self.maybe_free_model_hooks() diff --git a/tests/pipelines/ltx2/test_ltx2.py b/tests/pipelines/ltx2/test_ltx2.py index d727ee1dcba8..462e3aaa6c8e 100644 --- a/tests/pipelines/ltx2/test_ltx2.py +++ b/tests/pipelines/ltx2/test_ltx2.py @@ -18,7 +18,7 @@ from diffusers import LTX2Pipeline from ...testing_utils import assert_tensors_close, enable_full_determinism, torch_device -from ..testing_utils import PipelineTesterMixin +from ..testing_utils import PipelineTesterMixin, SplitDeviceTesterMixin from .testing_utils import ( LTX2BaseTesterConfig, LTX2LoraMemoryTesterMixin, @@ -279,6 +279,12 @@ class TestLTX2PipelineMemory(LTX2PipelineTesterConfig, LTX2MemoryTesterMixin): """Memory optimization tests (CPU offload, group offload, layerwise casting) for the LTX2 pipeline.""" +class TestLTX2PipelineSplitDevice(LTX2PipelineTesterConfig, SplitDeviceTesterMixin): + """Split-device tests (transformer on the accelerator, other components on CPU) for the LTX2 pipeline.""" + + accelerator_components = ("transformer",) + + class TestLTX2PipelineLoRA(LTX2PipelineTesterConfig, LTX2LoraTesterMixin): """LoRA tests for the LTX2 pipeline.""" diff --git a/tests/pipelines/ltx2/test_ltx2_condition.py b/tests/pipelines/ltx2/test_ltx2_condition.py index 81785b72c84e..9b98dcda2e80 100644 --- a/tests/pipelines/ltx2/test_ltx2_condition.py +++ b/tests/pipelines/ltx2/test_ltx2_condition.py @@ -18,7 +18,7 @@ from diffusers.pipelines.ltx2.pipeline_ltx2_condition import LTX2VideoCondition from ...testing_utils import enable_full_determinism -from ..testing_utils import PipelineTesterMixin +from ..testing_utils import PipelineTesterMixin, SplitDeviceTesterMixin from .testing_utils import ( LTX2BaseTesterConfig, LTX2LoraMemoryTesterMixin, @@ -90,6 +90,12 @@ class TestLTX2ConditionPipelineMemory(LTX2ConditionPipelineTesterConfig, LTX2Mem """Memory optimization tests (CPU offload, group offload, layerwise casting) for the LTX2 condition pipeline.""" +class TestLTX2ConditionPipelineSplitDevice(LTX2ConditionPipelineTesterConfig, SplitDeviceTesterMixin): + """Split-device tests (transformer on the accelerator, other components on CPU) for the LTX2 condition pipeline.""" + + accelerator_components = ("transformer",) + + class TestLTX2ConditionPipelineLoRA(LTX2ConditionPipelineTesterConfig, LTX2LoraTesterMixin): """LoRA tests for the LTX2 condition pipeline.""" diff --git a/tests/pipelines/ltx2/test_ltx2_hdr.py b/tests/pipelines/ltx2/test_ltx2_hdr.py index 6e9d95591763..b5c03b1c2c0d 100644 --- a/tests/pipelines/ltx2/test_ltx2_hdr.py +++ b/tests/pipelines/ltx2/test_ltx2_hdr.py @@ -20,7 +20,7 @@ from diffusers.pipelines.ltx2 import LTX2HDRReferenceCondition from ...testing_utils import enable_full_determinism -from ..testing_utils import PipelineTesterMixin +from ..testing_utils import PipelineTesterMixin, SplitDeviceTesterMixin from .testing_utils import ( LTX2BaseTesterConfig, LTX2LoraMemoryTesterMixin, @@ -113,6 +113,17 @@ class TestLTX2HDRPipelineMemory(LTX2HDRPipelineTesterConfig, LTX2MemoryTesterMix """Memory optimization tests (CPU offload, group offload, layerwise casting) for the LTX2 HDR pipeline.""" +class TestLTX2HDRPipelineSplitDevice(LTX2HDRPipelineTesterConfig, SplitDeviceTesterMixin): + """Split-device tests (transformer on the accelerator, other components on CPU) for the LTX2 HDR pipeline.""" + + accelerator_components = ("transformer",) + + # Compares decoded frames rather than latents to cover the VAE decode. The inverse LogC3 transfer function + # amplifies the differences between devices, hence the looser tolerance. + def test_split_device_forward_pass(self, base_pipe_output, expected_max_diff=1e-2): + super().test_split_device_forward_pass(base_pipe_output, expected_max_diff=expected_max_diff) + + class TestLTX2HDRPipelineLoRA(LTX2HDRPipelineTesterConfig, LTX2LoraTesterMixin): """LoRA tests for the LTX2 HDR pipeline.""" diff --git a/tests/pipelines/ltx2/test_ltx2_image2video.py b/tests/pipelines/ltx2/test_ltx2_image2video.py index 599555384140..63acf192e568 100644 --- a/tests/pipelines/ltx2/test_ltx2_image2video.py +++ b/tests/pipelines/ltx2/test_ltx2_image2video.py @@ -19,7 +19,7 @@ from diffusers.pipelines.ltx2 import LTX2LatentUpsamplePipeline from ...testing_utils import assert_tensors_close, enable_full_determinism, torch_device -from ..testing_utils import PipelineTesterMixin +from ..testing_utils import PipelineTesterMixin, SplitDeviceTesterMixin from .testing_utils import ( LTX2BaseTesterConfig, LTX2LoraMemoryTesterMixin, @@ -299,6 +299,12 @@ class TestLTX2ImageToVideoPipelineMemory(LTX2ImageToVideoPipelineTesterConfig, L """Memory optimization tests (CPU offload, group offload, layerwise casting) for the LTX2 I2V pipeline.""" +class TestLTX2ImageToVideoPipelineSplitDevice(LTX2ImageToVideoPipelineTesterConfig, SplitDeviceTesterMixin): + """Split-device tests (transformer on the accelerator, other components on CPU) for the LTX2 I2V pipeline.""" + + accelerator_components = ("transformer",) + + class TestLTX2ImageToVideoPipelineLoRA(LTX2ImageToVideoPipelineTesterConfig, LTX2LoraTesterMixin): """LoRA tests for the LTX2 I2V pipeline.""" diff --git a/tests/pipelines/ltx2/test_ltx2_in_context.py b/tests/pipelines/ltx2/test_ltx2_in_context.py index 17d73bdfb565..186b12be96ba 100644 --- a/tests/pipelines/ltx2/test_ltx2_in_context.py +++ b/tests/pipelines/ltx2/test_ltx2_in_context.py @@ -18,7 +18,7 @@ from diffusers.pipelines.ltx2.pipeline_ltx2_condition import LTX2VideoCondition from ...testing_utils import enable_full_determinism -from ..testing_utils import PipelineTesterMixin +from ..testing_utils import PipelineTesterMixin, SplitDeviceTesterMixin from .testing_utils import ( LTX2BaseTesterConfig, LTX2LoraMemoryTesterMixin, @@ -80,6 +80,12 @@ class TestLTX2InContextPipelineMemory(LTX2InContextPipelineTesterConfig, LTX2Mem """Memory optimization tests (CPU offload, group offload, layerwise casting) for the LTX2 IC pipeline.""" +class TestLTX2InContextPipelineSplitDevice(LTX2InContextPipelineTesterConfig, SplitDeviceTesterMixin): + """Split-device tests (transformer on the accelerator, other components on CPU) for the LTX2 IC pipeline.""" + + accelerator_components = ("transformer",) + + class TestLTX2InContextPipelineLoRA(LTX2InContextPipelineTesterConfig, LTX2LoraTesterMixin): """LoRA tests for the LTX2 IC pipeline.""" diff --git a/tests/pipelines/ltx2/test_pipeline_ltx2_dfr.py b/tests/pipelines/ltx2/test_pipeline_ltx2_dfr.py index c86cc14e333e..0e393cdaf68e 100644 --- a/tests/pipelines/ltx2/test_pipeline_ltx2_dfr.py +++ b/tests/pipelines/ltx2/test_pipeline_ltx2_dfr.py @@ -21,7 +21,7 @@ from diffusers.pipelines.ltx2.utils import EPILOGUE_KEYFRAME_STRENGTH, MAX_CONDITIONING_FPS, trim_canvas from ...testing_utils import enable_full_determinism, torch_device -from ..testing_utils import BasePipelineTesterConfig, PipelineTesterMixin +from ..testing_utils import BasePipelineTesterConfig, PipelineTesterMixin, SplitDeviceTesterMixin from .testing_utils import LTX2MemoryTesterMixin, get_dfr_dummy_components, get_dfr_dummy_inputs @@ -523,3 +523,7 @@ def test_the_epilogue_keeps_every_batch_element_distinct(self): class TestLTX2DFRPipelineMemory(LTX2DFRPipelineTesterConfig, LTX2MemoryTesterMixin): pass + + +class TestLTX2DFRPipelineSplitDevice(LTX2DFRPipelineTesterConfig, SplitDeviceTesterMixin): + accelerator_components = ("transformer",) diff --git a/tests/pipelines/ltx2/test_pipeline_ltx2_dfr_temporal_refine.py b/tests/pipelines/ltx2/test_pipeline_ltx2_dfr_temporal_refine.py index 5cdeeb9b548e..a3f2753d4e90 100644 --- a/tests/pipelines/ltx2/test_pipeline_ltx2_dfr_temporal_refine.py +++ b/tests/pipelines/ltx2/test_pipeline_ltx2_dfr_temporal_refine.py @@ -27,7 +27,7 @@ from diffusers.pipelines.ltx2.utils import ANCHOR_KEYFRAME_STRENGTH from ...testing_utils import enable_full_determinism, torch_device -from ..testing_utils import BasePipelineTesterConfig, PipelineTesterMixin +from ..testing_utils import BasePipelineTesterConfig, PipelineTesterMixin, SplitDeviceTesterMixin from .testing_utils import get_dfr_dummy_components, get_dfr_dummy_inputs, get_temporal_dummy_components @@ -306,3 +306,7 @@ def capture_denoise(**kwargs): _, anchor_latent, strength = round_2_anchors[0] assert strength == ANCHOR_KEYFRAME_STRENGTH assert torch.equal(pipe._pack_latents(anchor_latent), first_tile_slot) + + +class TestLTX2DFRTemporalRefinePipelineSplitDevice(LTX2DFRTemporalRefinePipelineTesterConfig, SplitDeviceTesterMixin): + accelerator_components = ("transformer",) diff --git a/tests/pipelines/testing_utils/__init__.py b/tests/pipelines/testing_utils/__init__.py index d9ab17601a61..11d4f4498c8b 100644 --- a/tests/pipelines/testing_utils/__init__.py +++ b/tests/pipelines/testing_utils/__init__.py @@ -15,6 +15,7 @@ LayerwiseCastingTesterMixin, MemoryTesterMixin, PipelineOffloadTesterMixin, + SplitDeviceTesterMixin, ) @@ -30,6 +31,7 @@ "PipelineOffloadTesterMixin", "GroupOffloadTesterMixin", "LayerwiseCastingTesterMixin", + "SplitDeviceTesterMixin", "CacheTesterMixin", "PyramidAttentionBroadcastTesterMixin", "FasterCacheTesterMixin", diff --git a/tests/pipelines/testing_utils/memory.py b/tests/pipelines/testing_utils/memory.py index 7f811e2ee4cc..1a374c131345 100644 --- a/tests/pipelines/testing_utils/memory.py +++ b/tests/pipelines/testing_utils/memory.py @@ -464,6 +464,29 @@ def test_pipeline_level_group_offloading_inference(self, base_pipe_output, expec ) +@is_memory +@require_accelerator +class SplitDeviceTesterMixin(BasePipelineOutputMixin): + """Inference with the `accelerator_components` on the accelerator and every other component on the CPU. + + Not part of `MemoryTesterMixin`: compose it for the pipelines that support this placement, and set + `accelerator_components` on the test class. + """ + + def test_split_device_forward_pass(self, base_pipe_output, expected_max_diff=1e-4): + pipe = self.get_pipeline() + for name in self.accelerator_components: + getattr(pipe, name).to(torch_device) + + output = self.run_pipe(pipe) + assert_tensors_close( + output.cpu(), + base_pipe_output.cpu(), + atol=expected_max_diff, + msg="running the other components on the CPU should not affect the inference results", + ) + + @is_memory @require_accelerator class MemoryTesterMixin(PipelineOffloadTesterMixin, GroupOffloadTesterMixin, LayerwiseCastingTesterMixin):