





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, apply_forward_hook
from .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer


@dataclass
class       lowercase					(				a_  ):



						"""simple docstring"""

						_UpperCamelCase	:						str    		=						42



class       lowercase					(				a_		,      a_  ):



						"""simple docstring"""

						@register_to_config
						def __init__(     self      :		int			,					lowerCamelCase_      :		int = 3			,					lowerCamelCase_      :		int = 3			,					lowerCamelCase_      :		Tuple[str] = ("DownEncoderBlock2D",)			,					lowerCamelCase_      :		Tuple[str] = ("UpDecoderBlock2D",)			,					lowerCamelCase_      :		Tuple[int] = (64,)			,					lowerCamelCase_      :		int = 1			,					lowerCamelCase_      :		str = "silu"			,					lowerCamelCase_      :		int = 3			,					lowerCamelCase_      :		int = 32			,					lowerCamelCase_      :		int = 2_56			,					lowerCamelCase_      :		int = 32			,					lowerCamelCase_      :		Optional[int] = None			,					lowerCamelCase_      :		float = 0.1_8215			,					lowerCamelCase_      :		str = "group"			,					):





										'''simple docstring'''







										super().__init__()

										# pass init params to Encoder
										_snake_case			:      List[Any]	    = Encoder(
										    in_channels=_lowerCAmelCase			,					out_channels=_lowerCAmelCase			,					down_block_types=_lowerCAmelCase			,					block_out_channels=_lowerCAmelCase			,					layers_per_block=_lowerCAmelCase			,					act_fn=_lowerCAmelCase			,					norm_num_groups=_lowerCAmelCase			,					double_z=_lowerCAmelCase			,					)

										_snake_case			:      Optional[int]	    = vq_embed_dim if vq_embed_dim is not None else latent_channels

										_snake_case			:      int	    = nn.Convad(_lowerCAmelCase			,					_lowerCAmelCase			,					1       )
										_snake_case			:      str	    = VectorQuantizer(_lowerCAmelCase			,					_lowerCAmelCase			,					beta=0.25			,					remap=_lowerCAmelCase			,					sane_index_shape=_lowerCAmelCase       )
										_snake_case			:      Dict	    = nn.Convad(_lowerCAmelCase			,					_lowerCAmelCase			,					1       )

										# pass init params to Decoder
										_snake_case			:      int	    = Decoder(
										    in_channels=_lowerCAmelCase			,					out_channels=_lowerCAmelCase			,					up_block_types=_lowerCAmelCase			,					block_out_channels=_lowerCAmelCase			,					layers_per_block=_lowerCAmelCase			,					act_fn=_lowerCAmelCase			,					norm_num_groups=_lowerCAmelCase			,					norm_type=_lowerCAmelCase			,					)







						@apply_forward_hook
						def 		__UpperCAmelCase							(     self      :		Tuple			,					lowerCamelCase_      :		torch.FloatTensor			,					lowerCamelCase_      :		bool = True       ):





										'''simple docstring'''







										_snake_case			:      Optional[int]	    = self.encoder(_lowerCAmelCase       )
										_snake_case			:      Optional[Any]	    = self.quant_conv(_lowerCAmelCase       )

										if not return_dict:
														return (h,)

										return VQEncoderOutput(latents=_lowerCAmelCase       )







						@apply_forward_hook
						def 		__UpperCAmelCase							(     self      :		str			,					lowerCamelCase_      :		torch.FloatTensor			,					lowerCamelCase_      :		bool = False			,					lowerCamelCase_      :		bool = True       ):





										'''simple docstring'''







										if not force_not_quantize:
														_snake_case    ,      _snake_case    ,      _snake_case			:      Union[str, Any]	    = self.quantize(_lowerCAmelCase       )
										else:
														_snake_case			:      List[Any]	    = h
										_snake_case			:      Dict	    = self.post_quant_conv(_lowerCAmelCase       )
										_snake_case			:      Optional[Any]	    = self.decoder(_lowerCAmelCase			,					quant if self.config.norm_type == 'spatial' else None       )

										if not return_dict:
														return (dec,)

										return DecoderOutput(sample=_lowerCAmelCase       )







						def 		__UpperCAmelCase							(     self      :		str			,					lowerCamelCase_      :		torch.FloatTensor			,					lowerCamelCase_      :		bool = True       ):





										'''simple docstring'''







										_snake_case			:      int	    = sample
										_snake_case			:      int	    = self.encode(_lowerCAmelCase       ).latents
										_snake_case			:      str	    = self.decode(_lowerCAmelCase       ).sample

										if not return_dict:
														return (dec,)

										return DecoderOutput(sample=_lowerCAmelCase       )










import math
import time
from typing import Dict, List, Optional

from torch.utils.data import Dataset

from transformers import SeqaSeqTrainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
   import torch_xla.core.xla_model as xm
   import torch_xla.debug.metrics as met


class      __lowerCAmelCase  (			a       ):






  """simple docstring"""





  def __init__(  self							:							Union[str, Any]     ,					*_lowerCAmelCase							:							Dict     ,					_lowerCAmelCase							:							List[Any]=None     ,					_lowerCAmelCase							:							str=None     ,					**_lowerCAmelCase							:							str	) ->			Dict:




     """simple docstring"""
     super().__init__(*_lowerCAmelCase     ,					**_lowerCAmelCase	)
     snake_case_            =       eval_examples
     snake_case_            =       post_process_function



  def        lowerCAmelCase__	(  self							:							Union[str, Any]     ,					_lowerCAmelCase							:							Optional[Dataset] = None     ,					_lowerCAmelCase							:							Any=None     ,					_lowerCAmelCase							:							Optional[List[str]] = None     ,					_lowerCAmelCase							:							str = "eval"     ,					**_lowerCAmelCase							:							Tuple     ,					) ->			Dict[str, float]:




     """simple docstring"""
     snake_case_            =       gen_kwargs.copy()
     snake_case_            =       (
         gen_kwargs["max_length"] if gen_kwargs.get("max_length"	) is not None else self.args.generation_max_length
     )
     snake_case_            =       (
         gen_kwargs["num_beams"] if gen_kwargs.get("num_beams"	) is not None else self.args.generation_num_beams
     )
     snake_case_            =       gen_kwargs

     snake_case_            =       self.eval_dataset if eval_dataset is None else eval_dataset
     snake_case_            =       self.get_eval_dataloader(_lowerCAmelCase	)
     snake_case_            =       self.eval_examples if eval_examples is None else eval_examples

     # Temporarily disable metric computation, we will do it in the loop here.
     snake_case_            =       self.compute_metrics
     snake_case_            =       None
     snake_case_            =       time.time()
     snake_case_            =       self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
     try:
        snake_case_            =       eval_loop(
            _lowerCAmelCase     ,					description="Evaluation"     ,					prediction_loss_only=True if compute_metrics is None else None     ,					ignore_keys=_lowerCAmelCase     ,					metric_key_prefix=_lowerCAmelCase     ,					)
     finally:
        snake_case_            =       compute_metrics
     snake_case_            =       self.args.eval_batch_size * self.args.world_size
     if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics:
        start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time''']
     output.metrics.update(
         speed_metrics(
             _lowerCAmelCase     ,					_lowerCAmelCase     ,					num_samples=output.num_samples     ,					num_steps=math.ceil(output.num_samples / total_batch_size	)     ,					)	)

     if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
        # Only the main node write the results by default
        snake_case_            =       self.post_process_function(_lowerCAmelCase     ,					_lowerCAmelCase     ,					_lowerCAmelCase	)
        snake_case_            =       self.compute_metrics(_lowerCAmelCase	)

        # Prefix all keys with metric_key_prefix + '_'
        for key in list(metrics.keys()	):
           if not key.startswith(F'''{metric_key_prefix}_'''	):
              snake_case_            =       metrics.pop(_lowerCAmelCase	)

        metrics.update(output.metrics	)
     else:
        snake_case_            =       output.metrics

     if self.args.should_log:
        # Only the main node log the results by default
        self.log(_lowerCAmelCase	)

     if self.args.tpu_metrics_debug or self.args.debug:
        # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
        xm.master_print(met.metrics_report()	)

     snake_case_            =       self.callback_handler.on_evaluate(self.args     ,					self.state     ,					self.control     ,					_lowerCAmelCase	)
     return metrics



  def        lowerCAmelCase__	(  self							:							Optional[Any]     ,					_lowerCAmelCase							:							Optional[Any]     ,					_lowerCAmelCase							:							Union[str, Any]     ,					_lowerCAmelCase							:							List[str]=None     ,					_lowerCAmelCase							:							str = "test"     ,					**_lowerCAmelCase							:							Optional[Any]	) ->			Union[str, Any]:




     """simple docstring"""
     snake_case_            =       gen_kwargs.copy()

     snake_case_            =       self.get_test_dataloader(_lowerCAmelCase	)

     # Temporarily disable metric computation, we will do it in the loop here.
     snake_case_            =       self.compute_metrics
     snake_case_            =       None
     snake_case_            =       time.time()
     snake_case_            =       self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
     try:
        snake_case_            =       eval_loop(
            _lowerCAmelCase     ,					description="Prediction"     ,					prediction_loss_only=True if compute_metrics is None else None     ,					ignore_keys=_lowerCAmelCase     ,					metric_key_prefix=_lowerCAmelCase     ,					)
     finally:
        snake_case_            =       compute_metrics

     snake_case_            =       self.args.eval_batch_size * self.args.world_size
     if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics:
        start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time''']
     output.metrics.update(
         speed_metrics(
             _lowerCAmelCase     ,					_lowerCAmelCase     ,					num_samples=output.num_samples     ,					num_steps=math.ceil(output.num_samples / total_batch_size	)     ,					)	)
     if self.post_process_function is None or self.compute_metrics is None:
        return output

     snake_case_            =       self.post_process_function(_lowerCAmelCase     ,					_lowerCAmelCase     ,					_lowerCAmelCase     ,					"predict"	)
     snake_case_            =       self.compute_metrics(_lowerCAmelCase	)

     # Prefix all keys with metric_key_prefix + '_'
     for key in list(metrics.keys()	):
        if not key.startswith(F'''{metric_key_prefix}_'''	):
           snake_case_            =       metrics.pop(_lowerCAmelCase	)
     metrics.update(output.metrics	)
     return PredictionOutput(predictions=predictions.predictions     ,					label_ids=predictions.label_ids     ,					metrics=_lowerCAmelCase	)




