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