




import random
import sys

from . import cryptomath_module as cryptomath

UpperCamelCase__		 =		(
    R" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`"
    R"abcdefghijklmnopqrstuvwxyz{|}~"
)






def       snake_case      (							A		,     A		,     A    )							->							None:




	'''simple docstring'''


	if mode == "encrypt":
		if key_a == 1:
			sys.exit(
			    'The affine cipher becomes weak when key '
			    'A is set to 1. Choose different key'    )
		if key_b == 0:
			sys.exit(
			    'The affine cipher becomes weak when key '
			    'B is set to 0. Choose different key'    )
	if key_a < 0 or key_b < 0 or key_b > len(snake_case_    ) - 1:
		sys.exit(
		    'Key A must be greater than 0 and key B must '
		    f"be between 0 and {len(snake_case_    ) - 1}."    )
	if cryptomath.gcd(snake_case_		,     len(snake_case_    )    ) != 1:
		sys.exit(
		    f"Key A {key_a} and the symbol set size {len(snake_case_    )} "
		    'are not relatively prime. Choose a different key.'    )






def       snake_case      (							A		,     A    )							->							str:




	'''simple docstring'''


	lowerCamelCase_							:	Dict							     =							divmod(snake_case_		,     len(snake_case_    )    )
	check_keys(snake_case_		,     snake_case_		,     'encrypt'    )
	lowerCamelCase_							:	Any							     =							''''''
	for symbol in message:
		if symbol in SYMBOLS:
			lowerCamelCase_							:	Tuple							     =							SYMBOLS.find(snake_case_    )
			cipher_text += SYMBOLS[(sym_index * key_a + key_b) % len(snake_case_    )]
		else:
			cipher_text += symbol
	return cipher_text






def       snake_case      (							A		,     A    )							->							str:




	'''simple docstring'''


	lowerCamelCase_							:	Optional[int]							     =							divmod(snake_case_		,     len(snake_case_    )    )
	check_keys(snake_case_		,     snake_case_		,     'decrypt'    )
	lowerCamelCase_							:	Tuple							     =							''''''
	lowerCamelCase_							:	Tuple							     =							cryptomath.find_mod_inverse(snake_case_		,     len(snake_case_    )    )
	for symbol in message:
		if symbol in SYMBOLS:
			lowerCamelCase_							:	Dict							     =							SYMBOLS.find(snake_case_    )
			plain_text += SYMBOLS[
			    (sym_index - key_b) * mod_inverse_of_key_a % len(snake_case_    )
			]
		else:
			plain_text += symbol
	return plain_text






def       snake_case      (							)							->							int:




	'''simple docstring'''


	while True:
		lowerCamelCase_							:	Optional[int]							     =							random.randint(2		,     len(snake_case_    )    )
		lowerCamelCase_							:	Union[str, Any]							     =							random.randint(2		,     len(snake_case_    )    )
		if cryptomath.gcd(snake_case_		,     len(snake_case_    )    ) == 1 and key_b % len(snake_case_    ) != 0:
			return key_b * len(snake_case_    ) + key_b






def       snake_case      (							)							->							None:




	'''simple docstring'''


	lowerCamelCase_							:	int							     =							input('Enter message: '    ).strip()
	lowerCamelCase_							:	Tuple							     =							int(input('Enter key [2000 - 9000]: '    ).strip()    )
	lowerCamelCase_							:	Optional[int]							     =							input('Encrypt/Decrypt [E/D]: '    ).strip().lower()

	if mode.startswith('e'    ):
		lowerCamelCase_							:	Union[str, Any]							     =							'''encrypt'''
		lowerCamelCase_							:	List[Any]							     =							encrypt_message(snake_case_		,     snake_case_    )
	elif mode.startswith('d'    ):
		lowerCamelCase_							:	Dict							     =							'''decrypt'''
		lowerCamelCase_							:	Optional[int]							     =							decrypt_message(snake_case_		,     snake_case_    )
	print(f"\n{mode.title()}ed text: \n{translated}"    )


if __name__ == "__main__":
							import doctest

							doctest.testmod()
							# main()






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        __SCREAMING_SNAKE_CASE							(	lowerCamelCase						):
					_lowerCamelCase							=				["""loss""", """ce_loss""", """mlm_loss""", """hid_loss_enc""", """hid_loss_dec"""]

					def __init__(       self				, __lowercase      ):







						'''simple docstring'''




						assert Path(hparams.data_dir      ).exists()
						lowerCamelCase_							:	str							     =							Path(hparams.output_dir      )
						self.output_dir.mkdir(exist_ok=__lowercase      )

						lowerCamelCase_							:	Union[str, Any]							     =							self.output_dir.joinpath('student'      )

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

						if hparams.length_penalty != -1:
							lowerCamelCase_							:	Tuple							     =							hparams.length_penalty
						lowerCamelCase_							:	List[Any]							     =							hparams.teacher  # Use teacher's tokenizer
						super().__init__(__lowercase				, model=__lowercase				, 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":
							lowerCamelCase_							:	int							     =							len(student.get_encoder().block      )
							lowerCamelCase_							:	str							     =							len(student.get_decoder().block      )
							lowerCamelCase_							:	List[str]							     =							len(teacher.get_encoder().block      )
							lowerCamelCase_							:	Any							     =							len(teacher.get_decoder().block      )
						else:
							lowerCamelCase_							:	Union[str, Any]							     =							student.config.encoder_layers
							lowerCamelCase_							:	Optional[Any]							     =							student.config.decoder_layers
							lowerCamelCase_							:	str							     =							teacher.config.encoder_layers
							lowerCamelCase_							:	Tuple							     =							teacher.config.decoder_layers

						lowerCamelCase_							:	Tuple							     =							not (hparams.student is None or hparams.teacher == hparams.student)
						lowerCamelCase_							:	int							     =							(not self.different_base_models) and hparams.alpha_hid > 0
						lowerCamelCase_							:	Tuple							     =							self.different_base_models or (student_encoder_layers != teacher_encoder_layers)
						# self.different_encoder determines whether we need to run the teacher encoder
						lowerCamelCase_							:	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:
							lowerCamelCase_							:	Optional[Any]							     =							list(range(__lowercase      )      )
						if d_layer_ids is None:
							lowerCamelCase_							:	str							     =							list(range(__lowercase      )      )

						lowerCamelCase_     ,    lowerCamelCase_							:	int							     =							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:
								lowerCamelCase_							:	int							     =							get_layers_to_supervise(
								    n_student=len(self.e_layer_ids      )				, n_teacher=__lowercase      )
								lowerCamelCase_							:	str							     =							get_layers_to_supervise(
								    n_student=len(self.d_layer_ids      )				, n_teacher=__lowercase      )
							else:  # student layer should emulate hidden states of the teacher layer it was copied from
								lowerCamelCase_							:	Optional[Any]							     =							self.e_layer_ids
								lowerCamelCase_							:	Tuple							     =							self.d_layer_ids
						else:
							lowerCamelCase_							:	str							     =							None
							lowerCamelCase_							:	List[Any]							     =							None

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

					def 			lowercase_							(       self				, __lowercase				, __lowercase				, __lowercase      ):







						'''simple docstring'''




						lowerCamelCase_							:	List[str]							     =							mask[:, :, None].expand_as(__lowercase      )
						lowerCamelCase_							:	Tuple							     =							s_logits.size(-1      )
						lowerCamelCase_							:	List[Any]							     =							torch.masked_select(__lowercase				, __lowercase      )  # (bs * seq_length * voc_size) modulo the 1s in mask
						lowerCamelCase_							:	Tuple							     =							torch.masked_select(__lowercase				, __lowercase      )  # (bs * seq_length * voc_size) modulo the 1s in mask
						lowerCamelCase_							:	int							     =							s_logits_slct.view(-1				, __lowercase      )  # (bs * seq_length, voc_size) modulo the 1s in mask
						lowerCamelCase_							:	Any							     =							t_logits_slct.view(-1				, __lowercase      )  # (bs * seq_length, voc_size) modulo the 1s in mask
						assert t_logits_slct.size() == s_logits_slct.size()
						lowerCamelCase_							:	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 			lowercase_							(       __lowercase				, __lowercase      ):







						'''simple docstring'''




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

					def 			lowercase_							(       self				, __lowercase      ):







						'''simple docstring'''




						lowerCamelCase_							:	Dict							     =							self.tokenizer.pad_token_id
						lowerCamelCase_     ,    lowerCamelCase_     ,    lowerCamelCase_							:	List[Any]							     =							batch['input_ids'], batch['attention_mask'], batch['labels']
						if isinstance(self.model				, __lowercase      ):
							lowerCamelCase_							:	Optional[Any]							     =							self.model._shift_right(__lowercase      )
						else:
							lowerCamelCase_							:	Optional[Any]							     =							shift_tokens_right(__lowercase				, __lowercase      )

						# noinspection PyCallingNonCallable
						lowerCamelCase_							:	Optional[int]							     =							self(
						    __lowercase				, attention_mask=__lowercase				, decoder_input_ids=__lowercase				, output_hidden_states=self.do_calc_hidden_loss				, output_attentions=__lowercase				, use_cache=__lowercase				, )
						lowerCamelCase_							:	List[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
							lowerCamelCase_							:	int							     =							nn.CrossEntropyLoss(ignore_index=__lowercase      )
							lowerCamelCase_							:	List[Any]							     =							loss_fct(lm_logits.view(-1				, lm_logits.shape[-1]      )				, labels.view(-1      )      )
						else:
							lowerCamelCase_							:	List[Any]							     =							nn.functional.log_softmax(__lowercase				, dim=-1      )
							lowerCamelCase_     ,    lowerCamelCase_							:	Union[str, Any]							     =							label_smoothed_nll_loss(
							    __lowercase				, __lowercase				, self.hparams.label_smoothing				, ignore_index=__lowercase      )

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

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

						lowerCamelCase_							:	List[str]							     =							self.teacher(
						    __lowercase				, attention_mask=__lowercase				, encoder_outputs=(teacher_enc_outputs,)				, decoder_input_ids=__lowercase				, output_hidden_states=self.do_calc_hidden_loss				, use_cache=__lowercase				, )
						lowerCamelCase_							:	List[str]							     =							decoder_input_ids.ne(__lowercase      )
						lowerCamelCase_							:	Dict							     =							self.calc_ce_loss(__lowercase				, __lowercase				, teacher_outputs['logits']      )
						if self.do_calc_hidden_loss:  # Intermediate supervision of decoder hidden states
							lowerCamelCase_							:	Tuple							     =							self.calc_hidden_loss(
							    __lowercase				, student_outputs['decoder_hidden_states']				, teacher_outputs['decoder_hidden_states']				, self.d_matches				, normalize_hidden=self.hparams.normalize_hidden				, )

						lowerCamelCase_							:	Optional[int]							     =							(
						    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 			lowercase_							(       __lowercase				, __lowercase				, __lowercase				, __lowercase				, __lowercase      ):







						'''simple docstring'''




						lowerCamelCase_							:	Any							     =							'expected list or tuple for hidden_states, got tensor of shape: '
						assert not isinstance(__lowercase				, torch.Tensor      ), f"{msg}{hidden_states.shape}"
						assert not isinstance(__lowercase				, torch.Tensor      ), f"{msg}{hidden_states_T.shape}"
						lowerCamelCase_							:	int							     =							attention_mask.to(hidden_states[0]      )
						lowerCamelCase_							:	int							     =							mask.sum() * hidden_states[0].size(-1      )
						lowerCamelCase_							:	List[Any]							     =							torch.stack([hidden_states[i] for i in range(len(__lowercase      )      )]      )
						lowerCamelCase_							:	Optional[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:
							lowerCamelCase_							:	List[str]							     =							nn.functional.layer_norm(__lowercase				, student_states.shape[1:]      )
							lowerCamelCase_							:	Dict							     =							nn.functional.layer_norm(__lowercase				, teacher_states.shape[1:]      )
						lowerCamelCase_							:	Union[str, Any]							     =							nn.functional.mse_loss(__lowercase				, __lowercase				, reduction='none'      )
						lowerCamelCase_							:	Dict							     =							(mse * mask.unsqueeze(0      ).unsqueeze(-1      )).sum() / valid_count
						return masked_mse






def       snake_case      (							A    )							->							Optional[int]:




	'''simple docstring'''


	parser.add_argument('--teacher'		,     type=A    )
	parser.add_argument('--alpha_ce'		,     default=0.8		,     type=A    )
	parser.add_argument('--alpha_mlm'		,     default=0.2		,     type=A    )
	parser.add_argument('--alpha_hid'		,     default=0.0		,     type=A		,     required=A    )
	parser.add_argument('--student'		,     type=A		,     required=A    )
	parser.add_argument('--student_decoder_layers'		,     default=12		,     type=A		,     required=A    )
	parser.add_argument('--student_encoder_layers'		,     default=12		,     type=A		,     required=A    )
	parser.add_argument('--no_teacher'		,     action='store_true'		,     default=A    )
	parser.add_argument('--length_penalty'		,     type=A		,     default=-1    )
	parser.add_argument('--supervise_forward'		,     action='store_true'		,     default=A    )
	parser.add_argument('--normalize_hidden'		,     action='store_true'		,     default=A    )


class        __SCREAMING_SNAKE_CASE							(	lowerCamelCase						):
					_lowerCamelCase							=				"""translation"""
					_lowerCamelCase							=				["""bleu"""]
					_lowerCamelCase							=				"""bleu"""

					def __init__(       self				, __lowercase				, **__lowercase      ):







						'''simple docstring'''




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

					def 			lowercase_							(       self				, __lowercase				, __lowercase      ):







						'''simple docstring'''




						return calculate_bleu(__lowercase				, __lowercase      )





					@staticmethod
					def 			lowercase_							(       __lowercase				, __lowercase      ):







						'''simple docstring'''




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






def       snake_case      (							A    )							->							str:




	'''simple docstring'''


	if args.no_teacher:
		lowerCamelCase_							:	Optional[Any]							     =							TranslationModule if 'translation' in args.task else SummarizationModule
	else:  # DISTILL WITH TEACHER
		lowerCamelCase_							:	Dict							     =							TranslationDistiller if 'translation' in args.task else SummarizationDistiller
	lowerCamelCase_							:	str							     =							module_cls.__name__
	print(f"using module {args.setup_cls}"    )
	lowerCamelCase_							:	Dict							     =							module_cls(A    )
	return model






def       snake_case      (							A    )							->							str:




	'''simple docstring'''


	Path(args.output_dir    ).mkdir(exist_ok=A    )
	check_output_dir(A		,     expected_items=3    )

	lowerCamelCase_							:	str							     =							create_module(A    )
	return ft_main(A		,     model=A    )


if __name__ == "__main__":
							UpperCamelCase__  =		argparse.ArgumentParser()
							UpperCamelCase__  =		pl.Trainer.add_argparse_args(parser)
							UpperCamelCase__  =		SummarizationDistiller.add_model_specific_args(parser, os.getcwd())
							UpperCamelCase__  =		parser.parse_args()

							distill_main(args)
