
    2Vh+                         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  ed       G d	 d
e             Zy)    )backend)keras_export)Layer)backend_utils)numerical_utils)tf_utils
tensorflowzkeras.layers.Hashingc                   H     e Zd ZdZ	 	 	 	 d fd	Zd Zd Zd Z fdZ xZ	S )HashingaB  A preprocessing layer which hashes and bins categorical features.

    This layer transforms categorical inputs to hashed output. It element-wise
    converts a ints or strings to ints in a fixed range. The stable hash
    function uses `tensorflow::ops::Fingerprint` to produce the same output
    consistently across all platforms.

    This layer uses [FarmHash64](https://github.com/google/farmhash) by default,
    which provides a consistent hashed output across different platforms and is
    stable across invocations, regardless of device and context, by mixing the
    input bits thoroughly.

    If you want to obfuscate the hashed output, you can also pass a random
    `salt` argument in the constructor. In that case, the layer will use the
    [SipHash64](https://github.com/google/highwayhash) hash function, with
    the `salt` value serving as additional input to the hash function.

    **Note:** This layer internally uses TensorFlow. It cannot
    be used as part of the compiled computation graph of a model with
    any backend other than TensorFlow.
    It can however be used with any backend when running eagerly.
    It can also always be used as part of an input preprocessing pipeline
    with any backend (outside the model itself), which is how we recommend
    to use this layer.

    **Note:** This layer is safe to use inside a `tf.data` pipeline
    (independently of which backend you're using).

    **Example (FarmHash64)**

    >>> layer = keras.layers.Hashing(num_bins=3)
    >>> inp = [['A'], ['B'], ['C'], ['D'], ['E']]
    >>> layer(inp)
    array([[1],
            [0],
            [1],
            [1],
            [2]])>

    **Example (FarmHash64) with a mask value**

    >>> layer = keras.layers.Hashing(num_bins=3, mask_value='')
    >>> inp = [['A'], ['B'], [''], ['C'], ['D']]
    >>> layer(inp)
    array([[1],
            [1],
            [0],
            [2],
            [2]])

    **Example (SipHash64)**

    >>> layer = keras.layers.Hashing(num_bins=3, salt=[133, 137])
    >>> inp = [['A'], ['B'], ['C'], ['D'], ['E']]
    >>> layer(inp)
    array([[1],
            [2],
            [1],
            [0],
            [2]])

    **Example (Siphash64 with a single integer, same as `salt=[133, 133]`)**

    >>> layer = keras.layers.Hashing(num_bins=3, salt=133)
    >>> inp = [['A'], ['B'], ['C'], ['D'], ['E']]
    >>> layer(inp)
    array([[0],
            [0],
            [2],
            [1],
            [0]])

    Args:
        num_bins: Number of hash bins. Note that this includes the `mask_value`
            bin, so the effective number of bins is `(num_bins - 1)`
            if `mask_value` is set.
        mask_value: A value that represents masked inputs, which are mapped to
            index 0. `None` means no mask term will be added and the
            hashing will start at index 0. Defaults to `None`.
        salt: A single unsigned integer or None.
            If passed, the hash function used will be SipHash64,
            with these values used as an additional input
            (known as a "salt" in cryptography).
            These should be non-zero. If `None`, uses the FarmHash64 hash
            function. It also supports tuple/list of 2 unsigned
            integer numbers, see reference paper for details.
            Defaults to `None`.
        output_mode: Specification for the output of the layer. Values can be
            `"int"`, `"one_hot"`, `"multi_hot"`, or
            `"count"` configuring the layer as follows:
            - `"int"`: Return the integer bin indices directly.
            - `"one_hot"`: Encodes each individual element in the input into an
                array the same size as `num_bins`, containing a 1
                at the input's bin index. If the last dimension is size 1,
                will encode on that dimension.
                If the last dimension is not size 1, will append a new
                dimension for the encoded output.
            - `"multi_hot"`: Encodes each sample in the input into a
                single array the same size as `num_bins`,
                containing a 1 for each bin index
                index present in the sample. Treats the last dimension
                as the sample dimension, if input shape is
                `(..., sample_length)`, output shape will be
                `(..., num_tokens)`.
            - `"count"`: As `"multi_hot"`, but the int array contains a count of
                the number of times the bin index appeared in the sample.
            Defaults to `"int"`.
        sparse: Boolean. Only applicable to `"one_hot"`, `"multi_hot"`,
            and `"count"` output modes. Only supported with TensorFlow
            backend. If `True`, returns a `SparseTensor` instead of
            a dense `Tensor`. Defaults to `False`.
        **kwargs: Keyword arguments to construct a layer.

    Input shape:
        A single string, a list of strings, or an `int32` or `int64` tensor
        of shape `(batch_size, ...,)`.

    Output shape:
        An `int32` tensor of shape `(batch_size, ...)`.

    Reference:

    - [SipHash with salt](https://www.131002.net/siphash/siphash.pdf)
    c                    t         j                  st        d      d|vs|d   |dk(  rdnt        j                         |d<   t        |   di | ||dk  rt        d| d      |dk(  r)| j                  j                  dvrt        d	|d          d
}||vrt        d| d|       |r|dk(  rt        d| d|       || _
        || _        |dnd| _        || _        || _        d | _        |^t!        |t"        t$        f      rt'        |      dk(  rt%        |      | _        n)t!        |t(              r
||g| _        nt        d| d      d| _        d| _        d| _        y )NzKLayer Hashing requires TensorFlow. Install it via `pip install tensorflow`.dtypeintint64r   zYThe `num_bins` for `Hashing` cannot be `None` or non-positive values. Received: num_bins=.)int32r   z`When `output_mode="int"`, `dtype` should be an integer type, 'int32' or 'in64'. Received: dtype=)r   one_hot	multi_hotcountz:Invalid value for argument `output_mode`. Expected one of z. Received: output_mode=zi`sparse` may only be true if `output_mode` is `"one_hot"`, `"multi_hot"`, or `"count"`. Received: sparse=z and output_mode=TF   znThe `salt` argument for `Hashing` can only be a tuple of size 2 integers, or a single integer. Received: salt= )tf	availableImportErrorr   floatxsuper__init__
ValueErrordtype_policynamenum_bins
mask_valuestrong_hashoutput_modesparsesalt
isinstancetuplelistlenr   _convert_input_args!_allow_non_tensor_positional_argssupports_jit)	selfr!   r"   r&   r$   r%   kwargsaccepted_output_modes	__class__s	           V/home/dcms/DCMS/lib/python3.12/site-packages/keras/src/layers/preprocessing/hashing.pyr   zHashing.__init__   s    ||;  & F7O$;&%/W^^5E 7O 	"6"x1};;C*AG 
 %""*<<<<B7O;LN  !I33##8"9 :))47  kU*$$*8 ,*m-  !$#'#34&	$.3t9> J	D#&!4L	 &&*V1. 
 $) 15.!    c                 F   ddl m} t        j                  |      }| j                  dk(  r/|j
                  d   dk(  r|j                  j                  |d      }t        |t        j                        rFt        j                  |j                  | j                  |j                        |j                        }n| j                  |      }t        j                   || j                  | j"                  | j$                  | j&                  |      }t)        j*                  |      S )	Nr   r	   r      )axis)indicesvaluesdense_shape)r$   depthr%   r   backend_module)keras.src.backendr
   r   ensure_tensorr$   shapenumpysqueezer'   r   SparseTensorr8   _hash_values_to_binsr9   r:   r   encode_categorical_inputsr!   r%   r   r   convert_tf_tensor)r.   inputs
tf_backendr8   outputss        r2   callzHashing.call   s    >''/y(V\\"-=-B%%--f2->Ffboo.oo00?"..G //7G!;;((--;;**%
 ..w77r3   c                    | j                   }d}| j                  *|dkD  r%|dz  }t        j                  || j                        }|j                  j
                  rt        j                  |d      }|j                  t        j                  k7  rt        j                  |      }| j                  r.t        j                  j                  ||d| j                        }n"t        j                  j                  ||d      }|St        j                  |t        j                  |            }t        j                   |t        j"                  |      |      }|S )z6Converts a non-sparse tensor of values to bin indices.Nr6   r   )r   hash)r    key)r    )r!   r"   r   equalr   is_floatingcaststring	as_stringr#   stringsto_hash_bucket_strongr&   to_hash_bucket_fastadd	ones_likewhere
zeros_like)r.   r9   	hash_binsmasks       r2   rC   zHashing._hash_values_to_bins   s   MM	??&9q=NI88FDOO4D <<##WWV73F<<299$\\&)FZZ55	DII 6 F ZZ33	 4 F VVFBLL$89FXXdBMM&$96BFr3   c                 :   | j                   dk(  r+t        j                  |j                  | j                        S t        |j                        dk\  rt        |j                        d d }nd}t        j                  || j                  fz   | j                        S )Nr   )r?   r   r6   r5   r   )r$   r   KerasTensorr?   r   r*   r(   r!   )r.   rF   
base_shapes      r2   compute_output_speczHashing.compute_output_spec	  s~    u$&&V\\LLv||!v||,Sb1JJ""//tzz
 	
r3   c                     t         |          }|j                  | j                  | j                  | j
                  | j                  | j                  d       |S )N)r!   r&   r"   r$   r%   )r   
get_configupdater!   r&   r"   r$   r%   )r.   configr1   s     r2   r`   zHashing.get_config  sM    #% MM		"oo#//++	
 r3   )NNr   F)
__name__
__module____qualname____doc__r   rI   rC   r^   r`   __classcell__)r1   s   @r2   r   r   
   s8    {@ I"V828	
 r3   r   N)	keras.srcr   keras.src.api_exportr   keras.src.layers.layerr   keras.src.utilsr   r   r   keras.src.utils.module_utilsr
   r   r   r   r3   r2   <module>rm      s>     - ( ) + $ 9 $%Te T &Tr3   