



import functools
import operator

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


a      :  Any			     =			logging.get_logger(__name__)

a      :  List[Any]			     =			{
    'microsoft/unispeech-large-1500h-cv': (
        'https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json'
    ),
    # See all UniSpeech models at https://huggingface.co/models?filter=unispeech
}







class 				_a				(   _lowerCAmelCase					):
			A      		=	'''unispeech'''

			def __init__(self,   SCREAMING_SNAKE_CASE_=32,   SCREAMING_SNAKE_CASE_=768,   SCREAMING_SNAKE_CASE_=12,   SCREAMING_SNAKE_CASE_=12,   SCREAMING_SNAKE_CASE_=3072,   SCREAMING_SNAKE_CASE_="gelu",   SCREAMING_SNAKE_CASE_=0.1,   SCREAMING_SNAKE_CASE_=0.1,   SCREAMING_SNAKE_CASE_=0.1,   SCREAMING_SNAKE_CASE_=0.0,   SCREAMING_SNAKE_CASE_=0.0,   SCREAMING_SNAKE_CASE_=0.1,   SCREAMING_SNAKE_CASE_=0.1,   SCREAMING_SNAKE_CASE_=0.0_2,   SCREAMING_SNAKE_CASE_=1E-5,   SCREAMING_SNAKE_CASE_="group",   SCREAMING_SNAKE_CASE_="gelu",   SCREAMING_SNAKE_CASE_=(512, 512, 512, 512, 512, 512, 512),   SCREAMING_SNAKE_CASE_=(5, 2, 2, 2, 2, 2, 2),   SCREAMING_SNAKE_CASE_=(10, 3, 3, 3, 3, 2, 2),   SCREAMING_SNAKE_CASE_=False,   SCREAMING_SNAKE_CASE_=128,   SCREAMING_SNAKE_CASE_=16,   SCREAMING_SNAKE_CASE_=False,   SCREAMING_SNAKE_CASE_=True,   SCREAMING_SNAKE_CASE_=0.0_5,   SCREAMING_SNAKE_CASE_=10,   SCREAMING_SNAKE_CASE_=2,   SCREAMING_SNAKE_CASE_=0.0,   SCREAMING_SNAKE_CASE_=10,   SCREAMING_SNAKE_CASE_=0,   SCREAMING_SNAKE_CASE_=320,   SCREAMING_SNAKE_CASE_=2,   SCREAMING_SNAKE_CASE_=0.1,   SCREAMING_SNAKE_CASE_=100,   SCREAMING_SNAKE_CASE_=256,   SCREAMING_SNAKE_CASE_=256,   SCREAMING_SNAKE_CASE_=0.1,   SCREAMING_SNAKE_CASE_="mean",   SCREAMING_SNAKE_CASE_=False,   SCREAMING_SNAKE_CASE_=False,   SCREAMING_SNAKE_CASE_=256,   SCREAMING_SNAKE_CASE_=80,   SCREAMING_SNAKE_CASE_=0,   SCREAMING_SNAKE_CASE_=1,   SCREAMING_SNAKE_CASE_=2,   SCREAMING_SNAKE_CASE_=0.5,   **SCREAMING_SNAKE_CASE_,   )       ->   List[str]:
						super().__init__(**SCREAMING_SNAKE_CASE_,   pad_token_id=SCREAMING_SNAKE_CASE_,   bos_token_id=SCREAMING_SNAKE_CASE_,   eos_token_id=SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		List[str]							      =     hidden_size
						UpperCAmelCase_:		Optional[Any]							      =     feat_extract_norm
						UpperCAmelCase_:		Optional[int]							      =     feat_extract_activation
						UpperCAmelCase_:		Optional[Any]							      =     list(SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		List[str]							      =     list(SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		List[str]							      =     list(SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		Any							      =     conv_bias
						UpperCAmelCase_:		Any							      =     num_conv_pos_embeddings
						UpperCAmelCase_:		Dict							      =     num_conv_pos_embedding_groups
						UpperCAmelCase_:		str							      =     len(self.conv_dim					)
						UpperCAmelCase_:		Optional[Any]							      =     num_hidden_layers
						UpperCAmelCase_:		str							      =     intermediate_size
						UpperCAmelCase_:		Union[str, Any]							      =     hidden_act
						UpperCAmelCase_:		Union[str, Any]							      =     num_attention_heads
						UpperCAmelCase_:		Optional[Any]							      =     hidden_dropout
						UpperCAmelCase_:		str							      =     attention_dropout
						UpperCAmelCase_:		Dict							      =     activation_dropout
						UpperCAmelCase_:		Tuple							      =     feat_proj_dropout
						UpperCAmelCase_:		Optional[int]							      =     final_dropout
						UpperCAmelCase_:		List[str]							      =     layerdrop
						UpperCAmelCase_:		Optional[int]							      =     layer_norm_eps
						UpperCAmelCase_:		Optional[Any]							      =     initializer_range
						UpperCAmelCase_:		List[str]							      =     num_ctc_classes
						UpperCAmelCase_:		Dict							      =     vocab_size
						UpperCAmelCase_:		List[str]							      =     do_stable_layer_norm
						UpperCAmelCase_:		str							      =     use_weighted_layer_sum
						UpperCAmelCase_:		Dict							      =     classifier_proj_size

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

						# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
						UpperCAmelCase_:		Dict							      =     apply_spec_augment
						UpperCAmelCase_:		str							      =     mask_time_prob
						UpperCAmelCase_:		Tuple							      =     mask_time_length
						UpperCAmelCase_:		str							      =     mask_time_min_masks
						UpperCAmelCase_:		Union[str, Any]							      =     mask_feature_prob
						UpperCAmelCase_:		Union[str, Any]							      =     mask_feature_length
						UpperCAmelCase_:		Any							      =     mask_feature_min_masks

						# parameters for pretraining with codevector quantized representations
						UpperCAmelCase_:		str							      =     num_codevectors_per_group
						UpperCAmelCase_:		Optional[Any]							      =     num_codevector_groups
						UpperCAmelCase_:		Optional[int]							      =     contrastive_logits_temperature
						UpperCAmelCase_:		Dict							      =     feat_quantizer_dropout
						UpperCAmelCase_:		Optional[int]							      =     num_negatives
						UpperCAmelCase_:		str							      =     codevector_dim
						UpperCAmelCase_:		Optional[Any]							      =     proj_codevector_dim
						UpperCAmelCase_:		str							      =     diversity_loss_weight

						# ctc loss
						UpperCAmelCase_:		Optional[int]							      =     ctc_loss_reduction
						UpperCAmelCase_:		int							      =     ctc_zero_infinity

						# pretraining loss
						UpperCAmelCase_:		List[Any]							      =     replace_prob

			@property
			def      __snake_case       (self					)       ->   Union[str, Any]:
						return functools.reduce(operator.mul,   self.conv_stride,   1					)











import logging
import os
from dataclasses import dataclass
from typing import List, Optional, Union

import tqdm
from filelock import FileLock

from transformers import (
    BartTokenizer,
    BartTokenizerFast,
    DataProcessor,
    PreTrainedTokenizer,
    RobertaTokenizer,
    RobertaTokenizerFast,
    XLMRobertaTokenizer,
    is_tf_available,
    is_torch_available,
)


a      :  Optional[Any]			     =			logging.getLogger(__name__)







@dataclass(frozen=_lowerCAmelCase					)
class 				_a				:
			A      		=	42
			A      		=	42
			A      		=	None
			A      		=	None
			A      		=	None







@dataclass(frozen=_lowerCAmelCase					)
class 				_a				:
			A      		=	42
			A      		=	None
			A      		=	None
			A      		=	None
			A      		=	None


if is_torch_available():
	import torch
	from torch.utils.data import Dataset







	class 				_a				(   _lowerCAmelCase					):
				A      		=	42

				def __init__(self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_ = None,   SCREAMING_SNAKE_CASE_=False,   SCREAMING_SNAKE_CASE_ = False,   )       ->   Union[str, Any]:
							UpperCAmelCase_:		Optional[Any]							      =     hans_processors[task]()

							UpperCAmelCase_:		Dict							      =     os.path.join(
							    SCREAMING_SNAKE_CASE_,   """cached_{}_{}_{}_{}""".format(
							        """dev""" if evaluate else """train""",   tokenizer.__class__.__name__,   str(SCREAMING_SNAKE_CASE_					),   SCREAMING_SNAKE_CASE_,   ),   )
							UpperCAmelCase_:		Dict							      =     processor.get_labels()
							if tokenizer.__class__ in (
							    RobertaTokenizer,
							    RobertaTokenizerFast,
							    XLMRobertaTokenizer,
							    BartTokenizer,
							    BartTokenizerFast,
							):
										# HACK(label indices are swapped in RoBERTa pretrained model)
										UpperCAmelCase_      ,							UpperCAmelCase_:		Tuple							      =     label_list[2], label_list[1]
							UpperCAmelCase_:		str							      =     label_list

							# Make sure only the first process in distributed training processes the dataset,
							# and the others will use the cache.
							UpperCAmelCase_:		int							      =     cached_features_file + """.lock"""
							with FileLock(SCREAMING_SNAKE_CASE_					):
										if os.path.exists(SCREAMING_SNAKE_CASE_					) and not overwrite_cache:
													logger.info(f'Loading features from cached file {cached_features_file}'					)
													UpperCAmelCase_:		Dict							      =     torch.load(SCREAMING_SNAKE_CASE_					)
										else:
													logger.info(f'Creating features from dataset file at {data_dir}'					)

													UpperCAmelCase_:		Union[str, Any]							      =     (
													    processor.get_dev_examples(SCREAMING_SNAKE_CASE_					) if evaluate else processor.get_train_examples(SCREAMING_SNAKE_CASE_					)
													)

													logger.info("""Training examples: %s""",   len(SCREAMING_SNAKE_CASE_					)					)
													UpperCAmelCase_:		List[Any]							      =     hans_convert_examples_to_features(SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)
													logger.info("""Saving features into cached file %s""",   SCREAMING_SNAKE_CASE_					)
													torch.save(self.features,   SCREAMING_SNAKE_CASE_					)

				def __len__(self					)       ->   Optional[int]:
							return len(self.features					)

				def __getitem__(self,   SCREAMING_SNAKE_CASE_					)       ->   InputFeatures:
							return self.features[i]

				def      __snake_case       (self					)       ->   List[str]:
							return self.label_list


if is_tf_available():
	import tensorflow as tf







	class 				_a				:
				A      		=	42

				def __init__(self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_ = 128,   SCREAMING_SNAKE_CASE_=False,   SCREAMING_SNAKE_CASE_ = False,   )       ->   Optional[int]:
							UpperCAmelCase_:		Union[str, Any]							      =     hans_processors[task]()
							UpperCAmelCase_:		List[Any]							      =     processor.get_labels()
							if tokenizer.__class__ in (
							    RobertaTokenizer,
							    RobertaTokenizerFast,
							    XLMRobertaTokenizer,
							    BartTokenizer,
							    BartTokenizerFast,
							):
										# HACK(label indices are swapped in RoBERTa pretrained model)
										UpperCAmelCase_      ,							UpperCAmelCase_:		List[str]							      =     label_list[2], label_list[1]
							UpperCAmelCase_:		Dict							      =     label_list

							UpperCAmelCase_:		List[str]							      =     processor.get_dev_examples(SCREAMING_SNAKE_CASE_					) if evaluate else processor.get_train_examples(SCREAMING_SNAKE_CASE_					)
							UpperCAmelCase_:		Any							      =     hans_convert_examples_to_features(SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)

							def gen():
										for ex_index, ex in tqdm.tqdm(enumerate(self.features					),   desc="""convert examples to features"""					):
													if ex_index % 10000 == 0:
																logger.info("""Writing example %d of %d""" % (ex_index, len(SCREAMING_SNAKE_CASE_					))					)

													yield (
													    {
													        "example_id": 0,
													        "input_ids": ex.input_ids,
													        "attention_mask": ex.attention_mask,
													        "token_type_ids": ex.token_type_ids,
													    },
													    ex.label,
													)

							UpperCAmelCase_:		List[str]							      =     tf.data.Dataset.from_generator(
							    SCREAMING_SNAKE_CASE_,   (
							        {
							            """example_id""": tf.intaa,
							            """input_ids""": tf.intaa,
							            """attention_mask""": tf.intaa,
							            """token_type_ids""": tf.intaa,
							        },
							        tf.intaa,
							    ),   (
							        {
							            """example_id""": tf.TensorShape([]					),
							            """input_ids""": tf.TensorShape([None, None]					),
							            """attention_mask""": tf.TensorShape([None, None]					),
							            """token_type_ids""": tf.TensorShape([None, None]					),
							        },
							        tf.TensorShape([]					),
							    ),   )

				def      __snake_case       (self					)       ->   Optional[Any]:
							return self.dataset

				def __len__(self					)       ->   Optional[int]:
							return len(self.features					)

				def __getitem__(self,   SCREAMING_SNAKE_CASE_					)       ->   InputFeatures:
							return self.features[i]

				def      __snake_case       (self					)       ->   Union[str, Any]:
							return self.label_list







class 				_a				(   _lowerCAmelCase					):

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_					)       ->   Dict:
						return self._create_examples(self._read_tsv(os.path.join(SCREAMING_SNAKE_CASE_,   """heuristics_train_set.txt"""					)					),   """train"""					)

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_					)       ->   Dict:
						return self._create_examples(self._read_tsv(os.path.join(SCREAMING_SNAKE_CASE_,   """heuristics_evaluation_set.txt"""					)					),   """dev"""					)

			def      __snake_case       (self					)       ->   Optional[int]:
						return ["contradiction", "entailment", "neutral"]

			def      __snake_case       (self,   SCREAMING_SNAKE_CASE_,   SCREAMING_SNAKE_CASE_					)       ->   List[Any]:
						UpperCAmelCase_:		Optional[Any]							      =     []
						for i, line in enumerate(SCREAMING_SNAKE_CASE_					):
									if i == 0:
												continue
									UpperCAmelCase_:		Tuple							      =     """%s-%s""" % (set_type, line[0])
									UpperCAmelCase_:		int							      =     line[5]
									UpperCAmelCase_:		int							      =     line[6]
									UpperCAmelCase_:		List[str]							      =     line[7][2:] if line[7].startswith("""ex"""					) else line[7]
									UpperCAmelCase_:		Any							      =     line[0]
									examples.append(InputExample(guid=SCREAMING_SNAKE_CASE_,   text_a=SCREAMING_SNAKE_CASE_,   text_b=SCREAMING_SNAKE_CASE_,   label=SCREAMING_SNAKE_CASE_,   pairID=SCREAMING_SNAKE_CASE_					)					)
						return examples







def  lowerCAmelCase_	(lowerCAmelCase__:		List[InputExample]		,						lowerCAmelCase__:		List[str]		,						lowerCAmelCase__:		int		,						lowerCAmelCase__:		PreTrainedTokenizer		,						):





			"""simple docstring"""


			UpperCAmelCase_:		List[str]							      =     {label: i for i, label in enumerate(lowerCAmelCase__  )}

			UpperCAmelCase_:		Optional[int]							      =     []
			for ex_index, example in tqdm.tqdm(enumerate(lowerCAmelCase__  )		,						desc="""convert examples to features"""  ):
						if ex_index % 1_0_0_0_0 == 0:
									logger.info("""Writing example %d""" % (ex_index)  )

						UpperCAmelCase_:		Tuple							      =     tokenizer(
						    example.text_a		,						example.text_b		,						add_special_tokens=lowerCAmelCase__		,						max_length=lowerCAmelCase__		,						padding="""max_length"""		,						truncation=lowerCAmelCase__		,						return_overflowing_tokens=lowerCAmelCase__		,						)

						UpperCAmelCase_:		Optional[Any]							      =     label_map[example.label] if example.label in label_map else 0

						UpperCAmelCase_:		Tuple							      =     int(example.pairID  )

						features.append(InputFeatures(**lowerCAmelCase__		,						label=lowerCAmelCase__		,						pairID=lowerCAmelCase__  )  )

			for i, example in enumerate(examples[:5]  ):
						logger.info("""*** Example ***"""  )
						logger.info(F'guid: {example}'  )
						logger.info(F'features: {features[i]}'  )

			return features


a      :  Optional[int]			     =			{
    'hans': 3,
}

a      :  Dict			     =			{
    'hans': HansProcessor,
}






