python 으로 llama2 모델을 실행하기
맥북이 아니거나 나는 docker 로 모델을 실행하고 싶다면 docker 에서 llama2 실행하기를 보길 바람.
llama.cpp 을 사용하여 실행할 것임.
언어 모델을 다운하기
meta 의 llama git 프로젝트 받기
원하는 경로에 llama git 을 클론하자.
(https://github.com/facebookresearch/llama)
다운로드 요청 링크 받기
meta 의 llama 페이지에 가서 download models 를 누르면 정보를 입력하는 페이지가 나온다.
(https://llama.meta.com/)
개인정보를 입력하고 사용할 모델을 선택하여 완료버튼을 누르면
입력한 이메일로 선택한 모델의 다운로드 요청 키가 발송된다.
이메일 내용에
How to download the models:
When asked for your unique custom URL, please insert the following:
이 부분에 링크가 있을 것이다. 복사해 두자.
다운로드 하기
클론한 프로젝트에 download.sh 가 있을 것이다. 실행 시키면 된다.
직접 download.sh 를 실행하면 그냥 닫히는 경우가 있는듯하니 다음처럼 cmd 에서 파일이 있는 경로로 이동하여 실행시키자.
cd ~/클론한프로젝트경로
./download.sh
# 실행시키면 뭔가 입력하라고 하는데 위에서 이메일로 받은 링크를 입력하면 된다.
Enter the URL from email:
Enter the list of models to download without spaces (7B, 13B, 70B, 7B-chat, 13B-chat, 70B-chat), or press Enter for all: 7B-chat
# 다운 받을 모델을 입력하면된다. 7B, 13B, 70B, 7B-chat, 13B-chat, 70B-chat 중에서 하나.
# 우리는 로컬에서 실행해야 하므로 가장 작은 7B-chat 모델을 다운 받겠다.
모델의 용량이 14gb 정도로 크니 여유 공간을 미리 확보하길 바란다.
다운이 완료되면 프로젝트에 llama-2-7b-chat 이라는 폴더가 생성되었을 것이다.
모델 변환 하기
맥북에서 실행시키기 위해 받은 모델을 변환해야 한다.
llama.cpp git 클론하기
(https://github.com/ggerganov/llama.cpp)
homebrew 와 xcode command line tools 를 설치해야 함.
위 두개 설치는 알아서 설치... 여기까지 읽은 사람이라면 이미 다른이유로 설치되어 있을 것이다.
클론한 llama.cpp 프로젝트 경로로 이동하여 다음 명령어를 실행한다.
cd llama.cpp
LLAMA_METAL=1 make
모델을 실행하기 위해 맥북의 GPU를 가속 하기 위한 설정인듯 하다.
모델 변환
이제 llama.cpp 의 python 가상환경을 만들고 필수 라이브러리를 설치해주자.
( python 가상환경은 여기까지 읽은 사람이라면... 생략 )
pip install -r requirements.txt
이제 llama.cpp 의 convert.py 를 다운받은 모델의 폴더(llama git 프로젝트) 경로를 옵션으로 주고 실행시키자.
python convert.py ../llama/llama-2-7b-chat
실행이 완료되면 llama-2-7b-chat 하위에 ggml-model-f16.gguf
파일이 생성되었을 것이다.
이 파일을 더 작게 만들어야 한다. llama.cpp 의 quantize 를 사용하여 다음과 같이 모델의 위치에 변환하자.
# ./quantize [양자화할모델경로] [양자화한모델명과저장경로] [양자화옵션]
./quantize ../llama/llama-2-7b-chat/ggml-model-f16.gguf ../llama/llama-2-7b-chat/ggml-model-f32_q4_1.gguf q4_1
양자화 정보
(https://github.com/ggerganov/llama.cpp?tab=readme-ov-file#quantization)
완료 되면 14gb 정도였던 ggml-model-f16.gguf 모델이 4gb 정도로 줄어든 ggml-model-f32_q4_1.gguf 모델이 만들어 졌을 것이다.
파이썬에서 실행하기 위한 llama-cpp-python 설치 및 metal 활성화
CMAKE_ARGS="-DLLAMA_METAL=on" FORCE_CMAKE=1 pip install llama-cpp-python
모델 실행 하기
간단하다. 아무 파이썬파일을 만들고 Llama 를 import 하여 사용할 모델의 경로만 넣어주고 실행하면 된다.
예제 파일
test.py
from llama_cpp import Llama
model_path = "모델 위치 ... llama/llama-2-7b-chat/ggml-model-f16-q4_1.gguf"
model = Llama(model_path = model_path,
n_ctx = 2048, # context window size
n_gpu_layers = 1, # enable GPU
use_mlock = True) # enable memory lock so not swap
str = input('질문 입력 : ')
prompt = f"""
[INST]<<SYS>>
{str}
[/INST]
"""
data = model(prompt = prompt, max_tokens = 120, temperature = 0.2)
print('output : ' , data['choices'][0]['text'])
질문결과는 다음과 같이 json 형태로 반환해 준다.
{
"id":"cmpl-1fc7e8f5-464c-4ca4-be0d-d908561152c6",
"object":"text_completion",
"created":1710147156,
"model":"모델경로/llama-2-7b-chat/ggml-model-f16-q4_1.gguf",
"choices":[
{
"text":"I'm not sure I understand what you are asking for. Could you please provide more context or clarify your question? As an AI language model, I can only provide text in a vector format if that is what you want. Please let me know if there is anything else I can help with.",
"index":0,
"logprobs":"None",
"finish_reason":"stop"
}
],
"usage":{
"prompt_tokens":24,
"completion_tokens":61,
"total_tokens":85
}
}
참고한 글
(https://medium.com/@auslei/llama-2-for-mac-m1-ed67bbd9a0c2)
'Dev > Devlog' 카테고리의 다른 글
[Mybatis] selectKey - INSERT 후 key 값 가져오기 (0) | 2025.02.12 |
---|---|
[VMware Horizon Client, Mac] - Mac 에서 클라이언트 여러개 실행하기 (0) | 2025.02.11 |
[llama2/docker/ollama] llama2 로컬에서 docker 로 실행하기 (0) | 2024.03.13 |
[spring boot/python/llama2/docker] spring boot 프로젝트에 LLM (llama2) 사용해보기 - 0 (0) | 2024.03.13 |
[Obsidian, Mac] mac 맥 옵시디언 obsidian 한글 입력 문제 (0) | 2023.12.06 |