
    2VhTf                        d dl 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 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      Z G d! d"e      Z	 d@d#ZdAd$ZdBd%Z	 	 	 	 	 	 	 	 	 	 	 	 	 dCd&Z e	d'd(g      	 	 	 	 	 	 	 	 	 dDd)       Z e	d*d+g      	 	 	 	 	 	 	 	 	 dEd,       Z  e	d-d.g      	 	 	 	 	 	 	 	 	 dFd/       Z! e	d0d1g      	 	 	 	 	 	 	 	 	 dGd2       Z" e	d3d4g      	 	 	 	 	 	 	 	 	 dHd5       Z#ejI                  d67      e_%        ejI                  d87      e _%        ejI                  d97      e!_%        ejI                  d:7      e"_%        ejI                  d;7      e#_%         e	d<      dAd=       Z& e	d>      dId?       Z'ejN                  jJ                  e'_%        y)J    N)backend)initializers)layers)ops)random)keras_export)imagenet_utils)Layer)
Functional)
Sequential)operation_utils)
file_utilszFhttps://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 Keras compatible parameters,
please refer to
[this repository](https://github.com/sayakpaul/keras-convnext-conversion).

Note: Each 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 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`. Defaults to None.
        - `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. Defaults to 1000 (number of
        ImageNet classes).
    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.
        Defaults to `"softmax"`.
        When loading pretrained weights, `classifier_activation` can only
        be `None` or `"softmax"`.
    name: The name of the model (string).

Returns:
    A 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)selfr9   kwargs	__class__s      O/home/dcms/DCMS/lib/python3.12/site-packages/keras/src/applications/convnext.pyr8   zStochasticDepth.__init__   s    "6",    c                    |rd| j                   z
  }t        j                  |      d   fdt        t        j                  |            dz
  z  z   }|t	        j
                  |dd      z   }t        j                  |      }||z  |z  S |S )N   r   )r@   )r9   r   shapelenr   uniformfloor)r:   xtraining	keep_probrA   random_tensors         r=   callzStochasticDepth.call   s~    D///IYYq\!_&SYYq\1BQ1F)GGE%ua(CCMIIm4M	M]22r>   c                 ^    t         |          }|j                  d| j                  i       |S )Nr9   )r7   
get_configupdater9   r:   configr<   s     r=   rK   zStochasticDepth.get_config   s-    #%')<)<=>r>   N)__name__
__module____qualname____doc__r8   rI   rK   __classcell__r<   s   @r=   r3   r3      s    "- r>   r3   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 r5   )r7   r8   init_valuesprojection_dim)r:   rY   rZ   r;   r<   s       r=   r8   zLayerScale.__init__   s#    "6"&,r>   c                     | j                  | j                  ft        j                  | j                        d      | _        y )NT)rA   initializer	trainable)
add_weightrZ   r   ConstantrY   gamma)r:   _s     r=   buildzLayerScale.build   s:    __&&($--d.>.>? % 

r>   c                      || j                   z  S rO   )r`   )r:   rE   s     r=   rI   zLayerScale.call   s    4::~r>   c                 t    t         |          }|j                  | j                  | j                  d       |S )N)rY   rZ   )r7   rK   rL   rY   rZ   rM   s     r=   rK   zLayerScale.get_config   s:    #%#//"&"5"5	
 r>   )	rP   rQ   rR   rS   r8   rb   rI   rK   rT   rU   s   @r=   rW   rW      s!    -

 r>   rW   c                 d     !dt        t        j                  d            z    fd}|S )af  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groupsnameư>
_layernormepsilonro      _pointwise_conv_1ro   gelu_gelu_pointwise_conv_2_layer_scale_stochastic_depthlinear	_identity)r   Conv2DLayerNormalizationDense
ActivationrW   r3   )inputsrE   layerr9   layer_scale_init_valuero   rZ   s      r=   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)rZ   r9   r   ro   r   s   ```` r=   ConvNeXtBlockr      s.    4 |3wy9::!< Lr>   c                 X      !dt        t        j                  d            z     fd}|S )z0Normalizes inputs with ImageNet-1k mean and std.rf   c                 R     t        j                  g dg ddz         |       } | S )N)g33333^@gR]@gRY@)g)~@gec}@g    ȷ@_prestem_normalization)meanvariancero   )r   Normalization)rE   ro   s    r=   r   zPreStem.<locals>.apply  s;    
F  8
 00
  r>   r   )ro   r   s   ` r=   PreStemr     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_gaprv   rp   _head_layernormrr   _head_dense)
activationro   )r   GlobalAveragePooling2Dr   r   )rE   classifier_activationro   num_classess    r=   r   zHead.<locals>.apply<  sw    BF))tk/AB1E
F%%t&77


FLL,%
 	
 r>   r   )r   r   ro   r   s   ``` r=   Headr   .  s)     |7??6*+
 Lr>   c                 z   t        j                         dk(  rt        d      |dv s t        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                  |	      d   }|	}n|}|}|r:t        j                         dk(  rdnd}|
|dz
     }|dk(  r t        |      |      }t        t        j                  |d   dd|dz         t        j                  d|dz         g|dz         }g }|j!                  |       d}t#        |      D ]  }t        t        j                  d|dz   t%        |      z         t        j                  ||dz      dd|dz   t%        |      z         g|dz   t%        |      z         }|j!                  |        t'        j(                  d|t+        |             D cg c]  }t-        |       }}d}d}t#        |      D ]O  } ||         }t#        | |         D ])  } t/        ||   |||z      ||d| d| z         |      }+ || |   z  }Q |r+t        j0                  ||        t3        |||             }n[|d!k(  r t        j4                               }n|d"k(  r t        j6                               } t        j                  d#            }t9        |||$      }|dk(  rwt:        |j=                  d%      d&      }| |d'   k7  s||d(   k7  r!t        d)| d*|d'    d+|  d,|d(    d+| d-      ||vr't        d.| d/| d0|j=                  d%      d&    d1      |dk(  rW|rd2}t>        |   d   } nd3}t>        |   d   } ||z   }!t        j@                  |!tB        |!z   d4| 5      }"|jE                  |"       |S ||jE                  |       |S c c}w )6a	  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.
        name: An optional name for the model.
        include_preprocessing: boolean denoting whether to
            include preprocessing in the model.
            When `weights="imagenet"` this should always be `True`.
            But for other models (e.g., randomly initialized) you 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 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 model instance.
    channels_firstzConvNeXt does not support the `channels_first` image data format. Switch to `channels_last` by editing your local config file at ~/.keras/keras.json>   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     zbIf using `weights="imagenet"` with `include_top=True`, `classes` should be 1000. Received classes=    )r'   min_sizedata_formatrequire_flattenweights)rA   )tensorrA   r   channels_lastr   r@   rv   rt   
_stem_conv)rl   stridesro   rp   _stem_layernormrr   _stem_downsampling_layernorm_   _downsampling_conv__downsampling_block_        _stage__block_)rZ   r9   r   ro   )r   r   ro   avgmax)rs   )r   outputsro   	convnext_r%   r&   z*Architecture configuration does not match z variant. When using pre-trained weights, the model architecture must match the pre-trained configuration exactly. Expected depths: z, got: z. Expected projection_dims: .zModel name "z"" does not match weights variant "z]". When using imagenet weights, model name must contain the weights variant (e.g., "convnext_z").z.h5z	_notop.h5models)cache_subdir	file_hash)#r   image_data_format
ValueErrorr   existsr	   obtain_input_shaper   Inputis_keras_tensorr   get_source_inputsr   r   r~   r   appendranger   nplinspacesumfloatr   validate_activationr   r   GlobalMaxPooling2Dr   MODEL_CONFIGSsplitWEIGHTS_HASHESget_fileBASE_WEIGHTS_PATHload_weights)#r%   r&   r9   r   r'   ro   include_preprocessinginclude_topr   input_tensorinput_shapepoolingclassesr   weights_name	img_inputr   rE   channel_axisnum_channelsstemdownsample_layersnum_downsample_layersidownsample_layerdepth_drop_ratescurnum_convnext_blocksjmodelexpected_configfile_suffixr   	file_nameweights_paths#                                      r=   ConvNeXtr   K  sF   ~   "&661
 	

 ))Z->->w-G<
 	
 *D  'y*
 	
 !33!--/#K LL{3	&&|4LLI$I 22<@C**,?AQ 	 #<!#341"T"1%A MM"L(	 %%4*;#;
	
 G^D  T"() 3%))  ::SVC #AE* ! 55A>	 ..Q7
 	  !12!3, ++c>3v;Ga 
 C&' 	 a #vay! 	A.q1/a8'=gaSs33	
 A	 	vay	 **+@'J
D"7
 	 e/--/2A+))+A.A3F%%d3A6fad;E *'(:(:;(G(KLoh///2C"DD<\N K- .=X-F,G Hx;"#456go=NaQ  t#tf % > "E%%k2267s<  *K&|4Q7I%K&|4Q7I;&	!**	)!	
 	<( L 
	7#L_s    P8z(keras.applications.convnext.ConvNeXtTinyzkeras.applications.ConvNeXtTinyc	                 r    t        dt        d   d   t        d   d   ddt        d   d   || |||||||      S )	Nr   r-   r%   r&   r   rp   r'   r   r%   r&   r9   r   r'   ro   r   r   r   r   r   r   r   r   r   r   	r   r   r   r   r   r   r   r   ro   s	            r=   ConvNeXtTinyr   ?  ]    " $V$X.%f-.?@#"6*>:3!3 r>   z)keras.applications.convnext.ConvNeXtSmallz keras.applications.ConvNeXtSmallc	                 r    t        dt        d   d   t        d   d   ddt        d   d   || |||||||      S )	Nr   r.   r%   r&   r   rp   r'   r   r   r   s	            r=   ConvNeXtSmallr   c  ]    " %W%h/%g./@A#"7+N;3!3 r>   z(keras.applications.convnext.ConvNeXtBasezkeras.applications.ConvNeXtBasec	                 r    t        dt        d   d   t        d   d   ddt        d   d   || |||||||      S )	Nr   r/   r%   r&   r   rp   r'   r   r   r   s	            r=   ConvNeXtBaser     r   r>   z)keras.applications.convnext.ConvNeXtLargez keras.applications.ConvNeXtLargec	                 r    t        dt        d   d   t        d   d   ddt        d   d   || |||||||      S )	Nr   r0   r%   r&   r   rp   r'   r   r   r   s	            r=   ConvNeXtLarger     r   r>   z*keras.applications.convnext.ConvNeXtXLargez!keras.applications.ConvNeXtXLargec	                 r    t        dt        d   d   t        d   d   ddt        d   d   || |||||||      S )	Nr   r1   r%   r&   r   rp   r'   r   r   r   s	            r=   ConvNeXtXLarger     s]    " &X&x0%h/0AB#"8,^<3!3 r>   r   rv   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 tensor.
        data_format: Optional data format of the image tensor/array. Defaults to
            None, in which case the global setting
            `keras.backend.image_data_format()` is used
            (unless you changed it, it defaults to `"channels_last"`).{mode}

    Returns:
        Unchanged `numpy.array` or tensor.
    r6   )rE   r   s     r=   preprocess_inputr     s	    & Hr>   z.keras.applications.convnext.decode_predictionsc                 0    t        j                  | |      S )N)top)r	   decode_predictions)predsr   s     r=   r   r     s    ,,U<<r>   )r   rp   NrO   )r   NN)r   rp   r$   convnextTTNNNNr   softmaxN)	TTr   NNNr   r   r   )	TTr   NNNr   r   r   )	TTr   NNNr   r   r   )	TTr   NNNr   r   r   )	TTr   NNNr   r   r   )   )(numpyr   	keras.srcr   r   r   r   r   keras.src.api_exportr   keras.src.applicationsr	   keras.src.layers.layerr
   keras.src.modelsr   r   keras.src.opsr   keras.src.utilsr   r   r   r   BASE_DOCSTRINGr3   rW   r   r   r   r   r   r   r   r   r   formatrS   r   r   r6   r>   r=   <module>r     s     "    - 1 ( ' ' ) & M 
#4 .  .  0  0  1+8BJ"e "J' 'V KO;|(@ 	#nh 2) #	< 3* #	< 2) #	< 3* #	< 4+ #	< &,,.,A &--?-C %,,.,A &--?-C '..4D.E  <= >* >?= @= ,>>FF  r>   