PyTorch torch.enable_grad 関数


Pytorch torch 参考手册Pytorch torch リファレンスマニュアル

torch.enable_gradPyTorch で勾配計算を有効にするためのコンテキストマネージャーです。これはtorch.no_grad反対に、勾配を必要とするコードブロック内で明示的に勾配計算を有効にするために使用されます。

これは、推論コード内で一時的にモデルをトレーニングする必要がある場合や、特定の局所領域で勾配計算を有効にする必要がある場合に非常に役立ちます。

関数定義

torch.enable_grad()

パラメータ:

  • パラメータはありません。これはコンテキストマネージャーです。

戻り値:

  • コンテキストマネージャーを返し、そのコンテキスト内で勾配計算を有効にします。

使用例

例1: 基本的な使い方

例

import torch

# デフォルトでは、no_grad コンテキスト内
with torch.no_grad():
    x = torch.tensor([1.0, 2.0, 3.0])
    print("no_grad 内:", x.requires_grad)

    # enable_grad を使用して一時的に勾配を有効化
    with torch.enable_grad():
        y = x * 2
        print("enable_grad 内:", y.requires_grad)

    # 終了後、no_grad 状態に戻ります
    z = x * 2
    print("終了後:", z.requires_grad)

出力結果は次のとおりです:

在 no_grad 中: False
在 enable_grad 中: True
退出后: False

例2: トレーニングと推論の併用

例

import torch
import torch.nn as nn

model = nn.Linear(10, 2)

# 推論モード
with torch.no_grad():
    x = torch.randn(5, 10)
    output1 = model(x)
    print("推論出力:", output1.shape)

    # 推論中に一部のパラメータを一時的にトレーニングする必要がある場合
    with torch.enable_grad():
        # 勾配を必要とするテンソルを作成して計算します
        temp_weight = torch.randn(10, 10, requires_grad=True)
        temp_output = torch.mm(x, temp_weight)
        print("一時的に勾配を有効化:", temp_output.requires_grad)

出力結果は次のとおりです:

推理输出: torch.Size([5, 2])
临时启用梯度: True

例3: デコレータでの使用

例

import torch

@torch.enable_grad()
def train_step(x, y):
    """トレーニング手順をシミュレートします"""
    # この関数内部では勾配計算が有効になります
    loss = (x - y).sum()
    return loss

# no_grad コンテキスト内で呼び出します
with torch.no_grad():
    x = torch.tensor([1.0, 2.0, 3.0])
    y = torch.tensor([0.0, 0.0, 0.0])
    # デコレータが勾配計算の有効化を保証します
    loss = train_step(x, y)
    print("Loss:", loss)
    print("勾配が必要:", loss.requires_grad)

出力結果は次のとおりです:

Loss: tensor(6.)
需要梯度: True

関連関数

  • torch.no_grad(): 勾配計算を無効にします。
  • torch.set_grad_enabled(grad): パラメータに応じて勾配計算を有効または無効にします。
  • torch.is_grad_enabled(): 現在勾配計算が有効かどうかを確認します。

注意事項

  • enable_grad主にno_gradコンテキスト内で一時的に勾配計算を有効にするために使用されます。
  • グローバルに勾配が有効化されている環境で使用する場合enable_grad、何の効果もありません。
  • 推奨されるのはenable_gradデコレータを使用して、関数内部で常に勾配が有効になるようにすることです。

Pytorch torch 参考手册Pytorch torch リファレンスマニュアル

その他の拡張