1

Increasing Speed a LLM Serving Inference

#73

해당 이슈를 참고하여 도출한 결과, fp16으로 추론을 하면 속도향상에 도움이 된다.

from transformers import AutoTokenizer, AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained(model_path, device_map = 'auto', torch_dtype = torch.float16)
  • 현재, ChatKoAlpaca는 TensorParallel을 통해 서빙중이며 fp16 모델로 서비스 중
  • #81 해당 Issue를 참고하여 text-generation-inference를 통해 서빙하는 방법론을 알아냈음

  • 그 외, Inference에 있어서 성능을 끌어 낼 수 있는 방안
    1. DeepSpeed 사용
    2. Accelerate 사용
      • Handling big models for inference
      • accelerate.infer_auto_device_map을 통해 각 GPU에 할당되는 메모리를 조절 가능한데.. 이게 속도 향상에 무슨 의미가 있는지 모르겠음. 기존 transformers의 Inference는 각 GPU에 동등하게 할당한 후, GPU+offload-CPU를 통해 추론하여 속도가 낮은 결과이므로 GPU할당량 자체를 늘려줘서 CPU사용량을 최소한으로 줄이겠다는 개념인지?
      • device_map = infer_auto_device_map(my_model, max_memory={0: "10GiB", 1: "10GiB", "cpu": "30GiB"}) 같은 방법으로 적용해줄 수 있음

Tensor Parallel

import tensor_parallel as tp

model = AutoModelForCausalLM.from_pretrained(model_path, device_map = 'auto')
model = tp.TensorParallelPreTrainedModel(model, device_ids = ['cuda:0', 'cuda:1'])

#TensorParallelPreTrainedModel(
#  (wrapped_model): TensorParallel(
#    (module_shards): ModuleList(
#      (0-1): 2 x GPTNeoXForCausalLM(
#        (gpt_neox): GPTNeoXModel(
#          (embed_in): TensorParallelWrapper(
#            (tp_wrapped_module): Embedding(30080, 4096)
#          )
#          (layers): ModuleList(
#            (0-27): 28 x GPTNeoXLayer(
#              (input_layernorm): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)
#              (post_attention_layernorm): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)
#              (attention): TensorParallelWrapper(
#                (tp_wrapped_module): GPTNeoXAttention(
#                  (rotary_emb): RotaryEmbedding()
#                  (query_key_value): Linear(in_features=4096, out_features=6144, bias=True)
#                  (dense): Linear(in_features=2048, out_features=4096, bias=True)
#                )
#              )
#              (mlp): TensorParallelWrapper(
#                (tp_wrapped_module): GPTNeoXMLP(
#                  (dense_h_to_4h): Linear(in_features=4096, out_features=8192, bias=True)
#                  (dense_4h_to_h): Linear(in_features=8192, out_features=4096, bias=True)
#                  (act): GELUActivation()
#                )
#              )
#            )
#          )
#          (final_layer_norm): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)
#        )
#        (embed_out): TensorParallelWrapper(
#          (tp_wrapped_module): Linear(in_features=4096, out_features=15040, bias=False)
#        )
#      )
#    )
#    (_sanity_check_params): ParameterList(
#        (0): Parameter containing: [torch.float32 of size 0 (GPU 0)]
#        (1): Parameter containing: [torch.float32 of size 0 (GPU 1)]
#    )
#  )
#)

Pypi - Tensor parallel 패키지를 사용하여 모델을 Tensor Parallel 적용 가능하나 내 경우엔 Inference 속도 향상의 효과는 전혀 보지 못하였음.

4bit or 8bit Quantization

## 4bit
double_quant_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_use_double_quant=True,
    bnb_4bit_quant_type = "nf4",
    bnb_4bit_compute_dtype=torch.bfloat16
)

qnt4_model = AutoModelForCausalLM.from_pretrained(model_path, quantization_config = double_quant_config)
  • 위 코드로 4bit 실험 결과, 필요 메모리 또한 24GB로 그대로였고 성능에서도 별 차이가 없었음. 4bit 활용 자체가 안된 듯.

  • load_in_8bit = True로 모델을 불러온 결과, 8bit로 모델을 불러온 것을 확인하였고 메모리 사용량 또한 8.4GB만을 사용하였음을 확인. 더불어서 모델 성능은 약간 저하되었으나 GPU resource가 적은 machine에서 사용하면 적합한 방법론이라고 생각이 들었음.

  • 4bit quantization은 peft-LoRA를 사용해서 불러와야 resource나 performance에서 효과를 볼 수 있는듯?? 이에 polyglot-ko-12.8b 모델로 실험 진행

    • base model 메모리 : 25.6GB + 25.6GB
    • peft-4bit model 메모리 : 25.6GB + 37.7GB
    • base model 8bit 로드 메모리 : 7.8GB + 7.8GB
      • Inference 속도 : 약 58초

결론

2

  • Ubuntu 20.04
  • python -V and python3 -V » Python 3.10.12
  • python3.10 -V » Python 3.10.6

상황

  1. root directory의 메모리가 초과된 상황
  2. 이에 가상환경은 외장하드에 구축한 상황
  3. 패키지를 가상환경에 따로 구축하고 싶은 상황

이슈

  1. 가상환경에 activate하여 패키지 설치 도중, device space 초과 에러 발생

Trouble-Shooting

  1. numpy 패키지 설치 > pip list > numpy 패키지 설치 확인 + venv/lib/python3.10/site-package/에 numpy 폴더 확인
  2. 잘 설치되는 것 같아, pip install torch==2.0.0+cu118 torchvision==0.15.1+cu118 torchaudio==2.0.1 --index-url https://download.pytorch.org/whl/cu118를 통해 torch 설치
  3. 또 device space 초과 에러 발생!!
  4. pip install -r requirements.txt --user –user 옵션을 통해 base의 패키지를 가져와서 커스텀하려 했으나 가상환경의 패키지 폴더 안에 패키지가 따로 구축이 안됨.. 근데 pip list 하면 base의 패키지 모두 설치되어 있음. 해당 옵션을 사용하면 가상환경 폴더 내에 패키지를 구축하는 방식은 아닌듯.

결론

  1. sudo pip install ~~ 절대 하지 말 것
  2. base 환경의 패키지를 가져올 때, pip install 옵션에 디렉토리를 변경해 줄 수 있는 방법이 있는지 찾아봐야 할 듯
  3. pip가 root directory에 설치됐나? or 사용하고 있는 파이썬 자체가 root directory에 설치됐을 수도 있음 » 확인 결과, 파이썬(3.10.6)은 외장하드에 설치되어있음.
  4. 패키지 설치를 pip3.10 install로 해야하나??

해결

  • wget을 통해 .whl 파일을 받아 직접 설치