code: 
  '''simple docstring'''
  
  
  
  import argparse
  
  import torch
  from saprl.hub import distilhubert
  
  from transformers import HubertConfig, HubertModel, WavaVecaFeatureExtractor, logging
  
  
  logging.set_verbosity_info()
  __A          =    logging.get_logger(__name__)
  
  __A          =    {
      "post_extract_proj": "feature_projection.projection",
      "encoder.pos_conv.0": "encoder.pos_conv_embed.conv",
      "self_attn.k_proj": "encoder.layers.*.attention.k_proj",
      "self_attn.v_proj": "encoder.layers.*.attention.v_proj",
      "self_attn.q_proj": "encoder.layers.*.attention.q_proj",
      "self_attn.out_proj": "encoder.layers.*.attention.out_proj",
      "self_attn_layer_norm": "encoder.layers.*.layer_norm",
      "fc1": "encoder.layers.*.feed_forward.intermediate_dense",
      "fc2": "encoder.layers.*.feed_forward.output_dense",
      "final_layer_norm": "encoder.layers.*.final_layer_norm",
      "encoder.layer_norm": "encoder.layer_norm",
      "mask_emb": "masked_spec_embed",
  }
  
  
  
  
  
  def  _A		(				lowercase__		,		lowercase__		,		lowercase__		,		lowercase__		,		lowercase__	):
  						for attribute in key.split("""."""	):
  												lowercase__							 =       getattr(lowercase__		,		lowercase__	)
  
  						if weight_type is not None:
  												lowercase__							 =       getattr(lowercase__		,		lowercase__	).shape
  						else:
  												lowercase__							 =       hf_pointer.shape
  
  						assert hf_shape == value.shape, (
  						    f'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be'''
  						    f''' {value.shape} for {full_name}'''
  						)
  
  						if weight_type == "weight":
  												lowercase__							 =       value
  						elif weight_type == "weight_g":
  												lowercase__							 =       value
  						elif weight_type == "weight_v":
  												lowercase__							 =       value
  						elif weight_type == "bias":
  												lowercase__							 =       value
  						else:
  												lowercase__							 =       value
  
  						logger.info(f'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.'''	)
  
  
  
  
  
  def  _A		(				lowercase__		,		lowercase__	):
  						lowercase__							 =       []
  						lowercase__							 =       fairseq_model.state_dict()
  
  						lowercase__							 =       hf_model.feature_extractor
  
  						for name, value in fairseq_dict.items():
  												lowercase__							 =       False
  												if "conv_layers" in name:
  																		load_conv_layer(
  																		    lowercase__		,		lowercase__		,		lowercase__		,		lowercase__		,		hf_model.config.feat_extract_norm == """group"""		,		)
  																		lowercase__							 =       True
  												else:
  																		for key, mapped_key in MAPPING.items():
  																								lowercase__							 =       mapped_key
  
  																								if key in name:
  																														lowercase__							 =       True
  																														if "*" in mapped_key:
  																																				lowercase__							 =       name.split(lowercase__	)[0].split("""."""	)[-2]
  																																				lowercase__							 =       mapped_key.replace("""*"""		,		lowercase__	)
  																														if "weight_g" in name:
  																																				lowercase__							 =       """weight_g"""
  																														elif "weight_v" in name:
  																																				lowercase__							 =       """weight_v"""
  																														elif "weight" in name:
  																																				lowercase__							 =       """weight"""
  																														elif "bias" in name:
  																																				lowercase__							 =       """bias"""
  																														else:
  																																				lowercase__							 =       None
  																														set_recursively(lowercase__		,		lowercase__		,		lowercase__		,		lowercase__		,		lowercase__	)
  																								continue
  												if not is_used:
  																		unused_weights.append(lowercase__	)
  
  						logger.warning(f'''Unused weights: {unused_weights}'''	)
  
  
  
  
  
  def  _A		(				lowercase__		,		lowercase__		,		lowercase__		,		lowercase__		,		lowercase__	):
  						lowercase__							 =       full_name.split("""conv_layers."""	)[-1]
  						lowercase__							 =       name.split("""."""	)
  						lowercase__							 =       int(items[0]	)
  						lowercase__							 =       int(items[1]	)
  
  						if type_id == 0:
  												if "bias" in name:
  																		assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
  																		    f'''{full_name} has size {value.shape}, but'''
  																		    f''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.'''
  																		)
  																		lowercase__							 =       value
  																		logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.'''	)
  												elif "weight" in name:
  																		assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
  																		    f'''{full_name} has size {value.shape}, but'''
  																		    f''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.'''
  																		)
  																		lowercase__							 =       value
  																		logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.'''	)
  						elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
  												if "bias" in name:
  																		assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
  																		    f'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was'''
  																		    " found."
  																		)
  																		lowercase__							 =       value
  																		logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'''	)
  												elif "weight" in name:
  																		assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
  																		    f'''{full_name} has size {value.shape}, but'''
  																		    f''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.'''
  																		)
  																		lowercase__							 =       value
  																		logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'''	)
  						else:
  												unused_weights.append(lowercase__	)
  
  
  
  
  
  def  _A		(				lowercase__	):
  						lowercase__							 =       HubertConfig()
  						lowercase__							 =       model.config
  
  						lowercase__							 =       fs_config.activation_dropout
  						lowercase__							 =       False
  						lowercase__							 =       fs_config.attention_dropout
  						lowercase__							 =       False
  						lowercase__							 =       eval(fs_config.extractor_conv_feature_layers	)
  						lowercase__							 =       [x[0] for x in conv_layers]
  						lowercase__							 =       [x[1] for x in conv_layers]
  						lowercase__							 =       [x[2] for x in conv_layers]
  						lowercase__							 =       """gelu"""
  						lowercase__							 =       """layer""" if fs_config.extractor_mode == """layer_norm""" else """group"""
  						lowercase__							 =       False
  						lowercase__							 =       0.0
  						lowercase__							 =       0.0
  						lowercase__							 =       fs_config.activation_fn
  						lowercase__							 =       fs_config.dropout
  						lowercase__							 =       fs_config.encoder_embed_dim
  						lowercase__							 =       0.0_2
  						lowercase__							 =       fs_config.encoder_ffn_embed_dim
  						lowercase__							 =       1e-5
  						lowercase__							 =       0.0
  						lowercase__							 =       fs_config.encoder_attention_heads
  						lowercase__							 =       fs_config.conv_pos_groups
  						lowercase__							 =       fs_config.conv_pos
  						lowercase__							 =       len(lowercase__	)
  						lowercase__							 =       fs_config.encoder_layers
  
  						return config
  
  
  
  
  
  @torch.no_grad()
  def  _A		(				lowercase__		,		lowercase__=None	):
  						lowercase__							 =       distilhubert().model.model
  
  						if config_path is not None:
  												lowercase__							 =       HubertConfig.from_pretrained(lowercase__	)
  						else:
  												lowercase__							 =       convert_config(lowercase__	)
  						lowercase__							 =       model.eval()
  
  						lowercase__							 =       WavaVecaFeatureExtractor(
  						    feature_size=1		,		sampling_rate=16000		,		padding_value=0		,		do_normalize=lowercase__		,		return_attention_mask=lowercase__		,		)
  						lowercase__							 =       HubertModel(lowercase__	)
  
  						recursively_load_weights(lowercase__		,		lowercase__	)
  
  						feature_extractor.save_pretrained(lowercase__	)
  						hf_model.save_pretrained(lowercase__	)
  
  
  if __name__ == "__main__":
  				__A          =    argparse.ArgumentParser()
  				parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
  				parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
  				__A          =    parser.parse_args()
  				convert_hubert_checkpoint(args.pytorch_dump_folder_path, args.config_path)
  
  
  
  
  
  
  
style_context: 
  '''simple docstring'''
  
  
  
  import timeit
  from typing import Callable, Optional
  
  from ..configuration_utils import PretrainedConfig
  from ..models.auto.modeling_auto import MODEL_MAPPING, MODEL_WITH_LM_HEAD_MAPPING
  from ..utils import is_pyanvml_available, is_torch_available, logging
  from .benchmark_utils import (
      Benchmark,
      Memory,
      MemorySummary,
      measure_peak_memory_cpu,
      start_memory_tracing,
      stop_memory_tracing,
  )
  
  
  if is_torch_available():
  				import torch
  
  				from .benchmark_args import PyTorchBenchmarkArguments
  
  
  if is_pyanvml_available():
  				import pyanvml.pyanvml as nvml
  
  
  __A          =    logging.get_logger(__name__)
  
  
  
  
  
  class 			A							(       __UpperCAmelCase				):
  			lowerCamelCase							:							PyTorchBenchmarkArguments
  			lowerCamelCase							:							PretrainedConfig
  			lowerCamelCase							:							str       		=  "PyTorch"
  
  
  
  			@property
  			def A__ (					self       )			->		Union[str, Any]:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									return torch.__version__
  
  
  
  			def A__ (					self       ,     lowerCamelCase__       ,     lowerCamelCase__       ,     lowerCamelCase__       )			->		float:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									lowercase__							 =       self._prepare_inference_func(lowerCamelCase__       ,     lowerCamelCase__       ,     lowerCamelCase__       )
  									return self._measure_speed(_inference       )
  
  
  
  			def A__ (					self       ,     lowerCamelCase__       ,     lowerCamelCase__       ,     lowerCamelCase__       )			->		[Memory, Optional[MemorySummary]]:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									lowercase__							 =       self._prepare_inference_func(lowerCamelCase__       ,     lowerCamelCase__       ,     lowerCamelCase__       )
  									return self._measure_memory(_inference       )
  
  
  
  			def A__ (					self       ,     lowerCamelCase__       ,     lowerCamelCase__       ,     lowerCamelCase__       )			->		float:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									lowercase__							 =       self._prepare_train_func(lowerCamelCase__       ,     lowerCamelCase__       ,     lowerCamelCase__       )
  									return self._measure_speed(_train       )
  
  
  
  			def A__ (					self       ,     lowerCamelCase__       ,     lowerCamelCase__       ,     lowerCamelCase__       )			->		[Memory, Optional[MemorySummary]]:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									lowercase__							 =       self._prepare_train_func(lowerCamelCase__       ,     lowerCamelCase__       ,     lowerCamelCase__       )
  									return self._measure_memory(_train       )
  
  
  
  			def A__ (					self       ,     lowerCamelCase__       ,     lowerCamelCase__       ,     lowerCamelCase__       )			->		Callable[[], None]:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									lowercase__							 =       self.config_dict[model_name]
  
  									if self.args.torchscript:
  															lowercase__							 =       True
  
  									lowercase__							 =       (
  									    hasattr(lowerCamelCase__       ,     """architectures"""       )
  									    and isinstance(config.architectures       ,     lowerCamelCase__       )
  									    and len(config.architectures       ) > 0
  									)
  									if not self.args.only_pretrain_model and has_model_class_in_config:
  															try:
  																					lowercase__							 =       config.architectures[0]
  																					lowercase__							 =       __import__("""transformers"""       ,     fromlist=[model_class]       )
  																					lowercase__							 =       getattr(lowerCamelCase__       ,     lowerCamelCase__       )
  																					lowercase__							 =       model_cls(lowerCamelCase__       )
  															except ImportError:
  																					raise ImportError(
  																					    F'''{model_class} does not exist. If you just want to test the pretrained model, you might want to'''
  																					    """ set `--only_pretrain_model` or `args.only_pretrain_model=True`."""       )
  									else:
  															lowercase__							 =       MODEL_MAPPING[config.__class__](lowerCamelCase__       )
  
  									model.eval()
  									model.to(self.args.device       )
  
  									# encoder-decoder has vocab size saved differently
  									lowercase__							 =       config.vocab_size if hasattr(lowerCamelCase__       ,     """vocab_size"""       ) else config.encoder.vocab_size
  									lowercase__							 =       torch.randint(lowerCamelCase__       ,     (batch_size, sequence_length)       ,     dtype=torch.long       ,     device=self.args.device       )
  
  									if self.args.fpaa:
  															logger.info("""Running training in Mixed Precision..."""       )
  															if not self.args.is_gpu:
  																					raise ValueError("""Mixed precision is possible only for GPU."""       )
  															# amp seems to have memory leaks so that memory usage
  															# is measured using .half() for now https://github.com/NVIDIA/apex/issues/439
  															model.half()
  
  									if self.args.torchscript:
  															with torch.no_grad():
  																					lowercase__							 =       torch.jit.trace(lowerCamelCase__       ,     lowerCamelCase__       )
  									else:
  															lowercase__							 =       model
  
  									def encoder_decoder_forward():
  															with torch.no_grad():
  																					lowercase__							 =       inference_model(lowerCamelCase__       ,     decoder_input_ids=lowerCamelCase__       )
  															return outputs
  
  									def encoder_forward():
  															with torch.no_grad():
  																					lowercase__							 =       inference_model(lowerCamelCase__       )
  															return outputs
  
  									lowercase__							 =       encoder_decoder_forward if config.is_encoder_decoder else encoder_forward
  									return _forward
  
  
  
  			def A__ (					self       ,     lowerCamelCase__       ,     lowerCamelCase__       ,     lowerCamelCase__       )			->		Callable[[], None]:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									lowercase__							 =       self.config_dict[model_name]
  
  									lowercase__							 =       (
  									    hasattr(lowerCamelCase__       ,     """architectures"""       )
  									    and isinstance(config.architectures       ,     lowerCamelCase__       )
  									    and len(config.architectures       ) > 0
  									)
  									if not self.args.only_pretrain_model and has_model_class_in_config:
  															try:
  																					lowercase__							 =       config.architectures[0]
  																					lowercase__							 =       __import__("""transformers"""       ,     fromlist=[model_class]       )
  																					lowercase__							 =       getattr(lowerCamelCase__       ,     lowerCamelCase__       )
  																					lowercase__							 =       model_cls(lowerCamelCase__       )
  															except ImportError:
  																					raise ImportError(
  																					    F'''{model_class} does not exist. If you just want to test the pretrained model, you might want to'''
  																					    """ set `--only_pretrain_model` or `args.only_pretrain_model=True`."""       )
  									else:
  															lowercase__							 =       MODEL_WITH_LM_HEAD_MAPPING[config.__class__](lowerCamelCase__       )
  
  									if self.args.torchscript:
  															raise NotImplementedError("""Training for torchscript is currently not implemented"""       )
  									else:
  															lowercase__							 =       model
  
  									model.train()
  									model.to(self.args.device       )
  
  									# encoder-decoder has vocab size saved differently
  									lowercase__							 =       config.vocab_size if hasattr(lowerCamelCase__       ,     """vocab_size"""       ) else config.encoder.vocab_size
  									lowercase__							 =       torch.randint(lowerCamelCase__       ,     (batch_size, sequence_length)       ,     dtype=torch.long       ,     device=self.args.device       )
  
  									if self.args.fpaa:
  															logger.info("""Running training in Mixed Precision..."""       )
  															if not self.args.is_gpu:
  																					raise ValueError("""Mixed precision is possible only for GPU."""       )
  
  															# amp seems to have memory leaks so that memory usage
  															# is measured using .half() for now https://github.com/NVIDIA/apex/issues/439
  															model.half()
  
  									def compute_loss_and_backprob_encoder():
  															lowercase__							 =       train_model(lowerCamelCase__       ,     labels=lowerCamelCase__       )[0]
  															loss.backward()
  															return loss
  
  									def compute_loss_and_backprob_encoder_decoder():
  															lowercase__							 =       train_model(lowerCamelCase__       ,     decoder_input_ids=lowerCamelCase__       ,     labels=lowerCamelCase__       )[0]
  															loss.backward()
  															return loss
  
  									lowercase__							 =       (
  									    compute_loss_and_backprob_encoder_decoder
  									    if config.is_encoder_decoder
  									    else compute_loss_and_backprob_encoder
  									)
  									return _train
  
  
  
  			def A__ (					self       ,     lowerCamelCase__       )			->		float:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									try:
  															if self.args.is_tpu or self.args.torchscript:
  																					# run additional 10 times to stabilize compilation for tpu and torchscript
  																					logger.info("""Do inference on TPU or torchscript. Running model 5 times to stabilize compilation"""       )
  																					timeit.repeat(
  																					    lowerCamelCase__       ,     repeat=1       ,     number=5       ,     )
  
  															# as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average
  															lowercase__							 =       timeit.repeat(
  															    lowerCamelCase__       ,     repeat=self.args.repeat       ,     number=10       ,     )
  
  															if self.args.is_tpu and self.args.torch_xla_tpu_print_metrics:
  																					import torch_xla.debug.metrics as met
  
  																					self.print_fn(met.metrics_report()       )
  
  															return min(lowerCamelCase__       ) / 10.0
  									except RuntimeError as e:
  															self.print_fn(F'''Doesn\'t fit on GPU. {e}'''       )
  															return "N/A"
  
  
  
  			def A__ (					self       ,     lowerCamelCase__       )			->		[Memory, MemorySummary]:
  
  
  
  
  									'''simple docstring'''
  
  
  
  									try:
  															if self.args.trace_memory_line_by_line:
  																					lowercase__							 =       start_memory_tracing("""transformers"""       )
  
  															if self.args.is_tpu:
  																					# tpu
  																					raise NotImplementedError(
  																					    """Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking with"""
  																					    """ `--no-memory` or `args.memory=False`"""       )
  															elif self.args.is_gpu:
  																					if not is_pyanvml_available():
  																											logger.warning(
  																											    """py3nvml not installed, we won't log GPU memory usage. """
  																											    """Install py3nvml (pip install py3nvml) to log information about GPU."""       )
  																											lowercase__							 =       """N/A"""
  																					else:
  																											logger.info(
  																											    """Measuring total GPU usage on GPU device. Make sure to not have additional processes running"""
  																											    """ on the same GPU."""       )
  																											# init nvml
  																											nvml.nvmlInit()
  																											func()
  																											lowercase__							 =       nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx       )
  																											lowercase__							 =       nvml.nvmlDeviceGetMemoryInfo(lowerCamelCase__       )
  																											lowercase__							 =       meminfo.used
  																											lowercase__							 =       Memory(lowerCamelCase__       )
  																											# shutdown nvml
  																											nvml.nvmlShutdown()
  															else:
  																					# cpu
  																					lowercase__							 =       measure_peak_memory_cpu(lowerCamelCase__       )
  																					lowercase__							 =       Memory(lowerCamelCase__       ) if isinstance(lowerCamelCase__       ,     lowerCamelCase__       ) else memory_bytes
  
  															if self.args.trace_memory_line_by_line:
  																					lowercase__							 =       stop_memory_tracing(lowerCamelCase__       )
  															else:
  																					lowercase__							 =       None
  
  															return memory, summary
  									except RuntimeError as e:
  															self.print_fn(F'''Doesn\'t fit on GPU. {e}'''       )
  															return "N/A", None
  
  
  
  
  
  
  