





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    lowerCAmelCase							(					__UpperCamelCase			):
 UpperCAmelCase__													=		42


class    lowerCAmelCase							(					nn.Module			):
 def __init__(      self  :      Tuple			,     UpperCAmelCase  :      Dict=3			,     UpperCAmelCase  :      Union[str, Any]=3			,     UpperCAmelCase  :      Optional[Any]=("DownEncoderBlock2D",)			,     UpperCAmelCase  :      List[str]=(64,)			,     UpperCAmelCase  :      Any=2			,     UpperCAmelCase  :      List[Any]=32			,     UpperCAmelCase  :      List[str]="silu"			,     UpperCAmelCase  :      Tuple=True			,     )			->	Tuple:
     super().__init__()
     lowerCamelCase__    :      Optional[Any]					 =		layers_per_block

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

     lowerCamelCase__    :      Tuple					 =		None
     lowerCamelCase__    :      Union[str, Any]					 =		nn.ModuleList([]	)

     # down
     lowerCamelCase__    :      Tuple					 =		block_out_channels[0]
     for i, down_block_type in enumerate(UpperCAmelCase	):
         lowerCamelCase__    :      List[Any]					 =		output_channel
         lowerCamelCase__    :      Dict					 =		block_out_channels[i]
         lowerCamelCase__    :      int					 =		i == len(UpperCAmelCase	) - 1

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

     # mid
     lowerCamelCase__    :      Tuple					 =		UNetMidBlockaD(
         in_channels=block_out_channels[-1]			,     resnet_eps=1e-6			,     resnet_act_fn=UpperCAmelCase			,     output_scale_factor=1			,     resnet_time_scale_shift='default'			,     attention_head_dim=block_out_channels[-1]			,     resnet_groups=UpperCAmelCase			,     temb_channels=UpperCAmelCase			,     )

     # out
     lowerCamelCase__    :      Optional[Any]					 =		nn.GroupNorm(num_channels=block_out_channels[-1]			,     num_groups=UpperCAmelCase			,     eps=1e-6	)
     lowerCamelCase__    :      List[Any]					 =		nn.SiLU()

     lowerCamelCase__    :      List[str]					 =		2 * out_channels if double_z else out_channels
     lowerCamelCase__    :      Any					 =		nn.Convad(block_out_channels[-1]			,     UpperCAmelCase			,     3			,     padding=1	)

     lowerCamelCase__    :      List[Any]					 =		False







 def      A_	(      self  :      Dict			,     UpperCAmelCase  :      Optional[int]	)			->	Union[str, Any]:
     lowerCamelCase__    :      Dict					 =		x
     lowerCamelCase__    :      Dict					 =		self.conv_in(UpperCAmelCase	)

     if self.training and self.gradient_checkpointing:

         def create_custom_forward(UpperCAmelCase  :      Dict	):
             def custom_forward(*UpperCAmelCase  :      Any	):
                 return module(*UpperCAmelCase	)

             return custom_forward

         # down
         if is_torch_version('>='			,     '1.11.0'	):
             for down_block in self.down_blocks:
                 lowerCamelCase__    :      Optional[Any]					 =		torch.utils.checkpoint.checkpoint(
                     create_custom_forward(UpperCAmelCase	)			,     UpperCAmelCase			,     use_reentrant=UpperCAmelCase	)
             # middle
             lowerCamelCase__    :      Tuple					 =		torch.utils.checkpoint.checkpoint(
                 create_custom_forward(self.mid_block	)			,     UpperCAmelCase			,     use_reentrant=UpperCAmelCase	)
         else:
             for down_block in self.down_blocks:
                 lowerCamelCase__    :      str					 =		torch.utils.checkpoint.checkpoint(create_custom_forward(UpperCAmelCase	)			,     UpperCAmelCase	)
             # middle
             lowerCamelCase__    :      Dict					 =		torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block	)			,     UpperCAmelCase	)

     else:
         # down
         for down_block in self.down_blocks:
             lowerCamelCase__    :      Optional[Any]					 =		down_block(UpperCAmelCase	)

         # middle
         lowerCamelCase__    :      List[str]					 =		self.mid_block(UpperCAmelCase	)

     # post-process
     lowerCamelCase__    :      str					 =		self.conv_norm_out(UpperCAmelCase	)
     lowerCamelCase__    :      List[Any]					 =		self.conv_act(UpperCAmelCase	)
     lowerCamelCase__    :      Union[str, Any]					 =		self.conv_out(UpperCAmelCase	)

     return sample


class    lowerCAmelCase							(					nn.Module			):
 def __init__(      self  :      Any			,     UpperCAmelCase  :      Optional[int]=3			,     UpperCAmelCase  :      List[Any]=3			,     UpperCAmelCase  :      int=("UpDecoderBlock2D",)			,     UpperCAmelCase  :      Optional[Any]=(64,)			,     UpperCAmelCase  :      str=2			,     UpperCAmelCase  :      Union[str, Any]=32			,     UpperCAmelCase  :      int="silu"			,     UpperCAmelCase  :      List[str]="group"			,     )			->	Any:
     super().__init__()
     lowerCamelCase__    :      List[str]					 =		layers_per_block

     lowerCamelCase__    :      Optional[Any]					 =		nn.Convad(
         UpperCAmelCase			,     block_out_channels[-1]			,     kernel_size=3			,     stride=1			,     padding=1			,     )

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

     lowerCamelCase__    :      Dict					 =		in_channels if norm_type == 'spatial' else None

     # mid
     lowerCamelCase__    :      List[Any]					 =		UNetMidBlockaD(
         in_channels=block_out_channels[-1]			,     resnet_eps=1e-6			,     resnet_act_fn=UpperCAmelCase			,     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=UpperCAmelCase			,     temb_channels=UpperCAmelCase			,     )

     # up
     lowerCamelCase__    :      Tuple					 =		list(reversed(UpperCAmelCase	)	)
     lowerCamelCase__    :      Dict					 =		reversed_block_out_channels[0]
     for i, up_block_type in enumerate(UpperCAmelCase	):
         lowerCamelCase__    :      Dict					 =		output_channel
         lowerCamelCase__    :      List[Any]					 =		reversed_block_out_channels[i]

         lowerCamelCase__    :      Union[str, Any]					 =		i == len(UpperCAmelCase	) - 1

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

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

     lowerCamelCase__    :      Dict					 =		False







 def      A_	(      self  :      Tuple			,     UpperCAmelCase  :      Tuple			,     UpperCAmelCase  :      Any=None	)			->	List[str]:
     lowerCamelCase__    :      Any					 =		z
     lowerCamelCase__    :      Union[str, Any]					 =		self.conv_in(UpperCAmelCase	)

     lowerCamelCase__    :      Optional[int]					 =		next(iter(self.up_blocks.parameters()	)	).dtype
     if self.training and self.gradient_checkpointing:

         def create_custom_forward(UpperCAmelCase  :      Any	):
             def custom_forward(*UpperCAmelCase  :      Any	):
                 return module(*UpperCAmelCase	)

             return custom_forward

         if is_torch_version('>='			,     '1.11.0'	):
             # middle
             lowerCamelCase__    :      str					 =		torch.utils.checkpoint.checkpoint(
                 create_custom_forward(self.mid_block	)			,     UpperCAmelCase			,     UpperCAmelCase			,     use_reentrant=UpperCAmelCase	)
             lowerCamelCase__    :      Tuple					 =		sample.to(UpperCAmelCase	)

             # up
             for up_block in self.up_blocks:
                 lowerCamelCase__    :      str					 =		torch.utils.checkpoint.checkpoint(
                     create_custom_forward(UpperCAmelCase	)			,     UpperCAmelCase			,     UpperCAmelCase			,     use_reentrant=UpperCAmelCase	)
         else:
             # middle
             lowerCamelCase__    :      str					 =		torch.utils.checkpoint.checkpoint(
                 create_custom_forward(self.mid_block	)			,     UpperCAmelCase			,     UpperCAmelCase	)
             lowerCamelCase__    :      Dict					 =		sample.to(UpperCAmelCase	)

             # up
             for up_block in self.up_blocks:
                 lowerCamelCase__    :      Tuple					 =		torch.utils.checkpoint.checkpoint(create_custom_forward(UpperCAmelCase	)			,     UpperCAmelCase			,     UpperCAmelCase	)
     else:
         # middle
         lowerCamelCase__    :      Any					 =		self.mid_block(UpperCAmelCase			,     UpperCAmelCase	)
         lowerCamelCase__    :      Optional[int]					 =		sample.to(UpperCAmelCase	)

         # up
         for up_block in self.up_blocks:
             lowerCamelCase__    :      List[Any]					 =		up_block(UpperCAmelCase			,     UpperCAmelCase	)

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

     return sample


class    lowerCAmelCase							(					nn.Module			):
 def __init__(      self  :      Dict			,     UpperCAmelCase  :      str			,     UpperCAmelCase  :      Optional[int]			,     UpperCAmelCase  :      Optional[Any]			,     UpperCAmelCase  :      str=None			,     UpperCAmelCase  :      Optional[Any]="random"			,     UpperCAmelCase  :      Optional[int]=False			,     UpperCAmelCase  :      List[Any]=True	)			->	Optional[int]:
     super().__init__()
     lowerCamelCase__    :      int					 =		n_e
     lowerCamelCase__    :      Any					 =		vq_embed_dim
     lowerCamelCase__    :      Optional[int]					 =		beta
     lowerCamelCase__    :      Optional[Any]					 =		legacy

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

     lowerCamelCase__    :      Any					 =		remap
     if self.remap is not None:
         self.register_buffer('used'			,     torch.tensor(np.load(self.remap	)	)	)
         lowerCamelCase__    :      str					 =		self.used.shape[0]
         lowerCamelCase__    :      Any					 =		unknown_index  # "random" or "extra" or integer
         if self.unknown_index == "extra":
             lowerCamelCase__    :      List[Any]					 =		self.re_embed
             lowerCamelCase__    :      List[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:
         lowerCamelCase__    :      List[Any]					 =		n_e

     lowerCamelCase__    :      Optional[Any]					 =		sane_index_shape
 def      A_	(      self  :      Union[str, Any]			,     UpperCAmelCase  :      Any	)			->	Dict:
     lowerCamelCase__    :      Any					 =		inds.shape
     assert len(UpperCAmelCase	) > 1
     lowerCamelCase__    :      str					 =		inds.reshape(ishape[0]			,     -1	)
     lowerCamelCase__    :      str					 =		self.used.to(UpperCAmelCase	)
     lowerCamelCase__    :      Dict					 =		(inds[:, :, None] == used[None, None, ...]).long()
     lowerCamelCase__    :      Optional[int]					 =		match.argmax(-1	)
     lowerCamelCase__    :      Dict					 =		match.sum(2	) < 1
     if self.unknown_index == "random":
         lowerCamelCase__    :      Optional[int]					 =		torch.randint(0			,     self.re_embed			,     size=new[unknown].shape	).to(device=new.device	)
     else:
         lowerCamelCase__    :      int					 =		self.unknown_index
     return new.reshape(UpperCAmelCase	)
 def      A_	(      self  :      List[str]			,     UpperCAmelCase  :      Tuple	)			->	Optional[int]:
     lowerCamelCase__    :      List[Any]					 =		inds.shape
     assert len(UpperCAmelCase	) > 1
     lowerCamelCase__    :      List[Any]					 =		inds.reshape(ishape[0]			,     -1	)
     lowerCamelCase__    :      str					 =		self.used.to(UpperCAmelCase	)
     if self.re_embed > self.used.shape[0]:  # extra token
         lowerCamelCase__    :      Any					 =		0  # simply set to zero
     lowerCamelCase__    :      Any					 =		torch.gather(used[None, :][inds.shape[0] * [0], :]			,     1			,     UpperCAmelCase	)
     return back.reshape(UpperCAmelCase	)
 def      A_	(      self  :      Tuple			,     UpperCAmelCase  :      Union[str, Any]	)			->	Optional[int]:
     # reshape z -> (batch, height, width, channel) and flatten
     lowerCamelCase__    :      Tuple					 =		z.permute(0			,     2			,     3			,     1	).contiguous()
     lowerCamelCase__    :      List[Any]					 =		z.view(-1			,     self.vq_embed_dim	)

     # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
     lowerCamelCase__    :      List[str]					 =		torch.argmin(torch.cdist(UpperCAmelCase			,     self.embedding.weight	)			,     dim=1	)

     lowerCamelCase__    :      Optional[Any]					 =		self.embedding(UpperCAmelCase	).view(z.shape	)
     lowerCamelCase__    :      int					 =		None
     lowerCamelCase__    :      Union[str, Any]					 =		None

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

     # preserve gradients
     lowerCamelCase__    :      Union[str, Any]					 =		z + (z_q - z).detach()

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

     if self.remap is not None:
         lowerCamelCase__    :      int					 =		min_encoding_indices.reshape(z.shape[0]			,     -1	)  # add batch axis
         lowerCamelCase__    :      Union[str, Any]					 =		self.remap_to_used(UpperCAmelCase	)
         lowerCamelCase__    :      Optional[int]					 =		min_encoding_indices.reshape(-1			,     1	)  # flatten

     if self.sane_index_shape:
         lowerCamelCase__    :      Any					 =		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      A_	(      self  :      int			,     UpperCAmelCase  :      Dict			,     UpperCAmelCase  :      List[Any]	)			->	List[Any]:
     # shape specifying (batch, height, width, channel)
     if self.remap is not None:
         lowerCamelCase__    :      str					 =		indices.reshape(shape[0]			,     -1	)  # add batch axis
         lowerCamelCase__    :      Optional[Any]					 =		self.unmap_to_all(UpperCAmelCase	)
         lowerCamelCase__    :      Union[str, Any]					 =		indices.reshape(-1	)  # flatten again

     # get quantized latent vectors
     lowerCamelCase__    :      str					 =		self.embedding(UpperCAmelCase	)

     if shape is not None:
         lowerCamelCase__    :      List[str]					 =		z_q.view(UpperCAmelCase	)
         # reshape back to match original input shape
         lowerCamelCase__    :      Union[str, Any]					 =		z_q.permute(0			,     3			,     1			,     2	).contiguous()

     return z_q


class    lowerCAmelCase							(					__UpperCamelCase			):
 def __init__(      self  :      Any			,     UpperCAmelCase  :      Tuple			,     UpperCAmelCase  :      List[Any]=False	)			->	List[str]:
     lowerCamelCase__    :      List[str]					 =		parameters
     lowerCamelCase__ ,							lowerCamelCase__    :      List[str]					 =		torch.chunk(UpperCAmelCase			,     2			,     dim=1	)
     lowerCamelCase__    :      Union[str, Any]					 =		torch.clamp(self.logvar			,     -3_0.0			,     2_0.0	)
     lowerCamelCase__    :      List[Any]					 =		deterministic
     lowerCamelCase__    :      Optional[int]					 =		torch.exp(0.5 * self.logvar	)
     lowerCamelCase__    :      Optional[Any]					 =		torch.exp(self.logvar	)
     if self.deterministic:
         lowerCamelCase__    :      str					 =		torch.zeros_like(
             self.mean			,     device=self.parameters.device			,     dtype=self.parameters.dtype	)
 def      A_	(      self  :      List[str]			,     UpperCAmelCase  :      Optional[torch.Generator] = None	)			->	torch.FloatTensor:
     # make sure sample is on the same device as the parameters and has same dtype
     lowerCamelCase__    :      Any					 =		randn_tensor(
         self.mean.shape			,     generator=UpperCAmelCase			,     device=self.parameters.device			,     dtype=self.parameters.dtype	)
     lowerCamelCase__    :      Optional[int]					 =		self.mean + self.std * sample
     return x
 def      A_	(      self  :      Dict			,     UpperCAmelCase  :      Optional[Any]=None	)			->	Optional[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      A_	(      self  :      str			,     UpperCAmelCase  :      int			,     UpperCAmelCase  :      List[Any]=[1, 2, 3]	)			->	List[str]:
     if self.deterministic:
         return torch.Tensor([0.0]	)
     lowerCamelCase__    :      int					 =		np.log(2.0 * np.pi	)
     return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean			,     2	) / self.var			,     dim=UpperCAmelCase	)







 def      A_	(      self  :      Optional[int]	)			->	List[str]:
     return self.mean






import os
import unittest

from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer
from transformers.testing_utils import require_jieba, tooslow

from ...test_tokenization_common import TokenizerTesterMixin


@require_jieba
class      lowerCamelCase    (SCREAMING_SNAKE_CASE__     ,					unittest.TestCase    ):
  """simple docstring"""







  lowerCamelCase__   =  CpmAntTokenizer
  lowerCamelCase__   =  False







  def       __A   (							self       :				List[str]      )     ->		str:
        super().setUp()

        SCREAMING_SNAKE_CASE_      =     [
            "<d>",
            "</d>",
            "<s>",
            "</s>",
            "</_>",
            "<unk>",
            "<pad>",
            "</n>",
            "我",
            "是",
            "C",
            "P",
            "M",
            "A",
            "n",
            "t",
        ]
        SCREAMING_SNAKE_CASE_      =     os.path.join(self.tmpdirname     ,   VOCAB_FILES_NAMES["vocab_file"]      )
        with open(self.vocab_file     ,   "w"     ,   encoding="utf-8"      ) as vocab_writer:
              vocab_writer.write("".join([x + "\n" for x in vocab_tokens]      )      )







  @tooslow
  def       __A   (							self       :				int      )     ->		Union[str, Any]:
        SCREAMING_SNAKE_CASE_      =     CpmAntTokenizer.from_pretrained("openbmb/cpm-ant-10b"      )
        SCREAMING_SNAKE_CASE_      =     "今天天气真好！"
        SCREAMING_SNAKE_CASE_      =     ["今天", "天气", "真", "好", "！"]
        SCREAMING_SNAKE_CASE_      =     tokenizer.tokenize(__magic_name__      )
        self.assertListEqual(__magic_name__     ,   __magic_name__      )
        SCREAMING_SNAKE_CASE_      =     "今天天气真好！"
        SCREAMING_SNAKE_CASE_      =     [tokenizer.bos_token] + tokens

        SCREAMING_SNAKE_CASE_      =     [6, 9_802, 14_962, 2_082, 831, 244]
        self.assertListEqual(tokenizer.convert_tokens_to_ids(__magic_name__      )     ,   __magic_name__      )

        SCREAMING_SNAKE_CASE_      =     tokenizer.decode(__magic_name__      )
        self.assertEqual(__magic_name__     ,   __magic_name__      )


