使用 LightningModule 定義模型

Scalable AI Models with PyTorch Lightning

Sergiy Tkachuk

Director, GenAI Productivity

聚焦 LightningModule

  1. 封裝模型架構
  2. 將訓練邏輯整理為單一且易管理的單元
  3. 為深度學習專案建立清晰有序的藍圖

PyTorch LightningModule 圖示

Scalable AI Models with PyTorch Lightning

定義 init 方法

重點任務:

  • 模型初始化
  • super():
    • 自動處理訓練迴圈
    • 紀錄日誌
    • 檢查點儲存
  • 初始化後定義模型層
  • 模組化且易於維護
import lightning.pytorch as pl
import torch.nn as nn

class ClassificationModel(pl.LightningModule):
    def __init__(self, input_dim,
                 hidden_dim, num_class):
          # Initialize parent class
        super().__init__()

# First layer self.layer1 = nn.Linear(input_dim, hidden_dim) # Activation function self.relu = nn.ReLU() # Output layer self.layer2 = nn.Linear(hidden_dim, num_class)
Scalable AI Models with PyTorch Lightning

實作 forward 方法

關鍵步驟:

  • 定義資料在網路中的流向
  • 依序經過各層處理輸入
    • 線性轉換
    • 啟用函式
    • 最後一層與輸出
import lightning.pytorch as pl
import torch.nn as nn

class ClassificationModel(pl.LightningModule):
    def __init__(self, input_dim,
                 hidden_dim, num_class):
          ...

def forward(self, x):
x = self.layer1(x) # Pass input
x = nn.ReLU(x) # Apply activation
x = self.layer2(x) # Compute output
return x # Return result
Scalable AI Models with PyTorch Lightning

範例:手寫數字分類

import lightning.pytorch as pl
from torch.utils.data import DataLoader
from torchvision.datasets import MNIST
from torchvision import transforms

transform = transforms.ToTensor() train_ds = MNIST(root='.', train=True, download=True, transform=transform) test_ds = MNIST(root='.', train=False, download=True, transform=transform) train_loader = DataLoader(train_ds, batch_size=64, shuffle=True) test_loader = DataLoader(test_ds, batch_size=64)
model = ClassificationModel(input_dim=28*28, hidden_dim=128, num_class=10)
trainer = pl.Trainer(max_epochs=3, accelerator='auto') trainer.fit(model, train_loader, test_loader)
Scalable AI Models with PyTorch Lightning

將模型用於分類任務的整合

$$

  • 聚焦分類情境
  • 全流程封裝於 LightningModule
  • 輸出提供軟性最大值前的原始分數
  • 與 Lightning Trainer 整合
class ClassificationModel(pl.LightningModule):
  def __init__(self, input_dim, 
               hidden_dim, output_dim):
    super().__init__()

self.hid = nn.Linear(input_dim, hidden_dim) self.out = nn.Linear(hidden_dim, output_dim)
def forward(self, x):
x = self.hidden(x) x = nn.ReLU(x) x = self.output(x)
return x
Scalable AI Models with PyTorch Lightning

一起來練習吧!

Scalable AI Models with PyTorch Lightning

Preparing Video For Download...