

import functools
import operator

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


_UpperCAmelCase		:   Optional[Any]										=       logging.get_logger(__name__)

_UpperCAmelCase		:   str										=       {
    """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  lowercase				(       lowercase_			):
				__SCREAMING_SNAKE_CASE					: Union[str, Any]       			=			'''unispeech'''




				def __init__(					self      ,   snake_case=32      ,   snake_case=768      ,   snake_case=12      ,   snake_case=12      ,   snake_case=3072      ,   snake_case="gelu"      ,   snake_case=0.1      ,   snake_case=0.1      ,   snake_case=0.1      ,   snake_case=0.0      ,   snake_case=0.0      ,   snake_case=0.1      ,   snake_case=0.1      ,   snake_case=0.02      ,   snake_case=1e-5      ,   snake_case="group"      ,   snake_case="gelu"      ,   snake_case=(512, 512, 512, 512, 512, 512, 512)      ,   snake_case=(5, 2, 2, 2, 2, 2, 2)      ,   snake_case=(10, 3, 3, 3, 3, 2, 2)      ,   snake_case=False      ,   snake_case=128      ,   snake_case=16      ,   snake_case=False      ,   snake_case=True      ,   snake_case=0.05      ,   snake_case=10      ,   snake_case=2      ,   snake_case=0.0      ,   snake_case=10      ,   snake_case=0      ,   snake_case=320      ,   snake_case=2      ,   snake_case=0.1      ,   snake_case=100      ,   snake_case=256      ,   snake_case=256      ,   snake_case=0.1      ,   snake_case="mean"      ,   snake_case=False      ,   snake_case=False      ,   snake_case=256      ,   snake_case=80      ,   snake_case=0      ,   snake_case=1      ,   snake_case=2      ,   snake_case=0.5      ,   **snake_case      ,   ):
											super().__init__(**snake_case      ,   pad_token_id=snake_case      ,   bos_token_id=snake_case      ,   eos_token_id=snake_case       )
											snake_case_							=    hidden_size
											snake_case_							=    feat_extract_norm
											snake_case_							=    feat_extract_activation
											snake_case_							=    list(snake_case       )
											snake_case_							=    list(snake_case       )
											snake_case_							=    list(snake_case       )
											snake_case_							=    conv_bias
											snake_case_							=    num_conv_pos_embeddings
											snake_case_							=    num_conv_pos_embedding_groups
											snake_case_							=    len(self.conv_dim       )
											snake_case_							=    num_hidden_layers
											snake_case_							=    intermediate_size
											snake_case_							=    hidden_act
											snake_case_							=    num_attention_heads
											snake_case_							=    hidden_dropout
											snake_case_							=    attention_dropout
											snake_case_							=    activation_dropout
											snake_case_							=    feat_proj_dropout
											snake_case_							=    final_dropout
											snake_case_							=    layerdrop
											snake_case_							=    layer_norm_eps
											snake_case_							=    initializer_range
											snake_case_							=    num_ctc_classes
											snake_case_							=    vocab_size
											snake_case_							=    do_stable_layer_norm
											snake_case_							=    use_weighted_layer_sum
											snake_case_							=    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
											snake_case_							=    apply_spec_augment
											snake_case_							=    mask_time_prob
											snake_case_							=    mask_time_length
											snake_case_							=    mask_time_min_masks
											snake_case_							=    mask_feature_prob
											snake_case_							=    mask_feature_length
											snake_case_							=    mask_feature_min_masks

											# parameters for pretraining with codevector quantized representations
											snake_case_							=    num_codevectors_per_group
											snake_case_							=    num_codevector_groups
											snake_case_							=    contrastive_logits_temperature
											snake_case_							=    feat_quantizer_dropout
											snake_case_							=    num_negatives
											snake_case_							=    codevector_dim
											snake_case_							=    proj_codevector_dim
											snake_case_							=    diversity_loss_weight

											# ctc loss
											snake_case_							=    ctc_loss_reduction
											snake_case_							=    ctc_zero_infinity

											# pretraining loss
											snake_case_							=    replace_prob




				@property
				def     a							(					self       ):
											return functools.reduce(operator.mul      ,   self.conv_stride      ,   1       )







import os

import numpy
import onnx





def 					__lowerCamelCase	( UpperCamelCase__   ,							UpperCamelCase__      ):







							'''simple docstring'''






							snake_case_							=    a.name
							snake_case_							=    b.name

							snake_case_							=    ''
							snake_case_							=    ''

							snake_case_							=    a == b

							snake_case_							=    name_a
							snake_case_							=    name_b

							return res





def 					__lowerCamelCase	( UpperCamelCase__   ,							UpperCamelCase__   ,							UpperCamelCase__      ):







							'''simple docstring'''






							for i, input_name in enumerate(node_proto.input      ):
														if input_name == name:
																					node_proto.input.insert(UpperCamelCase__   ,							UpperCamelCase__      )
																					node_proto.input.pop(i + 1      )

							if node_proto.op_type == "If":
														_graph_replace_input_with(node_proto.attribute[0].g   ,							UpperCamelCase__   ,							UpperCamelCase__      )
														_graph_replace_input_with(node_proto.attribute[1].g   ,							UpperCamelCase__   ,							UpperCamelCase__      )
							if node_proto.op_type == "Loop":
														_graph_replace_input_with(node_proto.attribute[0].g   ,							UpperCamelCase__   ,							UpperCamelCase__      )





def 					__lowerCamelCase	( UpperCamelCase__   ,							UpperCamelCase__   ,							UpperCamelCase__      ):







							'''simple docstring'''






							for n in graph_proto.node:
														_node_replace_input_with(UpperCamelCase__   ,							UpperCamelCase__   ,							UpperCamelCase__      )





def 					__lowerCamelCase	( UpperCamelCase__   ,							UpperCamelCase__   ,							UpperCamelCase__      ):







							'''simple docstring'''






							snake_case_							=    list(model.graph.initializer      )
							snake_case_							=    list(model_without_ext.graph.initializer      )
							for i, ref_i in ind_to_replace:
														assert inits_with_data[i].name == inits[i].name
														assert inits_with_data[ref_i].name == inits[ref_i].name
														assert i > ref_i

														snake_case_							=    inits[i].name
														snake_case_							=    inits[ref_i].name

														model_without_ext.graph.initializer.remove(inits[i]      )

														# for n in model.graph.node:
														_graph_replace_input_with(model_without_ext.graph   ,							UpperCamelCase__   ,							UpperCamelCase__      )





def 					__lowerCamelCase	( UpperCamelCase__      ):







							'''simple docstring'''






							snake_case_							=    os.path.dirname(UpperCamelCase__      )
							snake_case_							=    os.path.basename(UpperCamelCase__      )

							snake_case_							=    onnx.load(os.path.join(UpperCamelCase__   ,							UpperCamelCase__      )      )

							snake_case_							=    list(model.graph.initializer      )

							snake_case_							=    set()
							snake_case_							=    {}
							snake_case_							=    []

							snake_case_							=    0

							for i in range(len(UpperCamelCase__      )      ):
														if i in dup_set:
																					continue

														for j in range(i + 1   ,							len(UpperCamelCase__      )      ):
																					if j in dup_set:
																												continue
																					if _is_equal_tensor_proto(inits[i]   ,							inits[j]      ):
																												dup_set.add(UpperCamelCase__      )
																												dup_set.add(UpperCamelCase__      )

																												snake_case_							=    inits[j].data_type
																												snake_case_							=    numpy.prod(inits[j].dims      )
																												if dtype == 1:
																																			mem_size *= 4
																												elif dtype == 6:
																																			mem_size *= 4
																												elif dtype == 7 or dtype == 11:
																																			mem_size *= 8
																												else:
																																			print('unexpected data type: '   ,							UpperCamelCase__      )
																												total_reduced_size += mem_size

																												snake_case_							=    inits[i].name
																												snake_case_							=    inits[j].name

																												if name_i in dup_map:
																																			dup_map[name_i].append(UpperCamelCase__      )
																												else:
																																			snake_case_							=    [name_j]
																												ind_to_replace.append((j, i)      )

							print('total reduced size: '   ,							total_reduced_size / 1024 / 1024 / 1024   ,							'GB'      )

							snake_case_							=    sorted(UpperCamelCase__      )
							_remove_dup_initializers_from_model(UpperCamelCase__   ,							UpperCamelCase__   ,							UpperCamelCase__      )

							snake_case_							=    'optimized_' + model_file_name
							snake_case_							=    os.path.join(UpperCamelCase__   ,							UpperCamelCase__      )
							onnx.save(UpperCamelCase__   ,							UpperCamelCase__      )

							return new_model




