



import math
from typing import Optional

import numpy as np
import torch
from torch import nn

from .activations import get_activation




def 						UpperCAmelCase (    _lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase = False			,     _lowerCamelCase = 1			,     _lowerCamelCase = 1			,     _lowerCamelCase = 1_0000			,     ):
			assert len(timesteps.shape     ) == 1, "Timesteps should be a 1d-array"

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

			A				:       Tuple														=    torch.exp(_lowerCamelCase     )
			A				:       int														=    timesteps[:, None].float() * emb[None, :]

			# scale embeddings
			A				:       List[Any]														=    scale * emb

			# concat sine and cosine embeddings
			A				:       List[str]														=    torch.cat([torch.sin(_lowerCamelCase     ), torch.cos(_lowerCamelCase     )]			,     dim=-1     )

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

			# zero pad
			if embedding_dim % 2 == 1:
						A				:       Any														=    torch.nn.functional.pad(_lowerCamelCase			,     (0, 1, 0, 0)     )
			return emb




def 						UpperCAmelCase (    _lowerCamelCase			,     _lowerCamelCase			,     _lowerCamelCase=False			,     _lowerCamelCase=0     ):
			A				:       Union[str, Any]														=    np.arange(_lowerCamelCase			,     dtype=np.floataa     )
			A				:       List[str]														=    np.arange(_lowerCamelCase			,     dtype=np.floataa     )
			A				:       Tuple														=    np.meshgrid(_lowerCamelCase			,     _lowerCamelCase     )  # here w goes first
			A				:       int														=    np.stack(_lowerCamelCase			,     axis=0     )

			A				:       List[str]														=    grid.reshape([2, 1, grid_size, grid_size]     )
			A				:       Dict														=    get_ad_sincos_pos_embed_from_grid(_lowerCamelCase			,     _lowerCamelCase     )
			if cls_token and extra_tokens > 0:
						A				:       Optional[int]														=    np.concatenate([np.zeros([extra_tokens, embed_dim]     ), pos_embed]			,     axis=0     )
			return pos_embed




def 						UpperCAmelCase (    _lowerCamelCase			,     _lowerCamelCase     ):
			if embed_dim % 2 != 0:
						raise ValueError("embed_dim must be divisible by 2"     )

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

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




def 						UpperCAmelCase (    _lowerCamelCase			,     _lowerCamelCase     ):
			if embed_dim % 2 != 0:
						raise ValueError("embed_dim must be divisible by 2"     )

			A				:       Tuple														=    np.arange(embed_dim // 2			,     dtype=np.floataa     )
			omega /= embed_dim / 2.0
			A				:       Any														=    1.0 / 1_0000**omega  # (D/2,)

			A				:       Union[str, Any]														=    pos.reshape(-1     )  # (M,)
			A				:       str														=    np.einsum("m,d->md"			,     _lowerCamelCase			,     _lowerCamelCase     )  # (M, D/2), outer product

			A				:       Any														=    np.sin(_lowerCamelCase     )  # (M, D/2)
			A				:       str														=    np.cos(_lowerCamelCase     )  # (M, D/2)

			A				:       Optional[Any]														=    np.concatenate([emb_sin, emb_cos]			,     axis=1     )  # (M, D)
			return emb

class 						lowerCamelCase_     (			nn.Module    ):






						'''simple docstring'''







						def __init__(						self   :      str						,						__lowerCamelCase   :      List[Any]=2_24						,						__lowerCamelCase   :      Union[str, Any]=2_24						,						__lowerCamelCase   :      Union[str, Any]=16						,						__lowerCamelCase   :      Tuple=3						,						__lowerCamelCase   :      Optional[int]=7_68						,						__lowerCamelCase   :      Any=False						,						__lowerCamelCase   :      List[str]=True						,						__lowerCamelCase   :      int=True						,						)   ->					Optional[Any]:
									super().__init__()

									A				:       Optional[Any]														=    (height // patch_size) * (width // patch_size)
									A				:       Union[str, Any]														=    flatten
									A				:       Any														=    layer_norm

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

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







						def       SCREAMING_SNAKE_CASE__		(						self   :      Tuple						,						__lowerCamelCase   :      List[str]			)   ->					Union[str, Any]:
									A				:       Optional[int]														=    self.proj(__lowerCamelCase			)
									if self.flatten:
												A				:       Optional[Any]														=    latent.flatten(2			).transpose(1						,						2			)  # BCHW -> BNC
									if self.layer_norm:
												A				:       str														=    self.norm(__lowerCamelCase			)
									return latent + self.pos_embed







class 						lowerCamelCase_     (			nn.Module    ):






						'''simple docstring'''







						def __init__(						self   :      str						,						__lowerCamelCase   :      int						,						__lowerCamelCase   :      int						,						__lowerCamelCase   :      str = "silu"						,						__lowerCamelCase   :      int = None						,						__lowerCamelCase   :      Optional[str] = None						,						__lowerCamelCase   :      List[str]=None						,						)   ->					str:
									super().__init__()

									A				:       Tuple														=    nn.Linear(__lowerCamelCase						,						__lowerCamelCase			)

									if cond_proj_dim is not None:
												A				:       Optional[int]														=    nn.Linear(__lowerCamelCase						,						__lowerCamelCase						,						bias=__lowerCamelCase			)
									else:
												A				:       Optional[Any]														=    None

									A				:       Tuple														=    get_activation(__lowerCamelCase			)

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

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







						def       SCREAMING_SNAKE_CASE__		(						self   :      Tuple						,						__lowerCamelCase   :      int						,						__lowerCamelCase   :      Optional[int]=None			)   ->					List[str]:
									if condition is not None:
												A				:       Optional[int]														=    sample + self.cond_proj(__lowerCamelCase			)
									A				:       str														=    self.linear_a(__lowerCamelCase			)

									if self.act is not None:
												A				:       List[str]														=    self.act(__lowerCamelCase			)

									A				:       List[str]														=    self.linear_a(__lowerCamelCase			)

									if self.post_act is not None:
												A				:       Tuple														=    self.post_act(__lowerCamelCase			)
									return sample







class 						lowerCamelCase_     (			nn.Module    ):






						'''simple docstring'''







						def __init__(						self   :      List[str]						,						__lowerCamelCase   :      int						,						__lowerCamelCase   :      bool						,						__lowerCamelCase   :      float			)   ->					Dict:
									super().__init__()
									A				:       Dict														=    num_channels
									A				:       Any														=    flip_sin_to_cos
									A				:       Tuple														=    downscale_freq_shift







						def       SCREAMING_SNAKE_CASE__		(						self   :      Optional[Any]						,						__lowerCamelCase   :      Optional[int]			)   ->					str:
									A				:       int														=    get_timestep_embedding(
									    __lowerCamelCase						,						self.num_channels						,						flip_sin_to_cos=self.flip_sin_to_cos						,						downscale_freq_shift=self.downscale_freq_shift						,						)
									return t_emb







class 						lowerCamelCase_     (			nn.Module    ):






						'''simple docstring'''







						def __init__(						self   :      Optional[int]						,						__lowerCamelCase   :      int = 2_56						,						__lowerCamelCase   :      float = 1.0						,						__lowerCamelCase   :      int=True						,						__lowerCamelCase   :      Optional[int]=True						,						__lowerCamelCase   :      Tuple=False			)   ->					Union[str, Any]:
									super().__init__()
									A				:       Optional[int]														=    nn.Parameter(torch.randn(__lowerCamelCase			) * scale						,						requires_grad=__lowerCamelCase			)
									A				:       Optional[int]														=    log
									A				:       Tuple														=    flip_sin_to_cos

									if set_W_to_weight:
												# to delete later
												A				:       Optional[Any]														=    nn.Parameter(torch.randn(__lowerCamelCase			) * scale						,						requires_grad=__lowerCamelCase			)

												A				:       Optional[int]														=    self.W







						def       SCREAMING_SNAKE_CASE__		(						self   :      str						,						__lowerCamelCase   :      Optional[int]			)   ->					int:
									if self.log:
												A				:       str														=    torch.log(__lowerCamelCase			)

									A				:       List[str]														=    x[:, None] * self.weight[None, :] * 2 * np.pi

									if self.flip_sin_to_cos:
												A				:       Union[str, Any]														=    torch.cat([torch.cos(__lowerCamelCase			), torch.sin(__lowerCamelCase			)]						,						dim=-1			)
									else:
												A				:       List[str]														=    torch.cat([torch.sin(__lowerCamelCase			), torch.cos(__lowerCamelCase			)]						,						dim=-1			)
									return out







class 						lowerCamelCase_     (			nn.Module    ):






						'''simple docstring'''







						def __init__(						self   :      List[Any]						,						__lowerCamelCase   :      int						,						__lowerCamelCase   :      int						,						__lowerCamelCase   :      int						,						__lowerCamelCase   :      int						,						)   ->					Optional[Any]:
									super().__init__()

									A				:       Any														=    height
									A				:       Tuple														=    width
									A				:       Any														=    num_embed
									A				:       str														=    embed_dim

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







						def       SCREAMING_SNAKE_CASE__		(						self   :      List[str]						,						__lowerCamelCase   :      List[str]			)   ->					Union[str, Any]:
									A				:       Union[str, Any]														=    self.emb(__lowerCamelCase			)

									A				:       List[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
									A				:       Tuple														=    height_emb.unsqueeze(2			)

									A				:       Dict														=    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
									A				:       str														=    width_emb.unsqueeze(1			)

									A				:       Optional[int]														=    height_emb + width_emb

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

									A				:       Tuple														=    emb + pos_emb[:, : emb.shape[1], :]

									return emb







class 						lowerCamelCase_     (			nn.Module    ):






						'''simple docstring'''







						def __init__(						self   :      List[Any]						,						__lowerCamelCase   :      List[str]						,						__lowerCamelCase   :      Optional[int]						,						__lowerCamelCase   :      Tuple			)   ->					Union[str, Any]:
									super().__init__()
									A				:       Optional[Any]														=    dropout_prob > 0
									A				:       int														=    nn.Embedding(num_classes + use_cfg_embedding						,						__lowerCamelCase			)
									A				:       str														=    num_classes
									A				:       Optional[Any]														=    dropout_prob







						def       SCREAMING_SNAKE_CASE__		(						self   :      str						,						__lowerCamelCase   :      Optional[int]						,						__lowerCamelCase   :      Union[str, Any]=None			)   ->					int:
									if force_drop_ids is None:
												A				:       Optional[Any]														=    torch.rand(labels.shape[0]						,						device=labels.device			) < self.dropout_prob
									else:
												A				:       int														=    torch.tensor(force_drop_ids == 1			)
									A				:       Any														=    torch.where(__lowerCamelCase						,						self.num_classes						,						__lowerCamelCase			)
									return labels







						def       SCREAMING_SNAKE_CASE__		(						self   :      Dict						,						__lowerCamelCase   :      torch.LongTensor						,						__lowerCamelCase   :      List[Any]=None			)   ->					Any:
									A				:       List[Any]														=    self.dropout_prob > 0
									if (self.training and use_dropout) or (force_drop_ids is not None):
												A				:       Tuple														=    self.token_drop(__lowerCamelCase						,						__lowerCamelCase			)
									A				:       Tuple														=    self.embedding_table(__lowerCamelCase			)
									return embeddings







class 						lowerCamelCase_     (			nn.Module    ):






						'''simple docstring'''







						def __init__(						self   :      int						,						__lowerCamelCase   :      int = 10_24						,						__lowerCamelCase   :      int = 7_68						,						__lowerCamelCase   :      int = 7_68						,						__lowerCamelCase   :      int = 10						,						)   ->					Any:
									super().__init__()

									A				:       str														=    num_image_text_embeds
									A				:       str														=    nn.Linear(__lowerCamelCase						,						self.num_image_text_embeds * cross_attention_dim			)
									A				:       Tuple														=    nn.Linear(__lowerCamelCase						,						__lowerCamelCase			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      List[str]						,						__lowerCamelCase   :      torch.FloatTensor						,						__lowerCamelCase   :      torch.FloatTensor			)   ->					List[str]:
									A				:       Union[str, Any]														=    text_embeds.shape[0]

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

									# text
									A				:       Dict														=    self.text_proj(__lowerCamelCase			)

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







class 						lowerCamelCase_     (			nn.Module    ):






						'''simple docstring'''







						def __init__(						self   :      Optional[Any]						,						__lowerCamelCase   :      int = 7_68						,						__lowerCamelCase   :      int = 7_68						,						__lowerCamelCase   :      int = 32						,						)   ->					Union[str, Any]:
									super().__init__()

									A				:       Dict														=    num_image_text_embeds
									A				:       List[Any]														=    nn.Linear(__lowerCamelCase						,						self.num_image_text_embeds * cross_attention_dim			)
									A				:       Tuple														=    nn.LayerNorm(__lowerCamelCase			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      Tuple						,						__lowerCamelCase   :      torch.FloatTensor			)   ->					Any:
									A				:       Tuple														=    image_embeds.shape[0]

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







class 						lowerCamelCase_     (			nn.Module    ):






						'''simple docstring'''







						def __init__(						self   :      Union[str, Any]						,						__lowerCamelCase   :      Dict						,						__lowerCamelCase   :      int						,						__lowerCamelCase   :      Optional[Any]=0.1			)   ->					Union[str, Any]:
									super().__init__()

									A				:       str														=    Timesteps(num_channels=2_56						,						flip_sin_to_cos=__lowerCamelCase						,						downscale_freq_shift=1			)
									A				:       Dict														=    TimestepEmbedding(in_channels=2_56						,						time_embed_dim=__lowerCamelCase			)
									A				:       Optional[int]														=    LabelEmbedding(__lowerCamelCase						,						__lowerCamelCase						,						__lowerCamelCase			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      List[str]						,						__lowerCamelCase   :      Optional[int]						,						__lowerCamelCase   :      Optional[int]						,						__lowerCamelCase   :      Dict=None			)   ->					Any:
									A				:       int														=    self.time_proj(__lowerCamelCase			)
									A				:       Tuple														=    self.timestep_embedder(timesteps_proj.to(dtype=__lowerCamelCase			)			)  # (N, D)

									A				:       int														=    self.class_embedder(__lowerCamelCase			)  # (N, D)

									A				:       Union[str, Any]														=    timesteps_emb + class_labels  # (N, D)

									return conditioning







class 						lowerCamelCase_     (			nn.Module    ):






						'''simple docstring'''







						def __init__(						self   :      Optional[int]						,						__lowerCamelCase   :      int						,						__lowerCamelCase   :      int						,						__lowerCamelCase   :      int = 64			)   ->					Tuple:
									super().__init__()
									A				:       Optional[int]														=    nn.LayerNorm(__lowerCamelCase			)
									A				:       int														=    AttentionPooling(__lowerCamelCase						,						__lowerCamelCase			)
									A				:       Tuple														=    nn.Linear(__lowerCamelCase						,						__lowerCamelCase			)
									A				:       str														=    nn.LayerNorm(__lowerCamelCase			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      Optional[int]						,						__lowerCamelCase   :      Tuple			)   ->					Tuple:
									A				:       str														=    self.norma(__lowerCamelCase			)
									A				:       Dict														=    self.pool(__lowerCamelCase			)
									A				:       int														=    self.proj(__lowerCamelCase			)
									A				:       str														=    self.norma(__lowerCamelCase			)
									return hidden_states







class 						lowerCamelCase_     (			nn.Module    ):






						'''simple docstring'''







						def __init__(						self   :      Any						,						__lowerCamelCase   :      int = 7_68						,						__lowerCamelCase   :      int = 7_68						,						__lowerCamelCase   :      int = 15_36			)   ->					str:
									super().__init__()
									A				:       Optional[int]														=    nn.Linear(__lowerCamelCase						,						__lowerCamelCase			)
									A				:       Any														=    nn.LayerNorm(__lowerCamelCase			)
									A				:       Tuple														=    nn.Linear(__lowerCamelCase						,						__lowerCamelCase			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      Union[str, Any]						,						__lowerCamelCase   :      torch.FloatTensor						,						__lowerCamelCase   :      torch.FloatTensor			)   ->					str:
									# text
									A				:       Union[str, Any]														=    self.text_proj(__lowerCamelCase			)
									A				:       Tuple														=    self.text_norm(__lowerCamelCase			)

									# image
									A				:       Union[str, Any]														=    self.image_proj(__lowerCamelCase			)

									return time_image_embeds + time_text_embeds







class 						lowerCamelCase_     (			nn.Module    ):






						'''simple docstring'''







						def __init__(						self   :      str						,						__lowerCamelCase   :      int = 7_68						,						__lowerCamelCase   :      int = 15_36			)   ->					Tuple:
									super().__init__()
									A				:       Optional[Any]														=    nn.Linear(__lowerCamelCase						,						__lowerCamelCase			)
									A				:       Tuple														=    nn.LayerNorm(__lowerCamelCase			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      Union[str, Any]						,						__lowerCamelCase   :      torch.FloatTensor			)   ->					Tuple:
									# image
									A				:       str														=    self.image_proj(__lowerCamelCase			)
									A				:       int														=    self.image_norm(__lowerCamelCase			)
									return time_image_embeds







class 						lowerCamelCase_     (			nn.Module    ):






						'''simple docstring'''







						def __init__(						self   :      Union[str, Any]						,						__lowerCamelCase   :      int = 7_68						,						__lowerCamelCase   :      int = 15_36			)   ->					Union[str, Any]:
									super().__init__()
									A				:       Union[str, Any]														=    nn.Linear(__lowerCamelCase						,						__lowerCamelCase			)
									A				:       str														=    nn.LayerNorm(__lowerCamelCase			)
									A				:       str														=    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       SCREAMING_SNAKE_CASE__		(						self   :      Optional[int]						,						__lowerCamelCase   :      torch.FloatTensor						,						__lowerCamelCase   :      torch.FloatTensor			)   ->					Tuple:
									# image
									A				:       Union[str, Any]														=    self.image_proj(__lowerCamelCase			)
									A				:       Union[str, Any]														=    self.image_norm(__lowerCamelCase			)
									A				:       Optional[int]														=    self.input_hint_block(__lowerCamelCase			)
									return time_image_embeds, hint







class 						lowerCamelCase_     (			nn.Module    ):






						'''simple docstring'''







						def __init__(						self   :      str						,						__lowerCamelCase   :      Optional[Any]						,						__lowerCamelCase   :      Dict						,						__lowerCamelCase   :      Dict=None			)   ->					int:
									super().__init__()
									A				:       List[str]														=    dtype
									A				:       Any														=    nn.Parameter(torch.randn(1						,						__lowerCamelCase			) / embed_dim**0.5			)
									A				:       Optional[Any]														=    nn.Linear(__lowerCamelCase						,						__lowerCamelCase						,						dtype=self.dtype			)
									A				:       List[str]														=    nn.Linear(__lowerCamelCase						,						__lowerCamelCase						,						dtype=self.dtype			)
									A				:       Optional[int]														=    nn.Linear(__lowerCamelCase						,						__lowerCamelCase						,						dtype=self.dtype			)
									A				:       str														=    num_heads
									A				:       Optional[Any]														=    embed_dim // self.num_heads







						def       SCREAMING_SNAKE_CASE__		(						self   :      List[Any]						,						__lowerCamelCase   :      int			)   ->					List[str]:
									A							,			A							,			A				:       List[str]														=    x.size()

									def shape(__lowerCamelCase   :      Dict			):
												# (bs, length, width) --> (bs, length, n_heads, dim_per_head)
												A				:       List[str]														=    x.view(__lowerCamelCase						,						-1						,						self.num_heads						,						self.dim_per_head			)
												# (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head)
												A				:       Optional[Any]														=    x.transpose(1						,						2			)
												# (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head)
												A				:       Optional[Any]														=    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)
												A				:       Optional[Any]														=    x.transpose(1						,						2			)
												return x

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

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

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

									# (bs*n_heads, dim_per_head, class_token_length)
									A				:       List[str]														=    torch.einsum("bts,bcs->bct"						,						__lowerCamelCase						,						__lowerCamelCase			)

									# (bs, length+1, width)
									A				:       List[Any]														=    a.reshape(__lowerCamelCase						,						-1						,						1			).transpose(1						,						2			)

									return a[:, 0, :]  # cls_token




from copy import deepcopy
from unittest.case import TestCase

import pytest

from datasets.arrow_dataset import Dataset
from datasets.features import Audio, ClassLabel, Features, Image, Sequence, Value
from datasets.info import DatasetInfo
from datasets.tasks import (
    AudioClassification,
    AutomaticSpeechRecognition,
    ImageClassification,
    LanguageModeling,
    QuestionAnsweringExtractive,
    Summarization,
    TextClassification,
    task_template_from_dict,
)
from datasets.utils.py_utils import asdict


__SCREAMING_SNAKE_CASE     =	{
    """id""": """5733be284776f41900661182""",
    """title""": """University_of_Notre_Dame""",
    """context""": """Architecturally, the school has a Catholic character. Atop the Main Building\'s gold dome is a golden statue of the Virgin Mary. Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend \"Venite Ad Me Omnes\". Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection. It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858. At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome), is a simple, modern stone statue of Mary.""",
    """question""": """To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?""",
    """answers""": {"""text""": ["""Saint Bernadette Soubirous"""], """answer_start""": [515]},
}




@pytest.mark.parametrize(
    "task_cls"			,     [
        AudioClassification,
        AutomaticSpeechRecognition,
        ImageClassification,
        LanguageModeling,
        QuestionAnsweringExtractive,
        Summarization,
        TextClassification,
    ]			,     )
def 						UpperCAmelCase (    _lowerCamelCase     ):
			A				:       Optional[int]														=    task_cls()
			A				:       int														=    asdict(_lowerCamelCase     )
			A				:       int														=    task_template_from_dict(_lowerCamelCase     )
			assert task == reloaded

class 						lowerCamelCase_     :






						'''simple docstring'''







						def       SCREAMING_SNAKE_CASE__		(						self   :      Union[str, Any]			)   ->					Any:
									A				:       str														=    LanguageModeling(text_column="input_text"			)
									assert {"input_text": "text"} == task.column_mapping







						def       SCREAMING_SNAKE_CASE__		(						self   :      Any			)   ->					str:
									A				:       Tuple														=    Features({"text": Value("string"			)}			)
									A				:       Dict														=    {"text_column": "input_text"}
									A				:       Optional[int]														=    LanguageModeling.from_dict(__lowerCamelCase			)
									assert "language-modeling" == task.task
									assert input_schema == task.input_schema







class 						lowerCamelCase_     (			_A    ):






						'''simple docstring'''







						def       SCREAMING_SNAKE_CASE__		(						self   :      List[Any]			)   ->					str:
									A				:       List[Any]														=    sorted(["pos", "neg"]			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      str			)   ->					Optional[int]:
									A				:       List[Any]														=    TextClassification(text_column="input_text"						,						label_column="input_label"			)
									self.assertDictEqual({"input_text": "text", "input_label": "labels"}						,						task.column_mapping			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      Dict			)   ->					Optional[int]:
									A				:       Tuple														=    Features({"text": Value("string"			)}			)
									# Labels are cast to tuple during `TextClassification.__post_init__`, so we do the same here
									A				:       str														=    Features({"labels": ClassLabel}			)
									A				:       List[Any]														=    {"text_column": "input_text", "label_column": "input_labels"}
									A				:       Any														=    TextClassification.from_dict(__lowerCamelCase			)
									self.assertEqual("text-classification"						,						task.task			)
									self.assertEqual(__lowerCamelCase						,						task.input_schema			)
									self.assertEqual(__lowerCamelCase						,						task.label_schema			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      Tuple			)   ->					int:
									A				:       Dict														=    TextClassification(text_column="input_text"						,						label_column="input_label"			)
									self.assertEqual(task.label_schema["labels"]						,						__lowerCamelCase			)
									A				:       Any														=    task.align_with_features(Features({"input_label": ClassLabel(names=self.labels			)}			)			)
									self.assertEqual(task.label_schema["labels"]						,						ClassLabel(names=self.labels			)			)







class 						lowerCamelCase_     (			_A    ):






						'''simple docstring'''







						def       SCREAMING_SNAKE_CASE__		(						self   :      str			)   ->					Dict:
									A				:       Optional[int]														=    QuestionAnsweringExtractive(
									    context_column="input_context"						,						question_column="input_question"						,						answers_column="input_answers"			)
									self.assertDictEqual(
									    {"input_context": "context", "input_question": "question", "input_answers": "answers"}						,						task.column_mapping			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      Optional[int]			)   ->					Tuple:
									A				:       Dict														=    Features({"question": Value("string"			), "context": Value("string"			)}			)
									A				:       int														=    Features(
									    {
									        "answers": Sequence(
									            {
									                "text": Value("string"			),
									                "answer_start": Value("int32"			),
									            }			)
									    }			)
									A				:       Optional[int]														=    {
									    "context_column": "input_input_context",
									    "question_column": "input_question",
									    "answers_column": "input_answers",
									}
									A				:       Tuple														=    QuestionAnsweringExtractive.from_dict(__lowerCamelCase			)
									self.assertEqual("question-answering-extractive"						,						task.task			)
									self.assertEqual(__lowerCamelCase						,						task.input_schema			)
									self.assertEqual(__lowerCamelCase						,						task.label_schema			)







class 						lowerCamelCase_     (			_A    ):






						'''simple docstring'''







						def       SCREAMING_SNAKE_CASE__		(						self   :      Optional[Any]			)   ->					Tuple:
									A				:       Optional[Any]														=    Summarization(text_column="input_text"						,						summary_column="input_summary"			)
									self.assertDictEqual({"input_text": "text", "input_summary": "summary"}						,						task.column_mapping			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      List[Any]			)   ->					Any:
									A				:       Union[str, Any]														=    Features({"text": Value("string"			)}			)
									A				:       Tuple														=    Features({"summary": Value("string"			)}			)
									A				:       Optional[Any]														=    {"text_column": "input_text", "summary_column": "input_summary"}
									A				:       str														=    Summarization.from_dict(__lowerCamelCase			)
									self.assertEqual("summarization"						,						task.task			)
									self.assertEqual(__lowerCamelCase						,						task.input_schema			)
									self.assertEqual(__lowerCamelCase						,						task.label_schema			)







class 						lowerCamelCase_     (			_A    ):






						'''simple docstring'''







						def       SCREAMING_SNAKE_CASE__		(						self   :      Union[str, Any]			)   ->					Any:
									A				:       Union[str, Any]														=    AutomaticSpeechRecognition(audio_column="input_audio"						,						transcription_column="input_transcription"			)
									self.assertDictEqual({"input_audio": "audio", "input_transcription": "transcription"}						,						task.column_mapping			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      List[Any]			)   ->					str:
									A				:       Tuple														=    Features({"audio": Audio()}			)
									A				:       Any														=    Features({"transcription": Value("string"			)}			)
									A				:       List[str]														=    {
									    "audio_column": "input_audio",
									    "transcription_column": "input_transcription",
									}
									A				:       Dict														=    AutomaticSpeechRecognition.from_dict(__lowerCamelCase			)
									self.assertEqual("automatic-speech-recognition"						,						task.task			)
									self.assertEqual(__lowerCamelCase						,						task.input_schema			)
									self.assertEqual(__lowerCamelCase						,						task.label_schema			)







class 						lowerCamelCase_     (			_A    ):






						'''simple docstring'''







						def       SCREAMING_SNAKE_CASE__		(						self   :      List[Any]			)   ->					Tuple:
									A				:       Optional[Any]														=    sorted(["pos", "neg"]			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      Optional[Any]			)   ->					Union[str, Any]:
									A				:       Optional[int]														=    AudioClassification(audio_column="input_audio"						,						label_column="input_label"			)
									self.assertDictEqual({"input_audio": "audio", "input_label": "labels"}						,						task.column_mapping			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      Tuple			)   ->					Tuple:
									A				:       Union[str, Any]														=    Features({"audio": Audio()}			)
									A				:       Dict														=    Features({"labels": ClassLabel}			)
									A				:       Tuple														=    {
									    "audio_column": "input_image",
									    "label_column": "input_label",
									}
									A				:       Any														=    AudioClassification.from_dict(__lowerCamelCase			)
									self.assertEqual("audio-classification"						,						task.task			)
									self.assertEqual(__lowerCamelCase						,						task.input_schema			)
									self.assertEqual(__lowerCamelCase						,						task.label_schema			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      Tuple			)   ->					Any:
									A				:       str														=    AudioClassification(audio_column="input_audio"						,						label_column="input_label"			)
									self.assertEqual(task.label_schema["labels"]						,						__lowerCamelCase			)
									A				:       List[str]														=    task.align_with_features(Features({"input_label": ClassLabel(names=self.labels			)}			)			)
									self.assertEqual(task.label_schema["labels"]						,						ClassLabel(names=self.labels			)			)







class 						lowerCamelCase_     (			_A    ):






						'''simple docstring'''







						def       SCREAMING_SNAKE_CASE__		(						self   :      List[str]			)   ->					Optional[int]:
									A				:       int														=    sorted(["pos", "neg"]			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      Tuple			)   ->					int:
									A				:       List[Any]														=    ImageClassification(image_column="input_image"						,						label_column="input_label"			)
									self.assertDictEqual({"input_image": "image", "input_label": "labels"}						,						task.column_mapping			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      Any			)   ->					int:
									A				:       Optional[int]														=    Features({"image": Image()}			)
									A				:       str														=    Features({"labels": ClassLabel}			)
									A				:       List[str]														=    {
									    "image_column": "input_image",
									    "label_column": "input_label",
									}
									A				:       Tuple														=    ImageClassification.from_dict(__lowerCamelCase			)
									self.assertEqual("image-classification"						,						task.task			)
									self.assertEqual(__lowerCamelCase						,						task.input_schema			)
									self.assertEqual(__lowerCamelCase						,						task.label_schema			)







						def       SCREAMING_SNAKE_CASE__		(						self   :      Union[str, Any]			)   ->					Tuple:
									A				:       str														=    ImageClassification(image_column="input_image"						,						label_column="input_label"			)
									self.assertEqual(task.label_schema["labels"]						,						__lowerCamelCase			)
									A				:       Optional[Any]														=    task.align_with_features(Features({"input_label": ClassLabel(names=self.labels			)}			)			)
									self.assertEqual(task.label_schema["labels"]						,						ClassLabel(names=self.labels			)			)







class 						lowerCamelCase_     (			_A    ):






						'''simple docstring'''







						def       SCREAMING_SNAKE_CASE__		(						self   :      Optional[Any]			)   ->					Optional[int]:
									A				:       Dict														=    DatasetInfo(task_templates=QuestionAnsweringExtractive()			)
									A				:       List[Any]														=    Dataset.from_dict({k: [v] for k, v in SAMPLE_QUESTION_ANSWERING_EXTRACTIVE.items()}						,						info=__lowerCamelCase			)
									assert isinstance(dataset.info.task_templates						,						__lowerCamelCase			)
									assert len(dataset.info.task_templates			) == 1

									def keep_task(__lowerCamelCase   :      List[str]			):
												return x

									def dont_keep_task(__lowerCamelCase   :      Any			):
												A				:       Optional[Any]														=    deepcopy(__lowerCamelCase			)
												A				:       List[Any]														=    0
												return out

									A				:       Optional[int]														=    dataset.map(__lowerCamelCase			)
									assert mapped_dataset.info.task_templates == dataset.info.task_templates
									# reload from cache
									A				:       List[Any]														=    dataset.map(__lowerCamelCase			)
									assert mapped_dataset.info.task_templates == dataset.info.task_templates

									A				:       Union[str, Any]														=    dataset.map(__lowerCamelCase			)
									assert mapped_dataset.info.task_templates == []
									# reload from cache
									A				:       Optional[Any]														=    dataset.map(__lowerCamelCase			)
									assert mapped_dataset.info.task_templates == []







						def       SCREAMING_SNAKE_CASE__		(						self   :      str			)   ->					Tuple:
									A				:       Optional[Any]														=    Features({"text": Value("string"			), "label": ClassLabel(names=("pos", "neg")			)}			)
									A				:       Optional[Any]														=    TextClassification(text_column="text"						,						label_column="label"			)
									A				:       Optional[Any]														=    DatasetInfo(features=__lowerCamelCase						,						task_templates=__lowerCamelCase			)
									A				:       Optional[int]														=    Dataset.from_dict({"text": ["A sentence."], "label": ["pos"]}						,						info=__lowerCamelCase			)

									def process(__lowerCamelCase   :      Dict			):
												return example

									A				:       List[Any]														=    dataset.remove_columns("label"			)
									A				:       Dict														=    modified_dataset.map(__lowerCamelCase			)
									assert mapped_dataset.info.task_templates == []