View source: R/ag_checkpoint.R
| ag_checkpoint | R Documentation |
Executes fn(...) with the gradient tape switched off, so none of the
intermediate activations inside fn are kept. During
backward() the segment is run again – with the same RNG state
– to rebuild what the gradient rules need.
ag_checkpoint(fn, ...)
fn |
A function taking the tensors in One caveat, because it bites in the most natural usage: |
... |
Input |
This trades compute for memory: the segment's forward pass runs twice, and in exchange the tape never holds its activations. Use it on the deep middle of a network, not on cheap layers.
An ag_tensor holding the segment's output. Its gradient flows
back into both ... and any parameters used inside fn.
block <- ag_linear(8L, 8L, activation = "relu")
x <- ag_tensor(matrix(runif(8 * 4), 8, 4))
y <- ag_tensor(matrix(runif(8 * 4), 8, 4))
with_grad_tape({
h <- ag_checkpoint(function(inp) block$forward(inp), x)
loss <- ag_mse_loss(h, y)
})
backward(loss)
# Checkpointing every second block of a deeper stack. local() gives each
# segment its own binding -- see the note on `fn` for why that matters.
layers <- lapply(1:4, function(i) ag_linear(8L, 8L, activation = "relu"))
with_grad_tape({
h <- x
for (i in seq_along(layers)) {
seg <- local({
lyr <- layers[[i]]
function(inp) lyr$forward(inp)
})
h <- if (i %% 2L == 0L) ag_checkpoint(seg, h) else seg(h)
}
loss <- ag_mse_loss(h, y)
})
backward(loss)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.