a
    Sics                     @   s   d Z ddlZddlZddlZddlZddlZddlm  m	Z
 ddlmZ ddlmZ eddddZdd	d
Zdd ZdddZdddZd ddZdd Zdd Zdd ZG dd dZdS )!z/Utilities related to layer/model functionality.    N)io_utils)keras_exportzkeras.utils.get_source_inputsc                    s   t | ds| S |du s|r&| j\}}}|js2| gS |j| }|jrPtj|jS g }| D ]B\}}}} t	| ||}|D ]$ t
 fdd|D rx|  qxq\|S dS )a  Returns the list of input tensors necessary to compute `tensor`.

    Output will always be a list of tensors
    (potentially with 1 element).

    Args:
        tensor: The tensor to start from.
        layer: Origin layer of the tensor. Will be
            determined via tensor._keras_history if not provided.
        node_index: Origin node index of the tensor.

    Returns:
        List of input tensors.
    _keras_historyNc                 3   s   | ]} |uV  qd S N ).0txr   S/var/www/html/django/DPS/env/lib/python3.9/site-packages/keras/utils/layer_utils.py	<genexpr>B       z$get_source_inputs.<locals>.<genexpr>)hasattrr   _inbound_nodesis_inputtfnestflatteninput_tensorsiterate_inboundget_source_inputsallappend)tensorlayer
node_index_nodesource_tensorsprevious_sourcesr   r	   r   r       s     

r   Fc                 C   s   |r| du rdS |r t | r dS t| tr6| |v r6dS |r>dnd}||rLdnd7 }|d|f 7 }|rrd| d}nd}td| d	| d
| d| d|  
dS )z0Validates the correctness of a string-based arg.Nz`None`,  za `Callable`, z"or one of the following values: %szIf restoring a model and `z` is a custom callable, please ensure the callable is registered as a custom object. See https://www.tensorflow.org/guide/keras/save_and_serialize#registering_the_custom_object for details. zUnkown value for `z` argument of layer z. zAllowed values are: z. Received: )callable
isinstancestr
ValueError)
input_dataallowable_strings
layer_namearg_name
allow_noneallow_callablesallowed_argsZcallable_noter   r   r   validate_string_argG   s0    	
r,   c                 C   sR   dd | D   }dd |D }dd |D }dd |D }ttdd |D S )	zCount the total number of scalars composing the weights.

    Args:
        weights: An iterable containing the weights on which to compute params

    Returns:
        The total number of scalars composing the weights
    c                 S   s   i | ]}t ||qS r   )idr   wr   r   r   
<dictcomp>u   r   z count_params.<locals>.<dictcomp>c                 S   s   g | ]}t |d r|qS )shape)r   r.   r   r   r   
<listcomp>w   r   z count_params.<locals>.<listcomp>c                 S   s   g | ]}|j  qS r   )r1   as_listr.   r   r   r   r2   x   r   c                 S   s   g | ]}d d |D qS )c                 S   s   g | ]}|d u rdn|qS )Nr   r   )r   w_ir   r   r   r2   z   r   z+count_params.<locals>.<listcomp>.<listcomp>r   r.   r   r   r   r2   y   s   c                 s   s   | ]}t |V  qd S r   )npprodr   pr   r   r   r   |   r   zcount_params.<locals>.<genexpr>)valuesintsum)weightsunique_weightsweight_shapesstandardized_weight_shapesr   r   r   count_paramsl   s    	r@   c                    s    durXt  dkr,td  dt   t d trHt d tsftd  ndt | jgS  fdd	t| jD } fd
d	t| jD }|r|std  t|t|krt|t|d gS t|t|d gS )a3  Get the layer indexes from the model based on layer names.

    The layer indexes can be used to slice the model into sub models for
    display.

    Args:
        model: `tf.keras.Model` instance.
        layer_names: a list or tuple of 2 strings, the starting layer name and
            ending layer name (both inclusive) for the result. All layers will
            be included when `None` is provided.

    Returns:
        The index value of layer based on its unique name (layer_names).
        Output will be [first_layer_index, last_layer_index + 1].
    N   zIlayer_range must be a list or tuple of length 2. Received: layer_range = z of length r      z7layer_range should contain string type only. Received: c                    s&   g | ]\}}t  d  |jr|qS r   rematchnamer   idxr   layer_ranger   r   r2      s   z7get_layer_index_bound_by_layer_name.<locals>.<listcomp>c                    s&   g | ]\}}t  d  |jr|qS )rB   rD   rH   rJ   r   r   r2      s   zHPassed layer_names do not match the layer names in the model. Received: )lenr$   r"   r#   layers	enumerateminmax)modelrK   Zlower_indexZupper_indexr   rJ   r   #get_layer_index_bound_by_layer_name   sB    

rR   c                    s  du rt j| jjdkr d	n| js,d	nd	| j }g }|D ]F}	t|	dksxt|	dkrttj	
|	d jdkrd	 q||	7 }qB	r| jD ]6}
d}|
jD ]}||v r|rd	 qqd}q	s qq	rpdpg dd	 dkrfd
dD g d}n^pdp&g dd	 dkrHfddD g d}g | j D ]}	|	7 q^
rd7  |d t| |}d"fdd	d| j d  | d  d#
fdd	d$
fdd	d% 	fdd	| j|d |d  D ]}
|
 q0d  t| drdt| j}n
t| j}t| j}d||  d | d!| d  dS )&a  Prints a summary of a model.

    Args:
        model: Keras model instance.
        line_length: Total length of printed lines
            (e.g. set this to adapt the display to different
            terminal window sizes).
        positions: Relative or absolute positions of log elements in each line.
            If not provided, defaults to `[.33, .55, .67, 1.]`.
        print_fn: Print function to use.
            It will be called on each line of the summary.
            You can set it to a custom function
            in order to capture the string summary.
            It defaults to `print` (prints to stdout).
        expand_nested: Whether to expand the nested models.
            If not provided, defaults to `False`.
        show_trainable: Whether to show if a layer is trainable.
            If not provided, defaults to `False`.
        layer_range: List or tuple containing two strings,
            the starting layer name and ending layer name (both inclusive),
            indicating the range of layers to be printed in the summary. The
            strings could also be regexes instead of an exact name. In this
             case, the starting layer will be the first layer that matches
            `layer_range[0]` and the ending layer will be the last element that
            matches `layer_range[1]`. By default (`None`) all
            layers in the model are included in the summary.
    N
SequentialTrB   r   FA   )g?g333333?      ?c                    s   g | ]}t  | qS r   r:   r7   line_lengthr   r   r2     r   z!print_summary.<locals>.<listcomp>)Layer (type)Output ShapeParam #b   )gQ?g?gq=
ףp?rU   c                    s   g | ]}t  | qS r   rW   r7   rX   r   r   r2   	  r   )rZ   r[   r\   zConnected to   Z	Trainablec                    sR  dd | D }t |rNd}tt|D ]}|dkrD||d  }nd}|| }|t|d krddnd}|| | }	|| d |	  d}
 fdd|
D }|rt|}	 d |	  |dkr|d	| d
 7 }| 7 }||rd
| nd7 }|| |	d  ||< |r|d
|| t| |  7 }q(|d
|| t|  7 }q(|d	| 7 }| qd S )Nc                 S   s   g | ]}t |qS r   )r#   r   r
   r   r   r   r2     r   z4print_summary.<locals>.print_row.<locals>.<listcomp>r    r   rB   rA   )z),z},z],z',c                    s,   g | ]$}  |d kr  |t| qS rC   )findrL   r_   Zfit_into_liner   r   r2   )  s   | )anyrangerL   rO   )fields	positionsnested_levelZleft_to_printlinecol	start_posend_posspacecutoffZline_break_conditionsZcandidate_cutoffs)print_fnra   r   	print_row  s8    

z print_summary.<locals>.print_rowzModel: "{}"r   =c                    s   z
| j }W n* ty    d}Y n ty4   d}Y n0 | j}| jj}| js\t| dds\d}n|  }|d | d ||g}r|	| j
rdnd	 | | d
S )zPrints a summary for a single layer.

        Args:
            layer: target layer.
            nested_level: level of nesting of the layer inside its parent layer
              (e.g. 0 for a top-level layer, 1 for a nested layer).
        multiple?_is_graph_networkFz
0 (unused) ()YNN)output_shapeAttributeErrorRuntimeErrorrG   	__class____name__builtgetattrr@   r   	trainable)r   rh   ry   rG   cls_nameparamsrf   )rg   rp   show_trainabler   r   print_layer_summaryE  s    

z*print_summary.<locals>.print_layer_summaryc              	      s   z
| j }W n ty    d}Y n0 g }| jD ]>}r>|vr>q,| D ]"\}}}}|d|j|| qFq,| j}	| jj}
|	d |
 d || 	 |g}r|| j
rdnd | | dS )a  Prints a summary for a single layer (including topological connections).

        Args:
            layer: target layer.
            nested_level: level of nesting of the layer inside its parent layer
              (e.g. 0 for a top-level layer, 1 for a nested layer).
        rr   z
{}[{}][{}]ru   rv   rw   rx   N)ry   rz   r   r   r   formatrG   r|   r}   r@   r   )r   rh   ry   connectionsr   inbound_layerr   tensor_indexr   rG   r   rf   )rg   rp   relevant_nodesr   r   r   $print_layer_summary_with_connectionsc  s:    


z;print_summary.<locals>.print_layer_summary_with_connectionsc                    s   r| | n
| |  rt | dr| jrƈd|d  dd|  d   d|d    | j}d}tt|D ],}|t|d krd}|| |d | qtd| dd|    d|   |sd| dd|    d|   d S )	NrM   rb   rB      ¯rA   FTrc   )r   rM   re   rL   )r   rh   Zis_nested_lastZnested_layeri)expand_nestedrY   ro   print_layerr   r   sequential_liker   r   r     s@    


z"print_summary.<locals>.print_layer_collected_trainable_weightszTotal params: {:,}zTrainable params: {:,}zNon-trainable params: {:,})r   )r   )r   )r   F)r   	print_msgr|   r}   rt   _nodes_by_depthr9   rL   r   r   r   keras_inputsrM   r   r   rR   r   rG   r   r@   r   trainable_weightsnon_trainable_weights)rQ   rY   rg   ro   r   r   rK   nodes_by_depthnodesvr   flagr   
to_displaytrainable_countnon_trainable_countr   )r   rY   rg   ro   r   r   r   rp   r   r   r   r   print_summary   s    $









)
,!

r   channels_firstc                 C   s   |dv sJ |   \}}t|jd D ]}|dkrj|\}}}|||f}	|dd|f |	}
t|
d}
n6|\}}}|||f}	|dd|f |	}
t|
d}
t|
t|f|dd|f< q&| ||g dS )a]  Utility useful when changing a convnet's `data_format`.

    When porting the weights of a convnet from one data format to the other,
    if the convnet includes a `Flatten` layer
    (applied to the last convolutional feature map)
    followed by a `Dense` layer, the weights of that `Dense` layer
    should be updated to reflect the new dimension ordering.

    Args:
        dense: The target `Dense` layer.
        previous_feature_map_shape: A shape tuple of 3 integers,
            e.g. `(512, 7, 7)`. The shape of the convolutional
            feature map right before the `Flatten` layer that
            came before the target `Dense` layer.
        target_data_format: One of "channels_last", "channels_first".
            Set it "channels_last"
            if converting a "channels_first" model to "channels_last",
            or reciprocally.
    >   r   channels_lastrB   r   N)rA   r   rB   )rB   rA   r   )get_weightsre   r1   reshaper5   	transposer6   set_weights)denseprevious_feature_map_shapetarget_data_formatkernelbiasr   chr/   original_fm_shapekir   r   r   !convert_dense_weights_data_format  s    



"r   c                 C   s$   t | dd sdS | jdko"| jdkS )N_keras_api_namesF)zkeras.layers.Layer)r   r   _keras_api_names_v1)r   r   r   r   is_builtin_layer  s
    
r   c                    s*   t   t fdd} |_|S )a
  Lightweight decorator for caching lazily constructed properties.

    When to use:
    This decorator provides simple caching with minimal overhead. It is designed
    for properties which are expensive to compute and static over the life of a
    class instance, and provides no mechanism for cache invalidation. Thus it is
    best suited for lazily exposing derived properties of other static data.

    For classes with custom getattr / setattr behavior (such as trackable
    objects), storing cache results as object attributes is not performant.
    Instead, a specialized cache can significantly reduce property lookup
    overhead. (While still allowing the decorated property to be lazily
    computed.) Consider the following class:

    ```
    class MyClass:
      def __setattr__(self, key, value):
        # Some expensive class specific code
        # ...
        # ...

        super(MyClass, self).__setattr__(key, value)

      @property
      def thing(self):
        # `thing` is expensive to compute (and may not even be requested), so we
        # want to lazily compute it and then cache it.
        output = getattr(self, '_thing', None)
        if output is None:
          self._thing = output = compute_thing(self)
        return output
    ```

    It's also worth noting that ANY overriding of __setattr__, even something as
    simple as:
    ```
      def __setattr__(self, key, value):
        super(MyClass, self).__setattr__(key, value)
    ```

    Slows down attribute assignment by nearly 10x.

    By contrast, replacing the definition of `thing` with the following
    sidesteps the expensive __setattr__ altogether:

    '''
    @property
    @tracking.cached_per_instance
    def thing(self):
      # `thing` is expensive to compute (and may not even be requested), so we
      # want to lazily compute it and then cache it.
      return compute_thing(self)
    '''

    Performance:
    The overhead for this decorator is ~0.4 us / call. A much lower overhead
    implementation (~0.085 us / call) can be achieved by using a custom dict
    type:

    ```
    def dict_based_cache(f):
      class Cache(dict):
        __slots__ = ()
        def __missing__(self, key):
          self[key] = output = f(key)
          return output

      return property(Cache().__getitem__)
    ```

    However, that implementation holds class instances as keys, and as a result
    blocks garbage collection. (And modifying it to use weakref's as keys raises
    the lookup overhead to ~0.4 us) As a result, the WeakKeyDictionary
    implementation below turns out to be more prudent.

    Args:
      f: The function to cache.

    Returns:
      f decorated with simple caching behavior.
    c                    s&     | }|d u r"|   | < }|S r   )get)itemoutputcachefr   r   wrappedH  s    
z$cached_per_instance.<locals>.wrapped)weakrefWeakKeyDictionary	functoolswrapsr   )r   r   r   r   r   cached_per_instance  s
    Sr   c                 c   s   t  }| ddd }|r~| }t||v r.q|t| t|drXt|tsX|V  qt|ddpfg }||ddd  qdS )z4Filter out empty Layer-like containers and uniquify.NrV   	_is_layerrM   )	setpopr-   addr   r"   typer   extend)
layer_listexistingto_visitobj
sub_layersr   r   r   filter_empty_layer_containersS  s    r   c                   @   s   e Zd ZdZdd Zedd Zedd Zejdd Zee	d	d
 Z
edd Zejdd Zedd Zejdd Zedd ZdddZdddZdddZdd ZdS ) CallFunctionSpeczKCaches the spec and provides utilities for handling call function
    args.c                 C   s   || _ t| j j| _| jr8| jd dkr8| jdd | _|  j| j jpHg 7  _| j jdu}d| jv pf|| _d| jv pv|| _| j jpg }t	 }t
dt| dD ]}|| || j| < q|| j jpi  |d| _dS )zInitialies a `CallFunctionSpec`.

        Args:
          full_argspec: the FullArgSpec of a call function of a layer.
        r   selfrB   NtrainingmaskrV   )_full_argspeclistargs
_arg_names
kwonlyargsvarkw_expects_training_arg_expects_mask_argdefaultsdictre   rL   updatekwonlydefaultsr   _default_training_arg)r   full_argspecZcall_accepts_kwargscall_fn_defaultsr   r   r   r   r   __init__k  s     zCallFunctionSpec.__init__c                 C   s   | j S )z-Returns the FullArgSpec of the call function.)r   r   r   r   r   r     s    zCallFunctionSpec.full_argspecc                 C   s   | j S )z%List of names of args and kwonlyargs.r   r   r   r   r   	arg_names  s    zCallFunctionSpec.arg_namesc                 C   s
   || _ d S r   r   r   valuer   r   r   r     s    c                 C   s&   t  }t| jD ]\}}|||< q|S )z:Returns a dict mapping arg names to their index positions.)r   rN   r   )r   call_fn_arg_positionsposargr   r   r   arg_positions  s    
zCallFunctionSpec.arg_positionsc                 C   s   | j S )z9Whether the call function uses 'training' as a parameter.r   r   r   r   r   expects_training_arg  s    z%CallFunctionSpec.expects_training_argc                 C   s
   || _ d S r   r   r   r   r   r   r     s    c                 C   s   | j S )z5Whether the call function uses `mask` as a parameter.r   r   r   r   r   expects_mask_arg  s    z!CallFunctionSpec.expects_mask_argc                 C   s
   || _ d S r   r   r   r   r   r   r     s    c                 C   s   | j S )z3The default value given to the "training" argument.)r   r   r   r   r   default_training_arg  s    z%CallFunctionSpec.default_training_argFc                 C   s@   |s|sdS ||v rdS | j }|s.|dd }|tt||v S )a  Returns true if argument is present in `args` or `kwargs`.

        Args:
          arg_name: String name of the argument to find.
          args: Tuple of args passed to the call function.
          kwargs: Dictionary of kwargs  passed to the call function.
          inputs_in_args: Whether the input argument (the first argument in the
            call function) is included in `args`. Defaults to `False`.

        Returns:
          True if argument with `arg_name` is present in `args` or `kwargs`.
        FTrB   Nr   r   zip)r   r(   r   kwargsinputs_in_argscall_fn_argsr   r   r   arg_was_passed  s    zCallFunctionSpec.arg_was_passedc                 C   s<   ||v r|| S | j }|s&|dd }tt||}|| S )ak  Retrieves the value for the argument with name `arg_name`.

        Args:
          arg_name: String name of the argument to find.
          args: Tuple of args passed to the call function.
          kwargs: Dictionary of kwargs  passed to the call function.
          inputs_in_args: Whether the input argument (the first argument in the
            call function) is included in `args`. Defaults to `False`.

        Returns:
          The value of the argument with name `arg_name`, extracted from `args`
          or `kwargs`.

        Raises:
          KeyError if the value of `arg_name` cannot be found.
        rB   Nr   )r   r(   r   r   r   r   	args_dictr   r   r   get_arg_value  s    zCallFunctionSpec.get_arg_valuec                 C   s   | j jrLz*| j j|}| j jd dkr0|d8 }W qZ tyH   d}Y qZ0 n| j|d}|dur|sn|d }t||krt|}|||< t	||fS |du r|r|
|d n|||< ||fS )a  Sets the value of an argument into the given args/kwargs.

        Args:
          arg_name: String name of the argument to find.
          new_value: New value to give to the argument.
          args: Tuple of args passed to the call function.
          kwargs: Dictionary of kwargs  passed to the call function.
          inputs_in_args: Whether the input argument (the first argument in the
            call function) is included in `args`. Defaults to `False`.
          pop_kwarg_if_none: If the new value is `None`, and this is `True`,
            then the argument is deleted from `kwargs`.

        Returns:
          The updated `(args, kwargs)`.
        r   r   rB   N)r   varargsr   indexr$   r   r   rL   r   tupler   )r   r(   	new_valuer   r   r   pop_kwarg_if_nonearg_posr   r   r   set_arg_value  s&    zCallFunctionSpec.set_arg_valuec                 C   sV   |r|d }|dd }n2| j d |v rDt|}|| j d }ntd|||fS )z2Splits (args, kwargs) into (inputs, args, kwargs).r   rB   Nz9The first argument to `Layer.call` must always be passed.)r   copyr   r$   )r   r   r   inputsr   r   r   split_out_first_arg   s    
z$CallFunctionSpec.split_out_first_argN)F)F)FF)r}   
__module____qualname____doc__r   propertyr   r   setterr   r   r   r   r   r   r   r   r   r   r   r   r   r   g  s6   !


	






   
0r   )NN)FF)N)NNNFFN)r   )r   r   r   rE   r   numpyr5   tensorflow.compat.v2compatv2r   keras.utilsr    tensorflow.python.util.tf_exportr   r   r,   r@   rR   r   r   r   r   r   r   r   r   r   r   <module>   s<   +  
%
8      
   
'`