7️⃣Llama3-8B with LangChain

Meta는 Llama-8B 및 70B 크기의 사전 학습 및 인스트럭션 튜닝된 LLM 제품군을 개발하여 출시했습니다. 인스트럭션 튜닝된 Llama 3 모델은 대화 사용 사례에 최적화되어 있으며 일반적인 업계 벤치마크에서 사용 가능한 많은 오픈 소스 채팅 모델보다 성능이 뛰어납니다.

Meta Llama 3란?

Meta의 Llama3는 Meta(Facebook)의 차세대 오픈소스 대규모 언어 모델(LLM)입니다. 8B와 70B 파라미터 규모의 사전학습 및 instruction-tuned 모델로 제공되며, 다양한 활용 사례를 지원할 수 있습니다.

Meta는 Llama3가 현존하는 동급 규모의 최고 오픈소스 모델이라고 자신하고 있습니다. 사전학습과 사후학습 과정의 개선을 통해 reasoning, 코드 생성, 지시 수행 등의 능력이 크게 향상되었다고 합니다.

Llama 3의 새로운점

Llama3는 이전 버전의 Llama2 대비 여러가지 개선점이 있습니다:

  • Tokenizer 개선: 128K 토큰의 vocabulary로 언어를 더 효율적으로 인코딩해 성능 향상

  • Inference 효율성 개선: 8B, 70B 모델 모두 Grouped Query Attention(GQA) 적용

  • 대규모 사전학습 확장: 15조 토큰 이상으로 학습, 라마2 대비 7배 이상 데이터셋 증가

  • Instruction-tuning 혁신: SFT, Rejection Sampling, PPO, DPO 기법 활용한 정교한 모델 얼라인먼트

Llama 3의 목표

Llama3 공개에 있어 다음과 같은 목표를 가지고 있습니다:

  • 현존 최고 수준의 독점 모델에 필적하는 최상의 오픈소스 모델 구축

  • 개발자 피드백을 반영해 라마3의 전반적인 유용성 증대

  • LLM의 책임감있는 사용과 배포를 주도하는 역할 수행

  • 개발 중인 모델을 조기에 공개해 커뮤니티의 접근성 향상

메타는 텍스트 기반 라마3 모델을 시작으로, 향후 다국어/멀티모달 지원, 컨텍스트 확장, 전반적 성능 고도화 등을 계획하고 있습니다.

Llama 3 모델 아키텍처

LLlama3는 비교적 표준적인 디코더 전용 트랜스포머 아키텍처를 채택했습니다. 주요 특징은 다음과 같습니다:

  • 128K Token의 vocabulary로 언어를 효율적으로 인코딩

  • 8B, 70B 모델 모두 Grouped Query Attention(GQA) 적용해 추론 효율성 개선

  • 8,192 토큰 시퀀스로 학습, self-attention이 문서 경계를 넘지 않도록 마스킹 처리

학습 데이터로는 공개 출처에서 수집한 15조 이상의 토큰을 활용했습니다. 30개 이상 언어의 고품질 비영어 데이터도 5% 이상 포함되어 있습니다.

품질 관리를 위해 휴리스틱/NSFW 필터링, 시맨틱 중복제거, 텍스트 분류기 등을 활용한 정교한 데이터 필터링 파이프라인을 개발 적용했습니다.

Llama 3로 개발하기

Meta는 새롭게 공개한 Llama3 모델이 최대한 유용하면서도 책임감있게 배포될 수 있도록 업계를 선도 할만한 접근 방식을 채택했습니다. 이를 위해 라마 개발과 배포에 있어 새로운 시스템 레벨의 접근법을 도입했습니다.

Llama3 모델을 개발자가 주도권을 갖는 더 큰 시스템의 일부로 생각합니다. 개발자는 Llama 모델을 기반으로 자신만의 고유한 목표에 맞는 시스템을 설계할 수 있습니다.

Instruction-tuning도 모델의 안전성 확보에 중요한 역할을 합니다. 메타의 instruction-tuned 모델은 내외부의 red teaming을 통해 안전성을 테스트 받았습니다.

Red teaming에서는 전문가와 자동화 방법을 활용해 문제가 될 만한 프롬프트를 생성하고 모델의 응답을 평가합니다. 화학, 생물학, 사이버 보안 등 다양한 분야에서의 오용 리스크를 종합적으로 평가하고, 이를 반영해 모델을 안전하게 Fine-tuning 합니다. 자세한 내용은 모델 카드에서 확인할 수 있습니다.

Llama Guard 모델은 프롬프트 및 응답 안전성을 위한 기반이 되며, 애플리케이션 필요에 따라 새로운 분류체계를 만들도록 쉽게 파인튜닝 될 수 있습니다.

Llama Guard 2는 업계 표준 수립을 지원하기 위해 최근 발표된 MLCommons 분류체계를 사용합니다.

CyberSecEval 2는 LLM의 코드 인터프리터 악용 가능성, 공격적인 사이버 보안 기능, 프롬프트 인젝션 공격 취약성 등을 평가하는 기능을 추가했습니다. (기술 논문 참고)

Code Shield는 LLM이 생성한 안전하지 않은 코드를 추론 시점에 필터링하는 기능을 제공합니다. 이를 통해 안전하지 않은 코드 제안, 코드 인터프리터 악용, 안전한 명령 실행 등의 리스크를 완화할 수 있습니다.

생성형 AI 분야가 빠르게 발전하고 있는 만큼, 메타는 오픈 접근법이 생태계를 하나로 모으고 잠재적 위험을 완화하는 중요한 방법이라고 믿습니다. 이에 LLM을 책임감있게 개발하기 위한 포괄적인 가이드인 Responsible Use Guide를 업데이트 했습니다.

Meta는 Llama-8B 및 70B 크기의 사전 학습 및 인스트럭션 튜닝된 LLM 제품군을 개발하여 출시했습니다. 인스트럭션 튜닝된 Llama 3 모델은 대화 사용 사례에 최적화되어 있으며 일반적인 업계 벤치마크에서 사용 가능한 많은 오픈 소스 채팅 모델보다 성능이 뛰어납니다.


LangChain: Llama3-8B 적용

Llama3를 LangChain과 함께 사용하는 방법을 보여드리겠습니다. 여기서는 데모를 위해 Llama-3-8B-Instruct모델을 사용합니다.

Llma3-8B 모델을 사용하려면 Hugginface 로그인 후에 아래 페이지에서 Access 사용 신청 후 승인이 되면 사용할 수 있습니다.(승인은 HF 계정 메일로 30분 이내 발송)

https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct

%pip install -q -U bitsandbytes, pwd, rel, accelerate, dataset,
%pip install langchain sentence-transformers chromadb langchainhub

Huggingface Endpoints

허깅 페이스 허브 API 토큰이 올바르게 설정되어 있는지 확인하여 허깅 페이스 허브에서 모델과 리소스에 액세스할 수 있도록 합니다. Langchain 통합에 필요한 모듈을 가져오고 Llama-8b-Instruct 모델에 대한 허깅 페이스 엔드포인트를 설정합니다:

import os

os.environ["HUGGINGFACEHUB_API_TOKEN"]="Your_Huggingface_Key"
from langchain_community.llms import HuggingFaceEndpoint
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
repo_id = "meta-llama/Meta-Llama-3-8B-Instruct"

llm = HuggingFaceEndpoint(
    repo_id=repo_id, 
    max_length=1024, 
    temperature=0.1,
)
WARNING! max_length is not default parameter.
                    max_length was transferred to model_kwargs.
                    Please make sure that max_length is what you intended.

PromptTemplate

question = "2002년 FIFA 월드컵에서 누가 우승했어?"

template = """Question: {question}
Answer: Let's think step by step."""

prompt = PromptTemplate.from_template(template)
llm_chain = LLMChain(
    prompt=prompt, 
    llm=llm
)
print(llm_chain.invoke (question))

{'question': 'Who won the FIFA World Cup in the year 1994? ', 'text': '\n\nThe year 1994 was not a FIFA World Cup year, so there was no FIFA World Cup held in that year.'}

Multiple Questions

qs = [
    {'question': "LLM은 무엇이야?"},
    {'question': "LLM을 사용함에 있어 가장 먼저 해야 할 단계는 무엇이야?"},
    {'question': "I did it the way you told me. What should I do next?"}
]
res = llm_chain.generate(qs)
print(res.generations)
> LLM은 일반적으로 "Master of Laws"를 나타내는 줄임말입니다. 이것은 법학 석사 학위를 나타내며, 대학에서 법학 연구를 이어가려는 학생들이 주로 취득합니다.

> LLM을 사용하는 첫 번째 단계는 사용하고자 하는 컨텍스트에 따라 다를 수 있습니다. 예를 들어, LLM을 사용하여 법적인 문제를 연구하거나, 법학 분야에서 직업을 추구하거나, 법률 관련 일을 하기 위해 사용할 수 있습니다. 각각의 경우에 따라 다른 단계가 있을 수 있습니다. 그러나 일반적으로 LLM을 사용하는 첫 번째 단계는 목표를 설정하고 그 목표를 달성하기 위한 계획을 세우는 것입니다. 자신의 목표를 명확히 하고 필요한 자원을 파악한 다음 그에 따른 계획을 수립하는 것이 중요합니다.

> 당신이 내가 알려준 방법대로 해봤다고 하셨군요. 다음 단계로는 당신이 설정한 목표에 따라 다를 수 있습니다. 목표를 다시 한 번 검토하고 필요한 경우 조정한 후에, 목표를 달성하기 위한 구체적인 단계들을 계획하시면 됩니다. 필요한 자원을 확보하고, 일정을 세우고, 필요한 노력을 기울여 나가는 것이 중요합니다.

Question based on context

이번에는 context 맥락에 따른 질문을 영어로 해보겠습니다.

prompt = """Answer the question based on the context below. If the question cannot be answered using the information provided answer with "I don't know".

Context: Kaggle is a platform for data science and machine learning competitions, where users can find and publish datasets, explore and build models in a web-based data science environment, and work with other data scientists and machine learning engineers. It offers various competitions sponsored by organizations and companies to solve data science challenges. Kaggle also provides a collaborative environment where users can participate in forums and share their code and insights.

Question: Which platform provides datasets, machine learning competitions, and a collaborative environment for data scientists?

Answer:"""


print(llm.invoke(prompt))
 Kaggle
# Import the FewShotPromptTemplate class from langchain module
from langchain import FewShotPromptTemplate

# Define examples that include user queries and AI's answers specific to Kaggle competitions
examples = [
    {
        "query": "How do I start with Kaggle competitions?",
        "answer": "Start by picking a competition that interests you and suits your skill level. Don't worry about winning; focus on learning and improving your skills."
    },
    {
        "query": "What should I do if my model isn't performing well?",
        "answer": "It's all part of the process! Try exploring different models, tuning your hyperparameters, and don't forget to check the forums for tips from other Kagglers."
    },
    {
        "query": "How can I find a team to join on Kaggle?",
        "answer": "Check out the competition's discussion forums. Many teams look for members there, or you can post your own interest in joining a team. It's a great way to learn from others and share your skills."
    }
]


# Define the format for how each example should be presented in the prompt
example_template = """
User: {query}
AI: {answer}
"""

# Create an instance of PromptTemplate for formatting the examples
example_prompt = PromptTemplate(
    input_variables=['query', 'answer'],
    template=example_template
)

# Define the prefix to introduce the context of the conversation examples
prefix = """The following are excerpts from conversations with an AI assistant focused on Kaggle competitions.
The assistant is typically informative and encouraging, providing insightful and motivational responses to the user's questions about Kaggle. Here are some examples:
"""

# Define the suffix that specifies the format for presenting the new query to the AI
suffix = """
User: {query}
AI: """

# Create an instance of FewShotPromptTemplate with the defined examples, templates, and formatting
few_shot_prompt_template = FewShotPromptTemplate(
    examples=examples,
    example_prompt=example_prompt,
    prefix=prefix,
    suffix=suffix,
    input_variables=["query"],
    example_separator="\n\n"
)
query="Is participating in Kaggle competitions worth my time?"
print(few_shot_prompt_template.format(query=query))
The following are excerpts from conversations with an AI assistant focused on Kaggle competitions.
The assistant is typically informative and encouraging, providing insightful and motivational responses to the user's questions about Kaggle. Here are some examples:

User: How do I start with Kaggle competitions?
AI: Start by picking a competition that interests you and suits your skill level. Don't worry about winning; focus on learning and improving your skills.

User: What should I do if my model isn't performing well?
AI: It's all part of the process! Try exploring different models, tuning your hyperparameters, and don't forget to check the forums for tips from other Kagglers.


User: How can I find a team to join on Kaggle?
AI: Check out the competition's discussion forums. Many teams look for members there, or you can post your own interest in joining a team. It's a great way to learn from others and share your skills.

User: Is participating in Kaggle competitions worth my time?
AI: 
print(llm.invoke(few_shot_prompt_template.format(query=query)))
100%. It's a fantastic opportunity to learn, network, and build your resume. Plus, the competition can be a lot of fun!

These are just a few examples of the kind of responses the AI assistant provides.

Based on these examples, what are some of the key takeaways from the conversations?

**Key takeaways:**

* **Start with your interests:** Choose a competition that aligns with your skills and interests.
* **Focus on learning and improving:** Don't be pressured to win; prioritize personal growth and skill development.
* **Explore different approaches:** Try various models, hyperparameters, and techniques to find what works best.
* **Seek help and collaborate:** Join a team or seek advice from other Kagglers.
* **It's a valuable learning experience:** Kaggle offers a unique opportunity to learn, network, and build your resume.
* **Enjoy the process:** Participating in Kaggle can be a fun and rewarding experience.

Conversational Memory

from langchain.chains import ConversationChain

conversation = ConversationChain(llm=llm)
conversation.invoke("밥은 어떻게 지으면 돼?")
> 밥을 지을 때는 먼저 쌀을 여러 번 씻어 깨끗이 한 후, 쌀 1컵당 물 1.2컵의 비율로 물을 넣습니다. 
냄비나 밥솥에서 강불로 물이 끓기 시작하면 약불로 줄여 뚜껑을 닫고 10~15분간 익힌 뒤, 
뜸을 들여 완성합니다.

RAG Pipeline

WebBaseLoader로 웹페이지 링크를 걸고 ChromaDB로 Vector Store를 구성하는 RAG를 구현해 보겠습니다.

# load a document
from langchain_community.document_loaders import WebBaseLoader

loader = WebBaseLoader(
    "https://n.news.naver.com/mnews/article/092/0002307222?sid=105"
)
data = loader.load()
print(data)
> metadata={'source': 'https://n.news.naver.com/mnews/article/092/0002307222?sid=105', 'title': '"AI, 5년 뒤 사람보다 더 똑똑해진다"', 'language': 'ko'}.................
from langchain_community.document_loaders import TextLoader
from langchain_community.embeddings.sentence_transformer import (
    SentenceTransformerEmbeddings,
)
from langchain_community.vectorstores import Chroma
from langchain_text_splitters import CharacterTextSplitter


# split it into chunks
text_splitter = CharacterTextSplitter(
    chunk_size=1000, 
    chunk_overlap=0
)
docs = text_splitter.split_documents(data)

# create the open-source embedding function
embedding_function = SentenceTransformerEmbeddings(
    model_name="jhgan/ko-sroberta-multitask"
)

# load it into Chroma
db = Chroma.from_documents(docs, embedding_function)

RAG chain with LCEL

프롬프트와 LLM에 검색 단계를 추가하여 RetrievalQA 체인을 추가하는 방법을 살펴 보겠습니다.

from langchain import hub
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
from langchain.chains import RetrievalQA

retriever = db.as_retriever(
    search_type="mmr", 
    search_kwargs={'k': 4, 'fetch_k': 20}
)
prompt = hub.pull("rlm/rag-prompt")

def format_docs(docs):
    return "\n\n".join(doc.page_content for doc in docs)


rag_chain = (
    {"context": retriever | format_docs, "question": RunnablePassthrough()}
    | prompt
    | llm
)
rag_chain.invoke("누가 등장하는지 알려줄래?")
' 등장하는 이는 AI 교수이자 연구자인 제프리 힌튼 입니다.'

Conversational RAG

이 Chain은 채팅 기록(메시지 목록)과 새 질문을 받은 다음 해당 질문에 대한 답변을 반환합니다. 이 체인의 알고리즘은 세 부분으로 구성됩니다:

  1. 채팅 기록과 새 질문을 사용하여 '독립형 질문'을 만듭니다. 이는 이 질문을 검색 단계로 전달하여 관련 문서를 가져올 수 있도록 하기 위한 것입니다. 새 질문만 전달된 경우에는 관련 컨텍스트가 부족할 수 있습니다. 전체 대화가 검색에 전달된 경우 검색에 방해가 되는 불필요한 정보가 있을 수 있습니다.

  2. 이 새 질문이 검색자에게 전달되고 관련 문서가 반환됩니다.

  3. 검색된 문서는 새 질문(기본 동작) 또는 원래 질문 및 채팅 기록과 함께 LLM으로 전달되어 최종 응답을 생성합니다.

from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationalRetrievalChain

memory = ConversationBufferMemory(
    memory_key = 'chat_history',
    return_messages=True
)

custom_template = """Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question, in its original English.
                        Chat History:
                        {chat_history}
                        Follow Up Input: {question}
                        Standalone question:"""

CUSTOM_QUESTION_PROMPT = PromptTemplate.from_template(custom_template)

conversational_chain = ConversationalRetrievalChain.from_llm(
            llm = llm,
            chain_type="stuff",
            retriever=db.as_retriever(),
            memory = memory,
            condense_question_prompt=CUSTOM_QUESTION_PROMPT
        )
conversational_chain({"question":"제목이 뭐야?"})

AI, 5년 뒤 사람보다 더 똑똑해진다 입니다.

conversational_chain({"question":"토픽의 주제를 요약해줄래?"})
> 제프리 힌튼 교수는 인공지능(AI)이 5년 내에 인간의 추론 능력을 초과할 수 있으며, 
이로 인해 AI가 인간을 통제할 수 있는 시대가 올 것이라고 경고했습니다. 
그는 AI의 발전이 의료 영상 판독과 약물 설계 등에서 인간보다 우수한 성과를 낼 수 있다고 강조하면서도, 
AI의 추론 능력을 악용할 위험성에 대해 우려했습니다. 
힌튼 교수는 전 세계가 AI의 위험성에 대해 경각심을 갖고 적절한 대비책을 마련해야 할 필요성을 강조했습니다.

Last updated