


'''simple docstring'''
import argparse
import math
import os

import torch
from neural_compressor.utils.pytorch import load
from PIL import Image
from transformers import CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, StableDiffusionPipeline, UNetaDConditionModel


def 			a      (			)  ->	Any:



					'''simple docstring'''






					UpperCamelCase__   :List[str]												= argparse.ArgumentParser()
					parser.add_argument(
					    '''-m''' ,					'''--pretrained_model_name_or_path''' ,					type=snake_case_ ,					default=snake_case_ ,					required=snake_case_ ,					help='''Path to pretrained model or model identifier from huggingface.co/models.''' ,					)
					parser.add_argument(
					    '''-c''' ,					'''--caption''' ,					type=snake_case_ ,					default='''robotic cat with wings''' ,					help='''Text used to generate images.''' ,					)
					parser.add_argument(
					    '''-n''' ,					'''--images_num''' ,					type=snake_case_ ,					default=4 ,					help='''How much images to generate.''' ,					)
					parser.add_argument(
					    '''-s''' ,					'''--seed''' ,					type=snake_case_ ,					default=42 ,					help='''Seed for random process.''' ,					)
					parser.add_argument(
					    '''-ci''' ,					'''--cuda_id''' ,					type=snake_case_ ,					default=0 ,					help='''cuda_id.''' ,					)
					UpperCamelCase__   :int												= parser.parse_args()
					return args


def 			a      (			__a ,					__a ,					__a   )  ->	str:



					'''simple docstring'''






					if not len(snake_case_   ) == rows * cols:
										raise ValueError('''The specified number of rows and columns are not correct.'''   )

					UpperCamelCase__					,				UpperCamelCase__   :Union[str, Any]												= imgs[0].size
					UpperCamelCase__   :Tuple												= Image.new('''RGB''' ,					size=(cols * w, rows * h)   )
					UpperCamelCase__					,				UpperCamelCase__   :str												= grid.size

					for i, img in enumerate(snake_case_   ):
										grid.paste(snake_case_ ,					box=(i % cols * w, i // cols * h)   )
					return grid


def 			a      (			__a ,					__a="robotic cat with wings" ,					__a=7.5 ,					__a=50 ,					__a=1 ,					__a=42 ,					)  ->	Optional[int]:



					'''simple docstring'''






					UpperCamelCase__   :Optional[Any]												= torch.Generator(pipeline.device   ).manual_seed(snake_case_   )
					UpperCamelCase__   :Optional[Any]												= pipeline(
					    snake_case_ ,					guidance_scale=snake_case_ ,					num_inference_steps=snake_case_ ,					generator=snake_case_ ,					num_images_per_prompt=snake_case_ ,					).images
					UpperCamelCase__   :List[Any]												= int(math.sqrt(snake_case_   )   )
					UpperCamelCase__   :str												= image_grid(snake_case_ ,					rows=_rows ,					cols=num_images_per_prompt // _rows   )
					return grid, images


__snake_case							      =     parse_args()
# Load models and create wrapper for stable diffusion
__snake_case							      =     CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder='''tokenizer''')
__snake_case							      =     CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder='''text_encoder''')
__snake_case							      =     AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder='''vae''')
__snake_case							      =     UNetaDConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder='''unet''')

__snake_case							      =     StableDiffusionPipeline.from_pretrained(
    args.pretrained_model_name_or_path, text_encoder=text_encoder, vae=vae, unet=unet, tokenizer=tokenizer
)
__snake_case							      =     lambda images, clip_input: (images, False)
if os.path.exists(os.path.join(args.pretrained_model_name_or_path, '''best_model.pt''')):
		__snake_case							      =     load(args.pretrained_model_name_or_path, model=unet)
		unet.eval()
		setattr(pipeline, '''unet''', unet)
else:
		__snake_case							      =     unet.to(torch.device('''cuda''', args.cuda_id))
__snake_case							      =     pipeline.to(unet.device)
__snake_case							      =     generate_images(pipeline, prompt=args.caption, num_images_per_prompt=args.images_num, seed=args.seed)
grid.save(os.path.join(args.pretrained_model_name_or_path, '''{}.png'''.format('''_'''.join(args.caption.split()))))
__snake_case							      =     os.path.join(args.pretrained_model_name_or_path, '''_'''.join(args.caption.split()))
os.makedirs(dirname, exist_ok=True)
for idx, image in enumerate(images):
		image.save(os.path.join(dirname, '''{}.png'''.format(idx + 1)))
'''simple docstring'''

from typing import Optional, Tuple, Union

import flax
import flax.linen as nn
import jax
import jax.numpy as jnp
from flax.core.frozen_dict import FrozenDict

from ..configuration_utils import ConfigMixin, flax_register_to_config
from ..utils import BaseOutput
from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps
from .modeling_flax_utils import FlaxModelMixin
from .unet_ad_blocks_flax import (
    FlaxCrossAttnDownBlockaD,
    FlaxCrossAttnUpBlockaD,
    FlaxDownBlockaD,
    FlaxUNetMidBlockaDCrossAttn,
    FlaxUpBlockaD,
)







@flax.struct.dataclass
class 				_lowercase     (				UpperCAmelCase__			):


 '''simple docstring'''






 _SCREAMING_SNAKE_CASE     :       jnp.ndarray







@flax_register_to_config
class 				_lowercase     (				nn.Module  ,							UpperCAmelCase__  ,							UpperCAmelCase__			):


 '''simple docstring'''






 _SCREAMING_SNAKE_CASE     :       int      	=					32
 _SCREAMING_SNAKE_CASE     :       int      	=					4
 _SCREAMING_SNAKE_CASE     :       int      	=					4
 _SCREAMING_SNAKE_CASE     :       Tuple[str]      	=					(
     "CrossAttnDownBlock2D",
     "CrossAttnDownBlock2D",
     "CrossAttnDownBlock2D",
     "DownBlock2D",
 )
 _SCREAMING_SNAKE_CASE     :       Tuple[str]      	=					("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")
 _SCREAMING_SNAKE_CASE     :       Union[bool, Tuple[bool]]      	=					False
 _SCREAMING_SNAKE_CASE     :       Tuple[int]      	=					(320, 640, 1280, 1280)
 _SCREAMING_SNAKE_CASE     :       int      	=					2
 _SCREAMING_SNAKE_CASE     :       Union[int, Tuple[int]]      	=					8
 _SCREAMING_SNAKE_CASE     :       Optional[Union[int, Tuple[int]]]      	=					None
 _SCREAMING_SNAKE_CASE     :       int      	=					1280
 _SCREAMING_SNAKE_CASE     :       float      	=					0.0
 _SCREAMING_SNAKE_CASE     :       bool      	=					False
 _SCREAMING_SNAKE_CASE     :       jnp.dtype      	=					jnp.floataa
 _SCREAMING_SNAKE_CASE     :       bool      	=					True
 _SCREAMING_SNAKE_CASE     :       int      	=					0
 _SCREAMING_SNAKE_CASE     :       bool      	=					False
 def a					(      self   :	Dict      ,       SCREAMING_SNAKE_CASE__   :	jax.random.KeyArray							)  ->    FrozenDict:
  # init input tensors
  __lowerCAmelCase											=						(1, self.in_channels, self.sample_size, self.sample_size)
  __lowerCAmelCase											=						jnp.zeros(SCREAMING_SNAKE_CASE__      ,       dtype=jnp.floataa							)
  __lowerCAmelCase											=						jnp.ones((1,)      ,       dtype=jnp.intaa							)
  __lowerCAmelCase											=						jnp.zeros((1, 1, self.cross_attention_dim)      ,       dtype=jnp.floataa							)

  __lowerCAmelCase							,       __lowerCAmelCase											=						jax.random.split(SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase											=						{"""params""": params_rng, """dropout""": dropout_rng}

  return self.init(SCREAMING_SNAKE_CASE__      ,       SCREAMING_SNAKE_CASE__      ,       SCREAMING_SNAKE_CASE__      ,       SCREAMING_SNAKE_CASE__							)["params"]
 def a					(      self   :	int							)  ->    List[str]:
  __lowerCAmelCase											=						self.block_out_channels
  __lowerCAmelCase											=						block_out_channels[0] * 4

  if self.num_attention_heads is not None:
   raise ValueError(
       """At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19."""							)

  # If `num_attention_heads` is not defined (which is the case for most models)
  # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
  # The reason for this behavior is to correct for incorrectly named variables that were introduced
  # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
  # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
  # which is why we correct for the naming here.
  __lowerCAmelCase											=						self.num_attention_heads or self.attention_head_dim

  # input
  __lowerCAmelCase											=						nn.Conv(
      block_out_channels[0]      ,       kernel_size=(3, 3)      ,       strides=(1, 1)      ,       padding=((1, 1), (1, 1))      ,       dtype=self.dtype      ,       )

  # time
  __lowerCAmelCase											=						FlaxTimesteps(
      block_out_channels[0]      ,       flip_sin_to_cos=self.flip_sin_to_cos      ,       freq_shift=self.config.freq_shift							)
  __lowerCAmelCase											=						FlaxTimestepEmbedding(SCREAMING_SNAKE_CASE__      ,       dtype=self.dtype							)

  __lowerCAmelCase											=						self.only_cross_attention
  if isinstance(SCREAMING_SNAKE_CASE__      ,       SCREAMING_SNAKE_CASE__							):
   __lowerCAmelCase											=						(only_cross_attention,) * len(self.down_block_types							)

  if isinstance(SCREAMING_SNAKE_CASE__      ,       SCREAMING_SNAKE_CASE__							):
   __lowerCAmelCase											=						(num_attention_heads,) * len(self.down_block_types							)

  # down
  __lowerCAmelCase											=						[]
  __lowerCAmelCase											=						block_out_channels[0]
  for i, down_block_type in enumerate(self.down_block_types							):
   __lowerCAmelCase											=						output_channel
   __lowerCAmelCase											=						block_out_channels[i]
   __lowerCAmelCase											=						i == len(SCREAMING_SNAKE_CASE__							) - 1

   if down_block_type == "CrossAttnDownBlock2D":
    __lowerCAmelCase											=						FlaxCrossAttnDownBlockaD(
        in_channels=SCREAMING_SNAKE_CASE__      ,       out_channels=SCREAMING_SNAKE_CASE__      ,       dropout=self.dropout      ,       num_layers=self.layers_per_block      ,       num_attention_heads=num_attention_heads[i]      ,       add_downsample=not is_final_block      ,       use_linear_projection=self.use_linear_projection      ,       only_cross_attention=only_cross_attention[i]      ,       use_memory_efficient_attention=self.use_memory_efficient_attention      ,       dtype=self.dtype      ,       )
   else:
    __lowerCAmelCase											=						FlaxDownBlockaD(
        in_channels=SCREAMING_SNAKE_CASE__      ,       out_channels=SCREAMING_SNAKE_CASE__      ,       dropout=self.dropout      ,       num_layers=self.layers_per_block      ,       add_downsample=not is_final_block      ,       dtype=self.dtype      ,       )

   down_blocks.append(SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase											=						down_blocks

  # mid
  __lowerCAmelCase											=						FlaxUNetMidBlockaDCrossAttn(
      in_channels=block_out_channels[-1]      ,       dropout=self.dropout      ,       num_attention_heads=num_attention_heads[-1]      ,       use_linear_projection=self.use_linear_projection      ,       use_memory_efficient_attention=self.use_memory_efficient_attention      ,       dtype=self.dtype      ,       )

  # up
  __lowerCAmelCase											=						[]
  __lowerCAmelCase											=						list(reversed(SCREAMING_SNAKE_CASE__							)							)
  __lowerCAmelCase											=						list(reversed(SCREAMING_SNAKE_CASE__							)							)
  __lowerCAmelCase											=						list(reversed(SCREAMING_SNAKE_CASE__							)							)
  __lowerCAmelCase											=						reversed_block_out_channels[0]
  for i, up_block_type in enumerate(self.up_block_types							):
   __lowerCAmelCase											=						output_channel
   __lowerCAmelCase											=						reversed_block_out_channels[i]
   __lowerCAmelCase											=						reversed_block_out_channels[min(i + 1      ,       len(SCREAMING_SNAKE_CASE__							) - 1							)]

   __lowerCAmelCase											=						i == len(SCREAMING_SNAKE_CASE__							) - 1

   if up_block_type == "CrossAttnUpBlock2D":
    __lowerCAmelCase											=						FlaxCrossAttnUpBlockaD(
        in_channels=SCREAMING_SNAKE_CASE__      ,       out_channels=SCREAMING_SNAKE_CASE__      ,       prev_output_channel=SCREAMING_SNAKE_CASE__      ,       num_layers=self.layers_per_block + 1      ,       num_attention_heads=reversed_num_attention_heads[i]      ,       add_upsample=not is_final_block      ,       dropout=self.dropout      ,       use_linear_projection=self.use_linear_projection      ,       only_cross_attention=only_cross_attention[i]      ,       use_memory_efficient_attention=self.use_memory_efficient_attention      ,       dtype=self.dtype      ,       )
   else:
    __lowerCAmelCase											=						FlaxUpBlockaD(
        in_channels=SCREAMING_SNAKE_CASE__      ,       out_channels=SCREAMING_SNAKE_CASE__      ,       prev_output_channel=SCREAMING_SNAKE_CASE__      ,       num_layers=self.layers_per_block + 1      ,       add_upsample=not is_final_block      ,       dropout=self.dropout      ,       dtype=self.dtype      ,       )

   up_blocks.append(SCREAMING_SNAKE_CASE__							)
   __lowerCAmelCase											=						output_channel
  __lowerCAmelCase											=						up_blocks

  # out
  __lowerCAmelCase											=						nn.GroupNorm(num_groups=32      ,       epsilon=1e-5							)
  __lowerCAmelCase											=						nn.Conv(
      self.out_channels      ,       kernel_size=(3, 3)      ,       strides=(1, 1)      ,       padding=((1, 1), (1, 1))      ,       dtype=self.dtype      ,       )





 def __call__(      self   :	Dict      ,       SCREAMING_SNAKE_CASE__   :	int      ,       SCREAMING_SNAKE_CASE__   :	Tuple      ,       SCREAMING_SNAKE_CASE__   :	Union[str, Any]      ,       SCREAMING_SNAKE_CASE__   :	Optional[Any]=None      ,       SCREAMING_SNAKE_CASE__   :	List[str]=None      ,       SCREAMING_SNAKE_CASE__   :	bool = True      ,       SCREAMING_SNAKE_CASE__   :	bool = False      ,       )  ->    Union[FlaxUNetaDConditionOutput, Tuple]:
  # 1. time
  if not isinstance(SCREAMING_SNAKE_CASE__      ,       jnp.ndarray							):
   __lowerCAmelCase											=						jnp.array([timesteps]      ,       dtype=jnp.intaa							)
  elif isinstance(SCREAMING_SNAKE_CASE__      ,       jnp.ndarray							) and len(timesteps.shape							) == 0:
   __lowerCAmelCase											=						timesteps.astype(dtype=jnp.floataa							)
   __lowerCAmelCase											=						jnp.expand_dims(SCREAMING_SNAKE_CASE__      ,       0							)

  __lowerCAmelCase											=						self.time_proj(SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase											=						self.time_embedding(SCREAMING_SNAKE_CASE__							)

  # 2. pre-process
  __lowerCAmelCase											=						jnp.transpose(SCREAMING_SNAKE_CASE__      ,       (0, 2, 3, 1)							)
  __lowerCAmelCase											=						self.conv_in(SCREAMING_SNAKE_CASE__							)

  # 3. down
  __lowerCAmelCase											=						(sample,)
  for down_block in self.down_blocks:
   if isinstance(SCREAMING_SNAKE_CASE__      ,       SCREAMING_SNAKE_CASE__							):
    __lowerCAmelCase							,       __lowerCAmelCase											=						down_block(SCREAMING_SNAKE_CASE__      ,       SCREAMING_SNAKE_CASE__      ,       SCREAMING_SNAKE_CASE__      ,       deterministic=not train							)
   else:
    __lowerCAmelCase							,       __lowerCAmelCase											=						down_block(SCREAMING_SNAKE_CASE__      ,       SCREAMING_SNAKE_CASE__      ,       deterministic=not train							)
   down_block_res_samples += res_samples

  if down_block_additional_residuals is not None:
   __lowerCAmelCase											=						()

   for down_block_res_sample, down_block_additional_residual in zip(
       SCREAMING_SNAKE_CASE__      ,       SCREAMING_SNAKE_CASE__							):
    down_block_res_sample += down_block_additional_residual
    new_down_block_res_samples += (down_block_res_sample,)

   __lowerCAmelCase											=						new_down_block_res_samples

  # 4. mid
  __lowerCAmelCase											=						self.mid_block(SCREAMING_SNAKE_CASE__      ,       SCREAMING_SNAKE_CASE__      ,       SCREAMING_SNAKE_CASE__      ,       deterministic=not train							)

  if mid_block_additional_residual is not None:
   sample += mid_block_additional_residual

  # 5. up
  for up_block in self.up_blocks:
   __lowerCAmelCase											=						down_block_res_samples[-(self.layers_per_block + 1) :]
   __lowerCAmelCase											=						down_block_res_samples[: -(self.layers_per_block + 1)]
   if isinstance(SCREAMING_SNAKE_CASE__      ,       SCREAMING_SNAKE_CASE__							):
    __lowerCAmelCase											=						up_block(
        SCREAMING_SNAKE_CASE__      ,       temb=SCREAMING_SNAKE_CASE__      ,       encoder_hidden_states=SCREAMING_SNAKE_CASE__      ,       res_hidden_states_tuple=SCREAMING_SNAKE_CASE__      ,       deterministic=not train      ,       )
   else:
    __lowerCAmelCase											=						up_block(SCREAMING_SNAKE_CASE__      ,       temb=SCREAMING_SNAKE_CASE__      ,       res_hidden_states_tuple=SCREAMING_SNAKE_CASE__      ,       deterministic=not train							)

        # 6. post-process
  __lowerCAmelCase											=						self.conv_norm_out(SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase											=						nn.silu(SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase											=						self.conv_out(SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase											=						jnp.transpose(SCREAMING_SNAKE_CASE__      ,       (0, 3, 1, 2)							)

  if not return_dict:
   return (sample,)

  return FlaxUNetaDConditionOutput(sample=SCREAMING_SNAKE_CASE__							)






