


'''simple docstring'''


import warnings
from pathlib import Path
from typing import List, Tuple, Union

import fire
from torch import nn

from transformers import AutoModelForSeqaSeqLM, AutoTokenizer, PreTrainedModel
from transformers.utils import logging


UpperCAmelCase_		:   Dict							   =		logging.get_logger(__name__)







def 			snake_case_   (  SCREAMING_SNAKE_CASE__							,      SCREAMING_SNAKE_CASE__							,      SCREAMING_SNAKE_CASE__     ):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      nn.ModuleList([src_layers[i] for i in layers_to_copy]     )
				assert len(SCREAMING_SNAKE_CASE__     ) == len(SCREAMING_SNAKE_CASE__     ), f"""{len(SCREAMING_SNAKE_CASE__     )} != {len(SCREAMING_SNAKE_CASE__     )}"""
				dest_layers.load_state_dict(layers_to_copy.state_dict()     )


UpperCAmelCase_		:   Dict							   =		{
    # maps  num layers in teacher -> num_layers in student -> which teacher layers to copy.
    # 12: bart, 16: pegasus, 6: marian/Helsinki-NLP
    12: {
        1: [0],  # This says that if the teacher has 12 layers and the student has 1, copy layer 0 of the teacher
        2: [0, 6],
        3: [0, 6, 11],
        4: [0, 4, 8, 11],
        6: [0, 2, 4, 7, 9, 11],
        9: [0, 1, 2, 4, 5, 7, 9, 10, 11],
        12: list(range(12)),
    },
    16: {  # maps  num layers in student -> which teacher layers to copy
        1: [0],
        2: [0, 15],
        3: [0, 8, 15],
        4: [0, 5, 10, 15],
        6: [0, 3, 6, 9, 12, 15],
        8: [0, 2, 4, 6, 8, 10, 12, 15],
        9: [0, 1, 3, 5, 7, 9, 11, 13, 15],
        12: [0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15],
        16: list(range(16)),
    },
    6: {1: [0], 2: [0, 5], 3: [0, 2, 5], 4: [0, 1, 3, 5], 6: list(range(6))},
}
UpperCAmelCase_		:   List[str]							   =		{
    # maps  num layers in student -> which teacher layers to copy.
    6: {1: [5], 2: [3, 5], 3: [1, 4, 5], 4: [1, 2, 4, 5]},
    12: {1: [11], 2: [5, 11], 3: [3, 7, 11], 6: [1, 3, 5, 8, 10, 11]},
    16: {1: [15], 4: [4, 9, 12, 15], 8: [1, 3, 5, 7, 9, 11, 13, 15]},
}







def 			snake_case_   (  SCREAMING_SNAKE_CASE__							,      SCREAMING_SNAKE_CASE__     ):







				"""simple docstring"""





				try:
								_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      LAYERS_TO_COPY[n_teacher][n_student]
								return val
				except KeyError:
								if n_student != n_teacher:
												warnings.warn(
												    f"""no hardcoded layers to copy for teacher {n_teacher} -> student {n_student}, defaulting to first"""
												    f""" {n_student}"""     )
								return list(range(SCREAMING_SNAKE_CASE__     )     )







def 			snake_case_   (  SCREAMING_SNAKE_CASE__							,      SCREAMING_SNAKE_CASE__     ):







				"""simple docstring"""





				if n_student > n_teacher:
								raise ValueError(f"""Cannot perform intermediate supervision for student {n_student} > teacher {n_teacher}"""     )
				elif n_teacher == n_student:
								return list(range(SCREAMING_SNAKE_CASE__     )     )
				elif n_student == 1:
								return [n_teacher - 1]
				else:
								return LAYERS_TO_SUPERVISE[n_teacher][n_student]







def 			snake_case_   (  SCREAMING_SNAKE_CASE__							,      SCREAMING_SNAKE_CASE__ = "student"							,      SCREAMING_SNAKE_CASE__ = None							,      SCREAMING_SNAKE_CASE__ = None							,      SCREAMING_SNAKE_CASE__=False							,      SCREAMING_SNAKE_CASE__=None							,      SCREAMING_SNAKE_CASE__=None							,      **SCREAMING_SNAKE_CASE__							,      ):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE :       str     		=      """encoder_layers and decoder_layers cannot be both None-- you would just have an identical teacher."""
				assert (e is not None) or (d is not None), _msg
				if isinstance(SCREAMING_SNAKE_CASE__							,      SCREAMING_SNAKE_CASE__     ):
								AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__     ).save_pretrained(SCREAMING_SNAKE_CASE__     )  # purely for convenience
								_SCREAMING_SNAKE_CASE :       List[str]     		=      AutoModelForSeqaSeqLM.from_pretrained(SCREAMING_SNAKE_CASE__     ).eval()
				else:
								assert isinstance(SCREAMING_SNAKE_CASE__							,      SCREAMING_SNAKE_CASE__     ), f"""teacher must be a model or string got type {type(SCREAMING_SNAKE_CASE__     )}"""
				_SCREAMING_SNAKE_CASE :       Tuple     		=      teacher.config.to_diff_dict()

				try:
								_SCREAMING_SNAKE_CASE		,       _SCREAMING_SNAKE_CASE :       int     		=      teacher.config.encoder_layers, teacher.config.decoder_layers
								if e is None:
												_SCREAMING_SNAKE_CASE :       str     		=      teacher_e
								if d is None:
												_SCREAMING_SNAKE_CASE :       Tuple     		=      teacher_d
								init_kwargs.update({"""encoder_layers""": e, """decoder_layers""": d}     )
				except AttributeError:  # T5
								if hasattr(teacher.config							,      """num_encoder_layers"""     ):
												_SCREAMING_SNAKE_CASE		,       _SCREAMING_SNAKE_CASE :       List[Any]     		=      teacher.config.num_encoder_layers, teacher.config.num_decoder_layers
								else:
												_SCREAMING_SNAKE_CASE		,       _SCREAMING_SNAKE_CASE :       Any     		=      teacher.config.num_layers, teacher.config.num_decoder_layers
								if e is None:
												_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      teacher_e
								if d is None:
												_SCREAMING_SNAKE_CASE :       Optional[int]     		=      teacher_d
								if hasattr(teacher.config							,      """num_encoder_layers"""     ):
												init_kwargs.update({"""num_encoder_layers""": e, """num_decoder_layers""": d}     )
								else:
												init_kwargs.update({"""num_layers""": e, """num_decoder_layers""": d}     )

    # Kwargs to instantiate student: teacher kwargs with updated layer numbers + **extra_config_kwargs
				init_kwargs.update(SCREAMING_SNAKE_CASE__     )

				# Copy weights
				_SCREAMING_SNAKE_CASE :       List[str]     		=      teacher.config_class(**SCREAMING_SNAKE_CASE__     )
				_SCREAMING_SNAKE_CASE :       str     		=      AutoModelForSeqaSeqLM.from_config(SCREAMING_SNAKE_CASE__     )
				# Start by copying the full teacher state dict this will copy the first N teacher layers to the student.
				_SCREAMING_SNAKE_CASE :       int     		=      student.load_state_dict(teacher.state_dict()							,      strict=SCREAMING_SNAKE_CASE__     )
				assert info.missing_keys == [], info.missing_keys  # every student key should have a teacher keys.

				if copy_first_teacher_layers:  # Our copying is done. We just log and save
								_SCREAMING_SNAKE_CASE		,       _SCREAMING_SNAKE_CASE :       List[str]     		=      list(range(SCREAMING_SNAKE_CASE__     )     ), list(range(SCREAMING_SNAKE_CASE__     )     )
								logger.info(
								    f"""Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to"""
								    f""" {save_path}"""     )
								student.save_pretrained(SCREAMING_SNAKE_CASE__     )
								return student, e_layers_to_copy, d_layers_to_copy

				# Decide which layers of the teacher to copy. Not exactly alternating -- we try to keep first and last layer.
				if e_layers_to_copy is None:
								_SCREAMING_SNAKE_CASE :       List[int]     		=      pick_layers_to_copy(SCREAMING_SNAKE_CASE__							,      SCREAMING_SNAKE_CASE__     )
				if d_layers_to_copy is None:
								_SCREAMING_SNAKE_CASE :       List[int]     		=      pick_layers_to_copy(SCREAMING_SNAKE_CASE__							,      SCREAMING_SNAKE_CASE__     )

				try:
								if hasattr(
								    SCREAMING_SNAKE_CASE__							,      """prophetnet"""     ):  # For ProphetNet, student.model.encoder.layers is called student.prophetnet.encoder.layers
												copy_layers(teacher.prophetnet.encoder.layers							,      student.prophetnet.encoder.layers							,      SCREAMING_SNAKE_CASE__     )
												copy_layers(teacher.prophetnet.decoder.layers							,      student.prophetnet.decoder.layers							,      SCREAMING_SNAKE_CASE__     )
								else:
												copy_layers(teacher.model.encoder.layers							,      student.model.encoder.layers							,      SCREAMING_SNAKE_CASE__     )
												copy_layers(teacher.model.decoder.layers							,      student.model.decoder.layers							,      SCREAMING_SNAKE_CASE__     )
				except AttributeError:  # For t5, student.model.encoder.layers is called student.encoder.block
								copy_layers(teacher.encoder.block							,      student.encoder.block							,      SCREAMING_SNAKE_CASE__     )
								copy_layers(teacher.decoder.block							,      student.decoder.block							,      SCREAMING_SNAKE_CASE__     )
				logger.info(
				    f"""Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to {save_path}"""     )
				_SCREAMING_SNAKE_CASE :       Dict     		=      {
				    """teacher_type""": teacher.config.model_type,
				    """copied_encoder_layers""": e_layers_to_copy,
				    """copied_decoder_layers""": d_layers_to_copy,
				}
				student.save_pretrained(SCREAMING_SNAKE_CASE__     )
				# Save information about copying for easier reproducibility

				return student, e_layers_to_copy, d_layers_to_copy


if __name__ == "__main__":
				fire.Fire(create_student_by_copying_alternating_layers)








'''simple docstring'''


import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch

import numpy as np
import pytest
from absl.testing import parameterized

import datasets
from datasets import load_metric

from .utils import for_all_test_methods, local, slow


# mark all tests as integration
UpperCAmelCase_		:   Union[str, Any]							   =		pytest.mark.integration


UpperCAmelCase_		:   List[Any]							   =		{'comet'}
UpperCAmelCase_		:   int							   =		importlib.util.find_spec('fairseq') is not None

UpperCAmelCase_		:   Optional[Any]							   =		{'code_eval'}
UpperCAmelCase_		:   Optional[int]							   =		os.name == 'nt'

UpperCAmelCase_		:   Dict							   =		{'bertscore', 'frugalscore', 'perplexity'}
UpperCAmelCase_		:   Dict							   =		importlib.util.find_spec('transformers') is not None







def 			snake_case_   (  SCREAMING_SNAKE_CASE__     ):







				"""simple docstring"""





				@wraps(SCREAMING_SNAKE_CASE__     )
				def wrapper(self							,      SCREAMING_SNAKE_CASE__     ):
								if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
												self.skipTest("""\"test requires Fairseq\""""     )
								else:
												test_case(self							,      SCREAMING_SNAKE_CASE__     )

				return wrapper







def 			snake_case_   (  SCREAMING_SNAKE_CASE__     ):







				"""simple docstring"""





				@wraps(SCREAMING_SNAKE_CASE__     )
				def wrapper(self							,      SCREAMING_SNAKE_CASE__     ):
								if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
												self.skipTest("""\"test requires transformers\""""     )
								else:
												test_case(self							,      SCREAMING_SNAKE_CASE__     )

				return wrapper







def 			snake_case_   (  SCREAMING_SNAKE_CASE__     ):







				"""simple docstring"""





				@wraps(SCREAMING_SNAKE_CASE__     )
				def wrapper(self							,      SCREAMING_SNAKE_CASE__     ):
								if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
												self.skipTest("""\"test not supported on Windows\""""     )
								else:
												test_case(self							,      SCREAMING_SNAKE_CASE__     )

				return wrapper







def 			snake_case_   (  ):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE :       Dict     		=      [metric_dir.split(os.sep     )[-2] for metric_dir in glob.glob("""./metrics/*/"""     )]
				return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"]  # gleu is unfinished





@parameterized.named_parameters(get_local_metric_names()					)
@for_all_test_methods(
    _snake_case     ,     _snake_case     ,     _snake_case					)
@local
class     lowercase__  (						parameterized.TestCase					):





							'''simple docstring'''


							A_							:      Optional[int]      	=  {}
							A_							:      Union[str, Any]      	=  None






							@pytest.mark.filterwarnings("""ignore:metric_module_factory is deprecated:FutureWarning"""  )
							@pytest.mark.filterwarnings("""ignore:load_metric is deprecated:FutureWarning"""  )
							def UpperCAmelCase_	(    self    ,					__snake_case  ):
											_SCREAMING_SNAKE_CASE :       str     		=      """[...]"""
											_SCREAMING_SNAKE_CASE :       Any     		=      importlib.import_module(
											    datasets.load.metric_module_factory(os.path.join("""metrics"""    ,					__snake_case  )  ).module_path  )
											_SCREAMING_SNAKE_CASE :       Optional[int]     		=      datasets.load.import_main_class(metric_module.__name__    ,					dataset=__snake_case  )
											# check parameters
											_SCREAMING_SNAKE_CASE :       Tuple     		=      inspect.signature(metric._compute  ).parameters
											self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values()  )  )  # no **kwargs
											# run doctest
											with self.patch_intensive_calls(__snake_case    ,					metric_module.__name__  ):
															with self.use_local_metrics():
																			try:
																							_SCREAMING_SNAKE_CASE :       int     		=      doctest.testmod(__snake_case    ,					verbose=__snake_case    ,					raise_on_error=__snake_case  )
																			except doctest.UnexpectedException as e:
																							raise e.exc_info[1]  # raise the exception that doctest caught
											self.assertEqual(results.failed    ,					0  )
											self.assertGreater(results.attempted    ,					1  )






							@slow
							def UpperCAmelCase_	(    self    ,					__snake_case  ):
											_SCREAMING_SNAKE_CASE :       List[Any]     		=      """[...]"""
											_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      importlib.import_module(
											    datasets.load.metric_module_factory(os.path.join("""metrics"""    ,					__snake_case  )  ).module_path  )
											# run doctest
											with self.use_local_metrics():
															_SCREAMING_SNAKE_CASE :       List[str]     		=      doctest.testmod(__snake_case    ,					verbose=__snake_case    ,					raise_on_error=__snake_case  )
											self.assertEqual(results.failed    ,					0  )
											self.assertGreater(results.attempted    ,					1  )






							@contextmanager
							def UpperCAmelCase_	(    self    ,					__snake_case    ,					__snake_case  ):
											if metric_name in self.INTENSIVE_CALLS_PATCHER:
															with self.INTENSIVE_CALLS_PATCHER[metric_name](__snake_case  ):
																			yield
											else:
															yield






							@contextmanager
							def UpperCAmelCase_	(    self  ):
											def load_local_metric(__snake_case    ,					*__snake_case    ,					**__snake_case  ):
															return load_metric(os.path.join("""metrics"""    ,					__snake_case  )    ,					*__snake_case    ,					**__snake_case  )

											with patch("""datasets.load_metric"""  ) as mock_load_metric:
															_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      load_local_metric
															yield






							@classmethod
							def UpperCAmelCase_	(    cls    ,					__snake_case  ):
											def wrapper(__snake_case  ):
															_SCREAMING_SNAKE_CASE :       Any     		=      contextmanager(__snake_case  )
															_SCREAMING_SNAKE_CASE :       int     		=      patcher
															return patcher

											return wrapper







@LocalMetricTest.register_intensive_calls_patcher("""bleurt"""     )
def 			snake_case_   (  SCREAMING_SNAKE_CASE__     ):







				"""simple docstring"""





				import tensorflow.compat.va as tf
				from bleurt.score import Predictor

				tf.flags.DEFINE_string("""sv"""							,      """"""							,      """"""     )  # handle pytest cli flags





				class     lowercase__  (						_snake_case					):





											'''simple docstring'''


											def UpperCAmelCase_	(    self    ,					__snake_case  ):
															assert len(input_dict["""input_ids"""]  ) == 2
															return np.array([1.03, 1.04]  )

    # mock predict_fn which is supposed to do a forward pass with a bleurt model
				with patch("""bleurt.score._create_predictor"""     ) as mock_create_predictor:
								_SCREAMING_SNAKE_CASE :       Any     		=      MockedPredictor()
								yield







@LocalMetricTest.register_intensive_calls_patcher("""bertscore"""     )
def 			snake_case_   (  SCREAMING_SNAKE_CASE__     ):







				"""simple docstring"""





				import torch

				def bert_cos_score_idf(SCREAMING_SNAKE_CASE__							,      SCREAMING_SNAKE_CASE__							,      *SCREAMING_SNAKE_CASE__							,      **SCREAMING_SNAKE_CASE__     ):
								return torch.tensor([[1.0, 1.0, 1.0]] * len(SCREAMING_SNAKE_CASE__     )     )

				# mock get_model which is supposed to do download a bert model
				# mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
				with patch("""bert_score.scorer.get_model"""     ), patch(
				    """bert_score.scorer.bert_cos_score_idf"""     ) as mock_bert_cos_score_idf:
								_SCREAMING_SNAKE_CASE :       Any     		=      bert_cos_score_idf
								yield







@LocalMetricTest.register_intensive_calls_patcher("""comet"""     )
def 			snake_case_   (  SCREAMING_SNAKE_CASE__     ):







				"""simple docstring"""





				def load_from_checkpoint(SCREAMING_SNAKE_CASE__     ):





								class     lowercase__  :





															'''simple docstring'''


															def UpperCAmelCase_	(    self    ,					__snake_case    ,					*__snake_case    ,					**__snake_case  ):
																			assert len(__snake_case  ) == 2
																			_SCREAMING_SNAKE_CASE :       Dict     		=      [0.19, 0.92]
																			return scores, sum(__snake_case  ) / len(__snake_case  )



								return Model()

				# mock load_from_checkpoint which is supposed to do download a bert model
				# mock load_from_checkpoint which is supposed to do download a bert model
				with patch("""comet.download_model"""     ) as mock_download_model:
								_SCREAMING_SNAKE_CASE :       Any     		=      None
								with patch("""comet.load_from_checkpoint"""     ) as mock_load_from_checkpoint:
												_SCREAMING_SNAKE_CASE :       List[str]     		=      load_from_checkpoint
												yield







def 			snake_case_   (  ):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      load_metric(os.path.join("""metrics"""							,      """seqeval"""     )     )
				_SCREAMING_SNAKE_CASE :       List[str]     		=      """ERROR"""
				_SCREAMING_SNAKE_CASE :       Tuple     		=      f"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}"""
				with pytest.raises(SCREAMING_SNAKE_CASE__							,      match=re.escape(SCREAMING_SNAKE_CASE__     )     ):
								metric.compute(predictions=[]							,      references=[]							,      scheme=SCREAMING_SNAKE_CASE__     )




