




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

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, logging, randn_tensor
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin


lowercase_			:       List[Any]						       =				logging.get_logger(__name__)  # pylint: disable=invalid-name






@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->EulerAncestralDiscrete
class 					__lowerCAmelCase				( UpperCAmelCase__				):
			snake_case_   :				torch.FloatTensor
			snake_case_   :				Optional[torch.FloatTensor]				  =  None




def 							__SCREAMING_SNAKE_CASE						(    snake_case_			,					snake_case_=0.999			,					snake_case_="cosine"			,					):

						'''simple docstring'''


						if alpha_transform_type == "cosine":

												def alpha_bar_fn(snake_case_		):
																		return math.cos((t + 0.008) / 1.008 * math.pi / 2		) ** 2

						elif alpha_transform_type == "exp":

												def alpha_bar_fn(snake_case_		):
																		return math.exp(t * -12.0		)

						else:
												raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}"""		)

						_UpperCAmelCase									=  []
						for i in range(snake_case_		):
												_UpperCAmelCase									=  i / num_diffusion_timesteps
												_UpperCAmelCase									=  (i + 1) / num_diffusion_timesteps
												betas.append(min(1 - alpha_bar_fn(snake_case_		) / alpha_bar_fn(snake_case_		)			,					snake_case_		)		)
						return torch.tensor(snake_case_			,					dtype=torch.floataa		)






class 					__lowerCAmelCase				( UpperCAmelCase__      ,	UpperCAmelCase__				):
			snake_case_   :				Dict				  =  [e.name for e in KarrasDiffusionSchedulers]
			snake_case_   :				List[str]				  =  1







			@register_to_config
			def __init__( self					:    Dict					,					snake_case__					:    int = 1_000					,					snake_case__					:    float = 0.0_001					,					snake_case__					:    float = 0.02					,					snake_case__					:    str = "linear"					,					snake_case__					:    Optional[Union[np.ndarray, List[float]]] = None					,					snake_case__					:    str = "epsilon"					,					snake_case__					:    str = "linspace"					,					snake_case__					:    int = 0					,					):




									"""simple docstring"""


									if trained_betas is not None:
															_UpperCAmelCase									=  torch.tensor(snake_case__					,					dtype=torch.floataa   )
									elif beta_schedule == "linear":
															_UpperCAmelCase									=  torch.linspace(snake_case__					,					snake_case__					,					snake_case__					,					dtype=torch.floataa   )
									elif beta_schedule == "scaled_linear":
															# this schedule is very specific to the latent diffusion model.
															_UpperCAmelCase									=  (
															    torch.linspace(beta_start**0.5					,					beta_end**0.5					,					snake_case__					,					dtype=torch.floataa   ) ** 2
															)
									elif beta_schedule == "squaredcos_cap_v2":
															# Glide cosine schedule
															_UpperCAmelCase									=  betas_for_alpha_bar(snake_case__   )
									else:
															raise NotImplementedError(F"""{beta_schedule} does is not implemented for {self.__class__}"""   )

									_UpperCAmelCase									=  1.0 - self.betas
									_UpperCAmelCase									=  torch.cumprod(self.alphas					,					dim=0   )

									_UpperCAmelCase									=  np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5   )
									_UpperCAmelCase									=  np.concatenate([sigmas[::-1], [0.0]]   ).astype(np.floataa   )
									_UpperCAmelCase									=  torch.from_numpy(snake_case__   )

									# setable values
									_UpperCAmelCase									=  None
									_UpperCAmelCase									=  np.linspace(0					,					num_train_timesteps - 1					,					snake_case__					,					dtype=snake_case__   )[::-1].copy()
									_UpperCAmelCase									=  torch.from_numpy(snake_case__   )
									_UpperCAmelCase									=  False







			@property
			def UpperCamelCase    ( self					:    Optional[int]   ):




									"""simple docstring"""


									if self.config.timestep_spacing in ["linspace", "trailing"]:
															return self.sigmas.max()

									return (self.sigmas.max() ** 2 + 1) ** 0.5







			def UpperCamelCase    ( self					:    Tuple					,					snake_case__					:    torch.FloatTensor					,					snake_case__					:    Union[float, torch.FloatTensor]   ):




									"""simple docstring"""


									if isinstance(snake_case__					,					torch.Tensor   ):
															_UpperCAmelCase									=  timestep.to(self.timesteps.device   )
									_UpperCAmelCase									=  (self.timesteps == timestep).nonzero().item()
									_UpperCAmelCase									=  self.sigmas[step_index]
									_UpperCAmelCase									=  sample / ((sigma**2 + 1) ** 0.5)
									_UpperCAmelCase									=  True
									return sample







			def UpperCamelCase    ( self					:    List[str]					,					snake_case__					:    int					,					snake_case__					:    Union[str, torch.device] = None   ):




									"""simple docstring"""


									_UpperCAmelCase									=  num_inference_steps

									# "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
									if self.config.timestep_spacing == "linspace":
															_UpperCAmelCase									=  np.linspace(0					,					self.config.num_train_timesteps - 1					,					snake_case__					,					dtype=snake_case__   )[
															    ::-1
															].copy()
									elif self.config.timestep_spacing == "leading":
															_UpperCAmelCase									=  self.config.num_train_timesteps // self.num_inference_steps
															# creates integer timesteps by multiplying by ratio
															# casting to int to avoid issues when num_inference_step is power of 3
															_UpperCAmelCase									=  (np.arange(0					,					snake_case__   ) * step_ratio).round()[::-1].copy().astype(snake_case__   )
															timesteps += self.config.steps_offset
									elif self.config.timestep_spacing == "trailing":
															_UpperCAmelCase									=  self.config.num_train_timesteps / self.num_inference_steps
															# creates integer timesteps by multiplying by ratio
															# casting to int to avoid issues when num_inference_step is power of 3
															_UpperCAmelCase									=  (np.arange(self.config.num_train_timesteps					,					0					,					-step_ratio   )).round().copy().astype(snake_case__   )
															timesteps -= 1
									else:
															raise ValueError(
															    F"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'."""   )

									_UpperCAmelCase									=  np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5   )
									_UpperCAmelCase									=  np.interp(snake_case__					,					np.arange(0					,					len(snake_case__   )   )					,					snake_case__   )
									_UpperCAmelCase									=  np.concatenate([sigmas, [0.0]]   ).astype(np.floataa   )
									_UpperCAmelCase									=  torch.from_numpy(snake_case__   ).to(device=snake_case__   )
									if str(snake_case__   ).startswith("mps"   ):
															# mps does not support float64
															_UpperCAmelCase									=  torch.from_numpy(snake_case__   ).to(snake_case__					,					dtype=torch.floataa   )
									else:
															_UpperCAmelCase									=  torch.from_numpy(snake_case__   ).to(device=snake_case__   )







			def UpperCamelCase    ( self					:    List[str]					,					snake_case__					:    torch.FloatTensor					,					snake_case__					:    Union[float, torch.FloatTensor]					,					snake_case__					:    torch.FloatTensor					,					snake_case__					:    Optional[torch.Generator] = None					,					snake_case__					:    bool = True					,					):




									"""simple docstring"""


									if (
									    isinstance(snake_case__					,					snake_case__   )
									    or isinstance(snake_case__					,					torch.IntTensor   )
									    or isinstance(snake_case__					,					torch.LongTensor   )
									):
															raise ValueError(
															    (
															        "Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to"
															        " `EulerDiscreteScheduler.step()` is not supported. Make sure to pass"
															        " one of the `scheduler.timesteps` as a timestep."
															    )					,					)

									if not self.is_scale_input_called:
															logger.warning(
															    "The `scale_model_input` function should be called before `step` to ensure correct denoising. "
															    "See `StableDiffusionPipeline` for a usage example."   )

									if isinstance(snake_case__					,					torch.Tensor   ):
															_UpperCAmelCase									=  timestep.to(self.timesteps.device   )

									_UpperCAmelCase									=  (self.timesteps == timestep).nonzero().item()
									_UpperCAmelCase									=  self.sigmas[step_index]

									# 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
									if self.config.prediction_type == "epsilon":
															_UpperCAmelCase									=  sample - sigma * model_output
									elif self.config.prediction_type == "v_prediction":
															# * c_out + input * c_skip
															_UpperCAmelCase									=  model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (sample / (sigma**2 + 1))
									elif self.config.prediction_type == "sample":
															raise NotImplementedError("prediction_type not implemented yet: sample"   )
									else:
															raise ValueError(
															    F"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`"""   )

									_UpperCAmelCase									=  self.sigmas[step_index]
									_UpperCAmelCase									=  self.sigmas[step_index + 1]
									_UpperCAmelCase									=  (sigma_to**2 * (sigma_from**2 - sigma_to**2) / sigma_from**2) ** 0.5
									_UpperCAmelCase									=  (sigma_to**2 - sigma_up**2) ** 0.5

									# 2. Convert to an ODE derivative
									_UpperCAmelCase									=  (sample - pred_original_sample) / sigma

									_UpperCAmelCase									=  sigma_down - sigma

									_UpperCAmelCase									=  sample + derivative * dt

									_UpperCAmelCase									=  model_output.device
									_UpperCAmelCase									=  randn_tensor(model_output.shape					,					dtype=model_output.dtype					,					device=snake_case__					,					generator=snake_case__   )

									_UpperCAmelCase									=  prev_sample + noise * sigma_up

									if not return_dict:
															return (prev_sample,)

									return EulerAncestralDiscreteSchedulerOutput(
									    prev_sample=snake_case__					,					pred_original_sample=snake_case__   )







			def UpperCamelCase    ( self					:    List[str]					,					snake_case__					:    torch.FloatTensor					,					snake_case__					:    torch.FloatTensor					,					snake_case__					:    torch.FloatTensor					,					):




									"""simple docstring"""


									_UpperCAmelCase									=  self.sigmas.to(device=original_samples.device					,					dtype=original_samples.dtype   )
									if original_samples.device.type == "mps" and torch.is_floating_point(snake_case__   ):
															# mps does not support float64
															_UpperCAmelCase									=  self.timesteps.to(original_samples.device					,					dtype=torch.floataa   )
															_UpperCAmelCase									=  timesteps.to(original_samples.device					,					dtype=torch.floataa   )
									else:
															_UpperCAmelCase									=  self.timesteps.to(original_samples.device   )
															_UpperCAmelCase									=  timesteps.to(original_samples.device   )

									_UpperCAmelCase									=  [(schedule_timesteps == t).nonzero().item() for t in timesteps]

									_UpperCAmelCase									=  sigmas[step_indices].flatten()
									while len(sigma.shape   ) < len(original_samples.shape   ):
															_UpperCAmelCase									=  sigma.unsqueeze(-1   )

									_UpperCAmelCase									=  original_samples + noise * sigma
									return noisy_samples







			def __len__( self					:    str   ):




									"""simple docstring"""


									return self.config.num_train_timesteps










import copy

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


lowercase_			:       Tuple						       =				logging.get_logger(__name__)

lowercase_			:       List[Any]						       =				{
    'facebook/sam-vit-huge': 'https://huggingface.co/facebook/sam-vit-huge/resolve/main/config.json',
    'facebook/sam-vit-large': 'https://huggingface.co/facebook/sam-vit-large/resolve/main/config.json',
    'facebook/sam-vit-base': 'https://huggingface.co/facebook/sam-vit-base/resolve/main/config.json',
}






class 					__lowerCAmelCase				( UpperCAmelCase__				):







			def __init__( self					:    Optional[int]					,					snake_case__					:    int=256					,					snake_case__					:    Dict=1_024					,					snake_case__					:    Dict=16					,					snake_case__					:    Union[str, Any]=16					,					snake_case__					:    Any=4					,					snake_case__					:    Tuple="gelu"					,					snake_case__					:    Tuple=1e-6					,					**snake_case__					:    str					,					):




									"""simple docstring"""


									super().__init__(**snake_case__   )
									_UpperCAmelCase									=  hidden_size
									_UpperCAmelCase									=  image_size
									_UpperCAmelCase									=  patch_size
									_UpperCAmelCase									=  image_size // patch_size
									_UpperCAmelCase									=  mask_input_channels
									_UpperCAmelCase									=  num_point_embeddings
									_UpperCAmelCase									=  hidden_act
									_UpperCAmelCase									=  layer_norm_eps






class 					__lowerCAmelCase				( UpperCAmelCase__				):







			def __init__( self					:    str					,					snake_case__					:    List[str]=256					,					snake_case__					:    Tuple="relu"					,					snake_case__					:    int=2_048					,					snake_case__					:    Optional[int]=2					,					snake_case__					:    Dict=8					,					snake_case__					:    List[Any]=2					,					snake_case__					:    List[Any]=3					,					snake_case__					:    List[Any]=3					,					snake_case__					:    Optional[int]=256					,					snake_case__					:    Tuple=1e-6					,					**snake_case__					:    Any					,					):




									"""simple docstring"""


									super().__init__(**snake_case__   )
									_UpperCAmelCase									=  hidden_size
									_UpperCAmelCase									=  hidden_act
									_UpperCAmelCase									=  mlp_dim
									_UpperCAmelCase									=  num_hidden_layers
									_UpperCAmelCase									=  num_attention_heads
									_UpperCAmelCase									=  attention_downsample_rate
									_UpperCAmelCase									=  num_multimask_outputs
									_UpperCAmelCase									=  iou_head_depth
									_UpperCAmelCase									=  iou_head_hidden_dim
									_UpperCAmelCase									=  layer_norm_eps






class 					__lowerCAmelCase				( UpperCAmelCase__				):







			def __init__( self					:    List[str]					,					snake_case__					:    str=768					,					snake_case__					:    Dict=256					,					snake_case__					:    Any=12					,					snake_case__					:    Union[str, Any]=12					,					snake_case__					:    Any=3					,					snake_case__					:    List[str]=1_024					,					snake_case__					:    Union[str, Any]=16					,					snake_case__					:    Any="gelu"					,					snake_case__					:    List[str]=1e-06					,					snake_case__					:    Union[str, Any]=0.0					,					snake_case__					:    Optional[int]=1e-10					,					snake_case__					:    int=True					,					snake_case__					:    Dict=4.0					,					snake_case__					:    Optional[Any]=True					,					snake_case__					:    Tuple=True					,					snake_case__					:    List[Any]=14					,					snake_case__					:    List[str]=[2, 5, 8, 11]					,					snake_case__					:    List[Any]=128					,					snake_case__					:    List[Any]=None					,					**snake_case__					:    Any					,					):




									"""simple docstring"""


									super().__init__(**snake_case__   )

									_UpperCAmelCase									=  hidden_size
									_UpperCAmelCase									=  output_channels
									_UpperCAmelCase									=  num_hidden_layers
									_UpperCAmelCase									=  num_attention_heads
									_UpperCAmelCase									=  num_channels
									_UpperCAmelCase									=  image_size
									_UpperCAmelCase									=  patch_size
									_UpperCAmelCase									=  hidden_act
									_UpperCAmelCase									=  layer_norm_eps
									_UpperCAmelCase									=  attention_dropout
									_UpperCAmelCase									=  initializer_range
									_UpperCAmelCase									=  qkv_bias
									_UpperCAmelCase									=  mlp_ratio
									_UpperCAmelCase									=  use_abs_pos
									_UpperCAmelCase									=  use_rel_pos
									_UpperCAmelCase									=  window_size
									_UpperCAmelCase									=  global_attn_indexes
									_UpperCAmelCase									=  num_pos_feats
									_UpperCAmelCase									=  int(hidden_size * mlp_ratio   ) if mlp_dim is None else mlp_dim






class 					__lowerCAmelCase				( UpperCAmelCase__				):
			snake_case_   :				Tuple				  =  "sam"
			snake_case_   :				Tuple				  =  True







			def __init__( self					:    Optional[int]					,					snake_case__					:    Optional[Any]=None					,					snake_case__					:    Any=None					,					snake_case__					:    int=None					,					snake_case__					:    List[Any]=0.02					,					**snake_case__					:    str					,					):




									"""simple docstring"""


									super().__init__(**snake_case__   )
									_UpperCAmelCase									=  vision_config if vision_config is not None else {}
									_UpperCAmelCase									=  prompt_encoder_config if prompt_encoder_config is not None else {}
									_UpperCAmelCase									=  mask_decoder_config if mask_decoder_config is not None else {}

									if isinstance(snake_case__					,					snake_case__   ):
															_UpperCAmelCase									=  vision_config.to_dict()
									if isinstance(snake_case__					,					snake_case__   ):
															_UpperCAmelCase									=  prompt_encoder_config.to_dict()
									if isinstance(snake_case__					,					snake_case__   ):
															_UpperCAmelCase									=  mask_decoder_config.to_dict()

									_UpperCAmelCase									=  SamVisionConfig(**snake_case__   )
									_UpperCAmelCase									=  SamPromptEncoderConfig(**snake_case__   )
									_UpperCAmelCase									=  SamMaskDecoderConfig(**snake_case__   )
									_UpperCAmelCase									=  initializer_range







			def UpperCamelCase    ( self					:    Any   ):




									"""simple docstring"""


									_UpperCAmelCase									=  copy.deepcopy(self.__dict__   )
									_UpperCAmelCase									=  self.vision_config.to_dict()
									_UpperCAmelCase									=  self.prompt_encoder_config.to_dict()
									_UpperCAmelCase									=  self.mask_decoder_config.to_dict()
									_UpperCAmelCase									=  self.__class__.model_type
									return output




