


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    _UpperCamelCase     (       __snake_case					):

				"""simple docstring"""







				def __init__(    self					, *a__					, a__=None					, a__=None					, **a__ )						->					Dict:
					super().__init__(*a__					, **a__ )
					A             =					eval_examples
					A             =					post_process_function

				def   _UpperCAmelCase       (    self					, a__ = None					, a__=None					, a__ = None					, a__ = "eval"					, **a__					, )						->					Dict[str, float]:
					A             =					gen_kwargs.copy()
					A             =					(
					    gen_kwargs["""max_length"""] if gen_kwargs.get("""max_length""" ) is not None else self.args.generation_max_length
					)
					A             =					(
					    gen_kwargs["""num_beams"""] if gen_kwargs.get("""num_beams""" ) is not None else self.args.generation_num_beams
					)
					A             =					gen_kwargs

					A             =					self.eval_dataset if eval_dataset is None else eval_dataset
					A             =					self.get_eval_dataloader(a__ )
					A             =					self.eval_examples if eval_examples is None else eval_examples

					# Temporarily disable metric computation, we will do it in the loop here.
					A             =					self.compute_metrics
					A             =					None
					A             =					time.time()
					A             =					self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
					try:
						A             =					eval_loop(
						    a__					, description="""Evaluation"""					, prediction_loss_only=True if compute_metrics is None else None					, ignore_keys=a__					, metric_key_prefix=a__					, )
					finally:
						A             =					compute_metrics
					A             =					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(
					        a__					, a__					, 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
						A             =					self.post_process_function(a__					, a__					, a__ )
						A             =					self.compute_metrics(a__ )

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

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

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

					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() )

					A             =					self.callback_handler.on_evaluate(self.args					, self.state					, self.control					, a__ )
					return metrics

				def   _UpperCAmelCase       (    self					, a__					, a__					, a__=None					, a__ = "test"					, **a__ )						->					Tuple:
					A             =					gen_kwargs.copy()

					A             =					self.get_test_dataloader(a__ )

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

					A             =					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(
					        a__					, a__					, 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

					A             =					self.post_process_function(a__					, a__					, a__					, """predict""" )
					A             =					self.compute_metrics(a__ )

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







from ....configuration_utils import PretrainedConfig
from ....utils import logging


_lowercase							:   List[Any]						=						logging.get_logger(__name__)

_lowercase							:   List[str]						=						{
    "speechbrain/m-ctc-t-large": "https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json",
    # See all M-CTC-T models at https://huggingface.co/models?filter=mctct
}






class    _UpperCamelCase     (       __snake_case					):

				"""simple docstring"""







				lowerCAmelCase					=			'mctct'

				def __init__(    self					, a__=8065					, a__=1536					, a__=36					, a__=6144					, a__=4					, a__=384					, a__=920					, a__=1e-5					, a__=0.3					, a__="relu"					, a__=0.02					, a__=0.3					, a__=0.3					, a__=1					, a__=0					, a__=2					, a__=1					, a__=0.3					, a__=1					, a__=(7,)					, a__=(3,)					, a__=80					, a__=1					, a__=None					, a__="sum"					, a__=False					, **a__					, )						->					Optional[Any]:
					super().__init__(**a__					, pad_token_id=a__					, bos_token_id=a__					, eos_token_id=a__ )
					A             =					vocab_size
					A             =					hidden_size
					A             =					num_hidden_layers
					A             =					intermediate_size
					A             =					num_attention_heads
					A             =					attention_head_dim
					A             =					max_position_embeddings
					A             =					layer_norm_eps
					A             =					layerdrop
					A             =					hidden_act
					A             =					initializer_range
					A             =					hidden_dropout_prob
					A             =					attention_probs_dropout_prob
					A             =					pad_token_id
					A             =					bos_token_id
					A             =					eos_token_id
					A             =					conv_glu_dim
					A             =					conv_dropout
					A             =					num_conv_layers
					A             =					input_feat_per_channel
					A             =					input_channels
					A             =					conv_channels
					A             =					ctc_loss_reduction
					A             =					ctc_zero_infinity

					# prevents config testing fail with exporting to json
					A             =					list(a__ )
					A             =					list(a__ )

					if len(self.conv_kernel ) != self.num_conv_layers:
						raise ValueError(
						    """Configuration for convolutional module is incorrect. """
						    """It is required that `len(config.conv_kernel)` == `config.num_conv_layers` """
						    f'but is `len(config.conv_kernel) = {len(self.conv_kernel )}`, '
						    f'`config.num_conv_layers = {self.num_conv_layers}`.' )



