Accelerate documentation

대형 모델 추론

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

대형 모델 추론

Accelerate가 제공하는 가장 큰 발전 중 하나는 Big Model Inference로, 그래픽 카드에 완전히 들어가지 않는 모델로도 추론을 수행할 수 있게 해줍니다.

이 튜토리얼에서는 Accelerate와 Hugging Face 생태계에서 Big Model Inference를 사용하는 방법을 보여줍니다.

Accelerate

PyTorch 모델을 로드하는 일반적인 워크플로우는 다음과 같습니다. ModelClass는 사용자의 장치(mps 또는 cuda 또는 xpu)의 GPU 메모리를 초과하는 모델입니다.

import torch

my_model = ModelClass(...)
state_dict = torch.load(checkpoint_file)
my_model.load_state_dict(state_dict)

Big Model Inference에서는 init_empty_weights 컨텍스트 매니저를 사용하여 모델의 빈 스켈레톤을 초기화하는 것이 첫 번째 단계입니다. my_model이 “파라미터가 없는” 상태이므로 메모리가 필요하지 않습니다.

from accelerate import init_empty_weights
with init_empty_weights():
    my_model = ModelClass(...)

다음으로 추론을 위해 가중치가 모델에 로드됩니다.

load_checkpoint_and_dispatch() 메서드는 빈 모델 내부에 체크포인트를 로드하고, 각 레이어의 가중치를 사용 가능한 모든 장치에 분배합니다. 이 과정에서 가장 빠른 장치(GPU, MPS, XPU, NPU, MLU, SDAA, MUSA)부터 시작하여 더 느린 장치(CPU 및 하드 드라이브)로 이동합니다.

device_map="auto"를 설정하면 먼저 GPU의 모든 사용 가능한 공간을 채운 다음 CPU, 그리고 여전히 메모리가 부족하면 하드 드라이브(가장 느린 옵션)에 배치합니다.

자체 device map를 설계하는 방법에 대한 자세한 내용은 Designing a device map 가이드를 참조하세요.

from accelerate import load_checkpoint_and_dispatch

model = load_checkpoint_and_dispatch(
    model, checkpoint=checkpoint_file, device_map="auto"
)

분할해서는 안 되는 특정 레이어 “chunks”가 있는 경우, no_split_module_classes에 전달하세요(자세한 내용은 여기를 참조).

모델의 가중치는 state_dict가 메모리에 맞지 않는 경우와 같이 메모리를 절약하기 위해 여러 체크포인트로 분할(shard)할 수도 있습니다(자세한 내용은 여기를 참조).

모델이 완전히 배포된 이제 추론을 수행할 수 있습니다.

input = torch.randn(2,3)
device_type = next(iter(model.parameters())).device.type
input = input.to(device_type)
output = model(input)

입력이 각 레이어를 통과할 때마다 CPU에서 GPU(또는 디스크에서 CPU를 거쳐 GPU)로 전송되고, 출력이 계산된 후, 해당 레이어는 GPU에서 제거되어 다시 아래로 내려갑니다. 이는 추론에 일부 오버헤드를 추가하지만, 가장 큰 레이어가 GPU에 들어맞기만 하면 시스템에서 어떤 크기의 모델이든 실행할 수 있게 해줍니다.

여러 GPU, 즉 “모델 병렬성”을 활용할 수 있지만, 한 번에 하나의 GPU만 활성화됩니다. 이로 인해 GPU는 이전 GPU가 출력을 전송할 때까지 대기해야 합니다. torchrun이나 accelerate launch와 같은 다른 도구 대신 Python으로 스크립트를 정상적으로 실행해야 합니다.

아래에서 Big Model Inference의 전체 예제를 확인해 보세요.

import torch
from accelerate import init_empty_weights, load_checkpoint_and_dispatch

with init_empty_weights():
    model = MyModel(...)

model = load_checkpoint_and_dispatch(
    model, checkpoint=checkpoint_file, device_map="auto"
)

input = torch.randn(2,3)
device_type = next(iter(model.parameters())).device.type
input = input.to(device_type)
output = model(input)

Hugging Face 생태계

Transformers나 Diffusers와 같은 Hugging Face 생태계의 다른 라이브러리들은 from_pretrained 생성자에서 Big Model Inference를 지원합니다.

Big Model Inference를 활성화하려면 from_pretrained에 device_map="auto"만 추가하면 됩니다.

예를 들어, Big Model Inference를 사용하여 Big Sciences의 110억 파라미터 모델인 T0pp를 로드할 수 있습니다.

from transformers import AutoModelForSeq2SeqLM

model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0pp", device_map="auto")

모델을 로드한 후, 이전의 빈 init 및 스마트 디스패치 단계가 실행되어 모델이 기기의 모든 리소스를 활용하도록 완전히 준비됩니다. 이러한 생성자를 통해 torch_dtype 매개변수를 지정하여 더 낮은 정밀도로 모델을 로드함으로써 메모리를 더 절약할 수도 있습니다.

from transformers import AutoModelForSeq2SeqLM

model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0pp", device_map="auto", torch_dtype=torch.float16)

다음 단계

Big Model Inference에 대한 더 자세한 설명은 개념 가이드를 꼭 확인해 보세요!

Update on GitHub