본문 바로가기
데이터&AI/langchain

Qwen2 + langchain. On-premise모델을 langchain으로 사용하기!

by 일등박사 2024. 6. 27.
728x90

 

2024.06.23 - [데이터&AI/LLM] - qwen2 모델 톺아보기 (feat. llama3 모델과의 비교!)

 

qwen2 모델 톺아보기 (feat. llama3 모델과의 비교!)

2024.06.23 - [데이터&AI/LLM] - 알리바바의 llm 모델 qwen2 사용해보기 (feat.놀라운 한국어실력) 알리바바의 llm 모델 qwen2 사용해보기 (feat.놀라운 한국어실력)여러가지 오픈소스 모델들을 알아보고있었

drfirst.tistory.com

 

지난 포스팅에서 Qwen2의 모델을 살펴보고, huggingface에서 모델을 다운받아 로드해보고,

llama모델과 비교해보았었는데요!!

오늘은 이 qwen2 모델을 AutoModelForCausalLM 기반으로, 또 langchain 기반으로 실행해 보겠습니다~~

 

qwen2 모델과 AutoModelForCausalLM


. qwen2모델을 huggingface로 부터 받아  AutoModelForCausalLM  기반으로 실행해 보겠습니다!

(사전에 transformers와 cuda, pytorch 등은 세팅이 되어있어야합니다~!)

from transformers import AutoModelForCausalLM, AutoTokenizer
device = "cuda" # the device to load the model onto

model = AutoModelForCausalLM.from_pretrained(
    "Qwen/Qwen2-1.5B-Instruct-GPTQ-Int8",
    torch_dtype="auto",
    device_map="auto"
)

tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-1.5B-Instruct-GPTQ-Int8")

 

이제 프롬포트를 입력하고 모델을 실행하면 끝!!

prompt = "고려 공민왕의 업적에 대하여 소개해줘"
messages = [
    {"role": "system", "content": "You are a helpful assistant.한국어로 답변해!!"},
    {"role": "user", "content": prompt}
]
text = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True
)
model_inputs = tokenizer([text], return_tensors="pt").to(device)

generated_ids = model.generate(
    model_inputs.input_ids,
    max_new_tokens=1028
)
generated_ids = [
    output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
]

response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]

print(response)

 

일본어가 조금 섞여있네요,, 지금까지 라는뜻일듯합니다

 

 

qwen2 모델과 Langchain (HuggingFacePipeline) 


이번에는, HuggingFacePipeline를 활용 langchain 의 객채로서 활용할 수 있도록 해보겠습니다!!

from langchain.llms import HuggingFacePipeline
from transformers import pipeline
from langchain import PromptTemplate, LLMChain
from transformers import AutoModelForCausalLM, AutoTokenizer
###
tokenizer =AutoTokenizer.from_pretrained("Qwen/Qwen2-1.5B-Instruct-GPTQ-Int8")
model = AutoModelForCausalLM.from_pretrained(
    "Qwen/Qwen2-1.5B-Instruct-GPTQ-Int8",
    torch_dtype="auto",
    device_map="auto"
)
pipe = pipeline(
    "text-generation",
    model=model, 
    tokenizer=tokenizer,
    max_new_tokens=1028,  
)
llm_qwen = HuggingFacePipeline(pipeline=pipe)

 

이제 llm_qwen 에 객채로 인식되었고~~

invoke 및 question 두가지 방식으로 실행시켜보겠습니다~!

 

1. invoke

res = llm_qwen.invoke("발레리나의 꿈이라는 주제로  소설 제목 및  플롯 짜줘")
print(res)

 

2. question.

template = """너는 친절하고 도움이 되는 AI 어시스턴트야. 다음 질문에 답해줘.

질문: {question}

답변:"""
prompt = PromptTemplate(template=template, input_variables=["question"])
llm_chain = LLMChain(prompt=prompt, llm=llm_qwen)

question = "비오는날 읽고싶은 소설 줄거리 써줄래?"
response = llm_chain.run(question)
print(response)

 

 

사용하면 사용할수록~ 오픈소스 모델들의 성능에 놀라게됩니다!

더 많은 GPU로 신나게 돌려보고싶네요~!^^

728x90

댓글