std :: ml::tensor
Struct std::GradGuard
struct GradGuard {
int was;
}Global, not per-TU: every tensor_<op> across every separately-compiled file linked into the same program shares one flag (that's why these are ordinary externally-linked functions, defined once in tensor.sc, not 'static' — unlike the internal helpers below, this state must be visible and consistent everywhere, not private per including file).
Mirrors PyTorch's torch.no_grad(): while disabled, every tensor produced by tensor_add/matmul/etc. gets requiresGrad=0 regardless of its inputs' — __tensor_link1/__tensor_link2 (below) skip pushing to 'parents' and setting 'gradFn' entirely, which is the real cost this exists to avoid (Vec::push's first call allocates; skipping it removes a real std::alloc from every op call during inference). Doesn't affect LEAF tensors' own requiresGrad (Tensor::new_2d's explicit argument is unaffected) — only what happens when ops COMPOSE tensors.
The flag lives in the program's one Autograd state, reached through Autograd::get():
struct GradGuard g = Autograd::get().no_grad(); // inference from here
... forward passes record nothing ...
g.restore(); // back to the previous mode
Fields
the mode no_grad() found
Methods
Puts the mode back as no_grad() found it (guards nest).