Chuyển tới nội dung chính

{/* Trang này được tạo tự động từ SKILL.md của kỹ năng bởi website/scripts/generate-skill-docs.py. Chỉnh sửa nguồn SKILL.md, không phải trang này. */}

Tia sét Pytorch

Khung PyTorch cấp cao với lớp Huấn luyện viên, đào tạo phân tán tự động (DDP/FSDP/DeepSpeed), hệ thống gọi lại và bản soạn sẵn tối thiểu. Cân từ laptop đến siêu máy tính cùng mã. Sử dụng khi bạn muốn vòng lặp đào tạo rõ ràng với các phương pháp hay nhất được tích hợp sẵn.

Siêu dữ liệu kỹ năng

NguồnTùy chọn — cài đặt với
`Hermes skills install official/mlops/pytorch-lightning
`
Đường dẫn

optional-skills/mlops/pytorch-lightning ` | | Phiên bản |

1.0.0 ` | | Tác giả | Nghiên cứu dàn nhạc | | Giấy phép | MIT | | Phụ thuộc |

lightning

, `torch

, transformers | | Nền tảng | Linux, macOS, Windows | | Thẻ |

PyTorch Lightning

, `Training Framework

, `Distributed Training

, `DDP

, `FSDP

, `DeepSpeed

, `High-Level API

, `Callbacks

, `Best Practices

, Scalable |

Tham khảo: đầy đủ SKILL.md

thông tin

Sau đây là định nghĩa kỹ năng đầy đủ mà Hermes tải khi kỹ năng này được kích hoạt. Đây là những gì tác nhân coi là hướng dẫn khi kỹ năng được kích hoạt.

PyTorch Lightning - Khung đào tạo cấp cao

Bắt đầu nhanh

PyTorch Lightning tổ chức mã PyTorch để loại bỏ bản soạn sẵn trong khi vẫn duy trì tính linh hoạt.

Cài đặt:

`

pip install lightning

`
``**Chuyển đổi PyTorch sang Lightning** (3 bước):

`Python
import lightning as L
import torch
from torch import nn
from torch.utils.data import DataLoader, Dataset

# Step 1: Define LightningModule (organize your PyTorch code)
class LitModel(L.LightningModule):
def __init__(self, hidden_size=128):
super().__init__()
self.model = nn.Sequential(
nn.Linear(28 * 28, hidden_size),
nn.ReLU(),
nn.Linear(hidden_size, 10)
)

def training_step(self, batch, batch_idx):
x, y = batch
y_hat = self.model(x)
loss = nn.functional.cross_entropy(y_hat, y)
self.log('train_loss', loss) # Auto-logged to TensorBoard
return loss`def configure_optimizers(self):
return torch.optim.Adam(self.parameters(), lr=1e-3)

# Step 2: Create data
train_loader = DataLoader(train_dataset, batch_size=32)

# Step 3: Train with Trainer (handles everything else!)
trainer = L.Trainer(max_epochs=10, accelerator='gpu', devices=2)
model = LitModel()
trainer.fit(model, train_loader)

`
``**Vậy đó!** Huấn luyện viên xử lý:

- Chuyển đổi GPU/TPU/CPU
- Đào tạo phân tán (DDP, FSDP, DeepSpeed)
- Độ chính xác hỗn hợp (FP16, BF16)
- Tích lũy độ dốc
- Kiểm tra điểm
- Ghi nhật ký
- Thanh tiến trình

## Quy trình công việc chung

### Workflow 1: Từ PyTorch tới Lightning`**Mã PyTorch gốc**:

`
``` python
model = MyModel()
optimizer = torch.optim.Adam(model.parameters())
model.to('cuda')

for epoch in range(max_epochs):
for batch in train_loader:
batch = batch.to('cuda')
optimizer.zero_grad()
loss = model(batch)
loss.backward()
optimizer.step()

`
``**Phiên bản tia chớp**:

`
`Python
class LitModel(L.LightningModule):
def __init__(self):
super().__init__()
self.model = MyModel()

def training_step(self, batch, batch_idx):
loss = self.model(batch) # No .to('cuda') needed!
return loss`def configure_optimizers(self):
return torch.optim.Adam(self.parameters())

# Train
trainer = L.Trainer(max_epochs=10, accelerator='gpu')
trainer.fit(LitModel(), train_loader)

`
``**Lợi ích**: 40+ dòng → 15 dòng, không quản lý thiết bị, phân phối tự động

### Quy trình 2: Xác thực và thử nghiệm

`Python
class LitModel(L.LightningModule):
def __init__(self):
super().__init__()
self.model = MyModel()

def training_step(self, batch, batch_idx):
x, y = batch
y_hat = self.model(x)
loss = nn.functional.cross_entropy(y_hat, y)
self.log('train_loss', loss)
return loss`def validation_step(self, batch, batch_idx):
x, y = batch
y_hat = self.model(x)
val_loss = nn.functional.cross_entropy(y_hat, y)
acc = (y_hat.argmax(dim=1) == y).float().mean()
self.log('val_loss', val_loss)
self.log('val_acc', acc)

def test_step(self, batch, batch_idx):
x, y = batch
y_hat = self.model(x)
test_loss = nn.functional.cross_entropy(y_hat, y)
self.log('test_loss', test_loss)

def configure_optimizers(self):
return torch.optim.Adam(self.parameters(), lr=1e-3)

# Train with validation
trainer = L.Trainer(max_epochs=10)
trainer.fit(model, train_loader, val_loader)

# Test
trainer.test(model, test_loader)

`
``**Tính năng tự động**:

- Xác thực chạy mọi kỷ nguyên theo mặc định
- Số liệu được ghi vào TensorBoard
- Điểm kiểm tra mô hình tốt nhất dựa trên val_loss

### Quy trình làm việc 3: Đào tạo phân tán (DDP)

``` python

# Same code as single GPU!
model = LitModel()

# 8 GPUs with DDP (automatic!)
trainer = L.Trainer(
accelerator='gpu',
devices=8,
strategy='ddp' # Or 'fsdp', 'deepspeed'
)

trainer.fit(model, train_loader)

`
``**Khởi động**:

`
``` bash

# Single command, Lightning handles the rest
Python train.py

`
``**Không cần thay đổi**:
- Phân phối dữ liệu tự động
- Đồng bộ hóa độ dốc
- Hỗ trợ nhiều nút (chỉ cần đặt
`num_nodes=2

)

### Quy trình 4: Lệnh gọi lại để giám sát

``` python
from lightning.pytorch.callbacks import ModelCheckpoint, EarlyStopping, LearningRateMonitor

# Create callbacks
checkpoint = ModelCheckpoint(
monitor='val_loss',
mode='min',
save_top_k=3,
filename='model-\{epoch:02d}-\{val_loss:.2f}'
)

early_stop = EarlyStopping(
monitor='val_loss',
patience=5,
mode='min'
)

lr_monitor = LearningRateMonitor(logging_interval='epoch')

# Add to Trainer
trainer = L.Trainer(
max_epochs=100,
callbacks=[checkpoint, early_stop, lr_monitor]
)

trainer.fit(model, train_loader, val_loader)

`
``**Kết quả**:

- Tự động lưu 3 mẫu tốt nhất
- Dừng sớm nếu không cải thiện trong 5 đợt
- Ghi lại tốc độ học tập vào TensorBoard

### Quy trình 5: Lập kế hoạch tốc độ học tập

``` python
class LitModel(L.LightningModule):

# ... (training_step, etc.)

def configure_optimizers(self):
optimizer = torch.optim.Adam(self.parameters(), lr=1e-3)

# Cosine annealing
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
optimizer,
T_max=100,
eta_min=1e-5
)

return {
'optimizer': optimizer,
'lr_scheduler': {
'scheduler': scheduler,
'interval': 'epoch', # Update per epoch
'frequency': 1
}
}

# Learning rate auto-logged!
trainer = L.Trainer(max_epochs=100)
trainer.fit(model, train_loader)

`

## Khi nào nên sử dụng so với các lựa chọn thay thế`**Sử dụng PyTorch Lightning khi**:
- Muốn code sạch sẽ, có tổ chức
- Cần các vòng đào tạo sẵn sàng sản xuất
- Chuyển đổi giữa GPU đơn, đa GPU, TPU
- Muốn gọi lại và ghi nhật ký tích hợp
- Hợp tác nhóm (cấu trúc tiêu chuẩn hóa)

**Ưu điểm chính**:
- **Có tổ chức**: Tách mã nghiên cứu khỏi kỹ thuật
- **Tự động**: DDP, FSDP, DeepSpeed với 1 dòng
- **Gọi lại**: Tiện ích mở rộng đào tạo theo mô-đun
- **Có thể tái tạo**: Ít bản soạn sẵn hơn = ít lỗi hơn
- **Đã thử nghiệm**: Hơn 1 triệu lượt tải xuống/tháng, đã được thử nghiệm trong trận chiến`**Thay vào đó hãy sử dụng các lựa chọn thay thế**:
- **Tăng tốc**: Thay đổi tối thiểu đối với mã hiện có, linh hoạt hơn
- **Ray Train**: Điều phối nhiều nút, điều chỉnh siêu tham số
- **Raw PyTorch**: Kiểm soát tối đa, mục đích học tập
- **Keras**: Hệ sinh thái TensorFlow

## Các vấn đề thường gặp`**Vấn đề: Tổn thất không giảm**

Kiểm tra dữ liệu và thiết lập mô hình:

`
``` python

# Add to training_step
def training_step(self, batch, batch_idx):
if batch_idx == 0:
print(f"Batch shape: \{batch[0].shape}")
print(f"Labels: \{batch[1]}")
loss = ...
return loss

`
``**Vấn đề: Hết bộ nhớ**

Giảm kích thước lô hoặc sử dụng tích lũy độ dốc:

`
``` python
trainer = L.Trainer(
accumulate_grad_batches=4, # Effective batch = batch_size × 4
precision='bf16' # Or 'fp16', reduces memory 50%
)

`
``**Vấn đề: Xác thực không chạy**

Đảm bảo bạn vượt qua val_loader:

`
`Python

# WRONG
trainer.fit(model, train_loader)

# CORRECT
trainer.fit(model, train_loader, val_loader)

`
``**Vấn đề: DDP sinh ra nhiều quy trình một cách bất ngờ**

Lightning tự động phát hiện GPU. Thiết bị được đặt rõ ràng:

`
``` python

# Test on CPU first
trainer = L.Trainer(accelerator='cpu', devices=1)

# Then GPU
trainer = L.Trainer(accelerator='gpu', devices=1)

`

## Chủ đề nâng cao`**Gọi lại**: Xem [references/callbacks.md](https://GitHub.com/NousResearch/Hermes-agent/blob/main/optional-skills/mlops/pytorch-lightning/references/callbacks.md) để biết EarlyStopping, ModelCheckpoint, lệnh gọi lại tùy chỉnh và móc gọi lại.

**Chiến lược phân tán**: Xem [references/distributed.md](https://GitHub.com/NousResearch/Hermes-agent/blob/main/optional-skills/mlops/pytorch-lightning/references/distributed.md) để biết tích hợp DDP, FSDP, DeepSpeed ​​Zero, thiết lập nhiều nút.

**Điều chỉnh siêu tham số**: Xem [references/hyperparameter-tuning.md](https://GitHub.com/NousResearch/Hermes-agent/blob/main/optional-skills/mlops/pytorch-lightning/references/hyperparameter-tuning.md) để tích hợp với các lần quét Optuna, Ray Tune và WandB.

## Yêu cầu về phần cứng
- **CPU**: Hoạt động (tốt cho việc gỡ lỗi)
- **GPU đơn**: Hoạt động
- **Đa GPU**: DDP (mặc định), FSDP hoặc DeepSpeed
- **Đa nút**: DDP, FSDP, DeepSpeed
- **TPU**: Được hỗ trợ (8 lõi)
- **Apple MPS**: Được hỗ trợ**Tùy chọn chính xác**:
- FP32 (mặc định)
- FP16 (V100, GPU cũ hơn)
- BF16 (A100/H100, khuyến khích)
-FP8 (H100)

## Tài nguyên
- Tài liệu: https://lightning.ai/docs/pytorch/stable/
- GitHub: https://GitHub.com/Lightning-AI/pytorch-lightning ⭐ 29.000+
- Phiên bản: 2.5.5+
- Ví dụ: https://GitHub.com/Lightning-AI/pytorch-lightning/tree/master/examples
- Discord: https://Discord.gg/lightning-ai
- Được sử dụng bởi: Người chiến thắng Kaggle, phòng thí nghiệm nghiên cứu, nhóm sản xuất