



'''simple docstring'''



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


lowerCamelCase	 =       logging.get_logger(__name__)  # pylint: disable=invalid-name

lowerCamelCase	 =       """
    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 _UpperCamelCase		(     A		):





				'''simple docstring'''





				lowerCAmelCase__					    =    42





class _UpperCamelCase		(     A		):





				'''simple docstring'''





				def __init__(							self  :  Dict  ,       _lowerCAmelCase  :  PriorTransformer  ,       _lowerCAmelCase  :  CLIPVisionModel  ,       _lowerCAmelCase  :  CLIPImageProcessor  ,       _lowerCAmelCase  :  HeunDiscreteScheduler  ,       _lowerCAmelCase  :  ShapERenderer  ,       ):







											'''simple docstring'''

											super().__init__()

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

				def 				__lowerCamelCase     (							self  :  List[Any]  ,       _lowerCAmelCase  :  Optional[Any]  ,       _lowerCAmelCase  :  str  ,       _lowerCAmelCase  :  Optional[Any]  ,       _lowerCAmelCase  :  List[Any]  ,       _lowerCAmelCase  :  int  ,       _lowerCAmelCase  :  str):







											'''simple docstring'''

											if latents is None:
																		__lowercase       	=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}""")
																		__lowercase       	=latents.to(_lowerCAmelCase)

											__lowercase       	=latents * scheduler.init_noise_sigma
											return latents

				def 				__lowerCamelCase     (							self  :  Optional[int]  ,       _lowerCAmelCase  :  List[Any]=0):







											'''simple docstring'''

											if is_accelerate_available():
																		from accelerate import cpu_offload
											else:
																		raise ImportError('Please install accelerate via `pip install accelerate`')

											__lowercase       	=torch.device(f"""cuda:{gpu_id}""")

											__lowercase       	=[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  :  Union[str, Any]):







											'''simple docstring'''

											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  :  List[str]  ,       _lowerCAmelCase  :  str  ,       _lowerCAmelCase  :  Union[str, Any]  ,       _lowerCAmelCase  :  List[str]  ,       _lowerCAmelCase  :  Optional[Any]  ,       ):







											'''simple docstring'''

											if isinstance(_lowerCAmelCase  ,       _lowerCAmelCase) and isinstance(image[0]  ,       torch.Tensor):
																		__lowercase       	=torch.cat(_lowerCAmelCase  ,       axis=0) if image[0].ndim == 4 else torch.stack(_lowerCAmelCase  ,       axis=0)

											if not isinstance(_lowerCAmelCase  ,       torch.Tensor):
																		__lowercase       	=self.image_processor(_lowerCAmelCase  ,       return_tensors='pt').pixel_values[0].unsqueeze(0)

											__lowercase       	=image.to(dtype=self.image_encoder.dtype  ,       device=_lowerCAmelCase)

											__lowercase       	=self.image_encoder(_lowerCAmelCase)['last_hidden_state']
											__lowercase       	=image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

											__lowercase       	=image_embeds.repeat_interleave(_lowerCAmelCase  ,       dim=0)

											if do_classifier_free_guidance:
																		__lowercase       	=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
																		__lowercase       	=torch.cat([negative_image_embeds, image_embeds])

											return image_embeds

				@torch.no_grad()
				@replace_example_docstring(_lowerCAmelCase)
				def __call__(							self  :  Any  ,       _lowerCAmelCase  :  Union[PIL.Image.Image, List[PIL.Image.Image]]  ,       _lowerCAmelCase  :  int = 1  ,       _lowerCAmelCase  :  int = 2_5  ,       _lowerCAmelCase  :  Optional[Union[torch.Generator, List[torch.Generator]]] = None  ,       _lowerCAmelCase  :  Optional[torch.FloatTensor] = None  ,       _lowerCAmelCase  :  float = 4.0  ,       _lowerCAmelCase  :  int = 6_4  ,       _lowerCAmelCase  :  Optional[str] = "pil"  ,       _lowerCAmelCase  :  bool = True  ,       ):







											'''simple docstring'''

											if isinstance(_lowerCAmelCase  ,       PIL.Image.Image):
																		__lowercase       	=1
											elif isinstance(_lowerCAmelCase  ,       torch.Tensor):
																		__lowercase       	=image.shape[0]
											elif isinstance(_lowerCAmelCase  ,       _lowerCAmelCase) and isinstance(image[0]  ,       (torch.Tensor, PIL.Image.Image)):
																		__lowercase       	=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)}""")

											__lowercase       	=self._execution_device

											__lowercase       	=batch_size * num_images_per_prompt

											__lowercase       	=guidance_scale > 1.0
											__lowercase       	=self._encode_image(_lowerCAmelCase  ,       _lowerCAmelCase  ,       _lowerCAmelCase  ,       _lowerCAmelCase)

											# prior

											self.scheduler.set_timesteps(_lowerCAmelCase  ,       device=_lowerCAmelCase)
											__lowercase       	=self.scheduler.timesteps

											__lowercase       	=self.prior.config.num_embeddings
											__lowercase       	=self.prior.config.embedding_dim

											__lowercase       	=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
											__lowercase       	=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
																		__lowercase       	=torch.cat([latents] * 2) if do_classifier_free_guidance else latents
																		__lowercase       	=self.scheduler.scale_model_input(_lowerCAmelCase  ,       _lowerCAmelCase)

																		__lowercase       	=self.prior(
																		    _lowerCAmelCase  ,       timestep=_lowerCAmelCase  ,       proj_embedding=_lowerCAmelCase  ,       ).predicted_image_embedding

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

																		if do_classifier_free_guidance is not None:
																									__lowercase	,				__lowercase       	=noise_pred.chunk(2)
																									__lowercase       	=noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

																		__lowercase       	=self.scheduler.step(
																		    _lowerCAmelCase  ,       timestep=_lowerCAmelCase  ,       sample=_lowerCAmelCase  ,       ).prev_sample

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

											__lowercase       	=[]
											for i, latent in enumerate(_lowerCAmelCase):
																		print()
																		__lowercase       	=self.renderer.decode(
																		    latent[None, :]  ,       _lowerCAmelCase  ,       size=_lowerCAmelCase  ,       ray_batch_size=4_0_9_6  ,       n_coarse_samples=6_4  ,       n_fine_samples=1_2_8  ,       )

																		images.append(_lowerCAmelCase)

											__lowercase       	=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}""")

											__lowercase       	=images.cpu().numpy()

											if output_type == "pil":
																		__lowercase       	=[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)








'''simple docstring'''



import argparse
import json
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from typing import List

import timm
import torch
import torch.nn as nn
from huggingface_hub import hf_hub_download
from torch import Tensor

from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification
from transformers.utils import logging


logging.set_verbosity_info()
lowerCamelCase	 =       logging.get_logger()





@dataclass
class _UpperCamelCase		:





				'''simple docstring'''





				lowerCAmelCase__					    =    42
				lowerCAmelCase__					    =    field(default_factory=A		)
				lowerCAmelCase__					    =    field(default_factory=A		)

				def 				__lowerCamelCase     (							self  :  int  ,       _lowerCAmelCase  :  List[Any]  ,       _lowerCAmelCase  :  Tensor  ,       _lowerCAmelCase  :  Tensor):







											'''simple docstring'''

											__lowercase       	=len(list(m.modules())) == 1 or isinstance(_lowerCAmelCase  ,       nn.Convad) or isinstance(_lowerCAmelCase  ,       nn.BatchNormad)
											if has_not_submodules:
																		self.traced.append(_lowerCAmelCase)

				def __call__(							self  :  Dict  ,       _lowerCAmelCase  :  Tensor):







											'''simple docstring'''

											for m in self.module.modules():
																		self.handles.append(m.register_forward_hook(self._forward_hook))
											self.module(_lowerCAmelCase)
											[x.remove() for x in self.handles]
											return self

				@property
				def 				__lowerCamelCase     (							self  :  Any):







											'''simple docstring'''

											return list(filter(lambda _lowerCAmelCase: len(list(x.state_dict().keys())) > 0  ,       self.traced))





@dataclass
class _UpperCamelCase		:





				'''simple docstring'''





				lowerCAmelCase__					    =    42
				lowerCAmelCase__					    =    42
				lowerCAmelCase__					    =    0
				lowerCAmelCase__					    =    field(default_factory=A		)
				lowerCAmelCase__					    =    field(default_factory=A		)

				def __call__(							self  :  Any  ,       _lowerCAmelCase  :  Tensor):







											'''simple docstring'''

											__lowercase       	=Tracker(self.dest)(_lowerCAmelCase).parametrized
											__lowercase       	=Tracker(self.src)(_lowerCAmelCase).parametrized

											__lowercase       	=list(filter(lambda _lowerCAmelCase: type(_lowerCAmelCase) not in self.src_skip  ,       _lowerCAmelCase))
											__lowercase       	=list(filter(lambda _lowerCAmelCase: type(_lowerCAmelCase) not in self.dest_skip  ,       _lowerCAmelCase))

											if len(_lowerCAmelCase) != len(_lowerCAmelCase):
																		raise Exception(
																		    f"""Numbers of operations are different. Source module has {len(_lowerCAmelCase)} operations while"""
																		    f""" destination module has {len(_lowerCAmelCase)}.""")

											for dest_m, src_m in zip(_lowerCAmelCase  ,       _lowerCAmelCase):
																		dest_m.load_state_dict(src_m.state_dict())
																		if self.verbose == 1:
																									print(f"""Transfered from={src_m} to={dest_m}""")



def   _A       (   _lowerCAmelCase  ,   _lowerCAmelCase  ,   _lowerCAmelCase  ,   _lowerCAmelCase = True					):



							"""simple docstring"""



							print(f"""Converting {name}..."""					)
							with torch.no_grad():
														__lowercase       	=timm.create_model(_lowerCAmelCase  ,   pretrained=_lowerCAmelCase					).eval()
														__lowercase       	=ResNetForImageClassification(_lowerCAmelCase					).eval()
														__lowercase       	=ModuleTransfer(src=_lowerCAmelCase  ,   dest=_lowerCAmelCase					)
														__lowercase       	=torch.randn((1, 3, 224, 224)					)
														module_transfer(_lowerCAmelCase					)

							assert torch.allclose(from_model(_lowerCAmelCase					)  ,   our_model(_lowerCAmelCase					).logits					), "The model logits don't match the original one."

							__lowercase       	=f"""resnet{'-'.join(name.split('resnet'					)					)}"""
							print(_lowerCAmelCase					)

							if push_to_hub:
														our_model.push_to_hub(
														    repo_path_or_name=save_directory / checkpoint_name  ,   commit_message='Add model'  ,   use_temp_dir=_lowerCAmelCase  ,   )

														# we can use the convnext one
														__lowercase       	=AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k'					)
														image_processor.push_to_hub(
														    repo_path_or_name=save_directory / checkpoint_name  ,   commit_message='Add image processor'  ,   use_temp_dir=_lowerCAmelCase  ,   )

														print(f"""Pushed {checkpoint_name}"""					)



def   _A       (   _lowerCAmelCase  ,   _lowerCAmelCase = None  ,   _lowerCAmelCase = True					):



							"""simple docstring"""



							__lowercase       	='imagenet-1k-id2label.json'
							__lowercase       	=1_000
							__lowercase       	=(1, num_labels)

							__lowercase       	='huggingface/label-files'
							__lowercase       	=num_labels
							__lowercase       	=json.load(open(hf_hub_download(_lowerCAmelCase  ,   _lowerCAmelCase  ,   repo_type='dataset'					)  ,   'r'					)					)
							__lowercase       	={int(_lowerCAmelCase					): v for k, v in idalabel.items()}

							__lowercase       	=idalabel
							__lowercase       	={v: k for k, v in idalabel.items()}

							__lowercase       	=partial(_lowerCAmelCase  ,   num_labels=_lowerCAmelCase  ,   idalabel=_lowerCAmelCase  ,   labelaid=_lowerCAmelCase					)

							__lowercase       	={
							    'resnet18': ImageNetPreTrainedConfig(
							        depths=[2, 2, 2, 2]  ,   hidden_sizes=[64, 128, 256, 512]  ,   layer_type='basic'					),
							    'resnet26': ImageNetPreTrainedConfig(
							        depths=[2, 2, 2, 2]  ,   hidden_sizes=[256, 512, 1_024, 2_048]  ,   layer_type='bottleneck'					),
							    'resnet34': ImageNetPreTrainedConfig(
							        depths=[3, 4, 6, 3]  ,   hidden_sizes=[64, 128, 256, 512]  ,   layer_type='basic'					),
							    'resnet50': ImageNetPreTrainedConfig(
							        depths=[3, 4, 6, 3]  ,   hidden_sizes=[256, 512, 1_024, 2_048]  ,   layer_type='bottleneck'					),
							    'resnet101': ImageNetPreTrainedConfig(
							        depths=[3, 4, 23, 3]  ,   hidden_sizes=[256, 512, 1_024, 2_048]  ,   layer_type='bottleneck'					),
							    'resnet152': ImageNetPreTrainedConfig(
							        depths=[3, 8, 36, 3]  ,   hidden_sizes=[256, 512, 1_024, 2_048]  ,   layer_type='bottleneck'					),
							}

							if model_name:
														convert_weight_and_push(_lowerCAmelCase  ,   names_to_config[model_name]  ,   _lowerCAmelCase  ,   _lowerCAmelCase					)
							else:
														for model_name, config in names_to_config.items():
																					convert_weight_and_push(_lowerCAmelCase  ,   _lowerCAmelCase  ,   _lowerCAmelCase  ,   _lowerCAmelCase					)
							return config, expected_shape


if __name__ == "__main__":
		lowerCamelCase	 =       argparse.ArgumentParser()
		# Required parameters
		parser.add_argument(
		    """--model_name""",
		    default=None,
		    type=str,
		    help=(
		        """The name of the model you wish to convert, it must be one of the supported resnet* architecture,"""
		        """ currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted."""
		    ),
		)
		parser.add_argument(
		    """--pytorch_dump_folder_path""",
		    default=None,
		    type=Path,
		    required=True,
		    help="""Path to the output PyTorch model directory.""",
		)
		parser.add_argument(
		    """--push_to_hub""",
		    default=True,
		    type=bool,
		    required=False,
		    help="""If True, push model and image processor to the hub.""",
		)

		lowerCamelCase	 =       parser.parse_args()
		lowerCamelCase	 =       args.pytorch_dump_folder_path
		pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True)
		convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)



