arjunanand13 commited on
Commit
a9f989b
·
verified ·
1 Parent(s): 8868bb5

Delete app_27_5_28_mistral2.py

Browse files
Files changed (1) hide show
  1. app_27_5_28_mistral2.py +0 -259
app_27_5_28_mistral2.py DELETED
@@ -1,259 +0,0 @@
1
- import os
2
- import torch
3
- from torch import cuda, bfloat16
4
- from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline, BitsAndBytesConfig, StoppingCriteria, StoppingCriteriaList
5
- from langchain.llms import HuggingFacePipeline
6
- from langchain.vectorstores import FAISS
7
- from langchain.chains import ConversationalRetrievalChain
8
- import gradio as gr
9
- from langchain.embeddings import HuggingFaceEmbeddings
10
-
11
-
12
- # Load the Hugging Face token from environment
13
- HF_TOKEN = os.environ.get("HF_TOKEN", None)
14
-
15
- # Define stopping criteria
16
- class StopOnTokens(StoppingCriteria):
17
- def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
18
- for stop_ids in stop_token_ids:
19
- if torch.eq(input_ids[0][-len(stop_ids):], stop_ids).all():
20
- return True
21
- return False
22
-
23
- # Load the LLaMA model and tokenizer
24
- # model_id = 'meta-llama/Meta-Llama-3-8B-Instruct'
25
- # model_id= "meta-llama/Llama-2-7b-chat-hf"
26
- model_id="mistralai/Mistral-7B-Instruct-v0.2"
27
- device = f'cuda:{cuda.current_device()}' if cuda.is_available() else 'cpu'
28
-
29
- # Set quantization configuration
30
- bnb_config = BitsAndBytesConfig(
31
- load_in_4bit=True,
32
- bnb_4bit_quant_type='nf4',
33
- bnb_4bit_use_double_quant=True,
34
- bnb_4bit_compute_dtype=bfloat16
35
- )
36
-
37
- tokenizer = AutoTokenizer.from_pretrained(model_id, token=HF_TOKEN)
38
- model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", token=HF_TOKEN, quantization_config=bnb_config)
39
-
40
- # Define stopping criteria
41
- stop_list = ['\nHuman:', '\n```\n']
42
- stop_token_ids = [tokenizer(x)['input_ids'] for x in stop_list]
43
- stop_token_ids = [torch.LongTensor(x).to(device) for x in stop_token_ids]
44
- stopping_criteria = StoppingCriteriaList([StopOnTokens()])
45
-
46
- # Create text generation pipeline
47
- generate_text = pipeline(
48
- model=model,
49
- tokenizer=tokenizer,
50
- return_full_text=True,
51
- task='text-generation',
52
- # stopping_criteria=stopping_criteria,
53
- temperature=0.1,
54
- max_new_tokens=2048,
55
- # repetition_penalty=1.1
56
- )
57
-
58
- llm = HuggingFacePipeline(pipeline=generate_text)
59
-
60
- # Load the stored FAISS index
61
- try:
62
- vectorstore = FAISS.load_local('faiss_index', HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2", model_kwargs={"device": "cuda"}))
63
- print("Loaded embedding successfully")
64
- except ImportError as e:
65
- print("FAISS could not be imported. Make sure FAISS is installed correctly.")
66
- raise e
67
-
68
- # Set up the Conversational Retrieval Chain
69
- chain = ConversationalRetrievalChain.from_llm(llm, vectorstore.as_retriever(), return_source_documents=True)
70
-
71
- chat_history = []
72
-
73
- def format_prompt(query):
74
- prompt = f"""
75
- You are a knowledgeable assistant with access to a comprehensive database.
76
- I need you to answer my question and provide related information in a specific format.
77
- Here's what I need:
78
- A brief, general response to my question based on related answers retrieved.
79
- Include a brief final answer without additional comments, sign-offs, or extra phrases. Be direct and to the point.
80
-
81
- A JSON-formatted output containing: ALL SOURCE DOCUMENTS
82
- - "question": The ticketName
83
- - "answer": The Responses
84
- Here's my question:
85
- {query}
86
- """
87
-
88
- # - "related_questions": A list of related questions and their answers, each as a dictionary with the keys. Consider all source documents:
89
- # - "question": The related question.
90
- # - "answer": The related answer.
91
-
92
-
93
-
94
- # Example 1:
95
- # {{
96
- # "question": "How to use IPU1_0 instead of A15_0 to process NDK in TDA2x-EVM",
97
- # "answer": "To use IPU1_0 instead of A15_0 to process NDK in TDA2x-EVM, you need to modify the configuration file of the NDK application. Specifically, change the processor reference from 'A15_0' to 'IPU1_0'.",
98
- # "related_questions": [
99
- # {{
100
- # "question": "Can you provide MLBP documentation on TDA2?",
101
- # "answer": "MLB is documented for DRA devices in the TRM book, chapter 24.12."
102
- # }},
103
- # {{
104
- # "question": "Hi, could you share me the TDA2x documents about Security(SPRUHS7) and Cryptographic(SPRUHS8) addendums?",
105
- # "answer": "Most of TDA2 documents are on ti.com under the product folder."
106
- # }},
107
- # {{
108
- # "question": "Is any one can provide us a way to access CDDS for nessary docs?",
109
- # "answer": "Which document are you looking for?"
110
- # }},
111
- # {{
112
- # "question": "What can you tell me about the TDA2 and TDA3 processors? Can they / do they run Linux?",
113
- # "answer": "We have moved your post to the appropriate forum."
114
- # }}
115
- # ]
116
- # }}
117
-
118
- # Final Answer: To use IPU1_0 instead of A15_0 to process NDK in TDA2x-EVM, you need to modify the configuration file of the NDK application. Specifically, change the processor reference from 'A15_0' to 'IPU1_0'.
119
-
120
- # Example 2:
121
- # {{
122
- # "question": "Can BQ25896 support I2C interface?",
123
- # "answer": "Yes, the BQ25896 charger supports the I2C interface for communication.",
124
- # "related_questions": [
125
- # {{
126
- # "question": "What are the main features of BQ25896?",
127
- # "answer": "The BQ25896 features include high-efficiency, fast charging capability, and a wide input voltage range."
128
- # }},
129
- # {{
130
- # "question": "How to configure the BQ25896 for USB charging?",
131
- # "answer": "To configure the BQ25896 for USB charging, set the input current limit and the charging current via I2C registers."
132
- # }}
133
- # ]
134
- # }}
135
-
136
- # Final Answer: Yes, the BQ25896 charger supports the I2C interface for communication.
137
-
138
- # """
139
-
140
-
141
- return prompt
142
-
143
-
144
- def qa_infer(query):
145
- formatted_prompt = format_prompt(query)
146
- result = chain({"question": formatted_prompt, "chat_history": chat_history})
147
- for doc in result['source_documents']:
148
- print("-"*50)
149
- print("Retrieved Document:", doc.page_content)
150
- print("#"*100)
151
- print(result['answer'])
152
- return result['answer']
153
-
154
- EXAMPLES = ["How to use IPU1_0 instead of A15_0 to process NDK in TDA2x-EVM",
155
- "I'm using Code Composer Studio 5.4.0.00091 and enabled FPv4SPD16 floating point support for CortexM4 in TDA2. However, after building the project, the .asm file shows --float_support=vfplib instead of FPv4SPD16. Why is this happening?",
156
- "Master core in TDA2XX is a15 and in TDA3XX it is m4,so we have to shift all modules that are being used by a15 in TDA2XX to m4 in TDA3xx."]
157
-
158
- demo = gr.Interface(fn=qa_infer, inputs="text", allow_flagging='never', examples=EXAMPLES, cache_examples=False, outputs="text")
159
- demo.launch()
160
-
161
- # import os
162
- # import torch
163
- # from torch import cuda, bfloat16
164
- # from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline, BitsAndBytesConfig, StoppingCriteria, StoppingCriteriaList
165
- # from langchain.llms import HuggingFacePipeline
166
- # from langchain.vectorstores import FAISS
167
- # from langchain.chains import ConversationalRetrievalChain
168
- # import gradio as gr
169
- # from langchain.embeddings import HuggingFaceEmbeddings
170
-
171
- # # Load the Hugging Face token from environment
172
- # HF_TOKEN = os.environ.get("HF_TOKEN", None)
173
-
174
- # # Define stopping criteria
175
- # class StopOnTokens(StoppingCriteria):
176
- # def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
177
- # for stop_ids in stop_token_ids:
178
- # if torch.eq(input_ids[0][-len(stop_ids):], stop_ids).all():
179
- # return True
180
- # return False
181
-
182
- # # Load the LLaMA model and tokenizer
183
- # model_id = 'meta-llama/Meta-Llama-3-8B-Instruct'
184
- # device = f'cuda:{cuda.current_device()}' if cuda.is_available() else 'cpu'
185
-
186
- # # Set quantization configuration
187
- # bnb_config = BitsAndBytesConfig(
188
- # load_in_4bit=True,
189
- # bnb_4bit_quant_type='nf4',
190
- # bnb_4bit_use_double_quant=True,
191
- # bnb_4bit_compute_dtype=bfloat16
192
- # )
193
-
194
- # tokenizer = AutoTokenizer.from_pretrained(model_id, token=HF_TOKEN)
195
- # model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", token=HF_TOKEN, quantization_config=bnb_config)
196
-
197
- # # Define stopping criteria
198
- # stop_list = ['\nHuman:', '\n```\n']
199
- # stop_token_ids = [tokenizer(x)['input_ids'] for x in stop_list]
200
- # stop_token_ids = [torch.LongTensor(x).to(device) for x in stop_token_ids]
201
- # stopping_criteria = StoppingCriteriaList([StopOnTokens()])
202
-
203
- # # Create text generation pipeline
204
- # generate_text = pipeline(
205
- # model=model,
206
- # tokenizer=tokenizer,
207
- # return_full_text=True,
208
- # task='text-generation',
209
- # stopping_criteria=stopping_criteria,
210
- # temperature=0.1,
211
- # max_new_tokens=512,
212
- # repetition_penalty=1.1
213
- # )
214
-
215
- # llm = HuggingFacePipeline(pipeline=generate_text)
216
-
217
- # # Load the stored FAISS index
218
- # try:
219
- # embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2", model_kwargs={"device": "cuda"})
220
- # vectorstore = FAISS.load_local('faiss_index', embeddings)
221
- # print("Loaded embedding successfully")
222
- # except ImportError as e:
223
- # print("FAISS could not be imported. Make sure FAISS is installed correctly.")
224
- # raise e
225
-
226
- # # Set up the Conversational Retrieval Chain
227
- # chain = ConversationalRetrievalChain.from_llm(llm, vectorstore.as_retriever(), return_source_documents=True)
228
-
229
- # chat_history = []
230
-
231
- # def format_prompt(query):
232
- # prompt = f"""
233
- # You are a knowledgeable assistant with access to a comprehensive database.
234
- # I need you to answer my question and provide related information in a specific format.
235
- # Here's what I need:
236
- # 1. A brief, general response to my question based on related answers retrieved.
237
- # 2. A JSON-formatted output containing:
238
- # - "question": The original question.
239
- # - "answer": The detailed answer.
240
- # - "related_questions": A list of related questions and their answers, each as a dictionary with the keys:
241
- # - "question": The related question.
242
- # - "answer": The related answer.
243
- # Here's my question:
244
- # {query}
245
- # Include a brief final answer without additional comments, sign-offs, or extra phrases. Be direct and to the point.
246
- # """
247
- # return prompt
248
-
249
- # def qa_infer(query):
250
- # formatted_prompt = format_prompt(query)
251
- # result = chain({"question": formatted_prompt, "chat_history": chat_history})
252
- # return result['answer']
253
-
254
- # EXAMPLES = ["How to use IPU1_0 instead of A15_0 to process NDK in TDA2x-EVM",
255
- # "Can BQ25896 support I2C interface?",
256
- # "Does TDA2 vout support bt656 8-bit mode?"]
257
-
258
- # demo = gr.Interface(fn=qa_infer, inputs="text", allow_flagging='never', examples=EXAMPLES, cache_examples=False, outputs="text")
259
- # demo.launch()