Learn R Programming

ggmlR (version 0.8.4)

clip_grad_value: Clip gradients element-wise by value

Description

Clamps every gradient element into [-clip_value, clip_value]. Unlike clip_grad_norm this does not preserve the gradient direction — each element is treated independently. Modifies the grads environment in-place.

Usage

clip_grad_value(params, grads, clip_value)

Value

Numeric: the largest absolute gradient value before clipping (invisibly). Returns 0 when no gradients were found.

Arguments

params

Named list of ag_param tensors (same as passed to optimizer).

grads

Gradient environment returned by backward().

clip_value

Positive numeric; maximum absolute value per element.

Details

Call this after backward() and before optimizer$step().

See Also

clip_grad_norm

Examples

Run this code
# \donttest{
w  <- ag_param(matrix(runif(4), 2, 2))
x  <- ag_tensor(matrix(c(1, 1), 2, 1))
with_grad_tape({
  out  <- ag_matmul(w, x)
  loss <- ag_mse_loss(out, matrix(0, 2, 1))
})
grads <- backward(loss)
clip_grad_value(list(w = w), grads, clip_value = 0.5)
# }

Run the code above in your browser using DataLab