Skip to content
class

NoGradGuard

NoGradGuard

RAII guard that disables gradient tracking for the lifetime of the object on the calling thread.

Constructing the guard captures the current value of GradMode::is_enabled and forces the flag to false; the destructor unconditionally restores the saved value. This nests correctly with any outer guards because each instance only restores what it itself saw — multiple nested guards rebuild the original state level by level on unwind.

See Also

GradMode — underlying flag accessors. lucid.no_grad — Python equivalent.

Attributes

prev_bool
Snapshot of GradMode::is_enabled taken at construction time and restored verbatim by the destructor.

Notes

The C++ counterpart of Python's lucid.no_grad context manager. Bindings that need a with block on the Python side instantiate one of these and tie its lifetime to __enter__ / __exit__. The guard is intentionally non-copyable so that the "exactly one restore per construction" invariant cannot be broken.

Examples

Disable autograd for a small inference subroutine without touching
the surrounding training loop's mode::
    {
        NoGradGuard nograd;
        auto y = model->forward(x);  // no graph built
    }
    // grad mode automatically restored here

Constructors

1

Destructor

1
dtor

~NoGradGuard

void ~NoGradGuard()

Restores the grad-mode flag to the value captured at construction.

Operators

1
op

operator=

NoGradGuard & operator=(const NoGradGuard &)