
    ij                        d dl Z d dlZd dlZd dlZ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  ej                         dk(  r!ej6                  j,                  j8                  Znd Zd Z e
d       G d de             Z e
d       G d de             Z y)    N)backend)tree)keras_export)is_float_dtype)standardize_dtype)Layer	draw_seed)serialization_lib)	jax_utils)tracking)jax)
tensorflowr   c                     | S N )fns    n/var/www/html/emotional.easysim.app/public_html/venv/lib/python3.12/site-packages/keras/src/utils/jax_layer.py#tf_no_automatic_dependency_trackingr      s    	    c                     t        j                          dk(  r't        j                  | t        j                        d   S | S )Nr   r   )r   tfbitcastuint32)tensors    r   _convert_to_jax_keyr      s0    L(zz&")),Q//Mr   zkeras.layers.JaxLayerc                        e Zd ZdZ	 	 	 	 	 d fd	Zd Zd Zd Zd Ze	j                  ed               Zd Zd	 Zd
 Zd Zd Z fdZddZ fdZe fd       Z xZS )JaxLayera!  Keras Layer that wraps a JAX model.

    This layer enables the use of JAX components within Keras when using JAX as
    the backend for Keras.

    ## Model function

    This layer accepts JAX models in the form of a function, `call_fn`, which
    must take the following arguments with these exact names:

    - `params`: trainable parameters of the model.
    - `state` (*optional*): non-trainable state of the model. Can be omitted if
        the model has no non-trainable state.
    - `rng` (*optional*): a `jax.random.PRNGKey` instance. Can be omitted if the
        model does not need RNGs, neither during training nor during inference.
    - `inputs`: inputs to the model, a JAX array or a `PyTree` of arrays.
    - `training` (*optional*): an argument specifying if we're in training mode
        or inference mode, `True` is passed in training mode. Can be omitted if
        the model behaves the same in training mode and inference mode.

    The `inputs` argument is mandatory. Inputs to the model must be provided via
    a single argument. If the JAX model takes multiple inputs as separate
    arguments, they must be combined into a single structure, for instance in a
    `tuple` or a `dict`.

    ## Model weights initialization

    The initialization of the `params` and `state` of the model can be handled
    by this layer, in which case the `init_fn` argument must be provided. This
    allows the model to be initialized dynamically with the right shape.
    Alternatively, and if the shape is known, the `params` argument and
    optionally the `state` argument can be used to create an already initialized
    model.

    The `init_fn` function, if provided, must take the following arguments with
    these exact names:

    - `rng`: a `jax.random.PRNGKey` instance.
    - `inputs`: a JAX array or a `PyTree` of arrays with placeholder values to
        provide the shape of the inputs.
    - `training` (*optional*): an argument specifying if we're in training mode
        or inference mode. `True` is always passed to `init_fn`. Can be omitted
        regardless of whether `call_fn` has a `training` argument.

    ## Models with non-trainable state

    For JAX models that have non-trainable state:

    - `call_fn` must have a `state` argument
    - `call_fn` must return a `tuple` containing the outputs of the model and
        the new non-trainable state of the model
    - `init_fn` must return a `tuple` containing the initial trainable params of
        the model and the initial non-trainable state of the model.

    This code shows a possible combination of `call_fn` and `init_fn` signatures
    for a model with non-trainable state. In this example, the model has a
    `training` argument and an `rng` argument in `call_fn`.

    ```python
    def stateful_call(params, state, rng, inputs, training):
        outputs = ...
        new_state = ...
        return outputs, new_state

    def stateful_init(rng, inputs):
        initial_params = ...
        initial_state = ...
        return initial_params, initial_state
    ```

    ## Models without non-trainable state

    For JAX models with no non-trainable state:

    - `call_fn` must not have a `state` argument
    - `call_fn` must return only the outputs of the model
    - `init_fn` must return only the initial trainable params of the model.

    This code shows a possible combination of `call_fn` and `init_fn` signatures
    for a model without non-trainable state. In this example, the model does not
    have a `training` argument and does not have an `rng` argument in `call_fn`.

    ```python
    def stateless_call(params, inputs):
        outputs = ...
        return outputs

    def stateless_init(rng, inputs):
        initial_params = ...
        return initial_params
    ```

    ## Conforming to the required signature

    If a model has a different signature than the one required by `JaxLayer`,
    one can easily write a wrapper method to adapt the arguments. This example
    shows a model that has multiple inputs as separate arguments, expects
    multiple RNGs in a `dict`, and has a `deterministic` argument with the
    opposite meaning of `training`. To conform, the inputs are combined in a
    single structure using a `tuple`, the RNG is split and used the populate the
    expected `dict`, and the Boolean flag is negated:

    ```python
    def my_model_fn(params, rngs, input1, input2, deterministic):
        ...
        if not deterministic:
            dropout_rng = rngs["dropout"]
            keep = jax.random.bernoulli(dropout_rng, dropout_rate, x.shape)
            x = jax.numpy.where(keep, x / dropout_rate, 0)
            ...
        ...
        return outputs

    def my_model_wrapper_fn(params, rng, inputs, training):
        input1, input2 = inputs
        rng1, rng2 = jax.random.split(rng)
        rngs = {"dropout": rng1, "preprocessing": rng2}
        deterministic = not training
        return my_model_fn(params, rngs, input1, input2, deterministic)

    keras_layer = JaxLayer(my_model_wrapper_fn, params=initial_params)
    ```

    ## Usage with Haiku modules

    `JaxLayer` enables the use of [Haiku](https://dm-haiku.readthedocs.io)
    components in the form of
    [`haiku.Module`](https://dm-haiku.readthedocs.io/en/latest/api.html#module).
    This is achieved by transforming the module per the Haiku pattern and then
    passing `module.apply` in the `call_fn` parameter and `module.init` in the
    `init_fn` parameter if needed.

    If the model has non-trainable state, it should be transformed with
    [`haiku.transform_with_state`](
      https://dm-haiku.readthedocs.io/en/latest/api.html#haiku.transform_with_state).
    If the model has no non-trainable state, it should be transformed with
    [`haiku.transform`](
      https://dm-haiku.readthedocs.io/en/latest/api.html#haiku.transform).
    Additionally, and optionally, if the module does not use RNGs in "apply", it
    can be transformed with
    [`haiku.without_apply_rng`](
      https://dm-haiku.readthedocs.io/en/latest/api.html#without-apply-rng).

    The following example shows how to create a `JaxLayer` from a Haiku module
    that uses random number generators via `hk.next_rng_key()` and takes a
    training positional argument:

    ```python
    class MyHaikuModule(hk.Module):
        def __call__(self, x, training):
            x = hk.Conv2D(32, (3, 3))(x)
            x = jax.nn.relu(x)
            x = hk.AvgPool((1, 2, 2, 1), (1, 2, 2, 1), "VALID")(x)
            x = hk.Flatten()(x)
            x = hk.Linear(200)(x)
            if training:
                x = hk.dropout(rng=hk.next_rng_key(), rate=0.3, x=x)
            x = jax.nn.relu(x)
            x = hk.Linear(10)(x)
            x = jax.nn.softmax(x)
            return x

    def my_haiku_module_fn(inputs, training):
        module = MyHaikuModule()
        return module(inputs, training)

    transformed_module = hk.transform(my_haiku_module_fn)

    keras_layer = JaxLayer(
        call_fn=transformed_module.apply,
        init_fn=transformed_module.init,
    )
    ```

    Args:
        call_fn: The function to call the model. See description above for the
            list of arguments it takes and the outputs it returns.
        init_fn: the function to call to initialize the model. See description
            above for the list of arguments it takes and the outputs it returns.
            If `None`, then `params` and/or `state` must be provided.
      params: A `PyTree` containing all the model trainable parameters. This
            allows passing trained parameters or controlling the initialization.
            If both `params` and `state` are `None`, `init_fn` is called at
            build time to initialize the trainable parameters of the model.
      state: A `PyTree` containing all the model non-trainable state. This
            allows passing learned state or controlling the initialization. If
            both `params` and `state` are `None`, and `call_fn` takes a `state`
            argument, then `init_fn` is called at build time to initialize the
            non-trainable state of the model.
      seed: Seed for random number generator. Optional.
      native_serialization_platforms: Sequence of platforms ('cpu', 'cuda',
            'rocm', 'tpu') to compile for when using `jax2tf.convert` with
            native serialization. This is only used when the Keras backend is
            `tensorflow`. If `None`, the function is compiled for the
            default backend. If multiple platforms are specified, the exported
            module will be device-polymorphic.
    c                 <   t        j                          dvr6t        | j                  j                   dt        j                                 t	        	|   di | || _        || _        | j                  |d      | _	        | j                  |d      | _
        | j                  | j                  | j                          | j                  |dh ddh      | _        d	| j                  v | _        d
| j                  v | _        d| j                  v }|r%t         j$                  j'                  |      | _        nd | _        |'|%|#| j                   s| j"                  rt        d      |r| j                  |dh ddh      | _        d | _        d | _        || _        y )N)r   r   zH is only supported with the JAX or Tensorflow backend. Current backend: T	trainableFcall_fn>   rngstateinputsparamstrainingr%   r&   r$   r#   zk`init_fn`, `params` and `state` cannot all be `None` when `call_fn` takes a `params` or a `state` argument.init_fn>   r#   r%   r'   r   )r   
ValueError	__class____name__super__init__r"   r(   _create_variablestracked_paramstracked_stater&   r$   _build_at_init_validate_signaturecall_fn_argumentscall_fn_has_paramscall_fn_has_staterandomSeedGeneratorseed_generatorinit_fn_argumentsjax2tf_training_false_fnjax2tf_training_true_fn%jax2tf_native_serialization_platforms)
selfr"   r(   r&   r$   seednative_serialization_platformskwargscall_fn_has_rngr*   s
            r   r-   zJaxLayer.__init__   s    ??$99>>**+ ,99@9J8KM 
 	"6""44Vt4L!33EU3K;;"djj&<!!%!9!9<J	"
 #+d.D.D"D!(D,B,B!B4#9#99")..">">t"DD"&D O((D,B,BD 
 %)%=%=$AH:&D"
 )-%'+$* 	2r   c                 Z   t        j                  |      j                  }|D ]  }||vst        d| d| d       g }|j	                         D ]Y  }|j
                  |vr.t        d| d|j
                   ddj                  |       d      |j                  |j
                         [ |S )NzMissing required argument in `z`: ``zUnsupported argument in `z`, supported arguments are `z`, `)inspect	signature
parametersr)   valuesnamejoinappend)	r=   r   fn_nameallowedrequiredfn_parametersparameter_nameparameter_names	parameters	            r   r2   zJaxLayer._validate_signature+  s    ))"-88& 	N]2 4WI >&'q* 	 &--/ 	3I~~W, /yY^^<L M006G0D/EQH  ""9>>2	3 r   c           
          t        j                  t        j                  t        j                  d t        j
                  t        j                  d                  fd}t        j                  ||      }|S )a  Convert input shape in a format suitable for `jax2tf`.

        `jax2tf` expects a letter for each unknown dimension, which allows
        correlated dimensions. Since correlated dimensions are not supported by
        Keras, we simply use 'a', 'b', 'c'..., for each unknown dimension. We
        however use 'batch' for dimension 0 if not defined to correlate the
        batch size across inputs.

        Example (spaces added for readability):
        ```
        input_shape:  (None , 4   , None, None, 5   )
        result:      "(batch, 4   , a   , b   , 5   )"
        ```

        Args:
          input_shape: a single shape or a structure of shapes for the inputs.
        Returns:
          the shape or shapes structure in the `jax2tf` format as strings.
        c                     | |z   S r   r   )abs     r   <lambda>z2JaxLayer._get_jax2tf_input_shape.<locals>.<lambda>V  s
    QU r      )repeatc                     g }t        |       D ]S  \  }}||j                  t        |             #|dk(  r|j                  d       :|j                  t                     U ddj	                  |      z   dz   S )Nr   batch(z, ))	enumeraterJ   strnextrI   )shapejax2tf_shapeindexdim	dim_namess       r   get_single_jax2tf_shapezAJaxLayer._get_jax2tf_input_shape.<locals>.get_single_jax2tf_shape[  sy    L'. 9
s? ''C1aZ ''0 ''Y89 <00366r   )	itertoolschainstringascii_lowercasestarmapproductr   map_shape_structure)r=   input_shapere   resrd   s       @r   _get_jax2tf_input_shapez JaxLayer._get_jax2tf_input_shape?  sb    ( OO"""!!&"8"8C
		7 &&'>L
r   c                     ddl m} d|i}| j                  | j                  |d<    |j                  |fi |}t        j
                  j                  j                  |      }|S )Nr   )jax2tfpolymorphic_shapesr?   )jax.experimentalrq   r<   convertr   	autographexperimentaldo_not_convert)r=   r   rr   rq   jax2tf_kwargsconverted_fns         r   _jax2tf_convertzJaxLayer._jax2tf_convertk  sg    +-/AB55A:: :; &v~~b:M:||00??Mr   c                 J    t        j                        fd       }|S )a  Return a new partial with one positional argument set to a value.

        This is needed because `jax2tf` only supports positional arguments and
        `functools.partial` only supports setting positional arguments starting
        from the left. Our use case is the `training` argument which is
        typically the righmost argument.

        Args:
          fn: the function to wrap.
          index: the index of the positional argument to set to `value`.
          value: the value for the positional argument at `index`.
        c                  ,    | d fz   | d  z   }  |  S )Nr   r   )argsr   rb   values    r   wrapperz2JaxLayer._partial_with_positional.<locals>.wrapper  s*    %=E8+d56l:Dt9r   )	functoolswraps)r=   r   rb   r~   r   s    ``` r   _partial_with_positionalz!JaxLayer._partial_with_positionaly  s'     
		 
	 r   c                       fd}t         j                  j                  ||      }r| _        n| _        t         j                  j                  |      \  }}|S )a  Create a structure of variables from a structure of JAX arrays.

        `values` is traversed via JAX's `tree_map`. When a leaf is a JAX array
        or a tensor-like object, a corresponding variable is created with it as
        the initial value. The resulting structure of variables is assigned to
        `self.params` or `self.state` depending on `trainable`. Then, a
        flattened version of the variables is returned for tracking.
        `self.params` or `self.state` are intentionally not tracked because
        structures like `TrackedList` interfere with `jax.tree_utils`.
        Note that leaf objects that are not JAX arrays and not tensor-like are
        left intact as they are assumed to be configuration used by the model.

        Args:
            values: the structure of values to traverse.
            trainable: whether to create trainable variables.

        Returns:
            flat list of variables initialized with `values` for tracking.
        c                    t        j                  |       s9t        | t        j                  t        j
                  t        j                  f      rK| j                  }t        |      rd }j                  | j                  t        j                  |       |      S t        | t        t        t        f      rIt!        t#        |             }t        |      rd }j                  dt        j                  |       |      S | S )N)initializerdtyper!   r   )r   	is_tensor
isinstancenpndarraygenericr   Arrayr   r   
add_weightr`   convert_to_tensorboolintfloatr   type)r~   r   r=   r!   s     r   create_variablez3JaxLayer._create_variables.<locals>.create_variable  s      ':

BJJ		:, !%( EKK ' 9 9% @'	 '   ED#u#56)$u+6!%( E ' 9 9% @'	 '   r   )r   	tree_utiltree_mapr&   r$   tree_flatten)r=   rG   r!   r   	variablesflat_variables_s   ` `    r   r.   zJaxLayer._create_variables  sP    .	6 MM**?FC	#DK"DJMM66yAr   c                     t        d      S )z
        Returns a single seed as a tensor of shape [2].

        Call this within `_get_init_rng()` to obtain a new seed.

        Returns:
            A native tensor of shape [2] and the backend dtype for seeds.
        Nr	   r=   s    r   _get_init_seedzJaxLayer._get_init_seed  s     r   c                 "    | j                         S )a  
        Returns a seed or seeds to pass as the `rng` argument of `init_fn`.

        By default, this returns a single seed. Override this to return a
        different structure. Overrides should use `self._get_init_seed()` to
        obtain new seeds.

        Returns:
            RNG key or structure of keys as tensors of shape [2] and the backend
            dtype for seeds.
        r   r   s    r   _get_init_rngzJaxLayer._get_init_rng  s     ""$$r   c                 6    | j                   j                         S )z
        Returns a single seed as a tensor of shape [2].

        Call this within `_get_call_rng()` to obtain a new seed.

        Returns:
            A native tensor of shape [2] and the backend dtype for seeds.
        )r8   r_   r   s    r   _get_call_seedzJaxLayer._get_call_seed  s     ""''))r   c                 (    |r| j                         S y)a  
        Returns a seed or seeds to pass as the `rng` argument of `call_fn`.

        By default, this returns a seed when `training` is `True`, and `None`
        when `training` is `False`. Override this to return a different
        structure or to pass seeds in inference mode too. Overrides should use
        `self._get_call_seed()` to obtain seeds.

        Returns:
            RNG key or structure of keys as tensors of shape [2] and the backend
            dtype for seeds.
        Nr   r=   r'   s     r   _get_call_rngzJaxLayer._get_call_rng  s     &&((r   c                    t        j                         rt        d      d }t        j                  ||      }t        j
                         dk(  r6t        j                  t        j                  |      d         rt        d      g }| j                  D ]t  }|dk(  r?|j                  t        j                  j                  d | j                                      G|dk(  r|j                  |       ^|d	k(  sd|j                  d
       v  | j                  | }| j                   r|\  }}n|d }}| j#                  |d
      | _        | j#                  |d      | _        y )Nz-'JaxLayer' cannot be built inside tf functionc                 p    | D cg c]  }||nd
 } }t         j                  j                  |       S c c}w )N   )r   numpyones)r`   ds     r   create_inputz2JaxLayer._initialize_weights.<locals>.create_input  s6    8=>1!-QQ.>E>99>>%(( ?s   3r   r   z-'JaxLayer' cannot be built in a tracing scoper#   c                 R    t         j                  j                  t        |             S r   )r   r   arrayr   )xs    r   rV   z.JaxLayer._initialize_weights.<locals>.<lambda>  s    #))//2Ea2H"I r   r%   r'   Tr    F)r   inside_functionr)   r   rl   r   r   is_in_jax_tracing_scopeflattenr9   rJ   r   r   r   r   r(   r5   r.   r/   r0   )	r=   rm   r   init_inputs	init_argsargument_nameinit_resultinit_params
init_states	            r   _initialize_weightszJaxLayer._initialize_weights  sR   LMM	) ..|[I??%)*K*KLL%a(+
 LMM	!33 	'M%  MM**I**, (*  -*,  &	' #dllI.!!&1#K&14K"444 5 
 "33J%3Pr   c                    | j                   5| j                  )| j                  s| j                  r| j	                  |       t        j
                         dk(  rg }| j                  D ]?  }|dk(  r!|j                  | j                  |             )|dk7  s/|j                  d       A d| j                  v r| j                  j                  d      }| j                  | j                  | j                  |d      |      | _        | j                  | j                  | j                  |d      |      | _        n(| j                  | j                  |      | _        d | _        t        | A  |       y y )Nr   r%   r'   z...FT)r&   r$   r4   r5   r   r   r3   rJ   ro   rb   rz   r   r"   r:   r;   r,   build)r=   rm   rr   argumenttraining_argument_indexr*   s        r   r   zJaxLayer.build)  si   KK

"((D,B,B$$[1??,!# 22 5x'&--44[A +&--e45 T333*.*@*@*F*F+' 150D0D11&=u '	1- 04/C/C11&=t '	0, 150D0DLL&1- 04,GM+&C -r   c           	      J    d }g  j                   D ]  }|dk(  r:j                  t        j                  j	                  | j
                               C|dk(  r:j                  t        j                  j	                  | j                               |dk(  rCj                  t        j                  j	                  t         j                  |                   |dk(  rj                  |       |dk(  st        j                         dk(  sj                  |        d  fd	}t        j                         dk(  r | j                        S t        j                         d
k(  r2|r j                   | j                        S  | j                        S y )Nc                 "    | d S | j                   S r   )r~   )variables    r   unwrap_variablez&JaxLayer.call.<locals>.unwrap_variableU  s    #+4??r   r&   r$   r#   r%   r'   r   c                 T    t        |d      st        d      |j                  |        y )NassignzStructure mismatch: the structure of the state returned by `call` does not match the structure of the state at initialization time.)hasattrr)   r   )r~   r   s     r   assign_state_to_variablez/JaxLayer.call.<locals>.assign_state_to_variablen  s,    8X. + 
 OOE"r   c                     j                   r5 |  \  }}t        j                  j                  |j                         |S  |  S r   )r5   r   r   r   r$   )r   predictions	new_stater   	call_argsr=   s      r   call_with_fnz#JaxLayer.call.<locals>.call_with_fnx  sI    %%)+Y&Y&&,i #"9~%r   r   )r3   rJ   r   r   r   r&   r$   r   r   r   r"   r;   r:   )r=   r%   r'   r   r   r   r   r   s   `     @@r   callzJaxLayer.callT  sh   	@ 	!33 	/M(  MM**?DKKH ')  MM**?DJJG %'  MM**+T-?-?-I
 (*  (*,??$-$$X.'	/*	#	& ??%--__,.D88D#D$@$@AA#D$A$ABB	 /r   c                 ,   t        j                  | j                        t        j                  | j                        | j                  d}t
        |          }t        t        |j                               t        |j                               z         S )N)r"   r(   r?   )
r   serialize_keras_objectr"   r(   r<   r,   
get_configdictlistitems)r=   configbase_configr*   s      r   r   zJaxLayer.get_config  so    (??M(??M::	
 g(*D**,-V\\^0DDEEr   c                     t        j                  |d         }t        j                  |d         }||d<   ||d<   t        |   |      S )Nr"   r(   )r   deserialize_keras_objectr,   from_config)clsr   r"   r(   r*   s       r   r   zJaxLayer.from_config  sQ    #<<VI=NO#<<VI=NO#y#yw"6**r   )NNNNN)F)r+   
__module____qualname____doc__r-   r2   ro   rz   r   r    no_automatic_dependency_trackingr   r.   r   r   r   r   r   r   r   r   classmethodr   __classcell__r*   s   @r   r   r   %   s    DR '+<
|(*X* ..(8 ) /8t
%	*$&QP)'V4Cl	F + +r   r   zkeras.layers.FlaxLayerc                   Z     e Zd ZdZ	 	 d	 fd	Zd Zd Zd Zd Z fdZ	e
d        Z xZS )
	FlaxLayerak  Keras Layer that wraps a [Flax](https://flax.readthedocs.io) module.

    This layer enables the use of Flax components in the form of
    [`flax.linen.Module`](
        https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html)
    instances within Keras when using JAX as the backend for Keras.

    The module method to use for the forward pass can be specified via the
    `method` argument and is `__call__` by default. This method must take the
    following arguments with these exact names:

    - `self` if the method is bound to the module, which is the case for the
        default of `__call__`, and `module` otherwise to pass the module.
    - `inputs`: the inputs to the model, a JAX array or a `PyTree` of arrays.
    - `training` *(optional)*: an argument specifying if we're in training mode
        or inference mode, `True` is passed in training mode.

    `FlaxLayer` handles the non-trainable state of your model and required RNGs
    automatically. Note that the `mutable` parameter of
    [`flax.linen.Module.apply()`](
        https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html#flax.linen.apply)
    is set to `DenyList(["params"])`, therefore making the assumption that all
    the variables outside of the "params" collection are non-trainable weights.

    This example shows how to create a `FlaxLayer` from a Flax `Module` with
    the default `__call__` method and no training argument:

    ```python
    class MyFlaxModule(flax.linen.Module):
        @flax.linen.compact
        def __call__(self, inputs):
            x = inputs
            x = flax.linen.Conv(features=32, kernel_size=(3, 3))(x)
            x = flax.linen.relu(x)
            x = flax.linen.avg_pool(x, window_shape=(2, 2), strides=(2, 2))
            x = x.reshape((x.shape[0], -1))  # flatten
            x = flax.linen.Dense(features=200)(x)
            x = flax.linen.relu(x)
            x = flax.linen.Dense(features=10)(x)
            x = flax.linen.softmax(x)
            return x

    flax_module = MyFlaxModule()
    keras_layer = FlaxLayer(flax_module)
    ```

    This example shows how to wrap the module method to conform to the required
    signature. This allows having multiple input arguments and a training
    argument that has a different name and values. This additionally shows how
    to use a function that is not bound to the module.

    ```python
    class MyFlaxModule(flax.linen.Module):
        @flax.linen.compact
        def forward(self, input1, input2, deterministic):
            ...
            return outputs

    def my_flax_module_wrapper(module, inputs, training):
        input1, input2 = inputs
        return module.forward(input1, input2, not training)

    flax_module = MyFlaxModule()
    keras_layer = FlaxLayer(
        module=flax_module,
        method=my_flax_module_wrapper,
    )
    ```

    Args:
        module: An instance of `flax.linen.Module` or subclass.
        method: The method to call the model. This is generally a method in the
            `Module`. If not provided, the `__call__` method is used. `method`
            can also be a function not defined in the `Module`, in which case it
            must take the `Module` as the first argument. It is used for both
            `Module.init` and `Module.apply`. Details are documented in the
            `method` argument of [`flax.linen.Module.apply()`](
              https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html#flax.linen.apply).
        variables: A `dict` containing all the variables of the module in the
            same format as what is returned by [`flax.linen.Module.init()`](
              https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html#flax.linen.init).
            It should contain a "params" key and, if applicable, other keys for
            collections of variables for non-trainable state. This allows
            passing trained parameters and learned non-trainable state or
            controlling the initialization. If `None` is passed, the module's
            `init` function is called at build time to initialize the variables
            of the model.
    c                 0    ddl m} | _        | _         |dg       fd} fd} fd} fd}	dt	        j
                  |xs |j                        j                  v r||}}
n||	}}
 j                  |      \  }}t         (  d
|
|||d	| y )Nr   )DenyListr&   c                 z    j                   j                  j                  | |      ||j                  |      S )N)rngsmethodmutabler'   moduleapply_params_and_state_to_variablesr   )r&   r$   r#   r%   r'   apply_mutabler=   s        r   apply_with_trainingz/FlaxLayer.__init__.<locals>.apply_with_training  sB    ;;$$33FEB{{%! %  r   c                 x    j                   j                  j                  | |      ||j                        S )N)r   r   r   r   )r&   r$   r#   r%   r   r=   s       r   apply_without_trainingz2FlaxLayer.__init__.<locals>.apply_without_training  s?    ;;$$33FEB{{% %  r   c                 t    j                  j                  j                  | |j                  |            S )N)r   r'   _variables_to_params_and_stater   initr   )r#   r%   r'   r=   s      r   init_with_trainingz.FlaxLayer.__init__.<locals>.init_with_training  s=    66  ;;%	 !  r   c                 r    j                  j                  j                  | |j                              S )N)r   r   )r#   r%   r=   s     r   init_without_trainingz1FlaxLayer.__init__.<locals>.init_without_training%  s:    66  ;; !  r   r'   )r"   r(   r&   r$   r   )
flax.linenr   r   r   rD   rE   __call__rF   r   r,   r-   )r=   r   r   r   r@   r   r   r   r   r   r"   r(   r&   r$   r   r*   s   `             @r   r-   zFlaxLayer.__init__  s     	( (,				   !:6??;FFG  34FWG57LWG;;IF 	
		

 	
r   c                 &    |r
|ri ||S |S |r|S i S r   r   )r=   r&   r$   s      r   r   z(FlaxLayer._params_and_state_to_variables@  s*    *&*E**L	r   c                     |yd|vri |fS t        |      dk(  r|i fS d|d   i}|j                         D ci c]  \  }}|dk7  s|| }}}||fS c c}}w )NNNr&   r   )lenr   )r=   r   r&   kvr$   s         r   r   z(FlaxLayer._variables_to_params_and_stateJ  sz    9$y= y>Qb= Ih/0"+//"3E$!QqH}AEEu} Fs   AAc                 D    | j                         | j                         dS )N)r&   dropoutr   r   s    r   r   zFlaxLayer._get_init_rngY  s$    ))+**,
 	
r   c                 .    |rd| j                         iS i S )Nr   r   r   s     r   r   zFlaxLayer._get_call_rng_  s    t22455Ir   c                    | j                   }t        | j                   d      r9| j                   j                  | j                  k(  r| j                   j                  }t        j                  | j                        t        j                  |      d}t        | !         }|j                  d       |j                  d       t        t        |j                               t        |j                               z         S )N__self__)r   r   r"   r(   )r   r   r  r   r+   r   r   r,   r   popr   r   r   )r=   config_methodr   r   r*   s       r   r   zFlaxLayer.get_confige  s    DKK,$$3 !KK00M'>>t{{K'>>}M
 g(*	"	"D**,-V\\^0DDEEr   c                     t        j                  |d         }t        j                  |d         }t        |d   t              rt	        ||      }||d<   ||d<    | di |S )Nr   r   r   )r   r   r   r^   getattr)r   r   r   r   s       r   r   zFlaxLayer.from_configw  sg    ";;F8<LM";;F8<LMfX&,VV,F!x!x}V}r   r   )r+   r   r   r   r-   r   r   r   r   r   r   r   r   r   s   @r   r   r     sG    Wx 	E
N
F$  r   r   )!r   rD   rf   rh   r   r   	keras.srcr   r   keras.src.api_exportr   "keras.src.backend.common.variablesr   r   keras.src.layers.layerr   keras.src.random.seed_generatorr
   keras.src.savingr   keras.src.utilsr   r   keras.src.utils.module_utilsr   r   r   __internal__r   r   r   r   r   r   r   r   <module>r     s           - = @ ( 5 . % $ , 97??$
  AA (
 %&u	+u u	+ 'u	+p &'a a (ar   