


"""simple docstring"""

import collections
import inspect
import unittest

from transformers import FocalNetConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
       import torch
       from torch import nn

       from transformers import (
           FocalNetBackbone,
           FocalNetForImageClassification,
           FocalNetForMaskedImageModeling,
           FocalNetModel,
       )
       from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
       from PIL import Image

       from transformers import AutoImageProcessor





class     lowercase_	:



 '''simple docstring'''

 def __init__(			self	:	Any   ,							_UpperCAmelCase	:	List[str]   ,							_UpperCAmelCase	:	List[str]=13   ,							_UpperCAmelCase	:	Union[str, Any]=32   ,							_UpperCAmelCase	:	List[str]=2   ,							_UpperCAmelCase	:	List[str]=3   ,							_UpperCAmelCase	:	Optional[Any]=16   ,							_UpperCAmelCase	:	Tuple=[32, 64, 128]   ,							_UpperCAmelCase	:	Dict=[1, 2, 1]   ,							_UpperCAmelCase	:	Union[str, Any]=[2, 2, 4]   ,							_UpperCAmelCase	:	Dict=2   ,							_UpperCAmelCase	:	Optional[Any]=2.0   ,							_UpperCAmelCase	:	int=True   ,							_UpperCAmelCase	:	Union[str, Any]=0.0   ,							_UpperCAmelCase	:	Tuple=0.0   ,							_UpperCAmelCase	:	List[Any]=0.1   ,							_UpperCAmelCase	:	Union[str, Any]="gelu"   ,							_UpperCAmelCase	:	Any=False   ,							_UpperCAmelCase	:	Union[str, Any]=True   ,							_UpperCAmelCase	:	Union[str, Any]=0.02   ,							_UpperCAmelCase	:	Any=1E-5   ,							_UpperCAmelCase	:	str=True   ,							_UpperCAmelCase	:	int=None   ,							_UpperCAmelCase	:	Optional[int]=True   ,							_UpperCAmelCase	:	Any=10   ,							_UpperCAmelCase	:	Optional[Any]=8   ,							_UpperCAmelCase	:	Any=["stage1", "stage2"]   ,							_UpperCAmelCase	:	Optional[Any]=[1, 2]   ,							):
       _A        =       parent
       _A        =       batch_size
       _A        =       image_size
       _A        =       patch_size
       _A        =       num_channels
       _A        =       embed_dim
       _A        =       hidden_sizes
       _A        =       depths
       _A        =       num_heads
       _A        =       window_size
       _A        =       mlp_ratio
       _A        =       qkv_bias
       _A        =       hidden_dropout_prob
       _A        =       attention_probs_dropout_prob
       _A        =       drop_path_rate
       _A        =       hidden_act
       _A        =       use_absolute_embeddings
       _A        =       patch_norm
       _A        =       layer_norm_eps
       _A        =       initializer_range
       _A        =       is_training
       _A        =       scope
       _A        =       use_labels
       _A        =       type_sequence_label_size
       _A        =       encoder_stride
       _A        =       out_features
       _A        =       out_indices

 def       lowerCAmelCase_							(			self	:	int		):
       _A        =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

       _A        =       None
       if self.use_labels:
             _A        =       ids_tensor([self.batch_size]   ,							self.type_sequence_label_size		)

       _A        =       self.get_config()

       return config, pixel_values, labels

 def       lowerCAmelCase_							(			self	:	List[Any]		):
       return FocalNetConfig(
           image_size=self.image_size   ,							patch_size=self.patch_size   ,							num_channels=self.num_channels   ,							embed_dim=self.embed_dim   ,							hidden_sizes=self.hidden_sizes   ,							depths=self.depths   ,							num_heads=self.num_heads   ,							window_size=self.window_size   ,							mlp_ratio=self.mlp_ratio   ,							qkv_bias=self.qkv_bias   ,							hidden_dropout_prob=self.hidden_dropout_prob   ,							attention_probs_dropout_prob=self.attention_probs_dropout_prob   ,							drop_path_rate=self.drop_path_rate   ,							hidden_act=self.hidden_act   ,							use_absolute_embeddings=self.use_absolute_embeddings   ,							path_norm=self.patch_norm   ,							layer_norm_eps=self.layer_norm_eps   ,							initializer_range=self.initializer_range   ,							encoder_stride=self.encoder_stride   ,							out_features=self.out_features   ,							out_indices=self.out_indices   ,							)

 def       lowerCAmelCase_							(			self	:	Union[str, Any]   ,							_UpperCAmelCase	:	List[str]   ,							_UpperCAmelCase	:	Optional[Any]   ,							_UpperCAmelCase	:	Tuple		):
       _A        =       FocalNetModel(config=_UpperCAmelCase		)
       model.to(_UpperCAmelCase		)
       model.eval()
       _A        =       model(_UpperCAmelCase		)

       _A        =       ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths		) - 1))
       _A        =       int(config.embed_dim * 2 ** (len(config.depths		) - 1)		)

       self.parent.assertEqual(result.last_hidden_state.shape   ,							(self.batch_size, expected_seq_len, expected_dim)		)

 def       lowerCAmelCase_							(			self	:	List[str]   ,							_UpperCAmelCase	:	Optional[int]   ,							_UpperCAmelCase	:	Any   ,							_UpperCAmelCase	:	List[str]		):
       _A        =       FocalNetBackbone(config=_UpperCAmelCase		)
       model.to(_UpperCAmelCase		)
       model.eval()
       _A        =       model(_UpperCAmelCase		)

       # verify feature maps
       self.parent.assertEqual(len(result.feature_maps		)   ,							len(config.out_features		)		)
       self.parent.assertListEqual(list(result.feature_maps[0].shape		)   ,							[self.batch_size, self.image_size, 8, 8]		)

       # verify channels
       self.parent.assertEqual(len(model.channels		)   ,							len(config.out_features		)		)
       self.parent.assertListEqual(model.channels   ,							config.hidden_sizes[:-1]		)

       # verify backbone works with out_features=None
       _A        =       None
       _A        =       FocalNetBackbone(config=_UpperCAmelCase		)
       model.to(_UpperCAmelCase		)
       model.eval()
       _A        =       model(_UpperCAmelCase		)

       # verify feature maps
       self.parent.assertEqual(len(result.feature_maps		)   ,							1		)
       self.parent.assertListEqual(list(result.feature_maps[0].shape		)   ,							[self.batch_size, self.image_size * 2, 4, 4]		)

       # verify channels
       self.parent.assertEqual(len(model.channels		)   ,							1		)
       self.parent.assertListEqual(model.channels   ,							[config.hidden_sizes[-1]]		)

 def       lowerCAmelCase_							(			self	:	Dict   ,							_UpperCAmelCase	:	str   ,							_UpperCAmelCase	:	Dict   ,							_UpperCAmelCase	:	int		):
       _A        =       FocalNetForMaskedImageModeling(config=_UpperCAmelCase		)
       model.to(_UpperCAmelCase		)
       model.eval()
       _A        =       model(_UpperCAmelCase		)
       self.parent.assertEqual(
           result.reconstruction.shape   ,							(self.batch_size, self.num_channels, self.image_size, self.image_size)		)

       # test greyscale images
       _A        =       1
       _A        =       FocalNetForMaskedImageModeling(_UpperCAmelCase		)
       model.to(_UpperCAmelCase		)
       model.eval()

       _A        =       floats_tensor([self.batch_size, 1, self.image_size, self.image_size]		)
       _A        =       model(_UpperCAmelCase		)
       self.parent.assertEqual(result.reconstruction.shape   ,							(self.batch_size, 1, self.image_size, self.image_size)		)

 def       lowerCAmelCase_							(			self	:	List[Any]   ,							_UpperCAmelCase	:	List[Any]   ,							_UpperCAmelCase	:	str   ,							_UpperCAmelCase	:	str		):
       _A        =       self.type_sequence_label_size
       _A        =       FocalNetForImageClassification(_UpperCAmelCase		)
       model.to(_UpperCAmelCase		)
       model.eval()
       _A        =       model(_UpperCAmelCase   ,							labels=_UpperCAmelCase		)
       self.parent.assertEqual(result.logits.shape   ,							(self.batch_size, self.type_sequence_label_size)		)

       # test greyscale images
       _A        =       1
       _A        =       FocalNetForImageClassification(_UpperCAmelCase		)
       model.to(_UpperCAmelCase		)
       model.eval()

       _A        =       floats_tensor([self.batch_size, 1, self.image_size, self.image_size]		)
       _A        =       model(_UpperCAmelCase		)
       self.parent.assertEqual(result.logits.shape   ,							(self.batch_size, self.type_sequence_label_size)		)



 def       lowerCAmelCase_							(			self	:	Tuple		):
       _A        =       self.prepare_config_and_inputs()

       _A       ,   _A       ,   _A        =       config_and_inputs
       _A        =       {'pixel_values': pixel_values}
       return config, inputs_dict





@require_torch
class     lowercase_	(					__lowerCAmelCase      ,     __lowerCAmelCase      ,     unittest.TestCase							):



 '''simple docstring'''
 UpperCAmelCase   :					int				  =     (
     (
         FocalNetModel,
         FocalNetForImageClassification,
         FocalNetForMaskedImageModeling,
         FocalNetBackbone,
     )
     if is_torch_available()
     else ()
 )
 UpperCAmelCase   :					List[Any]				  =     (
     {'''feature-extraction''': FocalNetModel, '''image-classification''': FocalNetForImageClassification}
     if is_torch_available()
     else {}
 )
 UpperCAmelCase   :					Optional[int]				  =     False

 UpperCAmelCase   :					Tuple				  =     False
 UpperCAmelCase   :					List[str]				  =     False
 UpperCAmelCase   :					str				  =     False
 UpperCAmelCase   :					Optional[Any]				  =     False

 def       lowerCAmelCase_							(			self	:	Optional[Any]		):
       _A        =       FocalNetModelTester(self		)
       _A        =       ConfigTester(self   ,							config_class=_UpperCAmelCase   ,							embed_dim=37   ,							has_text_modality=_UpperCAmelCase		)

 def       lowerCAmelCase_							(			self	:	Optional[int]		):
       self.create_and_test_config_common_properties()
       self.config_tester.create_and_test_config_to_json_string()
       self.config_tester.create_and_test_config_to_json_file()
       self.config_tester.create_and_test_config_from_and_save_pretrained()
       self.config_tester.create_and_test_config_with_num_labels()
       self.config_tester.check_config_can_be_init_without_params()
       self.config_tester.check_config_arguments_init()

 def       lowerCAmelCase_							(			self	:	List[Any]		):
       return

 def       lowerCAmelCase_							(			self	:	Dict		):
       _A        =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_UpperCAmelCase		)

 def       lowerCAmelCase_							(			self	:	Any		):
       _A        =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_backbone(*_UpperCAmelCase		)

 def       lowerCAmelCase_							(			self	:	str		):
       _A        =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_image_modeling(*_UpperCAmelCase		)

 def       lowerCAmelCase_							(			self	:	Any		):
       _A        =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase		)

 @unittest.skip(reason='FocalNet does not use inputs_embeds'		)
 def       lowerCAmelCase_							(			self	:	Union[str, Any]		):
       pass

 @unittest.skip(reason='FocalNet does not use feedforward chunking'		)
 def       lowerCAmelCase_							(			self	:	int		):
       pass

 def       lowerCAmelCase_							(			self	:	Dict		):
       _A       ,   _A        =       self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes[:-1]:
             _A        =       model_class(_UpperCAmelCase		)
             self.assertIsInstance(model.get_input_embeddings()   ,							(nn.Module)		)
             _A        =       model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(_UpperCAmelCase   ,							nn.Linear		)		)

 def       lowerCAmelCase_							(			self	:	Any		):
       _A       ,   _A        =       self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes[:-1]:
             _A        =       model_class(_UpperCAmelCase		)
             _A        =       inspect.signature(model.forward		)
             # signature.parameters is an OrderedDict => so arg_names order is deterministic
             _A        =       [*signature.parameters.keys()]

             _A        =       ['pixel_values']
             self.assertListEqual(arg_names[:1]   ,							_UpperCAmelCase		)

 def       lowerCAmelCase_							(			self	:	str   ,							_UpperCAmelCase	:	str   ,							_UpperCAmelCase	:	List[Any]   ,							_UpperCAmelCase	:	int   ,							_UpperCAmelCase	:	Union[str, Any]		):
       _A        =       model_class(_UpperCAmelCase		)
       model.to(_UpperCAmelCase		)
       model.eval()

       with torch.no_grad():
             _A        =       model(**self._prepare_for_class(_UpperCAmelCase   ,							_UpperCAmelCase		)		)

       _A        =       outputs.hidden_states

       _A        =       getattr(
           self.model_tester   ,							'expected_num_hidden_layers'   ,							len(self.model_tester.depths		) + 1		)
       self.assertEqual(len(_UpperCAmelCase		)   ,							_UpperCAmelCase		)

       # FocalNet has a different seq_length
       _A        =       (
           config.patch_size
           if isinstance(config.patch_size   ,							collections.abc.Iterable		)
           else (config.patch_size, config.patch_size)
       )

       _A        =       (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

       self.assertListEqual(
           list(hidden_states[0].shape[-2:]		)   ,							[num_patches, self.model_tester.embed_dim]   ,							)

       _A        =       outputs.reshaped_hidden_states
       self.assertEqual(len(_UpperCAmelCase		)   ,							_UpperCAmelCase		)

       _A       ,   _A       ,   _A       ,   _A        =       reshaped_hidden_states[0].shape
       _A        =       (
           reshaped_hidden_states[0].view(_UpperCAmelCase   ,							_UpperCAmelCase   ,							height * width		).permute(0   ,							2   ,							1		)
       )
       self.assertListEqual(
           list(reshaped_hidden_states.shape[-2:]		)   ,							[num_patches, self.model_tester.embed_dim]   ,							)

 def       lowerCAmelCase_							(			self	:	Tuple		):
       _A       ,   _A        =       self.model_tester.prepare_config_and_inputs_for_common()

       _A        =       (
           self.model_tester.image_size
           if isinstance(self.model_tester.image_size   ,							collections.abc.Iterable		)
           else (self.model_tester.image_size, self.model_tester.image_size)
       )

       for model_class in self.all_model_classes[:-1]:
             _A        =       True
             self.check_hidden_states_output(_UpperCAmelCase   ,							_UpperCAmelCase   ,							_UpperCAmelCase   ,							_UpperCAmelCase		)

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             _A        =       True

             self.check_hidden_states_output(_UpperCAmelCase   ,							_UpperCAmelCase   ,							_UpperCAmelCase   ,							_UpperCAmelCase		)

 def       lowerCAmelCase_							(			self	:	List[str]		):
       _A       ,   _A        =       self.model_tester.prepare_config_and_inputs_for_common()
       _A        =       3

       _A        =       (
           self.model_tester.image_size
           if isinstance(self.model_tester.image_size   ,							collections.abc.Iterable		)
           else (self.model_tester.image_size, self.model_tester.image_size)
       )
       _A        =       (
           config.patch_size
           if isinstance(config.patch_size   ,							collections.abc.Iterable		)
           else (config.patch_size, config.patch_size)
       )

       _A        =       image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
       _A        =       image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

       for model_class in self.all_model_classes[:-1]:
             _A        =       True
             self.check_hidden_states_output(_UpperCAmelCase   ,							_UpperCAmelCase   ,							_UpperCAmelCase   ,							(padded_height, padded_width)		)

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             _A        =       True
             self.check_hidden_states_output(_UpperCAmelCase   ,							_UpperCAmelCase   ,							_UpperCAmelCase   ,							(padded_height, padded_width)		)

 @slow
 def       lowerCAmelCase_							(			self	:	Tuple		):
       for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             _A        =       FocalNetModel.from_pretrained(_UpperCAmelCase		)
             self.assertIsNotNone(_UpperCAmelCase		)



 def       lowerCAmelCase_							(			self	:	str		):
       _A       ,   _A        =       self.model_tester.prepare_config_and_inputs_for_common()

       _A        =       _config_zero_init(_UpperCAmelCase		)
       for model_class in self.all_model_classes:
             _A        =       model_class(config=_UpperCAmelCase		)
             for name, param in model.named_parameters():
                   if "embeddings" not in name and param.requires_grad:
                         self.assertIn(
                             ((param.data.mean() * 1E9).round() / 1E9).item()   ,							[0.0, 1.0]   ,							msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''   ,							)





@require_vision
@require_torch
class     lowercase_	(					unittest.TestCase							):



 '''simple docstring'''

 @cached_property
 def       lowerCAmelCase_							(			self	:	str		):
       # TODO update organization
       return AutoImageProcessor.from_pretrained('microsoft/focalnet-tiny'		) if is_vision_available() else None



 @slow
 def       lowerCAmelCase_							(			self	:	List[str]		):
       _A        =       FocalNetForImageClassification.from_pretrained('microsoft/focalnet-tiny'		).to(_UpperCAmelCase		)
       _A        =       self.default_image_processor

       _A        =       Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'		)
       _A        =       image_processor(images=_UpperCAmelCase   ,							return_tensors='pt'		).to(_UpperCAmelCase		)

       # forward pass
       with torch.no_grad():
             _A        =       model(**_UpperCAmelCase		)

       # verify the logits
       _A        =       torch.Size((1, 1_000)		)
       self.assertEqual(outputs.logits.shape   ,							_UpperCAmelCase		)
       _A        =       torch.tensor([0.2166, -0.4368, 0.2191]		).to(_UpperCAmelCase		)
       self.assertTrue(torch.allclose(outputs.logits[0, :3]   ,							_UpperCAmelCase   ,							atol=1E-4		)		)
       self.assertTrue(outputs.logits.argmax(dim=-1		).item()   ,							281		)





@require_torch
class     lowercase_	(					__lowerCAmelCase      ,     unittest.TestCase							):



 '''simple docstring'''
 UpperCAmelCase   :					List[str]				  =     (FocalNetBackbone,) if is_torch_available() else ()
 UpperCAmelCase   :					Union[str, Any]				  =     FocalNetConfig

 UpperCAmelCase   :					Tuple				  =     False

 def       lowerCAmelCase_							(			self	:	str		):
       _A        =       FocalNetModelTester(self		)







"""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


a         =      logging.getLogger(__name__)





@dataclass
class     lowercase_	:



 '''simple docstring'''
 UpperCAmelCase   :					str
 UpperCAmelCase   :					List[str]
 UpperCAmelCase   :					Optional[List[str]]





@dataclass
class     lowercase_	:



 '''simple docstring'''
 UpperCAmelCase   :					List[int]
 UpperCAmelCase   :					List[int]
 UpperCAmelCase   :					Optional[List[int]]				  =     None
 UpperCAmelCase   :					Optional[List[int]]				  =     None





class     lowercase_	(					__lowerCAmelCase							):



 '''simple docstring'''
 UpperCAmelCase   :					Any				  =     '''train'''
 UpperCAmelCase   :					Tuple				  =     '''dev'''
 UpperCAmelCase   :					int				  =     '''test'''





class     lowercase_	:



 '''simple docstring'''

 @staticmethod
 def       lowerCAmelCase_							(			_UpperCAmelCase	:	int   ,							_UpperCAmelCase	:	Union[Split, str]		):
       raise NotImplementedError

 @staticmethod
 def       lowerCAmelCase_							(			_UpperCAmelCase	:	str		):
       raise NotImplementedError



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

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

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

                   # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space.
                   if len(_UpperCAmelCase		) > 0:
                         tokens.extend(_UpperCAmelCase		)
                         # 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(_UpperCAmelCase		) - 1)		)

            # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa.
             _A        =       tokenizer.num_special_tokens_to_add()
             if len(_UpperCAmelCase		) > 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(_UpperCAmelCase		)

             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(_UpperCAmelCase		)

             # 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(_UpperCAmelCase		)

             # Zero-pad up to the sequence length.
             _A        =       max_seq_length - len(_UpperCAmelCase		)
             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(_UpperCAmelCase		) == max_seq_length
             assert len(_UpperCAmelCase		) == max_seq_length
             assert len(_UpperCAmelCase		) == max_seq_length
             assert len(_UpperCAmelCase		) == max_seq_length

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

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

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


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





       class     lowercase_	(					__lowerCAmelCase							):



        '''simple docstring'''
        UpperCAmelCase   :					List[InputFeatures]
        UpperCAmelCase   :					int				  =     nn.CrossEntropyLoss().ignore_index

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

              # 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(_UpperCAmelCase		):
                    if os.path.exists(_UpperCAmelCase		) and not overwrite_cache:
                          logger.info(F'''Loading features from cached file {cached_features_file}'''		)
                          _A        =       torch.load(_UpperCAmelCase		)
                    else:
                          logger.info(F'''Creating features from dataset file at {data_dir}'''		)
                          _A        =       token_classification_task.read_examples_from_file(_UpperCAmelCase   ,							_UpperCAmelCase		)
                          # TODO clean up all this to leverage built-in features of tokenizers
                          _A        =       token_classification_task.convert_examples_to_features(
                              _UpperCAmelCase   ,							_UpperCAmelCase   ,							_UpperCAmelCase   ,							_UpperCAmelCase   ,							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=_UpperCAmelCase   ,							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   ,							_UpperCAmelCase		)

        def __len__(			self	:	Dict		):
              return len(self.features		)



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


if is_tf_available():
       import tensorflow as tf





       class     lowercase_	:



        '''simple docstring'''
        UpperCAmelCase   :					List[InputFeatures]
        UpperCAmelCase   :					int				  =     -100

        def __init__(			self	:	int   ,							_UpperCAmelCase	:	TokenClassificationTask   ,							_UpperCAmelCase	:	str   ,							_UpperCAmelCase	:	PreTrainedTokenizer   ,							_UpperCAmelCase	:	List[str]   ,							_UpperCAmelCase	:	str   ,							_UpperCAmelCase	:	Optional[int] = None   ,							_UpperCAmelCase	:	Optional[Any]=False   ,							_UpperCAmelCase	:	Split = Split.train   ,							):
              _A        =       token_classification_task.read_examples_from_file(_UpperCAmelCase   ,							_UpperCAmelCase		)
              # TODO clean up all this to leverage built-in features of tokenizers
              _A        =       token_classification_task.convert_examples_to_features(
                  _UpperCAmelCase   ,							_UpperCAmelCase   ,							_UpperCAmelCase   ,							_UpperCAmelCase   ,							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=_UpperCAmelCase   ,							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(
                        _UpperCAmelCase   ,							({'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(
                        _UpperCAmelCase   ,							({'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       lowerCAmelCase_							(			self	:	Dict		):
              _A        =       self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features		)		)		)

              return self.dataset

        def __len__(			self	:	Tuple		):
              return len(self.features		)



        def __getitem__(			self	:	Dict   ,							_UpperCAmelCase	:	Optional[int]		):
              return self.features[i]

