tf.keras.remat
Stay organized with collections
Save and categorize content based on your preferences.
Applies rematerialization to a function or layer for memory optimization.
tf.keras.remat(
f
)
Rematerialization is a memory optimization technique that trades off
computation for memory. Instead of storing intermediate results
(e.g. activations) for backpropagation, they are recomputed during the
backward pass. This reduces peak memory usage at the cost of increased
computation time, allowing the training of larger models or using larger
batch sizes within the same memory constraints.
Args |
f
|
A callable function, to which rematerialization is
applied. This is typically a computationally expensive operation
where intermediate states can be recomputed instead of stored.
|
Returns |
|
A wrapped function that applies rematerialization. The returned
function defines a custom gradient, ensuring that during the backward
pass, the forward computation is recomputed as needed.
|
Example:
from keras import Model
class CustomRematLayer(layers.Layer):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.remat_function = remat(self.intermediate_function)
def intermediate_function(self, x):
for _ in range(2):
x = x + x * 0.1 # Simple scaled transformation
return x
def call(self, inputs):
return self.remat_function(inputs)
# Define a simple model using the custom layer
inputs = layers.Input(shape=(4,))
x = layers.Dense(4, activation="relu")(inputs)
x = CustomRematLayer()(x) # Custom layer with rematerialization
outputs = layers.Dense(1)(x)
# Create and compile the model
model = Model(inputs=inputs, outputs=outputs)
model.compile(optimizer="sgd", loss="mse")
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 2026-10-31 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 2026-10-31 UTC."],[],[]]