





from manim import *





class  A__    (							__UpperCAmelCase	):




   """simple docstring"""



   def 							__lowercase		(					self)			->						Tuple:







          '''simple docstring'''

          a__						:	List[Any] =				Rectangle(height=0.5					,  width=0.5)
          a__						:	str =				Rectangle(height=0.46					,  width=0.46).set_stroke(width=0)

          a__						:	Any =				Rectangle(height=0.25					,  width=0.25)

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

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

          a__						:	Any =				[mem.copy() for i in range(6)]
          a__						:	List[str] =				VGroup(*lowercase).arrange(lowercase					,  buff=0)

          a__						:	int =				Text('Model'					,  font_size=24)
          a__						:	List[Any] =				Group(lowercase					,  lowercase).arrange(lowercase					,  buff=0.5					,  aligned_edge=lowercase)
          model.move_to([3, -1.0, 0])
          self.add(lowercase)

          a__						:	Dict =				[]
          a__						:	str =				[]

          for i, rect in enumerate(lowercase):
                 a__						:	Tuple =				fill.copy().set_fill(lowercase					,  opacity=0.8)
                 target.move_to(lowercase)
                 model_arr.append(lowercase)

                 a__						:	int =				Rectangle(height=0.46					,  width=0.46).set_stroke(width=0.0).set_fill(lowercase					,  opacity=0.8)
                 cpu_target.move_to(cpu_left_col_base[i])
                 model_cpu_arr.append(lowercase)

          self.add(*lowercase					,  *lowercase)

          a__						:	Dict =				[meta_mem.copy() for i in range(6)]
          a__						:	List[Any] =				[meta_mem.copy() for i in range(6)]
          a__						:	Union[str, Any] =				VGroup(*lowercase).arrange(lowercase					,  buff=0)
          a__						:	Dict =				VGroup(*lowercase).arrange(lowercase					,  buff=0)
          a__						:	List[Any] =				VGroup(lowercase					,  lowercase).arrange(lowercase					,  buff=0)
          a__						:	Dict =				Text('Disk'					,  font_size=24)
          a__						:	Optional[int] =				Group(lowercase					,  lowercase).arrange(lowercase					,  buff=0.5					,  aligned_edge=lowercase)
          disk.move_to([-4, -1.25, 0])
          self.add(lowercase					,  lowercase)

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

          a__						:	List[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(lowercase					,  lowercase)

          a__						:	Dict =				MarkupText(
              F'<span fgcolor=\'{BLUE}\'>●</span> Checkpoint'					,  font_size=18					,  )

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

          a__						:	Dict =				MarkupText(
              F'Now watch as an input is passed through the model\nand how the memory is utilized and handled.'					,  font_size=24					,  )
          step_a.move_to([2, 2, 0])

          self.play(Write(lowercase))

          a__						:	int =				Square(0.3)
          input.set_fill(lowercase					,  opacity=1.0)
          input.set_stroke(width=0.0)
          input.next_to(model_base[0]					,  lowercase					,  buff=0.5)

          self.play(Write(lowercase))

          input.generate_target()
          input.target.next_to(model_arr[0]					,  direction=lowercase					,  buff=0.02)
          self.play(MoveToTarget(lowercase))

          self.play(FadeOut(lowercase))

          a__						:	str =				Arrow(start=lowercase					,  end=lowercase					,  color=lowercase					,  buff=0.5)
          a.next_to(model_arr[0].get_left()					,  lowercase					,  buff=0.2)

          model_cpu_arr[0].generate_target()
          model_cpu_arr[0].target.move_to(gpu_rect[0])

          a__						:	Union[str, Any] =				MarkupText(
              F'As the input reaches a layer, the hook triggers\nand weights are moved from the CPU\nto the GPU and back.'					,  font_size=24					,  )
          step_a.move_to([2, 2, 0])

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

          a__						:	Union[str, Any] =				{'run_time': 1, 'fade_in': True, 'fade_out': True, 'buff': 0.02}

          self.play(
              Write(lowercase)					,  Circumscribe(model_arr[0]					,  color=lowercase					,  **lowercase)					,  Circumscribe(model_cpu_arr[0]					,  color=lowercase					,  **lowercase)					,  Circumscribe(gpu_rect[0]					,  color=lowercase					,  **lowercase)					,  )
          self.play(MoveToTarget(model_cpu_arr[0]))

          a__						:	List[Any] =				a.copy()
          for i in range(6):
                 a_c.next_to(model_arr[i].get_right() + 0.02					,  lowercase					,  buff=0.2)

                 input.generate_target()
                 input.target.move_to(model_arr[i].get_right() + 0.02)

                 a__						:	Any =				AnimationGroup(
                     FadeOut(lowercase					,  run_time=0.5)					,  MoveToTarget(lowercase					,  run_time=0.5)					,  FadeIn(lowercase					,  run_time=0.5)					,  lag_ratio=0.2)

                 self.play(lowercase)

                 model_cpu_arr[i].generate_target()
                 model_cpu_arr[i].target.move_to(cpu_left_col_base[i])

                 if i < 5:
                        model_cpu_arr[i + 1].generate_target()
                        model_cpu_arr[i + 1].target.move_to(gpu_rect[0])
                        if i >= 1:
                               a__						:	Tuple =				0.7

                        self.play(
                            Circumscribe(model_arr[i]					,  **lowercase)					,  Circumscribe(cpu_left_col_base[i]					,  **lowercase)					,  Circumscribe(cpu_left_col_base[i + 1]					,  color=lowercase					,  **lowercase)					,  Circumscribe(gpu_rect[0]					,  color=lowercase					,  **lowercase)					,  Circumscribe(model_arr[i + 1]					,  color=lowercase					,  **lowercase)					,  )
                        if i < 1:
                               self.play(
                                   MoveToTarget(model_cpu_arr[i])					,  MoveToTarget(model_cpu_arr[i + 1])					,  )
                        else:
                               self.play(
                                   MoveToTarget(model_cpu_arr[i]					,  run_time=0.7)					,  MoveToTarget(model_cpu_arr[i + 1]					,  run_time=0.7)					,  )
                 else:
                        model_cpu_arr[i].generate_target()
                        model_cpu_arr[i].target.move_to(cpu_left_col_base[-1])
                        input.generate_target()
                        input.target.next_to(model_arr[-1].get_right()					,  RIGHT + 0.02					,  buff=0.2)

                        self.play(
                            Circumscribe(model_arr[-1]					,  color=lowercase					,  **lowercase)					,  Circumscribe(cpu_left_col_base[-1]					,  color=lowercase					,  **lowercase)					,  Circumscribe(gpu_rect[0]					,  color=lowercase					,  **lowercase)					,  )

                        self.play(MoveToTarget(model_cpu_arr[i]))

                 a__						:	Optional[int] =				a_c
                 a__						:	str =				a_c.copy()

          input.generate_target()
          input.target.next_to(model_base[-1]					,  RIGHT + 0.02					,  buff=0.5)
          self.play(
              FadeOut(lowercase)					,  FadeOut(lowercase					,  run_time=0.5)					,  )

          a__						:	List[Any] =				MarkupText(F'Inference on a model too large for GPU memory\nis successfully completed.'					,  font_size=24)
          step_a.move_to([2, 2, 0])

          self.play(Write(lowercase					,  run_time=3)					,  MoveToTarget(lowercase))

          self.wait()





'''simple docstring'''






import argparse

import fairseq
import torch

from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging


logging.set_verbosity_info()
lowerCAmelCase__											=	logging.get_logger(__name__)

lowerCAmelCase__											=	{
    '''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''',
    '''encoder.layer_norm_for_extract''': '''layer_norm_for_extract''',
    '''w2v_model.layer_norm''': '''feature_projection.layer_norm''',
    '''quantizer.weight_proj''': '''quantizer.weight_proj''',
    '''quantizer.vars''': '''quantizer.codevectors''',
    '''project_q''': '''project_q''',
    '''final_proj''': '''project_hid''',
    '''w2v_encoder.proj''': '''lm_head''',
    '''label_embs_concat''': '''label_embeddings_concat''',
    '''mask_emb''': '''masked_spec_embed''',
    '''spk_proj''': '''speaker_proj''',
}
lowerCAmelCase__											=	[
    '''lm_head''',
    '''quantizer.weight_proj''',
    '''quantizer.codevectors''',
    '''project_q''',
    '''project_hid''',
    '''label_embeddings_concat''',
    '''speaker_proj''',
    '''layer_norm_for_extract''',
]


def 		_A     (    A__     ,				A__     ,				A__     ,				A__     ,				A__      ):






 """simple docstring"""



 for attribute in key.split('''.'''      ):
  __lowercase							  = getattr(A__     ,				A__      )

 if weight_type is not None:
  __lowercase							  = getattr(A__     ,				A__      ).shape
 else:
  __lowercase							  = hf_pointer.shape

 if hf_shape != value.shape:
  raise ValueError(
      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     (    A__     ,				A__      ):






 """simple docstring"""



 __lowercase							  = []
 __lowercase							  = fairseq_model.state_dict()

 __lowercase							  = hf_model.unispeech_sat.feature_extractor

 for name, value in fairseq_dict.items():
  __lowercase							  = False
  if "conv_layers" in name:
   load_conv_layer(
       A__     ,				A__     ,				A__     ,				A__     ,				hf_model.config.feat_extract_norm == '''group'''     ,				)
   __lowercase							  = True
  else:
   for key, mapped_key in MAPPING.items():
    __lowercase							  = '''unispeech_sat.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
    if key in name or key.split('''w2v_model.'''      )[-1] == name.split('''.'''      )[0]:
     if "layer_norm_for_extract" in name and (".".join(name.split('''.'''      )[:-1]      ) != key):
      # special case since naming is very similar
      continue
     __lowercase							  = True
     if "*" in mapped_key:
      __lowercase							  = name.split(A__      )[0].split('''.'''      )[-2]
      __lowercase							  = mapped_key.replace('''*'''     ,				A__      )
     if "weight_g" in name:
      __lowercase							  = '''weight_g'''
     elif "weight_v" in name:
      __lowercase							  = '''weight_v'''
     elif "bias" in name:
      __lowercase							  = '''bias'''
     elif "weight" in name:
      # TODO: don't match quantizer.weight_proj
      __lowercase							  = '''weight'''
     else:
      __lowercase							  = None
     set_recursively(A__     ,				A__     ,				A__     ,				A__     ,				A__      )
    continue
  if not is_used:
   unused_weights.append(A__      )

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


def 		_A     (    A__     ,				A__     ,				A__     ,				A__     ,				A__      ):






 """simple docstring"""



 __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:
   if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape:
    raise ValueError(
        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:
   if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape:
    raise ValueError(
        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:
   if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:
    raise ValueError(
        F"{full_name} has size {value.shape}, but"
        F" {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:
   if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
    raise ValueError(
        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(A__      )


@torch.no_grad()
def 		_A     (    A__     ,				A__     ,				A__=None     ,				A__=None     ,				A__=True      ):






 """simple docstring"""



 if config_path is not None:
  __lowercase							  = UniSpeechSatConfig.from_pretrained(A__      )
 else:
  __lowercase							  = UniSpeechSatConfig()

 __lowercase							  = ''''''

 if is_finetuned:
  __lowercase							  = UniSpeechSatForCTC(A__      )
 else:
  __lowercase							  = UniSpeechSatForPreTraining(A__      )

 __lowercase  ,	__lowercase  ,	__lowercase							  = fairseq.checkpoint_utils.load_model_ensemble_and_task(
     [checkpoint_path]     ,				arg_overrides={'''data''': '''/'''.join(dict_path.split('''/'''      )[:-1]      )}      )
 __lowercase							  = model[0].eval()

 recursively_load_weights(A__     ,				A__      )

 hf_wavavec.save_pretrained(A__      )


if __name__ == "__main__":
 lowerCAmelCase__											=	argparse.ArgumentParser()
 parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
 parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''')
 parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''')
 parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''')
 parser.add_argument(
     '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not'''
 )
 lowerCAmelCase__											=	parser.parse_args()
 convert_unispeech_sat_checkpoint(
     args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
 )

