



from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPImageProcessor, CLIPVisionModel

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


SCREAMING_SNAKE_CASE_:Optional[int]					=						logging.get_logger(__name__)  # pylint: disable=invalid-name

SCREAMING_SNAKE_CASE_:Any					=						"""
    Examples:
        ```py
        >>> from PIL import Image
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif, load_image

        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")

        >>> repo = \"openai/shap-e-img2img\"
        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)
        >>> pipe = pipe.to(device)

        >>> guidance_scale = 3.0
        >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\"
        >>> image = load_image(image_url).convert(\"RGB\")

        >>> images = pipe(
        ...     image,
        ...     guidance_scale=guidance_scale,
        ...     num_inference_steps=64,
        ...     frame_size=256,
        ... ).images

        >>> gif_path = export_to_gif(images[0], \"corgi_3d.gif\")
        ```
"""






@dataclass
class SCREAMING_SNAKE_CASE__					(		SCREAMING_SNAKE_CASE__   ):




    '''simple docstring'''






    __lowerCamelCase      :			Union[PIL.Image.Image, np.ndarray]






class SCREAMING_SNAKE_CASE__					(		SCREAMING_SNAKE_CASE__   ):




    '''simple docstring'''






    def __init__(	self,		lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__,		):
        super().__init__()

        self.register_modules(
            prior=lowerCamelCase__,		image_encoder=lowerCamelCase__,		image_processor=lowerCamelCase__,		scheduler=lowerCamelCase__,		renderer=lowerCamelCase__,		)






    def       _lowerCAmelCase (	self,		lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__		):
        if latents is None:
            A			:	Optional[int]										=       randn_tensor(lowerCamelCase__,		generator=lowerCamelCase__,		device=lowerCamelCase__,		dtype=lowerCamelCase__		)
        else:
            if latents.shape != shape:
                raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}'''		)
            A			:	Optional[Any]										=       latents.to(lowerCamelCase__		)

        A			:	Dict										=       latents * scheduler.init_noise_sigma
        return latents






    def       _lowerCAmelCase (	self,		lowerCamelCase__=0		):
        if is_accelerate_available():
            from accelerate import cpu_offload
        else:
            raise ImportError("""Please install accelerate via `pip install accelerate`"""		)

        A			:	Tuple										=       torch.device(f'''cuda:{gpu_id}'''		)

        A			:	Optional[Any]										=       [self.image_encoder, self.prior]
        for cpu_offloaded_model in models:
            if cpu_offloaded_model is not None:
                cpu_offload(lowerCamelCase__,		lowerCamelCase__		)






    @property
    def       _lowerCAmelCase (	self		):
        if self.device != torch.device("""meta"""		) or not hasattr(self.image_encoder,		"""_hf_hook"""		):
            return self.device
        for module in self.image_encoder.modules():
            if (
                hasattr(lowerCamelCase__,		"""_hf_hook"""		)
                and hasattr(module._hf_hook,		"""execution_device"""		)
                and module._hf_hook.execution_device is not None
            ):
                return torch.device(module._hf_hook.execution_device		)
        return self.device






    def       _lowerCAmelCase (	self,		lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__,		):
        if isinstance(lowerCamelCase__,		lowerCamelCase__		) and isinstance(image[0],		torch.Tensor		):
            A			:	Union[str, Any]										=       torch.cat(lowerCamelCase__,		axis=0		) if image[0].ndim == 4 else torch.stack(lowerCamelCase__,		axis=0		)

        if not isinstance(lowerCamelCase__,		torch.Tensor		):
            A			:	Tuple										=       self.image_processor(lowerCamelCase__,		return_tensors="""pt"""		).pixel_values[0].unsqueeze(0		)

        A			:	Any										=       image.to(dtype=self.image_encoder.dtype,		device=lowerCamelCase__		)

        A			:	List[Any]										=       self.image_encoder(lowerCamelCase__		)["""last_hidden_state"""]
        A			:	Tuple										=       image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

        A			:	List[str]										=       image_embeds.repeat_interleave(lowerCamelCase__,		dim=0		)

        if do_classifier_free_guidance:
            A			:	Optional[int]										=       torch.zeros_like(lowerCamelCase__		)

            # For classifier free guidance, we need to do two forward passes.
            # Here we concatenate the unconditional and text embeddings into a single batch
            # to avoid doing two forward passes
            A			:	Dict										=       torch.cat([negative_image_embeds, image_embeds]		)

        return image_embeds






    @torch.no_grad()
    @replace_example_docstring(lowerCamelCase__		)
    def __call__(	self,		lowerCamelCase__,		lowerCamelCase__ = 1,		lowerCamelCase__ = 25,		lowerCamelCase__ = None,		lowerCamelCase__ = None,		lowerCamelCase__ = 4.0,		lowerCamelCase__ = 64,		lowerCamelCase__ = "pil",		lowerCamelCase__ = True,		):

        if isinstance(lowerCamelCase__,		PIL.Image.Image		):
            A			:	Tuple										=       1
        elif isinstance(lowerCamelCase__,		torch.Tensor		):
            A			:	Tuple										=       image.shape[0]
        elif isinstance(lowerCamelCase__,		lowerCamelCase__		) and isinstance(image[0],		(torch.Tensor, PIL.Image.Image)		):
            A			:	Optional[Any]										=       len(lowerCamelCase__		)
        else:
            raise ValueError(
                f'''`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(lowerCamelCase__		)}'''		)

        A			:	List[Any]										=       self._execution_device

        A			:	List[str]										=       batch_size * num_images_per_prompt

        A			:	str										=       guidance_scale > 1.0
        A			:	Optional[Any]										=       self._encode_image(lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__		)

        # prior

        self.scheduler.set_timesteps(lowerCamelCase__,		device=lowerCamelCase__		)
        A			:	List[str]										=       self.scheduler.timesteps

        A			:	Dict										=       self.prior.config.num_embeddings
        A			:	Any										=       self.prior.config.embedding_dim

        A			:	Optional[int]										=       self.prepare_latents(
            (batch_size, num_embeddings * embedding_dim),		image_embeds.dtype,		lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__,		self.scheduler,		)

        # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim
        A			:	List[Any]										=       latents.reshape(latents.shape[0],		lowerCamelCase__,		lowerCamelCase__		)

        for i, t in enumerate(self.progress_bar(lowerCamelCase__		)		):
            # expand the latents if we are doing classifier free guidance
            A			:	Dict										=       torch.cat([latents] * 2		) if do_classifier_free_guidance else latents
            A			:	Any										=       self.scheduler.scale_model_input(lowerCamelCase__,		lowerCamelCase__		)

            A			:	List[Any]										=       self.prior(
                lowerCamelCase__,		timestep=lowerCamelCase__,		proj_embedding=lowerCamelCase__,		).predicted_image_embedding

            # remove the variance
            A			:	Optional[Any]										=       noise_pred.split(
                scaled_model_input.shape[2],		dim=2		)  # batch_size, num_embeddings, embedding_dim

            if do_classifier_free_guidance is not None:
                A			:	str										=       noise_pred.chunk(2		)
                A			:	Any										=       noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

            A			:	Optional[Any]										=       self.scheduler.step(
                lowerCamelCase__,		timestep=lowerCamelCase__,		sample=lowerCamelCase__,		).prev_sample

        if output_type == "latent":
            return ShapEPipelineOutput(images=lowerCamelCase__		)

        A			:	Tuple										=       []
        for i, latent in enumerate(lowerCamelCase__		):
            print()
            A			:	Dict										=       self.renderer.decode(
                latent[None, :],		lowerCamelCase__,		size=lowerCamelCase__,		ray_batch_size=4096,		n_coarse_samples=64,		n_fine_samples=128,		)

            images.append(lowerCamelCase__		)

        A			:	int										=       torch.stack(lowerCamelCase__		)

        if output_type not in ["np", "pil"]:
            raise ValueError(f'''Only the output types `pil` and `np` are supported not output_type={output_type}'''		)

        A			:	Union[str, Any]										=       images.cpu().numpy()

        if output_type == "pil":
            A			:	Union[str, Any]										=       [self.numpy_to_pil(lowerCamelCase__		) for image in images]

        # Offload last model to CPU
        if hasattr(self,		"""final_offload_hook"""		) and self.final_offload_hook is not None:
            self.final_offload_hook.offload()

        if not return_dict:
            return (images,)

        return ShapEPipelineOutput(images=lowerCamelCase__		)







import inspect
import unittest

import torch
import torch.nn as nn

from accelerate.hooks import (
    AlignDevicesHook,
    ModelHook,
    SequentialHook,
    add_hook_to_module,
    attach_align_device_hook,
    remove_hook_from_module,
    remove_hook_from_submodules,
)
from accelerate.test_utils import require_multi_gpu






class SCREAMING_SNAKE_CASE__					(		nn.Module   ):




    '''simple docstring'''






    def __init__(	self		):
        super().__init__()
        A			:	Union[str, Any]										=       nn.Linear(3,		4		)
        A			:	Union[str, Any]										=       nn.BatchNormad(4		)
        A			:	Optional[Any]										=       nn.Linear(4,		5		)






    def       _lowerCAmelCase (	self,		lowerCamelCase__		):
        return self.lineara(self.batchnorm(self.lineara(lowerCamelCase__		)		)		)






class SCREAMING_SNAKE_CASE__					(		SCREAMING_SNAKE_CASE__   ):




    '''simple docstring'''






    def       _lowerCAmelCase (	self,		lowerCamelCase__,		*lowerCamelCase__,		**lowerCamelCase__		):
        return (args[0] + 1,) + args[1:], kwargs






class SCREAMING_SNAKE_CASE__					(		SCREAMING_SNAKE_CASE__   ):




    '''simple docstring'''






    def       _lowerCAmelCase (	self,		lowerCamelCase__,		lowerCamelCase__		):
        return output + 1






class SCREAMING_SNAKE_CASE__					(		unittest.TestCase   ):




    '''simple docstring'''






    def       _lowerCAmelCase (	self		):
        A			:	Tuple										=       ModelForTest()
        A			:	Any										=       ModelHook()

        add_hook_to_module(lowerCamelCase__,		lowerCamelCase__		)
        self.assertEqual(test_model._hf_hook,		lowerCamelCase__		)
        self.assertTrue(hasattr(lowerCamelCase__,		"""_old_forward"""		)		)

        # Check adding the hook did not change the name or the signature
        self.assertEqual(test_model.forward.__name__,		"""forward"""		)
        self.assertListEqual(list(inspect.signature(test_model.forward		).parameters		),		["""x"""]		)

        remove_hook_from_module(lowerCamelCase__		)
        self.assertFalse(hasattr(lowerCamelCase__,		"""_hf_hook"""		)		)
        self.assertFalse(hasattr(lowerCamelCase__,		"""_old_forward"""		)		)






    def       _lowerCAmelCase (	self		):
        A			:	Tuple										=       ModelForTest()
        A			:	Optional[int]										=       ModelHook()

        add_hook_to_module(lowerCamelCase__,		lowerCamelCase__		)
        add_hook_to_module(lowerCamelCase__,		lowerCamelCase__,		append=lowerCamelCase__		)

        self.assertEqual(isinstance(test_model._hf_hook,		lowerCamelCase__		),		lowerCamelCase__		)
        self.assertEqual(len(test_model._hf_hook.hooks		),		2		)
        self.assertTrue(hasattr(lowerCamelCase__,		"""_old_forward"""		)		)

        # Check adding the hook did not change the name or the signature
        self.assertEqual(test_model.forward.__name__,		"""forward"""		)
        self.assertListEqual(list(inspect.signature(test_model.forward		).parameters		),		["""x"""]		)

        remove_hook_from_module(lowerCamelCase__		)
        self.assertFalse(hasattr(lowerCamelCase__,		"""_hf_hook"""		)		)
        self.assertFalse(hasattr(lowerCamelCase__,		"""_old_forward"""		)		)






    def       _lowerCAmelCase (	self		):
        A			:	Any										=       ModelForTest()
        A			:	Tuple										=       torch.randn(2,		3		)
        A			:	Optional[int]										=       test_model(x + 1		)
        A			:	List[str]										=       test_model(x + 2		)

        A			:	List[str]										=       PreForwardHook()
        add_hook_to_module(lowerCamelCase__,		lowerCamelCase__		)
        A			:	List[str]										=       test_model(lowerCamelCase__		)
        self.assertTrue(torch.allclose(lowerCamelCase__,		lowerCamelCase__,		atol=1e-5		)		)

        # Attaching a hook to a model when it already has one replaces, does not chain
        A			:	Optional[Any]										=       PreForwardHook()
        add_hook_to_module(lowerCamelCase__,		lowerCamelCase__		)
        A			:	Tuple										=       test_model(lowerCamelCase__		)
        self.assertTrue(torch.allclose(lowerCamelCase__,		lowerCamelCase__,		atol=1e-5		)		)

        # You need to use the sequential hook to chain two or more hooks
        A			:	Any										=       SequentialHook(PreForwardHook(),		PreForwardHook()		)
        add_hook_to_module(lowerCamelCase__,		lowerCamelCase__		)

        A			:	Optional[Any]										=       test_model(lowerCamelCase__		)
        assert torch.allclose(lowerCamelCase__,		lowerCamelCase__,		atol=1e-5		)






    def       _lowerCAmelCase (	self		):
        A			:	Tuple										=       ModelForTest()
        A			:	Any										=       torch.randn(2,		3		)
        A			:	Any										=       test_model(lowerCamelCase__		)

        A			:	List[Any]										=       PostForwardHook()
        add_hook_to_module(lowerCamelCase__,		lowerCamelCase__		)
        A			:	str										=       test_model(lowerCamelCase__		)
        self.assertTrue(torch.allclose(lowerCamelCase__,		output + 1,		atol=1e-5		)		)

        # Attaching a hook to a model when it already has one replaces, does not chain
        A			:	Tuple										=       PostForwardHook()
        add_hook_to_module(lowerCamelCase__,		lowerCamelCase__		)
        A			:	Optional[int]										=       test_model(lowerCamelCase__		)
        self.assertTrue(torch.allclose(lowerCamelCase__,		output + 1,		atol=1e-5		)		)

        # You need to use the sequential hook to chain two or more hooks
        A			:	Dict										=       SequentialHook(PostForwardHook(),		PostForwardHook()		)
        add_hook_to_module(lowerCamelCase__,		lowerCamelCase__		)

        A			:	List[str]										=       test_model(lowerCamelCase__		)
        assert torch.allclose(lowerCamelCase__,		output + 2,		atol=1e-5		)






    def       _lowerCAmelCase (	self		):
        A			:	List[Any]										=       ModelForTest()
        A			:	Tuple										=       torch.randn(2,		3		)
        A			:	Union[str, Any]										=       test_model(lowerCamelCase__		)

        A			:	List[Any]										=       PostForwardHook()
        add_hook_to_module(lowerCamelCase__,		lowerCamelCase__		)
        A			:	List[Any]										=       test_model(lowerCamelCase__		)
        self.assertTrue(torch.allclose(lowerCamelCase__,		output + 1		)		)
        self.assertTrue(outputa.requires_grad		)

        A			:	int										=       True
        A			:	Tuple										=       test_model(lowerCamelCase__		)
        self.assertFalse(outputa.requires_grad		)






    @require_multi_gpu
    def       _lowerCAmelCase (	self		):
        A			:	int										=       ModelForTest()
        # Everything is on CPU
        self.assertEqual(model.lineara.weight.device,		torch.device("""cpu"""		)		)
        self.assertEqual(model.batchnorm.weight.device,		torch.device("""cpu"""		)		)
        self.assertEqual(model.lineara.weight.device,		torch.device("""cpu"""		)		)

        # This will move each submodule on different devices
        add_hook_to_module(model.lineara,		AlignDevicesHook(execution_device=0		)		)
        add_hook_to_module(model.batchnorm,		AlignDevicesHook(execution_device=0		)		)
        add_hook_to_module(model.lineara,		AlignDevicesHook(execution_device=1		)		)

        self.assertEqual(model.lineara.weight.device,		torch.device(0		)		)
        self.assertEqual(model.batchnorm.weight.device,		torch.device(0		)		)
        self.assertEqual(model.batchnorm.running_mean.device,		torch.device(0		)		)
        self.assertEqual(model.lineara.weight.device,		torch.device(1		)		)

        # We can still make a forward pass. The input does not need to be on any particular device
        A			:	str										=       torch.randn(2,		3		)
        A			:	int										=       model(lowerCamelCase__		)
        self.assertEqual(output.device,		torch.device(1		)		)

        # We can add a general hook to put back output on same device as input.
        add_hook_to_module(lowerCamelCase__,		AlignDevicesHook(io_same_device=lowerCamelCase__		)		)
        A			:	int										=       torch.randn(2,		3		).to(0		)
        A			:	str										=       model(lowerCamelCase__		)
        self.assertEqual(output.device,		torch.device(0		)		)






    def       _lowerCAmelCase (	self		):
        A			:	List[str]										=       ModelForTest()

        # Everything is on CPU
        self.assertEqual(model.lineara.weight.device,		torch.device("""cpu"""		)		)
        self.assertEqual(model.batchnorm.weight.device,		torch.device("""cpu"""		)		)
        self.assertEqual(model.lineara.weight.device,		torch.device("""cpu"""		)		)

        # This will move each submodule on different devices
        A			:	int										=       {"""execution_device""": 0 if torch.cuda.is_available() else """cpu""", """offload""": True}

        add_hook_to_module(model.lineara,		AlignDevicesHook(**lowerCamelCase__		)		)
        add_hook_to_module(model.batchnorm,		AlignDevicesHook(**lowerCamelCase__		)		)
        add_hook_to_module(model.lineara,		AlignDevicesHook(**lowerCamelCase__		)		)

        # Parameters have been offloaded, so on the meta device
        self.assertEqual(model.lineara.weight.device,		torch.device("""meta"""		)		)
        self.assertEqual(model.batchnorm.weight.device,		torch.device("""meta"""		)		)
        self.assertEqual(model.lineara.weight.device,		torch.device("""meta"""		)		)
        # Buffers are not included in the offload by default, so are on the execution device
        A			:	Dict										=       torch.device(hook_kwargs["""execution_device"""]		)
        self.assertEqual(model.batchnorm.running_mean.device,		lowerCamelCase__		)

        A			:	int										=       torch.randn(2,		3		)
        A			:	List[Any]										=       model(lowerCamelCase__		)
        self.assertEqual(output.device,		lowerCamelCase__		)

        # Removing hooks loads back the weights in the model.
        remove_hook_from_module(model.lineara		)
        remove_hook_from_module(model.batchnorm		)
        remove_hook_from_module(model.lineara		)
        self.assertEqual(model.lineara.weight.device,		torch.device("""cpu"""		)		)
        self.assertEqual(model.batchnorm.weight.device,		torch.device("""cpu"""		)		)
        self.assertEqual(model.lineara.weight.device,		torch.device("""cpu"""		)		)

        # Now test with buffers included in the offload
        A			:	int										=       {
            """execution_device""": 0 if torch.cuda.is_available() else """cpu""",
            """offload""": True,
            """offload_buffers""": True,
        }

        add_hook_to_module(model.lineara,		AlignDevicesHook(**lowerCamelCase__		)		)
        add_hook_to_module(model.batchnorm,		AlignDevicesHook(**lowerCamelCase__		)		)
        add_hook_to_module(model.lineara,		AlignDevicesHook(**lowerCamelCase__		)		)

        # Parameters have been offloaded, so on the meta device, buffers included
        self.assertEqual(model.lineara.weight.device,		torch.device("""meta"""		)		)
        self.assertEqual(model.batchnorm.weight.device,		torch.device("""meta"""		)		)
        self.assertEqual(model.lineara.weight.device,		torch.device("""meta"""		)		)
        self.assertEqual(model.batchnorm.running_mean.device,		torch.device("""meta"""		)		)

        A			:	int										=       torch.randn(2,		3		)
        A			:	str										=       model(lowerCamelCase__		)
        self.assertEqual(output.device,		lowerCamelCase__		)

        # Removing hooks loads back the weights in the model.
        remove_hook_from_module(model.lineara		)
        remove_hook_from_module(model.batchnorm		)
        remove_hook_from_module(model.lineara		)
        self.assertEqual(model.lineara.weight.device,		torch.device("""cpu"""		)		)
        self.assertEqual(model.batchnorm.weight.device,		torch.device("""cpu"""		)		)
        self.assertEqual(model.lineara.weight.device,		torch.device("""cpu"""		)		)






    def       _lowerCAmelCase (	self		):
        A			:	Any										=       ModelForTest()

        # Everything is on CPU
        self.assertEqual(model.lineara.weight.device,		torch.device("""cpu"""		)		)
        self.assertEqual(model.batchnorm.weight.device,		torch.device("""cpu"""		)		)
        self.assertEqual(model.lineara.weight.device,		torch.device("""cpu"""		)		)

        # This will move each submodule on different devices
        A			:	Tuple										=       0 if torch.cuda.is_available() else """cpu"""
        attach_align_device_hook(lowerCamelCase__,		execution_device=lowerCamelCase__,		offload=lowerCamelCase__		)

        # Parameters have been offloaded, so on the meta device
        self.assertEqual(model.lineara.weight.device,		torch.device("""meta"""		)		)
        self.assertEqual(model.batchnorm.weight.device,		torch.device("""meta"""		)		)
        self.assertEqual(model.lineara.weight.device,		torch.device("""meta"""		)		)
        # Buffers are not included in the offload by default, so are on the execution device
        A			:	Optional[int]										=       torch.device(lowerCamelCase__		)
        self.assertEqual(model.batchnorm.running_mean.device,		lowerCamelCase__		)

        A			:	List[str]										=       torch.randn(2,		3		)
        A			:	Optional[int]										=       model(lowerCamelCase__		)
        self.assertEqual(output.device,		lowerCamelCase__		)

        # Removing hooks loads back the weights in the model.
        remove_hook_from_submodules(lowerCamelCase__		)
        self.assertEqual(model.lineara.weight.device,		torch.device("""cpu"""		)		)
        self.assertEqual(model.batchnorm.weight.device,		torch.device("""cpu"""		)		)
        self.assertEqual(model.lineara.weight.device,		torch.device("""cpu"""		)		)

        # Now test with buffers included in the offload
        attach_align_device_hook(lowerCamelCase__,		execution_device=lowerCamelCase__,		offload=lowerCamelCase__,		offload_buffers=lowerCamelCase__		)

        # Parameters have been offloaded, so on the meta device, buffers included
        self.assertEqual(model.lineara.weight.device,		torch.device("""meta"""		)		)
        self.assertEqual(model.batchnorm.weight.device,		torch.device("""meta"""		)		)
        self.assertEqual(model.lineara.weight.device,		torch.device("""meta"""		)		)
        self.assertEqual(model.batchnorm.running_mean.device,		torch.device("""meta"""		)		)

        A			:	List[str]										=       torch.randn(2,		3		)
        A			:	List[str]										=       model(lowerCamelCase__		)
        self.assertEqual(output.device,		lowerCamelCase__		)

        # Removing hooks loads back the weights in the model.
        remove_hook_from_submodules(lowerCamelCase__		)
        self.assertEqual(model.lineara.weight.device,		torch.device("""cpu"""		)		)
        self.assertEqual(model.batchnorm.weight.device,		torch.device("""cpu"""		)		)
        self.assertEqual(model.lineara.weight.device,		torch.device("""cpu"""		)		)






    def       _lowerCAmelCase (	self		):
        A			:	int										=       ModelForTest()

        # Everything is on CPU
        self.assertEqual(model.lineara.weight.device,		torch.device("""cpu"""		)		)
        self.assertEqual(model.batchnorm.weight.device,		torch.device("""cpu"""		)		)
        self.assertEqual(model.lineara.weight.device,		torch.device("""cpu"""		)		)

        # This will move each submodule on different devices
        A			:	List[str]										=       0 if torch.cuda.is_available() else """cpu"""
        attach_align_device_hook(
            lowerCamelCase__,		execution_device=lowerCamelCase__,		offload=lowerCamelCase__,		weights_map=model.state_dict()		)

        # Parameters have been offloaded, so on the meta device
        self.assertEqual(model.lineara.weight.device,		torch.device("""meta"""		)		)
        self.assertEqual(model.batchnorm.weight.device,		torch.device("""meta"""		)		)
        self.assertEqual(model.lineara.weight.device,		torch.device("""meta"""		)		)
        # Buffers are not included in the offload by default, so are on the execution device
        A			:	Any										=       torch.device(lowerCamelCase__		)
        self.assertEqual(model.batchnorm.running_mean.device,		lowerCamelCase__		)

        A			:	Optional[Any]										=       torch.randn(2,		3		)
        A			:	Tuple										=       model(lowerCamelCase__		)
        self.assertEqual(output.device,		lowerCamelCase__		)

        # Removing hooks loads back the weights in the model.
        remove_hook_from_submodules(lowerCamelCase__		)
        self.assertEqual(model.lineara.weight.device,		torch.device("""cpu"""		)		)
        self.assertEqual(model.batchnorm.weight.device,		torch.device("""cpu"""		)		)
        self.assertEqual(model.lineara.weight.device,		torch.device("""cpu"""		)		)

        # Now test with buffers included in the offload
        attach_align_device_hook(
            lowerCamelCase__,		execution_device=lowerCamelCase__,		offload=lowerCamelCase__,		weights_map=model.state_dict(),		offload_buffers=lowerCamelCase__,		)

        # Parameters have been offloaded, so on the meta device, buffers included
        self.assertEqual(model.lineara.weight.device,		torch.device("""meta"""		)		)
        self.assertEqual(model.batchnorm.weight.device,		torch.device("""meta"""		)		)
        self.assertEqual(model.lineara.weight.device,		torch.device("""meta"""		)		)
        self.assertEqual(model.batchnorm.running_mean.device,		torch.device("""meta"""		)		)

        A			:	List[Any]										=       torch.randn(2,		3		)
        A			:	Dict										=       model(lowerCamelCase__		)
        self.assertEqual(output.device,		lowerCamelCase__		)

        # Removing hooks loads back the weights in the model.
        remove_hook_from_submodules(lowerCamelCase__		)
        self.assertEqual(model.lineara.weight.device,		torch.device("""cpu"""		)		)
        self.assertEqual(model.batchnorm.weight.device,		torch.device("""cpu"""		)		)
        self.assertEqual(model.lineara.weight.device,		torch.device("""cpu"""		)		)


