version functionkeras.version()
Guides and examples using version
clear_session functionkeras.utils.clear_session(free_memory=True)
Resets all state generated by Keras.
Keras manages a global state, which it uses to implement the Functional model-building API and to uniquify autogenerated layer names.
If you are creating many models in a loop, this global state will consume
an increasing amount of memory over time, and you may want to clear it.
Calling clear_session() releases the global state: this helps avoid
clutter from old models and layers, especially when memory is limited.
Arguments
clear_session() in a short loop,
you may want to skip it.Example 1: calling clear_session() when creating models in a loop
for _ in range(100):
# Without `clear_session()`, each iteration of this loop will
# slightly increase the size of the global state managed by Keras
model = keras.Sequential([
keras.layers.Dense(10) for _ in range(10)])
for _ in range(100):
# With `clear_session()` called at the beginning,
# Keras starts with a blank state at each iteration
# and memory consumption is constant over time.
keras.backend.clear_session()
model = keras.Sequential([
keras.layers.Dense(10) for _ in range(10)])
Example 2: resetting the layer name generation counter
>>> layers = [keras.layers.Dense(10) for _ in range(10)]
>>> new_layer = keras.layers.Dense(10)
>>> print(new_layer.name)
dense_10
>>> keras.backend.clear_session()
>>> new_layer = keras.layers.Dense(10)
>>> print(new_layer.name)
dense
enable_traceback_filtering functionkeras.config.enable_traceback_filtering()
Turn on traceback filtering.
Raw Keras tracebacks (also known as stack traces) involve many internal frames, which can be challenging to read through, while not being actionable for end users. By default, Keras filters internal frames in most exceptions that it raises, to keep traceback short, readable, and focused on what's actionable for you (your own code).
See also keras.config.disable_traceback_filtering() and
keras.config.is_traceback_filtering_enabled().
If you have previously disabled traceback filtering via
keras.config.disable_traceback_filtering(), you can re-enable it via
keras.config.enable_traceback_filtering().
disable_traceback_filtering functionkeras.config.disable_traceback_filtering()
Turn off traceback filtering.
Raw Keras tracebacks (also known as stack traces) involve many internal frames, which can be challenging to read through, while not being actionable for end users. By default, Keras filters internal frames in most exceptions that it raises, to keep traceback short, readable, and focused on what's actionable for you (your own code).
See also keras.config.enable_traceback_filtering() and
keras.config.is_traceback_filtering_enabled().
If you have previously disabled traceback filtering via
keras.config.disable_traceback_filtering(), you can re-enable it via
keras.config.enable_traceback_filtering().
Guides and examples using disable_traceback_filtering
is_traceback_filtering_enabled functionkeras.config.is_traceback_filtering_enabled()
Check if traceback filtering is enabled.
Raw Keras tracebacks (also known as stack traces) involve many internal frames, which can be challenging to read through, while not being actionable for end users. By default, Keras filters internal frames in most exceptions that it raises, to keep traceback short, readable, and focused on what's actionable for you (your own code).
See also keras.config.enable_traceback_filtering() and
keras.config.disable_traceback_filtering().
If you have previously disabled traceback filtering via
keras.config.disable_traceback_filtering(), you can re-enable it via
keras.config.enable_traceback_filtering().
Returns
Boolean, True if traceback filtering is enabled,
and False otherwise.
enable_interactive_logging functionkeras.config.enable_interactive_logging()
Turn on interactive logging.
When interactive logging is enabled, Keras displays logs via stdout. This provides the best experience when using Keras in an interactive environment such as a shell or a notebook.
disable_interactive_logging functionkeras.config.disable_interactive_logging()
Turn off interactive logging.
When interactive logging is disabled, Keras sends logs to absl.logging.
This is the best option when using Keras in a non-interactive
way, such as running a training or inference job on a server.
is_interactive_logging_enabled functionkeras.config.is_interactive_logging_enabled()
Check if interactive logging is enabled.
To switch between writing logs to stdout and absl.logging, you may use
keras.config.enable_interactive_logging() and
keras.config.disable_interactive_logging().
Returns
Boolean, True if interactive logging is enabled,
and False otherwise.
enable_unsafe_deserialization functionkeras.config.enable_unsafe_deserialization()
Disables safe mode globally, allowing deserialization of lambdas.
floatx functionkeras.config.floatx()
Return the default float type, as a string.
E.g. 'bfloat16', 'float16', 'float32', 'float64'.
Returns
String, the current default float type.
Example
>>> keras.config.floatx()
'float32'
set_floatx functionkeras.config.set_floatx(value)
Set the default float dtype.
Note: It is not recommended to set this to "float16" for training,
as this will likely cause numeric stability issues.
Instead, mixed precision, which leverages
a mix of float16 and float32. It can be configured by calling
keras.mixed_precision.set_dtype_policy('mixed_float16').
Arguments
'bfloat16', 'float16', 'float32', or 'float64'.Examples
>>> keras.config.floatx()
'float32'
>>> keras.config.set_floatx('float64')
>>> keras.config.floatx()
'float64'
>>> # Set it back to float32
>>> keras.config.set_floatx('float32')
Raises
image_data_format functionkeras.config.image_data_format()
Return the default image data format convention.
Returns
A string, either 'channels_first' or 'channels_last'.
Example
>>> keras.config.image_data_format()
'channels_last'
set_image_data_format functionkeras.config.set_image_data_format(data_format)
Set the value of the image data format convention.
Arguments
'channels_first' or 'channels_last'.Examples
>>> keras.config.image_data_format()
'channels_last'
>>> keras.config.set_image_data_format('channels_first')
>>> keras.config.image_data_format()
'channels_first'
>>> # Set it back to `'channels_last'`
>>> keras.config.set_image_data_format('channels_last')
epsilon functionkeras.config.epsilon()
Return the value of the fuzz factor used in numeric expressions.
Returns
A float.
Example
>>> keras.config.epsilon()
1e-07
set_epsilon functionkeras.config.set_epsilon(value)
Set the value of the fuzz factor used in numeric expressions.
Arguments
Examples
>>> keras.config.epsilon()
1e-07
>>> keras.config.set_epsilon(1e-5)
>>> keras.config.epsilon()
1e-05
>>> # Set it back to the default value.
>>> keras.config.set_epsilon(1e-7)
backend functionkeras.config.backend()
Publicly accessible method for determining the current backend.
Returns
String, the name of the backend Keras is currently using. One of
"tensorflow", "torch", or "jax".
Example
>>> keras.config.backend()
'tensorflow'
Guides and examples using backend
set_backend functionkeras.config.set_backend(backend)
Reload the backend (and the Keras package).
Example
>>> import os
>>> os.environ["KERAS_BACKEND"] = "tensorflow"
>>>
>>> import keras
>>> from keras import ops
>>> type(ops.ones(()))
<class 'tensorflow.python.framework.ops.EagerTensor'>
>>>
>>> keras.config.set_backend("jax")
UserWarning: Using [`keras.config.set_backend`](/api/utils/config_utils#setbackend-function) is dangerous...
>>> del keras, ops
>>>
>>> import keras
>>> from keras import ops
>>> type(ops.ones(()))
<class 'jaxlib.xla_extension.ArrayImpl'>
⚠️ WARNING ⚠️: Using this function is dangerous and should be done
carefully. Changing the backend will NOT convert
the type of any already-instantiated objects.
Thus, any layers / tensors / etc. already created will no
longer be usable without errors. It is strongly recommended not
to keep around any Keras-originated objects instances created
before calling set_backend().
This includes any function or class instance that uses any Keras
functionality. All such code needs to be re-executed after calling
set_backend() and re-importing all imported keras modules.
enable_flash_attention functionkeras.config.enable_flash_attention()
Enable flash attention.
Flash attention offers performance optimization for attention layers, making it especially useful for large language models (LLMs) that benefit from faster and more memory-efficient attention computations.
Once enabled, supported layers like MultiHeadAttention will attempt to
use flash attention for faster computations. By default, this feature is
enabled.
Note that enabling flash attention does not guarantee it will always be
used. Typically, the inputs must be in float16 or bfloat16 dtype, and
input layout requirements may vary depending on the backend.
disable_flash_attention functionkeras.config.disable_flash_attention()
Disable flash attention.
Flash attention offers performance optimization for attention layers, making it especially useful for large language models (LLMs) that benefit from faster and more memory-efficient attention computations.
Once disabled, supported layers like MultiHeadAttention will not
use flash attention for faster computations.
is_flash_attention_enabled functionkeras.config.is_flash_attention_enabled()
Checks whether flash attention is globally enabled in Keras.
Flash attention is a performance-optimized method for computing attention
in large models, such as transformers, allowing for faster and more
memory-efficient operations. This function checks the global Keras
configuration to determine if flash attention is enabled for compatible
layers (e.g., MultiHeadAttention).
Note that enabling flash attention does not guarantee it will always be
used. Typically, the inputs must be in float16 or bfloat16 dtype, and
input layout requirements may vary depending on the backend.
Returns
False if disabled; otherwise, it indicates that it is enabled.
is_nnx_enabled functionkeras.config.is_nnx_enabled()
Checks whether NNX specific features are enabled for the JAX backend.
Returns
True if NNX backend features are enabled, False otherwise.
Defaults to False.max_epochs functionkeras.config.max_epochs()
Get the maximum number of epochs for any call to fit.
Retrieves the limit on the number of epochs set by
keras.config.set_max_epochs or the KERAS_MAX_EPOCHS environment
variable.
Returns
The integer limit on the number of epochs or None, if no limit has
been set.
set_max_epochs functionkeras.config.set_max_epochs(max_epochs)
Limit the maximum number of epochs for any call to fit.
This will cap the number of epochs for any training run using model.fit().
This is purely for debugging, and can also be set via the KERAS_MAX_EPOCHS
environment variable to quickly run a script without modifying its source.
Arguments
None. If
None, no limit is applied.max_steps_per_epoch functionkeras.config.max_steps_per_epoch()
Get the maximum number of steps for any call to fit/evaluate/predict.
Retrieves the limit on the number of epochs set by
keras.config.set_max_steps_per_epoch or the KERAS_MAX_STEPS_PER_EPOCH
environment variable.
Arguments
None. If
None, no limit is applied.set_max_steps_per_epoch functionkeras.config.set_max_steps_per_epoch(max_steps_per_epoch)
Limit the maximum number of steps for any call to fit/evaluate/predict.
This will cap the number of steps for single epoch of a call to fit(),
evaluate(), or predict(). This is purely for debugging, and can also be
set via the KERAS_MAX_STEPS_PER_EPOCH environment variable to quickly run
a scrip without modifying its source.
Arguments
None. If
None, no limit is applied.