

import math
from typing import Optional

import numpy as np
import torch
from torch import nn

from .activations import get_activation







def  UpperCAmelCase_   (_lowerCAmelCase :		torch.Tensor     ,			_lowerCAmelCase :		int     ,			_lowerCAmelCase :		bool = False     ,			_lowerCAmelCase :		float = 1     ,			_lowerCAmelCase :		float = 1     ,			_lowerCAmelCase :		int = 1_00_00     ,			):
			assert len(timesteps.shape		) == 1, "Timesteps should be a 1d-array"

			__UpperCamelCase    :    Dict								=      embedding_dim // 2
			__UpperCamelCase    :    List[Any]								=      -math.log(_lowerCAmelCase		) * torch.arange(
			    start=0     ,			end=_lowerCAmelCase     ,			dtype=torch.floataa     ,			device=timesteps.device		)
			__UpperCamelCase    :    Optional[Any]								=      exponent / (half_dim - downscale_freq_shift)

			__UpperCamelCase    :    Optional[Any]								=      torch.exp(_lowerCAmelCase		)
			__UpperCamelCase    :    Optional[Any]								=      timesteps[:, None].float() * emb[None, :]

			# scale embeddings
			__UpperCamelCase    :    Optional[Any]								=      scale * emb

			# concat sine and cosine embeddings
			__UpperCamelCase    :    Tuple								=      torch.cat([torch.sin(_lowerCAmelCase		), torch.cos(_lowerCAmelCase		)]     ,			dim=-1		)

			# flip sine and cosine embeddings
			if flip_sin_to_cos:
						__UpperCamelCase    :    str								=      torch.cat([emb[:, half_dim:], emb[:, :half_dim]]     ,			dim=-1		)

			# zero pad
			if embedding_dim % 2 == 1:
						__UpperCamelCase    :    Union[str, Any]								=      torch.nn.functional.pad(_lowerCAmelCase     ,			(0, 1, 0, 0)		)
			return emb







def  UpperCAmelCase_   (_lowerCAmelCase :		Dict     ,			_lowerCAmelCase :		int     ,			_lowerCAmelCase :		Optional[int]=False     ,			_lowerCAmelCase :		List[str]=0		):
			__UpperCamelCase    :    int								=      np.arange(_lowerCAmelCase     ,			dtype=np.floataa		)
			__UpperCamelCase    :    Optional[int]								=      np.arange(_lowerCAmelCase     ,			dtype=np.floataa		)
			__UpperCamelCase    :    int								=      np.meshgrid(_lowerCAmelCase     ,			_lowerCAmelCase		)  # here w goes first
			__UpperCamelCase    :    str								=      np.stack(_lowerCAmelCase     ,			axis=0		)

			__UpperCamelCase    :    Optional[Any]								=      grid.reshape([2, 1, grid_size, grid_size]		)
			__UpperCamelCase    :    Optional[Any]								=      get_ad_sincos_pos_embed_from_grid(_lowerCAmelCase     ,			_lowerCAmelCase		)
			if cls_token and extra_tokens > 0:
						__UpperCamelCase    :    Any								=      np.concatenate([np.zeros([extra_tokens, embed_dim]		), pos_embed]     ,			axis=0		)
			return pos_embed







def  UpperCAmelCase_   (_lowerCAmelCase :		Any     ,			_lowerCAmelCase :		Tuple		):
			if embed_dim % 2 != 0:
						raise ValueError("embed_dim must be divisible by 2"		)

			# use half of dimensions to encode grid_h
			__UpperCamelCase    :    List[Any]								=      get_ad_sincos_pos_embed_from_grid(embed_dim // 2     ,			grid[0]		)  # (H*W, D/2)
			__UpperCamelCase    :    Tuple								=      get_ad_sincos_pos_embed_from_grid(embed_dim // 2     ,			grid[1]		)  # (H*W, D/2)

			__UpperCamelCase    :    int								=      np.concatenate([emb_h, emb_w]     ,			axis=1		)  # (H*W, D)
			return emb







def  UpperCAmelCase_   (_lowerCAmelCase :		int     ,			_lowerCAmelCase :		List[str]		):
			if embed_dim % 2 != 0:
						raise ValueError("embed_dim must be divisible by 2"		)

			__UpperCamelCase    :    Optional[int]								=      np.arange(embed_dim // 2     ,			dtype=np.floataa		)
			omega /= embed_dim / 2.0
			__UpperCamelCase    :    Tuple								=      1.0 / 1_00_00**omega  # (D/2,)

			__UpperCamelCase    :    Dict								=      pos.reshape(-1		)  # (M,)
			__UpperCamelCase    :    int								=      np.einsum("m,d->md"     ,			_lowerCAmelCase     ,			_lowerCAmelCase		)  # (M, D/2), outer product

			__UpperCamelCase    :    Union[str, Any]								=      np.sin(_lowerCAmelCase		)  # (M, D/2)
			__UpperCamelCase    :    Optional[int]								=      np.cos(_lowerCAmelCase		)  # (M, D/2)

			__UpperCamelCase    :    Any								=      np.concatenate([emb_sin, emb_cos]     ,			axis=1		)  # (M, D)
			return emb
class 		SCREAMING_SNAKE_CASE__					(		nn.Module   ):







						"""simple docstring"""




						def __init__(				self , __UpperCamelCase=2_24 , __UpperCamelCase=2_24 , __UpperCamelCase=16 , __UpperCamelCase=3 , __UpperCamelCase=7_68 , __UpperCamelCase=False , __UpperCamelCase=True , __UpperCamelCase=True , )							->	List[Any]:




									'''simple docstring'''


									super().__init__()

									__UpperCamelCase    :    str								=      (height // patch_size) * (width // patch_size)
									__UpperCamelCase    :    Tuple								=      flatten
									__UpperCamelCase    :    int								=      layer_norm

									__UpperCamelCase    :    Tuple								=      nn.Convad(
									    __UpperCamelCase , __UpperCamelCase , kernel_size=(patch_size, patch_size) , stride=__UpperCamelCase , bias=__UpperCamelCase    )
									if layer_norm:
												__UpperCamelCase    :    Optional[Any]								=      nn.LayerNorm(__UpperCamelCase , elementwise_affine=__UpperCamelCase , eps=1E-6    )
									else:
												__UpperCamelCase    :    Optional[Any]								=      None

									__UpperCamelCase    :    List[Any]								=      get_ad_sincos_pos_embed(__UpperCamelCase , int(num_patches**0.5    )    )
									self.register_buffer("pos_embed" , torch.from_numpy(__UpperCamelCase    ).float().unsqueeze(0    ) , persistent=__UpperCamelCase    )




						def __lowerCamelCase					(				self , __UpperCamelCase    )							->	Dict:




									'''simple docstring'''


									__UpperCamelCase    :    Dict								=      self.proj(__UpperCamelCase    )
									if self.flatten:
												__UpperCamelCase    :    Union[str, Any]								=      latent.flatten(2    ).transpose(1 , 2    )  # BCHW -> BNC
									if self.layer_norm:
												__UpperCamelCase    :    int								=      self.norm(__UpperCamelCase    )
									return latent + self.pos_embed







class 		SCREAMING_SNAKE_CASE__					(		nn.Module   ):







						"""simple docstring"""




						def __init__(				self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = "silu" , __UpperCamelCase = None , __UpperCamelCase = None , __UpperCamelCase=None , )							->	List[Any]:




									'''simple docstring'''


									super().__init__()

									__UpperCamelCase    :    Union[str, Any]								=      nn.Linear(__UpperCamelCase , __UpperCamelCase    )

									if cond_proj_dim is not None:
												__UpperCamelCase    :    Union[str, Any]								=      nn.Linear(__UpperCamelCase , __UpperCamelCase , bias=__UpperCamelCase    )
									else:
												__UpperCamelCase    :    List[str]								=      None

									__UpperCamelCase    :    Optional[Any]								=      get_activation(__UpperCamelCase    )

									if out_dim is not None:
												__UpperCamelCase    :    int								=      out_dim
									else:
												__UpperCamelCase    :    Union[str, Any]								=      time_embed_dim
									__UpperCamelCase    :    str								=      nn.Linear(__UpperCamelCase , __UpperCamelCase    )

									if post_act_fn is None:
												__UpperCamelCase    :    Union[str, Any]								=      None
									else:
												__UpperCamelCase    :    List[str]								=      get_activation(__UpperCamelCase    )




						def __lowerCamelCase					(				self , __UpperCamelCase , __UpperCamelCase=None    )							->	Optional[int]:




									'''simple docstring'''


									if condition is not None:
												__UpperCamelCase    :    List[str]								=      sample + self.cond_proj(__UpperCamelCase    )
									__UpperCamelCase    :    int								=      self.linear_a(__UpperCamelCase    )

									if self.act is not None:
												__UpperCamelCase    :    Union[str, Any]								=      self.act(__UpperCamelCase    )

									__UpperCamelCase    :    Optional[int]								=      self.linear_a(__UpperCamelCase    )

									if self.post_act is not None:
												__UpperCamelCase    :    int								=      self.post_act(__UpperCamelCase    )
									return sample







class 		SCREAMING_SNAKE_CASE__					(		nn.Module   ):







						"""simple docstring"""




						def __init__(				self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase    )							->	int:




									'''simple docstring'''


									super().__init__()
									__UpperCamelCase    :    List[Any]								=      num_channels
									__UpperCamelCase    :    str								=      flip_sin_to_cos
									__UpperCamelCase    :    Optional[Any]								=      downscale_freq_shift




						def __lowerCamelCase					(				self , __UpperCamelCase    )							->	Optional[int]:




									'''simple docstring'''


									__UpperCamelCase    :    Dict								=      get_timestep_embedding(
									    __UpperCamelCase , self.num_channels , flip_sin_to_cos=self.flip_sin_to_cos , downscale_freq_shift=self.downscale_freq_shift , )
									return t_emb







class 		SCREAMING_SNAKE_CASE__					(		nn.Module   ):







						"""simple docstring"""




						def __init__(				self , __UpperCamelCase = 2_56 , __UpperCamelCase = 1.0 , __UpperCamelCase=True , __UpperCamelCase=True , __UpperCamelCase=False    )							->	str:




									'''simple docstring'''


									super().__init__()
									__UpperCamelCase    :    Any								=      nn.Parameter(torch.randn(__UpperCamelCase    ) * scale , requires_grad=__UpperCamelCase    )
									__UpperCamelCase    :    Union[str, Any]								=      log
									__UpperCamelCase    :    str								=      flip_sin_to_cos

									if set_W_to_weight:
												# to delete later
												__UpperCamelCase    :    int								=      nn.Parameter(torch.randn(__UpperCamelCase    ) * scale , requires_grad=__UpperCamelCase    )

												__UpperCamelCase    :    Optional[int]								=      self.W




						def __lowerCamelCase					(				self , __UpperCamelCase    )							->	Optional[Any]:




									'''simple docstring'''


									if self.log:
												__UpperCamelCase    :    Union[str, Any]								=      torch.log(__UpperCamelCase    )

									__UpperCamelCase    :    Union[str, Any]								=      x[:, None] * self.weight[None, :] * 2 * np.pi

									if self.flip_sin_to_cos:
												__UpperCamelCase    :    List[Any]								=      torch.cat([torch.cos(__UpperCamelCase    ), torch.sin(__UpperCamelCase    )] , dim=-1    )
									else:
												__UpperCamelCase    :    Optional[int]								=      torch.cat([torch.sin(__UpperCamelCase    ), torch.cos(__UpperCamelCase    )] , dim=-1    )
									return out







class 		SCREAMING_SNAKE_CASE__					(		nn.Module   ):







						"""simple docstring"""




						def __init__(				self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , )							->	Optional[Any]:




									'''simple docstring'''


									super().__init__()

									__UpperCamelCase    :    Any								=      height
									__UpperCamelCase    :    str								=      width
									__UpperCamelCase    :    Union[str, Any]								=      num_embed
									__UpperCamelCase    :    Optional[int]								=      embed_dim

									__UpperCamelCase    :    str								=      nn.Embedding(self.num_embed , __UpperCamelCase    )
									__UpperCamelCase    :    List[Any]								=      nn.Embedding(self.height , __UpperCamelCase    )
									__UpperCamelCase    :    Any								=      nn.Embedding(self.width , __UpperCamelCase    )




						def __lowerCamelCase					(				self , __UpperCamelCase    )							->	Any:




									'''simple docstring'''


									__UpperCamelCase    :    Optional[int]								=      self.emb(__UpperCamelCase    )

									__UpperCamelCase    :    Any								=      self.height_emb(torch.arange(self.height , device=index.device    ).view(1 , self.height    )    )

									# 1 x H x D -> 1 x H x 1 x D
									__UpperCamelCase    :    Tuple								=      height_emb.unsqueeze(2    )

									__UpperCamelCase    :    List[Any]								=      self.width_emb(torch.arange(self.width , device=index.device    ).view(1 , self.width    )    )

									# 1 x W x D -> 1 x 1 x W x D
									__UpperCamelCase    :    List[Any]								=      width_emb.unsqueeze(1    )

									__UpperCamelCase    :    Optional[Any]								=      height_emb + width_emb

									# 1 x H x W x D -> 1 x L xD
									__UpperCamelCase    :    Any								=      pos_emb.view(1 , self.height * self.width , -1    )

									__UpperCamelCase    :    Optional[Any]								=      emb + pos_emb[:, : emb.shape[1], :]

									return emb







class 		SCREAMING_SNAKE_CASE__					(		nn.Module   ):







						"""simple docstring"""




						def __init__(				self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase    )							->	Optional[Any]:




									'''simple docstring'''


									super().__init__()
									__UpperCamelCase    :    List[str]								=      dropout_prob > 0
									__UpperCamelCase    :    Any								=      nn.Embedding(num_classes + use_cfg_embedding , __UpperCamelCase    )
									__UpperCamelCase    :    Union[str, Any]								=      num_classes
									__UpperCamelCase    :    List[str]								=      dropout_prob

						def __lowerCamelCase					(				self , __UpperCamelCase , __UpperCamelCase=None    )							->	int:




									'''simple docstring'''


									if force_drop_ids is None:
												__UpperCamelCase    :    Dict								=      torch.rand(labels.shape[0] , device=labels.device    ) < self.dropout_prob
									else:
												__UpperCamelCase    :    str								=      torch.tensor(force_drop_ids == 1    )
									__UpperCamelCase    :    Optional[Any]								=      torch.where(__UpperCamelCase , self.num_classes , __UpperCamelCase    )
									return labels




						def __lowerCamelCase					(				self , __UpperCamelCase , __UpperCamelCase=None    )							->	Tuple:




									'''simple docstring'''


									__UpperCamelCase    :    List[str]								=      self.dropout_prob > 0
									if (self.training and use_dropout) or (force_drop_ids is not None):
												__UpperCamelCase    :    List[Any]								=      self.token_drop(__UpperCamelCase , __UpperCamelCase    )
									__UpperCamelCase    :    Optional[int]								=      self.embedding_table(__UpperCamelCase    )
									return embeddings







class 		SCREAMING_SNAKE_CASE__					(		nn.Module   ):







						"""simple docstring"""




						def __init__(				self , __UpperCamelCase = 10_24 , __UpperCamelCase = 7_68 , __UpperCamelCase = 7_68 , __UpperCamelCase = 10 , )							->	List[Any]:




									'''simple docstring'''


									super().__init__()

									__UpperCamelCase    :    Optional[Any]								=      num_image_text_embeds
									__UpperCamelCase    :    Dict								=      nn.Linear(__UpperCamelCase , self.num_image_text_embeds * cross_attention_dim    )
									__UpperCamelCase    :    Tuple								=      nn.Linear(__UpperCamelCase , __UpperCamelCase    )




						def __lowerCamelCase					(				self , __UpperCamelCase , __UpperCamelCase    )							->	Union[str, Any]:




									'''simple docstring'''


									__UpperCamelCase    :    Optional[Any]								=      text_embeds.shape[0]

									# image
									__UpperCamelCase    :    Union[str, Any]								=      self.image_embeds(__UpperCamelCase    )
									__UpperCamelCase    :    Optional[Any]								=      image_text_embeds.reshape(__UpperCamelCase , self.num_image_text_embeds , -1    )

									# text
									__UpperCamelCase    :    Union[str, Any]								=      self.text_proj(__UpperCamelCase    )

									return torch.cat([image_text_embeds, text_embeds] , dim=1    )







class 		SCREAMING_SNAKE_CASE__					(		nn.Module   ):







						"""simple docstring"""




						def __init__(				self , __UpperCamelCase = 7_68 , __UpperCamelCase = 7_68 , __UpperCamelCase = 32 , )							->	Tuple:




									'''simple docstring'''


									super().__init__()

									__UpperCamelCase    :    Dict								=      num_image_text_embeds
									__UpperCamelCase    :    List[Any]								=      nn.Linear(__UpperCamelCase , self.num_image_text_embeds * cross_attention_dim    )
									__UpperCamelCase    :    Optional[Any]								=      nn.LayerNorm(__UpperCamelCase    )




						def __lowerCamelCase					(				self , __UpperCamelCase    )							->	str:




									'''simple docstring'''


									__UpperCamelCase    :    Any								=      image_embeds.shape[0]

									# image
									__UpperCamelCase    :    Optional[Any]								=      self.image_embeds(__UpperCamelCase    )
									__UpperCamelCase    :    str								=      image_embeds.reshape(__UpperCamelCase , self.num_image_text_embeds , -1    )
									__UpperCamelCase    :    Optional[int]								=      self.norm(__UpperCamelCase    )
									return image_embeds







class 		SCREAMING_SNAKE_CASE__					(		nn.Module   ):







						"""simple docstring"""




						def __init__(				self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=0.1    )							->	List[Any]:




									'''simple docstring'''


									super().__init__()

									__UpperCamelCase    :    str								=      Timesteps(num_channels=2_56 , flip_sin_to_cos=__UpperCamelCase , downscale_freq_shift=1    )
									__UpperCamelCase    :    Optional[int]								=      TimestepEmbedding(in_channels=2_56 , time_embed_dim=__UpperCamelCase    )
									__UpperCamelCase    :    Union[str, Any]								=      LabelEmbedding(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase    )




						def __lowerCamelCase					(				self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None    )							->	str:




									'''simple docstring'''


									__UpperCamelCase    :    Dict								=      self.time_proj(__UpperCamelCase    )
									__UpperCamelCase    :    Tuple								=      self.timestep_embedder(timesteps_proj.to(dtype=__UpperCamelCase    )    )  # (N, D)

									__UpperCamelCase    :    List[Any]								=      self.class_embedder(__UpperCamelCase    )  # (N, D)

									__UpperCamelCase    :    Tuple								=      timesteps_emb + class_labels  # (N, D)

									return conditioning







class 		SCREAMING_SNAKE_CASE__					(		nn.Module   ):







						"""simple docstring"""




						def __init__(				self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = 64    )							->	Optional[int]:




									'''simple docstring'''


									super().__init__()
									__UpperCamelCase    :    Optional[int]								=      nn.LayerNorm(__UpperCamelCase    )
									__UpperCamelCase    :    int								=      AttentionPooling(__UpperCamelCase , __UpperCamelCase    )
									__UpperCamelCase    :    Tuple								=      nn.Linear(__UpperCamelCase , __UpperCamelCase    )
									__UpperCamelCase    :    str								=      nn.LayerNorm(__UpperCamelCase    )




						def __lowerCamelCase					(				self , __UpperCamelCase    )							->	int:




									'''simple docstring'''


									__UpperCamelCase    :    Tuple								=      self.norma(__UpperCamelCase    )
									__UpperCamelCase    :    str								=      self.pool(__UpperCamelCase    )
									__UpperCamelCase    :    Tuple								=      self.proj(__UpperCamelCase    )
									__UpperCamelCase    :    Optional[Any]								=      self.norma(__UpperCamelCase    )
									return hidden_states







class 		SCREAMING_SNAKE_CASE__					(		nn.Module   ):







						"""simple docstring"""




						def __init__(				self , __UpperCamelCase = 7_68 , __UpperCamelCase = 7_68 , __UpperCamelCase = 15_36    )							->	int:




									'''simple docstring'''


									super().__init__()
									__UpperCamelCase    :    int								=      nn.Linear(__UpperCamelCase , __UpperCamelCase    )
									__UpperCamelCase    :    Tuple								=      nn.LayerNorm(__UpperCamelCase    )
									__UpperCamelCase    :    Dict								=      nn.Linear(__UpperCamelCase , __UpperCamelCase    )




						def __lowerCamelCase					(				self , __UpperCamelCase , __UpperCamelCase    )							->	Union[str, Any]:




									'''simple docstring'''


									__UpperCamelCase    :    List[str]								=      self.text_proj(__UpperCamelCase    )
									__UpperCamelCase    :    str								=      self.text_norm(__UpperCamelCase    )

									# image
									__UpperCamelCase    :    Optional[Any]								=      self.image_proj(__UpperCamelCase    )

									return time_image_embeds + time_text_embeds







class 		SCREAMING_SNAKE_CASE__					(		nn.Module   ):







						"""simple docstring"""




						def __init__(				self , __UpperCamelCase = 7_68 , __UpperCamelCase = 15_36    )							->	Optional[Any]:




									'''simple docstring'''


									super().__init__()
									__UpperCamelCase    :    Any								=      nn.Linear(__UpperCamelCase , __UpperCamelCase    )
									__UpperCamelCase    :    Any								=      nn.LayerNorm(__UpperCamelCase    )




						def __lowerCamelCase					(				self , __UpperCamelCase    )							->	Any:




									'''simple docstring'''


									__UpperCamelCase    :    Union[str, Any]								=      self.image_proj(__UpperCamelCase    )
									__UpperCamelCase    :    str								=      self.image_norm(__UpperCamelCase    )
									return time_image_embeds







class 		SCREAMING_SNAKE_CASE__					(		nn.Module   ):







						"""simple docstring"""




						def __init__(				self , __UpperCamelCase = 7_68 , __UpperCamelCase = 15_36    )							->	Tuple:




									'''simple docstring'''


									super().__init__()
									__UpperCamelCase    :    int								=      nn.Linear(__UpperCamelCase , __UpperCamelCase    )
									__UpperCamelCase    :    int								=      nn.LayerNorm(__UpperCamelCase    )
									__UpperCamelCase    :    Union[str, Any]								=      nn.Sequential(
									    nn.Convad(3 , 16 , 3 , padding=1    ) , nn.SiLU() , nn.Convad(16 , 16 , 3 , padding=1    ) , nn.SiLU() , nn.Convad(16 , 32 , 3 , padding=1 , stride=2    ) , nn.SiLU() , nn.Convad(32 , 32 , 3 , padding=1    ) , nn.SiLU() , nn.Convad(32 , 96 , 3 , padding=1 , stride=2    ) , nn.SiLU() , nn.Convad(96 , 96 , 3 , padding=1    ) , nn.SiLU() , nn.Convad(96 , 2_56 , 3 , padding=1 , stride=2    ) , nn.SiLU() , nn.Convad(2_56 , 4 , 3 , padding=1    ) , )




						def __lowerCamelCase					(				self , __UpperCamelCase , __UpperCamelCase    )							->	Optional[Any]:




									'''simple docstring'''


									__UpperCamelCase    :    str								=      self.image_proj(__UpperCamelCase    )
									__UpperCamelCase    :    Optional[Any]								=      self.image_norm(__UpperCamelCase    )
									__UpperCamelCase    :    List[str]								=      self.input_hint_block(__UpperCamelCase    )
									return time_image_embeds, hint







class 		SCREAMING_SNAKE_CASE__					(		nn.Module   ):







						"""simple docstring"""




						def __init__(				self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=None    )							->	str:




									'''simple docstring'''


									super().__init__()
									__UpperCamelCase    :    int								=      dtype
									__UpperCamelCase    :    Union[str, Any]								=      nn.Parameter(torch.randn(1 , __UpperCamelCase    ) / embed_dim**0.5    )
									__UpperCamelCase    :    int								=      nn.Linear(__UpperCamelCase , __UpperCamelCase , dtype=self.dtype    )
									__UpperCamelCase    :    List[Any]								=      nn.Linear(__UpperCamelCase , __UpperCamelCase , dtype=self.dtype    )
									__UpperCamelCase    :    int								=      nn.Linear(__UpperCamelCase , __UpperCamelCase , dtype=self.dtype    )
									__UpperCamelCase    :    int								=      num_heads
									__UpperCamelCase    :    Optional[int]								=      embed_dim // self.num_heads




						def __lowerCamelCase					(				self , __UpperCamelCase    )							->	Any:




									'''simple docstring'''


									__UpperCamelCase							,				__UpperCamelCase							,				__UpperCamelCase    :    Optional[Any]								=      x.size()

									def shape(__UpperCamelCase    ):
												# (bs, length, width) --> (bs, length, n_heads, dim_per_head)
												__UpperCamelCase    :    Tuple								=      x.view(__UpperCamelCase , -1 , self.num_heads , self.dim_per_head    )
												# (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head)
												__UpperCamelCase    :    Union[str, Any]								=      x.transpose(1 , 2    )
												# (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head)
												__UpperCamelCase    :    Tuple								=      x.reshape(bs * self.num_heads , -1 , self.dim_per_head    )
												# (bs*n_heads, length, dim_per_head) --> (bs*n_heads, dim_per_head, length)
												__UpperCamelCase    :    int								=      x.transpose(1 , 2    )
												return x

									__UpperCamelCase    :    int								=      x.mean(dim=1 , keepdim=__UpperCamelCase    ) + self.positional_embedding.to(x.dtype    )
									__UpperCamelCase    :    Tuple								=      torch.cat([class_token, x] , dim=1    )  # (bs, length+1, width)

									# (bs*n_heads, class_token_length, dim_per_head)
									__UpperCamelCase    :    Union[str, Any]								=      shape(self.q_proj(__UpperCamelCase    )    )
									# (bs*n_heads, length+class_token_length, dim_per_head)
									__UpperCamelCase    :    Optional[int]								=      shape(self.k_proj(__UpperCamelCase    )    )
									__UpperCamelCase    :    Optional[Any]								=      shape(self.v_proj(__UpperCamelCase    )    )

									# (bs*n_heads, class_token_length, length+class_token_length):
									__UpperCamelCase    :    str								=      1 / math.sqrt(math.sqrt(self.dim_per_head    )    )
									__UpperCamelCase    :    str								=      torch.einsum("bct,bcs->bts" , q * scale , k * scale    )  # More stable with f16 than dividing afterwards
									__UpperCamelCase    :    Optional[int]								=      torch.softmax(weight.float() , dim=-1    ).type(weight.dtype    )

									# (bs*n_heads, dim_per_head, class_token_length)
									__UpperCamelCase    :    Tuple								=      torch.einsum("bts,bcs->bct" , __UpperCamelCase , __UpperCamelCase    )

									# (bs, length+1, width)
									__UpperCamelCase    :    Any								=      a.reshape(__UpperCamelCase , -1 , 1    ).transpose(1 , 2    )

									return a[:, 0, :]  # cls_token


import os
import pickle
import tempfile
import unittest
from typing import Callable, Optional

import numpy as np

from transformers import (
    BatchEncoding,
    BertTokenizer,
    BertTokenizerFast,
    PreTrainedTokenizer,
    PreTrainedTokenizerFast,
    TensorType,
    TokenSpan,
    is_tokenizers_available,
)
from transformers.models.gpta.tokenization_gpta import GPTaTokenizer
from transformers.testing_utils import CaptureStderr, require_flax, require_tf, require_tokenizers, require_torch, slow


if is_tokenizers_available():
					from tokenizers import Tokenizer
					from tokenizers.models import WordPiece
class 		SCREAMING_SNAKE_CASE__					(		unittest.TestCase   ):







						"""simple docstring"""




						def __lowerCamelCase					(				self , __UpperCamelCase    )							->	Union[str, Any]:




									'''simple docstring'''


									__UpperCamelCase    :    List[str]								=      list(tokenizer_class.max_model_input_sizes.keys()    )
									for model_name in sa_models[:1]:
												__UpperCamelCase    :    int								=      tokenizer_class.from_pretrained(__UpperCamelCase    )
												self.assertIsNotNone(__UpperCamelCase    )
												self.assertIsInstance(__UpperCamelCase , __UpperCamelCase    )
												self.assertIsInstance(__UpperCamelCase , __UpperCamelCase    )

												for special_tok in tokenizer.all_special_tokens:
															self.assertIsInstance(__UpperCamelCase , __UpperCamelCase    )
															__UpperCamelCase    :    str								=      tokenizer.convert_tokens_to_ids(__UpperCamelCase    )
															self.assertIsInstance(__UpperCamelCase , __UpperCamelCase    )

						def __lowerCamelCase					(				self , __UpperCamelCase , __UpperCamelCase = None    )							->	Tuple:




									'''simple docstring'''


									__UpperCamelCase    :    Optional[Any]								=      pickle.dumps(__UpperCamelCase    )
									self.assertIsNotNone(__UpperCamelCase    )

									__UpperCamelCase    :    List[str]								=      pickle.loads(__UpperCamelCase    )

									# Ensure is_fast is correctly restored
									self.assertEqual(be_restored.is_fast , be_original.is_fast    )

									# Ensure encodings are potentially correctly restored
									if be_original.is_fast:
												self.assertIsNotNone(be_restored.encodings    )
									else:
												self.assertIsNone(be_restored.encodings    )

									# Ensure the keys are the same
									for original_v, restored_v in zip(be_original.values() , be_restored.values()    ):
												if equal_op:
															self.assertTrue(equal_op(__UpperCamelCase , __UpperCamelCase    )    )
												else:
															self.assertEqual(__UpperCamelCase , __UpperCamelCase    )

						@slow
						def __lowerCamelCase					(				self    )							->	List[Any]:




									'''simple docstring'''


									self.check_tokenizer_from_pretrained(__UpperCamelCase    )

						def __lowerCamelCase					(				self    )							->	Optional[int]:




									'''simple docstring'''


									self.assertEqual(TensorType("tf"    ) , TensorType.TENSORFLOW    )
									self.assertEqual(TensorType("pt"    ) , TensorType.PYTORCH    )
									self.assertEqual(TensorType("np"    ) , TensorType.NUMPY    )

						@require_tokenizers
						def __lowerCamelCase					(				self    )							->	List[str]:




									'''simple docstring'''


									import numpy as np

									__UpperCamelCase    :    str								=      BertTokenizer.from_pretrained("bert-base-cased"    )
									__UpperCamelCase    :    Optional[Any]								=      BertTokenizerFast.from_pretrained("bert-base-cased"    )

									# Python no tensor
									with self.subTest("BatchEncoding (Python, return_tensors=None)"    ):
												self.assert_dump_and_restore(tokenizer_p("Small example to encode"    )    )

									with self.subTest("BatchEncoding (Python, return_tensors=NUMPY)"    ):
												self.assert_dump_and_restore(
												    tokenizer_p("Small example to encode" , return_tensors=TensorType.NUMPY    ) , np.array_equal    )

									with self.subTest("BatchEncoding (Rust, return_tensors=None)"    ):
												self.assert_dump_and_restore(tokenizer_r("Small example to encode"    )    )

									with self.subTest("BatchEncoding (Rust, return_tensors=NUMPY)"    ):
												self.assert_dump_and_restore(
												    tokenizer_r("Small example to encode" , return_tensors=TensorType.NUMPY    ) , np.array_equal    )

						@require_tf
						@require_tokenizers
						def __lowerCamelCase					(				self    )							->	Union[str, Any]:




									'''simple docstring'''


									import tensorflow as tf

									def tf_array_equals(__UpperCamelCase , __UpperCamelCase    ):
												return tf.reduce_all(tf.equal(__UpperCamelCase , __UpperCamelCase    )    )

									__UpperCamelCase    :    int								=      BertTokenizer.from_pretrained("bert-base-cased"    )
									__UpperCamelCase    :    Dict								=      BertTokenizerFast.from_pretrained("bert-base-cased"    )

									with self.subTest("BatchEncoding (Python, return_tensors=TENSORFLOW)"    ):
												self.assert_dump_and_restore(
												    tokenizer_p("Small example to encode" , return_tensors=TensorType.TENSORFLOW    ) , __UpperCamelCase    )

									with self.subTest("BatchEncoding (Rust, return_tensors=TENSORFLOW)"    ):
												self.assert_dump_and_restore(
												    tokenizer_r("Small example to encode" , return_tensors=TensorType.TENSORFLOW    ) , __UpperCamelCase    )

						@require_torch
						@require_tokenizers
						def __lowerCamelCase					(				self    )							->	Any:




									'''simple docstring'''


									import torch

									__UpperCamelCase    :    List[Any]								=      BertTokenizer.from_pretrained("bert-base-cased"    )
									__UpperCamelCase    :    Optional[Any]								=      BertTokenizerFast.from_pretrained("bert-base-cased"    )

									with self.subTest("BatchEncoding (Python, return_tensors=PYTORCH)"    ):
												self.assert_dump_and_restore(
												    tokenizer_p("Small example to encode" , return_tensors=TensorType.PYTORCH    ) , torch.equal    )

									with self.subTest("BatchEncoding (Rust, return_tensors=PYTORCH)"    ):
												self.assert_dump_and_restore(
												    tokenizer_r("Small example to encode" , return_tensors=TensorType.PYTORCH    ) , torch.equal    )

						@require_tokenizers
						def __lowerCamelCase					(				self    )							->	Any:




									'''simple docstring'''


									__UpperCamelCase    :    Optional[int]								=      BertTokenizer.from_pretrained("bert-base-cased"    )
									__UpperCamelCase    :    Tuple								=      BertTokenizerFast.from_pretrained("bert-base-cased"    )

									with self.subTest("Python Tokenizer"    ):
												self.assertFalse(tokenizer_p("Small example to_encode"    ).is_fast    )

									with self.subTest("Rust Tokenizer"    ):
												self.assertTrue(tokenizer_r("Small example to_encode"    ).is_fast    )

						@require_tokenizers
						def __lowerCamelCase					(				self    )							->	Union[str, Any]:




									'''simple docstring'''


									__UpperCamelCase    :    Any								=      BertTokenizerFast.from_pretrained("bert-base-cased"    )
									__UpperCamelCase    :    Dict								=      tokenizer_r(["Test", "\xad", "test"] , is_split_into_words=__UpperCamelCase    )

									self.assertEqual(encoded.word_to_tokens(0    ) , TokenSpan(start=1 , end=2    )    )
									self.assertEqual(encoded.word_to_tokens(1    ) , __UpperCamelCase    )
									self.assertEqual(encoded.word_to_tokens(2    ) , TokenSpan(start=2 , end=3    )    )

						def __lowerCamelCase					(				self    )							->	Optional[int]:




									'''simple docstring'''


									__UpperCamelCase    :    str								=      BatchEncoding({"inputs": [[1, 2, 3], [4, 5, 6]], "labels": [0, 1]}    )
									__UpperCamelCase    :    List[str]								=      batch.convert_to_tensors(tensor_type="np"    )
									self.assertEqual(tensor_batch["inputs"].shape , (2, 3)    )
									self.assertEqual(tensor_batch["labels"].shape , (2,)    )
									# test converting the converted
									with CaptureStderr() as cs:
												__UpperCamelCase    :    Optional[Any]								=      batch.convert_to_tensors(tensor_type="np"    )
									self.assertFalse(len(cs.err    ) , msg=f'''should have no warning, but got {cs.err}'''    )

									__UpperCamelCase    :    Union[str, Any]								=      BatchEncoding({"inputs": [1, 2, 3], "labels": 0}    )
									__UpperCamelCase    :    int								=      batch.convert_to_tensors(tensor_type="np" , prepend_batch_axis=__UpperCamelCase    )
									self.assertEqual(tensor_batch["inputs"].shape , (1, 3)    )
									self.assertEqual(tensor_batch["labels"].shape , (1,)    )

						@require_torch
						def __lowerCamelCase					(				self    )							->	List[str]:




									'''simple docstring'''


									__UpperCamelCase    :    Dict								=      BatchEncoding({"inputs": [[1, 2, 3], [4, 5, 6]], "labels": [0, 1]}    )
									__UpperCamelCase    :    List[Any]								=      batch.convert_to_tensors(tensor_type="pt"    )
									self.assertEqual(tensor_batch["inputs"].shape , (2, 3)    )
									self.assertEqual(tensor_batch["labels"].shape , (2,)    )
									# test converting the converted
									with CaptureStderr() as cs:
												__UpperCamelCase    :    Tuple								=      batch.convert_to_tensors(tensor_type="pt"    )
									self.assertFalse(len(cs.err    ) , msg=f'''should have no warning, but got {cs.err}'''    )

									__UpperCamelCase    :    Union[str, Any]								=      BatchEncoding({"inputs": [1, 2, 3], "labels": 0}    )
									__UpperCamelCase    :    List[Any]								=      batch.convert_to_tensors(tensor_type="pt" , prepend_batch_axis=__UpperCamelCase    )
									self.assertEqual(tensor_batch["inputs"].shape , (1, 3)    )
									self.assertEqual(tensor_batch["labels"].shape , (1,)    )

						@require_tf
						def __lowerCamelCase					(				self    )							->	Optional[Any]:




									'''simple docstring'''


									__UpperCamelCase    :    List[Any]								=      BatchEncoding({"inputs": [[1, 2, 3], [4, 5, 6]], "labels": [0, 1]}    )
									__UpperCamelCase    :    Tuple								=      batch.convert_to_tensors(tensor_type="tf"    )
									self.assertEqual(tensor_batch["inputs"].shape , (2, 3)    )
									self.assertEqual(tensor_batch["labels"].shape , (2,)    )
									# test converting the converted
									with CaptureStderr() as cs:
												__UpperCamelCase    :    Optional[int]								=      batch.convert_to_tensors(tensor_type="tf"    )
									self.assertFalse(len(cs.err    ) , msg=f'''should have no warning, but got {cs.err}'''    )

									__UpperCamelCase    :    str								=      BatchEncoding({"inputs": [1, 2, 3], "labels": 0}    )
									__UpperCamelCase    :    Union[str, Any]								=      batch.convert_to_tensors(tensor_type="tf" , prepend_batch_axis=__UpperCamelCase    )
									self.assertEqual(tensor_batch["inputs"].shape , (1, 3)    )
									self.assertEqual(tensor_batch["labels"].shape , (1,)    )

						@require_flax
						def __lowerCamelCase					(				self    )							->	List[Any]:




									'''simple docstring'''


									__UpperCamelCase    :    str								=      BatchEncoding({"inputs": [[1, 2, 3], [4, 5, 6]], "labels": [0, 1]}    )
									__UpperCamelCase    :    int								=      batch.convert_to_tensors(tensor_type="jax"    )
									self.assertEqual(tensor_batch["inputs"].shape , (2, 3)    )
									self.assertEqual(tensor_batch["labels"].shape , (2,)    )
									# test converting the converted
									with CaptureStderr() as cs:
												__UpperCamelCase    :    Dict								=      batch.convert_to_tensors(tensor_type="jax"    )
									self.assertFalse(len(cs.err    ) , msg=f'''should have no warning, but got {cs.err}'''    )

									__UpperCamelCase    :    Tuple								=      BatchEncoding({"inputs": [1, 2, 3], "labels": 0}    )
									__UpperCamelCase    :    Union[str, Any]								=      batch.convert_to_tensors(tensor_type="jax" , prepend_batch_axis=__UpperCamelCase    )
									self.assertEqual(tensor_batch["inputs"].shape , (1, 3)    )
									self.assertEqual(tensor_batch["labels"].shape , (1,)    )

						def __lowerCamelCase					(				self    )							->	int:




									'''simple docstring'''


									__UpperCamelCase    :    str								=      [{"input_ids": np.array([0, 1, 2]    )}, {"input_ids": np.array([0, 1, 2, 3]    )}]
									__UpperCamelCase    :    Any								=      BertTokenizer.from_pretrained("bert-base-cased"    )

									__UpperCamelCase    :    Optional[Any]								=      tokenizer.pad(__UpperCamelCase , padding=__UpperCamelCase    )
									self.assertTrue(isinstance(batch["input_ids"] , np.ndarray    )    )
									self.assertEqual(batch["input_ids"].tolist() , [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]    )
									__UpperCamelCase    :    Optional[Any]								=      tokenizer.pad(__UpperCamelCase , padding=__UpperCamelCase , return_tensors="np"    )
									self.assertTrue(isinstance(batch["input_ids"] , np.ndarray    )    )
									self.assertEqual(batch["input_ids"].tolist() , [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]    )

						@require_torch
						def __lowerCamelCase					(				self    )							->	Optional[int]:




									'''simple docstring'''


									import torch

									__UpperCamelCase    :    List[str]								=      [{"input_ids": torch.tensor([0, 1, 2]    )}, {"input_ids": torch.tensor([0, 1, 2, 3]    )}]
									__UpperCamelCase    :    str								=      BertTokenizer.from_pretrained("bert-base-cased"    )

									__UpperCamelCase    :    str								=      tokenizer.pad(__UpperCamelCase , padding=__UpperCamelCase    )
									self.assertTrue(isinstance(batch["input_ids"] , torch.Tensor    )    )
									self.assertEqual(batch["input_ids"].tolist() , [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]    )
									__UpperCamelCase    :    int								=      tokenizer.pad(__UpperCamelCase , padding=__UpperCamelCase , return_tensors="pt"    )
									self.assertTrue(isinstance(batch["input_ids"] , torch.Tensor    )    )
									self.assertEqual(batch["input_ids"].tolist() , [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]    )

						@require_tf
						def __lowerCamelCase					(				self    )							->	List[Any]:




									'''simple docstring'''


									import tensorflow as tf

									__UpperCamelCase    :    List[Any]								=      [{"input_ids": tf.constant([0, 1, 2]    )}, {"input_ids": tf.constant([0, 1, 2, 3]    )}]
									__UpperCamelCase    :    int								=      BertTokenizer.from_pretrained("bert-base-cased"    )

									__UpperCamelCase    :    Optional[Any]								=      tokenizer.pad(__UpperCamelCase , padding=__UpperCamelCase    )
									self.assertTrue(isinstance(batch["input_ids"] , tf.Tensor    )    )
									self.assertEqual(batch["input_ids"].numpy().tolist() , [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]    )
									__UpperCamelCase    :    List[str]								=      tokenizer.pad(__UpperCamelCase , padding=__UpperCamelCase , return_tensors="tf"    )
									self.assertTrue(isinstance(batch["input_ids"] , tf.Tensor    )    )
									self.assertEqual(batch["input_ids"].numpy().tolist() , [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]    )

						@require_tokenizers
						def __lowerCamelCase					(				self    )							->	int:




									'''simple docstring'''


									__UpperCamelCase    :    List[Any]								=      Tokenizer(WordPiece(unk_token="[UNK]"    )    )
									PreTrainedTokenizerFast(tokenizer_object=__UpperCamelCase    )




						@require_tokenizers
						def __lowerCamelCase					(				self    )							->	Optional[int]:




									'''simple docstring'''


									__UpperCamelCase    :    Union[str, Any]								=      Tokenizer(WordPiece(unk_token="[UNK]"    )    )
									with tempfile.TemporaryDirectory() as tmpdirname:
												bert_tokenizer.save(os.path.join(__UpperCamelCase , "tokenizer.json"    )    )
												PreTrainedTokenizerFast(tokenizer_file=os.path.join(__UpperCamelCase , "tokenizer.json"    )    )