
    2Vh:F                         d 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  G d de      Zy)z(Keras base class for convolution layers.    )activations)constraints)initializers)ops)regularizers)standardize_data_format)	InputSpec)Layer)compute_conv_output_shape)standardize_padding)standardize_tuplec                        e Zd ZdZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fd	Zd Zed        Zd Zd Z	d Z
	 	 	 ddZd	 Zd
 Z fdZd Z xZS )BaseConva  Abstract N-D convolution layer (private, used as implementation base).

    This layer creates a convolution kernel that is convolved (actually
    cross-correlated) with the layer input to produce a tensor of outputs. If
    `use_bias` is True (and a `bias_initializer` is provided), a bias vector is
    created and added to the outputs. Finally, if `activation` is not `None`, it
    is applied to the outputs as well.

    Note: layer attributes cannot be modified after the layer has been called
    once (except the `trainable` attribute).

    Args:
        rank: int, the rank of the convolution, e.g. 2 for 2D convolution.
        filters: int, the dimension of the output space (the number of filters
            in the convolution).
        kernel_size: int or tuple/list of `rank` integers, specifying the size
            of the convolution window.
        strides: int or tuple/list of `rank` integers, specifying the stride
            length of the convolution. If only one int is specified, the same
            stride size will be used for all dimensions. `strides > 1` is
            incompatible with `dilation_rate > 1`.
        padding: string, either `"valid"` or `"same"` (case-insensitive).
            `"valid"` means no padding. `"same"` results in padding evenly to
            the left/right or up/down of the input. When `padding="same"` and
            `strides=1`, the output has the same size as the input.
        data_format: string, either `"channels_last"` or `"channels_first"`.
            The ordering of the dimensions in the inputs. `"channels_last"`
            corresponds to inputs with shape `(batch, steps, features)`
            while `"channels_first"` corresponds to inputs with shape
            `(batch, features, steps)`. It defaults to the `image_data_format`
            value found in your Keras config file at `~/.keras/keras.json`.
            If you never set it, then it will be `"channels_last"`.
        dilation_rate: int or tuple/list of `rank` integers, specifying the
            dilation rate to use for dilated convolution. If only one int is
            specified, the same dilation rate will be used for all dimensions.
        groups: A positive int specifying the number of groups in which the
            input is split along the channel axis. Each group is convolved
            separately with `filters // groups` filters. The output is the
            concatenation of all the `groups` results along the channel axis.
            Input channels and `filters` must both be divisible by `groups`.
        activation: Activation function. If `None`, no activation is applied.
        use_bias: bool, if `True`, bias will be added to the output.
        kernel_initializer: Initializer for the convolution kernel. If `None`,
            the default initializer (`"glorot_uniform"`) will be used.
        bias_initializer: Initializer for the bias vector. If `None`, the
            default initializer (`"zeros"`) will be used.
        kernel_regularizer: Optional regularizer for the convolution kernel.
        bias_regularizer: Optional regularizer for the bias vector.
        activity_regularizer: Optional regularizer function for the output.
        kernel_constraint: Optional projection function to be applied to the
            kernel after being updated by an `Optimizer` (e.g. used to implement
            norm constraints or value constraints for layer weights). The
            function must take as input the unprojected variable and must return
            the projected variable (which must have the same shape). Constraints
            are not safe to use when doing asynchronous distributed training.
        bias_constraint: Optional projection function to be applied to the
            bias after being updated by an `Optimizer`.
        lora_rank: Optional integer. If set, the layer's forward pass
            will implement LoRA (Low-Rank Adaptation)
            with the provided rank. LoRA sets the layer's kernel
            to non-trainable and replaces it with a delta over the
            original kernel, obtained via multiplying two lower-rank
            trainable matrices. This can be useful to reduce the
            computation cost of fine-tuning large dense layers.
            You can also enable LoRA on an existing layer by calling
            `layer.enable_lora(rank)`.
        lora_alpha: Optional integer. If set, this parameter scales the
            low-rank adaptation delta (computed as the product of two lower-rank
            trainable matrices) during the forward pass. The delta is scaled by
            `lora_alpha / lora_rank`, allowing you to fine-tune the strength of
            the LoRA adjustment independently of `lora_rank`.
    c                    t        |   dd|i| || _        || _        || _        t        ||d      | _        t        ||d      | _        t        ||d      | _        t        ||dk(        | _
        t        |      | _        t        j                  |	      | _        |
| _        t#        j                  |      | _        t#        j                  |      | _        t)        j                  |      | _        t)        j                  |      | _        t/        j                  |      | _        t/        j                  |      | _        || _        ||n|| _        d| _        t;        | j                  dz   	      | _        | j                  | _        | j                  (| j                  d
k  rt?        d| j                   d      | j                  d
k  rt?        d| j                   d      | j                  B| j                  | j                  z  d
k7  r&t?        d| j                   d| j                   d      tA        | j                        st?        d| j                   d      tA        | j                        st?        d| j                         tC        | j                        dkD  r>tC        | j                        dkD  r%t?        d| j                   d| j                         y y )Nactivity_regularizerkernel_sizestridesdilation_rate   )allow_causalF   )min_ndimr   z[Invalid value for argument `filters`. Expected a strictly positive value. Received filters=.zBThe number of groups must be a positive integer. Received: groups=zYThe number of filters must be evenly divisible by the number of groups. Received: groups=z
, filters=zBThe argument `kernel_size` cannot contain 0. Received kernel_size=z;The argument `strides` cannot contains 0. Received strides=zW`strides > 1` not supported in conjunction with `dilation_rate > 1`. Received: strides=z and dilation_rate= )"super__init__rankfiltersgroupsr   r   r   r   r   paddingr   data_formatr   get
activationuse_biasr   kernel_initializerbias_initializerr   kernel_regularizerbias_regularizerr   kernel_constraintbias_constraint	lora_rank
lora_alphalora_enabledr	   
input_spec
ValueErrorallmax)selfr   r   r   r   r    r!   r   r   r#   r$   r%   r&   r'   r(   r   r)   r*   r+   r,   kwargs	__class__s                        X/home/dcms/DCMS/lib/python3.12/site-packages/keras/src/layers/convolutional/base_conv.pyr   zBaseConv.__init__Z   s   . 	M.BMfM	,[$N($	B.4
 +7K2;?%//*5 "."2"23E"F , 0 01A B"."2"23E"F , 0 01A B!,1B!C*?"(2(>*I!#TYY];++<<#(9448LL>D 
 ;;!$$(KK=3 
 <<#t{{(Ba(G66:kk] C<<.+  4##$#//03 
 4<< <<.* 
 t||q S););%<q%@::>,, H!!%!3!3 46  &A     c           	         | j                   dk(  rd}|d   }nd}|d   }t        | j                  dz   ||i      | _        || j                  z  dk7  rt        d| j                   d| d	| d
      | j                  || j                  z  | j                  fz   }| j                  |       | j                  d|| j                  | j                  | j                  d| j                        | _        | j                  rQ| j                  d| j                  f| j                   | j"                  | j$                  d| j                        | _        nd | _        d| _        | j*                  r(| j-                  | j*                  | j.                         y y )Nchannels_lastr   r   )r   axesr   z_The number of input channels must be evenly divisible by the number of groups. Received groups=z, but the input has z channels (full input shape is z).kernelT)nameshapeinitializerregularizer
constraint	trainabledtypebias)r,   )r!   r	   r   r.   r   r/   r   r   compute_output_shape
add_weightr%   r'   r)   rB   _kernelr$   r&   r(   r*   rC   builtr+   enable_lorar,   )r2   input_shapechannel_axisinput_channelkernel_shapes        r5   buildzBaseConv.build   s   .L'OML'NM#YY],)F
 4;;&!+99= F*O+J-r#  ''T[[(LL+
 
 	!!+.////--** ' 
 ==||o 11 11//jj ( DI DI
>>T^^H r6   c                    | j                   st        d      | j                  rQ| j                  | j                  | j
                  z  t        j                  | j                  | j                        z  z   S | j                  S )Nz3You must build the layer before accessing `kernel`.)
rG   AttributeErrorr-   rF   r,   r+   r   matmullora_kernel_alora_kernel_b)r2   s    r5   r;   zBaseConv.kernel   ss    zz E  <<$..0

4--t/A/AB#C C C ||r6   c                     t        j                  ||t        | j                        | j                  | j
                  | j                        S )N)r   r    r   r!   )r   convlistr   r    r   r!   )r2   inputsr;   s      r5   convolution_opzBaseConv.convolution_op   s>    xx&LL,,((
 	
r6   c                    | j                  || j                        }| j                  r| j                  dk(  r!d| j                  dz   z  | j
                  fz   }nd| j
                  fd| j                  z  z   }t        j                  | j                  |      }t        j                  ||      }| j                  | j                  |      S |S )Nr8   )r   r   )rW   r;   r$   r!   r   r   r   reshaperC   addr#   )r2   rV   outputs
bias_shaperC   s        r5   callzBaseConv.call   s    %%KK
 ==?2!TYY]3t||oE
.		1AA
;;tyy*5Dgggt,G??&??7++r6   c           	          t        || j                  | j                  | j                  | j                  | j
                  | j                        S )N)r   r    r!   r   )r   r   r   r   r    r!   r   )r2   rI   s     r5   rD   zBaseConv.compute_output_shape
  sB    (LLLLLL((,,
 	
r6   c                    | j                   rt        d      | j                  st        d      | j                  rt        d      | j                  j                          | j                  d| j                  j                  d d |fz   t        j                  |      | j                        | _        | j                  d|| j                  ft        j                  |      | j                        | _        d| j                  _        | j                  j!                          d	| _        || _        ||| _        y || _        y )
Nz}Lora is incompatible with kernel constraints. In order to enable lora on this layer, remove the `kernel_constraint` argument.z3Cannot enable lora on a layer that isn't yet built.z>lora is already enabled. This can only be done once per layer.rQ   r9   )r<   r=   r>   r?   rR   FT)r)   r/   rG   r-   _trackerunlockrE   rF   r=   r   r"   r'   rQ   r   rR   rA   lockr+   r,   )r2   r   r,   a_initializerb_initializers        r5   rH   zBaseConv.enable_lora  s-    !!0 
 zzE  P  	!__ ,,$$Sb)TG3$((7//	 - 
 "__ &$((7//	 - 
 "' (2(>*Dr6   c                     | j                   sy | j                  g}| j                  r|j                  | j                         t        |      D ]  \  }}||t        |      <    y N)rG   r;   r$   appendrC   	enumeratestrr2   storetarget_variablesivariables        r5   save_own_variableszBaseConv.save_own_variables=  sW    zz KK===##DII.$%56 	%KAx$E#a&M	%r6   c                 B   | j                   s| j                  |       | j                  sy | j                  g}| j                  r|j                  | j                         t        |      D ]"  \  }}|j                  |t        |                $ | j                   r| j                  j                  t        j                  | j                  j                               | j                  j                  t        j                  | j                  j                               y y rf   )r-   _check_load_own_variablesrG   rF   r$   rg   rC   rh   assignri   rQ   r   zerosr=   rR   rj   s        r5   load_own_variableszBaseConv.load_own_variablesG  s      **51zz LL>==##DII.$%56 	+KAxOOE#a&M*	+%%cii0B0B0H0H&IJ%%cii0B0B0H0H&IJ r6   c                 j   t         |          }|j                  i d| j                  d| j                  d| j
                  d| j                  d| j                  d| j                  d| j                  dt        j                  | j                        d	| j                  d
t        j                  | j                        dt        j                  | j                         dt#        j                  | j$                        dt#        j                  | j&                        dt#        j                  | j(                        dt+        j                  | j,                        dt+        j                  | j.                               | j0                  r| j0                  |d<   | j2                  |d<   |S )Nr   r   r   r    r!   r   r   r#   r$   r%   r&   r'   r(   r   r)   r*   r+   r,   )r   
get_configupdater   r   r   r    r!   r   r   r   	serializer#   r$   r   r%   r&   r   r'   r(   r   r   r)   r*   r+   r,   )r2   configr4   s     r5   rv   zBaseConv.get_configV  s   #%4<<t// 4<< 4<<	
 t//  !3!3 $++ k33DOOD DMM %l&<&<++' #L$:$:))%  %l&<&<++'!& #L$:$:))%', '(>(>--)-2 $[%:%:**&38 ";#8#89M9M#N9	
@ >>"&..F;#'??F< r6   c                 
   | j                   | j                  z   }t        |j                               t        |      k7  rt        |      dk(  rY| j                  sMt        d| j                   dt        |j                                d| j                   d| j                   d	      t        d| j                   dt        |       dt        |j                                d	|D cg c]  }|j                   c}       y c c}w )
Nr   zLayer 'zY' was never built and thus it doesn't have any variables. However the weights file lists z variables for this layer.
In most cases, this error indicates that either:

1. The layer is owned by a parent layer that implements a `build()` method, but calling the parent's `build()` method did NOT create the state of the child layer 'z'. A `build()` method must create ALL state for the layer, including the state of any children layers.

2. You need to implement the `def build_from_config(self, config)` method on layer 'a-  ', to specify how to rebuild it during loading. In this case, you might also want to implement the method that generates the build config at saving time, `def get_build_config(self)`. The method `build_from_config()` is meant to create the state of the layer (i.e. its variables) upon deserialization.z' expected z variables, but received z% variables during loading. Expected: )_trainable_variables_non_trainable_variableslenkeysrG   r/   r<   )r2   rk   all_varsvs       r5   rq   z"BaseConv._check_load_own_variables}  s    ,,t/L/LLuzz|H-8}!$** dii[ )669%**,6G5H I( )-		{ 3!
 "& ,NN . $))KH ? uzz|$% &.67aff78: 3 .: 8s   #D )r   validNr   r   NTglorot_uniformrs   NNNNNNN)N
he_uniformrs   )__name__
__module____qualname____doc__r   rM   propertyr;   rW   r]   rD   rH   ro   rt   rv   rq   __classcell__)r4   s   @r5   r   r      s    G\ + !)Tl1If 	 	
"	
 "&IP%K%N r6   r   N)r   	keras.srcr   r   r   r   r   keras.src.backendr   keras.src.layers.input_specr	   keras.src.layers.layerr
   keras.src.ops.operation_utilsr   #keras.src.utils.argument_validationr   r   r   r   r6   r5   <module>r      s7    . ! ! "  " 5 1 ( C C AMu Mr6   