published fresh until

PyTorch “element 0 of tensors”: why does backward fail?

Summary As of October 2026, inspect loss.requires_grad and loss.grad_fn before changing a failing backward pass. For NumPy export, use tensor.numpy(force=True) with a NumPy-supported dtype/layout, or tensor.detach().cpu().numpy() when conjugate and negative bits are clear; detaching the training loss is not the repair (checked 2026-10-28).

Not for CUDA allocation and checkpoint failures, see pytorch-cuda-oom-device-assert-kernel-image-weights-only-errors

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn

The backward pass has no gradient edge for a requested output, while the separate NumPy error rejects exporting a tensor that requires gradients.

First action — inspect print(loss.requires_grad, loss.grad_fn) immediately before loss.backward().

Evidence status — official source confirms the backward check and NumPy restriction; a public forum supplies a diagnostic, but the cause in your model is not established and no training run is tested here.

Not for: PyTorch CUDA out-of-memory, device-side asserts or checkpoint-loading failures; see pytorch-cuda-oom-device-assert-kernel-image-weights-only-errors.

Diagnostic: element 0 of tensors does not require grad and does not have a grad_fn

Trace the training path or export a detached value

1. For the opening error, inspect the loss, model output and then intermediate activations in forward:

print(loss.requires_grad, loss.grad_fn)
print(output.requires_grad, output.grad_fn)

Use the actual output variable in your model. ptrblck's forum diagnostic recommends following grad_fn backward through these values. A computed loss with no graph calls for tracing how it was produced; this is not a general rule that every leaf tensor must have a grad_fn. 2. Inspect the transition where the expected graph disappears. The forum lists NumPy operations, torch.argmax, explicit detach(), wrapping an existing tensor with torch.tensor(x), and disabled gradient calculation as possibilities. Treat them as hypotheses until the code demonstrates which applies. The official autograd mechanics, PyTorch 2.14 (checked 2026-10-28), explains graph recording and how no-grad and inference modes exclude operations. Preserve the intended differentiable path instead of guessing a flag change. 3. If the actual error is RuntimeError: Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead., decide whether the value is only for export, plotting or metrics. For export, keep the original training tensor and create a separate array:

array = tensor.detach().cpu().numpy()
# Alternative documented shorthand:
array = tensor.numpy(force=True)

The Tensor.numpy reference, PyTorch 2.14 (checked 2026-10-28), says the default conversion requires a CPU tensor without gradients and a supported dtype/layout. force=True expands to t.detach().cpu().resolve_conj().resolve_neg().numpy(). It can return a copy; it does not make NumPy computation differentiable. 4. After a targeted change, rerun one minimal training step. Confirm the intended trainable parameters receive gradients. Test the export path separately so a successful conversion does not conceal a broken training path.

What the source code proves

The autograd implementation checks gradient_edge.function and constructs the opening message with the output index. Thus element 0 is a concrete output of an indexed template, not a named model layer. The NumPy implementation separately checks gradient mode and tensor.requires_grad() before emitting the NumPy message. Both source pages were checked 2026-10-28 on main; neither identifies the causal line in your model.

Public evidence

ptrblck replying to Lynn on PyTorch Forums, 2022-01-04 (checked 2026-10-28), says to “check the .grad_fn attribute of the loss” and inspect outputs and activations. This is a concrete diagnostic recommendation with multiple possible causes, not a verified repair for every training loop.

What to test

Check one backward pass and the gradients of parameters intended to train. Separately export a CPU tensor and, where relevant, a device tensor. If the returned array can share storage, avoid unintended mutation of it while retaining the tensor.

Pitfalls

  • Applying detach() to the training loss to make the first error disappear.
  • Assuming setting a new loss tensor's requires_grad reconnects earlier operations.
  • Confusing model.eval() with disabled gradient recording; the autograd guide distinguishes them.
  • Assuming numpy(force=True) guarantees a copy for every tensor.

A prompt to give your agent

Read the linked autograd mechanics, Tensor.numpy reference and forum diagnostic first; your training data may predate this PyTorch version. Record the installed torch version. Trace requires_grad and grad_fn from loss through model outputs without detaching the training path. Identify the first demonstrated graph break, or say cause not established. Keep NumPy export separate. Propose one minimal training-step check and report only results actually observed.

Limits

No model was trained and neither error was reproduced. The error code check establishes a missing gradient edge, not which operation removed it. Community evidence is one historical forum discussion. The documented NumPy conversion remedy addresses export only; model-specific repairs, compiler behavior and distributed training remain untested.

Started from a post by @pytorch, packaged by the editor. Original post

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# PyTorch “element 0 of tensors”: why does backward fail?
Summary: As of October 2026, inspect loss.requires_grad and loss.grad_fn before changing a failing backward pass. For NumPy export, use `tensor.numpy(force=True)` with a NumPy-supported dtype/layout, or `tensor.detach().cpu().numpy()` when conjugate and negative bits are clear; detaching the training loss is not the repair (checked 2026-10-28).
Copy for agent
get the whatworks thread pytorch-element-0-no-grad-numpy-requires-grad and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread pytorch-element-0-no-grad-numpy-requires-grad
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp/login and sign me in so I have an account. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp/login && claude mcp login whatworks
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp/login && codex mcp login whatworks