
    hh
d                        d Z ddlZddlmc mZ ddlmZ ddlm	Z	 ddlm
Z
 ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ dZddddddZg dg dddg dg dddg dg dddg dg dddg dg ddddZdZ G d de
j0                        Z G d de
j0                        Z	 d=d Zd>d!Zd?d"Z	 	 	 	 	 	 	 	 	 	 	 	 d@d#Z ed$d%      	 	 	 	 	 	 	 	 	 dAd&       Z ed'd(      	 	 	 	 	 	 	 	 	 dBd)       Z  ed*d+      	 	 	 	 	 	 	 	 	 dCd,       Z! ed-d.      	 	 	 	 	 	 	 	 	 dDd/       Z" ed0d1      	 	 	 	 	 	 	 	 	 dEd2       Z#ejI                  d34      e_         ejI                  d54      e _         ejI                  d64      e!_         ejI                  d74      e"_         ejI                  d84      e#_          ed9      d>d:       Z% ed;      dFd<       Z&ejL                  j                   e&_         y)GzxConvNeXt models for TF-Keras.

References:

- [A ConvNet for the 2020s](https://arxiv.org/abs/2201.03545)
  (CVPR 2022)
    N)backend)initializers)layers)utils)imagenet_utils)
sequential)training)keras_exportzFhttps://storage.googleapis.com/tensorflow/keras-applications/convnext/)@8ae6e78ce2933352b1ef4008e6dd2f17bc40771563877d156bc6426c7cf503ff@d547c096cabd03329d7be5562c5e14798aa39ed24b474157cef5e85ab9e49ef1)@ce1277d8f1ee5a0ef0e171469089c18f5233860ceaf9b168049cb9263fd7483c@6fc8009faa2f00c1c1dfce59feea9b0745eb260a7dd11bee65c8e20843da6eab)@52cbb006d3dadd03f6e095a8ca1aca47aecdd75acb4bc74bce1f5c695d0086e6@40a20c5548a5e9202f69735ecc06c990e6b7c9d2de39f0361e27baeb24cb7c45)@070c5ed9ed289581e477741d3b34beffa920db8cf590899d6d2c67fba2a198a6@96f02b6f0753d4f543261bc9d09bed650f24dd6bc02ddde3066135b63d23a1cd)@c1f5ccab661354fc3a79a10fa99af82f0fbf10ec65cb894a3ae0815f17a889ee@de3f8a54174130e0cecdc71583354753d557fcf1f4487331558e2a16ba0cfe05)convnext_tinyconvnext_smallconvnext_baseconvnext_largeconvnext_xlarge)   r   	   r   )`              )depthsprojection_dimsdefault_size)r   r      r   )            )r   r   r   i   )r&   r'   r(   i   )tinysmallbaselargexlargea  Instantiates the {name} architecture.

  References:
    - [A ConvNet for the 2020s](https://arxiv.org/abs/2201.03545)
    (CVPR 2022)

  For image classification use cases, see
  [this page for detailed examples](
  https://keras.io/api/applications/#usage-examples-for-image-classification-models).
  For transfer learning use cases, make sure to read the
  [guide to transfer learning & fine-tuning](
    https://keras.io/guides/transfer_learning/).

  The `base`, `large`, and `xlarge` models were first pre-trained on the
  ImageNet-21k dataset and then fine-tuned on the ImageNet-1k dataset. The
  pre-trained parameters of the models were assembled from the
  [official repository](https://github.com/facebookresearch/ConvNeXt). To get a
  sense of how these parameters were converted to TF-Keras compatible
  parameters, please refer to
  [this repository](https://github.com/sayakpaul/keras-convnext-conversion).

  Note: Each TF-Keras Application expects a specific kind of input
  preprocessing. For ConvNeXt, preprocessing is included in the model using a
  `Normalization` layer. ConvNeXt models expect their inputs to be float or
  uint8 tensors of pixels with values in the [0-255] range.

  When calling the `summary()` method after instantiating a ConvNeXt model,
  prefer setting the `expand_nested` argument `summary()` to `True` to better
  investigate the instantiated model.

  Args:
    include_top: Whether to include the fully-connected
      layer at the top of the network. Defaults to `True`.
    weights: One of `None` (random initialization),
      `"imagenet"` (pre-training on ImageNet-1k), or the path to the weights
      file to be loaded. Defaults to `"imagenet"`.
    input_tensor: Optional TF-Keras tensor
      (i.e. output of `layers.Input()`)
      to use as image input for the model.
    input_shape: Optional shape tuple, only to be specified
      if `include_top` is False.
      It should have exactly 3 inputs channels.
    pooling: Optional pooling mode for feature extraction
      when `include_top` is `False`.
      - `None` means that the output of the model will be
        the 4D tensor output of the last convolutional layer.
      - `avg` means that global average pooling
        will be applied to the output of the
        last convolutional layer, and thus
        the output of the model will be a 2D tensor.
      - `max` means that global max pooling will
        be applied.
      Defaults to `None`.
    classes: Optional number of classes to classify images
      into, only to be specified if `include_top` is True, and
      if no `weights` argument is specified. 1000 is how many
      ImageNet classes there are. Defaults to `1000`.
    classifier_activation: A `str` or callable. The activation function to use
      on the "top" layer. Ignored unless `include_top=True`. Set
      `classifier_activation=None` to return the logits of the "top" layer.
      When loading pretrained weights, `classifier_activation` can only
      be `None` or `"softmax"`. Defaults to `"softmax"`.

  Returns:
    A `keras.Model` instance.
c                   4     e Zd ZdZ fdZddZ fdZ xZS )StochasticDeptha  Stochastic Depth module.

    It performs batch-wise dropping rather than sample-wise. In libraries like
    `timm`, it's similar to `DropPath` layers that drops residual paths
    sample-wise.

    References:
      - https://github.com/rwightman/pytorch-image-models

    Args:
      drop_path_rate (float): Probability of dropping paths. Should be within
        [0, 1].

    Returns:
      Tensor either with the residual path dropped or kept.
    c                 2    t        |   di | || _        y N )super__init__drop_path_rate)selfr5   kwargs	__class__s      `/var/www/html/dev/engine/venv/lib/python3.12/site-packages/tf_keras/src/applications/convnext.pyr4   zStochasticDepth.__init__   s    "6",    c                 &   |rd| j                   z
  }t        j                  |      d   fdt        t        j                  |            dz
  z  z   }|t        j                  j                  |dd      z   }t        j                  |      }||z  |z  S |S )N   r   )r<   )r5   tfshapelenrandomuniformfloor)r6   xr	   	keep_probr>   random_tensors         r9   callzStochasticDepth.call   s    D///IXXa[^%BHHQK0@10D(EEE%		(9(9%A(FFMHH]3M	M]22r:   c                 ^    t         |          }|j                  d| j                  i       |S )Nr5   )r3   
get_configupdater5   r6   configr8   s     r9   rH   zStochasticDepth.get_config   s-    #%')<)<=>r:   N)__name__
__module____qualname____doc__r4   rF   rH   __classcell__r8   s   @r9   r/   r/      s    "- r:   r/   c                   8     e Zd ZdZ fdZd Zd Z fdZ xZS )
LayerScalea#  Layer scale module.

    References:
      - https://arxiv.org/abs/2103.17239

    Args:
      init_values (float): Initial value for layer scale. Should be within
        [0, 1].
      projection_dim (int): Projection dimensionality.

    Returns:
      Tensor multiplied to the scale.
    c                 @    t        |   di | || _        || _        y r1   )r3   r4   init_valuesprojection_dim)r6   rV   rW   r7   r8   s       r9   r4   zLayerScale.__init__   s#    "6"&,r:   c                     | j                  d| j                  ft        j                  | j                        d      | _        y )NgammaT)namer>   initializer	trainable)
add_weightrW   r   ConstantrV   rY   )r6   input_shapes     r9   buildzLayerScale.build   s=    __&&($--d.>.>?	 % 

r:   c                      || j                   z  S rL   )rY   )r6   rC   s     r9   rF   zLayerScale.call   s    4::~r:   c                 t    t         |          }|j                  | j                  | j                  d       |S )N)rV   rW   )r3   rH   rI   rV   rW   rJ   s     r9   rH   zLayerScale.get_config   s:    #%#//"&"5"5	
 r:   )	rM   rN   rO   rP   r4   r`   rF   rH   rQ   rR   s   @r9   rT   rT      s!    -

 r:   rT   c                 d     !dt        t        j                  d            z    fd}|S )aJ  ConvNeXt block.

    References:
    - https://arxiv.org/abs/2201.03545
    - https://github.com/facebookresearch/ConvNeXt/blob/main/models/convnext.py

    Notes:
      In the original ConvNeXt implementation (linked above), the authors use
      `Dense` layers for pointwise convolutions for increased efficiency.
      Following that, this implementation also uses the same.

    Args:
      projection_dim (int): Number of filters for convolution layers. In the
        ConvNeXt paper, this is referred to as projection dimension.
      drop_path_rate (float): Probability of dropping paths. Should be within
        [0, 1].
      layer_scale_init_value (float): Layer scale value. Should be a small float
        number.
      name: name to path to the keras layer.

    Returns:
      A function representing a ConvNeXtBlock block.
    prestemc           	         | } t        j                  dddz         |      } t        j                  ddz         |      } t        j                  dz  d	z   
      |      } t        j                  ddz   
      |      } t        j                  dz   
      |      } t        dz   
      |      }rt        dz   
      }nt        j                  ddz   
      }|  ||      z   S )N   same_depthwise_conv)filterskernel_sizepaddinggroupsrZ   ư>
_layernormepsilonrZ      _pointwise_conv_1rZ   gelu_gelu_pointwise_conv_2_layer_scale_stochastic_depthlinear	_identity)r   Conv2DLayerNormalizationDense
ActivationrT   r/   )inputsrC   layerr5   layer_scale_init_valuerZ   rW   s      r9   applyzConvNeXtBlock.<locals>.apply  s$   
FMM"!))
  NF%%d9LMaPMFLL^+$9L2LMaP:Ff4'>:1=IFLLd5H.HI!L!-
&N* 	A
 #T,?%?E %%hTK5GHEa  r:   strr   get_uid)rW   r5   r   rZ   r   s   ```` r9   ConvNeXtBlockr      s.    4 |3wy9::!< Lr:   c                 X      !dt        t        j                  d            z     fd}|S )zNormalizes inputs with ImageNet-1k mean and std.

    Args:
      name (str): Name prefix.

    Returns:
      A presemt function.
    rd   c                 R     t        j                  g dg ddz         |       } | S )N)g33333^@gR]@gRY@)g)~@gec}@g    ȷ@_prestem_normalization)meanvariancerZ   )r   Normalization)rC   rZ   s    r9   r   zPreStem.<locals>.apply<  s;    
F  8
 00
  r:   r   )rZ   r   s   ` r9   PreStemr   0  s.     |3wy9::
 Lr:   c                 Z     t        t        j                  d             fd}|S )a  Implementation of classification head of ConvNeXt.

    Args:
      num_classes: number of classes for Dense layer
      classifier_activation: activation function for the Dense layer
      name: name prefix

    Returns:
      Classification head function.
    headc                      t        j                  dz         |       }  t        j                  ddz         |       }  t        j                  dz         |       } | S )N	_head_gaprs   rm   _head_layernormro   _head_dense)
activationrZ   )r   GlobalAveragePooling2Dr|   r}   )rC   classifier_activationrZ   num_classess    r9   r   zHead.<locals>.applyY  sw    BF))tk/AB1E
F%%t&77


FLL,%
 	
 r:   r   )r   r   rZ   r   s   ``` r9   Headr   K  s)     |7??6*+
 Lr:   c                    |dv s4t         j                  j                  j                  |      st	        d      |dk(  r|r|dk7  rt	        d      t        j                  |
|dt        j                         ||      }
|	t        j                  |
      }n/t        j                  |	      st        j                  |	|
	      }n|	}|	#t        j                  j                  |	      d
   }n|}|}|r:t        j                         dk(  rdnd}|
|dz
     }|dk(  r t        |      |      }t!        j"                  t        j$                  |d
   dd|dz         t        j&                  d|dz         g|dz         }g }|j)                  |       d}t+        |      D ]  }t!        j"                  t        j&                  d|dz   t-        |      z         t        j$                  ||dz      dd|dz   t-        |      z         g|dz   t-        |      z         }|j)                  |        t/        j0                  d|t3        |             D cg c]  }t5        |       }}d
}d}t+        |      D ]O  } ||         }t+        | |         D ])  } t7        ||   |||z      ||d| d| z         |      }+ || |   z  }Q |r+t        j8                  ||        t;        |||            }n[|dk(  r t        j<                               }n|d k(  r t        j>                               } t        j&                  d!            }tA        jB                  |||"      }|dk(  ra|rd#}tD        |   d
   }nd$}tD        |   d   }||z   }t        jF                  jI                  |tJ        |z   d%|&      } |jM                  |        |S ||jM                  |       |S c c}w )'aA
  Instantiates ConvNeXt architecture given specific configuration.

    Args:
      depths: An iterable containing depths for each individual stages.
      projection_dims: An iterable containing output number of channels of
      each individual stages.
      drop_path_rate: Stochastic depth probability. If 0.0, then stochastic
        depth won't be used.
      layer_scale_init_value: Layer scale coefficient. If 0.0, layer scaling
        won't be used.
      default_size: Default input image size.
      model_name: An optional name for the model.
      include_preprocessing: boolean denoting whther to include preprocessing in
        the model. When `weights="imagenet"` this should be always set to True.
        But for other models (e.g., randomly initialized) users should set it
        to False and apply preprocessing to data accordingly.
      include_top: Boolean denoting whether to include classification head to
        the model.
      weights: one of `None` (random initialization), `"imagenet"` (pre-training
        on ImageNet-1k), or the path to the weights file to be loaded.
      input_tensor: optional TF-Keras tensor (i.e. output of `layers.Input()`)
        to use as image input for the model.
      input_shape: optional shape tuple, only to be specified if `include_top`
        is False. It should have exactly 3 inputs channels.
      pooling: optional pooling mode for feature extraction when `include_top`
        is `False`.
        - `None` means that the output of the model will be the 4D tensor output
          of the last convolutional layer.
        - `avg` means that global average pooling will be applied to the output
          of the last convolutional layer, and thus the output of the model will
          be a 2D tensor.
        - `max` means that global max pooling will be applied.
      classes: optional number of classes to classify images into, only to be
        specified if `include_top` is True, and if no `weights` argument is
        specified.
      classifier_activation: A `str` or callable. The activation function to use
        on the "top" layer. Ignored unless `include_top=True`. Set
        `classifier_activation=None` to return the logits of the "top" layer.

    Returns:
      A `keras.Model` instance.

    Raises:
        ValueError: in case of invalid argument for `weights`,
          or invalid input shape.
        ValueError: if `classifier_activation` is not `softmax`, or `None`
          when using a pretrained top layer.
        ValueError: if `include_top` is True but `num_classes` is not 1000
          when using ImageNet.
    >   NimagenetzThe `weights` argument should be either `None` (random initialization), `imagenet` (pre-training on ImageNet), or the path to the weights file to be loaded.r     zWIf using `weights` as `'imagenet'` with `include_top` as true, `classes` should be 1000    )r#   min_sizedata_formatrequire_flattenweights)r>   )tensorr>   r   channels_lastr   r<   rs   rq   
_stem_conv)rj   stridesrZ   rm   _stem_layernormro   _stem_downsampling_layernorm_   _downsampling_conv__downsampling_block_        _stage__block_)rW   r5   r   rZ   )r   r   rZ   avgmax)rp   )r   outputsrZ   z.h5z	_notop.h5models)cache_subdir	file_hash)'r=   iogfileexists
ValueErrorr   obtain_input_shaper   image_data_formatr   Inputis_keras_tensorr   layer_utilsget_source_inputsr   r   
Sequentialr{   r|   appendranger   nplinspacesumfloatr   validate_activationr   r   GlobalMaxPooling2Dtraining_libModelWEIGHTS_HASHES
data_utilsget_fileBASE_WEIGHTS_PATHload_weights)!r!   r"   r5   r   r#   
model_nameinclude_preprocessinginclude_topr   input_tensorr_   poolingclassesr   	img_inputr   rC   channel_axisnum_channelsstemdownsample_layersnum_downsample_layersidownsample_layerdepth_drop_ratescurnum_convnext_blocksjmodelfile_suffixr   	file_nameweights_paths!                                    r9   ConvNeXtr   h  sc   D ))RUU[[-?-?-H<
 	
 *D1
 	
 !33!--/#K LL{3	&&|4LLI$I""44\B1EA**,?AQ 	 #<!#341(Z(+A   MM",.	 %%:0A#A
	
 '!D  T"() 3%00)) #&@@3q6I #AE* !#&;;c!fD	 44s1v=
 	  !12!3, ++c>3v;Ga 
 C&' 	 a #vay! 	A.q1/a8'=GA3gaS"99	
 A	 	vay	 **+@'J
D"7
 	 e/--/2A+))+A.A3F%%d3A6fajIE *K&z215I%K&z215I,	''00	)!	 1 
 	<( L 
	7#Los   Oz(keras.applications.convnext.ConvNeXtTinyzkeras.applications.ConvNeXtTinyc	                 p    t        t        d   d   t        d   d   ddt        d   d   | ||||||||      S )Nr)   r!   r"   r   rm   r#   r!   r"   r5   r   r#   r   r   r   r   r   r_   r   r   r   r   MODEL_CONFIGS	r   r   r   r   r   r_   r   r   r   s	            r9   ConvNeXtTinyr   ?  Z     V$X.%f-.?@#"6*>:3!3 r:   z)keras.applications.convnext.ConvNeXtSmallz keras.applications.ConvNeXtSmallc	                 p    t        t        d   d   t        d   d   ddt        d   d   | ||||||||      S )Nr*   r!   r"   r   rm   r#   r   r   r   s	            r9   ConvNeXtSmallr   `  Z     W%h/%g./@A#"7+N;3!3 r:   z(keras.applications.convnext.ConvNeXtBasezkeras.applications.ConvNeXtBasec	                 p    t        t        d   d   t        d   d   ddt        d   d   | ||||||||      S )Nr+   r!   r"   r   rm   r#   r   r   r   s	            r9   ConvNeXtBaser     r   r:   z)keras.applications.convnext.ConvNeXtLargez keras.applications.ConvNeXtLargec	                 p    t        t        d   d   t        d   d   ddt        d   d   | ||||||||      S )Nr,   r!   r"   r   rm   r#   r   r   r   s	            r9   ConvNeXtLarger     r   r:   z*keras.applications.convnext.ConvNeXtXLargez!keras.applications.ConvNeXtXLargec	                 p    t        t        d   d   t        d   d   ddt        d   d   | ||||||||      S )Nr-   r!   r"   r   rm   r#   r   r   r   s	            r9   ConvNeXtXLarger     sZ     X&x0%h/0AB#"8,^<3!3 r:   r   rs   r   r   r   r   z,keras.applications.convnext.preprocess_inputc                     | S )a  A placeholder method for backward compatibility.

    The preprocessing logic has been included in the convnext model
    implementation. Users are no longer required to call this method to
    normalize the input data. This method does nothing and only kept as a
    placeholder to align the API surface between old and new version of model.

    Args:
      x: A floating point `numpy.array` or a `tf.Tensor`.
      data_format: Optional data format of the image tensor/array. `None` means
        the global setting `tf.keras.backend.image_data_format()` is used
        (unless you changed it, it uses "channels_last").
        Defaults to `None`.

    Returns:
      Unchanged `numpy.array` or `tf.Tensor`.
    r2   )rC   r   s     r9   preprocess_inputr     s	    & Hr:   z.keras.applications.convnext.decode_predictionsc                 0    t        j                  | |      S )N)top)r   decode_predictions)predsr   s     r9   r   r     s    ,,U<<r:   )r   rm   NrL   )r   NN)r   rm   r    convnextTTNNNNr   softmax)	r   TTr   NNNr   r   )	r   TTr   NNNr   r   )	r   TTr   NNNr   r   )	r   TTr   NNNr   r   )	r   TTr   NNNr   r   )   )'rP   numpyr   tensorflow.compat.v2compatv2r=   tf_keras.srcr   r   r   r   tf_keras.src.applicationsr   tf_keras.src.enginer   r	   r    tensorflow.python.util.tf_exportr
   r   r   r   BASE_DOCSTRINGLayerr/   rT   r   r   r   r   r   r   r   r   r   formatr   r   r2   r:   r9   <module>r	     s
  "  ! !   %   4 * 8 : M 
#4 .  .  0  0  1+8AH"fll "J' 'V KO;|6@ #Qn .%
 #	: /&
  #	: .%
 #	: /&
  #	: 0'
 !#	: &,,.,A &--?-C %,,.,A &--?-C '..4D.E  <= >* >?= @= ,>>FF  r:   