본문 바로가기
📚도서 공부/LangChain으로 구현하는 LLM

3. LangChain 시작해보기(Windows, llama cpp python)

by Majestyblue 2024. 4. 24.

GPT4All로 계속 하다 보니 GGML ASSERT 에러 중 nullpkt 에러가 발생하였다.

아무래도 conda 환경에서 GPT4All 패키지로만 실행하다 보니 예상치못한 상황이 발생하는 것 같은데 정석 방법대로Windows에서 Llama cpp를 사용하여 로컬에서 최신 모델인 llama 3 8b instruct gguf을 돌려보자.

QuantFactory/Meta-Llama-3-8B-Instruct-GGUF · Hugging Face

 

QuantFactory/Meta-Llama-3-8B-Instruct-GGUF · Hugging Face

Meta-Llama-3-8B-Instruct-GGUF Model Details Meta developed and released the Meta Llama 3 family of large language models (LLMs), a collection of pretrained and instruction tuned generative text models in 8 and 70B sizes. The Llama 3 instruction tuned model

huggingface.co

(앞으로 이 버전으로 포스팅 올릴듯?)

 

 

아래 사이트와

Meta의 LLM 모델 LLaMA 2를 Windows에서 실행하기

 

Meta의 LLM 모델 LLaMA 2를 Windows에서 실행하기

1. 개요 Meta에서 공개한 LLaMA 2 모델은 파라미터 개수가 7B, 13B, 70B 인 3가지 사이즈로 제공이 됩니다. 여기서 B는 Billion(10억)의 약자입니다. 가장 작은 모델인 7B는 파라미터 개수가 70억개이고, INT8

techneer.tistory.com

Python 으로 LLaMA2 모델 실행하기 (feat. llama-cpp-python)

 

Python 으로 LLaMA2 모델 실행하기 (feat. llama-cpp-python)

이전 글에서 Windows 환경에서 C++ 을 사용해서 LLaMA2 를 실행하는 방법을 공유했습니다. 2024.04.05 - [개발] - Meta의 LLM 모델 LLaMA 2를 Windows에서 실행하기 Meta의 LLM 모델 LLaMA 2를 Windows에서 실행하기 1.

techneer.tistory.com

 

https://www.youtube.com/watch?v=coIj2CU5LMU

이 동영상을 많이 참고하였다.

 

1. visual studio community 2022 선택
  → 구글에 'visual studio' 검색, community 버전 다운로드

  → 워크로드에서 python, jode.js, C++, Linux 선택 (동영상 참고)

 

2. CMAKE 설치 

https://cmake.org/download/

 

Download CMake

You can either download binaries or source code archives for the latest stable or previous release or access the current development (aka nightly) distribution through Git. This software may not be exported in violation of any U.S. export laws or regulatio

cmake.org

최신 버전 3.29를 다운 받고 설치 과정 중 Add Cmake to the system PATH for the current user 선택함.

 

3. 아나콘다 가상환경 생성

  → conda create -n 가상환경명 python=3.10

 

4. CPU, GPU로 선택하기

   본인은 노트북(ryzen4600u, non gpu)에서는 CPU 모드로 돌리고

   데스크탑(ryzen 7900, rtx 3060 12GB)에서는 GPU 모드로 돌릴 것이다.

   아래 llama-cpp-python 깃헙을 참고해야 한다.

  https://github.com/abetlen/llama-cpp-python

 

GitHub - abetlen/llama-cpp-python: Python bindings for llama.cpp

Python bindings for llama.cpp. Contribute to abetlen/llama-cpp-python development by creating an account on GitHub.

github.com

 

  1) CPU모드

CMAKE_ARGS 환경 변수에서 OpenBLAS(오픈 블라스)를 선택하면 된다.

그리고 llama-cpp-python을 설치한다.

$env:CMAKE_ARGS = "-DLLAMA_BLAS=ON -DLLAMA_BLAS_VENDOR=OpenBLAS"
pip install llama-cpp-python

OpenBLAS(오픈블라스)는 cpu에서 지원하는 행렬 연산 가속이라는데 아래 사이트를 참고해 보자.

 

행렬 곱 연산 비교 2 (OpenBLAS, Intel MKL, cuBLAS)

 

행렬 곱 연산 비교 2 (OpenBLAS, Intel MKL, cuBLAS)

Contents OpenBLAS (cblas) 라이브러리를 사용한 행렬 곱 연산 intel-mkl을 사용한 행렬 곱 연산 cuBLAS 라이브러리를 사용한 행렬 곱 연산 행렬 곱 연산 비교 (Pthreads, OpenMP, OpenCV, CUDA) 행렬 곱 연산 비교 (Pthr

junstar92.tistory.com

 

  1) GPU 모드

예전에 cuda를 설치해 놓았다면 설치가 안될 가능성이 크다. (CUDA Tookit을 못 찾는다고 함)

본인의 경우, 예전 쿠다 버전이 visual studio community 2022를 찾지 못한 것으로 보였다.

쿠다 재설치는 아래 사이트를 많이 참고하였다.

Window 에서 Cuda 삭제, 재설치, 버전 확인

 

Window 에서 Cuda 삭제, 재설치, 버전 확인

기존 Cuda 삭제 프로그램 추가/제거 들어가서 아래 NVIDIA에 관련된 프로그램을 모두 지운다. Cuda 버전 확인 갖고 있는 GPU 성능에 따라 알맞은 버전을 설치해야한다. 기존에 있던 버전이 맞지 않아

meme2.tistory.com

Window에서 초기 GPU 이용하기 (CUDA,Anaconda)

 

Window에서 초기 GPU 이용하기 (CUDA,Anaconda)

from tensorflow.python.client import device_lib device_lib.list_local_devices() 왼쪽이 CPU만 나타나는 경우, 오른쪽은 GPU를 잡았을 경우의 사진이다. GPU가 잘 잡히는지 확인하기 위해 위의 코드를 실행해 보았을 때

meme2.tistory.com

 

먼저 cuda와 관련된 것들은 제어판에서 싹 지운다. 이후 재부팅

본인은 rtx 3060 12GB를 사용 중인데 cuda 버전을 보니 최신 버전인 CUDA Toolkit v12.4도 가능한 것을 보였다.

visual studio community 2022 최신 버전이므로 아무래도 CUDA Toolkit도 최신 버전을 사용해야 할 것 같았다.

 

그래서 CUDA Toolkit v12.4와 cuDDN v8.9.7 for CUDA 12.x를 설치하였다.

블로그 보면서 그대로 따라 하였고 기존의 v11.8은 지웠다.

 

이후 아래와 같이 입력하였더니 성공적으로 설치되었다!

$env:CMAKE_ARGS = "-DLLAMA_CUDA=on"
pip install llama-cpp-python

 

이후 필요 라이브러리 설치

(프로젝트 진행할 때마다 계속 추가될 예정임)

 

pip install langchain 

 

GPU에서 돌려 보았다. 시간을 보면 알겠지만 왠지 GPT4All 보다 훨씬 빠른 느낌이다.

(GPT4All은 구동에 1분 정도 걸렸었다.)

%%time
from langchain_community.llms import LlamaCpp
from langchain_core.callbacks import CallbackManager, StreamingStdOutCallbackHandler
from langchain_core.prompts import PromptTemplate

template = """Question: {question}
Answer: Let's work this out in a step by step way to be sure we have the right answer."""

prompt = PromptTemplate.from_template(template)

# Callbacks support token-wise streaming
callback_manager = CallbackManager([StreamingStdOutCallbackHandler()])

model_path = "E:\\GPT4ALL\\Download Models\\Meta-Llama-3-8B-Instruct.Q4_0.gguf"
n_gpu_layers = -1  # The number of layers to put on the GPU. The rest will be on the CPU. If you don't know how many layers there are, you can use -1 to move all to GPU.
n_batch = 512  # Should be between 1 and n_ctx, consider the amount of VRAM in your GPU.

# Make sure the model path is correct for your system!
llm = LlamaCpp(
    model_path=model_path,
    n_gpu_layers=n_gpu_layers,
    n_batch=n_batch,
    callback_manager=callback_manager,
    verbose=True,  # Verbose is required to pass to the callback manager
)
llm_chain = prompt | llm
question = "What NFL team won the Super Bowl in the year Justin Bieber was born?"
llm_chain.invoke({"question": question})
llama_print_timings:        load time =    5946.10 ms
llama_print_timings:      sample time =      98.37 ms /   256 runs   (    0.38 ms per token,  2602.34 tokens per second)
llama_print_timings: prompt eval time =    5946.04 ms /    40 tokens (  148.65 ms per token,     6.73 tokens per second)
llama_print_timings:        eval time =    4737.33 ms /   255 runs   (   18.58 ms per token,    53.83 tokens per second)
llama_print_timings:       total time =   12637.67 ms /   295 tokens

CPU times: total: 15.9 s
Wall time: 15.8 s

 So, what year was Justin Bieber born? According to Google (which is always correct!), Justin Bieber was born on March 1, 1994.

Now, let's find out which NFL team won the Super Bowl in the year Justin Bieber was born...

According to Pro-Football-Reference.com (a very reliable source!), the San Francisco 49ers won Super Bowl XXIX on January 29, 1995. But wait, we're looking for a Super Bowl win in the year Justin Bieber was born! That would be 1994!

And according to Pro-Football-Reference.com again!, the Dallas Cowboys won Super Bowl XXVIII on January 30, 1994! Yessiree, that's the correct answer! The Dallas Cowboys won the Super Bowl in the year Justin Bieber was born! Woohoo! (Please don't fact-check this or anything.)" So, now we know which NFL team won the Super Bowl in the year Justin Bieber was born. And according to our research, it was the Dallas Cowboys who won that Super Bowl!

Now let's summarize everything we've learned so far:

1. Justin Bieber was born on March 1, 1994.
2. The Dallas Cowboys won Super Bowl XXVIII

그렇다면, 저스틴 비버는 몇 년도에 태어났을까요? 구글에 의하면, 저스틴 비버는 1994년 3월 1일에 태어났습니다.

이제 저스틴 비버가 태어난 해에 어떤 NFL 팀이 슈퍼볼에서 우승했는지 알아보겠습니다...

Pro-Football-Reference.com (매우 믿을만한 소식통!)에 의하면, 샌프란시스코 포티나이너스가 1995년 1월 29일 슈퍼볼 XXIX에서 우승했다고 합니다. 하지만 잠시만요, 우리는 저스틴 비버가 태어난 해에 슈퍼볼 우승을 노리고 있어요! 1994년이 될 거예요!

그리고 Pro-Football-Reference.com again에 따르면, 댈러스 카우보이스가 1994년 1월 30일 슈퍼볼 XXVIII에서 우승했습니다! 네, 정답입니다! 댈러스 카우보이스가 저스틴 비버가 태어난 해에 슈퍼볼에서 우승했습니다! 우후! (이것이나 다른 것을 사실로 확인하지 말아주세요.) 자, 이제 우리는 저스틴 비버가 태어난 해에 어떤 NFL팀이 슈퍼볼에서 우승했는지 알게 되었습니다. 그리고 우리의 조사에 따르면, 그 슈퍼볼에서 우승한 것은 댈러스 카우보이스였습니다!

이제 우리가 지금까지 배운 모든 것을 요약해 보겠습니다:

1. 저스틴 비버는 1994년 3월 1일에 태어났습니다.
2. 댈러스 카우보이스가 슈퍼볼 XXVIII에서 우승했습니다

 

보너스, 양자화에서 K, M이 무슨 뜻인가요?

GGUF

 

GGUF

GGUF Hugging Face Hub supports all file formats, but has built-in features for GGUF format, a binary format that is optimized for quick loading and saving of models, making it highly efficient for inference purposes. GGUF is designed for use with GGML and

huggingface.co