





import argparse
import gc
import os
import sys
from pathlib import Path
from typing import List  # noqa: F401

import pytorch_lightning as pl
import torch
from finetune import SummarizationModule, TranslationModule
from finetune import main as ft_main
from make_student import create_student_by_copying_alternating_layers, get_layers_to_supervise
from torch import nn

from transformers import AutoModelForSeqaSeqLM, MBartTokenizer, TaForConditionalGeneration
from transformers.models.bart.modeling_bart import shift_tokens_right
from utils import calculate_bleu, check_output_dir, freeze_params, label_smoothed_nll_loss, use_task_specific_params


# need the parent dir module
sys.path.insert(2, str(Path(__file__).resolve().parents[1]))
from lightning_base import generic_train  # noqa


class 					__magic_name__  (							lowerCamelCase__							):





     """simple docstring"""



     __UpperCamelCase					    =     ['''loss''', '''ce_loss''', '''mlm_loss''', '''hid_loss_enc''', '''hid_loss_dec''']



     def __init__(							self       :Any			,      snake_case       :Tuple  ):





        '''simple docstring'''




        assert Path(hparams.data_dir  ).exists()
        A_					:				str          =			Path(hparams.output_dir  )
        self.output_dir.mkdir(exist_ok=snake_case  )

        A_					:				List[str]          =			self.output_dir.joinpath("student"  )

        A_					:				Dict          =			str(snake_case  )  # Tell lightning we are training the student
        A_					:				int          =			AutoModelForSeqaSeqLM.from_pretrained(hparams.teacher  ).eval()
        use_task_specific_params(snake_case			,      hparams.task  )  # We copy good generation parameters to student by default
        if hparams.student is not None:
           A_					:				Optional[Any]          =			AutoModelForSeqaSeqLM.from_pretrained(hparams.student  )
           use_task_specific_params(snake_case			,      hparams.task  )
           A_      ,						A_					:				Tuple          =			None, None
        else:
           A_      ,						A_      ,						A_					:				Optional[int]          =			create_student_by_copying_alternating_layers(
               snake_case			,      e=hparams.student_encoder_layers			,      d=hparams.student_decoder_layers			,      save_path=snake_case  )

        if hparams.length_penalty != -1:
           A_					:				List[Any]          =			hparams.length_penalty
        A_					:				str          =			hparams.teacher  # Use teacher's tokenizer
        super().__init__(snake_case			,      model=snake_case			,      config=student.config  )
        assert student.config.model_type == teacher.config.model_type, (
            f"teacher, student model types should be the same, got {student.config.model_type} !="
            f" {teacher.config.model_type}"
        )

        if student.config.model_type == "t5":
           A_					:				Any          =			len(student.get_encoder().block  )
           A_					:				Tuple          =			len(student.get_decoder().block  )
           A_					:				Any          =			len(teacher.get_encoder().block  )
           A_					:				Optional[int]          =			len(teacher.get_decoder().block  )
        else:
           A_					:				Tuple          =			student.config.encoder_layers
           A_					:				Dict          =			student.config.decoder_layers
           A_					:				Dict          =			teacher.config.encoder_layers
           A_					:				Optional[Any]          =			teacher.config.decoder_layers

        A_					:				List[Any]          =			not (hparams.student is None or hparams.teacher == hparams.student)
        A_					:				List[str]          =			(not self.different_base_models) and hparams.alpha_hid > 0
        A_					:				Dict          =			self.different_base_models or (student_encoder_layers != teacher_encoder_layers)
        # self.different_encoder determines whether we need to run the teacher encoder
        A_					:				List[Any]          =			teacher
        freeze_params(self.teacher  )

        if not self.different_encoder:  # To save RAM, delete teacher encoder and freeze student encoder.
           try:
              del self.teacher.model.encoder
           except AttributeError:  # T5
              del self.teacher.encoder

        if e_layer_ids is None:
           A_					:				Optional[Any]          =			list(range(snake_case  )  )
        if d_layer_ids is None:
           A_					:				List[Any]          =			list(range(snake_case  )  )

        A_      ,						A_					:				Optional[Any]          =			e_layer_ids, d_layer_ids  # type: List[int], List[int]

        if self.do_calc_hidden_loss:  # Intermediate supervision: Decide which layers to supervise
           if hparams.supervise_forward:
              A_					:				str          =			get_layers_to_supervise(
                  n_student=len(self.e_layer_ids  )			,      n_teacher=snake_case  )
              A_					:				Any          =			get_layers_to_supervise(
                  n_student=len(self.d_layer_ids  )			,      n_teacher=snake_case  )
           else:  # student layer should emulate hidden states of the teacher layer it was copied from
              A_					:				Optional[Any]          =			self.e_layer_ids
              A_					:				Optional[int]          =			self.d_layer_ids
        else:
           A_					:				str          =			None
           A_					:				Any          =			None

        A_					:				List[str]          =			nn.KLDivLoss(reduction="batchmean"  )
        A_					:				Optional[Any]          =			2.0
        A_					:				Union[str, Any]          =			hparams.alpha_mlm
        A_					:				Dict          =			hparams.alpha_ce
        A_					:				int          =			hparams.alpha_hid
        gc.collect()
        torch.cuda.empty_cache()



     def 						SCREAMING_SNAKE_CASE		(							self       :str			,      snake_case       :Union[str, Any]			,      snake_case       :Union[str, Any]			,      snake_case       :Optional[Any]  ):





        '''simple docstring'''




        A_					:				Optional[int]          =			mask[:, :, None].expand_as(snake_case  )
        A_					:				str          =			s_logits.size(-1  )
        A_					:				List[Any]          =			torch.masked_select(snake_case			,      snake_case  )  # (bs * seq_length * voc_size) modulo the 1s in mask
        A_					:				Optional[Any]          =			torch.masked_select(snake_case			,      snake_case  )  # (bs * seq_length * voc_size) modulo the 1s in mask
        A_					:				Any          =			s_logits_slct.view(-1			,      snake_case  )  # (bs * seq_length, voc_size) modulo the 1s in mask
        A_					:				int          =			t_logits_slct.view(-1			,      snake_case  )  # (bs * seq_length, voc_size) modulo the 1s in mask
        assert t_logits_slct.size() == s_logits_slct.size()
        A_					:				Tuple          =			(
            self.ce_loss_fct(
                nn.functional.log_softmax(s_logits_slct / self.temperature			,      dim=-1  )			,      nn.functional.softmax(t_logits_slct / self.temperature			,      dim=-1  )			,      )
            * (self.temperature) ** 2
        )
        return loss_ce



     @staticmethod
     def 						SCREAMING_SNAKE_CASE		(							snake_case       :Dict			,      snake_case       :str  ):





        '''simple docstring'''




        SummarizationModule.add_model_specific_args(snake_case			,      snake_case  )
        add_distill_args(snake_case  )
        return parser



     def 						SCREAMING_SNAKE_CASE		(							self       :Dict			,      snake_case       :dict  ):





        '''simple docstring'''




        A_					:				Tuple          =			self.tokenizer.pad_token_id
        A_      ,						A_      ,						A_					:				Union[str, Any]          =			batch["input_ids"], batch["attention_mask"], batch["labels"]
        if isinstance(self.model			,      snake_case  ):
           A_					:				Any          =			self.model._shift_right(snake_case  )
        else:
           A_					:				Optional[Any]          =			shift_tokens_right(snake_case			,      snake_case  )

        # noinspection PyCallingNonCallable
        A_					:				List[str]          =			self(
            snake_case			,      attention_mask=snake_case			,      decoder_input_ids=snake_case			,      output_hidden_states=self.do_calc_hidden_loss			,      output_attentions=snake_case			,      use_cache=snake_case			,      )
        A_					:				Optional[Any]          =			student_outputs["logits"]

        # Same cross entropy vs. label smoothing logic as finetune.py
        assert lm_logits.shape[-1] == self.model.config.vocab_size
        if self.hparams.label_smoothing == 0:
           # Same behavior as modeling_bart.py, besides ignoring pad_token_id
           A_					:				Dict          =			nn.CrossEntropyLoss(ignore_index=snake_case  )
           A_					:				Optional[Any]          =			loss_fct(lm_logits.view(-1			,      lm_logits.shape[-1]  )			,      labels.view(-1  )  )
        else:
           A_					:				Optional[Any]          =			nn.functional.log_softmax(snake_case			,      dim=-1  )
           A_      ,						A_					:				str          =			label_smoothed_nll_loss(
               snake_case			,      snake_case			,      self.hparams.label_smoothing			,      ignore_index=snake_case  )

        def zero_tensor():
           return torch.tensor(0.0  ).type_as(snake_case  )

        A_					:				List[Any]          =			student_outputs[
            "encoder_last_hidden_state"
        ]  # use this unless self.different_base_models
        A_      ,						A_					:				str          =			zero_tensor(), zero_tensor()
        if self.different_encoder:  # compute encoder hidden state loss
           A_					:				Any          =			self.teacher.get_encoder()(
               snake_case			,      attention_mask=snake_case			,      output_hidden_states=self.do_calc_hidden_loss			,      )
           if self.different_base_models:
              A_					:				Union[str, Any]          =			all_teacher_encoder_outputs["last_hidden_state"]
           elif self.do_calc_hidden_loss:
              A_					:				str          =			self.calc_hidden_loss(
                  snake_case			,      student_outputs["encoder_hidden_states"]			,      all_teacher_encoder_outputs["hidden_states"]			,      self.e_matches			,      normalize_hidden=self.hparams.normalize_hidden			,      )

        A_					:				Any          =			self.teacher(
            snake_case			,      attention_mask=snake_case			,      encoder_outputs=(teacher_enc_outputs,)			,      decoder_input_ids=snake_case			,      output_hidden_states=self.do_calc_hidden_loss			,      use_cache=snake_case			,      )
        A_					:				str          =			decoder_input_ids.ne(snake_case  )
        A_					:				int          =			self.calc_ce_loss(snake_case			,      snake_case			,      teacher_outputs["logits"]  )
        if self.do_calc_hidden_loss:  # Intermediate supervision of decoder hidden states
           A_					:				Optional[int]          =			self.calc_hidden_loss(
               snake_case			,      student_outputs["decoder_hidden_states"]			,      teacher_outputs["decoder_hidden_states"]			,      self.d_matches			,      normalize_hidden=self.hparams.normalize_hidden			,      )

        A_					:				Optional[Any]          =			(
            self.alpha_ce * loss_ce
            + self.alpha_mlm * student_lm_loss
            + self.hparams.alpha_hid * (hid_loss_enc + hid_loss_dec)
        )
        return blended_loss, loss_ce, student_lm_loss, hid_loss_enc, hid_loss_dec





     @staticmethod
     def 						SCREAMING_SNAKE_CASE		(							snake_case       :int			,      snake_case       :int			,      snake_case       :Dict			,      snake_case       :Dict			,      snake_case       :int  ):





        '''simple docstring'''




        A_					:				Optional[int]          =			"expected list or tuple for hidden_states, got tensor of shape: "
        assert not isinstance(snake_case			,      torch.Tensor  ), f"{msg}{hidden_states.shape}"
        assert not isinstance(snake_case			,      torch.Tensor  ), f"{msg}{hidden_states_T.shape}"
        A_					:				Optional[Any]          =			attention_mask.to(hidden_states[0]  )
        A_					:				Any          =			mask.sum() * hidden_states[0].size(-1  )
        A_					:				Tuple          =			torch.stack([hidden_states[i] for i in range(len(snake_case  )  )]  )
        A_					:				Any          =			torch.stack([hidden_states_T[j] for j in matches]  )
        assert student_states.shape == teacher_states.shape, f"{student_states.shape} != {teacher_states.shape}"
        if normalize_hidden:
           A_					:				str          =			nn.functional.layer_norm(snake_case			,      student_states.shape[1:]  )
           A_					:				Tuple          =			nn.functional.layer_norm(snake_case			,      teacher_states.shape[1:]  )
        A_					:				Dict          =			nn.functional.mse_loss(snake_case			,      snake_case			,      reduction="none"  )
        A_					:				str          =			(mse * mask.unsqueeze(0  ).unsqueeze(-1  )).sum() / valid_count
        return masked_mse




def      __snake_case						(					_lowerCAmelCase : Dict	) ->						str:
   # NOTE: if --student argument was specified and the teacher and student base models
   # are different, the models still have to have the same tokenizer, specified by
   # --tokenizer_name. So, for example, you can distill from t5_large to t5_small but not
   # from bart to t5. This s because if the tokenizers are different, the output space
   # for the two models is also different and their logits are not comparable.
   parser.add_argument("--teacher"				,				type=_lowerCAmelCase	)
   parser.add_argument("--alpha_ce"				,				default=0.8				,				type=_lowerCAmelCase	)
   parser.add_argument("--alpha_mlm"				,				default=0.2				,				type=_lowerCAmelCase	)
   parser.add_argument("--alpha_hid"				,				default=0.0				,				type=_lowerCAmelCase				,				required=_lowerCAmelCase	)
   parser.add_argument("--student"				,				type=_lowerCAmelCase				,				required=_lowerCAmelCase	)
   parser.add_argument("--student_decoder_layers"				,				default=12				,				type=_lowerCAmelCase				,				required=_lowerCAmelCase	)
   parser.add_argument("--student_encoder_layers"				,				default=12				,				type=_lowerCAmelCase				,				required=_lowerCAmelCase	)
   parser.add_argument("--no_teacher"				,				action="store_true"				,				default=_lowerCAmelCase	)
   parser.add_argument("--length_penalty"				,				type=_lowerCAmelCase				,				default=-1	)
   parser.add_argument("--supervise_forward"				,				action="store_true"				,				default=_lowerCAmelCase	)
   parser.add_argument("--normalize_hidden"				,				action="store_true"				,				default=_lowerCAmelCase	)


class 					__magic_name__  (							lowerCamelCase__							):





     """simple docstring"""



     __UpperCamelCase					    =     '''translation'''
     __UpperCamelCase					    =     ['''bleu''']
     __UpperCamelCase					    =     '''bleu'''



     def __init__(							self       :str			,      snake_case       :int			,      **snake_case       :Union[str, Any]  ):





        '''simple docstring'''




        super().__init__(snake_case			,      **snake_case  )
        assert hparams.src_lang is not None
        assert hparams.tgt_lang is not None
        A_					:				Dict          =			hparams.src_lang
        A_					:				List[Any]          =			hparams.tgt_lang
        if self.model.config.decoder_start_token_id is None and isinstance(self.tokenizer			,      snake_case  ):
           A_					:				List[Any]          =			self.tokenizer.lang_code_to_id[hparams.tgt_lang]



     def 						SCREAMING_SNAKE_CASE		(							self       :str			,      snake_case       :Union[str, Any]			,      snake_case       :Any  ):





        '''simple docstring'''




        return calculate_bleu(snake_case			,      snake_case  )





     @staticmethod
     def 						SCREAMING_SNAKE_CASE		(							snake_case       :str			,      snake_case       :Optional[int]  ):





        '''simple docstring'''




        TranslationModule.add_model_specific_args(snake_case			,      snake_case  )
        add_distill_args(snake_case  )
        return parser




def      __snake_case						(					_lowerCAmelCase : Dict	) ->						Union[str, Any]:
   if args.no_teacher:
      A_					:				List[Any]          =			TranslationModule if "translation" in args.task else SummarizationModule
   else:  # DISTILL WITH TEACHER
      A_					:				Optional[Any]          =			TranslationDistiller if "translation" in args.task else SummarizationDistiller
   A_					:				str          =			module_cls.__name__
   print(f"using module {args.setup_cls}"	)
   A_					:				str          =			module_cls(_lowerCAmelCase	)
   return model

def      __snake_case						(					_lowerCAmelCase : Optional[Any]	) ->						Union[str, Any]:
   Path(args.output_dir	).mkdir(exist_ok=_lowerCAmelCase	)
   check_output_dir(_lowerCAmelCase				,				expected_items=3	)

   A_					:				Union[str, Any]          =			create_module(_lowerCAmelCase	)
   return ft_main(_lowerCAmelCase				,				model=_lowerCAmelCase	)


if __name__ == "__main__":
 _lowerCAmelCase							:      List[str]						=	argparse.ArgumentParser()
 _lowerCAmelCase							:      Dict						=	pl.Trainer.add_argparse_args(parser)
 _lowerCAmelCase							:      Optional[int]						=	SummarizationDistiller.add_model_specific_args(parser, os.getcwd())
 _lowerCAmelCase							:      str						=	parser.parse_args()

 distill_main(args)







import argparse

import torch

from transformers import ChineseCLIPConfig, ChineseCLIPModel

def      __snake_case						(					_lowerCAmelCase : str				,				_lowerCAmelCase : Optional[int]				,				_lowerCAmelCase : Optional[Any]	) ->						List[str]:
   A_      ,						A_      ,						A_					:				Dict          =			pt_weights[f"{prefix}.in_proj_weight"].chunk(3				,				dim=0	)
   A_      ,						A_      ,						A_					:				Union[str, Any]          =			pt_weights[f"{prefix}.in_proj_bias"].chunk(3				,				dim=0	)

   A_					:				int          =			pt_weights[f"{prefix}.out_proj.weight"]
   A_					:				Dict          =			pt_weights[f"{prefix}.out_proj.bias"]

   A_					:				Optional[int]          =			q_proj
   A_					:				Optional[int]          =			q_proj_bias

   A_					:				Tuple          =			k_proj
   A_					:				str          =			k_proj_bias

   A_					:				Optional[int]          =			v_proj
   A_					:				int          =			v_proj_bias

   A_					:				int          =			out_proj_weights
   A_					:				List[Any]          =			out_proj_bias

def      __snake_case						(					_lowerCAmelCase : int				,				_lowerCAmelCase : Dict				,				_lowerCAmelCase : int	) ->						Dict:
   copy_linear(hf_mlp.fca				,				_lowerCAmelCase				,				f"{prefix}.c_fc"	)
   copy_linear(hf_mlp.fca				,				_lowerCAmelCase				,				f"{prefix}.c_proj"	)

def      __snake_case						(					_lowerCAmelCase : Tuple				,				_lowerCAmelCase : Optional[Any]				,				_lowerCAmelCase : Optional[int]	) ->						List[str]:
   A_					:				List[str]          =			pt_weights[f"{prefix}.weight"].data
   A_					:				int          =			pt_weights[f"{prefix}.bias"].data

def      __snake_case						(					_lowerCAmelCase : Dict				,				_lowerCAmelCase : str				,				_lowerCAmelCase : Optional[Any]	) ->						str:
   # copy layer norms
   copy_linear(hf_layer.layer_norma				,				_lowerCAmelCase				,				f"{prefix}.ln_1"	)
   copy_linear(hf_layer.layer_norma				,				_lowerCAmelCase				,				f"{prefix}.ln_2"	)

   # copy MLP
   copy_mlp(hf_layer.mlp				,				_lowerCAmelCase				,				f"{prefix}.mlp"	)

   # copy attn
   copy_attn_layer(hf_layer.self_attn				,				_lowerCAmelCase				,				f"{prefix}.attn"	)

def      __snake_case						(					_lowerCAmelCase : Optional[Any]				,				_lowerCAmelCase : int				,				_lowerCAmelCase : Optional[Any]	) ->						List[Any]:
   for layer_id, hf_layer in enumerate(_lowerCAmelCase	):
      copy_layer(_lowerCAmelCase				,				_lowerCAmelCase				,				f"{prefix}.{layer_id}"	)

def      __snake_case						(					_lowerCAmelCase : Union[str, Any]				,				_lowerCAmelCase : Any	) ->						Dict:
   # copy projection
   A_					:				Optional[Any]          =			pt_weights["text_projection"].data.T

   # copy text encoder
   for name, param in hf_model.text_model.named_parameters():
      A_					:				Any          =			pt_weights[f"bert.{name}"].data

def      __snake_case						(					_lowerCAmelCase : int				,				_lowerCAmelCase : Any	) ->						List[str]:
   # copy projection
   A_					:				Tuple          =			pt_weights["visual.proj"].data.T

   # copy layer norms
   copy_linear(hf_model.vision_model.pre_layrnorm				,				_lowerCAmelCase				,				"visual.ln_pre"	)
   copy_linear(hf_model.vision_model.post_layernorm				,				_lowerCAmelCase				,				"visual.ln_post"	)

   # copy embeddings
   A_					:				List[Any]          =			pt_weights["visual.conv1.weight"].data
   A_					:				Union[str, Any]          =			pt_weights["visual.class_embedding"].data
   A_					:				Tuple          =			pt_weights["visual.positional_embedding"].data

   # copy encoder
   copy_layers(hf_model.vision_model.encoder.layers				,				_lowerCAmelCase				,				"visual.transformer.resblocks"	)

@torch.no_grad()
def      __snake_case						(					_lowerCAmelCase : List[Any]				,				_lowerCAmelCase : int				,				_lowerCAmelCase : Optional[int]=None	) ->						str:
   assert config_path is not None, "Please specify the ChineseCLIP model config of the corresponding model size."
   A_					:				Optional[Any]          =			ChineseCLIPConfig.from_pretrained(_lowerCAmelCase	)

   A_					:				Tuple          =			ChineseCLIPModel(_lowerCAmelCase	).eval()

   A_					:				Any          =			torch.load(_lowerCAmelCase				,				map_location="cpu"	)["state_dict"]
   A_					:				Optional[Any]          =			{(name[7:] if name.startswith("module."	) else name): value for name, value in pt_weights.items()}

   copy_text_model_and_projection(_lowerCAmelCase				,				_lowerCAmelCase	)
   copy_vision_model_and_projection(_lowerCAmelCase				,				_lowerCAmelCase	)
   A_					:				List[Any]          =			pt_weights["logit_scale"].data

   hf_model.save_pretrained(_lowerCAmelCase	)


if __name__ == "__main__":
 _lowerCAmelCase							:      Optional[Any]						=	argparse.ArgumentParser()
 parser.add_argument(
     '''--pytorch_dump_folder_path''',
     default=None,
     type=str,
     help='''Path to the output folder storing converted hf PyTorch model.''',
 )
 parser.add_argument(
     '''--checkpoint_path''', default=None, type=str, help='''Path to original github format ChineseCLIP checkpoint.'''
 )
 parser.add_argument(
     '''--config_path''', default=None, required=True, type=str, help='''Path to hf config.json of model to convert.'''
 )
 _lowerCAmelCase							:      Tuple						=	parser.parse_args()

 convert_chinese_clip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
 print('''The conversion is finished!''')
