vishal0719 commited on
Commit
fc74c52
β€’
1 Parent(s): bfed7dd

adding application file

Browse files
Files changed (2) hide show
  1. app.py +215 -0
  2. requirements.txt +10 -0
app.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """InfogenQA_langchain.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1ubmRCRQhU3K16iDYgBcJ4XMPRffvctaa
8
+ """
9
+
10
+ # Installing all required libraries
11
+ # Langchain - for buiding retrieval chains
12
+ # faiss-gpu - for performing similarity search on GPUs
13
+ # sentence_transformers - pre-trained sentence embeddings for understanding semantics
14
+
15
+ # Install required libraries
16
+ # !pip install -qU transformers accelerate einops langchain xformers bitsandbytes faiss-gpu sentence_transformers
17
+ # !pip install gradio
18
+
19
+ # For handling UTF-8 locale error
20
+ import locale
21
+ def getpreferredencoding(do_setlocale = True):
22
+ return "UTF-8"
23
+ locale.getpreferredencoding = getpreferredencoding
24
+
25
+ from torch import cuda, bfloat16
26
+ import transformers
27
+
28
+ # Model used
29
+ model_id = 'meta-llama/Llama-2-7b-chat-hf'
30
+
31
+ # Detects available device (GPU or CPU)
32
+ device = f'cuda:{cuda.current_device()}' if cuda.is_available() else 'cpu'
33
+
34
+ # set quantization configuration to load large model with less GPU memory
35
+ # this requires the `bitsandbytes` library
36
+ bnb_config = transformers.BitsAndBytesConfig(
37
+ load_in_4bit=True,
38
+ bnb_4bit_quant_type='nf4',
39
+ bnb_4bit_use_double_quant=True,
40
+ bnb_4bit_compute_dtype=bfloat16
41
+ )
42
+
43
+
44
+ # Downloading and parsing model's configuration from HF
45
+ model_config = transformers.AutoConfig.from_pretrained(
46
+ model_id,
47
+ use_auth_token=hf_auth
48
+ )
49
+
50
+ # Downloading and Initializing the model
51
+ model = transformers.AutoModelForCausalLM.from_pretrained(
52
+ model_id,
53
+ trust_remote_code=True,
54
+ config=model_config,
55
+ quantization_config=bnb_config,
56
+ device_map='auto',
57
+ use_auth_token=hf_auth
58
+ )
59
+
60
+ # enable evaluation mode to allow model inference
61
+ model.eval()
62
+
63
+ print(f"Model loaded on {device}")
64
+
65
+ # Initialize tokenization process for Llama-2
66
+ # used to process text into LLM compatible format
67
+ tokenizer = transformers.AutoTokenizer.from_pretrained(
68
+ model_id,
69
+ use_auth_token=hf_auth
70
+ )
71
+
72
+ # Defining strings to be treated as 'stop tokens' during text generation
73
+ stop_list = ['\nHuman:', '\n```\n']
74
+
75
+ # Converting stop tokens to their corresponding numerical token IDs
76
+ stop_token_ids = [tokenizer(x)['input_ids'] for x in stop_list]
77
+ stop_token_ids
78
+
79
+ import torch
80
+
81
+ # Converitng stop_token_ids into long tensors (64-bit) and load into selected device
82
+ stop_token_ids = [torch.LongTensor(x).to(device) for x in stop_token_ids]
83
+ stop_token_ids
84
+
85
+ from transformers import StoppingCriteria, StoppingCriteriaList
86
+
87
+ # define custom stopping criteria object
88
+ # Allows us to check whether the generated text contains stop_token_ids
89
+ class StopOnTokens(StoppingCriteria):
90
+ def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
91
+ for stop_ids in stop_token_ids:
92
+ if torch.eq(input_ids[0][-len(stop_ids):], stop_ids).all():
93
+ return True
94
+ return False
95
+
96
+ # Defining a list of stopping criteria
97
+ stopping_criteria = StoppingCriteriaList([StopOnTokens()])
98
+
99
+ # Function to generate text using Llama
100
+
101
+ generate_text = transformers.pipeline(
102
+ model=model,
103
+ tokenizer=tokenizer,
104
+ return_full_text=True, # langchain expects the full text
105
+ task='text-generation',
106
+ # we pass model parameters here too
107
+ stopping_criteria=stopping_criteria, # without this model rambles during chat
108
+ temperature=0.1, # 'randomness' of outputs, 0.0 is the min and 1.0 the max
109
+ max_new_tokens=512, # max number of tokens to generate in the output
110
+ repetition_penalty=1.1 # without this output begins repeating
111
+ )
112
+
113
+ # Checking whether it is able to generate text or not
114
+ from langchain.llms import HuggingFacePipeline
115
+
116
+ llm = HuggingFacePipeline(pipeline=generate_text)
117
+
118
+ llm(prompt="Who is the CEO of Infogen Labs?")
119
+
120
+ # Importing WebBaseLoader class - used to load documents from web links
121
+ from langchain.document_loaders import WebBaseLoader
122
+
123
+ # A list containing web links from Infogen-Labs website
124
+ web_links = ["https://corp.infogen-labs.com/index.html",
125
+ "https://corp.infogen-labs.com/technology.html",
126
+ "https://corp.infogen-labs.com/EdTech.html",
127
+ "https://corp.infogen-labs.com/FinTech.html",
128
+ "https://corp.infogen-labs.com/retail.html",
129
+ "https://corp.infogen-labs.com/telecom.html",
130
+ "https://corp.infogen-labs.com/stud10.html",
131
+ "https://corp.infogen-labs.com/construction.html",
132
+ "https://corp.infogen-labs.com/RandD.html",
133
+ "https://corp.infogen-labs.com/microsoft.html",
134
+ "https://corp.infogen-labs.com/edge-technology.html",
135
+ "https://corp.infogen-labs.com/cloud-computing.html",
136
+ "https://corp.infogen-labs.com/uiux-studio.html",
137
+ "https://corp.infogen-labs.com/mobile-studio.html",
138
+ "https://corp.infogen-labs.com/qaqc-studio.html",
139
+ "https://corp.infogen-labs.com/platforms.html",
140
+ "https://corp.infogen-labs.com/about-us.html",
141
+ "https://corp.infogen-labs.com/career.html",
142
+ "https://corp.infogen-labs.com/contact-us.html"
143
+ ]
144
+
145
+ # Fetch the content from web links and store the extracted text
146
+ loader = WebBaseLoader(web_links)
147
+ documents = loader.load()
148
+
149
+ # Splitting large text documents into smaller chunks for easier processing
150
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
151
+
152
+ # Specifying chunk size
153
+ # chunk_overlap allows some overlap between cuts to maintain context
154
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=20)
155
+ # A lsit of splits from all the document
156
+ all_splits = text_splitter.split_documents(documents)
157
+
158
+ from langchain.embeddings import HuggingFaceEmbeddings # For numerical representation of the text
159
+ from langchain.vectorstores import FAISS # Similarity search in high-dimensional vector space
160
+
161
+ model_name = "sentence-transformers/all-mpnet-base-v2" # Embedding model
162
+ model_kwargs = {"device": "cuda"}
163
+
164
+ # used to generate embeddings from text
165
+ embeddings = HuggingFaceEmbeddings(model_name=model_name, model_kwargs=model_kwargs)
166
+
167
+ # storing embeddings in the vector store
168
+ vectorstore = FAISS.from_documents(all_splits, embeddings)
169
+
170
+ # Creating conversational agents that combine retrieval and generation capabilities
171
+ from langchain.chains import ConversationalRetrievalChain
172
+
173
+ # Creating a conversational retrieval chain by taking three arguments:
174
+ # LLM - for text generation
175
+ # converts FAISS vector store into a retriver object
176
+ # Also return the original source document to provide more context
177
+ chain = ConversationalRetrievalChain.from_llm(llm, vectorstore.as_retriever(), return_source_documents=True)
178
+
179
+ # For demo purpose
180
+ # Storing chat history for asking follow up questions
181
+ # chat_history = []
182
+
183
+ # # Asking query
184
+ # query = "Who is the CEO of Infogen Labs?"
185
+ # result = chain({"question": query, "chat_history": chat_history})
186
+
187
+ # # Printing the result
188
+ # print(result['answer'])
189
+
190
+ # # Adding current question and generated answer
191
+ # chat_history.append((query, result["answer"]))
192
+
193
+ # # Printing source document from where the results were derived
194
+ # print(result['source_documents'])
195
+
196
+ import gradio as gr
197
+
198
+ def process_answer(answer):
199
+ answer = answer.replace('If you don\'t know the answer to this question, please say so.', '')
200
+ answer = answer.replace('Based on the information provided in the passage', 'Based on my current knowledge')
201
+ return answer
202
+
203
+ def generate_response(message, history):
204
+ chat_history = []
205
+
206
+ for val in history:
207
+ chat_history.append(tuple(val))
208
+
209
+ result = chain({"question": message, "chat_history": chat_history})
210
+ response = process_answer(result['answer'])
211
+
212
+ return response
213
+
214
+ gr.ChatInterface(generate_response).launch()
215
+
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ transformers
3
+ accelerate
4
+ einops
5
+ langchain
6
+ xformers
7
+ bitsandbytes
8
+ faiss-gpu
9
+ sentence_transformers
10
+ gradio