Iriton's log

1. AI 언어 모델 Llama 3 실습 - Hugging Face & Ollama 기본 설정 본문

AI/Practice

1. AI 언어 모델 Llama 3 실습 - Hugging Face & Ollama 기본 설정

Iriton 2024. 10. 16. 19:07

Llama3 모델을 선정하여 테스트 해 보았다.

 

Ollama CLI 또는 Hugging Face를 통해 Llama 모델을 사용할 수 있다.

 

 

1-1. 허깅페이스 + Llama3 써보기

개요

Introduction - Hugging Face NLP Course

 

Introduction - Hugging Face NLP Course

2. Using 🤗 Transformers 3. Fine-tuning a pretrained model 4. Sharing models and tokenizers 5. The 🤗 Datasets library 6. The 🤗 Tokenizers library 9. Building and sharing demos new

huggingface.co

 

  • 다양한 인공지능 모델들을 오픈 소스로 제공하는 곳
  • AI 분야의 깃허브로 불리고, 오픈소스 AI모델과 학습용 데이터셋을 제공
  • Hugging Chat을 통해 OpenAI의 ChatGPT와 유사한 기능을 가진 맞춤형 AI 챗봇을 쉽게 만들 수 있다.
  • 트랜스포머 라이브러리 제공하고 사전학습된 트랜스포머 모델을 로드할 수 있다.
  • 데이터셋을 쉽게 로드할 수 있으며 파인튜닝은 Pytorch 사용해서 가능하다고 한다.
  • Git과 연동해서 작업 백업 및 협업도 가능
  • Getting Started with Repositories
 

Getting Started with Repositories

This beginner-friendly guide will help you get the basic skills you need to create and manage your repository on the Hub. Each section builds on the previous one, so feel free to choose where to start! This document shows how to handle repositories through

huggingface.co

 

설정

pip install huggingface_hub

허깅 페이스 가입 후 cmd 창을 열어서 다운로드

이메일 인증 후

 

https://huggingface.co/settings/tokens

 

Hugging Face – The AI community building the future.

 

huggingface.co

에서 User Access Tokens을 Create new token 버튼을 눌러서 발급 받는다.

 

huggingface-cli login

 

우클릭으로 토큰을 붙여넣는다. (정상적으로 붙여 넣기가 되어도 토큰이 보이지 않기 때문에 우클릭 한 번만 하고 그냥 엔터 누르면 된다.)

 

모델 끌어다 챗봇 어시스턴스를 간단히 만들어 보고자 한다.

HuggingChat - Assistants

 

HuggingChat - Assistants

Browse HuggingChat assistants made by the community.

huggingface.co

허깅 챗 어시스턴트로 이동

 

Create new assistant를 누르면

 

위와 같이 뜬다. (Llama 3.1 70B 모델로)

 

정보를 입력해 준 뒤 Create 버튼을 누르면 URL이 뜬다.

 

이후에 뜨는 Get Starting 버튼으로 챗봇과의 대화가 시작된다.

 

채팅 어시스턴스는 프롬프트 엔지니어링을 해서 이 모델이 어떻게 작동하는지 파악하기 쉬운 거고… 서비스에 적용하려면 NLP 작업과 파인 튜닝이 필수다.

그러려면 모델을 다운 받아서 실습해 봐야 하는데

 

meta-llama/Llama-3.1-70B · Hugging Face

 

meta-llama/Llama-3.1-70B · Hugging Face

The information you provide will be collected, stored, processed and shared in accordance with the Meta Privacy Policy. LLAMA 3.1 COMMUNITY LICENSE AGREEMENT Llama 3.1 Version Release Date: July 23, 2024 "Agreement" means the terms and conditions for use,

huggingface.co

 

들어가서 라이선스 받으려니까

 

승인이 되어야지만 사용해볼 수 있다.. 하루이틀 걸린다고 함.

나중에… 하자

 

1-2. Ollama + Llama3

로컬에서도 테스트를 해 보자.

설정

Ollama

 

Ollama

Get up and running with large language models.

ollama.com

OS에 맞게 다운로드 하면

 

cmd 창에서 명령어 사용 가능

 

library

 

library

Get up and running with large language models.

ollama.com

 

라이브러리에서 모델 선정

 

3.2가 현재 기준 가장 최신 버전인데… 그냥 안정화된 게 3.1 아닐까 싶어서(뇌피셜) 참고한 블로그 따라서 3.1 다운로드 하려고 함. 네모박스 명령어 복사해서 cmd에 붙여 넣으면 됨.

일단 테스트를 위한 거니까 8B로 선정함.

(70, 405는 그만큼 모델 사이즈가 커서 똑똑하겠지만 그만큼 리소스가 많이 필요로 함.)

 

 

CLI 환경에서 대화가 가능하다.

Flask 환경에서 써보기

import subprocess
from flask import Flask, request, jsonify

app = Flask(__name__)

# Ollama CLI를 호출하여 Llama 3.1 모델과 상호작용하는 함수
def ollama_generate(prompt):
    result = subprocess.run(
        ["ollama", "run", "llama3.1:8b"], 
        input=prompt, 
        capture_output=True, 
        text=True
    )
    
    # 표준 출력 및 표준 에러 출력
    print("STDOUT:", result.stdout)
    print("STDERR:", result.stderr)
    
    if result.stdout:
        return result.stdout.strip()
    else:
        return "Error occurred: " + result.stderr

@app.route("/generate", methods=["POST"])
def generate():
    user_input = request.json.get("input_text")
    response = ollama_generate(user_input)
    return jsonify({"response": response})

if __name__ == "__main__":
    app.run(debug=True)

 

포스트맨에서 테스트 해 보았는데 CLI에선 되던 한국어 대화를 여기선 하지 못한다.

뭔가 인코딩 디코딩 과정에서 문제가 있는 것 같다.

 

이건 지금 중요한 게 아니니… 얘도 넘어가고 아무튼 flask 환경에서도 테스트 완료.

 

뭐… 프롬프트 엔지니어링을 해서 서비스에 맞는 챗봇으로 만들어서 대화 흐름을 이끌어내면 된다.

 

그 다음은? 권한이 떨어진 후 추가 학습 및 파인튜닝을 하기

Comments