






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

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin
from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block





@dataclass
class  snake_case__      (							_lowerCAmelCase   ):
 lowercase__		:  torch.FloatTensor





class  snake_case__      (							_lowerCAmelCase		,						_lowerCAmelCase   ):
 @register_to_config
 def __init__(       self    ,     lowerCAmelCase__ = None    ,     lowerCAmelCase__ = 3    ,     lowerCAmelCase__ = 3    ,     lowerCAmelCase__ = False    ,     lowerCAmelCase__ = "positional"    ,     lowerCAmelCase__ = 0    ,     lowerCAmelCase__ = True    ,     lowerCAmelCase__ = ("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D")    ,     lowerCAmelCase__ = ("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D")    ,     lowerCAmelCase__ = (2_24, 4_48, 6_72, 8_96)    ,     lowerCAmelCase__ = 2    ,     lowerCAmelCase__ = 1    ,     lowerCAmelCase__ = 1    ,     lowerCAmelCase__ = "conv"    ,     lowerCAmelCase__ = "conv"    ,     lowerCAmelCase__ = "silu"    ,     lowerCAmelCase__ = 8    ,     lowerCAmelCase__ = 32    ,     lowerCAmelCase__ = 1e-5    ,     lowerCAmelCase__ = "default"    ,     lowerCAmelCase__ = True    ,     lowerCAmelCase__ = None    ,     lowerCAmelCase__ = None    ,     )							->   int:
       super().__init__()

       __magic_name__    :     Tuple     		=      sample_size
       __magic_name__    :     List[str]     		=      block_out_channels[0] * 4

       # Check inputs
       if len(lowerCAmelCase__				) != len(lowerCAmelCase__				):
             raise ValueError(
                 F'Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}.'				)

       if len(lowerCAmelCase__				) != len(lowerCAmelCase__				):
             raise ValueError(
                 F'Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}.'				)

       # input
       __magic_name__    :     Tuple     		=      nn.Convad(lowerCAmelCase__    ,     block_out_channels[0]    ,     kernel_size=3    ,     padding=(1, 1)				)

       # time
       if time_embedding_type == "fourier":
             __magic_name__    :     Any     		=      GaussianFourierProjection(embedding_size=block_out_channels[0]    ,     scale=16				)
             __magic_name__    :     List[Any]     		=      2 * block_out_channels[0]
       elif time_embedding_type == "positional":
             __magic_name__    :     Tuple     		=      Timesteps(block_out_channels[0]    ,     lowerCAmelCase__    ,     lowerCAmelCase__				)
             __magic_name__    :     Optional[Any]     		=      block_out_channels[0]

       __magic_name__    :     Union[str, Any]     		=      TimestepEmbedding(lowerCAmelCase__    ,     lowerCAmelCase__				)

       # class embedding
       if class_embed_type is None and num_class_embeds is not None:
             __magic_name__    :     List[Any]     		=      nn.Embedding(lowerCAmelCase__    ,     lowerCAmelCase__				)
       elif class_embed_type == "timestep":
             __magic_name__    :     str     		=      TimestepEmbedding(lowerCAmelCase__    ,     lowerCAmelCase__				)
       elif class_embed_type == "identity":
             __magic_name__    :     Optional[int]     		=      nn.Identity(lowerCAmelCase__    ,     lowerCAmelCase__				)
       else:
             __magic_name__    :     Tuple     		=      None

       __magic_name__    :     Union[str, Any]     		=      nn.ModuleList([]				)
       __magic_name__    :     int     		=      None
       __magic_name__    :     List[Any]     		=      nn.ModuleList([]				)

       # down
       __magic_name__    :     Optional[Any]     		=      block_out_channels[0]
       for i, down_block_type in enumerate(lowerCAmelCase__				):
             __magic_name__    :     Any     		=      output_channel
             __magic_name__    :     Dict     		=      block_out_channels[i]
             __magic_name__    :     List[str]     		=      i == len(lowerCAmelCase__				) - 1

             __magic_name__    :     Union[str, Any]     		=      get_down_block(
                 lowerCAmelCase__    ,     num_layers=lowerCAmelCase__    ,     in_channels=lowerCAmelCase__    ,     out_channels=lowerCAmelCase__    ,     temb_channels=lowerCAmelCase__    ,     add_downsample=not is_final_block    ,     resnet_eps=lowerCAmelCase__    ,     resnet_act_fn=lowerCAmelCase__    ,     resnet_groups=lowerCAmelCase__    ,     attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel    ,     downsample_padding=lowerCAmelCase__    ,     resnet_time_scale_shift=lowerCAmelCase__    ,     downsample_type=lowerCAmelCase__    ,     )
             self.down_blocks.append(lowerCAmelCase__				)

       # mid
       __magic_name__    :     List[Any]     		=      UNetMidBlockaD(
           in_channels=block_out_channels[-1]    ,     temb_channels=lowerCAmelCase__    ,     resnet_eps=lowerCAmelCase__    ,     resnet_act_fn=lowerCAmelCase__    ,     output_scale_factor=lowerCAmelCase__    ,     resnet_time_scale_shift=lowerCAmelCase__    ,     attention_head_dim=attention_head_dim if attention_head_dim is not None else block_out_channels[-1]    ,     resnet_groups=lowerCAmelCase__    ,     add_attention=lowerCAmelCase__    ,     )

       # up
       __magic_name__    :     Union[str, Any]     		=      list(reversed(lowerCAmelCase__				)				)
       __magic_name__    :     Optional[Any]     		=      reversed_block_out_channels[0]
       for i, up_block_type in enumerate(lowerCAmelCase__				):
             __magic_name__    :     Optional[Any]     		=      output_channel
             __magic_name__    :     Dict     		=      reversed_block_out_channels[i]
             __magic_name__    :     List[Any]     		=      reversed_block_out_channels[min(i + 1    ,     len(lowerCAmelCase__				) - 1				)]

             __magic_name__    :     Tuple     		=      i == len(lowerCAmelCase__				) - 1

             __magic_name__    :     str     		=      get_up_block(
                 lowerCAmelCase__    ,     num_layers=layers_per_block + 1    ,     in_channels=lowerCAmelCase__    ,     out_channels=lowerCAmelCase__    ,     prev_output_channel=lowerCAmelCase__    ,     temb_channels=lowerCAmelCase__    ,     add_upsample=not is_final_block    ,     resnet_eps=lowerCAmelCase__    ,     resnet_act_fn=lowerCAmelCase__    ,     resnet_groups=lowerCAmelCase__    ,     attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel    ,     resnet_time_scale_shift=lowerCAmelCase__    ,     upsample_type=lowerCAmelCase__    ,     )
             self.up_blocks.append(lowerCAmelCase__				)
             __magic_name__    :     Tuple     		=      output_channel

       # out
       __magic_name__    :     Optional[int]     		=      norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4    ,     32				)
       __magic_name__    :     List[Any]     		=      nn.GroupNorm(num_channels=block_out_channels[0]    ,     num_groups=lowerCAmelCase__    ,     eps=lowerCAmelCase__				)
       __magic_name__    :     Tuple     		=      nn.SiLU()
       __magic_name__    :     Dict     		=      nn.Convad(block_out_channels[0]    ,     lowerCAmelCase__    ,     kernel_size=3    ,     padding=1				)







 def     __magic_name__       (       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__ = None    ,     lowerCAmelCase__ = True    ,     )							->   Union[UNetaDOutput, Tuple]:
       # 0. center input if necessary
       if self.config.center_input_sample:
             __magic_name__    :     Union[str, Any]     		=      2 * sample - 1.0

       # 1. time
       __magic_name__    :     Any     		=      timestep
       if not torch.is_tensor(lowerCAmelCase__				):
             __magic_name__    :     Optional[Any]     		=      torch.tensor([timesteps]    ,     dtype=torch.long    ,     device=sample.device				)
       elif torch.is_tensor(lowerCAmelCase__				) and len(timesteps.shape				) == 0:
             __magic_name__    :     Optional[Any]     		=      timesteps[None].to(sample.device				)

       # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
       __magic_name__    :     Dict     		=      timesteps * torch.ones(sample.shape[0]    ,     dtype=timesteps.dtype    ,     device=timesteps.device				)

       __magic_name__    :     Tuple     		=      self.time_proj(lowerCAmelCase__				)

       # timesteps does not contain any weights and will always return f32 tensors
       # but time_embedding might actually be running in fp16. so we need to cast here.
       # there might be better ways to encapsulate this.
       __magic_name__    :     str     		=      t_emb.to(dtype=self.dtype				)
       __magic_name__    :     List[Any]     		=      self.time_embedding(lowerCAmelCase__				)

       if self.class_embedding is not None:
             if class_labels is None:
                   raise ValueError("""class_labels should be provided when doing class conditioning"""				)

             if self.config.class_embed_type == "timestep":
                   __magic_name__    :     Union[str, Any]     		=      self.time_proj(lowerCAmelCase__				)

             __magic_name__    :     Tuple     		=      self.class_embedding(lowerCAmelCase__				).to(dtype=self.dtype				)
             __magic_name__    :     Union[str, Any]     		=      emb + class_emb

       # 2. pre-process
       __magic_name__    :     Union[str, Any]     		=      sample
       __magic_name__    :     Optional[Any]     		=      self.conv_in(lowerCAmelCase__				)

       # 3. down
       __magic_name__    :     Any     		=      (sample,)
       for downsample_block in self.down_blocks:
             if hasattr(lowerCAmelCase__    ,     """skip_conv"""				):
                   __magic_name__    :     Optional[int]     		=      downsample_block(
                       hidden_states=lowerCAmelCase__    ,     temb=lowerCAmelCase__    ,     skip_sample=lowerCAmelCase__				)
             else:
                   __magic_name__    :     Dict     		=      downsample_block(hidden_states=lowerCAmelCase__    ,     temb=lowerCAmelCase__				)

             down_block_res_samples += res_samples

       # 4. mid
       __magic_name__    :     Optional[int]     		=      self.mid_block(lowerCAmelCase__    ,     lowerCAmelCase__				)

       # 5. up
       __magic_name__    :     Dict     		=      None
       for upsample_block in self.up_blocks:
             __magic_name__    :     Optional[Any]     		=      down_block_res_samples[-len(upsample_block.resnets				) :]
             __magic_name__    :     Union[str, Any]     		=      down_block_res_samples[: -len(upsample_block.resnets				)]

             if hasattr(lowerCAmelCase__    ,     """skip_conv"""				):
                   __magic_name__    :     List[str]     		=      upsample_block(lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__				)
             else:
                   __magic_name__    :     Tuple     		=      upsample_block(lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__				)

        # 6. post-process
       __magic_name__    :     Optional[Any]     		=      self.conv_norm_out(lowerCAmelCase__				)
       __magic_name__    :     List[str]     		=      self.conv_act(lowerCAmelCase__				)
       __magic_name__    :     Any     		=      self.conv_out(lowerCAmelCase__				)

       if skip_sample is not None:
             sample += skip_sample

       if self.config.time_embedding_type == "fourier":
             __magic_name__    :     str     		=      timesteps.reshape((sample.shape[0], *([1] * len(sample.shape[1:]				)))				)
             __magic_name__    :     Dict     		=      sample / timesteps

       if not return_dict:
             return (sample,)

       return UNetaDOutput(sample=lowerCAmelCase__				)








import sacrebleu as scb
from packaging import version

import datasets


__magic_name__:  Optional[int]  	=			"\\n@inproceedings{post-2018-call,\n    title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n    author = \"Post, Matt\",\n    booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n    month = oct,\n    year = \"2018\",\n    address = \"Belgium, Brussels\",\n    publisher = \"Association for Computational Linguistics\",\n    url = \"https://www.aclweb.org/anthology/W18-6319\",\n    pages = \"186--191\",\n}\n"

__magic_name__:  int  	=			"\\nSacreBLEU provides hassle-free computation of shareable, comparable, and reproducible BLEU scores.\nInspired by Rico Sennrich's `multi-bleu-detok.perl`, it produces the official WMT scores but works with plain text.\nIt also knows all the standard test sets and handles downloading, processing, and tokenization for you.\n\nSee the [README.md] file at https://github.com/mjpost/sacreBLEU for more information.\n"

__magic_name__:  List[Any]  	=			"\nProduces BLEU scores along with its sufficient statistics\nfrom a source against one or more references.\n\nArgs:\n    predictions (`list` of `str`): list of translations to score. Each translation should be tokenized into a list of tokens.\n    references (`list` of `list` of `str`): A list of lists of references. The contents of the first sub-list are the references for the first prediction, the contents of the second sub-list are for the second prediction, etc. Note that there must be the same number of references for each prediction (i.e. all sub-lists must be of the same length).\n    smooth_method (`str`): The smoothing method to use, defaults to `'exp'`. Possible values are:\n        - `'none'`: no smoothing\n        - `'floor'`: increment zero counts\n        - `'add-k'`: increment num/denom by k for n>1\n        - `'exp'`: exponential decay\n    smooth_value (`float`): The smoothing value. Only valid when `smooth_method='floor'` (in which case `smooth_value` defaults to `0.1`) or `smooth_method='add-k'` (in which case `smooth_value` defaults to `1`).\n    tokenize (`str`): Tokenization method to use for BLEU. If not provided, defaults to `'zh'` for Chinese, `'ja-mecab'` for Japanese and `'13a'` (mteval) otherwise. Possible values are:\n        - `'none'`: No tokenization.\n        - `'zh'`: Chinese tokenization.\n        - `'13a'`: mimics the `mteval-v13a` script from Moses.\n        - `'intl'`: International tokenization, mimics the `mteval-v14` script from Moses\n        - `'char'`: Language-agnostic character-level tokenization.\n        - `'ja-mecab'`: Japanese tokenization. Uses the [MeCab tokenizer](https://pypi.org/project/mecab-python3).\n    lowercase (`bool`): If `True`, lowercases the input, enabling case-insensitivity. Defaults to `False`.\n    force (`bool`): If `True`, insists that your tokenized input is actually detokenized. Defaults to `False`.\n    use_effective_order (`bool`): If `True`, stops including n-gram orders for which precision is 0. This should be `True`, if sentence-level BLEU will be computed. Defaults to `False`.\n\nReturns:\n    'score': BLEU score,\n    'counts': Counts,\n    'totals': Totals,\n    'precisions': Precisions,\n    'bp': Brevity penalty,\n    'sys_len': predictions length,\n    'ref_len': reference length,\n\nExamples:\n\n    Example 1:\n        >>> predictions = [\"hello there general kenobi\", \"foo bar foobar\"]\n        >>> references = [[\"hello there general kenobi\", \"hello there !\"], [\"foo bar foobar\", \"foo bar foobar\"]]\n        >>> sacrebleu = datasets.load_metric(\"sacrebleu\")\n        >>> results = sacrebleu.compute(predictions=predictions, references=references)\n        >>> print(list(results.keys()))\n        ['score', 'counts', 'totals', 'precisions', 'bp', 'sys_len', 'ref_len']\n        >>> print(round(results[\"score\"], 1))\n        100.0\n\n    Example 2:\n        >>> predictions = [\"hello there general kenobi\",\n        ...                 \"on our way to ankh morpork\"]\n        >>> references = [[\"hello there general kenobi\", \"hello there !\"],\n        ...                 [\"goodbye ankh morpork\", \"ankh morpork\"]]\n        >>> sacrebleu = datasets.load_metric(\"sacrebleu\")\n        >>> results = sacrebleu.compute(predictions=predictions,\n        ...                             references=references)\n        >>> print(list(results.keys()))\n        ['score', 'counts', 'totals', 'precisions', 'bp', 'sys_len', 'ref_len']\n        >>> print(round(results[\"score\"], 1))\n        39.8\n"





@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION		,						_KWARGS_DESCRIPTION   )
class  snake_case__      (							datasets.Metric   ):
	def     __magic_name__       (       self				)							->   Optional[int]:
							if version.parse(scb.__version__				) < version.parse("""1.4.12"""				):
													raise ImportWarning(
													    """To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n"""
													    """You can install it with `pip install \"sacrebleu>=1.4.12\"`."""				)
							return datasets.MetricInfo(
							    description=_DESCRIPTION    ,     citation=_CITATION    ,     homepage="""https://github.com/mjpost/sacreBLEU"""    ,     inputs_description=_KWARGS_DESCRIPTION    ,     features=datasets.Features(
							        {
							            """predictions""": datasets.Value("""string"""    ,     id="""sequence"""				),
							            """references""": datasets.Sequence(datasets.Value("""string"""    ,     id="""sequence"""				)    ,     id="""references"""				),
							        }				)    ,     codebase_urls=["""https://github.com/mjpost/sacreBLEU"""]    ,     reference_urls=[
							        """https://github.com/mjpost/sacreBLEU""",
							        """https://en.wikipedia.org/wiki/BLEU""",
							        """https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213""",
							    ]    ,     )







	def     __magic_name__       (       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__="exp"    ,     lowerCAmelCase__=None    ,     lowerCAmelCase__=False    ,     lowerCAmelCase__=False    ,     lowerCAmelCase__=None    ,     lowerCAmelCase__=False    ,     )							->   Optional[Any]:
							__magic_name__    :     Optional[int]     		=      len(references[0]				)
							if any(len(lowerCAmelCase__				) != references_per_prediction for refs in references				):
													raise ValueError("""Sacrebleu requires the same number of references for each prediction"""				)
							__magic_name__    :     Dict     		=      [[refs[i] for refs in references] for i in range(lowerCAmelCase__				)]
							__magic_name__    :     List[str]     		=      scb.corpus_bleu(
							    lowerCAmelCase__    ,     lowerCAmelCase__    ,     smooth_method=lowerCAmelCase__    ,     smooth_value=lowerCAmelCase__    ,     force=lowerCAmelCase__    ,     lowercase=lowerCAmelCase__    ,     use_effective_order=lowerCAmelCase__    ,     **({"""tokenize""": tokenize} if tokenize else {})    ,     )
							__magic_name__    :     List[str]     		=      {
							    """score""": output.score,
							    """counts""": output.counts,
							    """totals""": output.totals,
							    """precisions""": output.precisions,
							    """bp""": output.bp,
							    """sys_len""": output.sys_len,
							    """ref_len""": output.ref_len,
							}
							return output_dict
