另外我也希望device(GPU)的記憶體要被釋放
- User
另外我也希望device(GPU)的記憶體要被釋放
Assistant
非常好的補充!你希望在切換模型時,將前一個模型從 GPU 移回 CPU,並確保 GPU 記憶體被釋放,以避免 OOM(Out of Memory)錯誤。這在多模型推理、多輪測試或資源受限的環境中非常重要。
下面我會提供一個 完整、安全、可重用的解法,涵蓋:
- 模型在 GPU 和 CPU 之間的移動
- 確保 GPU 記憶體被釋放(包括
empty_cache()和gc.collect()) - 記錄當前活躍模型
- 保持代碼清晰、模組化
✅ 完整範例:使用
ModelSwitcher類來安全切換模型並釋放 GPU 記憶體import torch import gc from typing import Optional, Dict from transformers import AutoModel class ModelSwitcher: def __init__(self, device: str = 'cuda'): """ 初始化設備,自動判斷是否有 GPU。 """ self.device = torch.device(device if torch.cuda.is_available() else 'cpu') self.models: Dict[str, AutoModel] = {} # 儲存所有模型(初始在 CPU) self.active_model: Optional[str] = None # 當前激活的模型名稱 def add_model(self, name: str, pretrained_model_name_or_path: str): """ 添加模型(預設放在 CPU 上) """ if name in self.models: raise ValueError(f"Model '{name}' already exists.") model = AutoModel.from_pretrained(pretrained_model_name_or_path).to('cpu') self.models[name] = model print(f"[INFO] Model '{name}' loaded to CPU.") def switch_to_model(self, name: str): """ 切換到指定模型(移動到 GPU),並釋放當前模型(若存在) """ if name not in self.models: raise ValueError(f"Model '{name}' not found.") # 如果當前有活躍模型,先釋放 if self.active_model is not None and self.active_model != name: self._unload_current_model() # 將指定模型移動到 GPU self.models[name] = self.models[name].to(self.device) self.active_model = name print(f"[INFO] Switched to model '{name}' on {self.device}.") print(f"[INFO] GPU Memory: {self._get_gpu_memory()}") return self.models[name] def _unload_current_model(self): """ 卸載當前模型(移回 CPU),釋放 GPU 記憶體 """ if self.active_model: print(f"[INFO] Unloading model '{self.active_model}' from GPU...") self.models[self.active_model] = self.models[self.active_model].to('cpu') torch.cuda.empty_cache() gc.collect() print(f"[INFO] Model '{self.active_model}' unloaded from GPU.") print(f"[INFO] GPU Memory: {self._get_gpu_memory()}") def _get_gpu_memory(self): """ 查詢當前 GPU 記憶體使用情況(僅限有 GPU) """ if self.device.type == 'cuda': 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 detected." def get_active_model(self): """ 取得目前激活的模型 """ if self.active_model is None: return None return self.models[self.active_model] def remove_model(self, name: str): """ 從管理器中移除模型(並釋放記憶體) """ if name in self.models: if self.active_model == name: self._unload_current_model() del self.models[name] print(f"[INFO] Model '{name}' removed from manager.")
✅ 使用範例
# 初始化 switcher = ModelSwitcher(device='cuda') # 如果沒有 GPU,自動 fallback 到 CPU # 加入兩個模型 switcher.add_model("bert", "bert-base-uncased") switcher.add_model("gpt2", "gpt2") # 切換到 BERT 模型(GPU 上) bert_model = switcher.switch_to_model("bert") # 進行推理(假設你有 input_ids) # outputs = bert_model(input_ids.to(switcher.device)) # 切換到 GPT-2 模型(自動釋放 BERT) gpt2_model = switcher.switch_to_model("gpt2") # 進行推理 # outputs = gpt2_model(input_ids.to(switcher.device)) # 移除模型(可選) switcher.remove_model("bert") # 關閉應用前清空 GPU 記憶體(可選) switcher._unload_current_model() # 如果仍有模型在 GPU 上
✅ 額外提醒
-
記憶體釋放的可靠性:
torch.cuda.empty_cache()會釋放未使用的緩衝記憶體,但無法釋放仍被張量引用的記憶體。- 所以必須先將模型移出 GPU,再呼叫
empty_cache(),這樣才會真正釋放。
-
GC(垃圾回收):
gc.collect()可以清理 Python 中的無用物件,避免記憶體洩漏。
-
混合精度 / 多卡情況:
- 如果你使用的是
deepspeed、accelerate、fp16,記得同樣要清除相關的上下文和緩衝。
- 如果你使用的是
-
避免模型共享參數:
- 確保每個模型是獨立的實例,不要用
.to(device)重複共用同一個模型變數。
- 確保每個模型是獨立的實例,不要用
✅ 小技巧:快速檢查模型是否在 GPU 上
print(next(bert_model.parameters()).device) # 應該是 cuda:0 或 cpu
如果你還有特定需求,例如:
- 多張 GPU(如切換到
cuda:1) - 使用
transformers.pipeline - 在 Web API 或推理服務中切換模型
也可以告訴我,我可以提供進一步的整合範例。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.