def _prepare_latents(self, image, mask, gen, vae_scale_factor, device, dtype):
        """Helper function to prepare latents for a single batch."""
        # Concatenate images and masks along width dimension
        image = [torch.cat(img, dim=3).to(device=device, dtype=dtype) for img in image]
        mask = [torch.cat(m, dim=3).to(device=device, dtype=dtype) for m in mask]

        # Generate latent image IDs
        latent_image_ids = self._prepare_latent_image_ids(image, vae_scale_factor, device, dtype)

        # For initial encoding, use actual images
        image_latent = [self._encode_vae_image(img, gen) for img in image]
        masked_image_latent = [img.clone() for img in image_latent]

        for i in range(len(image_latent)):
            # Rearrange latents and masks for patch processing
            num_channels_latents, height, width = image_latent[i].shape[1:]
            image_latent[i] = self._pack_latents(image_latent[i], 1, num_channels_latents, height, width)
            masked_image_latent[i] = self._pack_latents(masked_image_latent[i], 1, num_channels_latents, height, width)

            # Rearrange masks for patch processing
            num_channels_latents, height, width = mask[i].shape[1:]
            mask[i] = mask[i].view(
                1,
                num_channels_latents,
                height // vae_scale_factor,
                vae_scale_factor,
                width // vae_scale_factor,
                vae_scale_factor,
            )
            mask[i] = mask[i].permute(0, 1, 3, 5, 2, 4)
            mask[i] = mask[i].reshape(
                1,
                num_channels_latents * (vae_scale_factor**2),
                height // vae_scale_factor,
                width // vae_scale_factor,
            )
            mask[i] = self._pack_latents(
                mask[i],
                1,
                num_channels_latents * (vae_scale_factor**2),
                height // vae_scale_factor,
                width // vae_scale_factor,
            )

        # Concatenate along batch dimension
        image_latent = torch.cat(image_latent, dim=1)
        masked_image_latent = torch.cat(masked_image_latent, dim=1)
        mask = torch.cat(mask, dim=1)

        return image_latent, masked_image_latent, mask, latent_image_ids
Helper function to prepare latents for a single batch.
src/diffusers/pipelines/visualcloze/pipeline_visualcloze_generation.py