LLaMa(Alpaca-LoRa)를 이용한 나만의 ChatGPT 만들기

AI|2023. 9. 4. 15:08

그동한 Meta가 공개한 LLama1를  fine-tuning 한 것을 정리보려 합니다.  LLama2가 이미 나오긴 했지만, 아직 LLama2에 대한 Apaca-Lora가 LLama2를 지원하지 않아서 전에 해본 내용을 정리해보았습니다.

OpenAI API가 비용이 드니까 특정 용도로만 쓴다면  ChatGPT를 이용해서 dataset를 생성하고  LLama를 이용해서 로컬에서 fine-tuning해서 사용하면 질은 약간 떨어져 비용면에서 유리하지 않을까 하는 생각에 시도를 해봤습니다.

아시다시피  Meta에서 LLMA (7B, 13B, 33B, 65B) 모델을 공개했습니다. 상업적 용도 외에는 마음대로 사용할 수 있어서 이때 부터 엄청난 뉴스를 쏟아져나왔고, LLaMa2까지도 공개를 했습니다.

아래 글을 참고하세요.
https://arstechnica.com/information-technology/2023/03/you-can-now-run-a-gpt-3-level-ai-model-on-your-laptop-phone-and-raspberry-pi/

그중에 스탠포드 학생들이 만든  Alpaca는 LLaMa를 기반으로 fine-tuning하는 방법을 제공했습니다.
https://crfm.stanford.edu/2023/03/13/alpaca.html

Alpaca는 52K data set를 제공하는데, GPT의 text-davinci-003 모델을 이용해 자동 생성했다고 합니다. 그런데, Nvidia A100정도의 GPU가 필요했습니다. 그런데, LoRA를 적용해서 게이밍 GPU에서도 fine-tuning할 방법이 나왔지요.
https://github.com/tatsu-lab/stanford_alpaca

그것이 바로 Alpaca-LoRa이고 제가 fine-tuning에 성공한 모델이기 합니다.

관련정보: https://devocean.sk.com/blog/techBoardDetail.do?page=&boardType=undefined&query=&ID=164659&searchData=&subIndex=

Fine-tuning

Fine-tuning은 기계 학습에서 미리 훈련된 모델을 특정 작업이나 데이터에 맞게 조정하는 과정을 의미합니다. 대규모 언어 모델(예: GPT )을 사용할 때,  특정 작업 또는 도메인에 더 적합하게 만들어야 할 필요가 있습니다. 이때 fine-tuning이 사용됩니다.

GPT → ChatGPT (Fine-tuning)

LoRa

LoRa에 대해 Bard에게 물어보니 아래와 같이 알려주네요

---------------

LoRA(Low-rank Adaptation)는 비지도 학습 기반의 적응 알고리즘으로, 딥러닝 모델을 새로운 데이터 세트에 적응시키는 데 사용됩니다. LoRA는 모델의 가중치를 낮은 차원의 표현으로 축소한 다음, 새로운 데이터 세트에 맞게 재구성합니다. LoRA는 모델의 복잡성을 줄이고 새로운 데이터 세트에 대한 일반화 성능을 향상시킬 수 있습니다.

LoRA는 다음과 같은 단계로 구현됩니다.

  1. 모델의 가중치를 낮은 차원의 표현으로 축소합니다.
  2. 새로운 데이터 세트에 대한 손실 함수를 계산합니다.
  3. 손실 함수를 최소화하는 방향으로 모델의 가중치를 재구성합니다.

LoRA는 다양한 데이터 세트에서 효과적으로 작동하는 것으로 나타났습니다. 예를 들어, LoRA는 이미지 인식, 자연어 처리, 음성 인식 등 다양한 분야에서 성능을 향상시킨 것으로 나타났습니다.

LoRA는 딥러닝 모델을 새로운 데이터 세트에 적응시키는 데 유용한 도구입니다. LoRA는 모델의 복잡성을 줄이고 새로운 데이터 세트에 대한 일반화 성능을 향상시킬 수 있습니다.

----------------

LoRa에 대한 자세한 설명: https://devocean.sk.com/blog/techBoardDetail.do?ID=164779&boardType=techBlog

LoRa덕분에 Nvidia 4090에서 fine-tuning 이 가능해졌습니다. 이제 우분투 22.04에서 Alpaca-Lora를 이용해 Nvidia 4090으로 fine-tuning을 해보겠습니다.

NVidia Driver 설치

우선 우분투22 .04에  NVidia Driver를 설치합니다.

https://www.nvidia.com/download/index.aspx

매달 업데이트 되는 듯 보이니, 자주 업데이트를 하세요. 

“You appear to be running an X server; please exit X before installing”

위와 같은 에러 메시가 나오면 현재 x-server나와서 weston로 다시 로그인해서 설치를 합니다.

Python & Pytorch 설치

이제, Python을 설치합니다.

$ sudo apt install python3-pip
$ sudo apt install python3-venv
$ python -m venv env
$ source env/bin/activate

Pytorch를 설치합니다.참고 저는 CUDA 11.7에 맞는 2.0.1을 설치했습니다.

https://pytorch.org/get-started/locally/

아래 코드를 실행해서 GPU Driver, CUDA, Pytorch가 제대로 설치되었는 확인합니다.

import torch

# Check if CUDA is available
if torch.cuda.is_available():
	print("CUDA is available.")
	# Print the CUDA device count
	print(f"Number of CUDA devices: {torch.cuda.device_count()}")
	# Print the name of the current CUDA device
	print(f"Current CUDA device name: {torch.cuda.get_device_name(torch.cuda.current_device())}")
else:
	print("CUDA is not available.")

print("pytorch version")
print(torch.__version__)
$ python cuda.py
CUDA is available.
Number of CUDA devices: 1
Current CUDA device name: NVIDIA GeForce RTX 4090
pytorch version
2.0.1+cu117

alpaca-lora 설치

$ git clone https://github.com/tloen/alpaca-lora.git
$ cd alpaca-lora
$ pip install -r requirements.txt

Fine-tuning

 

설치 끝나면 GPT4에서 새롭게 생성한 dataset으로 13b 모델을 fine-tuning을 해보겠습니다.

$ python3 finetune.py --base_model 'yahma/llama-13b-hf' --data_path alphca_data_gpt4.json --output_dir './lora-alpaca-13b'

base model로 아래와 같은 이유로 decapoda-research/llama-7b-hf 대신 yahma/llama-13b-hf를 사용했습니다.

https://github.com/tloen/alpaca-lora/issues/279#issuecomment-1500906791

Inference

fine-tuning할때 입력한 output_dir를 --lora_weight에 입력합니다.

$ python3 generate.py --load_8bit --base_model 'yahma/llama-13b-hf' --lora_weights ./lora-alpaca-13b

Running on local URL:  http://0.0.0.0:7860

위 링크를 열면 테스트를 해봅니다.

Test

Instruction: tell me about Bill Gates

 

Max tokens: 128

Bill Gates is an American business magnate, investor, author, philanthropist, and humanitarian. Gates is the former CEO and current chairman of Microsoft, the software company he founded with Paul Allen. He is consistently ranked among the world's wealthiest people and was the wealthiest overall from 1995 to 2009, excluding 2008, when he was ranked third. During his career at Microsoft, Gates held the positions of CEO and chief software architect, and he remains the largest individual shareholder with more than 6 percent of

Max tokens: 300

Bill Gates is an American business magnate, investor, author, philanthropist, and humanitarian. Gates is the former CEO and current chairman of Microsoft, the software company he founded with Paul Allen. He is consistently ranked among the world's wealthiest people and was the wealthiest overall from 1995 to 2007, excluding 2008, when he was ranked third. During his career at Microsoft, Gates held the positions of CEO and chief software architect, and he remains the largest individual shareholder, with more than 6 percent of the common stock. He has also authored or co-authored several books.
Gates is one of the best-known entrepreneurs of the personal computer revolution. He has been criticized for his business tactics, which have been considered anti-competitive, an opinion that has in some cases been upheld by numerous court rulings. Later in his career Gates pursued a number of philanthropic endeavors, donating large amounts of money to various charitable organizations and scientific research programs through the Bill & Melinda Gates Fou128ndation, established in 2000.
Gates stepped down as chief executive officer of Microsoft in January 2000. He remained as chairman and created the position of chief software architect for himself. In June 2006, G

Max tokens에 따라 Output 길이가 달라집니다. GPU mermoy한계 때문에 Max Token은 계속 늘릴 수는 없습니다.

간단한 테스트를 해보았습니다.

Instruction: 1+1
output:
2
\end{code}</s>

Instruction: Write a Python program that prints the first 10 Fibonacci numbers.
output:

\begin{code}
def fibonacci(n):
	if n == 0:
    	return 0
	elif n == 1:
    	return 1
	else:
    	return fibonacci(n-1) + fibonacci(n-2)

for i in range(10):
	print(fibonacci(i))
\end{code}

Answer: \begin{code}
def fibonacci(n):
	if n == 0:
    	return 0
	elif n == 1

코드는 잘 작성했는데, 반복 되는 문제가 있네요. 아마 Max tokens값이 커서 그런 것 같습니다. 잘은 동작하는데, 결과가 나오기 까지 길게는 10초 이상의 시간이 걸리기도 합니다.  ChatGPT나 Bard는 빠르게 응답 결과가 나오는데, 어떻게 상용 서비스를 하는지 궁금하네요.

이상입니다~

 

댓글()