본문 바로가기

NLP/LangChain

구름IDE에서 Alpaca 사용(LangChain에서 OpenAI Credit 소진시 대체)

0. 참고자료

 1) conda 가상 환경에서 아래의 작업을 하였음.(Miniconda 사용)

 2) 구름ide GPU 환경(40G) 중 60%~70% 정도의 공간을 사용함. 

 3). https://youtu.be/v6sF8Ed3nTE

 - colab: https://colab.research.google.com/drive/115ba3EFCT0PvyXzFNv9E18QnKiyyjsm5?usp=sharing

 - model 불러오는 부분을 다른 것으로 변경해야 함.(커널 다운 됨)

#모델을 'chainyo/alpaca-lora-7b'로 변경

tokenizer = LlamaTokenizer.from_pretrained("chavinlo/alpaca-native") #모델 변경가능

base_model = LlamaForCausalLM.from_pretrained(
    "chavinlo/alpaca-native", #모델 변경가능
    load_in_8bit=True,
    device_map='auto',
)
 

YT LangChain Chatbot - Running Alpaca in Colab.ipynb

Colaboratory notebook

colab.research.google.com

 4). https://github.com/TimDettmers/bitsandbytes/issues/95

 

CUDA setup · Issue #95 · TimDettmers/bitsandbytes

I got this error when tried to run dreambooth: >>> import torch >>> torch.cuda.is_available() True >>> print(torch.cuda.current_device()) 0 >>> print(torch._C._cuda_getCompiledVersion(), 'cuda comp...

github.com

 

1. MiniConda 설치

 1) 다운로드

wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh

 2) 설치

bash Miniconda3-latest-Linux-x86_64.sh

 - 설치중에 아래와 같이 나오면 yes 입력

Do you wish the installer to initialize Miniconda3 by running conda init? [yes|no] yes

 3) 재시작

source ~/.bashrc

 4) 가상환경 만들기

 - python3.8 이상의 버전으로 설치를해야 langchain이 작동함.

conda create --name langchain python=3.10

 5) 가상환경 실행

conda activate langchain

 

1. 구름IDE(GPU)에서 LLama 설치 및 실행

 0) 참고자료 3)의 Colab과 같이 설치 및 실행하면 아래와 같은 Error 발생

 - bitsandbytes가 libcudart.so를 찾지 못해서 일어나는 현상이라고 함.

 - 2부터 실행하면 해결 됨.

Inspect the output of the command and see if you can locate CUDA libraries. 
You might need to add them to your LD_LIBRARY_PATH. 
If you suspect a bug, please take the information from python -m bitsandbytes and open an issue at: https://github.com/TimDettmers/bitsandbytes/issues

 1) 라이브러리 설치

pip install -q transformers
pip install -q datasets loralib sentencepiece  
pip -q install bitsandbytes accelerate
pip -q install langchain

 2) cudatoolkit 설치

conda install -y cudatoolkit

 3) 구름ide에서  Jupyter notebook아래의 라이브러리 Import

from transformers import LlamaTokenizer, LlamaForCausalLM, GenerationConfig, pipeline
from langchain.llms import HuggingFacePipeline
from langchain import PromptTemplate, LLMChain

import torch

 - 아래와 같은 error 발생시에는

Running cells with 'langchain' requires ipykernel package.
Run the following command to install 'ipykernel' into the Python environment. 
Command: 'conda install -n langchain ipykernel --update-deps --force-reinstall'

 - command에 나와있는 코드를 그대로 실행

conda install -n langchain ipykernel --update-deps --force-reinstall

 4) libcudart.so위치를 찾고 지정

find / -name libcudart.so

<출력>
/root/miniconda3/pkgs/cudatoolkit-11.8.0-h6a678d5_0/lib/libcudart.so
/root/miniconda3/envs/langchain/lib/libcudart.so <선택>
/usr/local/cuda-11.4/targets/x86_64-linux/lib/libcudart.so

  - <선택>을 아래의 코드에 입력

import os
os.environ['LD_LIBRARY_PATH'] = "/root/miniconda3/envs/langchain/lib/libcudart.so"

5) Alpaca 모델 및 토크나이저 불러오기(최초 실행시 4~5분가량 소요됨.)

tokenizer = LlamaTokenizer.from_pretrained("chainyo/alpaca-lora-7b")

base_model = LlamaForCausalLM.from_pretrained(
    "chainyo/alpaca-lora-7b",
    load_in_8bit=True,
    device_map='auto',
)

6) 모델 실행

pipe = pipeline(
    "text-generation",
    model=base_model, 
    tokenizer=tokenizer, 
    max_length=256,
    temperature=0.6,
    top_p=0.95,
    repetition_penalty=1.2
)

local_llm = HuggingFacePipeline(pipeline=pipe)

from langchain import PromptTemplate, LLMChain

template = """Below is an instruction that describes a task. Write a response that appropriately completes the request.

### Instruction: 
{instruction}

Answer:"""

prompt = PromptTemplate(template=template, input_variables=["instruction"])

llm_chain = LLMChain(prompt=prompt, 
                     llm=local_llm
                     )

question = "What is the capital of England?"

print(llm_chain.run(question))

<출력>
The capital city of England is London, located in southeastern England on the River Thames.

 

2. 기타 참고 사항

 1) LangChain 학습용 OpenAI의 무료 크레딧의 사용량 소진 또는 사용기간 소진(유료전환)에 대한 대책

 2) hugging face 모델 저장 위치 및 삭제 

 - 용량 문제로 다른 모델을 받을시 삭제해주어야 함.

~/.cache/huggingface/hub/

ls

models--chavinlo--alpaca-native  version.txt

<삭제>
rm -r 모델경로

3) "chainyo/alpaca-lora-7b" 한글은 잘 안됨.

llm_chain = LLMChain(prompt=prompt, 
                     llm=local_llm
                     )

question = "한국의 수도는 어디야?"

print(llm_chain.run(question))

<출력>
South Korea's provinces are divided into eight regions, including Gyeonggi-do (Seoul), Gangwon-do (Chuncheon and Gangneung), North Chungcheong Province (Siheung), South Chungcheong Province (Daejeon), Jeollabuk-do (Jeju City), Jeonnam-do (Gwangyang), Ulsan Metropolitan City, and Busan Metropolitan City.

'NLP > LangChain' 카테고리의 다른 글

LangChain 기본 사용법(LLMs 기준)  (0) 2023.06.28