





'''simple docstring'''







import argparse

import torch
from saprl.hub import distilhubert

from transformers import HubertConfig, HubertModel, WavaVecaFeatureExtractor, logging


logging.set_verbosity_info()
snake_case_  :							Any            =	logging.get_logger(__name__)

snake_case_  :							List[Any]            =	{
    "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 							lowerCamelCase_   (	SCREAMING_SNAKE_CASE__   :      Any,      SCREAMING_SNAKE_CASE__   :      Tuple,      SCREAMING_SNAKE_CASE__   :      Optional[int],      SCREAMING_SNAKE_CASE__   :      Optional[int],      SCREAMING_SNAKE_CASE__   :      int )			->						List[Any]:
						for attribute in key.split('''.''' ):
												UpperCAmelCase_      :   int      =	getattr(SCREAMING_SNAKE_CASE__,      SCREAMING_SNAKE_CASE__ )

						if weight_type is not None:
												UpperCAmelCase_      :   Dict      =	getattr(SCREAMING_SNAKE_CASE__,      SCREAMING_SNAKE_CASE__ ).shape
						else:
												UpperCAmelCase_      :   Union[str, Any]      =	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":
												UpperCAmelCase_      :   Tuple      =	value
						elif weight_type == "weight_g":
												UpperCAmelCase_      :   Union[str, Any]      =	value
						elif weight_type == "weight_v":
												UpperCAmelCase_      :   Any      =	value
						elif weight_type == "bias":
												UpperCAmelCase_      :   int      =	value
						else:
												UpperCAmelCase_      :   Dict      =	value

						logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" )





def 							lowerCamelCase_   (	SCREAMING_SNAKE_CASE__   :      Dict,      SCREAMING_SNAKE_CASE__   :      Optional[Any] )			->						Union[str, Any]:
						UpperCAmelCase_      :   Any      =	[]
						UpperCAmelCase_      :   List[Any]      =	fairseq_model.state_dict()

						UpperCAmelCase_      :   Tuple      =	hf_model.feature_extractor

						for name, value in fairseq_dict.items():
												UpperCAmelCase_      :   str      =	False
												if "conv_layers" in name:
																		load_conv_layer(
																		    SCREAMING_SNAKE_CASE__,      SCREAMING_SNAKE_CASE__,      SCREAMING_SNAKE_CASE__,      SCREAMING_SNAKE_CASE__,      hf_model.config.feat_extract_norm == '''group''',      )
																		UpperCAmelCase_      :   List[Any]      =	True
												else:
																		for key, mapped_key in MAPPING.items():
																								UpperCAmelCase_      :   Optional[Any]      =	mapped_key

																								if key in name:
																														UpperCAmelCase_      :   int      =	True
																														if "*" in mapped_key:
																																				UpperCAmelCase_      :   str      =	name.split(SCREAMING_SNAKE_CASE__ )[0].split('''.''' )[-2]
																																				UpperCAmelCase_      :   Union[str, Any]      =	mapped_key.replace('''*''',      SCREAMING_SNAKE_CASE__ )
																														if "weight_g" in name:
																																				UpperCAmelCase_      :   Union[str, Any]      =	'''weight_g'''
																														elif "weight_v" in name:
																																				UpperCAmelCase_      :   Union[str, Any]      =	'''weight_v'''
																														elif "weight" in name:
																																				UpperCAmelCase_      :   str      =	'''weight'''
																														elif "bias" in name:
																																				UpperCAmelCase_      :   Optional[int]      =	'''bias'''
																														else:
																																				UpperCAmelCase_      :   List[str]      =	None
																														set_recursively(SCREAMING_SNAKE_CASE__,      SCREAMING_SNAKE_CASE__,      SCREAMING_SNAKE_CASE__,      SCREAMING_SNAKE_CASE__,      SCREAMING_SNAKE_CASE__ )
																								continue
												if not is_used:
																		unused_weights.append(SCREAMING_SNAKE_CASE__ )

						logger.warning(F"""Unused weights: {unused_weights}""" )





def 							lowerCamelCase_   (	SCREAMING_SNAKE_CASE__   :      Optional[int],      SCREAMING_SNAKE_CASE__   :      List[str],      SCREAMING_SNAKE_CASE__   :      Union[str, Any],      SCREAMING_SNAKE_CASE__   :      Union[str, Any],      SCREAMING_SNAKE_CASE__   :      str )			->						Any:
						UpperCAmelCase_      :   str      =	full_name.split('''conv_layers.''' )[-1]
						UpperCAmelCase_      :   Optional[Any]      =	name.split('''.''' )
						UpperCAmelCase_      :   Any      =	int(items[0] )
						UpperCAmelCase_      :   List[str]      =	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."""
																		)
																		UpperCAmelCase_      :   Optional[int]      =	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."""
																		)
																		UpperCAmelCase_      :   int      =	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."
																		)
																		UpperCAmelCase_      :   Optional[int]      =	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."""
																		)
																		UpperCAmelCase_      :   Optional[int]      =	value
																		logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" )
						else:
												unused_weights.append(SCREAMING_SNAKE_CASE__ )





def 							lowerCamelCase_   (	SCREAMING_SNAKE_CASE__   :      List[Any] )			->						Union[str, Any]:
						UpperCAmelCase_      :   Optional[int]      =	HubertConfig()
						UpperCAmelCase_      :   Dict      =	model.config

						UpperCAmelCase_      :   str      =	fs_config.activation_dropout
						UpperCAmelCase_      :   List[Any]      =	False
						UpperCAmelCase_      :   str      =	fs_config.attention_dropout
						UpperCAmelCase_      :   Optional[int]      =	False
						UpperCAmelCase_      :   str      =	eval(fs_config.extractor_conv_feature_layers )
						UpperCAmelCase_      :   Dict      =	[x[0] for x in conv_layers]
						UpperCAmelCase_      :   List[Any]      =	[x[1] for x in conv_layers]
						UpperCAmelCase_      :   Any      =	[x[2] for x in conv_layers]
						UpperCAmelCase_      :   Union[str, Any]      =	'''gelu'''
						UpperCAmelCase_      :   Optional[Any]      =	'''layer''' if fs_config.extractor_mode == '''layer_norm''' else '''group'''
						UpperCAmelCase_      :   str      =	False
						UpperCAmelCase_      :   Tuple      =	0.0
						UpperCAmelCase_      :   Optional[int]      =	0.0
						UpperCAmelCase_      :   Union[str, Any]      =	fs_config.activation_fn
						UpperCAmelCase_      :   Optional[Any]      =	fs_config.dropout
						UpperCAmelCase_      :   Any      =	fs_config.encoder_embed_dim
						UpperCAmelCase_      :   int      =	0.02
						UpperCAmelCase_      :   List[str]      =	fs_config.encoder_ffn_embed_dim
						UpperCAmelCase_      :   List[str]      =	1E-5
						UpperCAmelCase_      :   Union[str, Any]      =	0.0
						UpperCAmelCase_      :   List[str]      =	fs_config.encoder_attention_heads
						UpperCAmelCase_      :   str      =	fs_config.conv_pos_groups
						UpperCAmelCase_      :   str      =	fs_config.conv_pos
						UpperCAmelCase_      :   Tuple      =	len(SCREAMING_SNAKE_CASE__ )
						UpperCAmelCase_      :   int      =	fs_config.encoder_layers

						return config





@torch.no_grad()
def 							lowerCamelCase_   (	SCREAMING_SNAKE_CASE__   :      Dict,      SCREAMING_SNAKE_CASE__   :      List[str]=None )			->						Union[str, Any]:
						UpperCAmelCase_      :   Optional[Any]      =	distilhubert().model.model

						if config_path is not None:
												UpperCAmelCase_      :   str      =	HubertConfig.from_pretrained(SCREAMING_SNAKE_CASE__ )
						else:
												UpperCAmelCase_      :   Any      =	convert_config(SCREAMING_SNAKE_CASE__ )
						UpperCAmelCase_      :   Any      =	model.eval()

						UpperCAmelCase_      :   str      =	WavaVecaFeatureExtractor(
						    feature_size=1,      sampling_rate=16000,      padding_value=0,      do_normalize=SCREAMING_SNAKE_CASE__,      return_attention_mask=SCREAMING_SNAKE_CASE__,      )
						UpperCAmelCase_      :   str      =	HubertModel(SCREAMING_SNAKE_CASE__ )

						recursively_load_weights(SCREAMING_SNAKE_CASE__,      SCREAMING_SNAKE_CASE__ )

						feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE__ )
						hf_model.save_pretrained(SCREAMING_SNAKE_CASE__ )


if __name__ == "__main__":
					snake_case_  :							Any            =	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")
					snake_case_  :							List[str]            =	parser.parse_args()
					convert_hubert_checkpoint(args.pytorch_dump_folder_path, args.config_path)












'''simple docstring'''







from manim import *


class        __a   (lowerCamelCase  ):

							def      UpperCAmelCase__						(				self				:  str )       ->							Any:







													"""simple docstring"""
													UpperCAmelCase_      :   List[str]      =	Rectangle(height=0.5							,  width=0.5 )
													UpperCAmelCase_      :   int      =	Rectangle(height=0.4_6							,  width=0.4_6 ).set_stroke(width=0 )
													UpperCAmelCase_      :   str      =	Rectangle(height=0.2_5							,  width=0.2_5 )

													UpperCAmelCase_      :   Optional[Any]      =	[mem.copy() for i in range(6 )]
													UpperCAmelCase_      :   int      =	[mem.copy() for i in range(6 )]
													UpperCAmelCase_      :   List[str]      =	VGroup(*__magic_name__ ).arrange(__magic_name__							,  buff=0 )
													UpperCAmelCase_      :   Optional[Any]      =	VGroup(*__magic_name__ ).arrange(__magic_name__							,  buff=0 )
													UpperCAmelCase_      :   List[Any]      =	VGroup(__magic_name__							,  __magic_name__ ).arrange(__magic_name__							,  buff=0 )
													UpperCAmelCase_      :   int      =	Text('''CPU'''							,  font_size=24 )
													UpperCAmelCase_      :   Optional[Any]      =	Group(__magic_name__							,  __magic_name__ ).arrange(__magic_name__							,  buff=0.5							,  aligned_edge=__magic_name__ )
													cpu.move_to([-2.5, -0.5, 0] )
													self.add(__magic_name__ )

													UpperCAmelCase_      :   List[Any]      =	[mem.copy() for i in range(4 )]
													UpperCAmelCase_      :   List[str]      =	VGroup(*__magic_name__ ).arrange(__magic_name__							,  buff=0 )
													UpperCAmelCase_      :   str      =	Text('''GPU'''							,  font_size=24 )
													UpperCAmelCase_      :   Union[str, Any]      =	Group(__magic_name__							,  __magic_name__ ).arrange(__magic_name__							,  buff=0.5							,  aligned_edge=__magic_name__ )
													gpu.move_to([-1, -1, 0] )
													self.add(__magic_name__ )

													UpperCAmelCase_      :   Dict      =	[mem.copy() for i in range(6 )]
													UpperCAmelCase_      :   Optional[Any]      =	VGroup(*__magic_name__ ).arrange(__magic_name__							,  buff=0 )

													UpperCAmelCase_      :   Dict      =	Text('''Model'''							,  font_size=24 )
													UpperCAmelCase_      :   str      =	Group(__magic_name__							,  __magic_name__ ).arrange(__magic_name__							,  buff=0.5							,  aligned_edge=__magic_name__ )
													model.move_to([3, -1.0, 0] )
													self.add(__magic_name__ )

													UpperCAmelCase_      :   List[str]      =	[]
													UpperCAmelCase_      :   int      =	[]

													for i, rect in enumerate(__magic_name__ ):
																			rect.set_stroke(__magic_name__ )

																			UpperCAmelCase_      :   List[Any]      =	Rectangle(height=0.4_6 / 4							,  width=0.4_6 / 3 ).set_stroke(width=0.0 ).set_fill(__magic_name__							,  opacity=0.7 )

																			if i == 0:
																									cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT )							,  buff=0.0_2							,  direction=__magic_name__ )
																									cpu_target.set_x(cpu_target.get_x() + 0.1 )
																			elif i == 3:
																									cpu_target.next_to(model_cpu_arr[0]							,  direction=__magic_name__							,  buff=0.0 )
																			else:
																									cpu_target.next_to(model_cpu_arr[i - 1]							,  direction=__magic_name__							,  buff=0.0 )
																			self.add(__magic_name__ )
																			model_cpu_arr.append(__magic_name__ )

													self.add(*__magic_name__							,  *__magic_name__ )

													UpperCAmelCase_      :   Any      =	[meta_mem.copy() for i in range(6 )]
													UpperCAmelCase_      :   int      =	[meta_mem.copy() for i in range(6 )]
													UpperCAmelCase_      :   Optional[Any]      =	VGroup(*__magic_name__ ).arrange(__magic_name__							,  buff=0 )
													UpperCAmelCase_      :   Optional[int]      =	VGroup(*__magic_name__ ).arrange(__magic_name__							,  buff=0 )
													UpperCAmelCase_      :   Dict      =	VGroup(__magic_name__							,  __magic_name__ ).arrange(__magic_name__							,  buff=0 )
													UpperCAmelCase_      :   Optional[Any]      =	Text('''Disk'''							,  font_size=24 )
													UpperCAmelCase_      :   Any      =	Group(__magic_name__							,  __magic_name__ ).arrange(__magic_name__							,  buff=0.5							,  aligned_edge=__magic_name__ )
													disk.move_to([-4.0, -1.2_5, 0] )
													self.add(__magic_name__							,  __magic_name__ )

													UpperCAmelCase_      :   Optional[Any]      =	[]

													for i in range(6 ):
																			UpperCAmelCase_      :   Tuple      =	fill.copy().set_fill(__magic_name__							,  opacity=0.8 )
																			target.move_to(disk_left_col_base[i] ).scale(0.5 )
																			cpu_disk_arr.append(__magic_name__ )

													self.add(*__magic_name__ )

													UpperCAmelCase_      :   List[str]      =	Square(side_length=2.2 )
													key.move_to([-5, 2, 0] )

													UpperCAmelCase_      :   Union[str, Any]      =	MarkupText(
													    F"""<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model"""							,  font_size=18							,  )

													key_text.move_to([-5, 2.4, 0] )

													self.add(__magic_name__							,  __magic_name__ )

													UpperCAmelCase_      :   Union[str, Any]      =	MarkupText(
													    F"""<span fgcolor='{BLUE}'>●</span> Checkpoint"""							,  font_size=18							,  )

													blue_text.next_to(__magic_name__							,  DOWN * 2.4							,  aligned_edge=key_text.get_left() )
													self.add(__magic_name__ )

													UpperCAmelCase_      :   Dict      =	MarkupText(F"""The offloaded weights are all sent to the CPU."""							,  font_size=24 )
													step_a.move_to([2, 2, 0] )

													self.play(Write(__magic_name__							,  run_time=3 ) )

													for i in range(6 ):
																			UpperCAmelCase_      :   Dict      =	cpu_disk_arr[i]
																			UpperCAmelCase_      :   int      =	rect.copy().set_fill(__magic_name__							,  opacity=0.8 ).scale(2.0 )
																			cpa.generate_target()
																			cpa.target.move_to(model_base[i] )

																			if i == 0:
																									rect.set_fill(__magic_name__							,  opacity=0.8 )
																									rect.generate_target()
																									rect.target.move_to(cpu_left_col_base[0] ).scale(2.0 )

																									self.remove(
																									    *__magic_name__							,  *__magic_name__							,  )

																			else:
																									rect.generate_target()
																									rect.target.move_to(cpu_left_col_base[i] ).scale(2.0 )
																			self.play(MoveToTarget(__magic_name__ )							,  MoveToTarget(__magic_name__ )							,  model_base[i].animate.set_stroke(__magic_name__ ) )
													self.play(FadeOut(__magic_name__ ) )

													UpperCAmelCase_      :   int      =	MarkupText(
													    F"""Finally, hooks are added to each weight in the model\nto transfer the weights from CPU to GPU\n\t\tand back when needed."""							,  font_size=24							,  )
													step_a.move_to([2, 2, 0] )

													self.play(Write(__magic_name__							,  run_time=3 ) )

													UpperCAmelCase_      :   Union[str, Any]      =	[]
													UpperCAmelCase_      :   Tuple      =	[]
													for i in range(6 ):
																			UpperCAmelCase_      :   List[Any]      =	Arrow(start=__magic_name__							,  end=__magic_name__							,  color=__magic_name__							,  buff=0.5 )
																			a.next_to(model_base[i].get_left()							,  __magic_name__							,  buff=0.2 )
																			arrows.append(__magic_name__ )
																			animations.append(Write(__magic_name__ ) )
													self.play(*__magic_name__ )
													self.wait()





