

import logging

import torch
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss

from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward
from transformers.models.albert.modeling_albert import (
    ALBERT_INPUTS_DOCSTRING,
    ALBERT_START_DOCSTRING,
    AlbertModel,
    AlbertPreTrainedModel,
    AlbertTransformer,
)


SCREAMING_SNAKE_CASE_						=					logging.getLogger(__name__)

class  a     (		UpperCAmelCase ):


						def 				_UpperCAmelCase (				self  ,    A_  ,    A_  ,    A_=None  ,    A_=None		):







										'''simple docstring'''


										if current_layer == 0:
														_UpperCAmelCase				:						Tuple       						=			self.embedding_hidden_mapping_in(A_		)
										else:
														_UpperCAmelCase				:						int       						=			hidden_states[0]

										_UpperCAmelCase				:						int       						=			int(self.config.num_hidden_layers / self.config.num_hidden_groups		)

										# Index of the hidden group
										_UpperCAmelCase				:						Union[str, Any]       						=			int(current_layer / (self.config.num_hidden_layers / self.config.num_hidden_groups)		)

										_UpperCAmelCase				:						Dict       						=			self.albert_layer_groups[group_idx](
										    A_  ,    A_  ,    head_mask[group_idx * layers_per_group : (group_idx + 1) * layers_per_group]  ,    )
										_UpperCAmelCase				:						List[str]       						=			layer_group_output[0]

										return (hidden_states,)







@add_start_docstrings(
    "The bare ALBERT Model transformer with PABEE outputting raw hidden-states without any specific head on top."							,       UpperCAmelCase							,       )
class  a     (		UpperCAmelCase ):


						def __init__(				self  ,    A_		):







										'''simple docstring'''


										super().__init__(A_		)

										_UpperCAmelCase				:						Optional[Any]       						=			AlbertTransformerWithPabee(A_		)

										self.init_weights()
										_UpperCAmelCase				:						List[str]       						=			0
										_UpperCAmelCase				:						str       						=			0
										_UpperCAmelCase				:						Union[str, Any]       						=			0

										_UpperCAmelCase				:						Dict       						=			0


						def 				_UpperCAmelCase (				self  ,    A_		):







										'''simple docstring'''


										_UpperCAmelCase				:						Optional[int]       						=			threshold


						def 				_UpperCAmelCase (				self  ,    A_		):







										'''simple docstring'''


										_UpperCAmelCase				:						Dict       						=			patience


						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						Dict       						=			0
										_UpperCAmelCase				:						Union[str, Any]       						=			0


						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						Any       						=			self.inference_layers_num / self.inference_instances_num
										_UpperCAmelCase				:						Optional[Any]       						=			(
										    f'*** Patience = {self.patience} Avg. Inference Layers = {avg_inf_layers:.2f} Speed Up ='
										    f' {1 - avg_inf_layers / self.config.num_hidden_layers:.2f} ***'
										)
										print(A_		)





						@add_start_docstrings_to_model_forward(A_		)
						def 				_UpperCAmelCase (				self  ,    A_=None  ,    A_=None  ,    A_=None  ,    A_=None  ,    A_=None  ,    A_=None  ,    A_=None  ,    A_=None  ,    A_=False  ,    ):







										'''simple docstring'''


										if input_ids is not None and inputs_embeds is not None:
														raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time"		)
										elif input_ids is not None:
														_UpperCAmelCase				:						Any       						=			input_ids.size()
										elif inputs_embeds is not None:
														_UpperCAmelCase				:						Any       						=			inputs_embeds.size()[:-1]
										else:
														raise ValueError("You have to specify either input_ids or inputs_embeds"		)

										_UpperCAmelCase				:						Optional[int]       						=			input_ids.device if input_ids is not None else inputs_embeds.device

										if attention_mask is None:
														_UpperCAmelCase				:						List[str]       						=			torch.ones(A_  ,    device=A_		)
										if token_type_ids is None:
														_UpperCAmelCase				:						List[str]       						=			torch.zeros(A_  ,    dtype=torch.long  ,    device=A_		)

										_UpperCAmelCase				:						Optional[int]       						=			attention_mask.unsqueeze(1		).unsqueeze(2		)
										_UpperCAmelCase				:						Optional[int]       						=			extended_attention_mask.to(dtype=self.dtype		)  # fp16 compatibility
										_UpperCAmelCase				:						List[str]       						=			(1.0 - extended_attention_mask) * -1_00_00.0
										_UpperCAmelCase				:						str       						=			self.get_head_mask(A_  ,    self.config.num_hidden_layers		)

										_UpperCAmelCase				:						List[Any]       						=			self.embeddings(
										    A_  ,    position_ids=A_  ,    token_type_ids=A_  ,    inputs_embeds=A_		)
										_UpperCAmelCase				:						str       						=			embedding_output

										if self.training:
														_UpperCAmelCase				:						Any       						=			[]
														for i in range(self.config.num_hidden_layers		):
																		_UpperCAmelCase				:						Tuple       						=			self.encoder.adaptive_forward(
																		    A_  ,    current_layer=A_  ,    attention_mask=A_  ,    head_mask=A_  ,    )

																		_UpperCAmelCase				:						Any       						=			self.pooler_activation(self.pooler(encoder_outputs[0][:, 0]		)		)
																		_UpperCAmelCase				:						List[Any]       						=			output_layers[i](output_dropout(A_		)		)
																		res.append(A_		)
										elif self.patience == 0:  # Use all layers for inference
														_UpperCAmelCase				:						List[str]       						=			self.encoder(A_  ,    A_  ,    head_mask=A_		)
														_UpperCAmelCase				:						Optional[Any]       						=			self.pooler_activation(self.pooler(encoder_outputs[0][:, 0]		)		)
														_UpperCAmelCase				:						Union[str, Any]       						=			[output_layers[self.config.num_hidden_layers - 1](A_		)]
										else:
														_UpperCAmelCase				:						int       						=			0
														_UpperCAmelCase				:						List[Any]       						=			None
														_UpperCAmelCase				:						Dict       						=			0
														for i in range(self.config.num_hidden_layers		):
																		calculated_layer_num += 1
																		_UpperCAmelCase				:						Any       						=			self.encoder.adaptive_forward(
																		    A_  ,    current_layer=A_  ,    attention_mask=A_  ,    head_mask=A_  ,    )

																		_UpperCAmelCase				:						Optional[Any]       						=			self.pooler_activation(self.pooler(encoder_outputs[0][:, 0]		)		)
																		_UpperCAmelCase				:						Union[str, Any]       						=			output_layers[i](A_		)
																		if regression:
																						_UpperCAmelCase				:						Tuple       						=			logits.detach()
																						if patient_result is not None:
																										_UpperCAmelCase				:						str       						=			patient_result.detach()
																						if (patient_result is not None) and torch.abs(patient_result - labels		) < self.regression_threshold:
																										patient_counter += 1
																						else:
																										_UpperCAmelCase				:						Union[str, Any]       						=			0
																		else:
																						_UpperCAmelCase				:						int       						=			logits.detach().argmax(dim=1		)
																						if patient_result is not None:
																										_UpperCAmelCase				:						Any       						=			patient_result.detach().argmax(dim=1		)
																						if (patient_result is not None) and torch.all(labels.eq(A_		)		):
																										patient_counter += 1
																						else:
																										_UpperCAmelCase				:						Tuple       						=			0

																		_UpperCAmelCase				:						Dict       						=			logits
																		if patient_counter == self.patience:
																						break
														_UpperCAmelCase				:						List[str]       						=			[patient_result]
														self.inference_layers_num += calculated_layer_num
														self.inference_instances_num += 1

										return res







@add_start_docstrings(
    "Albert Model transformer with PABEE and a sequence classification/regression head on top (a linear layer on top of\n    the pooled output) e.g. for GLUE tasks. "							,       UpperCAmelCase							,       )
class  a     (		UpperCAmelCase ):


						def __init__(				self  ,    A_		):







										'''simple docstring'''


										super().__init__(A_		)
										_UpperCAmelCase				:						Optional[int]       						=			config.num_labels

										_UpperCAmelCase				:						str       						=			AlbertModelWithPabee(A_		)
										_UpperCAmelCase				:						Dict       						=			nn.Dropout(config.classifier_dropout_prob		)
										_UpperCAmelCase				:						Optional[Any]       						=			nn.ModuleList(
										    [nn.Linear(config.hidden_size  ,    self.config.num_labels		) for _ in range(config.num_hidden_layers		)]		)

										self.init_weights()





						@add_start_docstrings_to_model_forward(A_		)
						def 				_UpperCAmelCase (				self  ,    A_=None  ,    A_=None  ,    A_=None  ,    A_=None  ,    A_=None  ,    A_=None  ,    A_=None  ,    ):







										'''simple docstring'''


										_UpperCAmelCase				:						str       						=			self.albert(
										    input_ids=A_  ,    attention_mask=A_  ,    token_type_ids=A_  ,    position_ids=A_  ,    head_mask=A_  ,    inputs_embeds=A_  ,    output_dropout=self.dropout  ,    output_layers=self.classifiers  ,    regression=self.num_labels == 1  ,    )

										_UpperCAmelCase				:						Optional[Any]       						=			(logits[-1],)

										if labels is not None:
														_UpperCAmelCase				:						Tuple       						=			None
														_UpperCAmelCase				:						Tuple       						=			0
														for ix, logits_item in enumerate(A_		):
																		if self.num_labels == 1:
																						#  We are doing regression
																						_UpperCAmelCase				:						List[Any]       						=			MSELoss()
																						_UpperCAmelCase				:						List[str]       						=			loss_fct(logits_item.view(-1		)  ,    labels.view(-1		)		)
																		else:
																						_UpperCAmelCase				:						str       						=			CrossEntropyLoss()
																						_UpperCAmelCase				:						int       						=			loss_fct(logits_item.view(-1  ,    self.num_labels		)  ,    labels.view(-1		)		)
																		if total_loss is None:
																						_UpperCAmelCase				:						Dict       						=			loss
																		else:
																						total_loss += loss * (ix + 1)
																		total_weights += ix + 1
														_UpperCAmelCase				:						List[str]       						=			(total_loss / total_weights,) + outputs

										return outputs





import unittest

from transformers import (
    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    PreTrainedTokenizer,
    is_vision_available,
)
from transformers.pipelines import ImageClassificationPipeline, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_torch_or_tf,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
					from PIL import Image
else:

					class  a     :


											@staticmethod
											def 				_UpperCAmelCase (				*A_  ,    **A_		):







															'''simple docstring'''


															pass

@is_pipeline_test
@require_torch_or_tf
@require_vision
class  a     (		unittest.TestCase ):
						_lowercase			  =	MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
						_lowercase			  =	TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING


						def 				_UpperCAmelCase (				self  ,    A_  ,    A_  ,    A_		):







										'''simple docstring'''


										_UpperCAmelCase				:						Any       						=			ImageClassificationPipeline(model=A_  ,    image_processor=A_  ,    top_k=2		)
										_UpperCAmelCase				:						Optional[Any]       						=			[
										    Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"		),
										    "http://images.cocodataset.org/val2017/000000039769.jpg",
										]
										return image_classifier, examples


						def 				_UpperCAmelCase (				self  ,    A_  ,    A_		):







										'''simple docstring'''


										_UpperCAmelCase				:						Tuple       						=			image_classifier("./tests/fixtures/tests_samples/COCO/000000039769.png"		)

										self.assertEqual(
										    A_  ,    [
										        {"score": ANY(A_		), "label": ANY(A_		)},
										        {"score": ANY(A_		), "label": ANY(A_		)},
										    ]  ,    )

										import datasets

										_UpperCAmelCase				:						int       						=			datasets.load_dataset("hf-internal-testing/fixtures_image_utils"  ,    "image"  ,    split="test"		)

										# Accepts URL + PIL.Image + lists
										_UpperCAmelCase				:						Any       						=			image_classifier(
										    [
										        Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"		),
										        "http://images.cocodataset.org/val2017/000000039769.jpg",
										        # RGBA
										        dataset[0]["file"],
										        # LA
										        dataset[1]["file"],
										        # L
										        dataset[2]["file"],
										    ]		)
										self.assertEqual(
										    A_  ,    [
										        [
										            {"score": ANY(A_		), "label": ANY(A_		)},
										            {"score": ANY(A_		), "label": ANY(A_		)},
										        ],
										        [
										            {"score": ANY(A_		), "label": ANY(A_		)},
										            {"score": ANY(A_		), "label": ANY(A_		)},
										        ],
										        [
										            {"score": ANY(A_		), "label": ANY(A_		)},
										            {"score": ANY(A_		), "label": ANY(A_		)},
										        ],
										        [
										            {"score": ANY(A_		), "label": ANY(A_		)},
										            {"score": ANY(A_		), "label": ANY(A_		)},
										        ],
										        [
										            {"score": ANY(A_		), "label": ANY(A_		)},
										            {"score": ANY(A_		), "label": ANY(A_		)},
										        ],
										    ]  ,    )


						@require_torch
						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						Any       						=			"hf-internal-testing/tiny-random-vit"
										_UpperCAmelCase				:						List[Any]       						=			pipeline("image-classification"  ,    model=A_		)

										_UpperCAmelCase				:						Optional[int]       						=			image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg"		)
										self.assertEqual(
										    nested_simplify(A_  ,    decimals=4		)  ,    [{"label": "LABEL_1", "score": 0.5_74}, {"label": "LABEL_0", "score": 0.4_26}]  ,    )

										_UpperCAmelCase				:						List[str]       						=			image_classifier(
										    [
										        "http://images.cocodataset.org/val2017/000000039769.jpg",
										        "http://images.cocodataset.org/val2017/000000039769.jpg",
										    ]  ,    top_k=2  ,    )
										self.assertEqual(
										    nested_simplify(A_  ,    decimals=4		)  ,    [
										        [{"label": "LABEL_1", "score": 0.5_74}, {"label": "LABEL_0", "score": 0.4_26}],
										        [{"label": "LABEL_1", "score": 0.5_74}, {"label": "LABEL_0", "score": 0.4_26}],
										    ]  ,    )


						@require_tf
						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						int       						=			"hf-internal-testing/tiny-random-vit"
										_UpperCAmelCase				:						List[Any]       						=			pipeline("image-classification"  ,    model=A_  ,    framework="tf"		)

										_UpperCAmelCase				:						Union[str, Any]       						=			image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg"		)
										self.assertEqual(
										    nested_simplify(A_  ,    decimals=4		)  ,    [{"label": "LABEL_1", "score": 0.5_74}, {"label": "LABEL_0", "score": 0.4_26}]  ,    )

										_UpperCAmelCase				:						Optional[int]       						=			image_classifier(
										    [
										        "http://images.cocodataset.org/val2017/000000039769.jpg",
										        "http://images.cocodataset.org/val2017/000000039769.jpg",
										    ]  ,    top_k=2  ,    )
										self.assertEqual(
										    nested_simplify(A_  ,    decimals=4		)  ,    [
										        [{"label": "LABEL_1", "score": 0.5_74}, {"label": "LABEL_0", "score": 0.4_26}],
										        [{"label": "LABEL_1", "score": 0.5_74}, {"label": "LABEL_0", "score": 0.4_26}],
										    ]  ,    )


						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						Optional[Any]       						=			PreTrainedTokenizer()

										# Assert that the pipeline can be initialized with a feature extractor that is not in any mapping
										_UpperCAmelCase				:						int       						=			pipeline(
										    "image-classification"  ,    model="hf-internal-testing/tiny-random-vit"  ,    tokenizer=A_		)

										self.assertIs(image_classifier.tokenizer  ,    A_		)





						@slow
						@require_torch
						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						Dict       						=			pipeline("image-classification"  ,    model="deepmind/vision-perceiver-conv"		)
										_UpperCAmelCase				:						Union[str, Any]       						=			image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg"		)
										self.assertEqual(
										    nested_simplify(A_  ,    decimals=4		)  ,    [
										        {"score": 0.43_85, "label": "tabby, tabby cat"},
										        {"score": 0.3_21, "label": "tiger cat"},
										        {"score": 0.05_02, "label": "Egyptian cat"},
										        {"score": 0.01_37, "label": "crib, cot"},
										        {"score": 0.0_07, "label": "radiator"},
										    ]  ,    )

										_UpperCAmelCase				:						str       						=			pipeline("image-classification"  ,    model="deepmind/vision-perceiver-fourier"		)
										_UpperCAmelCase				:						Optional[int]       						=			image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg"		)
										self.assertEqual(
										    nested_simplify(A_  ,    decimals=4		)  ,    [
										        {"score": 0.56_58, "label": "tabby, tabby cat"},
										        {"score": 0.13_09, "label": "tiger cat"},
										        {"score": 0.07_22, "label": "Egyptian cat"},
										        {"score": 0.07_07, "label": "remote control, remote"},
										        {"score": 0.00_82, "label": "computer keyboard, keypad"},
										    ]  ,    )

										_UpperCAmelCase				:						List[Any]       						=			pipeline("image-classification"  ,    model="deepmind/vision-perceiver-learned"		)
										_UpperCAmelCase				:						str       						=			image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg"		)
										self.assertEqual(
										    nested_simplify(A_  ,    decimals=4		)  ,    [
										        {"score": 0.30_22, "label": "tabby, tabby cat"},
										        {"score": 0.23_62, "label": "Egyptian cat"},
										        {"score": 0.18_56, "label": "tiger cat"},
										        {"score": 0.03_24, "label": "remote control, remote"},
										        {"score": 0.00_96, "label": "quilt, comforter, comfort, puff"},
										    ]  ,    )


