



import torch.nn as nn

from .imports import is_fpa_available


if is_fpa_available():
		import transformer_engine.pytorch as te





def 						__lowerCamelCase       (      __magic_name__	:  List[str]     , __magic_name__	:  List[Any]=True     , __magic_name__	:  List[Any]=True     , __magic_name__	:  str=True						):
							if not is_fpa_available():
														raise ImportError("Using `convert_model` requires transformer_engine to be installed."						)
							for name, module in model.named_children():
														if isinstance(__magic_name__     , nn.Linear						) and to_transformer_engine and _convert_linear:
																					# Return early if the linear layer weights are not multiples of 16
																					if any(p % 16 != 0 for p in module.weight.shape						):
																												return
																					a__:       List[str]											=module.bias is not None
																					a__:       int											=te.Linear(
																					    module.in_features     , module.out_features     , bias=__magic_name__     , params_dtype=module.weight.dtype						)
																					a__:       Any											=module.weight.data.clone()
																					if has_bias:
																												a__:       Tuple											=module.bias.data.clone()

																					setattr(__magic_name__     , __magic_name__     , __magic_name__						)
														elif isinstance(__magic_name__     , nn.LayerNorm						) and to_transformer_engine and _convert_ln:
																					a__:       Optional[int]											=te.LayerNorm(module.normalized_shape[0]     , eps=module.eps     , params_dtype=module.weight.dtype						)
																					a__:       Dict											=module.weight.data.clone()
																					a__:       Optional[int]											=module.bias.data.clone()

																					setattr(__magic_name__     , __magic_name__     , __magic_name__						)
														elif isinstance(__magic_name__     , te.Linear						) and not to_transformer_engine and _convert_linear:
																					a__:       Any											=module.bias is not None
																					a__:       int											=nn.Linear(
																					    module.in_features     , module.out_features     , bias=__magic_name__     , params_dtype=module.weight.dtype						)
																					a__:       Any											=module.weight.data.clone()
																					if has_bias:
																												a__:       int											=module.bias.data.clone()

																					setattr(__magic_name__     , __magic_name__     , __magic_name__						)
														elif isinstance(__magic_name__     , te.LayerNorm						) and not to_transformer_engine and _convert_ln:
																					a__:       Tuple											=nn.LayerNorm(module.normalized_shape[0]     , eps=module.eps     , params_dtype=module.weight.dtype						)
																					a__:       Dict											=module.weight.data.clone()
																					a__:       Dict											=module.bias.data.clone()

																					setattr(__magic_name__     , __magic_name__     , __magic_name__						)
														else:
																					convert_model(
																					    __magic_name__     , to_transformer_engine=__magic_name__     , _convert_linear=_convert_linear     , _convert_ln=_convert_ln     , )







def 						__lowerCamelCase       (      __magic_name__	:  Dict						):
							if not is_fpa_available():
														raise ImportError("Using `has_transformer_engine_layers` requires transformer_engine to be installed."						)
							for m in model.modules():
														if isinstance(__magic_name__     , (te.LayerNorm, te.Linear)						):
																					return True
							return False










# This test is meant to be run in on an instance with TPUs like this:
#
#   python examples/pytorch/xla_spawn.py --num_cores=8 tests/test_trainer_tpu.py
#
# Replace 8 with the number of TPU cores you have.
#

import sys
from typing import Dict

from transformers import EvalPrediction, HfArgumentParser, TrainingArguments, is_torch_available
from transformers.utils import logging


__UpperCAmelCase						  =     logging.get_logger(__name__)


if is_torch_available():
		import torch
		from torch import nn
		from torch.utils.data import Dataset

		from transformers import Trainer


		class 	lowerCamelCase__ (		_a   ):


								def __init__( self						:  Any      ,       _a						:  int = 1_0_1			):
															a__:       Dict											=length


								def __len__( self						:  Optional[Any]			):
															return self.length







								def __getitem__( self						:  Dict      ,       _a						:  int			):
															return i


		class 	lowerCamelCase__ :


								def __call__( self						:  Any      ,       _a						:  List[str]			):
															return {"input_ids": torch.tensor(_a			), "labels": torch.tensor(_a			)}


		class 	lowerCamelCase__ (		nn.Module   ):


								def __init__( self						:  Tuple			):
															super().__init__()
															# Add some (unused) params otherwise DDP will complain.
															a__:       int											=nn.Linear(1_2_0      ,       8_0			)







								def   _lowerCamelCase			( self						:  str      ,       _a						:  List[Any]      ,       _a						:  List[str]=None			):
															if labels is not None:
																						return torch.tensor(0.0      ,       device=input_ids.device			), input_ids
															else:
																						return input_ids





def 						__lowerCamelCase       (      ):
							a__:       List[str]											=HfArgumentParser((TrainingArguments,)						)
							sys.argv += ["--output_dir", "./examples"]
							a__:       int											=parser.parse_args_into_dataclasses()[0]

							logger.warning(
							    F"Process rank: {training_args.local_rank}, device: {training_args.device}, "
							    F"tpu_num_cores: {training_args.tpu_num_cores}"     , )

							# Essentially, what we want to verify in the distributed case is
							# that we get all samples back, in the right order.
							# (this is crucial for prediction for instance)
							for dataset_length in [1_001, 256, 15]:
														a__:       Optional[Any]											=DummyDataset(__magic_name__						)

														def compute_metrics(__magic_name__	:  EvalPrediction						) -> Dict:
																					a__:       List[str]											=list(range(len(__magic_name__						)						)						)
																					a__:       Union[str, Any]											=p.predictions.tolist() == sequential and p.label_ids.tolist() == sequential
																					return {"success": success}

														a__:       Union[str, Any]											=Trainer(
														    model=DummyModel()     , args=__magic_name__     , data_collator=DummyDataCollator()     , eval_dataset=__magic_name__     , compute_metrics=__magic_name__     , )
														a__:       str											=trainer.evaluate()
														logger.info(__magic_name__						)
														if metrics["eval_success"] is not True:
																					logger.error(__magic_name__						)
																					exit(1						)

														a__:       List[str]											=trainer.predict(__magic_name__						)
														logger.info(p.metrics						)
														if p.metrics["test_success"] is not True:
																					logger.error(p.metrics						)
																					exit(1						)

														a__:       Tuple											=2

														a__:       Optional[int]											=trainer.evaluate()
														logger.info(__magic_name__						)
														if metrics["eval_success"] is not True:
																					logger.error(__magic_name__						)
																					exit(1						)

														a__:       List[str]											=trainer.predict(__magic_name__						)
														logger.info(p.metrics						)
														if p.metrics["test_success"] is not True:
																					logger.error(p.metrics						)
																					exit(1						)

														a__:       List[str]											=None

							logger.info("🔥 All distributed tests successful"						)





def 						__lowerCamelCase       (      __magic_name__	:  Optional[Any]						):
							# For xla_spawn (TPUs)
							main()


if __name__ == "__main__":
		main()





