Using detach() Before Calling Metrics
#2520
Replies: 2 comments
|
@RoyiAvital I am wondering the same thing but I can't find any relevant information in the documentation. |
|
Good question — and you're right the docs don't spell this out. TL;DR: TorchMetrics handles detach internally. You don't need to call Here's why: all Quick proof: import torch
from torchmetrics.classification import BinaryAccuracy
preds = torch.tensor([0.8, 0.2, 0.9], requires_grad=True)
target = torch.tensor([1, 0, 1])
metric = BinaryAccuracy()
result = metric(preds, target)
print(result.requires_grad) # False — no grad graphWhen you SHOULD detach: if you're storing raw predictions/targets in a list state (e.g., for ROC curves), the tensor references could keep the computation graph alive in memory. In practice, TorchMetrics' internal state management handles this, but if you're seeing unexpected GPU memory growth, adding # Safe pattern for memory-sensitive training loops
metric.update(preds.detach(), target)It's a no-op cost-wise (detach doesn't copy data), so there's no downside. Docs: Metric base class |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Should I call
detach()before calling metrics or is it built in?What is the suggested way to handle this in order to be as efficient as possible memory and run time wise?
All reactions