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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
path_work = "."
|
| 2 |
+
|
| 3 |
+
# hf_token
|
| 4 |
+
from dotenv import load_dotenv
|
| 5 |
+
load_dotenv()
|
| 6 |
+
import os
|
| 7 |
+
hf_token = os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
# [์ ํ1] ๊ฑฐ๋๋ชจ๋ธ ๋ญ์ฒด์ธ Custom LLM (HF InferenceClient) - 70B๊ฐ ๋ฌด๋ฃ!!!, openai๋ณด๋ค ์ฑ๋ฅ ์๋จ์ด์ง (์คํธ๋ฆฌ๋ฐ์ ์์ง ์๋จ)
|
| 11 |
+
# model_name = "tiiuae/falcon-180B-chat"
|
| 12 |
+
model_name="meta-llama/Llama-2-70b-chat-hf"
|
| 13 |
+
# model_name="NousResearch/Llama-2-70b-chat-hf"
|
| 14 |
+
# model_name="meta-llama/Llama-2-13b-chat-hf"
|
| 15 |
+
# model_name="meta-llama/Llama-2-7b-chat-hf"
|
| 16 |
+
# model_name = "HuggingFaceH4/zephyr-7b-alpha"
|
| 17 |
+
|
| 18 |
+
kwargs = {"max_new_tokens":256, "temperature":0.9, "top_p":0.6, "repetition_penalty":1.3, "do_sample":True}
|
| 19 |
+
|
| 20 |
+
# ์ปค์คํ
LLM
|
| 21 |
+
from pydantic import BaseModel, Field
|
| 22 |
+
from typing import Any, Optional, Dict, List
|
| 23 |
+
from huggingface_hub import InferenceClient
|
| 24 |
+
from langchain.llms.base import LLM
|
| 25 |
+
|
| 26 |
+
class KwArgsModel(BaseModel):
|
| 27 |
+
kwargs: Dict[str, Any] = Field(default_factory=dict)
|
| 28 |
+
|
| 29 |
+
class CustomInferenceClient(LLM, KwArgsModel):
|
| 30 |
+
model_name: str
|
| 31 |
+
inference_client: InferenceClient
|
| 32 |
+
|
| 33 |
+
def __init__(self, model_name: str, hf_token: str, kwargs: Optional[Dict[str, Any]] = None):
|
| 34 |
+
inference_client = InferenceClient(model=model_name, token=hf_token)
|
| 35 |
+
super().__init__(
|
| 36 |
+
model_name=model_name,
|
| 37 |
+
hf_token=hf_token,
|
| 38 |
+
kwargs=kwargs,
|
| 39 |
+
inference_client=inference_client # inference_client ์ธ์ ์ถ๊ฐ
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
def _call(
|
| 43 |
+
self,
|
| 44 |
+
prompt: str,
|
| 45 |
+
stop: Optional[List[str]] = None
|
| 46 |
+
) -> str:
|
| 47 |
+
if stop is not None:
|
| 48 |
+
raise ValueError("stop kwargs are not permitted.")
|
| 49 |
+
# pdb.set_trace()
|
| 50 |
+
# response_gen = self.__dict__['client'].text_generation(prompt, stream=True, **self.kwargs) # ์ ์ฅ๋ kwargs๋ฅผ ์ฌ์ฉ,
|
| 51 |
+
response_gen = self.inference_client.text_generation(prompt, **self.kwargs, stream=True)
|
| 52 |
+
response = ''.join(response_gen) # ์ ๋๋ ์ดํฐ์ ๋ชจ๋ ๊ฐ์ ๋ฌธ์์ด๋ก ์ฐ๊ฒฐ
|
| 53 |
+
return response
|
| 54 |
+
|
| 55 |
+
@property
|
| 56 |
+
def _llm_type(self) -> str:
|
| 57 |
+
return "custom"
|
| 58 |
+
|
| 59 |
+
@property
|
| 60 |
+
def _identifying_params(self) -> dict:
|
| 61 |
+
return {"model_name": self.model_name}
|
| 62 |
+
|
| 63 |
+
# ์ฌ์ฉ ์์ :
|
| 64 |
+
# prompt="How do you make cheese?"
|
| 65 |
+
# prompt = "Tell me the names of the last 10 U.S. presidents"
|
| 66 |
+
prompt="Tell me 10 of the world's largest buildings in high order"
|
| 67 |
+
|
| 68 |
+
llm = CustomInferenceClient(model_name=model_name, hf_token=hf_token, kwargs=kwargs) # hf_token ์ฌ์ฉํ๋ ๊ฒฝ์ฐ
|
| 69 |
+
# llm = CustomInferenceClient(model_name=model_name, kwargs=kwargs) # hf_token ์ฌ์ฉํ์ง ์๋ ๊ฒฝ์ฐ
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# ์๋ฒ ๋ฉ ๊ฐ์ฒด ์์ฑ
|
| 73 |
+
from langchain.embeddings import HuggingFaceInstructEmbeddings
|
| 74 |
+
embeddings = HuggingFaceInstructEmbeddings(
|
| 75 |
+
model_name="sentence-transformers/all-MiniLM-L6-v2",
|
| 76 |
+
cache_folder="./sentence-transformers/all-MiniLM-L6-v2",
|
| 77 |
+
model_kwargs={"device": "cpu"}
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
# ๋ฒกํฐDB ๋ก๋
|
| 81 |
+
path_work ='.'
|
| 82 |
+
|
| 83 |
+
from langchain.vectorstores import Chroma
|
| 84 |
+
vectordb = Chroma(
|
| 85 |
+
persist_directory = path_work + '/cromadb_llama2-papers',
|
| 86 |
+
embedding_function=embeddings)
|
| 87 |
+
|
| 88 |
+
retriever = vectordb.as_retriever(search_kwargs={"k": 5})
|
| 89 |
+
|
| 90 |
+
# RetrievalQA ์ฒด์ธ ๋ง๋ค๊ธฐ
|
| 91 |
+
from langchain.chains import RetrievalQA
|
| 92 |
+
qa_chain = RetrievalQA.from_chain_type(
|
| 93 |
+
# llm=OpenAI(), # from langchain.llms import OpenAI
|
| 94 |
+
llm=llm,
|
| 95 |
+
chain_type="stuff",
|
| 96 |
+
retriever=retriever,
|
| 97 |
+
return_source_documents=True,
|
| 98 |
+
verbose=True,
|
| 99 |
+
)
|
| 100 |
+
qa_chain
|
| 101 |
+
|
| 102 |
+
# ๊ทธ๋ผ๋์ค
|
| 103 |
+
import json
|
| 104 |
+
import os
|
| 105 |
+
import gradio as gr
|
| 106 |
+
|
| 107 |
+
# Stream text
|
| 108 |
+
def predict(message, chatbot, temperature=0.9, max_new_tokens=512, top_p=0.6, repetition_penalty=1.3,):
|
| 109 |
+
|
| 110 |
+
temperature = float(temperature)
|
| 111 |
+
if temperature < 1e-2: temperature = 1e-2
|
| 112 |
+
top_p = float(top_p)
|
| 113 |
+
|
| 114 |
+
# ํ๋กฌํํธ
|
| 115 |
+
# system_message = "\nYou are a psychological counselor who gives friendly and professional counseling on the concerns of Korean clients."
|
| 116 |
+
# input_prompt = f"[INST] <<SYS>>\n{system_message}\n<</SYS>>\n\n "
|
| 117 |
+
# for interaction in chatbot:
|
| 118 |
+
# input_prompt = input_prompt + str(interaction[0]) + " [/INST] " + str(interaction[1]) + " </s><s> [INST] "
|
| 119 |
+
|
| 120 |
+
# input_prompt = input_prompt + str(message) + " [/INST] "
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
# conversationalRetrievalChain (ํ์คํ ๋ฆฌ๊ฐ ์ฒด์ธ ๋ด์ฅ ํ๋กฌํํธ์ ์ธํ๋จ)
|
| 124 |
+
# chat_history = []
|
| 125 |
+
# for interaction in chatbot:
|
| 126 |
+
# chat_history = chat_history + [(str(interaction[0]), str(interaction[1]))]
|
| 127 |
+
# llm_response = qa_chain_conv({"question": message, "chat_history": chat_history})
|
| 128 |
+
# res_result = llm_response['answer']
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# RetrievalQA ์ฒด์ธ (ํ์คํ ๋ฆฌ๊ฐ ์ฒด์ธ ๋ด์ฅ ํ๋กฌํํธ์ ์ธํ ์๋จ)
|
| 132 |
+
llm_response = qa_chain(message)
|
| 133 |
+
res_result = llm_response['result']
|
| 134 |
+
|
| 135 |
+
# conversationalRetrievalChain, RetrievalQA ์ฒด์ธ ๊ณตํต
|
| 136 |
+
res_relevant_doc = [source.metadata['source'] for source in llm_response["source_documents"]]
|
| 137 |
+
response = f"{res_result}" + "\n\n" + "[๋ต๋ณ ๊ทผ๊ฑฐ ์์ค ๋
ผ๋ฌธ (ctrl + click ๏ฟฝ๏ฟฝ์ธ์!)] :" + "\n" + f" \n {res_relevant_doc}"
|
| 138 |
+
print("response: =====> \n", response, "\n\n")
|
| 139 |
+
|
| 140 |
+
#3) json ํํ๋ก ๋ณํ (api response์ ๊ฐ์ ํํ)
|
| 141 |
+
import json
|
| 142 |
+
tokens = response.split('\n')
|
| 143 |
+
token_list = []
|
| 144 |
+
for idx, token in enumerate(tokens):
|
| 145 |
+
token_dict = {"id": idx + 1, "text": token}
|
| 146 |
+
token_list.append(token_dict)
|
| 147 |
+
response = {"data": {"token": token_list}}
|
| 148 |
+
response = json.dumps(response, indent=4)
|
| 149 |
+
|
| 150 |
+
'''{'data': {'token': [{'id': 1, 'text': 'Artificial intelligence (AI) refers to...'},
|
| 151 |
+
{'id': 2, 'text': 'I hope this information helher questions!'}]}}'''
|
| 152 |
+
|
| 153 |
+
# ===========================================================================
|
| 154 |
+
# ์คํธ๋ฆฌ๋ฐ ์์ (partial_message)
|
| 155 |
+
response = json.loads(response) # {'data': {'token': [{'id': 1, 'text': '๋ต๋ณ์ " ์๋
ํ์ธ์. ์ ๋ ์ก์์ง ๋ฐ์ฌ.....
|
| 156 |
+
data_dict = response.get('data', {})
|
| 157 |
+
token_list = data_dict.get('token', [])
|
| 158 |
+
|
| 159 |
+
import time
|
| 160 |
+
partial_message = ""
|
| 161 |
+
# ํ์ด๋ผ์ดํธ: .iter_lines() ๋์ ์ token_list๋ฅผ ์ง์ ์ํํฉ๋๋ค.
|
| 162 |
+
for token_entry in token_list:
|
| 163 |
+
if token_entry: # filter out keep-alive new lines (if any)
|
| 164 |
+
try:
|
| 165 |
+
# ํ์ด๋ผ์ดํธ: ์ง์ ์ฌ์ ์์ 'id'์ 'text'๋ฅผ ์ถ์ถํฉ๋๋ค.
|
| 166 |
+
token_id = token_entry.get('id', None)
|
| 167 |
+
token_text = token_entry.get('text', None)
|
| 168 |
+
|
| 169 |
+
# time.sleep์ผ๋ก ๊ธ์ ์๋ ์กฐ์ ํ๋ฉฐ ๊ธ์ ๋ด๋ณด๋
|
| 170 |
+
if token_text: # ์ด ๋ถ๋ถ์ ์ํ๋ ๋๋ก ์กฐ์ ํ ์ ์์ต๋๋ค.
|
| 171 |
+
# partial_message = partial_message + token_text
|
| 172 |
+
for char in token_text: # ๋ฌธ์ ํ๋์ฉ ์ํ (์ถ๊ฐ๋จ)
|
| 173 |
+
partial_message += char # partial_message์ ๋ฌธ์ ์ถ๊ฐ (๋ณ๊ฒฝ๋จ)
|
| 174 |
+
yield partial_message
|
| 175 |
+
time.sleep(0.01)
|
| 176 |
+
else:
|
| 177 |
+
# gr.Warning(f"The key 'text' does not exist or is None in this token entry: {token_entry}")
|
| 178 |
+
print(f"[[์๋]] ==> The key 'text' does not exist or is None in this token entry: {token_entry}")
|
| 179 |
+
|
| 180 |
+
except KeyError as e:
|
| 181 |
+
gr.Warning(f"KeyError: {e} occurred for token entry: {token_entry}")
|
| 182 |
+
continue
|
| 183 |
+
|
| 184 |
+
# ํ์ดํ/์ค๋ช
/์ง๋ฌธ์์
|
| 185 |
+
title = "llama-2 ๋ชจ๋ธ ๊ด๋ จ ๋
ผ๋ฌธ QA ์๋น์ค"
|
| 186 |
+
description = """chat history ์ ์ง ๋ณด๋ค๋ QA์ ์ถฉ์คํ๋๋ก ์ ์๋์์ผ๋ Single turn์ผ๋ก ํ์ฉ์ ํ์ฌ ์ฃผ์ธ์. (chat history ํ์ฉ์ ๋ค๋ฅธ ์ฃผ์ ๋ก ๋ณ๋ ์ ์ ์์ )"""
|
| 187 |
+
css = """.toast-wrap { display: none !important } """
|
| 188 |
+
examples=[['Can you tell me about the llama-2 model?'],['What is percent accuracy, using the SPP layer as features on the SPP (ZF-5) model?'], ['What is percent accuracy, using the SPP layer as features on the SPP (ZF-5) model?'], ["tell me about method for human pose estimation based on DNNs"]]
|
| 189 |
+
|
| 190 |
+
# ์ข์์
|
| 191 |
+
import gradio as gr
|
| 192 |
+
def vote(data: gr.LikeData):
|
| 193 |
+
if data.liked: print("You upvoted this response: " + data.value)
|
| 194 |
+
else: print("You downvoted this response: " + data.value)
|
| 195 |
+
|
| 196 |
+
# ๊ทธ๋ผ๋์ค (์ธ์ ์กฐ์ )
|
| 197 |
+
additional_inputs = [
|
| 198 |
+
# gr.Textbox("", label="Optional system prompt"),
|
| 199 |
+
gr.Slider(label="Temperature", value=0.9, minimum=0.0, maximum=1.0, step=0.05, interactive=True, info="Higher values produce more diverse outputs"),
|
| 200 |
+
gr.Slider(label="Max new tokens", value=256, minimum=0, maximum=4096, step=64, interactive=True, info="The maximum numbers of new tokens"),
|
| 201 |
+
gr.Slider(label="Top-p (nucleus sampling)", value=0.6, minimum=0.0, maximum=1, step=0.05, interactive=True, info="Higher values sample more low-probability tokens"),
|
| 202 |
+
gr.Slider(label="Repetition penalty", value=1.2, minimum=1.0, maximum=2.0, step=0.05, interactive=True, info="Penalize repeated tokens")
|
| 203 |
+
]
|
| 204 |
+
|
| 205 |
+
chatbot_stream = gr.Chatbot(avatar_images=(
|
| 206 |
+
"https://drive.google.com/uc?id=13rYrN0cH_9tR7GveqO1q2JiyBCqkfCLZ", # https://drive.google.com/uc?id= ๋ค์ ID๊ฐ๋ง (๋ชจ๋ ์ฌ์ฉ์ ์ก์ธ์ค ๊ถํ ํ์ฉ)
|
| 207 |
+
"https://drive.google.com/uc?id=1tfELAQW_VbPCy6QTRbexRlwAEYo8rSSv"
|
| 208 |
+
), bubble_full_width = False)
|
| 209 |
+
|
| 210 |
+
chat_interface_stream = gr.ChatInterface(predict,
|
| 211 |
+
title=title,
|
| 212 |
+
description=description,
|
| 213 |
+
# textbox=gr.Textbox(lines=5),
|
| 214 |
+
chatbot=chatbot_stream,
|
| 215 |
+
css=css,
|
| 216 |
+
examples=examples,
|
| 217 |
+
# cache_examples=True,
|
| 218 |
+
# additional_inputs=additional_inputs,
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
# Gradio Demo
|
| 222 |
+
with gr.Blocks() as demo:
|
| 223 |
+
|
| 224 |
+
with gr.Tab("์คํธ๋ฆฌ๋ฐ"):
|
| 225 |
+
#gr.ChatInterface(predict, title=title, description=description, css=css, examples=examples, cache_examples=True, additional_inputs=additional_inputs,)
|
| 226 |
+
chatbot_stream.like(vote, None, None)
|
| 227 |
+
chat_interface_stream.render()
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
demo.queue(concurrency_count=75, max_size=100).launch(debug=True)
|
| 231 |
+
|