


"""simple docstring"""


import logging
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

from filelock import FileLock

from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available


UpperCamelCase						:				Any             =      logging.getLogger(__name__)



@dataclass
class 			lowerCamelCase__						:
						lowerCAmelCase       =     42
						lowerCAmelCase       =     42
						lowerCAmelCase       =     42



@dataclass
class 			lowerCamelCase__						:
						lowerCAmelCase       =     42
						lowerCAmelCase       =     42
						lowerCAmelCase       =     None
						lowerCAmelCase       =     None



class 			lowerCamelCase__						(   UpperCAmelCase_			):
						lowerCAmelCase       =     """train"""
						lowerCAmelCase       =     """dev"""
						lowerCAmelCase       =     """test"""



class 			lowerCamelCase__						:







						@staticmethod
						def __a						(							_lowercase   :    List[Any]			,			_lowercase   :    Union[Split, str]		):
								raise NotImplementedError







						@staticmethod
						def __a						(							_lowercase   :    str		):
								raise NotImplementedError







						@staticmethod
						def __a						(							_lowercase   :    List[InputExample]			,			_lowercase   :    List[str]			,			_lowercase   :    int			,			_lowercase   :    PreTrainedTokenizer			,			_lowercase   :    List[str]=False			,			_lowercase   :    Optional[int]="[CLS]"			,			_lowercase   :    Any=1			,			_lowercase   :    Optional[int]="[SEP]"			,			_lowercase   :    str=False			,			_lowercase   :    Optional[Any]=False			,			_lowercase   :    int=0			,			_lowercase   :    List[str]=0			,			_lowercase   :    Tuple=-100			,			_lowercase   :    str=0			,			_lowercase   :    Any=True			,			):
								A					       = {label: i for i, label in enumerate(_lowercase		)}

								A					       = []
								for ex_index, example in enumerate(_lowercase		):
										if ex_index % 10_000 == 0:
												logger.info('Writing example %d of %d'			,			_lowercase			,			len(_lowercase		)		)

										A					       = []
										A					       = []
										for word, label in zip(example.words			,			example.labels		):
												A					       = tokenizer.tokenize(_lowercase		)

												# bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space.
												if len(_lowercase		) > 0:
														tokens.extend(_lowercase		)
														# Use the real label id for the first token of the word, and padding ids for the remaining tokens
														label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(_lowercase		) - 1)		)

            # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa.
										A					       = tokenizer.num_special_tokens_to_add()
										if len(_lowercase		) > max_seq_length - special_tokens_count:
												A					       = tokens[: (max_seq_length - special_tokens_count)]
												A					       = label_ids[: (max_seq_length - special_tokens_count)]

										# The convention in BERT is:
										# (a) For sequence pairs:
										#  tokens:   [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
										#  type_ids:   0   0  0    0    0     0       0   0   1  1  1  1   1   1
										# (b) For single sequences:
										#  tokens:   [CLS] the dog is hairy . [SEP]
										#  type_ids:   0   0   0   0  0     0   0
										#
										# Where "type_ids" are used to indicate whether this is the first
										# sequence or the second sequence. The embedding vectors for `type=0` and
										# `type=1` were learned during pre-training and are added to the wordpiece
										# embedding vector (and position vector). This is not *strictly* necessary
										# since the [SEP] token unambiguously separates the sequences, but it makes
										# it easier for the model to learn the concept of sequences.
										#
										# For classification tasks, the first vector (corresponding to [CLS]) is
										# used as the "sentence vector". Note that this only makes sense because
										# the entire model is fine-tuned.
										tokens += [sep_token]
										label_ids += [pad_token_label_id]
										if sep_token_extra:
												# roberta uses an extra separator b/w pairs of sentences
												tokens += [sep_token]
												label_ids += [pad_token_label_id]
										A					       = [sequence_a_segment_id] * len(_lowercase		)

										if cls_token_at_end:
												tokens += [cls_token]
												label_ids += [pad_token_label_id]
												segment_ids += [cls_token_segment_id]
										else:
												A					       = [cls_token] + tokens
												A					       = [pad_token_label_id] + label_ids
												A					       = [cls_token_segment_id] + segment_ids

										A					       = tokenizer.convert_tokens_to_ids(_lowercase		)

										# The mask has 1 for real tokens and 0 for padding tokens. Only real
										# tokens are attended to.
										A					       = [1 if mask_padding_with_zero else 0] * len(_lowercase		)

										# Zero-pad up to the sequence length.
										A					       = max_seq_length - len(_lowercase		)
										if pad_on_left:
												A					       = ([pad_token] * padding_length) + input_ids
												A					       = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask
												A					       = ([pad_token_segment_id] * padding_length) + segment_ids
												A					       = ([pad_token_label_id] * padding_length) + label_ids
										else:
												input_ids += [pad_token] * padding_length
												input_mask += [0 if mask_padding_with_zero else 1] * padding_length
												segment_ids += [pad_token_segment_id] * padding_length
												label_ids += [pad_token_label_id] * padding_length

										assert len(_lowercase		) == max_seq_length
										assert len(_lowercase		) == max_seq_length
										assert len(_lowercase		) == max_seq_length
										assert len(_lowercase		) == max_seq_length

										if ex_index < 5:
												logger.info('*** Example ***'		)
												logger.info('guid: %s'			,			example.guid		)
												logger.info('tokens: %s'			,			' '.join([str(_lowercase		) for x in tokens]		)		)
												logger.info('input_ids: %s'			,			' '.join([str(_lowercase		) for x in input_ids]		)		)
												logger.info('input_mask: %s'			,			' '.join([str(_lowercase		) for x in input_mask]		)		)
												logger.info('segment_ids: %s'			,			' '.join([str(_lowercase		) for x in segment_ids]		)		)
												logger.info('label_ids: %s'			,			' '.join([str(_lowercase		) for x in label_ids]		)		)

										if "token_type_ids" not in tokenizer.model_input_names:
												A					       = None

										features.append(
										    InputFeatures(
										        input_ids=_lowercase			,			attention_mask=_lowercase			,			token_type_ids=_lowercase			,			label_ids=_lowercase		)		)
								return features


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



	class 			lowerCamelCase__						(   UpperCAmelCase_			):
							lowerCAmelCase       =     42
							lowerCAmelCase       =     nn.CrossEntropyLoss().ignore_index







							def __init__(							self   :    Dict			,			_lowercase   :    TokenClassificationTask			,			_lowercase   :    str			,			_lowercase   :    PreTrainedTokenizer			,			_lowercase   :    List[str]			,			_lowercase   :    str			,			_lowercase   :    Optional[int] = None			,			_lowercase   :    Tuple=False			,			_lowercase   :    Split = Split.train			,			):
									# Load data features from cache or dataset file
									A					       = os.path.join(
									    _lowercase			,			'cached_{}_{}_{}'.format(mode.value			,			tokenizer.__class__.__name__			,			str(_lowercase		)		)			,			)

									# Make sure only the first process in distributed training processes the dataset,
									# and the others will use the cache.
									A					       = cached_features_file + '.lock'
									with FileLock(_lowercase		):
											if os.path.exists(_lowercase		) and not overwrite_cache:
													logger.info(f'Loading features from cached file {cached_features_file}'		)
													A					       = torch.load(_lowercase		)
											else:
													logger.info(f'Creating features from dataset file at {data_dir}'		)
													A					       = token_classification_task.read_examples_from_file(_lowercase			,			_lowercase		)
													# TODO clean up all this to leverage built-in features of tokenizers
													A					       = token_classification_task.convert_examples_to_features(
													    _lowercase			,			_lowercase			,			_lowercase			,			_lowercase			,			cls_token_at_end=bool(model_type in ['xlnet']		)			,			cls_token=tokenizer.cls_token			,			cls_token_segment_id=2 if model_type in ['xlnet'] else 0			,			sep_token=tokenizer.sep_token			,			sep_token_extra=_lowercase			,			pad_on_left=bool(tokenizer.padding_side == 'left'		)			,			pad_token=tokenizer.pad_token_id			,			pad_token_segment_id=tokenizer.pad_token_type_id			,			pad_token_label_id=self.pad_token_label_id			,			)
													logger.info(f'Saving features into cached file {cached_features_file}'		)
													torch.save(self.features			,			_lowercase		)







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







							def __getitem__(							self   :    str			,			_lowercase   :    Optional[Any]		):
									return self.features[i]


if is_tf_available():
	import tensorflow as tf



	class 			lowerCamelCase__						:
							lowerCAmelCase       =     42
							lowerCAmelCase       =     -100







							def __init__(							self   :    Any			,			_lowercase   :    TokenClassificationTask			,			_lowercase   :    str			,			_lowercase   :    PreTrainedTokenizer			,			_lowercase   :    List[str]			,			_lowercase   :    str			,			_lowercase   :    Optional[int] = None			,			_lowercase   :    Optional[int]=False			,			_lowercase   :    Split = Split.train			,			):
									A					       = token_classification_task.read_examples_from_file(_lowercase			,			_lowercase		)
									# TODO clean up all this to leverage built-in features of tokenizers
									A					       = token_classification_task.convert_examples_to_features(
									    _lowercase			,			_lowercase			,			_lowercase			,			_lowercase			,			cls_token_at_end=bool(model_type in ['xlnet']		)			,			cls_token=tokenizer.cls_token			,			cls_token_segment_id=2 if model_type in ['xlnet'] else 0			,			sep_token=tokenizer.sep_token			,			sep_token_extra=_lowercase			,			pad_on_left=bool(tokenizer.padding_side == 'left'		)			,			pad_token=tokenizer.pad_token_id			,			pad_token_segment_id=tokenizer.pad_token_type_id			,			pad_token_label_id=self.pad_token_label_id			,			)

									def gen():
											for ex in self.features:
													if ex.token_type_ids is None:
															yield (
															    {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask},
															    ex.label_ids,
															)
													else:
															yield (
															    {
															        "input_ids": ex.input_ids,
															        "attention_mask": ex.attention_mask,
															        "token_type_ids": ex.token_type_ids,
															    },
															    ex.label_ids,
															)

									if "token_type_ids" not in tokenizer.model_input_names:
											A					       = tf.data.Dataset.from_generator(
											    _lowercase			,			({'input_ids': tf.intaa, 'attention_mask': tf.intaa}, tf.intaa)			,			(
											        {'input_ids': tf.TensorShape([None]		), 'attention_mask': tf.TensorShape([None]		)},
											        tf.TensorShape([None]		),
											    )			,			)
									else:
											A					       = tf.data.Dataset.from_generator(
											    _lowercase			,			({'input_ids': tf.intaa, 'attention_mask': tf.intaa, 'token_type_ids': tf.intaa}, tf.intaa)			,			(
											        {
											            'input_ids': tf.TensorShape([None]		),
											            'attention_mask': tf.TensorShape([None]		),
											            'token_type_ids': tf.TensorShape([None]		),
											        },
											        tf.TensorShape([None]		),
											    )			,			)







							def __a						(							self   :    Tuple		):
									A					       = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features		)		)		)

									return self.dataset







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







							def __getitem__(							self   :    Union[str, Any]			,			_lowercase   :    Optional[Any]		):
									return self.features[i]









"""simple docstring"""


import json
import os
import subprocess
import unittest
from ast import literal_eval

import pytest
from parameterized import parameterized, parameterized_class

from . import is_sagemaker_available


if is_sagemaker_available():
	from sagemaker import Session, TrainingJobAnalytics
	from sagemaker.huggingface import HuggingFace



@pytest.mark.skipif(
    literal_eval(os.getenv("""TEST_SAGEMAKER"""							,    """False"""			)			) is not True							,    reason="""Skipping test because should only be run when releasing minor transformers version"""							,    )
@pytest.mark.usefixtures("""sm_env"""			)
@parameterized_class(
    [
        {
            """framework""": """pytorch""",
            """script""": """run_glue.py""",
            """model_name_or_path""": """distilbert-base-cased""",
            """instance_type""": """ml.p3.16xlarge""",
            """results""": {"""train_runtime""": 650, """eval_accuracy""": 0.7, """eval_loss""": 0.6},
        },
        {
            """framework""": """pytorch""",
            """script""": """run_ddp.py""",
            """model_name_or_path""": """distilbert-base-cased""",
            """instance_type""": """ml.p3.16xlarge""",
            """results""": {"""train_runtime""": 600, """eval_accuracy""": 0.7, """eval_loss""": 0.6},
        },
        {
            """framework""": """tensorflow""",
            """script""": """run_tf_dist.py""",
            """model_name_or_path""": """distilbert-base-cased""",
            """instance_type""": """ml.p3.16xlarge""",
            """results""": {"""train_runtime""": 600, """eval_accuracy""": 0.6, """eval_loss""": 0.7},
        },
    ]			)
class 			lowerCamelCase__						(   unittest.TestCase			):







						def __a						(							self   :    int		):
								if self.framework == "pytorch":
										subprocess.run(
										    f'cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'.split()			,			encoding='utf-8'			,			check=_lowercase			,			)
								assert hasattr(self			,			'env'		)







						def __a						(							self   :    Optional[int]			,			_lowercase   :    int		):
								A					       = f'{self.env.base_job_name}-{instance_count}-{"ddp" if "ddp" in self.script else "smd"}'
								# distributed data settings
								A					       = {'smdistributed': {'dataparallel': {'enabled': True}}} if self.script != 'run_ddp.py' else None

								# creates estimator
								return HuggingFace(
								    entry_point=self.script			,			source_dir=self.env.test_path			,			role=self.env.role			,			image_uri=self.env.image_uri			,			base_job_name=_lowercase			,			instance_count=_lowercase			,			instance_type=self.instance_type			,			debugger_hook_config=_lowercase			,			hyperparameters={**self.env.distributed_hyperparameters, 'model_name_or_path': self.model_name_or_path}			,			metric_definitions=self.env.metric_definitions			,			distribution=_lowercase			,			py_version='py36'			,			)







						def __a						(							self   :    Tuple			,			_lowercase   :    List[str]		):
								TrainingJobAnalytics(_lowercase		).export_csv(f'{self.env.test_path}/{job_name}_metrics.csv'		)







						@parameterized.expand([(2,)]		)
						def __a						(							self   :    List[Any]			,			_lowercase   :    Union[str, Any]		):
								# create estimator
								A					       = self.create_estimator(_lowercase		)

								# run training
								estimator.fit()

								# result dataframe
								A					       = TrainingJobAnalytics(estimator.latest_training_job.name		).dataframe()

								# extract kpis
								A					       = list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value']		)
								A					       = list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value']		)
								# get train time from SageMaker job, this includes starting, preprocessing, stopping
								A					       = (
								    Session().describe_training_job(estimator.latest_training_job.name		).get('TrainingTimeInSeconds'			,			999_999		)
								)

								# assert kpis
								assert train_runtime <= self.results["train_runtime"]
								assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy		)
								assert all(t <= self.results['eval_loss'] for t in eval_loss		)

								# dump tests result into json file to share in PR
								with open(f'{estimator.latest_training_job.name}.json'			,			'w'		) as outfile:
										json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss}			,			_lowercase		)





