
import unittest

from transformers import (
    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    Pipeline,
    ZeroShotClassificationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow

from .test_pipelines_common import ANY


# These 2 model types require different inputs than those of the usual text models.
lowercase						:      Union[str, Any]									= {'''LayoutLMv2Config''', '''LayoutLMv3Config'''}




@is_pipeline_test
class 				lowerCamelCase__							(       unittest.TestCase):




	'''simple docstring'''




	_A			=  MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
	_A			=  TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

	if model_mapping is not None:
		_A			=  {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
	if tf_model_mapping is not None:
		_A			=  {
		    config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
		}







	def      _lowerCamelCase       (      self	:List[str]  ,     a	:Tuple  ,     a	:List[Any]  ,     a	:Dict		)	->				Any:
								__UpperCamelCase			:     Optional[Any]         =      ZeroShotClassificationPipeline(
								    model=__UpperCamelCase  ,     tokenizer=__UpperCamelCase  ,     candidate_labels=["polics", "health"]		)
								return classifier, ["Who are you voting for in 2020?", "My stomach hurts."]







	def      _lowerCamelCase       (      self	:Union[str, Any]  ,     a	:Tuple  ,     a	:Optional[int]		)	->				Tuple:
								__UpperCamelCase			:     List[Any]         =      classifier("Who are you voting for in 2020?"  ,     candidate_labels="politics"		)
								self.assertEqual(__UpperCamelCase  ,     {"sequence": ANY(__UpperCamelCase		), "labels": [ANY(__UpperCamelCase		)], "scores": [ANY(__UpperCamelCase		)]}		)

								# No kwarg
								__UpperCamelCase			:     Dict         =      classifier("Who are you voting for in 2020?"  ,     ["politics"]		)
								self.assertEqual(__UpperCamelCase  ,     {"sequence": ANY(__UpperCamelCase		), "labels": [ANY(__UpperCamelCase		)], "scores": [ANY(__UpperCamelCase		)]}		)

								__UpperCamelCase			:     Union[str, Any]         =      classifier("Who are you voting for in 2020?"  ,     candidate_labels=["politics"]		)
								self.assertEqual(__UpperCamelCase  ,     {"sequence": ANY(__UpperCamelCase		), "labels": [ANY(__UpperCamelCase		)], "scores": [ANY(__UpperCamelCase		)]}		)

								__UpperCamelCase			:     Optional[Any]         =      classifier("Who are you voting for in 2020?"  ,     candidate_labels="politics, public health"		)
								self.assertEqual(
								    __UpperCamelCase  ,     {"sequence": ANY(__UpperCamelCase		), "labels": [ANY(__UpperCamelCase		), ANY(__UpperCamelCase		)], "scores": [ANY(__UpperCamelCase		), ANY(__UpperCamelCase		)]}		)
								self.assertAlmostEqual(sum(nested_simplify(outputs["scores"]		)		)  ,     1.0		)

								__UpperCamelCase			:     List[str]         =      classifier("Who are you voting for in 2020?"  ,     candidate_labels=["politics", "public health"]		)
								self.assertEqual(
								    __UpperCamelCase  ,     {"sequence": ANY(__UpperCamelCase		), "labels": [ANY(__UpperCamelCase		), ANY(__UpperCamelCase		)], "scores": [ANY(__UpperCamelCase		), ANY(__UpperCamelCase		)]}		)
								self.assertAlmostEqual(sum(nested_simplify(outputs["scores"]		)		)  ,     1.0		)

								__UpperCamelCase			:     str         =      classifier(
								    "Who are you voting for in 2020?"  ,     candidate_labels="politics"  ,     hypothesis_template="This text is about {}"		)
								self.assertEqual(__UpperCamelCase  ,     {"sequence": ANY(__UpperCamelCase		), "labels": [ANY(__UpperCamelCase		)], "scores": [ANY(__UpperCamelCase		)]}		)

								# https://github.com/huggingface/transformers/issues/13846
								__UpperCamelCase			:     List[str]         =      classifier(["I am happy"]  ,     ["positive", "negative"]		)
								self.assertEqual(
								    __UpperCamelCase  ,     [
								        {"sequence": ANY(__UpperCamelCase		), "labels": [ANY(__UpperCamelCase		), ANY(__UpperCamelCase		)], "scores": [ANY(__UpperCamelCase		), ANY(__UpperCamelCase		)]}
								        for i in range(1		)
								    ]  ,     )
								__UpperCamelCase			:     Dict         =      classifier(["I am happy", "I am sad"]  ,     ["positive", "negative"]		)
								self.assertEqual(
								    __UpperCamelCase  ,     [
								        {"sequence": ANY(__UpperCamelCase		), "labels": [ANY(__UpperCamelCase		), ANY(__UpperCamelCase		)], "scores": [ANY(__UpperCamelCase		), ANY(__UpperCamelCase		)]}
								        for i in range(2		)
								    ]  ,     )

								with self.assertRaises(__UpperCamelCase		):
															classifier(""  ,     candidate_labels="politics"		)

								with self.assertRaises(__UpperCamelCase		):
															classifier(__UpperCamelCase  ,     candidate_labels="politics"		)

								with self.assertRaises(__UpperCamelCase		):
															classifier("Who are you voting for in 2020?"  ,     candidate_labels=""		)

								with self.assertRaises(__UpperCamelCase		):
															classifier("Who are you voting for in 2020?"  ,     candidate_labels=__UpperCamelCase		)

								with self.assertRaises(__UpperCamelCase		):
															classifier(
															    "Who are you voting for in 2020?"  ,     candidate_labels="politics"  ,     hypothesis_template="Not formatting template"  ,     )

								with self.assertRaises(__UpperCamelCase		):
															classifier(
															    "Who are you voting for in 2020?"  ,     candidate_labels="politics"  ,     hypothesis_template=__UpperCamelCase  ,     )

								self.run_entailment_id(__UpperCamelCase		)







	def      _lowerCamelCase       (      self	:Optional[int]  ,     a	:Pipeline		)	->				List[str]:
								__UpperCamelCase			:     List[str]         =      zero_shot_classifier.model.config
								__UpperCamelCase			:     List[Any]         =      config.labelaid
								__UpperCamelCase			:     Tuple         =      zero_shot_classifier.entailment_id

								__UpperCamelCase			:     Tuple         =      {"LABEL_0": 0, "LABEL_1": 1, "LABEL_2": 2}
								self.assertEqual(zero_shot_classifier.entailment_id  ,     -1		)

								__UpperCamelCase			:     Dict         =      {"entailment": 0, "neutral": 1, "contradiction": 2}
								self.assertEqual(zero_shot_classifier.entailment_id  ,     0		)

								__UpperCamelCase			:     Tuple         =      {"ENTAIL": 0, "NON-ENTAIL": 1}
								self.assertEqual(zero_shot_classifier.entailment_id  ,     0		)

								__UpperCamelCase			:     Optional[Any]         =      {"ENTAIL": 2, "NEUTRAL": 1, "CONTR": 0}
								self.assertEqual(zero_shot_classifier.entailment_id  ,     2		)

								__UpperCamelCase			:     Optional[int]         =      original_labelaid
								self.assertEqual(__UpperCamelCase  ,     zero_shot_classifier.entailment_id		)







	@require_torch
	def      _lowerCamelCase       (      self	:Dict		)	->				Tuple:
								__UpperCamelCase			:     Union[str, Any]         =      pipeline(
								    "zero-shot-classification"  ,     model="sshleifer/tiny-distilbert-base-cased-distilled-squad"  ,     framework="pt"  ,     )
								# There was a regression in 4.10 for this
								# Adding a test so we don't make the mistake again.
								# https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499
								zero_shot_classifier(
								    "Who are you voting for in 2020?" * 1_0_0  ,     candidate_labels=["politics", "public health", "science"]		)







	@require_torch
	def      _lowerCamelCase       (      self	:Optional[Any]		)	->				str:
								__UpperCamelCase			:     Tuple         =      pipeline(
								    "zero-shot-classification"  ,     model="sshleifer/tiny-distilbert-base-cased-distilled-squad"  ,     framework="pt"  ,     )
								__UpperCamelCase			:     List[Any]         =      zero_shot_classifier(
								    "Who are you voting for in 2020?"  ,     candidate_labels=["politics", "public health", "science"]		)

								self.assertEqual(
								    nested_simplify(__UpperCamelCase		)  ,     {
								        "sequence": "Who are you voting for in 2020?",
								        "labels": ["science", "public health", "politics"],
								        "scores": [0.333, 0.333, 0.333],
								    }  ,     )







	@require_tf
	def      _lowerCamelCase       (      self	:Any		)	->				int:
								__UpperCamelCase			:     List[Any]         =      pipeline(
								    "zero-shot-classification"  ,     model="sshleifer/tiny-distilbert-base-cased-distilled-squad"  ,     framework="tf"  ,     )
								__UpperCamelCase			:     Union[str, Any]         =      zero_shot_classifier(
								    "Who are you voting for in 2020?"  ,     candidate_labels=["politics", "public health", "science"]		)

								self.assertEqual(
								    nested_simplify(__UpperCamelCase		)  ,     {
								        "sequence": "Who are you voting for in 2020?",
								        "labels": ["science", "public health", "politics"],
								        "scores": [0.333, 0.333, 0.333],
								    }  ,     )







	@slow
	@require_torch
	def      _lowerCamelCase       (      self	:Optional[Any]		)	->				Any:
								__UpperCamelCase			:     str         =      pipeline("zero-shot-classification"  ,     model="roberta-large-mnli"  ,     framework="pt"		)
								__UpperCamelCase			:     Optional[Any]         =      zero_shot_classifier(
								    "Who are you voting for in 2020?"  ,     candidate_labels=["politics", "public health", "science"]		)

								self.assertEqual(
								    nested_simplify(__UpperCamelCase		)  ,     {
								        "sequence": "Who are you voting for in 2020?",
								        "labels": ["politics", "public health", "science"],
								        "scores": [0.976, 0.015, 0.009],
								    }  ,     )
								__UpperCamelCase			:     List[Any]         =      zero_shot_classifier(
								    "The dominant sequence transduction models are based on complex recurrent or convolutional neural networks"
								    " in an encoder-decoder configuration. The best performing models also connect the encoder and decoder"
								    " through an attention mechanism. We propose a new simple network architecture, the Transformer, based"
								    " solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two"
								    " machine translation tasks show these models to be superior in quality while being more parallelizable"
								    " and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014"
								    " English-to-German translation task, improving over the existing best results, including ensembles by"
								    " over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new"
								    " single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small"
								    " fraction of the training costs of the best models from the literature. We show that the Transformer"
								    " generalizes well to other tasks by applying it successfully to English constituency parsing both with"
								    " large and limited training data."  ,     candidate_labels=["machine learning", "statistics", "translation", "vision"]  ,     multi_label=__UpperCamelCase  ,     )
								self.assertEqual(
								    nested_simplify(__UpperCamelCase		)  ,     {
								        "sequence": (
								            "The dominant sequence transduction models are based on complex recurrent or convolutional neural"
								            " networks in an encoder-decoder configuration. The best performing models also connect the"
								            " encoder and decoder through an attention mechanism. We propose a new simple network"
								            " architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence"
								            " and convolutions entirely. Experiments on two machine translation tasks show these models to be"
								            " superior in quality while being more parallelizable and requiring significantly less time to"
								            " train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,"
								            " improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014"
								            " English-to-French translation task, our model establishes a new single-model state-of-the-art"
								            " BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training"
								            " costs of the best models from the literature. We show that the Transformer generalizes well to"
								            " other tasks by applying it successfully to English constituency parsing both with large and"
								            " limited training data."
								        ),
								        "labels": ["translation", "machine learning", "vision", "statistics"],
								        "scores": [0.817, 0.713, 0.018, 0.018],
								    }  ,     )







	@slow
	@require_tf
	def      _lowerCamelCase       (      self	:str		)	->				Dict:
								__UpperCamelCase			:     Optional[Any]         =      pipeline("zero-shot-classification"  ,     model="roberta-large-mnli"  ,     framework="tf"		)
								__UpperCamelCase			:     str         =      zero_shot_classifier(
								    "Who are you voting for in 2020?"  ,     candidate_labels=["politics", "public health", "science"]		)

								self.assertEqual(
								    nested_simplify(__UpperCamelCase		)  ,     {
								        "sequence": "Who are you voting for in 2020?",
								        "labels": ["politics", "public health", "science"],
								        "scores": [0.976, 0.015, 0.009],
								    }  ,     )
								__UpperCamelCase			:     Optional[int]         =      zero_shot_classifier(
								    "The dominant sequence transduction models are based on complex recurrent or convolutional neural networks"
								    " in an encoder-decoder configuration. The best performing models also connect the encoder and decoder"
								    " through an attention mechanism. We propose a new simple network architecture, the Transformer, based"
								    " solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two"
								    " machine translation tasks show these models to be superior in quality while being more parallelizable"
								    " and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014"
								    " English-to-German translation task, improving over the existing best results, including ensembles by"
								    " over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new"
								    " single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small"
								    " fraction of the training costs of the best models from the literature. We show that the Transformer"
								    " generalizes well to other tasks by applying it successfully to English constituency parsing both with"
								    " large and limited training data."  ,     candidate_labels=["machine learning", "statistics", "translation", "vision"]  ,     multi_label=__UpperCamelCase  ,     )
								self.assertEqual(
								    nested_simplify(__UpperCamelCase		)  ,     {
								        "sequence": (
								            "The dominant sequence transduction models are based on complex recurrent or convolutional neural"
								            " networks in an encoder-decoder configuration. The best performing models also connect the"
								            " encoder and decoder through an attention mechanism. We propose a new simple network"
								            " architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence"
								            " and convolutions entirely. Experiments on two machine translation tasks show these models to be"
								            " superior in quality while being more parallelizable and requiring significantly less time to"
								            " train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,"
								            " improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014"
								            " English-to-French translation task, our model establishes a new single-model state-of-the-art"
								            " BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training"
								            " costs of the best models from the literature. We show that the Transformer generalizes well to"
								            " other tasks by applying it successfully to English constituency parsing both with large and"
								            " limited training data."
								        ),
								        "labels": ["translation", "machine learning", "vision", "statistics"],
								        "scores": [0.817, 0.713, 0.018, 0.018],
								    }  ,     )

from .constants import (
    MODEL_NAME,
    OPTIMIZER_NAME,
    RNG_STATE_NAME,
    SAFE_WEIGHTS_INDEX_NAME,
    SAFE_WEIGHTS_NAME,
    SCALER_NAME,
    SCHEDULER_NAME,
    TORCH_LAUNCH_PARAMS,
    WEIGHTS_INDEX_NAME,
    WEIGHTS_NAME,
)
from .dataclasses import (
    BnbQuantizationConfig,
    ComputeEnvironment,
    CustomDtype,
    DeepSpeedPlugin,
    DistributedDataParallelKwargs,
    DistributedType,
    DynamoBackend,
    FPaRecipeKwargs,
    FullyShardedDataParallelPlugin,
    GradientAccumulationPlugin,
    GradScalerKwargs,
    InitProcessGroupKwargs,
    KwargsHandler,
    LoggerType,
    MegatronLMPlugin,
    PrecisionType,
    ProjectConfiguration,
    RNGType,
    SageMakerDistributedType,
    TensorInformation,
    TorchDynamoPlugin,
)
from .environment import get_int_from_env, parse_choice_from_env, parse_flag_from_env
from .imports import (
    get_ccl_version,
    is_abit_bnb_available,
    is_abit_bnb_available,
    is_aim_available,
    is_bfaa_available,
    is_bnb_available,
    is_botoa_available,
    is_ccl_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_fpa_available,
    is_ipex_available,
    is_megatron_lm_available,
    is_mlflow_available,
    is_mps_available,
    is_npu_available,
    is_rich_available,
    is_safetensors_available,
    is_sagemaker_available,
    is_tensorboard_available,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)
from .modeling import (
    check_device_map,
    check_tied_parameters_in_config,
    check_tied_parameters_on_same_device,
    compute_module_sizes,
    convert_file_size_to_int,
    dtype_byte_size,
    find_tied_parameters,
    get_balanced_memory,
    get_max_layer_size,
    get_max_memory,
    get_mixed_precision_context_manager,
    id_tensor_storage,
    infer_auto_device_map,
    load_checkpoint_in_model,
    load_offloaded_weights,
    load_state_dict,
    named_module_tensors,
    retie_parameters,
    set_module_tensor_to_device,
    shard_checkpoint,
)
from .offload import (
    OffloadedWeightsLoader,
    PrefixedDataset,
    extract_submodules_state_dict,
    load_offloaded_weight,
    offload_state_dict,
    offload_weight,
    save_offload_index,
)
from .operations import (
    broadcast,
    broadcast_object_list,
    concatenate,
    convert_outputs_to_fpaa,
    convert_to_fpaa,
    find_batch_size,
    find_device,
    gather,
    gather_object,
    get_data_structure,
    honor_type,
    initialize_tensors,
    is_namedtuple,
    is_tensor_information,
    is_torch_tensor,
    listify,
    pad_across_processes,
    recursively_apply,
    reduce,
    send_to_device,
    slice_tensors,
)
from .versions import compare_versions, is_torch_version


if is_deepspeed_available():
		from .deepspeed import (
		    DeepSpeedEngineWrapper,
		    DeepSpeedOptimizerWrapper,
		    DeepSpeedSchedulerWrapper,
		    DummyOptim,
		    DummyScheduler,
		    HfDeepSpeedConfig,
		)

from .bnb import has_abit_bnb_layers, load_and_quantize_model
from .fsdp_utils import load_fsdp_model, load_fsdp_optimizer, save_fsdp_model, save_fsdp_optimizer
from .launch import (
    PrepareForLaunch,
    _filter_args,
    prepare_deepspeed_cmd_env,
    prepare_multi_gpu_env,
    prepare_sagemager_args_inputs,
    prepare_simple_launcher_cmd_env,
    prepare_tpu,
)
from .megatron_lm import (
    AbstractTrainStep,
    BertTrainStep,
    GPTTrainStep,
    MegatronEngine,
    MegatronLMDummyDataLoader,
    MegatronLMDummyScheduler,
    MegatronLMOptimizerWrapper,
    MegatronLMSchedulerWrapper,
    TaTrainStep,
    avg_losses_across_data_parallel_group,
    gather_across_data_parallel_groups,
)
from .megatron_lm import initialize as megatron_lm_initialize
from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader
from .megatron_lm import prepare_model as megatron_lm_prepare_model
from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer
from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler
from .memory import find_executable_batch_size, release_memory
from .other import (
    extract_model_from_parallel,
    get_pretty_name,
    is_port_in_use,
    merge_dicts,
    patch_environment,
    save,
    wait_for_everyone,
    write_basic_config,
)
from .random import set_seed, synchronize_rng_state, synchronize_rng_states
from .torch_xla import install_xla
from .tqdm import tqdm
from .transformer_engine import convert_model, has_transformer_engine_layers