Docker를 사용하여 LLaMA2 오픈 소스 대형 모델의 공식 버전을 빠르게 시작하세요.

이 기사에서는 Docker 컨테이너를 사용하여 Meta AI에서 생성한 LLaMA2 오픈 소스 대형 모델을 빠르게 시작하는 방법에 대해 설명합니다.

앞에 쓰여진

어제 너무 바빠서 아침에 LLaMA2 모델 다운로드 권한 신청하고 저녁까지 도커 컨테이너 운영 솔루션 신경쓰지 않고 이 컨테이너에 무슨 일이 생겼고 어떻게 사용하는지에 대한 글을 쓸 시간이 없었습니다.

이제 LLaMA2 공식 버전의 대형 모델을 빠르게 시작하는 방법에 대해 이야기해 보겠습니다.

Docker LLaMA2 채팅 오픈 소스 프로젝트

전체 오픈 소스 프로젝트 코드를 soulteary/docker-llama2-chat 에 업로드했습니다 . 필요한 학생들은 스스로 가져갈 수 있습니다.

먼저 준비 작업을 함께 합시다.

준비

준비 작업에는 모델 파일 준비와 모델 실행 환경의 두 가지 주요 단계가 있습니다.

모델 실행 환경에 대해서는 이전 글 " 도커 기반 딥러닝 환경: 시작하기 " 에서 다루었 으므로 자세한 설명은 생략하도록 하겠습니다.

Docker 환경을 설치하고 Docker 컨테이너에 그래픽 카드를 호출할 수 있는 기본 환경을 구성했다면 다음 단계로 진행할 수 있습니다.

모델 다운로드

LLaMA2를 로컬에서 성공적으로 배포하기 위해서는 먼저 모델 파일의 다운로드 권한을 신청해야 하는데, 현재 신청할 수 있는 곳은 메타 AI 공식 홈페이지와 HuggingFace의 메타 모델 페이지 두 곳입니다.

어떤 방법을 선택하든 신청 후 잠시 기다리면 승인 이메일을 받은 다음 페이지를 새로고침하여 모델을 다운로드합니다.

모델 다운로드 권한 승인 알림 이메일

HuggingFace의 모델 다운로드 속도는 Meta AI의 공식 웹 사이트보다 빠르므로 HuggingFace에서 필요한 모델을 준비하는 방법에 중점을 둡니다.

HuggingFace에서 모델 파일 가져오기

HuggingFace에서 가져올 수 있는 두 가지 모델(원본 기본 모델 및 채팅 모델)이 있으며 HuggingFace 플랫폼에서는 PyTorch Pickle 형식과 HuggingFace SafeTensors 형식의 두 가지 형식으로 저장 됩니다 .

LLaMA2 모델 목록

HuggingFace 제품군 버킷도 사용하는 경우 후자 형식을 강력히 권장합니다. 미래에 대비하고 편리하고 안정적이며 로딩 성능이 더 강합니다(더 빠름).

시연을 용이하게 하고 적절한 경험을 얻기 위해 이 기사에서는 모델의 "LLaMA2-Chat-HF" 버전을 사용합니다. 다음 주소에서 모델 다운로드 인증을 신청할 수 있습니다.

그 중 모델의 7B 및 13B 버전은 일반 가정용 비디오 카드(아마도 10G ~ 14G 비디오 메모리 사용)에서 실행할 수 있습니다.

다운로드 권한이 승인되면 다음 명령을 사용하여 필요에 따라 다음 세 가지 모델을 다운로드할 수 있습니다.

# 本地需要按照 Git LFS,https://git-lfs.com
# 安装完毕,进行初始化
git lfs install

# 下载 7B 模型
git clone https://huggingface.co/meta-llama/Llama-2-7b-chat-hf

# 下载 13B 模型
git clone https://huggingface.co/meta-llama/Llama-2-13b-chat-hf

# 下载 70B 模型
git clone https://huggingface.co/meta-llama/Llama-2-70b-chat-hf

다운로드하기로 선택한 모델을 기다린 후 디렉토리 구조를 조정합니다.

# 创建一个新的目录,用于存放我们的模型
mkdir meta-llama

# 将下载好的模型移动到目录中
mv Llama-2-7b-chat-hf meta-llama/
mv Llama-2-13b-chat-hf meta-llama/
mv Llama-2-70b-chat-hf meta-llama/

전체 디렉토리 구조는 다음과 같습니다. 모든 모델은 meta-llama우리가 생성한 디렉토리보다 한 수준 아래에 있습니다.

# tree -L 2 meta-llama
meta-llama
├── Llama-2-13b-chat-hf
│   ├── added_tokens.json
│   ├── config.json
│   ├── generation_config.json
│   ├── LICENSE.txt
│   ├── model-00001-of-00003.safetensors
│   ├── model-00002-of-00003.safetensors
│   ├── model-00003-of-00003.safetensors
│   ├── model.safetensors.index.json
│   ├── pytorch_model-00001-of-00003.bin
│   ├── pytorch_model-00002-of-00003.bin
│   ├── pytorch_model-00003-of-00003.bin
│   ├── pytorch_model.bin.index.json
│   ├── README.md
│   ├── Responsible-Use-Guide.pdf
│   ├── special_tokens_map.json
│   ├── tokenizer_config.json
│   ├── tokenizer.model
│   └── USE_POLICY.md
└── Llama-2-7b-chat-hf
    ├── added_tokens.json
    ├── config.json
    ├── generation_config.json
    ├── LICENSE.txt
    ├── model-00001-of-00002.safetensors
    ├── model-00002-of-00002.safetensors
    ├── model.safetensors.index.json
    ├── models--meta-llama--Llama-2-7b-chat-hf
    ├── pytorch_model-00001-of-00003.bin
    ├── pytorch_model-00002-of-00003.bin
    ├── pytorch_model-00003-of-00003.bin
    ├── pytorch_model.bin.index.json
    ├── README.md
    ├── special_tokens_map.json
    ├── tokenizer_config.json
    ├── tokenizer.json
    ├── tokenizer.model
    └── USE_POLICY.md

위의 내용이 준비되면 모델 실행 준비를 시작합니다.

모델 애플리케이션 시작

다음 명령을 사용하여 Docker LLaMA2 채팅 모델 애플리케이션 파일을 다운로드합니다.

git clone https://github.com/soulteary/docker-llama2-chat.git

프로그램이 다운로드되기를 기다린 후 프로그램 디렉토리에 들어가 필요한 모델 컨테이너 이미지 빌드를 시작합니다.

# 进入程序目录
cd docker-llama2-chat
# 构建 7B 镜像
bash scripts/make-7b.sh
# 或者,构建 13B 镜像
bash scripts/make-13b.sh

meta-llama이미지가 빌드될 때까지 끈기 있게 기다린 후 모델을 저장하는 이전에 준비한 디렉토리를 현재 프로그램 디렉토리로 이동한 다음 시작할 모델 프로그램을 선택합니다.

# 运行 7B 镜像,应用程序
bash scripts/run-7b.sh
# 或者,运行 13B 镜像,应用程序
bash scripts/run-13b.sh

명령이 실행된 후 모든 것이 잘 진행되면 다음과 유사한 로그가 표시됩니다.

=============
== PyTorch ==
=============

NVIDIA Release 23.06 (build 63009835)
PyTorch Version 2.1.0a0+4136153

Container image Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved.

Copyright (c) 2014-2023 Facebook Inc.
Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert)
Copyright (c) 2012-2014 Deepmind Technologies    (Koray Kavukcuoglu)
Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)
Copyright (c) 2011-2013 NYU                      (Clement Farabet)
Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)
Copyright (c) 2006      Idiap Research Institute (Samy Bengio)
Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)
Copyright (c) 2015      Google Inc.
Copyright (c) 2015      Yangqing Jia
Copyright (c) 2013-2016 The Caffe contributors
All rights reserved.

Various files include modifications (c) NVIDIA CORPORATION & AFFILIATES.  All rights reserved.

This container image and its contents are governed by the NVIDIA Deep Learning Container License.
By pulling and using the container, you accept the terms and conditions of this license:
https://developer.nvidia.com/ngc/nvidia-deep-learning-container-license

WARNING: CUDA Minor Version Compatibility mode ENABLED.
  Using driver version 525.105.17 which has support for CUDA 12.0.  This container
  was built with CUDA 12.1 and will be run in Minor Version Compatibility mode.
  CUDA Forward Compatibility is preferred over Minor Version Compatibility for use
  with this container but was unavailable:
  [[Forward compatibility was attempted on non supported HW (CUDA_ERROR_COMPAT_NOT_SUPPORTED_ON_DEVICE) cuInit()=804]]
  See https://docs.nvidia.com/deploy/cuda-compatibility/ for details.

Loading checkpoint shards: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 2/2 [00:05<00:00,  2.52s/it]
Caching examples at: '/app/gradio_cached_examples/20'
Caching example 1/5
/usr/local/lib/python3.10/dist-packages/transformers/generation/utils.py:1270: UserWarning: You have modified the pretrained model configuration to control generation. This is a deprecated strategy to control generation and will be removed soon, in a future version. Please use a generation configuration file (see https://huggingface.co/docs/transformers/main_classes/text_generation )
  warnings.warn(
Caching example 2/5
Caching example 3/5
Caching example 4/5
Caching example 5/5
Caching complete

/usr/local/lib/python3.10/dist-packages/gradio/utils.py:839: UserWarning: Expected 7 arguments for function <function generate at 0x7f3e096a1000>, received 6.
  warnings.warn(
/usr/local/lib/python3.10/dist-packages/gradio/utils.py:843: UserWarning: Expected at least 7 arguments for function <function generate at 0x7f3e096a1000>, received 6.
  warnings.warn(
Running on local URL:  http://0.0.0.0:7860

To create a public link, set `share=True` in `launch()`.

그런 다음 브라우저를 사용하여 LLaMA2 채팅 모델을 열거 http://localhost:7860나 시작합니다.http://你的IP:7860

공식 예제를 사용하여 실행되는 모델 애플리케이션

메모리 사용량

7B 모델이 실제로 실행되면 약 13G의 비디오 메모리를 차지합니다.

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 525.105.17   Driver Version: 525.105.17   CUDA Version: 12.0     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  NVIDIA GeForce ...  Off  | 00000000:01:00.0  On |                  Off |
| 31%   42C    P8    34W / 450W |  14158MiB / 24564MiB |      2%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+
                                                                               
+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
|    0   N/A  N/A      1414      G   /usr/lib/xorg/Xorg                103MiB |
|    0   N/A  N/A      1593      G   /usr/bin/gnome-shell               16MiB |
|    0   N/A  N/A      2772      C   python                          14034MiB |
+-----------------------------------------------------------------------------+

13B 모델은 약 9G의 비디오 메모리를 실행하고 소비합니다.

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 525.105.17   Driver Version: 525.105.17   CUDA Version: 12.0     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  NVIDIA GeForce ...  Off  | 00000000:01:00.0 Off |                  Off |
| 31%   44C    P2    70W / 450W |   9057MiB / 24564MiB |      0%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+
                                                                               
+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
|    0   N/A  N/A      1414      G   /usr/lib/xorg/Xorg                167MiB |
|    0   N/A  N/A      1593      G   /usr/bin/gnome-shell               16MiB |
|    0   N/A  N/A      4686      C   python                           8870MiB |
+-----------------------------------------------------------------------------+

글쎄, 모델을 사용하는 방법을 이해하고 싶다면 이것으로 충분합니다.

모델 이미지 캡슐화

다음으로 위의 스크립트에서 수행된 작업을 간략하게 확장해 보겠습니다.

이 LLaMA2 Docker 이미지를 캡슐화하는 것은 실제로 매우 간단합니다.이전 모델 관련 기사와 다르지 않습니다.Nvidia 기본 이미지를 기반으로 간단한 다단계 빌드를 할 수 있습니다.

예를 들어 모델 프로그램을 실행하는 데 필요한 모든 종속 파일을 포함하는 기본 이미지를 먼저 정의할 수 있습니다.

ROM nvcr.io/nvidia/pytorch:23.06-py3
RUN pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple && \
    pip install accelerate==0.21.0 bitsandbytes==0.40.2 gradio==3.37.0 protobuf==3.20.3 scipy==1.11.1 sentencepiece==0.1.99 transformers==4.31.0
WORKDIR /app

그런 다음 위의 콘텐츠를 로 저장한 Dockerfile.base다음 docker build -t soulteary/llama2:base . -f docker/Dockerfile.base기본 이미지를 빌드하는 데 사용합니다.

다음으로 모델 호출 파일만 준비하면 되는데 관련 프로그램을 soulteary/docker-llama2-chat/llama2-7bsoulteary/docker-llama2-chat/llama2-13b 에 업로드했는데 크게 Gradio 웹 인터페이스와 모델 로딩 및 실행 프로그램 두 가지 파일이 있습니다.

모델 애플리케이션 이미지 파일을 작성합니다.

FROM soulteary/llama2:base
COPY llama2-7b/* ./
CMD ["python", "app.py"]

위 파일 Dockerfile.7bdocker build -t soulteary/llama2:7b . -f docker/Dockerfile.7b.

마지막으로 다음 명령을 사용하여 프로그램을 실행하고 재생합니다.

docker run --gpus all --ipc=host --ulimit memlock=-1 --ulimit stack=67108864 --rm -it -v `pwd`/meta-llama:/app/meta-llama -p 7860:7860 soulteary/llama2:7b

마침내

이 기사는 LLaMA2와 관련된 첫 번째 기사입니다. 불과 몇 달 만에 오픈 소스 프로젝트가 이렇게 빠르게 발전할 수 있어 매우 기쁘고 흥미진진합니다.

LLaMA2는 끝이 아니라 새로운 라운드의 시작입니다.오픈 소스 세계에서 우리는 항상 더 강한 녀석들이 등장하여 현재 세계의 왕에 도전하고 끊임없이 전진할 것을 기대할 수 있습니다.

이 기사의 제목은 다음 기사에 대한 단서를 숨기고 있습니다. 추측할 수 있습니까?

-EOF


이 문서는 "Signature 4.0 International(CC BY 4.0)" 라이선스 계약을 사용합니다. 이를 재인쇄하거나 재사용하는 것은 환영하지만 출처를 표시해야 합니다. 귀속 4.0 국제(CC BY 4.0)

이 글의 저자: 양수

생성 시간: 2023년 7월 21일 단어
수: 10092단어
읽는 시간: 읽는 데 21분

추천

출처blog.csdn.net/soulteary/article/details/131843161