推論のためのtorch.no_grad()
グラフの追跡を省略してメモリを節約します
「推論のためのtorch.no_grad()」はCoddyKit上の無料Deep Learning Academyレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはDeep Learning Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Deep Learning Academyコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
Not Every Pass Needs Grads
You only need gradients while training. When you just want predictions, tracking the graph is wasted work, so PyTorch lets you turn it off. 🛑
Meet torch.no_grad
Wrap code in a torch.no_grad() block and autograd stops recording inside it. No graph is built, and no gradients are stored.
with torch.no_grad():
preds = model(x)Why Skip the Graph
Building the graph costs memory to remember every step for a backward pass that will never come. During inference that overhead is pure waste.
Faster and Lighter
Inside no_grad your forward pass uses less memory and runs a little faster. On big models this lets you fit larger batches when only predicting.
Outputs Are Detached
Tensors created inside the block have requires_grad false. They are plain results you can print, save, or turn into NumPy without complaint.
Use It for Evaluation
Validation and test loops should always run under no_grad. You are scoring the model, not training it, so there is no reason to track gradients.
with torch.no_grad():
for x, y in val_loader:
out = model(x)Pair It With eval Mode
For inference, set model.eval() and wrap calls in no_grad together. eval fixes layers like dropout; no_grad stops the graph. They solve different problems.
It Is a Context Manager
no_grad only affects code inside the with block. Once you leave it, autograd switches tracking back on automatically for your next training step.
The decorator form
You can also tag a whole function with @torch.no_grad(). Every tensor op inside that function then runs without building a graph.
@torch.no_grad()
def predict(x):
return model(x)Detach for a Single Tensor
Need to free just one tensor from the graph instead of a whole block? Call .detach() on it to get a copy that carries no gradient history.
frozen = output.detach()A Safe, Common Habit
Reach for no_grad any time you are not learning: inference, metrics, or saving outputs. It is a tiny change that quietly saves memory and speed.
Quick Check
Recap
Wrap inference in torch.no_grad() to skip graph building, saving memory and time. Pair it with model.eval() whenever you predict instead of train. 🚀
AI チューターと学ぶ Python — 無料
ブラウザでリアルコードを書いて実行し、24/7 の AI チューターから瞬時にサポートを受け、ウェブまたはアプリで続きから学習できます。
- コース
- 30
- レッスン
- 120
よくある質問
「推論のためのtorch.no_grad()」レッスンは無料ですか?
はい。「推論のためのtorch.no_grad()」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Deep Learning Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Deep Learning Academyコースには全4レッスンが含まれています。
「推論のためのtorch.no_grad()」で何を学びますか?
グラフの追跡を省略してメモリを節約します ブラウザで直接実行するハンズオンコードでDeep Learning Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Deep Learning Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのDeep Learning Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「推論のためのtorch.no_grad()」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このDeep Learning Academyレッスンでコードを書いて実行できますか?
はい。すべてのDeep Learning Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- requires_gradと計算グラフ
- backward()を呼び出して勾配を取得する
- .gradの読み取りとゼロ化
- 推論のためのtorch.no_grad()