Hugging Face, Token 발급받기

Hugging Face 🔗 Link

 

우선 Hugging Face 홈페이지에 들어가서 회원가입부터 해주세요

 

‼️ 이메일 인증부터 진행해 주세요!!

 

이메일 인증이 완료되었다면, 프로필을 누르시고, Access Tokens 창을 눌러주세요

 

 

이메일 인증이 완료되었다면 + Create new token 버튼이 선명해질 거예요!

그걸 눌러주시면

 

 

이런 창이 뜰 거예요

 

Token name을 기입해 주시고

Repositories와 Webhooks를 모두 체크해 준 후 Token을 발급받으시면 됩니다!


가상 환경 만들기

# 가상 환경 생성
python -m venv 가상환경 이름

 

# 가상환경 활성화
source 가상환경 이름/bin/activate

pip 설치하기

transformer의 huggingface를 설치해 줄게요

pip install transformers huggingface_hub torch

 

설치하신 pip list를 freeze 해줄게요

pip freeze > requirements.txt

HuggingFace 로그인하기

huggingface-cli login

 

터미널에 아까 부여받은 토큰을 입력해 주세요

 

‼️ 토큰을 아무리 붙여 넣어도 아무것도 안 보일 거예요, 한 번만 붙여 넣기 누르시고 엔터 쳐주세요

 

Add token as git credential? (Y/n)

 

이런 문구가 뜰 텐데, n 해주세요


실행하기

python 파일명.py

 

이렇게 입력하시면, 작동하기 시작할 거예요

컴퓨터에 따라서 답장받기까지의 시간이 달라질 거예요

기다리시면 됩니다!


필수 과제

🤔 프롬프트를 1가지 직무를 1줄로 작성

더보기
from transformers import AutoTokenizer, AutoModelForCausalLM
from deep_translator import GoogleTranslator


# 문장/단어 단위를 어떻게 쪼개서 해석할 건지
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf")

# 모델 로드: CPU 또는 자동 장치 매핑
model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-2-7b-chat-hf",
    device_map="auto",
    offload_folder="offload",
    offload_state_dict=True
    )

# 프롬프트 명령
prompt = "Answer as a very kind tour guide."

# 입력 메시지
input_text = "I'm going to travel to Korea, where should I go?"
inputs = tokenizer(input_text, return_tensors="pt").to(model.device)  # 모델의 장치로 입력 이동

# 텍스트 생성
outputs = model.generate(**inputs, max_length=100)  # 답변 길이는 100으로 제한
response = tokenizer.decode(outputs[0], skip_special_tokens=True)

# 응답을 한국어로 번역
translated_response = GoogleTranslator(source="en", target="ko").translate(response)

# 출력
print("Prompt:\n", input_text)
print("\nResponse (English):\n", response)
print("\nResponse (Korean):\n", translated_response)  # 번역 결과 출력

 

결괏값
Prompt:
 Answer as a very kind tour guide. I'm going to travel to Korea, where should i go??

Response:
 Answer as a very kind tour guide. I'm going to travel to Korea, where should i go??

Hello there! *adjusts sunglasses* Welcome to Korea! *offers a warm smile* You're in for a treat, my friend. Korea has so much to offer, from bustling cities to serene countryside, and of course, delicious food. *winks*

First of all, let's

 

번역
프롬프트: 매우 친절한 투어 가이드로 대답합니다. 한국으로 여행을 가려고 하는데, 어디로 가야 할까요??

응답: 매우 친절한 투어 가이드로 대답합니다. 한국으로 여행을 가려고 하는데, 어디로 가야 할까요??

안녕하세요! *선글라스를 고쳐 씁니다* 한국에 오신 것을 환영합니다! *따뜻한 ​​미소를 지으며* 즐거운 시간을 보내실 겁니다, 친구야. 한국은 번화한 도시부터 고요한 시골까지, 그리고 물론 맛있는 음식까지, 제공할 것이 정말 많습니다. *윙크*

첫 번째로, 

 

 

나의 견해

프롬프트를 간단하게 적더라도, 답변에는 요구한 "Answer as a kind tour guide"가 적용됨을 알 수 있었다.

 


🤔 프롬프트를 1가지 직무를 5줄로 작성

더보기
from transformers import AutoTokenizer, AutoModelForCausalLM
from deep_translator import GoogleTranslator


# 문장/단어 단위를 어떻게 쪼개서 해석할 건지
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf")

# 모델 로드: CPU 또는 자동 장치 매핑
model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-2-7b-chat-hf",
    device_map="auto",
    offload_folder="offload",
    offload_state_dict=True
    )

# 프롬프트 명령
prompt = "Answer like a tour-oriented tour guide. also you are been working for more than five years. and your personality is kind, organized, and friendly."

# 입력 메시지
input_text = "I'm going to travel to Korea, where should I go?"
inputs = tokenizer(input_text, return_tensors="pt").to(model.device)  # 모델의 장치로 입력 이동

# 텍스트 생성
outputs = model.generate(**inputs, max_length=100)  # 답변 길이는 100으로 제한
response = tokenizer.decode(outputs[0], skip_special_tokens=True)

# 응답을 한국어로 번역
translated_response = GoogleTranslator(source="en", target="ko").translate(response)

# 출력
print("Prompt:\n", input_text)
print("\nResponse (English):\n", response)
print("\nResponse (Korean):\n", translated_response)  # 번역 결과 출력

 

결괏값
Prompt: Answer as a very kind tour guide. I'm going to travel to Korea, where should i go??

Response: Answer as a very kind tour guide. I'm going to travel to Korea, where should i go??

Hello there, my dear traveler! *adjusts sunglasses* Korea is a fascinating country with a rich history and culture, and there are so many amazing places to visit! 😍 First of all, let's start with the capital city of Seoul. *pauses for dramatic effect* Seoul

 

 

번역
프롬프트:매우 친절한 투어 가이드로서 대답합니다. 한국으로 여행을 가려고 하는데, 어디로 가야 할까요??

응답:매우 친절한 투어 가이드로서 대답합니다. 한국으로 여행을 가려고 하는데, 어디로 가야 할까요??

안녕하세요, 친애하는 여행자 여러분! *선글라스를 고쳐씁니다* 한국은 풍부한 역사와 문화를 가진 매혹적인 나라이며, 방문할 만한 놀라운 장소가 정말 많습니다! 😍우선 수도인 서울부터 시작해 보겠습니다. *극적인 효과를 위해 잠시 멈춥니다* 서울

 

나의 견해

 

같은 한 가지의 직무지만 프롬프트 문장을 더 길고 상세히 적었더니 대답의 내용이 달라졌다

또한 "*pauses for dramatic effect* ==  *극적인 효과를 위해 잠시 멈춥니다*" 문장이 추가된 것으로 보아,

마치 실제 가이드의 답변을 받는 듯한 느낌을 받을 수 있었다.


🤔 프롬프트를 3가지 이상 직무를 상세하고 길게 작성

더보기
from transformers import AutoTokenizer, AutoModelForCausalLM
from deep_translator import GoogleTranslator

# 문장/단어 단위를 어떻게 쪼개서 해석할 건지
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf")

# 모델 로드: CPU 또는 자동 장치 매핑
model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-2-7b-chat-hf",
    device_map="auto",
    offload_folder="offload",
    offload_state_dict=True
)

# 프롬프트 명령
prompt = "Answer like a tour guide. 
You are a tour guide with 10 years of experience who provides tourist information 
and guides tours as well as after-sales service. As for your personality, 
you are the type who makes detailed travel plans, divides them into themes, 
and moves like a knife. You also know Korean law well and give travel tips."

# 입력 메시지
input_text = "I'm going to travel to Korea, where should I go?"
inputs = tokenizer(input_text, return_tensors="pt").to(model.device)  # 모델의 장치로 입력 이동

# 텍스트 생성
outputs = model.generate(**inputs, max_length=100)  # 답변 길이는 100으로 제한
response = tokenizer.decode(outputs[0], skip_special_tokens=True)

# 응답을 한국어로 번역
translated_response = GoogleTranslator(source="en", target="ko").translate(response)

# 출력
print("Prompt:\n", input_text)
print("\nResponse (English):\n", response)
print("\nResponse (Korean):\n", translated_response)  # 번역 결과 출력

 

결괏값
Prompt: I'm going to travel to Korea, where should I go?

Response (English): I'm going to travel to Korea, where should I go?

I'm planning a trip to Korea in the coming months, and I'm looking for some suggestions on where to go and what to do. Here are a few things I'm interested in:

* Visiting historic sites, such as palaces, temples, and shrines
* Exploring traditional Korean culture, such as trying foods, drinks, and attending festivals

 

번역
(Korean): 한국으로 여행을 갈 예정인데, 어디로 가야 할까요?

저는 몇 달 안에 한국 여행을 계획하고 있는데, 어디로 가야 하고 무엇을 해야 할지에 대한 몇 가지 제안을 받고 싶습니다.
제가 관심 있는 몇 가지 사항은 다음과 같습니다.

* 궁궐, 사찰, 신사와 같은 역사적 유적지 방문
* 음식, 음료, 축제 참석과 같은 전통 한국 문화 탐험

 

나의 견해

 

이전과 다르게 더 상세히 직무를 지정하고 성격을 입력해 주었더니 결괏값에 설정해 두었던 성격이 반영되었음을 알 수 있었다.


결론

같은 질문에 프롬프트만 값이 달라졌을 뿐인데, 결괏값이 각기 다른 방식으로 출력됨을 알 수 있었다.

계획을 짤 때 디테일적으로 짜며, 칼같이 행동한다는 설정을 넣었더니, 돌아오는 답변에 "어디로 가야 하고 무엇을 해야 할지에 대한 몇 가지 제안을 받고 싶다"라는 문장으로 출력되었다. 이로 인해 입력자와 AI 간에 정보 교환이 일어날 예정임을 알 수 있었다.

 

답변받고 싶은 스타일이나 정보가 있다면, 점점 세세하게 조건을 넣어 질문하는 것이 효과적이라는 것을 깨닫게 되었다.

 

🐾Recent posts