



"""simple docstring"""






import inspect
import unittest

from transformers import ResNetConfig
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, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch
				from torch import nn

				from transformers import ResNetBackbone, ResNetForImageClassification, ResNetModel
				from transformers.models.resnet.modeling_resnet import RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
				from PIL import Image

				from transformers import AutoImageProcessor

class 	__lowerCAmelCase							:


					'''simple docstring'''


					def __init__(      self    ,       a    ,       a=3    ,       a=32    ,       a=3    ,       a=10    ,       a=[10, 20, 30, 40]    ,       a=[1, 1, 2, 1]    ,       a=True    ,       a=True    ,       a="relu"    ,       a=3    ,       a=None    ,       a=["stage2", "stage3", "stage4"]    ,       a=[2, 3, 4]    ,       ):




										"""simple docstring"""





										snake_case_						:int								=						parent
										snake_case_						:Tuple								=						batch_size
										snake_case_						:List[str]								=						image_size
										snake_case_						:str								=						num_channels
										snake_case_						:int								=						embeddings_size
										snake_case_						:Tuple								=						hidden_sizes
										snake_case_						:Tuple								=						depths
										snake_case_						:Optional[Any]								=						is_training
										snake_case_						:Any								=						use_labels
										snake_case_						:Optional[Any]								=						hidden_act
										snake_case_						:Optional[Any]								=						num_labels
										snake_case_						:Dict								=						scope
										snake_case_						:Dict								=						len(a_   )
										snake_case_						:str								=						out_features
										snake_case_						:Tuple								=						out_indices







					def 		_a (      self   ):




										"""simple docstring"""





										snake_case_						:str								=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

										snake_case_						:Dict								=						None
										if self.use_labels:
															snake_case_						:str								=						ids_tensor([self.batch_size]    ,       self.num_labels   )

										snake_case_						:int								=						self.get_config()

										return config, pixel_values, labels







					def 		_a (      self   ):




										"""simple docstring"""





										return ResNetConfig(
										    num_channels=self.num_channels    ,       embeddings_size=self.embeddings_size    ,       hidden_sizes=self.hidden_sizes    ,       depths=self.depths    ,       hidden_act=self.hidden_act    ,       num_labels=self.num_labels    ,       out_features=self.out_features    ,       out_indices=self.out_indices    ,       )







					def 		_a (      self    ,       a    ,       a    ,       a   ):




										"""simple docstring"""





										snake_case_						:List[str]								=						ResNetModel(config=a_   )
										model.to(a_   )
										model.eval()
										snake_case_						:str								=						model(a_   )
										# expected last hidden states: B, C, H // 32, W // 32
										self.parent.assertEqual(
										    result.last_hidden_state.shape    ,       (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)    ,       )







					def 		_a (      self    ,       a    ,       a    ,       a   ):




										"""simple docstring"""





										snake_case_						:List[str]								=						self.num_labels
										snake_case_						:Optional[int]								=						ResNetForImageClassification(a_   )
										model.to(a_   )
										model.eval()
										snake_case_						:Tuple								=						model(a_    ,       labels=a_   )
										self.parent.assertEqual(result.logits.shape    ,       (self.batch_size, self.num_labels)   )







					def 		_a (      self    ,       a    ,       a    ,       a   ):




										"""simple docstring"""





										snake_case_						:int								=						ResNetBackbone(config=a_   )
										model.to(a_   )
										model.eval()
										snake_case_						:Union[str, Any]								=						model(a_   )

										# 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.hidden_sizes[1], 4, 4]   )

										# 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
										snake_case_						:int								=						None
										snake_case_						:int								=						ResNetBackbone(config=a_   )
										model.to(a_   )
										model.eval()
										snake_case_						:List[Any]								=						model(a_   )

										# verify feature maps
										self.parent.assertEqual(len(result.feature_maps   )    ,       1   )
										self.parent.assertListEqual(list(result.feature_maps[0].shape   )    ,       [self.batch_size, self.hidden_sizes[-1], 1, 1]   )

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







					def 		_a (      self   ):




										"""simple docstring"""





										snake_case_						:Optional[int]								=						self.prepare_config_and_inputs()
										snake_case_	,  snake_case_	,  snake_case_						:List[str]								=						config_and_inputs
										snake_case_						:Optional[Any]								=						{"pixel_values": pixel_values}
										return config, inputs_dict



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


					'''simple docstring'''


					a__        =     (
					    (
					        ResNetModel,
					        ResNetForImageClassification,
					        ResNetBackbone,
					    )
					    if is_torch_available()
					    else ()
					)
					a__        =     (
					    {'''feature-extraction''': ResNetModel, '''image-classification''': ResNetForImageClassification}
					    if is_torch_available()
					    else {}
					)

					a__        =     True
					a__        =     False
					a__        =     False
					a__        =     False
					a__        =     False







					def 		_a (      self   ):




										"""simple docstring"""





										snake_case_						:Optional[Any]								=						ResNetModelTester(self   )
										snake_case_						:List[str]								=						ConfigTester(self    ,       config_class=a_    ,       has_text_modality=a_   )







					def 		_a (      self   ):




										"""simple docstring"""





										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 		_a (      self   ):




										"""simple docstring"""





										return







					@unittest.skip(reason="ResNet does not use inputs_embeds"   )
					def 		_a (      self   ):




										"""simple docstring"""





										pass







					@unittest.skip(reason="ResNet does not support input and output embeddings"   )
					def 		_a (      self   ):




										"""simple docstring"""





										pass







					def 		_a (      self   ):




										"""simple docstring"""





										snake_case_	,  snake_case_						:Dict								=						self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
															snake_case_						:List[str]								=						model_class(a_   )
															snake_case_						:List[Any]								=						inspect.signature(model.forward   )
															# signature.parameters is an OrderedDict => so arg_names order is deterministic
															snake_case_						:List[str]								=						[*signature.parameters.keys()]

															snake_case_						:int								=						["pixel_values"]
															self.assertListEqual(arg_names[:1]    ,       a_   )







					def 		_a (      self   ):




										"""simple docstring"""





										snake_case_						:str								=						self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*a_   )







					def 		_a (      self   ):




										"""simple docstring"""





										snake_case_						:Dict								=						self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_backbone(*a_   )







					def 		_a (      self   ):




										"""simple docstring"""





										snake_case_	,  snake_case_						:List[str]								=						self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
															snake_case_						:int								=						model_class(config=a_   )
															for name, module in model.named_modules():
																				if isinstance(a_    ,       (nn.BatchNormad, nn.GroupNorm)   ):
																									self.assertTrue(
																									    torch.all(module.weight == 1   )    ,       msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''    ,       )
																									self.assertTrue(
																									    torch.all(module.bias == 0   )    ,       msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''    ,       )







					def 		_a (      self   ):




										"""simple docstring"""





										def check_hidden_states_output(a    ,       a    ,       a   ):
															snake_case_						:Tuple								=						model_class(a_   )
															model.to(a_   )
															model.eval()

															with torch.no_grad():
																				snake_case_						:List[Any]								=						model(**self._prepare_for_class(a_    ,       a_   )   )

															snake_case_						:Any								=						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

															snake_case_						:Optional[int]								=						self.model_tester.num_stages
															self.assertEqual(len(a_   )    ,       expected_num_stages + 1   )

															# ResNet's feature maps are of shape (batch_size, num_channels, height, width)
															self.assertListEqual(
															    list(hidden_states[0].shape[-2:]   )    ,       [self.model_tester.image_size // 4, self.model_tester.image_size // 4]    ,       )

										snake_case_	,  snake_case_						:Union[str, Any]								=						self.model_tester.prepare_config_and_inputs_for_common()
										snake_case_						:Any								=						["basic", "bottleneck"]
										for model_class in self.all_model_classes:
															for layer_type in layers_type:
																				snake_case_						:List[str]								=						layer_type
																				snake_case_						:Optional[int]								=						True
																				check_hidden_states_output(a_    ,       a_    ,       a_   )

																				# check that output_hidden_states also work using config
																				del inputs_dict["output_hidden_states"]
																				snake_case_						:Optional[Any]								=						True

																				check_hidden_states_output(a_    ,       a_    ,       a_   )







					@unittest.skip(reason="ResNet does not use feedforward chunking"   )
					def 		_a (      self   ):




										"""simple docstring"""





										pass







					def 		_a (      self   ):




										"""simple docstring"""





										snake_case_						:Any								=						self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*a_   )







					@slow
					def 		_a (      self   ):




										"""simple docstring"""





										for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															snake_case_						:Any								=						ResNetModel.from_pretrained(a_   )
															self.assertIsNotNone(a_   )



def      A      (			):




					"""simple docstring"""
					snake_case_						:Dict								=						Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"							)
					return image

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


					'''simple docstring'''


					@cached_property
					def 		_a (      self   ):




										"""simple docstring"""





										return (
										    AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )
										    if is_vision_available()
										    else None
										)







					@slow
					def 		_a (      self   ):




										"""simple docstring"""





										snake_case_						:Any								=						ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]   ).to(a_   )

										snake_case_						:Optional[Any]								=						self.default_image_processor
										snake_case_						:str								=						prepare_img()
										snake_case_						:List[str]								=						image_processor(images=a_    ,       return_tensors="pt"   ).to(a_   )

										# forward pass
										with torch.no_grad():
															snake_case_						:Any								=						model(**a_   )

										# verify the logits
										snake_case_						:List[Any]								=						torch.Size((1, 10_00)   )
										self.assertEqual(outputs.logits.shape    ,       a_   )

										snake_case_						:int								=						torch.tensor([-11.1069, -9.7877, -8.3777]   ).to(a_   )

										self.assertTrue(torch.allclose(outputs.logits[0, :3]    ,       a_    ,       atol=1e-4   )   )



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


					'''simple docstring'''


					a__        =     (ResNetBackbone,) if is_torch_available() else ()
					a__        =     False
					a__        =     ResNetConfig







					def 		_a (      self   ):




										"""simple docstring"""





										snake_case_						:Optional[Any]								=						ResNetModelTester(self   )






"""simple docstring"""






from typing import Any

import numpy as np

class 	__lowerCAmelCase							:


					'''simple docstring'''


					def __init__(      self    ,       a    ,       a   ):




										"""simple docstring"""





										if np.any(tableau[:, -1]    ,       where=tableau[:, -1] < 0   ):
															raise ValueError("RHS must be > 0"   )

										snake_case_						:List[Any]								=						tableau
										snake_case_	,  snake_case_						:Dict								=						tableau.shape

										# Number of decision variables x1, x2, x3...
										snake_case_						:Union[str, Any]								=						n_vars

										# Number of artificial variables to be minimised
										snake_case_						:Tuple								=						len(np.where(tableau[self.n_vars : -1] == -1   )[0]   )

										# 2 if there are >= or == constraints (nonstandard), 1 otherwise (std)
										snake_case_						:List[str]								=						(self.n_art_vars > 0) + 1

										# Number of slack variables added to make inequalities into equalities
										snake_case_						:Optional[int]								=						self.n_rows - self.n_stages

										# Objectives for each stage
										snake_case_						:Union[str, Any]								=						["max"]

										# In two stage simplex, first minimise then maximise
										if self.n_art_vars:
															self.objectives.append("min"   )

										snake_case_						:Dict								=						[""]

										# Index of current pivot row and column
										snake_case_						:List[str]								=						None
										snake_case_						:List[Any]								=						None

										# Does objective row only contain (non)-negative values?
										snake_case_						:Union[str, Any]								=						False







					@staticmethod
					def 		_a (      *a   ):




										"""simple docstring"""





										if len(a   ) != 3:
															raise ValueError("Must provide n_vars, n_slack, and n_art_vars"   )

										if not all(x >= 0 and isinstance(a    ,       a   ) for x in args   ):
															raise ValueError("All arguments must be non-negative integers"   )

										# decision | slack | artificial
										snake_case_						:Tuple								=						["x", "s", "a"]
										snake_case_						:Dict								=						[]
										for i in range(3   ):
															for j in range(args[i]   ):
																				titles.append(string_starts[i] + str(j + 1   )   )
										titles.append("RHS"   )
										return titles







					def 		_a (      self    ,       a   ):




										"""simple docstring"""





										snake_case_						:str								=						self.objectives[-1]

										# Find entries of highest magnitude in objective rows
										snake_case_						:Dict								=						(objective == "min") - (objective == "max")
										snake_case_						:Optional[Any]								=						np.argmax(sign * tableau[0, : self.n_vars]   )

										# Choice is only valid if below 0 for maximise, and above for minimise
										if sign * self.tableau[0, col_idx] <= 0:
															snake_case_						:Dict								=						True
															return 0, 0

										# Pivot row is chosen as having the lowest quotient when elements of
										# the pivot column divide the right-hand side

										# Slice excluding the objective rows
										snake_case_						:str								=						slice(self.n_stages    ,       self.n_rows   )

										# RHS
										snake_case_						:Optional[Any]								=						tableau[s, -1]

										# Elements of pivot column within slice
										snake_case_						:Union[str, Any]								=						tableau[s, col_idx]

										# Array filled with nans
										snake_case_						:Optional[Any]								=						np.full(self.n_rows - self.n_stages    ,       np.nan   )

										# If element in pivot column is greater than zeron_stages, return
										# quotient or nan otherwise
										snake_case_						:Dict								=						np.divide(a    ,       a    ,       out=a    ,       where=divisor > 0   )

										# Arg of minimum quotient excluding the nan values. n_stages is added
										# to compensate for earlier exclusion of objective columns
										snake_case_						:List[Any]								=						np.nanargmin(a   ) + self.n_stages
										return row_idx, col_idx







					def 		_a (      self    ,       a    ,       a    ,       a   ):




										"""simple docstring"""





										snake_case_						:Tuple								=						tableau[row_idx].copy()

										snake_case_						:Any								=						piv_row[col_idx]

										# Entry becomes 1
										piv_row *= 1 / piv_val

										# Variable in pivot column becomes basic, ie the only non-zero entry
										for idx, coeff in enumerate(tableau[:, col_idx]   ):
															tableau[idx] += -coeff * piv_row
										snake_case_						:str								=						piv_row
										return tableau







					def 		_a (      self    ,       a   ):




										"""simple docstring"""





										self.objectives.pop()

										if not self.objectives:
															return tableau

										# Slice containing ids for artificial columns
										snake_case_						:str								=						slice(-self.n_art_vars - 1    ,       -1   )

										# Delete the artificial variable columns
										snake_case_						:Optional[int]								=						np.delete(a    ,       a    ,       axis=1   )

										# Delete the objective row of the first stage
										snake_case_						:List[str]								=						np.delete(a    ,       0    ,       axis=0   )

										snake_case_						:Optional[Any]								=						1
										self.n_rows -= 1
										snake_case_						:List[Any]								=						0
										snake_case_						:Dict								=						False
										return tableau







					def 		_a (      self   ):




										"""simple docstring"""





										for _ in range(1_00   ):
															# Completion of each stage removes an objective. If both stages
															# are complete, then no objectives are left
															if not self.objectives:
																				snake_case_						:str								=						self.generate_col_titles(
																				    self.n_vars    ,       self.n_slack    ,       self.n_art_vars   )

																				# Find the values of each variable at optimal solution
																				return self.interpret_tableau(self.tableau    ,       self.col_titles   )

															snake_case_	,  snake_case_						:Union[str, Any]								=						self.find_pivot(self.tableau   )

															# If there are no more negative values in objective row
															if self.stop_iter:
																				# Delete artificial variable columns and rows. Update attributes
																				snake_case_						:str								=						self.change_stage(self.tableau   )
															else:
																				snake_case_						:str								=						self.pivot(self.tableau    ,       a    ,       a   )
										return {}







					def 		_a (      self    ,       a    ,       a   ):




										"""simple docstring"""





										snake_case_						:Any								=						{"P": abs(tableau[0, -1]   )}

										for i in range(self.n_vars   ):
															# Gives ids of nonzero entries in the ith column
															snake_case_						:Dict								=						np.nonzero(tableau[:, i]   )
															snake_case_						:Tuple								=						len(nonzero[0]   )

															# First entry in the nonzero ids
															snake_case_						:Any								=						nonzero[0][0]
															snake_case_						:int								=						tableau[nonzero_rowidx, i]

															# If there is only one nonzero value in column, which is one
															if n_nonzero == nonzero_val == 1:
																				snake_case_						:Tuple								=						tableau[nonzero_rowidx, -1]
																				snake_case_						:Tuple								=						rhs_val

        # Check for basic variables
										for title in col_titles:
															# Don't add RHS or slack variables to output dict
															if title[0] not in "R-s-a":
																				output_dict.setdefault(a    ,       0   )
										return output_dict


if __name__ == "__main__":
				import doctest

				doctest.testmod()

