





'''simple docstring'''

from __future__ import annotations





def lowerCamelCase						(     __lowerCamelCase :    str					,       __lowerCamelCase :    str    )						->bool:
    _SCREAMING_SNAKE_CASE									=			get_failure_array(__lowerCamelCase    )

    # 2) Step through text searching for pattern
    _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			0, 0  # index into text, pattern
    while i < len(__lowerCamelCase    ):
        if pattern[j] == text[i]:
            if j == (len(__lowerCamelCase    ) - 1):
                return True
            j += 1

        # if this is a prefix in our pattern
        # just go back far enough to continue
        elif j > 0:
            _SCREAMING_SNAKE_CASE									=			failure[j - 1]
            continue
        i += 1
    return False





def lowerCamelCase						(     __lowerCamelCase :    str    )						->list[int]:
    _SCREAMING_SNAKE_CASE									=			[0]
    _SCREAMING_SNAKE_CASE									=			0
    _SCREAMING_SNAKE_CASE									=			1
    while j < len(__lowerCamelCase    ):
        if pattern[i] == pattern[j]:
            i += 1
        elif i > 0:
            _SCREAMING_SNAKE_CASE									=			failure[i - 1]
            continue
        j += 1
        failure.append(__lowerCamelCase    )
    return failure


if __name__ == "__main__":
      # Test 1)
      lowercase_					= """abc1abc12"""
      lowercase_					= """alskfjaldsabc1abc1abc12k23adsfabcabc"""
      lowercase_					= """alskfjaldsk23adsfabcabc"""
      assert kmp(pattern, texta) and not kmp(pattern, texta)

      # Test 2)
      lowercase_					= """ABABX"""
      lowercase_					= """ABABZABABYABABX"""
      assert kmp(pattern, text)

      # Test 3)
      lowercase_					= """AAAB"""
      lowercase_					= """ABAAAAAB"""
      assert kmp(pattern, text)

      # Test 4)
      lowercase_					= """abcdabcy"""
      lowercase_					= """abcxabcdabxabcdabcdabcy"""
      assert kmp(pattern, text)

      # Test 5)
      lowercase_					= """aabaabaaa"""
      assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]










'''simple docstring'''

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


lowercase_					= logging.get_logger(__name__)

# General docstring
lowercase_					= """PoolFormerConfig"""

# Base docstring
lowercase_					= """sail/poolformer_s12"""
lowercase_					= [1, 512, 7, 7]

# Image classification docstring
lowercase_					= """sail/poolformer_s12"""
lowercase_					= """tabby, tabby cat"""

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





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


class 					a_     (				nn.Module       ):

    '''simple docstring'''


    def __init__(		self ,		A = None       )		->   None:
        super().__init__()
        _SCREAMING_SNAKE_CASE									=			drop_prob


    def 			snake_case_(		self ,		A       )		->   torch.Tensor:
        return drop_path(A ,		self.drop_prob ,		self.training       )





    def 			snake_case_(		self       )		->   str:
        return "p={}".format(self.drop_prob       )




class 					a_     (				nn.Module       ):

    '''simple docstring'''


    def __init__(		self ,		A ,		A ,		A ,		A ,		A ,		A=None       )		->   Union[str, Any]:
        super().__init__()
        _SCREAMING_SNAKE_CASE									=			patch_size if isinstance(A ,		collections.abc.Iterable       ) else (patch_size, patch_size)
        _SCREAMING_SNAKE_CASE									=			stride if isinstance(A ,		collections.abc.Iterable       ) else (stride, stride)
        _SCREAMING_SNAKE_CASE									=			padding if isinstance(A ,		collections.abc.Iterable       ) else (padding, padding)

        _SCREAMING_SNAKE_CASE									=			nn.Convad(A ,		A ,		kernel_size=A ,		stride=A ,		padding=A       )
        _SCREAMING_SNAKE_CASE									=			norm_layer(A       ) if norm_layer else nn.Identity()





    def 			snake_case_(		self ,		A       )		->   Optional[Any]:
        _SCREAMING_SNAKE_CASE									=			self.projection(A       )
        _SCREAMING_SNAKE_CASE									=			self.norm(A       )
        return embeddings




class 					a_     (				nn.GroupNorm       ):

    '''simple docstring'''


    def __init__(		self ,		A ,		**A       )		->   Union[str, Any]:
        super().__init__(1 ,		A ,		**A       )




class 					a_     (				nn.Module       ):

    '''simple docstring'''


    def __init__(		self ,		A       )		->   Union[str, Any]:
        super().__init__()
        _SCREAMING_SNAKE_CASE									=			nn.AvgPoolad(A ,		stride=1 ,		padding=pool_size // 2 ,		count_include_pad=A       )





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




class 					a_     (				nn.Module       ):

    '''simple docstring'''


    def __init__(		self ,		A ,		A ,		A ,		A       )		->   List[Any]:
        super().__init__()
        _SCREAMING_SNAKE_CASE									=			nn.Convad(A ,		A ,		1       )
        _SCREAMING_SNAKE_CASE									=			nn.Convad(A ,		A ,		1       )
        _SCREAMING_SNAKE_CASE									=			PoolFormerDropPath(A       )
        if isinstance(config.hidden_act ,		A       ):
            _SCREAMING_SNAKE_CASE									=			ACTaFN[config.hidden_act]
        else:
            _SCREAMING_SNAKE_CASE									=			config.hidden_act





    def 			snake_case_(		self ,		A       )		->   Optional[int]:
        _SCREAMING_SNAKE_CASE									=			self.conva(A       )
        _SCREAMING_SNAKE_CASE									=			self.act_fn(A       )
        _SCREAMING_SNAKE_CASE									=			self.drop(A       )
        _SCREAMING_SNAKE_CASE									=			self.conva(A       )
        _SCREAMING_SNAKE_CASE									=			self.drop(A       )

        return hidden_states




class 					a_     (				nn.Module       ):

    '''simple docstring'''


    def __init__(		self ,		A ,		A ,		A ,		A ,		A ,		A       )		->   Union[str, Any]:
        super().__init__()
        _SCREAMING_SNAKE_CASE									=			PoolFormerPooling(A       )
        _SCREAMING_SNAKE_CASE									=			PoolFormerOutput(A ,		A ,		A ,		A       )
        _SCREAMING_SNAKE_CASE									=			PoolFormerGroupNorm(A       )
        _SCREAMING_SNAKE_CASE									=			PoolFormerGroupNorm(A       )

        # Useful for training neural nets
        _SCREAMING_SNAKE_CASE									=			PoolFormerDropPath(A       ) if drop_path > 0.0 else nn.Identity()
        _SCREAMING_SNAKE_CASE									=			config.use_layer_scale
        if config.use_layer_scale:
            _SCREAMING_SNAKE_CASE									=			nn.Parameter(
                config.layer_scale_init_value * torch.ones((A)       ) ,		requires_grad=A       )
            _SCREAMING_SNAKE_CASE									=			nn.Parameter(
                config.layer_scale_init_value * torch.ones((A)       ) ,		requires_grad=A       )





    def 			snake_case_(		self ,		A       )		->   Optional[Any]:
        if self.use_layer_scale:
            _SCREAMING_SNAKE_CASE									=			self.pooling(self.before_norm(A       )       )
            _SCREAMING_SNAKE_CASE									=			self.layer_scale_a.unsqueeze(-1       ).unsqueeze(-1       ) * pooling_output
            # First residual connection
            _SCREAMING_SNAKE_CASE									=			hidden_states + self.drop_path(A       )
            _SCREAMING_SNAKE_CASE									=			()

            _SCREAMING_SNAKE_CASE									=			self.output(self.after_norm(A       )       )
            _SCREAMING_SNAKE_CASE									=			self.layer_scale_a.unsqueeze(-1       ).unsqueeze(-1       ) * layer_output
            # Second residual connection
            _SCREAMING_SNAKE_CASE									=			hidden_states + self.drop_path(A       )

            _SCREAMING_SNAKE_CASE									=			(output,) + outputs
            return outputs

        else:
            _SCREAMING_SNAKE_CASE									=			self.drop_path(self.pooling(self.before_norm(A       )       )       )
            # First residual connection
            _SCREAMING_SNAKE_CASE									=			pooling_output + hidden_states
            _SCREAMING_SNAKE_CASE									=			()

            # Second residual connection inside the PoolFormerOutput block
            _SCREAMING_SNAKE_CASE									=			self.drop_path(self.output(self.after_norm(A       )       )       )
            _SCREAMING_SNAKE_CASE									=			hidden_states + layer_output

            _SCREAMING_SNAKE_CASE									=			(output,) + outputs
            return outputs




class 					a_     (				nn.Module       ):

    '''simple docstring'''


    def __init__(		self ,		A       )		->   Any:
        super().__init__()
        _SCREAMING_SNAKE_CASE									=			config
        # stochastic depth decay rule
        _SCREAMING_SNAKE_CASE									=			[x.item() for x in torch.linspace(0 ,		config.drop_path_rate ,		sum(config.depths       )       )]

        # patch embeddings
        _SCREAMING_SNAKE_CASE									=			[]
        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] ,		)       )
        _SCREAMING_SNAKE_CASE									=			nn.ModuleList(A       )

        # Transformer blocks
        _SCREAMING_SNAKE_CASE									=			[]
        _SCREAMING_SNAKE_CASE									=			0
        for i in range(config.num_encoder_blocks       ):
            # each block consists of layers
            _SCREAMING_SNAKE_CASE									=			[]
            if i != 0:
                cur += config.depths[i - 1]
            for j in range(config.depths[i]       ):
                layers.append(
                    PoolFormerLayer(
                        A ,		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(A       )       )

        _SCREAMING_SNAKE_CASE									=			nn.ModuleList(A       )





    def 			snake_case_(		self ,		A ,		A=False ,		A=True       )		->   List[Any]:
        _SCREAMING_SNAKE_CASE									=			() if output_hidden_states else None

        _SCREAMING_SNAKE_CASE									=			pixel_values
        for idx, layers in enumerate(zip(self.patch_embeddings ,		self.block       )       ):
            _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			layers
            # Get patch embeddings from hidden_states
            _SCREAMING_SNAKE_CASE									=			embedding_layer(A       )
            # Send the embeddings through the blocks
            for _, blk in enumerate(A       ):
                _SCREAMING_SNAKE_CASE									=			blk(A       )
                _SCREAMING_SNAKE_CASE									=			layer_outputs[0]

            if output_hidden_states:
                _SCREAMING_SNAKE_CASE									=			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=A ,		hidden_states=A       )




class 					a_     (				snake_case_       ):

    '''simple docstring'''
    UpperCamelCase     = PoolFormerConfig
    UpperCamelCase     = '''poolformer'''
    UpperCamelCase     = '''pixel_values'''
    UpperCamelCase     = True


    def 			snake_case_(		self ,		A       )		->   int:
        if isinstance(A ,		(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(A ,		nn.LayerNorm       ):
            module.bias.data.zero_()
            module.weight.data.fill_(1.0       )





    def 			snake_case_(		self ,		A ,		A=False       )		->   Dict:
        if isinstance(A ,		A       ):
            _SCREAMING_SNAKE_CASE									=			value




lowercase_					= 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.
"""

lowercase_					= 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.'''      ,    snake_case_      ,    )
class 					a_     (				snake_case_       ):

    '''simple docstring'''


    def __init__(		self ,		A       )		->   int:
        super().__init__(A       )
        _SCREAMING_SNAKE_CASE									=			config

        _SCREAMING_SNAKE_CASE									=			PoolFormerEncoder(A       )

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


    def 			snake_case_(		self       )		->   Any:
        return self.embeddings.patch_embeddings





    @add_start_docstrings_to_model_forward(A       )
    @add_code_sample_docstrings(
        checkpoint=_CHECKPOINT_FOR_DOC ,		output_type=A ,		config_class=_CONFIG_FOR_DOC ,		modality="""vision""" ,		expected_output=_EXPECTED_OUTPUT_SHAPE ,		)
    def 			snake_case_(		self ,		A = None ,		A = None ,		A = None ,		)		->   Union[Tuple, BaseModelOutputWithNoAttention]:
        _SCREAMING_SNAKE_CASE									=			(
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        _SCREAMING_SNAKE_CASE									=			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"""       )

        _SCREAMING_SNAKE_CASE									=			self.encoder(
            A ,		output_hidden_states=A ,		return_dict=A ,		)
        _SCREAMING_SNAKE_CASE									=			encoder_outputs[0]

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

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




class 					a_     (				nn.Module       ):

    '''simple docstring'''


    def __init__(		self ,		A       )		->   Dict:
        super().__init__()
        _SCREAMING_SNAKE_CASE									=			nn.Linear(config.hidden_size ,		config.hidden_size       )





    def 			snake_case_(		self ,		A       )		->   str:
        _SCREAMING_SNAKE_CASE									=			self.dense(A       )
        return output




@add_start_docstrings(
    '''
    PoolFormer Model transformer with an image classification head on top
    '''      ,    snake_case_      ,    )
class 					a_     (				snake_case_       ):

    '''simple docstring'''


    def __init__(		self ,		A       )		->   Optional[Any]:
        super().__init__(A       )
        _SCREAMING_SNAKE_CASE									=			config.num_labels
        _SCREAMING_SNAKE_CASE									=			PoolFormerModel(A       )

        # Final norm
        _SCREAMING_SNAKE_CASE									=			PoolFormerGroupNorm(config.hidden_sizes[-1]       )
        # Classifier head
        _SCREAMING_SNAKE_CASE									=			(
            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(A       )
    @add_code_sample_docstrings(
        checkpoint=_IMAGE_CLASS_CHECKPOINT ,		output_type=A ,		config_class=_CONFIG_FOR_DOC ,		expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,		)
    def 			snake_case_(		self ,		A = None ,		A = None ,		A = None ,		A = None ,		)		->   Union[Tuple, ImageClassifierOutputWithNoAttention]:
        _SCREAMING_SNAKE_CASE									=			return_dict if return_dict is not None else self.config.use_return_dict

        _SCREAMING_SNAKE_CASE									=			self.poolformer(
            A ,		output_hidden_states=A ,		return_dict=A ,		)

        _SCREAMING_SNAKE_CASE									=			outputs[0]

        _SCREAMING_SNAKE_CASE									=			self.classifier(self.norm(A       ).mean([-2, -1]       )       )

        _SCREAMING_SNAKE_CASE									=			None
        if labels is not None:
            if self.config.problem_type is None:
                if self.num_labels == 1:
                    _SCREAMING_SNAKE_CASE									=			"""regression"""
                elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
                    _SCREAMING_SNAKE_CASE									=			"""single_label_classification"""
                else:
                    _SCREAMING_SNAKE_CASE									=			"""multi_label_classification"""

            if self.config.problem_type == "regression":
                _SCREAMING_SNAKE_CASE									=			MSELoss()
                if self.num_labels == 1:
                    _SCREAMING_SNAKE_CASE									=			loss_fct(logits.squeeze() ,		labels.squeeze()       )
                else:
                    _SCREAMING_SNAKE_CASE									=			loss_fct(A ,		A       )
            elif self.config.problem_type == "single_label_classification":
                _SCREAMING_SNAKE_CASE									=			CrossEntropyLoss()
                _SCREAMING_SNAKE_CASE									=			loss_fct(logits.view(-1 ,		self.num_labels       ) ,		labels.view(-1       )       )
            elif self.config.problem_type == "multi_label_classification":
                _SCREAMING_SNAKE_CASE									=			BCEWithLogitsLoss()
                _SCREAMING_SNAKE_CASE									=			loss_fct(A ,		A       )

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

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



