在 PyTorch 和 Transformers 中,將模型在 GPU 和 CPU 之間移動是常見的操作,特別是在 GPU 記憶體有限的情況下。以下是幾種實現方法:
方法一:基本的模型移動操作
import torch
from transformers import AutoModel, AutoTokenizer
# 假設你有兩個模型
model1 = AutoModel.from_pretrained("bert-base-uncased")
model2 = AutoModel.from_pretrained("gpt2")
# 檢查是否有可用的 GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 將第一個模型移到 GPU
model1 = model1.to(device)
# 使用第一個模型...
# ...
# 將第一個模型移回 CPU
model1 = model1.to("cpu")
# 清理 GPU 記憶體
torch.cuda.empty_cache()
# 將第二個模型移到 GPU
model2 = model2.to(device)
方法二:使用上下文管理器(更優雅的方式)
import torch
import gc
from contextlib import contextmanager
@contextmanager
def model_on_device(model, device):
"""上下文管理器:自動管理模型的設備位置"""
original_device = next(model.parameters()).device
model = model.to(device)
try:
yield model
finally:
model = model.to(original_device)
if device.type == 'cuda':
torch.cuda.empty_cache()
gc.collect()
# 使用範例
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 模型1 在 GPU 上運行
with model_on_device(model1, device) as model:
# 在這裡使用 model1
outputs = model(input_ids)
# 離開上下文後,model1 自動回到 CPU
# 模型2 在 GPU 上運行
with model_on_device(model2, device) as model:
# 在這裡使用 model2
outputs = model(input_ids)
方法三:完整的記憶體管理方案
import torch
import gc
from transformers import AutoModel
class ModelManager:
def __init__(self, device='cuda'):
self.device = torch.device(device if torch.cuda.is_available() else 'cpu')
self.current_model = None
def load_model(self, model_name_or_path, model_class=AutoModel):
"""載入新模型並清理舊模型"""
# 清理當前模型
if self.current_model is not None:
self.unload_current_model()
# 載入新模型
print(f"Loading model: {model_name_or_path}")
model = model_class.from_pretrained(model_name_or_path)
model = model.to(self.device)
self.current_model = model
return model
def unload_current_model(self):
"""卸載當前模型並釋放記憶體"""
if self.current_model is not None:
# 將模型移回 CPU
self.current_model = self.current_model.to('cpu')
# 刪除模型引用
del self.current_model
self.current_model = None
# 清理記憶體
gc.collect()
torch.cuda.empty_cache()
print("Model unloaded and memory cleared")
def get_memory_usage(self):
"""獲取當前 GPU 記憶體使用情況"""
if torch.cuda.is_available():
allocated = torch.cuda.memory_allocated() / 1024**3 # GB
reserved = torch.cuda.memory_reserved() / 1024**3 # GB
return f"Allocated: {allocated:.2f}GB, Reserved: {reserved:.2f}GB"
return "No GPU available"
# 使用範例
manager = ModelManager()
# 載入第一個模型
model1 = manager.load_model("bert-base-uncased")
print(f"Memory after loading model1: {manager.get_memory_usage()}")
# 進行一些操作...
# outputs = model1(input_ids)
# 切換到第二個模型(自動清理第一個模型)
model2 = manager.load_model("gpt2")
print(f"Memory after loading model2: {manager.get_memory_usage()}")
# 清理所有模型
manager.unload_current_model()
print(f"Memory after cleanup: {manager.get_memory_usage()}")
方法四:處理多個模型的進階方案
import torch
import gc
from typing import Dict, Optional
class MultiModelManager:
def __init__(self, device='cuda'):
self.device = torch.device(device if torch.cuda.is_available() else 'cpu')
self.models: Dict[str, torch.nn.Module] = {}
self.active_model: Optional[str] = None
def add_model(self, name: str, model: torch.nn.Module):
"""添加模型到管理器(保持在 CPU)"""
model = model.to('cpu')
self.models[name] = model
def activate_model(self, name: str):
"""激活指定模型(移到 GPU)"""
if name not in self.models:
raise ValueError(f"Model '{name}' not found")
# 先停用當前活躍的模型
if self.active_model and self.active_model != name:
self.deactivate_current_model()
# 激活新模型
self.models[name] = self.models[name].to(self.device)
self.active_model = name
return self.models[name]
def deactivate_current_model(self):
"""停用當前模型(移回 CPU)"""
if self.active_model:
self.models[self.active_model] = self.models[self.active_model].to('cpu')
torch.cuda.empty_cache()
gc.collect()
self.active_model = None
def get_active_model(self):
"""獲取當前活躍的模型"""
if self.active_model:
return self.models[self.active_model]
return None
def remove_model(self, name: str):
"""完全移除模型"""
if name in self.models:
if self.active_model == name:
self.deactivate_current_model()
del self.models[name]
gc.collect()
# 使用範例
manager = MultiModelManager()
# 添加多個模型
from transformers import AutoModel
manager.add_model("bert", AutoModel.from_pretrained("bert-base-uncased"))
manager.add_model("gpt2", AutoModel.from_pretrained("gpt2"))
# 使用 BERT
bert_model = manager.activate_model("bert")
# 進行推理...
# 切換到 GPT-2
gpt2_model = manager.activate_model("gpt2")
# 進行推理...
# 清理
manager.deactivate_current_model()
重要提示
-
記憶體清理:使用 torch.cuda.empty_cache() 和 gc.collect() 確保記憶體被正確釋放。
-
檢查設備:始終檢查模型當前所在的設備:
device = next(model.parameters()).device
print(f"Model is on: {device}")
-
批次處理時的注意事項:確保輸入數據也在正確的設備上:
inputs = inputs.to(model.device)
-
混合精度訓練:如果使用混合精度,記得也要管理相關的狀態:
from torch.cuda.amp import autocast
with autocast():
outputs = model(inputs)
這些方法可以根據你的具體需求進行調整。如果你的應用場景有特殊要求,請告訴我,我可以提供更針對性的解決方案。