
import collections.abc
from typing import Optional, Tuple, Union

import torch
import torch.utils.checkpoint
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_poolformer import PoolFormerConfig


lowerCamelCase_    :			Optional[int]    =	logging.get_logger(__name__)

# General docstring
lowerCamelCase_    :			Any    =	"""PoolFormerConfig"""

# Base docstring
lowerCamelCase_    :			Optional[Any]    =	"""sail/poolformer_s12"""
lowerCamelCase_    :			List[Any]    =	[1, 5_12, 7, 7]

# Image classification docstring
lowerCamelCase_    :			Tuple    =	"""sail/poolformer_s12"""
lowerCamelCase_    :			Dict    =	"""tabby, tabby cat"""

lowerCamelCase_    :			Any    =	[
    """sail/poolformer_s12""",
    # See all PoolFormer models at https://huggingface.co/models?filter=poolformer
]







def 							A__       (    lowerCamelCase  ,     lowerCamelCase = 0.0  ,     lowerCamelCase = False    )	->						Optional[Any]:
				if drop_prob == 0.0 or not training:
								return input
				UpperCamelCase_:				Tuple						=    1 - drop_prob
				UpperCamelCase_:				Dict						=    (input.shape[0],) + (1,) * (input.ndim - 1)  # work with diff dim tensors, not just 2D ConvNets
				UpperCamelCase_:				Optional[int]						=    keep_prob + torch.rand(lowerCamelCase  ,     dtype=input.dtype  ,     device=input.device    )
				random_tensor.floor_()  # binarize
				UpperCamelCase_:				int						=    input.div(lowerCamelCase    ) * random_tensor
				return output

class 							_UpperCamelCase					(       nn.Module	):






			'''simple docstring'''

			def __init__(							self			:							Union[str, Any]    ,						snake_case_			:							Optional[float] = None   ):
							super().__init__()
							UpperCamelCase_:				int						=    drop_prob

			def    lowerCAmelCase__						(							self			:							Tuple    ,						snake_case_			:							torch.Tensor   ):
							return drop_path(snake_case_    ,						self.drop_prob    ,						self.training   )




			def    lowerCAmelCase__						(							self			:							Dict   ):
							return "p={}".format(self.drop_prob   )




class 							_UpperCamelCase					(       nn.Module	):






			'''simple docstring'''

			def __init__(							self			:							Any    ,						snake_case_			:							int    ,						snake_case_			:							Union[str, Any]    ,						snake_case_			:							List[Any]    ,						snake_case_			:							List[str]    ,						snake_case_			:							Optional[Any]    ,						snake_case_			:							List[str]=None   ):
							super().__init__()
							UpperCamelCase_:				Any						=    patch_size if isinstance(snake_case_    ,						collections.abc.Iterable   ) else (patch_size, patch_size)
							UpperCamelCase_:				int						=    stride if isinstance(snake_case_    ,						collections.abc.Iterable   ) else (stride, stride)
							UpperCamelCase_:				str						=    padding if isinstance(snake_case_    ,						collections.abc.Iterable   ) else (padding, padding)

							UpperCamelCase_:				str						=    nn.Convad(snake_case_    ,						snake_case_    ,						kernel_size=snake_case_    ,						stride=snake_case_    ,						padding=snake_case_   )
							UpperCamelCase_:				str						=    norm_layer(snake_case_   ) if norm_layer else nn.Identity()




			def    lowerCAmelCase__						(							self			:							int    ,						snake_case_			:							str   ):
							UpperCamelCase_:				str						=    self.projection(snake_case_   )
							UpperCamelCase_:				Optional[Any]						=    self.norm(snake_case_   )
							return embeddings




class 							_UpperCamelCase					(       nn.GroupNorm	):






			'''simple docstring'''

			def __init__(							self			:							Optional[int]    ,						snake_case_			:							List[Any]    ,						**snake_case_			:							int   ):
							super().__init__(1    ,						snake_case_    ,						**snake_case_   )




class 							_UpperCamelCase					(       nn.Module	):






			'''simple docstring'''

			def __init__(							self			:							Union[str, Any]    ,						snake_case_			:							str   ):
							super().__init__()
							UpperCamelCase_:				Optional[int]						=    nn.AvgPoolad(snake_case_    ,						stride=1    ,						padding=pool_size // 2    ,						count_include_pad=snake_case_   )




			def    lowerCAmelCase__						(							self			:							List[str]    ,						snake_case_			:							Union[str, Any]   ):
							return self.pool(snake_case_   ) - hidden_states




class 							_UpperCamelCase					(       nn.Module	):






			'''simple docstring'''

			def __init__(							self			:							Optional[Any]    ,						snake_case_			:							Tuple    ,						snake_case_			:							Dict    ,						snake_case_			:							str    ,						snake_case_			:							int   ):
							super().__init__()
							UpperCamelCase_:				str						=    nn.Convad(snake_case_    ,						snake_case_    ,						1   )
							UpperCamelCase_:				List[str]						=    nn.Convad(snake_case_    ,						snake_case_    ,						1   )
							UpperCamelCase_:				Any						=    PoolFormerDropPath(snake_case_   )
							if isinstance(config.hidden_act    ,						snake_case_   ):
											UpperCamelCase_:				Dict						=    ACTaFN[config.hidden_act]
							else:
											UpperCamelCase_:				List[str]						=    config.hidden_act




			def    lowerCAmelCase__						(							self			:							Tuple    ,						snake_case_			:							Optional[int]   ):
							UpperCamelCase_:				Dict						=    self.conva(snake_case_   )
							UpperCamelCase_:				Optional[Any]						=    self.act_fn(snake_case_   )
							UpperCamelCase_:				Optional[int]						=    self.drop(snake_case_   )
							UpperCamelCase_:				Tuple						=    self.conva(snake_case_   )
							UpperCamelCase_:				int						=    self.drop(snake_case_   )

							return hidden_states




class 							_UpperCamelCase					(       nn.Module	):






			'''simple docstring'''

			def __init__(							self			:							Union[str, Any]    ,						snake_case_			:							Optional[int]    ,						snake_case_			:							Optional[Any]    ,						snake_case_			:							str    ,						snake_case_			:							Optional[Any]    ,						snake_case_			:							List[Any]    ,						snake_case_			:							Optional[int]   ):
							super().__init__()
							UpperCamelCase_:				str						=    PoolFormerPooling(snake_case_   )
							UpperCamelCase_:				Union[str, Any]						=    PoolFormerOutput(snake_case_    ,						snake_case_    ,						snake_case_    ,						snake_case_   )
							UpperCamelCase_:				List[str]						=    PoolFormerGroupNorm(snake_case_   )
							UpperCamelCase_:				Optional[int]						=    PoolFormerGroupNorm(snake_case_   )

							# Useful for training neural nets
							UpperCamelCase_:				Dict						=    PoolFormerDropPath(snake_case_   ) if drop_path > 0.0 else nn.Identity()
							UpperCamelCase_:				Dict						=    config.use_layer_scale
							if config.use_layer_scale:
											UpperCamelCase_:				int						=    nn.Parameter(
											    config.layer_scale_init_value * torch.ones((snake_case_)   )    ,						requires_grad=snake_case_   )
											UpperCamelCase_:				Optional[Any]						=    nn.Parameter(
											    config.layer_scale_init_value * torch.ones((snake_case_)   )    ,						requires_grad=snake_case_   )




			def    lowerCAmelCase__						(							self			:							Optional[int]    ,						snake_case_			:							Optional[Any]   ):
							if self.use_layer_scale:
											UpperCamelCase_:				Dict						=    self.pooling(self.before_norm(snake_case_   )   )
											UpperCamelCase_:				Tuple						=    self.layer_scale_a.unsqueeze(-1   ).unsqueeze(-1   ) * pooling_output
											# First residual connection
											UpperCamelCase_:				str						=    hidden_states + self.drop_path(snake_case_   )
											UpperCamelCase_:				Dict						=    ()

											UpperCamelCase_:				Optional[Any]						=    self.output(self.after_norm(snake_case_   )   )
											UpperCamelCase_:				Tuple						=    self.layer_scale_a.unsqueeze(-1   ).unsqueeze(-1   ) * layer_output
											# Second residual connection
											UpperCamelCase_:				Optional[Any]						=    hidden_states + self.drop_path(snake_case_   )

											UpperCamelCase_:				Union[str, Any]						=    (output,) + outputs
											return outputs

							else:
											UpperCamelCase_:				int						=    self.drop_path(self.pooling(self.before_norm(snake_case_   )   )   )
											# First residual connection
											UpperCamelCase_:				List[str]						=    pooling_output + hidden_states
											UpperCamelCase_:				List[str]						=    ()

											# Second residual connection inside the PoolFormerOutput block
											UpperCamelCase_:				Any						=    self.drop_path(self.output(self.after_norm(snake_case_   )   )   )
											UpperCamelCase_:				str						=    hidden_states + layer_output

											UpperCamelCase_:				Optional[int]						=    (output,) + outputs
											return outputs




class 							_UpperCamelCase					(       nn.Module	):






			'''simple docstring'''

			def __init__(							self			:							Dict    ,						snake_case_			:							Optional[int]   ):
							super().__init__()
							UpperCamelCase_:				Dict						=    config
							# stochastic depth decay rule
							UpperCamelCase_:				Tuple						=    [x.item() for x in torch.linspace(0    ,						config.drop_path_rate    ,						sum(config.depths   )   )]

							# patch embeddings
							UpperCamelCase_:				Any						=    []
							for i in range(config.num_encoder_blocks   ):
											embeddings.append(
											    PoolFormerEmbeddings(
											        patch_size=config.patch_sizes[i]    ,						stride=config.strides[i]    ,						padding=config.padding[i]    ,						num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1]    ,						hidden_size=config.hidden_sizes[i]    ,						)   )
							UpperCamelCase_:				str						=    nn.ModuleList(snake_case_   )

							# Transformer blocks
							UpperCamelCase_:				List[Any]						=    []
							UpperCamelCase_:				Optional[Any]						=    0
							for i in range(config.num_encoder_blocks   ):
											# each block consists of layers
											UpperCamelCase_:				Tuple						=    []
											if i != 0:
															cur += config.depths[i - 1]
											for j in range(config.depths[i]   ):
															layers.append(
															    PoolFormerLayer(
															        snake_case_    ,						num_channels=config.hidden_sizes[i]    ,						pool_size=config.pool_size    ,						hidden_size=config.hidden_sizes[i]    ,						intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio   )    ,						drop_path=dpr[cur + j]    ,						)   )
											blocks.append(nn.ModuleList(snake_case_   )   )

							UpperCamelCase_:				List[str]						=    nn.ModuleList(snake_case_   )




			def    lowerCAmelCase__						(							self			:							Tuple    ,						snake_case_			:							int    ,						snake_case_			:							Optional[int]=False    ,						snake_case_			:							str=True   ):
							UpperCamelCase_:				Union[str, Any]						=    () if output_hidden_states else None

							UpperCamelCase_:				Any						=    pixel_values
							for idx, layers in enumerate(zip(self.patch_embeddings    ,						self.block   )   ):
											UpperCamelCase_, UpperCamelCase_:				Optional[Any]						=    layers
											# Get patch embeddings from hidden_states
											UpperCamelCase_:				Union[str, Any]						=    embedding_layer(snake_case_   )
											# Send the embeddings through the blocks
											for _, blk in enumerate(snake_case_   ):
															UpperCamelCase_:				Dict						=    blk(snake_case_   )
															UpperCamelCase_:				int						=    layer_outputs[0]

											if output_hidden_states:
															UpperCamelCase_:				Optional[int]						=    all_hidden_states + (hidden_states,)

							if not return_dict:
											return tuple(v for v in [hidden_states, all_hidden_states] if v is not None   )

							return BaseModelOutputWithNoAttention(last_hidden_state=snake_case_    ,						hidden_states=snake_case_   )




class 							_UpperCamelCase					(       _A	):






			'''simple docstring'''

			__UpperCamelCase   :    Any          =			PoolFormerConfig
			__UpperCamelCase   :    Optional[int]          =			"""poolformer"""
			__UpperCamelCase   :    Union[str, Any]          =			"""pixel_values"""
			__UpperCamelCase   :    Union[str, Any]          =			True

			def    lowerCAmelCase__						(							self			:							List[str]    ,						snake_case_			:							List[str]   ):
							if isinstance(snake_case_    ,						(nn.Linear, nn.Convad)   ):
											module.weight.data.normal_(mean=0.0    ,						std=self.config.initializer_range   )
											if module.bias is not None:
															module.bias.data.zero_()
							elif isinstance(snake_case_    ,						nn.LayerNorm   ):
											module.bias.data.zero_()
											module.weight.data.fill_(1.0   )




			def    lowerCAmelCase__						(							self			:							int    ,						snake_case_			:							Tuple    ,						snake_case_			:							Union[str, Any]=False   ):
							if isinstance(snake_case_    ,						snake_case_   ):
											UpperCamelCase_:				Optional[int]						=    value




lowerCamelCase_    :			Dict    =	r"""
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""

lowerCamelCase_    :			Union[str, Any]    =	r"""
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`PoolFormerImageProcessor.__call__`] for details.
"""

@add_start_docstrings(
    """The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top."""  ,							_A  ,							)
class 							_UpperCamelCase					(       _A	):






			'''simple docstring'''

			def __init__(							self			:							Optional[int]    ,						snake_case_			:							Dict   ):
							super().__init__(snake_case_   )
							UpperCamelCase_:				Optional[Any]						=    config

							UpperCamelCase_:				str						=    PoolFormerEncoder(snake_case_   )

							# Initialize weights and apply final processing
							self.post_init()

			def    lowerCAmelCase__						(							self			:							Union[str, Any]   ):
							return self.embeddings.patch_embeddings




			@add_start_docstrings_to_model_forward(snake_case_   )
			@add_code_sample_docstrings(
			    checkpoint=_CHECKPOINT_FOR_DOC    ,						output_type=snake_case_    ,						config_class=_CONFIG_FOR_DOC    ,						modality="""vision"""    ,						expected_output=_EXPECTED_OUTPUT_SHAPE    ,						)
			def    lowerCAmelCase__						(							self			:							Optional[int]    ,						snake_case_			:							Optional[torch.FloatTensor] = None    ,						snake_case_			:							Optional[bool] = None    ,						snake_case_			:							Optional[bool] = None    ,						):
							UpperCamelCase_:				Tuple						=    (
							    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
							)
							UpperCamelCase_:				Union[str, Any]						=    return_dict if return_dict is not None else self.config.use_return_dict

							if pixel_values is None:
											raise ValueError("""You have to specify pixel_values"""   )

							UpperCamelCase_:				str						=    self.encoder(
							    snake_case_    ,						output_hidden_states=snake_case_    ,						return_dict=snake_case_    ,						)
							UpperCamelCase_:				List[str]						=    encoder_outputs[0]

							if not return_dict:
											return (sequence_output, None) + encoder_outputs[1:]

							return BaseModelOutputWithNoAttention(
							    last_hidden_state=snake_case_    ,						hidden_states=encoder_outputs.hidden_states    ,						)




class 							_UpperCamelCase					(       nn.Module	):






			'''simple docstring'''

			def __init__(							self			:							Union[str, Any]    ,						snake_case_			:							Any   ):
							super().__init__()
							UpperCamelCase_:				Optional[int]						=    nn.Linear(config.hidden_size    ,						config.hidden_size   )




			def    lowerCAmelCase__						(							self			:							Optional[int]    ,						snake_case_			:							Optional[int]   ):
							UpperCamelCase_:				Dict						=    self.dense(snake_case_   )
							return output




@add_start_docstrings(
    """
    PoolFormer Model transformer with an image classification head on top
    """  ,							_A  ,							)
class 							_UpperCamelCase					(       _A	):






			'''simple docstring'''

			def __init__(							self			:							Optional[int]    ,						snake_case_			:							Dict   ):
							super().__init__(snake_case_   )
							UpperCamelCase_:				Tuple						=    config.num_labels
							UpperCamelCase_:				List[Any]						=    PoolFormerModel(snake_case_   )

							# Final norm
							UpperCamelCase_:				List[str]						=    PoolFormerGroupNorm(config.hidden_sizes[-1]   )
							# Classifier head
							UpperCamelCase_:				str						=    (
							    nn.Linear(config.hidden_sizes[-1]    ,						config.num_labels   ) if config.num_labels > 0 else nn.Identity()
							)

							# Initialize weights and apply final processing
							self.post_init()




			@add_start_docstrings_to_model_forward(snake_case_   )
			@add_code_sample_docstrings(
			    checkpoint=_IMAGE_CLASS_CHECKPOINT    ,						output_type=snake_case_    ,						config_class=_CONFIG_FOR_DOC    ,						expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT    ,						)
			def    lowerCAmelCase__						(							self			:							Tuple    ,						snake_case_			:							Optional[torch.FloatTensor] = None    ,						snake_case_			:							Optional[torch.LongTensor] = None    ,						snake_case_			:							Optional[bool] = None    ,						snake_case_			:							Optional[bool] = None    ,						):
							UpperCamelCase_:				Optional[Any]						=    return_dict if return_dict is not None else self.config.use_return_dict

							UpperCamelCase_:				Dict						=    self.poolformer(
							    snake_case_    ,						output_hidden_states=snake_case_    ,						return_dict=snake_case_    ,						)

							UpperCamelCase_:				Tuple						=    outputs[0]

							UpperCamelCase_:				Union[str, Any]						=    self.classifier(self.norm(snake_case_   ).mean([-2, -1]   )   )

							UpperCamelCase_:				Tuple						=    None
							if labels is not None:
											if self.config.problem_type is None:
															if self.num_labels == 1:
																			UpperCamelCase_:				Optional[Any]						=    """regression"""
															elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
																			UpperCamelCase_:				Dict						=    """single_label_classification"""
															else:
																			UpperCamelCase_:				str						=    """multi_label_classification"""

											if self.config.problem_type == "regression":
															UpperCamelCase_:				Union[str, Any]						=    MSELoss()
															if self.num_labels == 1:
																			UpperCamelCase_:				Tuple						=    loss_fct(logits.squeeze()    ,						labels.squeeze()   )
															else:
																			UpperCamelCase_:				Optional[int]						=    loss_fct(snake_case_    ,						snake_case_   )
											elif self.config.problem_type == "single_label_classification":
															UpperCamelCase_:				Union[str, Any]						=    CrossEntropyLoss()
															UpperCamelCase_:				Any						=    loss_fct(logits.view(-1    ,						self.num_labels   )    ,						labels.view(-1   )   )
											elif self.config.problem_type == "multi_label_classification":
															UpperCamelCase_:				Dict						=    BCEWithLogitsLoss()
															UpperCamelCase_:				Dict						=    loss_fct(snake_case_    ,						snake_case_   )

							if not return_dict:
											UpperCamelCase_:				str						=    (logits,) + outputs[2:]
											return ((loss,) + output) if loss is not None else output

							return ImageClassifierOutputWithNoAttention(loss=snake_case_    ,						logits=snake_case_    ,						hidden_states=outputs.hidden_states   )








import collections
import os
import re
from pathlib import Path


lowerCamelCase_    :			Optional[Any]    =	"""src/transformers"""


# Matches is_xxx_available()
lowerCamelCase_    :			Union[str, Any]    =	re.compile(r"""is\_([a-z_]*)_available()""")
# Catches a one-line _import_struct = {xxx}
lowerCamelCase_    :			int    =	re.compile(r"""^_import_structure\s+=\s+\{([^\}]+)\}""")
# Catches a line with a key-values pattern: "bla": ["foo", "bar"]
lowerCamelCase_    :			Union[str, Any]    =	re.compile(r"""\s+\"\S*\":\s+\[([^\]]*)\]""")
# Catches a line if not is_foo_available
lowerCamelCase_    :			Any    =	re.compile(r"""^\s*if\s+not\s+is\_[a-z_]*\_available\(\)""")
# Catches a line _import_struct["bla"].append("foo")
lowerCamelCase_    :			Any    =	re.compile(r"""^\s*_import_structure\[\"\S*\"\]\.append\(\"(\S*)\"\)""")
# Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"]
lowerCamelCase_    :			List[Any]    =	re.compile(r"""^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]""")
# Catches a line with an object between quotes and a comma:     "MyModel",
lowerCamelCase_    :			Any    =	re.compile(r"""^\s+\"([^\"]+)\",""")
# Catches a line with objects between brackets only:    ["foo", "bar"],
lowerCamelCase_    :			Tuple    =	re.compile(r"""^\s+\[([^\]]+)\]""")
# Catches a line with from foo import bar, bla, boo
lowerCamelCase_    :			Tuple    =	re.compile(r"""\s+from\s+\S*\s+import\s+([^\(\s].*)\n""")
# Catches a line with try:
lowerCamelCase_    :			Dict    =	re.compile(r"""^\s*try:""")
# Catches a line with else:
lowerCamelCase_    :			Union[str, Any]    =	re.compile(r"""^\s*else:""")







def 							A__       (    lowerCamelCase    )	->						List[Any]:
				if _re_test_backend.search(lowerCamelCase    ) is None:
								return None
				UpperCamelCase_:				Any						=    [b[0] for b in _re_backend.findall(lowerCamelCase    )]
				backends.sort()
				return "_and_".join(lowerCamelCase    )







def 							A__       (    lowerCamelCase    )	->						Union[str, Any]:
				with open(lowerCamelCase  ,     """r"""  ,     encoding="""utf-8"""  ,     newline="""\n"""    ) as f:
								UpperCamelCase_:				Dict						=    f.readlines()

				UpperCamelCase_:				Tuple						=    0
				while line_index < len(lowerCamelCase    ) and not lines[line_index].startswith("""_import_structure = {"""    ):
								line_index += 1

				# If this is a traditional init, just return.
				if line_index >= len(lowerCamelCase    ):
								return None

				# First grab the objects without a specific backend in _import_structure
				UpperCamelCase_:				Optional[int]						=    []
				while not lines[line_index].startswith("""if TYPE_CHECKING"""    ) and find_backend(lines[line_index]    ) is None:
								UpperCamelCase_:				Any						=    lines[line_index]
								# If we have everything on a single line, let's deal with it.
								if _re_one_line_import_struct.search(lowerCamelCase    ):
												UpperCamelCase_:				str						=    _re_one_line_import_struct.search(lowerCamelCase    ).groups()[0]
												UpperCamelCase_:				Tuple						=    re.findall(r"""\[([^\]]+)\]"""  ,     lowerCamelCase    )
												for imp in imports:
																objects.extend([obj[1:-1] for obj in imp.split(""", """    )]    )
												line_index += 1
												continue
								UpperCamelCase_:				Any						=    _re_import_struct_key_value.search(lowerCamelCase    )
								if single_line_import_search is not None:
												UpperCamelCase_:				Any						=    [obj[1:-1] for obj in single_line_import_search.groups()[0].split(""", """    ) if len(lowerCamelCase    ) > 0]
												objects.extend(lowerCamelCase    )
								elif line.startswith(""" """ * 8 + """\""""    ):
												objects.append(line[9:-3]    )
								line_index += 1

				UpperCamelCase_:				Optional[Any]						=    {"""none""": objects}
				# Let's continue with backend-specific objects in _import_structure
				while not lines[line_index].startswith("""if TYPE_CHECKING"""    ):
								# If the line is an if not is_backend_available, we grab all objects associated.
								UpperCamelCase_:				Any						=    find_backend(lines[line_index]    )
								# Check if the backend declaration is inside a try block:
								if _re_try.search(lines[line_index - 1]    ) is None:
												UpperCamelCase_:				Any						=    None

								if backend is not None:
												line_index += 1

												# Scroll until we hit the else block of try-except-else
												while _re_else.search(lines[line_index]    ) is None:
																line_index += 1

												line_index += 1

												UpperCamelCase_:				int						=    []
												# Until we unindent, add backend objects to the list
												while len(lines[line_index]    ) <= 1 or lines[line_index].startswith(""" """ * 4    ):
																UpperCamelCase_:				Tuple						=    lines[line_index]
																if _re_import_struct_add_one.search(lowerCamelCase    ) is not None:
																				objects.append(_re_import_struct_add_one.search(lowerCamelCase    ).groups()[0]    )
																elif _re_import_struct_add_many.search(lowerCamelCase    ) is not None:
																				UpperCamelCase_:				List[str]						=    _re_import_struct_add_many.search(lowerCamelCase    ).groups()[0].split(""", """    )
																				UpperCamelCase_:				str						=    [obj[1:-1] for obj in imports if len(lowerCamelCase    ) > 0]
																				objects.extend(lowerCamelCase    )
																elif _re_between_brackets.search(lowerCamelCase    ) is not None:
																				UpperCamelCase_:				Tuple						=    _re_between_brackets.search(lowerCamelCase    ).groups()[0].split(""", """    )
																				UpperCamelCase_:				List[Any]						=    [obj[1:-1] for obj in imports if len(lowerCamelCase    ) > 0]
																				objects.extend(lowerCamelCase    )
																elif _re_quote_object.search(lowerCamelCase    ) is not None:
																				objects.append(_re_quote_object.search(lowerCamelCase    ).groups()[0]    )
																elif line.startswith(""" """ * 8 + """\""""    ):
																				objects.append(line[9:-3]    )
																elif line.startswith(""" """ * 12 + """\""""    ):
																				objects.append(line[13:-3]    )
																line_index += 1

												UpperCamelCase_:				List[str]						=    objects
								else:
												line_index += 1

    # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend
				UpperCamelCase_:				List[str]						=    []
				while (
				    line_index < len(lowerCamelCase    )
				    and find_backend(lines[line_index]    ) is None
				    and not lines[line_index].startswith("""else"""    )
				):
								UpperCamelCase_:				List[str]						=    lines[line_index]
								UpperCamelCase_:				Union[str, Any]						=    _re_import.search(lowerCamelCase    )
								if single_line_import_search is not None:
												objects.extend(single_line_import_search.groups()[0].split(""", """    )    )
								elif line.startswith(""" """ * 8    ):
												objects.append(line[8:-2]    )
								line_index += 1

				UpperCamelCase_:				Any						=    {"""none""": objects}
				# Let's continue with backend-specific objects
				while line_index < len(lowerCamelCase    ):
								# If the line is an if is_backend_available, we grab all objects associated.
								UpperCamelCase_:				str						=    find_backend(lines[line_index]    )
								# Check if the backend declaration is inside a try block:
								if _re_try.search(lines[line_index - 1]    ) is None:
												UpperCamelCase_:				List[Any]						=    None

								if backend is not None:
												line_index += 1

												# Scroll until we hit the else block of try-except-else
												while _re_else.search(lines[line_index]    ) is None:
																line_index += 1

												line_index += 1

												UpperCamelCase_:				int						=    []
												# Until we unindent, add backend objects to the list
												while len(lines[line_index]    ) <= 1 or lines[line_index].startswith(""" """ * 8    ):
																UpperCamelCase_:				Tuple						=    lines[line_index]
																UpperCamelCase_:				Union[str, Any]						=    _re_import.search(lowerCamelCase    )
																if single_line_import_search is not None:
																				objects.extend(single_line_import_search.groups()[0].split(""", """    )    )
																elif line.startswith(""" """ * 12    ):
																				objects.append(line[12:-2]    )
																line_index += 1

												UpperCamelCase_:				Optional[Any]						=    objects
								else:
												line_index += 1

				return import_dict_objects, type_hint_objects







def 							A__       (    lowerCamelCase  ,     lowerCamelCase    )	->						List[Any]:

				def find_duplicates(lowerCamelCase    ):
								return [k for k, v in collections.Counter(lowerCamelCase    ).items() if v > 1]

				if list(import_dict_objects.keys()    ) != list(type_hint_objects.keys()    ):
								return ["Both sides of the init do not have the same backends!"]

				UpperCamelCase_:				Optional[int]						=    []
				for key in import_dict_objects.keys():
								UpperCamelCase_:				List[str]						=    find_duplicates(import_dict_objects[key]    )
								if duplicate_imports:
												errors.append(F'''Duplicate _import_structure definitions for: {duplicate_imports}'''    )
								UpperCamelCase_:				Tuple						=    find_duplicates(type_hint_objects[key]    )
								if duplicate_type_hints:
												errors.append(F'''Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}'''    )

								if sorted(set(import_dict_objects[key]    )    ) != sorted(set(type_hint_objects[key]    )    ):
												UpperCamelCase_:				int						=    """base imports""" if key == """none""" else F'''{key} backend'''
												errors.append(F'''Differences for {name}:'''    )
												for a in type_hint_objects[key]:
																if a not in import_dict_objects[key]:
																				errors.append(F'''  {a} in TYPE_HINT but not in _import_structure.'''    )
												for a in import_dict_objects[key]:
																if a not in type_hint_objects[key]:
																				errors.append(F'''  {a} in _import_structure but not in TYPE_HINT.'''    )
				return errors







def 							A__       (    )	->						Tuple:
				UpperCamelCase_:				Optional[int]						=    []
				for root, _, files in os.walk(lowerCamelCase    ):
								if "__init__.py" in files:
												UpperCamelCase_:				Union[str, Any]						=    os.path.join(lowerCamelCase  ,     """__init__.py"""    )
												UpperCamelCase_:				Optional[int]						=    parse_init(lowerCamelCase    )
												if objects is not None:
																UpperCamelCase_:				Any						=    analyze_results(*lowerCamelCase    )
																if len(lowerCamelCase    ) > 0:
																				UpperCamelCase_:				Any						=    F'''Problem in {fname}, both halves do not define the same objects.\n{errors[0]}'''
																				failures.append("""\n""".join(lowerCamelCase    )    )
				if len(lowerCamelCase    ) > 0:
								raise ValueError("""\n\n""".join(lowerCamelCase    )    )







def 							A__       (    )	->						Any:
				UpperCamelCase_:				List[Any]						=    []
				for path, directories, files in os.walk(lowerCamelCase    ):
								for folder in directories:
												# Ignore private modules
												if folder.startswith("""_"""    ):
																directories.remove(lowerCamelCase    )
																continue
												# Ignore leftovers from branches (empty folders apart from pycache)
												if len(list((Path(lowerCamelCase    ) / folder).glob("""*.py"""    )    )    ) == 0:
																continue
												UpperCamelCase_:				str						=    str((Path(lowerCamelCase    ) / folder).relative_to(lowerCamelCase    )    )
												UpperCamelCase_:				Optional[Any]						=    short_path.replace(os.path.sep  ,     """."""    )
												submodules.append(lowerCamelCase    )
								for fname in files:
												if fname == "__init__.py":
																continue
												UpperCamelCase_:				Dict						=    str((Path(lowerCamelCase    ) / fname).relative_to(lowerCamelCase    )    )
												UpperCamelCase_:				Optional[int]						=    short_path.replace(""".py"""  ,     """"""    ).replace(os.path.sep  ,     """."""    )
												if len(submodule.split("""."""    )    ) == 1:
																submodules.append(lowerCamelCase    )
				return submodules


lowerCamelCase_    :			Optional[int]    =	[
    """convert_pytorch_checkpoint_to_tf2""",
    """modeling_flax_pytorch_utils""",
    """models.esm.openfold_utils""",
]







def 							A__       (    )	->						List[str]:
				# This is to make sure the transformers module imported is the one in the repo.
				from transformers.utils import direct_transformers_import

				UpperCamelCase_:				Optional[Any]						=    direct_transformers_import(lowerCamelCase    )

				UpperCamelCase_:				Tuple						=    set(transformers._import_structure.keys()    )
				# This contains all the base keys of the _import_structure object defined in the init, but if the user is missing
				# some optional dependencies, they may not have all of them. Thus we read the init to read all additions and
				# (potentiall re-) add them.
				with open(os.path.join(lowerCamelCase  ,     """__init__.py"""    )  ,     """r"""    ) as f:
								UpperCamelCase_:				List[Any]						=    f.read()
				import_structure_keys.update(set(re.findall(r"""import_structure\[\"([^\"]*)\"\]"""  ,     lowerCamelCase    )    )    )

				UpperCamelCase_:				Dict						=    [
				    module
				    for module in get_transformers_submodules()
				    if module not in IGNORE_SUBMODULES and module not in import_structure_keys
				]

				if len(lowerCamelCase    ) > 0:
								UpperCamelCase_:				Dict						=    """\n""".join(F'''- {module}''' for module in module_not_registered    )
								raise ValueError(
								    """The following submodules are not properly registed in the main init of Transformers:\n"""
								    F'''{list_of_modules}\n'''
								    """Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value."""    )


if __name__ == "__main__":
							check_all_inits()
							check_submodules()






