def sample(
        self,
        latents: torch.FloatTensor,
        scheduler: Union[DDIMInverseScheduler, CogVideoXDDIMScheduler],
        prompt: Optional[Union[str, List[str]]] = None,
        negative_prompt: Optional[Union[str, List[str]]] = None,
        num_inference_steps: int = 50,
        guidance_scale: float = 6,
        use_dynamic_cfg: bool = False,
        eta: float = 0.0,
        generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
        attention_kwargs: Optional[Dict[str, Any]] = None,
        reference_latents: torch.FloatTensor = None,
    ) -> torch.FloatTensor:
        r"""
        Execute the core sampling loop for video generation/inversion using CogVideoX.

        Implements the full denoising trajectory recording for both DDIM inversion and
        generation processes. Supports dynamic classifier-free guidance and reference
        latent conditioning.

        Args:
            latents (`torch.FloatTensor`):
                Initial noise tensor of shape `[B, F, C, H, W]`.
            scheduler (`Union[DDIMInverseScheduler, CogVideoXDDIMScheduler]`):
                Scheduling strategy for diffusion process. Use:
                (1) `DDIMInverseScheduler` for inversion
                (2) `CogVideoXDDIMScheduler` for generation
            prompt (`Optional[Union[str, List[str]]]`):
                Text prompt(s) for conditional generation. Defaults to unconditional.
            negative_prompt (`Optional[Union[str, List[str]]]`):
                Negative prompt(s) for guidance. Requires `guidance_scale > 1`.
            num_inference_steps (`int`):
                Number of denoising steps. Affects quality/compute trade-off.
            guidance_scale (`float`):
                Classifier-free guidance weight. 1.0 = no guidance.
            use_dynamic_cfg (`bool`):
                Enable time-varying guidance scale (cosine schedule)
            eta (`float`):
                DDIM variance parameter (0 = deterministic process)
            generator (`Optional[Union[torch.Generator, List[torch.Generator]]]`):
                Random number generator(s) for reproducibility
            attention_kwargs (`Optional[Dict[str, Any]]`):
                Custom parameters for attention modules
            reference_latents (`torch.FloatTensor`):
                Reference latent trajectory for conditional sampling. Shape should match
                `[T, B, F, C, H, W]` where `T` is number of timesteps

        Returns:
            `torch.FloatTensor`:
                Full denoising trajectory tensor of shape `[T, B, F, C, H, W]`.
        """
        self._guidance_scale = guidance_scale
        self._attention_kwargs = attention_kwargs
        self._interrupt = False

        device = self._execution_device

        # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
        # of the Imagen paper: https://huggingface.co/papers/2205.11487 . `guidance_scale = 1`
        # corresponds to doing no classifier free guidance.
        do_classifier_free_guidance = guidance_scale > 1.0

        # 3. Encode input prompt
        prompt_embeds, negative_prompt_embeds = self.encode_prompt(
            prompt,
            negative_prompt,
            do_classifier_free_guidance,
            device=device,
        )
        if do_classifier_free_guidance:
            prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
        if reference_latents is not None:
            prompt_embeds = torch.cat([prompt_embeds] * 2, dim=0)

        # 4. Prepare timesteps
        timesteps, num_inference_steps = retrieve_timesteps(scheduler, num_inference_steps, device)
        self._num_timesteps = len(timesteps)

        # 5. Prepare latents.
        latents = latents.to(device=device) * scheduler.init_noise_sigma

        # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
        extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
        if isinstance(scheduler, DDIMInverseScheduler):  # Inverse scheduler does not accept extra kwargs
            extra_step_kwargs = {}

        # 7. Create rotary embeds if required
        image_rotary_emb = (
            self._prepare_rotary_positional_embeddings(
                height=latents.size(3) * self.vae_scale_factor_spatial,
                width=latents.size(4) * self.vae_scale_factor_spatial,
                num_frames=latents.size(1),
                device=device,
            )
            if self.transformer.config.use_rotary_positional_embeddings
            else None
        )

        # 8. Denoising loop
        num_warmup_steps = max(len(timesteps) - num_inference_steps * scheduler.order, 0)

        trajectory = torch.zeros_like(latents).unsqueeze(0).repeat(len(timesteps), 1, 1, 1, 1, 1)
        with self.progress_bar(total=num_inference_steps) as progress_bar:
            for i, t in enumerate(timesteps):
                if self.interrupt:
                    continue

                latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
                if reference_latents is not None:
                    reference = reference_latents[i]
                    reference = torch.cat([reference] * 2) if do_classifier_free_guidance else reference
                    latent_model_input = torch.cat([latent_model_input, reference], dim=0)
                latent_model_input = scheduler.scale_model_input(latent_model_input, t)

                # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
                timestep = t.expand(latent_model_input.shape[0])

                # predict noise model_output
                noise_pred = self.transformer(
                    hidden_states=latent_model_input,
                    encoder_hidden_states=prompt_embeds,
                    timestep=timestep,
                    image_rotary_emb=image_rotary_emb,
                    attention_kwargs=attention_kwargs,
                    return_dict=False,
                )[0]
                noise_pred = noise_pred.float()

                if reference_latents is not None:  # Recover the original batch size
                    noise_pred, _ = noise_pred.chunk(2)

                # perform guidance
                if use_dynamic_cfg:
                    self._guidance_scale = 1 + guidance_scale * (
                        (1 - math.cos(math.pi * ((num_inference_steps - t.item()) / num_inference_steps) ** 5.0)) / 2
                    )
                if do_classifier_free_guidance:
                    noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
                    noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)

                # compute the noisy sample x_t-1 -> x_t
                latents = scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
                latents = latents.to(prompt_embeds.dtype)
                trajectory[i] = latents

                if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % scheduler.order == 0):
                    progress_bar.update()

        # Offload all models
        self.maybe_free_model_hooks()

        return trajectory

        Execute the core sampling loop for video generation/inversion using CogVideoX.

        Implements the full denoising trajectory recording for both DDIM inversion and
        generation processes. Supports dynamic classifier-free guidance and reference
        latent conditioning.

        Args:
            latents (`torch.FloatTensor`):
                Initial noise tensor of shape `[B, F, C, H, W]`.
            scheduler (`Union[DDIMInverseScheduler, CogVideoXDDIMScheduler]`):
                Scheduling strategy for diffusion process. Use:
                (1) `DDIMInverseScheduler` for inversion
                (2) `CogVideoXDDIMScheduler` for generation
            prompt (`Optional[Union[str, List[str]]]`):
                Text prompt(s) for conditional generation. Defaults to unconditional.
            negative_prompt (`Optional[Union[str, List[str]]]`):
                Negative prompt(s) for guidance. Requires `guidance_scale > 1`.
            num_inference_steps (`int`):
                Number of denoising steps. Affects quality/compute trade-off.
            guidance_scale (`float`):
                Classifier-free guidance weight. 1.0 = no guidance.
            use_dynamic_cfg (`bool`):
                Enable time-varying guidance scale (cosine schedule)
            eta (`float`):
                DDIM variance parameter (0 = deterministic process)
            generator (`Optional[Union[torch.Generator, List[torch.Generator]]]`):
                Random number generator(s) for reproducibility
            attention_kwargs (`Optional[Dict[str, Any]]`):
                Custom parameters for attention modules
            reference_latents (`torch.FloatTensor`):
                Reference latent trajectory for conditional sampling. Shape should match
                `[T, B, F, C, H, W]` where `T` is number of timesteps

        Returns:
            `torch.FloatTensor`:
                Full denoising trajectory tensor of shape `[T, B, F, C, H, W]`.
        
examples/community/cogvideox_ddim_inversion.py