





"""simple docstring"""


import random

from .binary_exp_mod import bin_exp_mod




def 					lowercase__    (					lowercase_		,lowercase_=1_000			)					->		Union[str, Any]:




      """simple docstring"""

      if n < 2:
            return False

      if n % 2 == 0:
            return n == 2

      # this means n is odd
      _UpperCamelCase      :	str						=       n - 1
      _UpperCamelCase      :	Optional[int]						=       0
      while d % 2 == 0:
            d /= 2
            exp += 1

      # n - 1=d*(2**exp)
      _UpperCamelCase      :	List[str]						=       0
      while count < prec:
            _UpperCamelCase      :	Union[str, Any]						=       random.randint(2		,n - 1			)
            _UpperCamelCase      :	Optional[int]						=       bin_exp_mod(lowercase_		,lowercase_		,lowercase_			)
            if b != 1:
                  _UpperCamelCase      :	Optional[int]						=       True
                  for _ in range(lowercase_			):
                        if b == n - 1:
                              _UpperCamelCase      :	Tuple						=       False
                              break
                        _UpperCamelCase      :	List[Any]						=       b * b
                        b %= n
                  if flag:
                        return False
                  count += 1
      return True


if __name__ == "__main__":
  lowerCamelCase__				  =   abs(int(input("Enter bound : ").strip()))
  print("Here's the list of primes:")
  print(", ".join(str(i) for i in range(n + 1) if is_prime_big(i)))







"""simple docstring"""


from dataclasses import dataclass
from typing import Optional

import numpy as np
import torch
import torch.nn as nn

from ..utils import BaseOutput, is_torch_version, randn_tensor
from .attention_processor import SpatialNorm
from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block



@dataclass
class      __SCREAMING_SNAKE_CASE    (						_UpperCamelCase   ):







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__							:torch.FloatTensor





class      __SCREAMING_SNAKE_CASE    (						nn.Module   ):







  '''simple docstring'''


  def __init__(		self   :       Dict					,   __a   :       Dict=3					,   __a   :       Any=3					,   __a   :       Union[str, Any]=("DownEncoderBlock2D",)					,   __a   :       Optional[int]=(64,)					,   __a   :       int=2					,   __a   :       Tuple=32					,   __a   :       int="silu"					,   __a   :       str=True					,   )		->				Dict:
        super().__init__()
        _UpperCamelCase      :	List[str]						=       layers_per_block

        _UpperCamelCase      :	Dict						=       torch.nn.Convad(
            __a					,   block_out_channels[0]					,   kernel_size=3					,   stride=1					,   padding=1					,   )

        _UpperCamelCase      :	int						=       None
        _UpperCamelCase      :	Any						=       nn.ModuleList([]	)

        # down
        _UpperCamelCase      :	List[str]						=       block_out_channels[0]
        for i, down_block_type in enumerate(__a	):
              _UpperCamelCase      :	Tuple						=       output_channel
              _UpperCamelCase      :	int						=       block_out_channels[i]
              _UpperCamelCase      :	int						=       i == len(__a	) - 1

              _UpperCamelCase      :	Dict						=       get_down_block(
                  __a					,   num_layers=self.layers_per_block					,   in_channels=__a					,   out_channels=__a					,   add_downsample=not is_final_block					,   resnet_eps=1e-6					,   downsample_padding=0					,   resnet_act_fn=__a					,   resnet_groups=__a					,   attention_head_dim=__a					,   temb_channels=__a					,   )
              self.down_blocks.append(__a	)

        # mid
        _UpperCamelCase      :	Union[str, Any]						=       UNetMidBlockaD(
            in_channels=block_out_channels[-1]					,   resnet_eps=1e-6					,   resnet_act_fn=__a					,   output_scale_factor=1					,   resnet_time_scale_shift="default"					,   attention_head_dim=block_out_channels[-1]					,   resnet_groups=__a					,   temb_channels=__a					,   )

        # out
        _UpperCamelCase      :	Any						=       nn.GroupNorm(num_channels=block_out_channels[-1]					,   num_groups=__a					,   eps=1e-6	)
        _UpperCamelCase      :	Any						=       nn.SiLU()

        _UpperCamelCase      :	Union[str, Any]						=       2 * out_channels if double_z else out_channels
        _UpperCamelCase      :	Tuple						=       nn.Convad(block_out_channels[-1]					,   __a					,   3					,   padding=1	)

        _UpperCamelCase      :	Optional[int]						=       False


  def    __SCREAMING_SNAKE_CASE				(		self   :       List[str]					,   __a   :       Dict	)		->				List[str]:
        _UpperCamelCase      :	int						=       x
        _UpperCamelCase      :	Optional[int]						=       self.conv_in(__a	)

        if self.training and self.gradient_checkpointing:

              def create_custom_forward(__a   :       Tuple	):
                    def custom_forward(*__a   :       Any	):
                          return module(*__a	)

                    return custom_forward

              # down
              if is_torch_version(">="					,   "1.11.0"	):
                    for down_block in self.down_blocks:
                          _UpperCamelCase      :	Optional[int]						=       torch.utils.checkpoint.checkpoint(
                              create_custom_forward(__a	)					,   __a					,   use_reentrant=__a	)
                    # middle
                    _UpperCamelCase      :	Tuple						=       torch.utils.checkpoint.checkpoint(
                        create_custom_forward(self.mid_block	)					,   __a					,   use_reentrant=__a	)
              else:
                    for down_block in self.down_blocks:
                          _UpperCamelCase      :	Any						=       torch.utils.checkpoint.checkpoint(create_custom_forward(__a	)					,   __a	)
                    # middle
                    _UpperCamelCase      :	int						=       torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block	)					,   __a	)

        else:
              # down
              for down_block in self.down_blocks:
                    _UpperCamelCase      :	int						=       down_block(__a	)

              # middle
              _UpperCamelCase      :	int						=       self.mid_block(__a	)

        # post-process
        _UpperCamelCase      :	Any						=       self.conv_norm_out(__a	)
        _UpperCamelCase      :	Any						=       self.conv_act(__a	)
        _UpperCamelCase      :	Optional[Any]						=       self.conv_out(__a	)

        return sample





class      __SCREAMING_SNAKE_CASE    (						nn.Module   ):







  '''simple docstring'''


  def __init__(		self   :       Dict					,   __a   :       int=3					,   __a   :       Any=3					,   __a   :       str=("UpDecoderBlock2D",)					,   __a   :       Optional[int]=(64,)					,   __a   :       int=2					,   __a   :       Optional[int]=32					,   __a   :       Tuple="silu"					,   __a   :       Union[str, Any]="group"					,   )		->				str:
        super().__init__()
        _UpperCamelCase      :	List[Any]						=       layers_per_block

        _UpperCamelCase      :	Tuple						=       nn.Convad(
            __a					,   block_out_channels[-1]					,   kernel_size=3					,   stride=1					,   padding=1					,   )

        _UpperCamelCase      :	List[str]						=       None
        _UpperCamelCase      :	Dict						=       nn.ModuleList([]	)

        _UpperCamelCase      :	List[Any]						=       in_channels if norm_type == "spatial" else None

        # mid
        _UpperCamelCase      :	Optional[Any]						=       UNetMidBlockaD(
            in_channels=block_out_channels[-1]					,   resnet_eps=1e-6					,   resnet_act_fn=__a					,   output_scale_factor=1					,   resnet_time_scale_shift="default" if norm_type == "group" else norm_type					,   attention_head_dim=block_out_channels[-1]					,   resnet_groups=__a					,   temb_channels=__a					,   )

        # up
        _UpperCamelCase      :	List[str]						=       list(reversed(__a	)	)
        _UpperCamelCase      :	int						=       reversed_block_out_channels[0]
        for i, up_block_type in enumerate(__a	):
              _UpperCamelCase      :	int						=       output_channel
              _UpperCamelCase      :	Union[str, Any]						=       reversed_block_out_channels[i]

              _UpperCamelCase      :	Optional[Any]						=       i == len(__a	) - 1

              _UpperCamelCase      :	Union[str, Any]						=       get_up_block(
                  __a					,   num_layers=self.layers_per_block + 1					,   in_channels=__a					,   out_channels=__a					,   prev_output_channel=__a					,   add_upsample=not is_final_block					,   resnet_eps=1e-6					,   resnet_act_fn=__a					,   resnet_groups=__a					,   attention_head_dim=__a					,   temb_channels=__a					,   resnet_time_scale_shift=__a					,   )
              self.up_blocks.append(__a	)
              _UpperCamelCase      :	Optional[Any]						=       output_channel

        # out
        if norm_type == "spatial":
              _UpperCamelCase      :	Optional[int]						=       SpatialNorm(block_out_channels[0]					,   __a	)
        else:
              _UpperCamelCase      :	Optional[int]						=       nn.GroupNorm(num_channels=block_out_channels[0]					,   num_groups=__a					,   eps=1e-6	)
        _UpperCamelCase      :	str						=       nn.SiLU()
        _UpperCamelCase      :	str						=       nn.Convad(block_out_channels[0]					,   __a					,   3					,   padding=1	)

        _UpperCamelCase      :	Dict						=       False


  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[int]					,   __a   :       List[Any]					,   __a   :       Union[str, Any]=None	)		->				Tuple:
        _UpperCamelCase      :	List[str]						=       z
        _UpperCamelCase      :	Dict						=       self.conv_in(__a	)

        _UpperCamelCase      :	Any						=       next(iter(self.up_blocks.parameters()	)	).dtype
        if self.training and self.gradient_checkpointing:

              def create_custom_forward(__a   :       Any	):
                    def custom_forward(*__a   :       Tuple	):
                          return module(*__a	)

                    return custom_forward

              if is_torch_version(">="					,   "1.11.0"	):
                    # middle
                    _UpperCamelCase      :	str						=       torch.utils.checkpoint.checkpoint(
                        create_custom_forward(self.mid_block	)					,   __a					,   __a					,   use_reentrant=__a	)
                    _UpperCamelCase      :	Optional[int]						=       sample.to(__a	)

                    # up
                    for up_block in self.up_blocks:
                          _UpperCamelCase      :	List[Any]						=       torch.utils.checkpoint.checkpoint(
                              create_custom_forward(__a	)					,   __a					,   __a					,   use_reentrant=__a	)
              else:
                    # middle
                    _UpperCamelCase      :	Optional[int]						=       torch.utils.checkpoint.checkpoint(
                        create_custom_forward(self.mid_block	)					,   __a					,   __a	)
                    _UpperCamelCase      :	Union[str, Any]						=       sample.to(__a	)

                    # up
                    for up_block in self.up_blocks:
                          _UpperCamelCase      :	str						=       torch.utils.checkpoint.checkpoint(create_custom_forward(__a	)					,   __a					,   __a	)
        else:
              # middle
              _UpperCamelCase      :	str						=       self.mid_block(__a					,   __a	)
              _UpperCamelCase      :	int						=       sample.to(__a	)

              # up
              for up_block in self.up_blocks:
                    _UpperCamelCase      :	Any						=       up_block(__a					,   __a	)

        # post-process
        if latent_embeds is None:
              _UpperCamelCase      :	List[str]						=       self.conv_norm_out(__a	)
        else:
              _UpperCamelCase      :	Optional[int]						=       self.conv_norm_out(__a					,   __a	)
        _UpperCamelCase      :	Tuple						=       self.conv_act(__a	)
        _UpperCamelCase      :	List[Any]						=       self.conv_out(__a	)

        return sample





class      __SCREAMING_SNAKE_CASE    (						nn.Module   ):







  '''simple docstring'''


  def __init__(		self   :       Dict					,   __a   :       Tuple					,   __a   :       List[str]					,   __a   :       List[str]					,   __a   :       str=None					,   __a   :       Optional[int]="random"					,   __a   :       Any=False					,   __a   :       Optional[Any]=True	)		->				List[Any]:
        super().__init__()
        _UpperCamelCase      :	Tuple						=       n_e
        _UpperCamelCase      :	Tuple						=       vq_embed_dim
        _UpperCamelCase      :	Union[str, Any]						=       beta
        _UpperCamelCase      :	str						=       legacy

        _UpperCamelCase      :	Dict						=       nn.Embedding(self.n_e					,   self.vq_embed_dim	)
        self.embedding.weight.data.uniform_(-1.0 / self.n_e					,   1.0 / self.n_e	)

        _UpperCamelCase      :	Any						=       remap
        if self.remap is not None:
              self.register_buffer("used"					,   torch.tensor(np.load(self.remap	)	)	)
              _UpperCamelCase      :	Dict						=       self.used.shape[0]
              _UpperCamelCase      :	Optional[int]						=       unknown_index  # "random" or "extra" or integer
              if self.unknown_index == "extra":
                    _UpperCamelCase      :	Optional[int]						=       self.re_embed
                    _UpperCamelCase      :	Any						=       self.re_embed + 1
              print(
                  F'''Remapping {self.n_e} indices to {self.re_embed} indices. '''
                  F'''Using {self.unknown_index} for unknown indices.'''	)
        else:
              _UpperCamelCase      :	Union[str, Any]						=       n_e

        _UpperCamelCase      :	List[str]						=       sane_index_shape

  def    __SCREAMING_SNAKE_CASE				(		self   :       Union[str, Any]					,   __a   :       Optional[Any]	)		->				Optional[int]:
        _UpperCamelCase      :	str						=       inds.shape
        assert len(__a	) > 1
        _UpperCamelCase      :	Union[str, Any]						=       inds.reshape(ishape[0]					,   -1	)
        _UpperCamelCase      :	Optional[Any]						=       self.used.to(__a	)
        _UpperCamelCase      :	List[str]						=       (inds[:, :, None] == used[None, None, ...]).long()
        _UpperCamelCase      :	Optional[Any]						=       match.argmax(-1	)
        _UpperCamelCase      :	Any						=       match.sum(2	) < 1
        if self.unknown_index == "random":
              _UpperCamelCase      :	Optional[int]						=       torch.randint(0					,   self.re_embed					,   size=new[unknown].shape	).to(device=new.device	)
        else:
              _UpperCamelCase      :	Dict						=       self.unknown_index
        return new.reshape(__a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Dict					,   __a   :       Optional[int]	)		->				Optional[int]:
        _UpperCamelCase      :	int						=       inds.shape
        assert len(__a	) > 1
        _UpperCamelCase      :	List[Any]						=       inds.reshape(ishape[0]					,   -1	)
        _UpperCamelCase      :	Optional[int]						=       self.used.to(__a	)
        if self.re_embed > self.used.shape[0]:  # extra token
              _UpperCamelCase      :	int						=       0  # simply set to zero
        _UpperCamelCase      :	Union[str, Any]						=       torch.gather(used[None, :][inds.shape[0] * [0], :]					,   1					,   __a	)
        return back.reshape(__a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[int]					,   __a   :       str	)		->				Optional[int]:
        # reshape z -> (batch, height, width, channel) and flatten
        _UpperCamelCase      :	List[str]						=       z.permute(0					,   2					,   3					,   1	).contiguous()
        _UpperCamelCase      :	int						=       z.view(-1					,   self.vq_embed_dim	)

        # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
        _UpperCamelCase      :	Optional[int]						=       torch.argmin(torch.cdist(__a					,   self.embedding.weight	)					,   dim=1	)

        _UpperCamelCase      :	int						=       self.embedding(__a	).view(z.shape	)
        _UpperCamelCase      :	str						=       None
        _UpperCamelCase      :	Any						=       None

        # compute loss for embedding
        if not self.legacy:
              _UpperCamelCase      :	List[str]						=       self.beta * torch.mean((z_q.detach() - z) ** 2	) + torch.mean((z_q - z.detach()) ** 2	)
        else:
              _UpperCamelCase      :	str						=       torch.mean((z_q.detach() - z) ** 2	) + self.beta * torch.mean((z_q - z.detach()) ** 2	)

        # preserve gradients
        _UpperCamelCase      :	List[str]						=       z + (z_q - z).detach()

        # reshape back to match original input shape
        _UpperCamelCase      :	Optional[Any]						=       z_q.permute(0					,   3					,   1					,   2	).contiguous()

        if self.remap is not None:
              _UpperCamelCase      :	Tuple						=       min_encoding_indices.reshape(z.shape[0]					,   -1	)  # add batch axis
              _UpperCamelCase      :	Dict						=       self.remap_to_used(__a	)
              _UpperCamelCase      :	List[str]						=       min_encoding_indices.reshape(-1					,   1	)  # flatten

        if self.sane_index_shape:
              _UpperCamelCase      :	str						=       min_encoding_indices.reshape(z_q.shape[0]					,   z_q.shape[2]					,   z_q.shape[3]	)

        return z_q, loss, (perplexity, min_encodings, min_encoding_indices)


  def    __SCREAMING_SNAKE_CASE				(		self   :       List[str]					,   __a   :       List[str]					,   __a   :       str	)		->				Any:
        # shape specifying (batch, height, width, channel)
        if self.remap is not None:
              _UpperCamelCase      :	str						=       indices.reshape(shape[0]					,   -1	)  # add batch axis
              _UpperCamelCase      :	str						=       self.unmap_to_all(__a	)
              _UpperCamelCase      :	int						=       indices.reshape(-1	)  # flatten again

        # get quantized latent vectors
        _UpperCamelCase      :	Optional[int]						=       self.embedding(__a	)

        if shape is not None:
              _UpperCamelCase      :	Tuple						=       z_q.view(__a	)
              # reshape back to match original input shape
              _UpperCamelCase      :	Tuple						=       z_q.permute(0					,   3					,   1					,   2	).contiguous()

        return z_q





class      __SCREAMING_SNAKE_CASE    (						_UpperCamelCase   ):







  '''simple docstring'''


  def __init__(		self   :       Optional[int]					,   __a   :       List[str]					,   __a   :       Optional[Any]=False	)		->				int:
        _UpperCamelCase      :	Dict						=       parameters
        _UpperCamelCase,  _UpperCamelCase      :	str						=       torch.chunk(__a					,   2					,   dim=1	)
        _UpperCamelCase      :	Tuple						=       torch.clamp(self.logvar					,   -30.0					,   20.0	)
        _UpperCamelCase      :	Union[str, Any]						=       deterministic
        _UpperCamelCase      :	Dict						=       torch.exp(0.5 * self.logvar	)
        _UpperCamelCase      :	Any						=       torch.exp(self.logvar	)
        if self.deterministic:
              _UpperCamelCase      :	List[Any]						=       torch.zeros_like(
                  self.mean					,   device=self.parameters.device					,   dtype=self.parameters.dtype	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[int]					,   __a   :       Optional[torch.Generator] = None	)		->				torch.FloatTensor:
        # make sure sample is on the same device as the parameters and has same dtype
        _UpperCamelCase      :	List[Any]						=       randn_tensor(
            self.mean.shape					,   generator=__a					,   device=self.parameters.device					,   dtype=self.parameters.dtype	)
        _UpperCamelCase      :	List[Any]						=       self.mean + self.std * sample
        return x

  def    __SCREAMING_SNAKE_CASE				(		self   :       Any					,   __a   :       List[str]=None	)		->				List[Any]:
        if self.deterministic:
              return torch.Tensor([0.0]	)
        else:
              if other is None:
                    return 0.5 * torch.sum(torch.pow(self.mean					,   2	) + self.var - 1.0 - self.logvar					,   dim=[1, 2, 3]	)
              else:
                    return 0.5 * torch.sum(
                        torch.pow(self.mean - other.mean					,   2	) / other.var
                        + self.var / other.var
                        - 1.0
                        - self.logvar
                        + other.logvar					,   dim=[1, 2, 3]					,   )

  def    __SCREAMING_SNAKE_CASE				(		self   :       str					,   __a   :       Tuple					,   __a   :       List[str]=[1, 2, 3]	)		->				int:
        if self.deterministic:
              return torch.Tensor([0.0]	)
        _UpperCamelCase      :	List[str]						=       np.log(2.0 * np.pi	)
        return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean					,   2	) / self.var					,   dim=__a	)


  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[Any]	)		->				Optional[int]:
        return self.mean
