


import inspect
from typing import List, Optional, Tuple, Union

import numpy as np
import PIL
import torch
import torch.utils.checkpoint

from ...models import UNetaDModel, VQModel
from ...schedulers import (
    DDIMScheduler,
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
)
from ...utils import PIL_INTERPOLATION, randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput





def   _UpperCAmelCase       (     UpperCAmelCase      :			Any      ):
      """simple docstring"""




      __lowerCamelCase     :      int       						=						image.size
      __lowerCamelCase     :      str       						=						(x - x % 32 for x in (w, h))  # resize to integer multiple of 32
      __lowerCamelCase     :      Dict       						=						image.resize((w, h)						,	resample=PIL_INTERPOLATION["""lanczos"""]      )
      __lowerCamelCase     :      int       						=						np.array(UpperCAmelCase      ).astype(np.floataa      ) / 2_5_5.0
      __lowerCamelCase     :      Dict       						=						image[None].transpose(0						,	3						,	1						,	2      )
      __lowerCamelCase     :      Optional[int]       						=						torch.from_numpy(UpperCAmelCase      )
      return 2.0 * image - 1.0




class 							_UpperCamelCase (						UpperCamelCase_						):

   '''simple docstring'''







   def __init__(  self  : Tuple       ,  _lowerCamelCase  : List[Any]       ,  _lowerCamelCase  : str       ,  _lowerCamelCase  : Union[str, Any]       ,  ):






         '''simple docstring'''



         super().__init__()
         self.register_modules(vqvae=__a       ,  unet=__a       ,  scheduler=__a							)


   @torch.no_grad()
   def __call__(  self  : List[Any]       ,  _lowerCamelCase  : Union[str, Any] = None       ,  _lowerCamelCase  : Any = 1       ,  _lowerCamelCase  : List[Any] = 1_0_0       ,  _lowerCamelCase  : List[Any] = 0.0       ,  _lowerCamelCase  : List[str] = None       ,  _lowerCamelCase  : Optional[Any] = "pil"       ,  _lowerCamelCase  : Tuple = True       ,  ):






         '''simple docstring'''



         if isinstance(__a       ,  PIL.Image.Image							):
               __lowerCamelCase     :      Optional[int]       						=						1
         elif isinstance(__a       ,  torch.Tensor							):
               __lowerCamelCase     :      int       						=						image.shape[0]
         else:
               raise ValueError(F"""`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(__a							)}"""							)

         if isinstance(__a       ,  PIL.Image.Image							):
               __lowerCamelCase     :      Any       						=						preprocess(__a							)

         __lowerCamelCase     :      List[str]       						=						image.shape[-2:]

         # in_channels should be 6: 3 for latents, 3 for low resolution image
         __lowerCamelCase     :      List[str]       						=						(batch_size, self.unet.config.in_channels // 2, height, width)
         __lowerCamelCase     :      Optional[Any]       						=						next(self.unet.parameters()							).dtype

         __lowerCamelCase     :      Tuple       						=						randn_tensor(__a       ,  generator=__a       ,  device=self.device       ,  dtype=__a							)

         __lowerCamelCase     :      Optional[int]       						=						image.to(device=self.device       ,  dtype=__a							)

         # set timesteps and move to the correct device
         self.scheduler.set_timesteps(__a       ,  device=self.device							)
         __lowerCamelCase     :      Optional[int]       						=						self.scheduler.timesteps

         # scale the initial noise by the standard deviation required by the scheduler
         __lowerCamelCase     :      str       						=						latents * self.scheduler.init_noise_sigma

         # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature.
         # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
         # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
         # and should be between [0, 1]
         __lowerCamelCase     :      List[Any]       						=						'eta' in set(inspect.signature(self.scheduler.step							).parameters.keys()							)
         __lowerCamelCase     :      Optional[Any]       						=						{}
         if accepts_eta:
               __lowerCamelCase     :      List[str]       						=						eta

         for t in self.progress_bar(__a							):
               # concat latents and low resolution image in the channel dimension.
               __lowerCamelCase     :      Optional[Any]       						=						torch.cat([latents, image]       ,  dim=1							)
               __lowerCamelCase     :      Any       						=						self.scheduler.scale_model_input(__a       ,  __a							)
               # predict the noise residual
               __lowerCamelCase     :      Optional[Any]       						=						self.unet(__a       ,  __a							).sample
               # compute the previous noisy sample x_t -> x_t-1
               __lowerCamelCase     :      List[str]       						=						self.scheduler.step(__a       ,  __a       ,  __a       ,  **__a							).prev_sample

         # decode the image latents with the VQVAE
         __lowerCamelCase     :      Tuple       						=						self.vqvae.decode(__a							).sample
         __lowerCamelCase     :      Any       						=						torch.clamp(__a       ,  -1.0       ,  1.0							)
         __lowerCamelCase     :      Dict       						=						image / 2 + 0.5
         __lowerCamelCase     :      List[str]       						=						image.cpu().permute(0       ,  2       ,  3       ,  1							).numpy()

         if output_type == "pil":
               __lowerCamelCase     :      Optional[int]       						=						self.numpy_to_pil(__a							)

         if not return_dict:
               return (image,)

         return ImagePipelineOutput(images=__a							)







from ...configuration_utils import PretrainedConfig
from ...utils import logging


__UpperCamelCase    :						Tuple     =							logging.get_logger(__name__)

__UpperCamelCase    :						Any     =							{
    'facebook/nllb-moe-54B': 'https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json',
}



class 							_UpperCamelCase (						A						):

   '''simple docstring'''







   a_				:							int    = "nllb-moe"
   a_				:							Optional[int]    = ["past_key_values"]
   a_				:							Optional[Any]    = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}

   def __init__(  self  : int       ,  _lowerCamelCase  : Union[str, Any]=1_2_8_1_1_2       ,  _lowerCamelCase  : List[str]=1_0_2_4       ,  _lowerCamelCase  : Optional[int]=1_2       ,  _lowerCamelCase  : int=4_0_9_6       ,  _lowerCamelCase  : Union[str, Any]=1_6       ,  _lowerCamelCase  : int=1_2       ,  _lowerCamelCase  : Optional[int]=4_0_9_6       ,  _lowerCamelCase  : Any=1_6       ,  _lowerCamelCase  : Any=0.05       ,  _lowerCamelCase  : List[Any]=0.05       ,  _lowerCamelCase  : Tuple=True       ,  _lowerCamelCase  : Any=True       ,  _lowerCamelCase  : Optional[int]="relu"       ,  _lowerCamelCase  : Dict=1_0_2_4       ,  _lowerCamelCase  : Optional[int]=0.1       ,  _lowerCamelCase  : Optional[int]=0.1       ,  _lowerCamelCase  : Optional[int]=0.0       ,  _lowerCamelCase  : List[Any]=0.02       ,  _lowerCamelCase  : List[str]=2       ,  _lowerCamelCase  : List[str]=True       ,  _lowerCamelCase  : Union[str, Any]=False       ,  _lowerCamelCase  : Optional[Any]="float32"       ,  _lowerCamelCase  : Union[str, Any]=False       ,  _lowerCamelCase  : Tuple=1_2_8       ,  _lowerCamelCase  : Dict=6_4       ,  _lowerCamelCase  : Any=4       ,  _lowerCamelCase  : List[Any]=4       ,  _lowerCamelCase  : str=0.001       ,  _lowerCamelCase  : Dict=0.001       ,  _lowerCamelCase  : Any="all"       ,  _lowerCamelCase  : Optional[Any]=False       ,  _lowerCamelCase  : List[Any]=False       ,  _lowerCamelCase  : Optional[Any]=1.0       ,  _lowerCamelCase  : List[str]=0.2       ,  _lowerCamelCase  : List[Any]=1       ,  _lowerCamelCase  : str=0       ,  _lowerCamelCase  : int=2       ,  _lowerCamelCase  : int=False       ,  **_lowerCamelCase  : List[str]       ,  ):






         '''simple docstring'''



         __lowerCamelCase     :      Optional[Any]       						=						vocab_size
         __lowerCamelCase     :      str       						=						max_position_embeddings
         __lowerCamelCase     :      int       						=						d_model
         __lowerCamelCase     :      Optional[Any]       						=						encoder_ffn_dim
         __lowerCamelCase     :      str       						=						encoder_layers
         __lowerCamelCase     :      Tuple       						=						encoder_attention_heads
         __lowerCamelCase     :      Union[str, Any]       						=						decoder_ffn_dim
         __lowerCamelCase     :      Dict       						=						decoder_layers
         __lowerCamelCase     :      Any       						=						decoder_attention_heads
         __lowerCamelCase     :      Union[str, Any]       						=						dropout
         __lowerCamelCase     :      Dict       						=						attention_dropout
         __lowerCamelCase     :      int       						=						activation_dropout
         __lowerCamelCase     :      Union[str, Any]       						=						activation_function
         __lowerCamelCase     :      Optional[int]       						=						init_std
         __lowerCamelCase     :      Union[str, Any]       						=						encoder_layerdrop
         __lowerCamelCase     :      Dict       						=						decoder_layerdrop
         __lowerCamelCase     :      List[str]       						=						use_cache
         __lowerCamelCase     :      Any       						=						encoder_layers
         __lowerCamelCase     :      List[Any]       						=						scale_embedding  # scale factor will be sqrt(d_model) if True
         __lowerCamelCase     :      Optional[Any]       						=						router_z_loss_coef
         __lowerCamelCase     :      Union[str, Any]       						=						router_aux_loss_coef
         __lowerCamelCase     :      Dict       						=						decoder_sparse_step
         __lowerCamelCase     :      Optional[int]       						=						encoder_sparse_step
         __lowerCamelCase     :      Any       						=						num_experts
         __lowerCamelCase     :      int       						=						expert_capacity
         __lowerCamelCase     :      Dict       						=						router_bias
         if router_dtype not in ["float32", "float16", "bfloat16"]:
               raise ValueError(F"""`router_dtype` must be one of 'float32', 'float16' or 'bfloat16', got {router_dtype}"""							)
         __lowerCamelCase     :      Tuple       						=						router_dtype

         __lowerCamelCase     :      Dict       						=						router_ignore_padding_tokens
         __lowerCamelCase     :      str       						=						batch_prioritized_routing
         __lowerCamelCase     :      List[str]       						=						second_expert_policy
         __lowerCamelCase     :      Tuple       						=						normalize_router_prob_before_dropping
         __lowerCamelCase     :      Dict       						=						moe_eval_capacity_token_fraction
         __lowerCamelCase     :      Optional[int]       						=						moe_token_dropout
         __lowerCamelCase     :      Dict       						=						output_router_logits
         super().__init__(
             pad_token_id=_lowerCamelCase       ,  bos_token_id=_lowerCamelCase       ,  eos_token_id=_lowerCamelCase       ,  is_encoder_decoder=_lowerCamelCase       ,  decoder_start_token_id=_lowerCamelCase       ,  **_lowerCamelCase       ,  )



