tf.keras.layers.FlaxLayer
Stay organized with collections
Save and categorize content based on your preferences.
Keras Layer that wraps a Flax module.
Inherits From: JaxLayer
, Layer
, Operation
tf.keras.layers.FlaxLayer(
module, method=None, variables=None, **kwargs
)
This layer enables the use of Flax components in the form of
flax.linen.Module
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()
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:
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.
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() .
|
variables
|
A dict containing all the variables of the module in the
same format as what is returned by flax.linen.Module.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.
|
Attributes |
input
|
Retrieves the input tensor(s) of a symbolic operation.
Only returns the tensor(s) corresponding to the first time
the operation was called.
|
output
|
Retrieves the output tensor(s) of a layer.
Only returns the tensor(s) corresponding to the first time
the operation was called.
|
Methods
from_config
View source
@classmethod
from_config(
config
)
Creates a layer from its config.
This method is the reverse of get_config
,
capable of instantiating the same layer from the config
dictionary. It does not handle layer connectivity
(handled by Network), nor weights (handled by set_weights
).
Args |
config
|
A Python dictionary, typically the
output of get_config.
|
Returns |
A layer instance.
|
symbolic_call
View source
symbolic_call(
*args, **kwargs
)
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates. Some content is licensed under the numpy license.
Last updated 2024-06-07 UTC.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2024-06-07 UTC."],[],[],null,["# tf.keras.layers.FlaxLayer\n\n\u003cbr /\u003e\n\n|-----------------------------------------------------------------------------------------------------------------|\n| [View source on GitHub](https://github.com/keras-team/keras/tree/v3.3.3/keras/src/utils/jax_layer.py#L445-L677) |\n\nKeras Layer that wraps a [Flax](https://flax.readthedocs.io) module.\n\nInherits From: [`JaxLayer`](../../../tf/keras/layers/JaxLayer), [`Layer`](../../../tf/keras/Layer), [`Operation`](../../../tf/keras/Operation) \n\n tf.keras.layers.FlaxLayer(\n module, method=None, variables=None, **kwargs\n )\n\nThis layer enables the use of Flax components in the form of\n[`flax.linen.Module`](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html)\ninstances within Keras when using JAX as the backend for Keras.\n\nThe module method to use for the forward pass can be specified via the\n`method` argument and is `__call__` by default. This method must take the\nfollowing arguments with these exact names:\n\n- `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.\n- `inputs`: the inputs to the model, a JAX array or a `PyTree` of arrays.\n- `training` *(optional)* : an argument specifying if we're in training mode or inference mode, `True` is passed in training mode.\n\n`FlaxLayer` handles the non-trainable state of your model and required RNGs\nautomatically. Note that the `mutable` parameter of\n[`flax.linen.Module.apply()`](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html#flax.linen.apply)\nis set to `DenyList([\"params\"])`, therefore making the assumption that all\nthe variables outside of the \"params\" collection are non-trainable weights.\n\nThis example shows how to create a `FlaxLayer` from a Flax `Module` with\nthe default `__call__` method and no training argument: \n\n class MyFlaxModule(flax.linen.Module):\n @flax.linen.compact\n def __call__(self, inputs):\n x = inputs\n x = flax.linen.Conv(features=32, kernel_size=(3, 3))(x)\n x = flax.linen.relu(x)\n x = flax.linen.avg_pool(x, window_shape=(2, 2), strides=(2, 2))\n x = x.reshape((x.shape[0], -1)) # flatten\n x = flax.linen.Dense(features=200)(x)\n x = flax.linen.relu(x)\n x = flax.linen.Dense(features=10)(x)\n x = flax.linen.softmax(x)\n return x\n\n flax_module = MyFlaxModule()\n keras_layer = FlaxLayer(flax_module)\n\nThis example shows how to wrap the module method to conform to the required\nsignature. This allows having multiple input arguments and a training\nargument that has a different name and values. This additionally shows how\nto use a function that is not bound to the module. \n\n class MyFlaxModule(flax.linen.Module):\n @flax.linen.compact\n def forward(self, input1, input2, deterministic):\n ...\n return outputs\n\n def my_flax_module_wrapper(module, inputs, training):\n input1, input2 = inputs\n return module.forward(input1, input2, not training)\n\n flax_module = MyFlaxModule()\n keras_layer = FlaxLayer(\n module=flax_module,\n method=my_flax_module_wrapper,\n )\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Args ---- ||\n|-------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `module` | An instance of `flax.linen.Module` or subclass. |\n| `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). |\n| `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. |\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Attributes ---------- ||\n|----------|------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `input` | Retrieves the input tensor(s) of a symbolic operation. \u003cbr /\u003e Only returns the tensor(s) corresponding to the *first time* the operation was called. |\n| `output` | Retrieves the output tensor(s) of a layer. \u003cbr /\u003e Only returns the tensor(s) corresponding to the *first time* the operation was called. |\n\n\u003cbr /\u003e\n\nMethods\n-------\n\n### `from_config`\n\n[View source](https://github.com/keras-team/keras/tree/v3.3.3/keras/src/utils/jax_layer.py#L668-L677) \n\n @classmethod\n from_config(\n config\n )\n\nCreates a layer from its config.\n\nThis method is the reverse of `get_config`,\ncapable of instantiating the same layer from the config\ndictionary. It does not handle layer connectivity\n(handled by Network), nor weights (handled by `set_weights`).\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Args ||\n|----------|----------------------------------------------------------|\n| `config` | A Python dictionary, typically the output of get_config. |\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Returns ||\n|---|---|\n| A layer instance. ||\n\n\u003cbr /\u003e\n\n### `symbolic_call`\n\n[View source](https://github.com/keras-team/keras/tree/v3.3.3/keras/src/ops/operation.py#L58-L70) \n\n symbolic_call(\n *args, **kwargs\n )"]]