TGViewer
پایتون | Data Science | Machine Learning پایتون | Data Science | Machine Learning @python4all_pro · 24.3K subscribers
Post #1411 2.91K
یک فانکشن کاربردی برای پاک‌سازی کامل RAM سیستم و GPU VRAM از آبجکت‌هایی که در ادامه‌ی کد بهشون نیازی ندارین و مشاهده‌ی فضای اشغال‌شده‌ی GPU.

import gc
import time


def clear_memory():
# Delete variables if they exist in the current global scope
if "inputs" in globals():
del globals()["inputs"]
if "model" in globals():
del globals()["model"]
if "processor" in globals():
del globals()["processor"]
if "trainer" in globals():
del globals()["trainer"]
if "peft_model" in globals():
del globals()["peft_model"]
if "bnb_config" in globals():
del globals()["bnb_config"]
time.sleep(2)

# Garbage collection and clearing CUDA memory
gc.collect()
time.sleep(2)
torch.cuda.empty_cache()
torch.cuda.synchronize()
time.sleep(2)
gc.collect()
time.sleep(2)

print(f"GPU allocated memory: {torch.cuda.memory_allocated() / 1024**3:.2f} GB")
print(f"GPU reserved memory: {torch.cuda.memory_reserved() / 1024**3:.2f} GB")


clear_memory()



🆔 @Python4all_pro
  • 👍 8
  • ❤ 2
More from @python4all_pro
  1. Sep 29, 2026What better way to understand a powerful tool like Claude Code than to build your own vers…
  2. Sep 28, 2026🧨 ۲۰۰ آموزش جدید دیگر، جایگزین آموزش‌های قبلی شد... 💯 ۴۰۰+۲۰۰ آموزش در فرادرس، هر آموزش…
  3. Sep 28, 202625 GitHub Repositories Every Python Developer Should Know! Want to improve your Python ski…
  4. Sep 27, 202640+ FREE Python Books from Amazon! Want to improve your Python skills without spending a f…
  5. Sep 26, 2026📖 Turn a PDF into an Animated Flipbook with Python! Want to make your PDFs more interacti…
  6. Sep 23, 2026📚 کتاب‌ «۳۰۰ برنامه پایتون» منبع فوق‌العاده برای یادگیری پایتون از صفر تا سطح مصاحبه‌های…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →