출처: 퍼플렉시티

 

7B 규모 LLM을 8GB 이하의 GPU 메모리에서 학습하기 위해 네트워크 구조 변경 없이 메모리 효율성을 극대화하는 방법은 다음과 같습니다. 이 접근법은 주로 메모리 사용량 감소계산 효율성 향상에 초점을 맞추며, 추론 성능을 유지합니다.

핵심 전략 및 방법론

1. 양자화 (Quantization)

  • 8/4비트 학습: 옵티마이저 상태와 모델 가중치를 8비트 또는 4비트로 저장하여 메모리 사용량을 최대 82.5% 감소시킵니다27. bitsandbytes 라이브러리를 활용해 FP16/BF16 혼합 정밀도와 결합하면 성능 저하 없이 적용 가능합니다3.
  • GaLore (Gradient Low-Rank Projection): 옵티마이저 상태의 메모리 부담을 줄이기 위해 그래디언트 행렬의 저차원 구조를 활용합니다. Adam 옵티마이저의 메모리 요구량을 80% 이상 절감하며, 단일 GPU(예: RTX 4090 24GB)에서도 7B 모델 학습이 가능합니다2.

2. 메모리 최적화 기법

  • Gradient Checkpointing: 순전파 시 중간 활성값을 저장하지 않고 역전파 단계에서 재계산하여 VRAM 사용량을 60~70% 절약합니다36.
  • Activation Offloading: 활성화 텐서를 CPU 메모리 또는 NVMe 스토리지로 오프로드합니다. 특히 MEMO 프레임워크는 토큰 단위 활성화 재계산과 CPU-GPU 간 스와핑을 통해 100만 토큰 시퀀스 학습을 8개 GPU에서 가능하게 합니다8.
  • FlashAttention: 메모리 효율적인 어텐션 알고리즘으로 VRAM 사용량을 최적화하며, 기존 대비 2.2배 빠른 학습 속도를 달성합니다49.

3. 학습 파라미터 최적화

  • Gradient Accumulation: 작은 배치 크기를 사용하고 그래디언트를 누적하여 유효 배치 크기를 유지합니다. 8GB GPU에서는 배치 크기 1~2로 설정 후 8~16단계 누적이 일반적입니다35.
  • 8비트 옵티마이저: AdamW 대신 8비트로 압축된 Adafactor 또는 LAMB 옵티마이저를 사용해 메모리 사용량을 추가로 줄입니다37.

실행 단계 및 도구

  1. 라이브러리 선택: DeepSpeed(ZeRO-2/3), Hugging Face Accelerate, bitsandbytes를 조합해 메모리 최적화를 자동화합니다39.
  2. 모델 초기화: 4비트 양자화된 Llama-7B를 로드하고, GaLore를 적용해 옵티마이저 상태를 저차원으로 프로젝션합니다27.
  3. 학습 설정:
  4.  
    python
    # 예시: 8비트 Adam + Gradient Checkpointing model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b", load_in_4bit=True) model.gradient_checkpointing_enable() optimizer = bnb.optim.Adam8bit(model.parameters(), lr=1e-5)
  5. 실행: FlashAttention-2를 활성화하고, train_batch_size=1, gradient_accumulation_steps=8로 설정해 메모리 한계 내에서 실행합니다45.

성능 및 한계

  • MFU (Model FLOPS Utilization): MEMO 프레임워크는 기존 대비 2.4배 높은 52.3% MFU를 달성하며, 8GB GPU에서도 실용적인 학습 속도를 보장합니다8.
  • 트레이드오프: 양자화와 재계산으로 인해 20~30%의 추가 학습 시간이 발생하지만, 하드웨어 제약을 극복하는 데 필수적입니다16.

이 방법론들은 네트워크 구조 변경 없이도 VRAM 8GB 환경에서 7B 모델의 전체 파라미터 학습(full-parameter training)을 가능하게 하며, 추론 시 양자화된 가중치를 원본 정밀도로 복원해 성능 저하를 방지합니다24.

Citations:

  1. https://www.reddit.com/r/LocalLLaMA/comments/19f9z64/running_a_local_model_with_8gb_vram_is_it_even/
  2. https://www.linkedin.com/posts/anima-anandkumar_paper-page-galore-memory-efficient-llm-activity-7171555545848504320-WQAm
  3. https://huggingface.co/docs/transformers/en/perf_train_gpu_one
  4. https://huggingface.co/docs/transformers/main/llm_tutorial_optimization
  5. https://www.nitorinfotech.com/blog/training-large-language-models-llms-techniques-and-best-practices/
  6. https://github.com/InternLM/Awesome-LLM-Training-System/blob/main/Memory_Optimizations.md
  7. https://stackoverflow.com/questions/77531993/run-llm-on-single-gpu-with-8gb-ram
  8. https://openreview.net/forum?id=NIzbVvB3Ox
  9. https://deepsense.ai/blog/how-to-train-a-large-language-model-using-limited-hardware/
  10. https://milvus.io/ai-quick-reference/what-innovations-are-improving-llm-efficiency
  11. https://www.computer.org/publications/tech-news/trends/training-techniques-large-language-models/
  12. https://www.kisacoresearch.com/content/memory-optimizations-large-language-models-training-inference
  13. https://magazine.sebastianraschka.com/p/practical-tips-for-finetuning-llms
  14. https://www.hyperstack.cloud/technical-resources/tutorials/llm-inference-techniques-to-reduce-latency-and-boost-performance
  15. https://openreview.net/forum?id=s7DkcgpRxL
  16. https://www.youtube.com/watch?v=mbmaEDL2wms
  17. https://openreview.net/forum?id=e0bTcdF29g
  18. https://milvus.io/ai-quick-reference/how-are-llms-optimized-for-memory-usage
  19. https://www.linkedin.com/pulse/mastering-llm-inference-cost-efficiency-performance-victor-qfs6e
  20. https://discuss.huggingface.co/t/llama-7b-gpu-memory-requirement/34323
  21. https://openreview.net/forum?id=rWzECppYr4

Perplexity로부터의 답변: pplx.ai/share

출처: Claude 3.7 Sonnet

 

토치스크립트(TorchScript)

토치스크립트는 PyTorch 모델을 직렬화하고 최적화하기 위한 PyTorch의 중간 표현(Intermediate Representation) 방식입니다. 주요 특징은:

  • PyTorch 모델을 Python 의존성 없이 실행 가능한 형태로 변환합니다
  • C++와 같은 고성능 환경에서 모델을 배포할 수 있게 해줍니다
  • JIT(Just-In-Time) 컴파일을 통해 모델 최적화를 지원합니다
  • torch.jit.script나 torch.jit.trace 메서드를 사용하여 PyTorch 모델을 변환합니다

ONNX(Open Neural Network Exchange)

ONNX는 다양한 딥러닝 프레임워크 간의 모델을 교환하기 위한 개방형 포맷입니다. 주요 특징은:

  • Microsoft, Facebook, AWS 등이 주도하여 개발한 오픈 포맷입니다
  • PyTorch, TensorFlow, MXNet 등 다양한 프레임워크 간 모델 변환을 지원합니다
  • 모델 최적화, 추론 가속화를 위한 도구를 제공합니다
  • 다양한 하드웨어 및 플랫폼에서 일관된 성능을 낼 수 있도록 설계되었습니다

차이점과 관계

토치스크립트는 PyTorch 전용 솔루션인 반면, ONNX는 여러 프레임워크 간 호환성을 위한 범용 솔루션입니다. PyTorch 모델을 토치스크립트로 변환한 후 ONNX 포맷으로 내보내는 워크플로우가 일반적입니다. 이렇게 하면 PyTorch에서 개발한 모델을 TensorFlow 서빙, ONNX 런타임, TensorRT 등 다양한 추론 엔진에서 실행할 수 있습니다.

*상업적으로 이용가능한 라이선스

 

https://github.com/NVlabs/stylegan2-ada-pytorch

 

GitHub - NVlabs/stylegan2-ada-pytorch: StyleGAN2-ADA - Official PyTorch implementation

StyleGAN2-ADA - Official PyTorch implementation. Contribute to NVlabs/stylegan2-ada-pytorch development by creating an account on GitHub.

github.com

-Copyright © 2021, NVIDIA Corporation. All rights reserved.

NVIDIA Source License는 상업적 이용이 제한되어 있다네요.

 

 

https://github.com/NVIDIA/pix2pixHD

 

GitHub - NVIDIA/pix2pixHD: Synthesizing and manipulating 2048x1024 images with conditional GANs

Synthesizing and manipulating 2048x1024 images with conditional GANs - NVIDIA/pix2pixHD

github.com

-BSD License

 

 

https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix

 

GitHub - junyanz/pytorch-CycleGAN-and-pix2pix: Image-to-Image Translation in PyTorch

Image-to-Image Translation in PyTorch. Contribute to junyanz/pytorch-CycleGAN-and-pix2pix development by creating an account on GitHub.

github.com

-BSD License

 

 

출처:DeepSeek

그밖에 여러가지 모델

SPADE (SEAN) : https://github.com/NVlabs/SPADE

 

GitHub - NVlabs/SPADE: Semantic Image Synthesis with SPADE

Semantic Image Synthesis with SPADE. Contribute to NVlabs/SPADE development by creating an account on GitHub.

github.com

OASIS:https://github.com/boschresearch/OASIS

 

GitHub - boschresearch/OASIS: Official implementation of the paper "You Only Need Adversarial Supervision for Semantic Image Syn

Official implementation of the paper "You Only Need Adversarial Supervision for Semantic Image Synthesis" (ICLR 2021) - boschresearch/OASIS

github.com

DALL·E (OpenAI) : https://openai.com/dall-e

DeepLab + Pix2Pix : https://github.com/tensorflow/models/tree/master/research/deeplab

 

models/research/deeplab at master · tensorflow/models

Models and examples built with TensorFlow. Contribute to tensorflow/models development by creating an account on GitHub.

github.com

StyleGAN2-ADA:https://github.com/NVlabs/stylegan2-ada-pytorch

 

GitHub - NVlabs/stylegan2-ada-pytorch: StyleGAN2-ADA - Official PyTorch implementation

StyleGAN2-ADA - Official PyTorch implementation. Contribute to NVlabs/stylegan2-ada-pytorch development by creating an account on GitHub.

github.com

Stable Diffusion : https://github.com/CompVis/stable-diffusion

 

'Computer Vision' 카테고리의 다른 글

대형 LLM모델을 작은 VRAM으로 학습할 수 있는지  (0) 2025.03.21
TorchScript, ONNX  (0) 2025.03.12

+ Recent posts