tmskss commited on
Commit
a037d13
1 Parent(s): 99a4862

Update open source model based kubectl

Browse files
Files changed (1) hide show
  1. app.py +217 -112
app.py CHANGED
@@ -1,37 +1,99 @@
 
 
 
 
 
 
 
1
  import gradio as gr
2
  from transformers.generation.stopping_criteria import StoppingCriteria, StoppingCriteriaList
3
  from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
 
 
4
  from peft import PeftModel
5
- import torch
6
- import pinecone
7
  from sentence_transformers import SentenceTransformer
8
- from tqdm import tqdm
9
- from sentence_transformers.cross_encoder import CrossEncoder
10
- import numpy as np
11
- from torch import nn
12
- import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
- # Set up semantic search
15
- PINECONE_API_KEY = os.environ.get('PINECONE_API_KEY')
 
16
 
17
- def get_embedding(text):
18
- embed_text = sentencetransformer_model.encode(text)
19
- vector_text = embed_text.tolist()
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
- return vector_text
22
 
23
  def query_from_pinecone(query, top_k=3):
24
- # get embedding from THE SAME embedder as the documents
25
- query_embedding = get_embedding(query)
 
26
 
27
- return index.query(
28
- vector=query_embedding,
29
- top_k=top_k,
30
- include_metadata=True # gets the metadata (dates, text, etc)
31
- ).get('matches')
32
 
33
- def get_results_from_pinecone(query, top_k=3, re_rank=True, verbose=True):
34
 
 
 
 
 
35
  results_from_pinecone = query_from_pinecone(query, top_k=top_k)
36
  if not results_from_pinecone:
37
  return []
@@ -39,14 +101,15 @@ def get_results_from_pinecone(query, top_k=3, re_rank=True, verbose=True):
39
  if verbose:
40
  print("Query:", query)
41
 
42
-
43
  final_results = []
44
 
45
  if re_rank:
46
  if verbose:
47
- print('Document ID (Hash)\t\tRetrieval Score\tCE Score\tText')
48
 
49
- sentence_combinations = [[query, result_from_pinecone['metadata']['text']] for result_from_pinecone in results_from_pinecone]
 
 
50
 
51
  # Compute the similarity scores for these combinations
52
  similarity_scores = cross_encoder.predict(sentence_combinations, activation_fct=nn.Sigmoid())
@@ -59,46 +122,33 @@ def get_results_from_pinecone(query, top_k=3, re_rank=True, verbose=True):
59
  result_from_pinecone = results_from_pinecone[idx]
60
  final_results.append(result_from_pinecone)
61
  if verbose:
62
- print(f"{result_from_pinecone['id']}\t{result_from_pinecone['score']:.2f}\t{similarity_scores[idx]:.2f}\t{result_from_pinecone['metadata']['text'][:50]}")
 
 
63
  return final_results
64
 
65
  if verbose:
66
- print('Document ID (Hash)\t\tRetrieval Score\tText')
67
  for result_from_pinecone in results_from_pinecone:
68
  final_results.append(result_from_pinecone)
69
  if verbose:
70
- print(f"{result_from_pinecone['id']}\t{result_from_pinecone['score']:.2f}\t{result_from_pinecone['metadata']['text'][:50]}")
 
 
71
 
72
  return final_results
73
 
 
74
  def semantic_search(prompt):
75
  final_results = get_results_from_pinecone(prompt, top_k=9, re_rank=True, verbose=True)
 
 
76
 
77
- return '\n\n'.join(res['metadata']['text'].strip() for res in final_results[:3])
78
 
79
- cross_encoder = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-12-v2')
80
- sentencetransformer_model = SentenceTransformer('sentence-transformers/multi-qa-mpnet-base-cos-v1')
81
 
82
- pinecone_key = PINECONE_API_KEY
83
-
84
- INDEX_NAME = 'k8s-semantic-search'
85
- NAMESPACE = 'default'
86
-
87
- pinecone.init(api_key=pinecone_key, environment="gcp-starter")
88
-
89
- if not INDEX_NAME in pinecone.list_indexes():
90
- pinecone.create_index(
91
- INDEX_NAME, # The name of the index
92
- dimension=768, # The dimensionality of the vectors
93
- metric='cosine', # The similarity metric to use when searching the index
94
- pod_type='starter' # The type of Pinecone pod
95
- )
96
-
97
- index = pinecone.Index(INDEX_NAME)
98
-
99
- # Set up mistral model
100
- base_model_id = 'mistralai/Mistral-7B-Instruct-v0.1'
101
- lora_model_id = 'ComponentSoft/mistral-kubectl-instruct'
102
 
103
  tokenizer = AutoTokenizer.from_pretrained(
104
  lora_model_id,
@@ -109,10 +159,7 @@ tokenizer = AutoTokenizer.from_pretrained(
109
  tokenizer.pad_token = tokenizer.eos_token
110
 
111
  bnb_config = BitsAndBytesConfig(
112
- load_in_4bit=True,
113
- bnb_4bit_use_double_quant=True,
114
- bnb_4bit_quant_type="nf4",
115
- bnb_4bit_compute_dtype=torch.bfloat16
116
  )
117
 
118
  base_model = AutoModelForCausalLM.from_pretrained(
@@ -125,81 +172,139 @@ base_model = AutoModelForCausalLM.from_pretrained(
125
  model = PeftModel.from_pretrained(base_model, lora_model_id)
126
  model.eval()
127
 
128
- stop_terms=["</s>", "#End"]
129
- eos_token_ids_custom = [torch.tensor(tokenizer.encode(term, add_special_tokens=False)).to("cuda") for term in stop_terms]
130
 
131
- category_terms=["</s>", "\n"]
132
- category_eos_token_ids_custom = [torch.tensor(tokenizer.encode(term, add_special_tokens=False)).to("cuda") for term in category_terms]
 
 
 
 
133
 
 
134
 
135
- class EvalStopCriterion(StoppingCriteria):
136
- def __call__(self, input_ids: torch.LongTensor, score: torch.FloatTensor, **kwargs):
137
- return any(torch.equal(e, input_ids[0][-len(e):]) for e in eos_token_ids_custom)
138
 
 
 
139
 
140
- class CategoryStopCriterion(StoppingCriteria):
141
- def __call__(self, input_ids: torch.LongTensor, score: torch.FloatTensor, **kwargs):
142
- return any(torch.equal(e, input_ids[0][-len(e):]) for e in category_eos_token_ids_custom)
143
 
144
- start_template = '### Answer:'
145
- command_template = '# Command:'
146
- end_template = '#End'
147
 
148
- def text_to_text_generation(prompt):
149
  prompt = prompt.strip()
150
- ''
151
 
152
  is_kubectl_prompt = (
153
- f"[INST] You are a helpful assistant who classifies prompts into three categories. Respond with 0 if it pertains to a 'kubectl' operation. This is an instruction that can be answered with a 'kubectl' action. Look for keywords like 'get', 'list', 'create', 'show', 'view', and other command-like words. This category is an instruction instead of a question. Respond with 1 only if the prompt is a question, and is about a definition related to Kubernetes, or non-action inquiries. Respond with 2 every other scenario, for example if the question is a general question, not related to Kubernetes or 'kubectl'.\n"
154
  f"So for instance the following:\n"
155
- f"List all pods in Kubernetes\n"
156
  f"Would get a response:\n"
157
- f"0 [/INST]"
158
  f'text: "{prompt}"'
159
- f'response (0/1/2): '
160
  )
161
 
162
-
163
  model_input = tokenizer(is_kubectl_prompt, return_tensors="pt").to("cuda")
164
  with torch.no_grad():
165
- response = tokenizer.decode(model.generate(**model_input, max_new_tokens=8, pad_token_id=tokenizer.eos_token_id, repetition_penalty=1.15, stopping_criteria=StoppingCriteriaList([CategoryStopCriterion()]))[0], skip_special_tokens=True)
166
- response = response[len(is_kubectl_prompt):]
167
-
168
- print('-----------------------------QUERY START-----------------------------')
169
- print('Prompt: ' + prompt)
170
- print('Classified as: ' + response)
171
- response_num = 2 # Default to generic question
172
- if '0' in response:
173
- response_num = 0
174
- elif '1' in response:
175
- response_num = 1
176
-
177
-
178
- # Check if general question
179
- if response_num == 0:
180
- prompt = f'[INST] {prompt}\n Lets think step by step. [/INST] {start_template}'
181
- elif response_num == 1:
182
- retrieved_results = semantic_search(prompt)
183
- print('Query:')
184
- print(f'[INST] You are an assistant who summarizes results retrieved from a book about Kubernetes. This summary should answer the question. If the answer is not in the retrieved results, use your general knowledge. [/INST] Question: {prompt}\nRetrieved results:\n{retrieved_results}\nResponse:')
185
- prompt = f'[INST] You are an assistant who summarizes results retrieved from a book about Kubernetes. This summary should answer the question. If the answer is not in the retrieved results, use your general knowledge. [/INST] Question: {prompt}\nRetrieved results:\n{retrieved_results}\nResponse:'
186
- else:
187
- prompt = f'[INST] {prompt} [/INST]'
188
-
189
- # Generate output
190
- model_input = tokenizer(prompt, return_tensors="pt").to("cuda")
191
- with torch.no_grad():
192
- response = tokenizer.decode(model.generate(**model_input, max_new_tokens=256, pad_token_id=tokenizer.eos_token_id, repetition_penalty=1.15, stopping_criteria=StoppingCriteriaList([EvalStopCriterion()]))[0], skip_special_tokens=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
 
194
- # Get the relevalt parts
195
- start = response.index(start_template) + len(start_template) if start_template in response else len(prompt)
196
- start = response.index(command_template) + len(command_template) if command_template in response else start
197
- end = response.index(end_template) if end_template in response else len(response)
198
- true_response = response[start:end].strip()
199
- print('Returned: ' + true_response)
200
- print('------------------------------QUERY END------------------------------')
201
 
202
- return true_response
 
 
 
 
 
 
 
 
 
 
 
 
 
203
 
204
- iface = gr.Interface(fn=text_to_text_generation, inputs="text", outputs="text")
205
- iface.launch()
 
1
+ import torch
2
+ import time
3
+ import pinecone
4
+ import pickle
5
+ import os
6
+ import numpy as np
7
+ import hashlib
8
  import gradio as gr
9
  from transformers.generation.stopping_criteria import StoppingCriteria, StoppingCriteriaList
10
  from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
11
+ from torch import nn
12
+ from sentence_transformers.cross_encoder import CrossEncoder
13
  from peft import PeftModel
 
 
14
  from sentence_transformers import SentenceTransformer
15
+ from bs4 import BeautifulSoup
16
+ import requests
17
+
18
+ headers = {
19
+ "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit 537.36 (KHTML, like Gecko) Chrome",
20
+ "Accept":"text/html,application/xhtml+xml,application/xml; q=0.9,image/webp,*/*;q=0.8",
21
+ 'Cookie':'CONSENT=YES+cb.20210418-17-p0.it+FX+917; '
22
+ }
23
+
24
+ def google_search(text):
25
+ print(f"Google search on: {text}")
26
+ try:
27
+ site = requests.get(f'https://www.google.com/search?hl=en&q={text}', headers=headers)
28
+ main = BeautifulSoup(site.text, features="html.parser").select_one('#main').select('.VwiC3b.lyLwlc.yDYNvb.W8l4ac')
29
+ res = '\n\n'.join([m.get_text() for m in main])
30
+ except Exception as ex:
31
+ print(f"Error: {ex}")
32
+ res = ""
33
+
34
+ print(f"The result of the google search is: {res}")
35
+
36
+ return res
37
+
38
+ PINECONE_API_KEY = os.environ.get("PINECONE_API_KEY")
39
+
40
+ sentencetransformer_model = SentenceTransformer('sentence-transformers/multi-qa-mpnet-base-cos-v1')
41
+ pinecone.init(api_key=PINECONE_API_KEY, environment="gcp-starter")
42
+
43
+
44
+ CACHE_DIR = "./.cache"
45
+ INDEX_NAME = "k8s-semantic-search"
46
+
47
+ if not os.path.exists(CACHE_DIR):
48
+ os.makedirs(CACHE_DIR)
49
+
50
+
51
+ def cached(func):
52
+ def wrapper(*args, **kwargs):
53
+ SEP = "$|$"
54
+ cache_token = (
55
+ f"{func.__name__}{SEP}"
56
+ f"{SEP.join(str(arg) for arg in args)}{SEP}"
57
+ f"{SEP.join( str(key) + SEP * 2 + str(val) for key, val in kwargs.items())}"
58
+ )
59
+
60
+ hex_hash = hashlib.sha256(cache_token.encode()).hexdigest()
61
+ cache_filename: str = os.path.join(CACHE_DIR, f"{hex_hash}")
62
 
63
+ if os.path.exists(cache_filename):
64
+ with open(cache_filename, "rb") as cache_file:
65
+ return pickle.load(cache_file)
66
 
67
+ result = func(*args, **kwargs)
68
+ with open(cache_filename, "wb") as cache_file:
69
+ pickle.dump(result, cache_file)
70
+
71
+ return result
72
+
73
+ return wrapper
74
+
75
+
76
+ @cached
77
+ def create_embedding(text: str):
78
+ embed_text = sentencetransformer_model.encode(text)
79
+
80
+ return embed_text.tolist()
81
+
82
+ index = pinecone.Index(INDEX_NAME)
83
 
 
84
 
85
  def query_from_pinecone(query, top_k=3):
86
+ embedding = create_embedding(query)
87
+ if not embedding:
88
+ return None
89
 
90
+ return index.query(vector=embedding, top_k=top_k, include_metadata=True).get("matches") # gets the metadata (text)
 
 
 
 
91
 
 
92
 
93
+ cross_encoder = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-12-v2")
94
+
95
+
96
+ def get_results_from_pinecone(query, top_k=3, re_rank=True, verbose=True):
97
  results_from_pinecone = query_from_pinecone(query, top_k=top_k)
98
  if not results_from_pinecone:
99
  return []
 
101
  if verbose:
102
  print("Query:", query)
103
 
 
104
  final_results = []
105
 
106
  if re_rank:
107
  if verbose:
108
+ print("Document ID (Hash)\t\tRetrieval Score\tCE Score\tText")
109
 
110
+ sentence_combinations = [
111
+ [query, result_from_pinecone["metadata"]["text"]] for result_from_pinecone in results_from_pinecone
112
+ ]
113
 
114
  # Compute the similarity scores for these combinations
115
  similarity_scores = cross_encoder.predict(sentence_combinations, activation_fct=nn.Sigmoid())
 
122
  result_from_pinecone = results_from_pinecone[idx]
123
  final_results.append(result_from_pinecone)
124
  if verbose:
125
+ print(
126
+ f"{result_from_pinecone['id']}\t{result_from_pinecone['score']:.2f}\t{similarity_scores[idx]:.2f}\t{result_from_pinecone['metadata']['text'][:50]}"
127
+ )
128
  return final_results
129
 
130
  if verbose:
131
+ print("Document ID (Hash)\t\tRetrieval Score\tText")
132
  for result_from_pinecone in results_from_pinecone:
133
  final_results.append(result_from_pinecone)
134
  if verbose:
135
+ print(
136
+ f"{result_from_pinecone['id']}\t{result_from_pinecone['score']:.2f}\t{result_from_pinecone['metadata']['text'][:50]}"
137
+ )
138
 
139
  return final_results
140
 
141
+
142
  def semantic_search(prompt):
143
  final_results = get_results_from_pinecone(prompt, top_k=9, re_rank=True, verbose=True)
144
+ if not final_results:
145
+ return ""
146
 
147
+ return "\n\n".join(res["metadata"]["text"].strip() for res in final_results[:3])
148
 
 
 
149
 
150
+ base_model_id = "mistralai/Mistral-7B-Instruct-v0.1"
151
+ lora_model_id = "ComponentSoft/mistral-kubectl-instruct"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
 
153
  tokenizer = AutoTokenizer.from_pretrained(
154
  lora_model_id,
 
159
  tokenizer.pad_token = tokenizer.eos_token
160
 
161
  bnb_config = BitsAndBytesConfig(
162
+ load_in_4bit=True, bnb_4bit_use_double_quant=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16
 
 
 
163
  )
164
 
165
  base_model = AutoModelForCausalLM.from_pretrained(
 
172
  model = PeftModel.from_pretrained(base_model, lora_model_id)
173
  model.eval()
174
 
 
 
175
 
176
+ def create_stop_criterion(*args):
177
+ term_tokens = [torch.tensor(tokenizer.encode(term, add_special_tokens=False)).to("cuda") for term in args]
178
+
179
+ class CustomStopCriterion(StoppingCriteria):
180
+ def __call__(self, input_ids: torch.LongTensor, score: torch.FloatTensor, **kwargs):
181
+ return any(torch.equal(e, input_ids[0][-len(e) :]) for e in term_tokens)
182
 
183
+ return CustomStopCriterion()
184
 
 
 
 
185
 
186
+ eval_stop_criterion = create_stop_criterion("</s>", "#End")
187
+ category_stop_criterion = create_stop_criterion("</s>", "\n")
188
 
189
+ start_template = "### Answer:"
190
+ command_template = "# Command:"
191
+ end_template = "#End"
192
 
 
 
 
193
 
194
+ def text_to_text_generation(verbose, prompt):
195
  prompt = prompt.strip()
 
196
 
197
  is_kubectl_prompt = (
198
+ f"You are a helpful assistant who classifies prompts into three categories. [INST] Respond with 0 if it pertains to a 'kubectl' operation. This is an instruction that can be answered with a 'kubectl' action. Look for keywords like 'get', 'list', 'create', 'show', 'view', and other command-like words. This category is an instruction instead of a question. Respond with 1 only if the prompt is a question, and is about a definition related to Kubernetes, or non-action inquiries. Respond with 2 every other scenario, for example if the question is a general question, not related to Kubernetes or 'kubectl'.\n"
199
  f"So for instance the following:\n"
200
+ f'text: "List all pods in Kubernetes"\n'
201
  f"Would get a response:\n"
202
+ f"response (0/1/2): 0 [/INST] \n"
203
  f'text: "{prompt}"'
204
+ f"response (0/1/2): "
205
  )
206
 
 
207
  model_input = tokenizer(is_kubectl_prompt, return_tensors="pt").to("cuda")
208
  with torch.no_grad():
209
+ response = tokenizer.decode(
210
+ model.generate(
211
+ **model_input,
212
+ max_new_tokens=8,
213
+ pad_token_id=tokenizer.eos_token_id,
214
+ repetition_penalty=1.15,
215
+ stopping_criteria=StoppingCriteriaList([category_stop_criterion]),
216
+ )[0],
217
+ skip_special_tokens=True,
218
+ )
219
+ response = response[len(is_kubectl_prompt) :]
220
+
221
+ print(f'{" Query Start ":-^40}')
222
+ print("Classified as: " + response)
223
+
224
+ response_num = 0 if "0" in response else (1 if "1" in response else 2)
225
+
226
+ def generate(response_num, prompt, retriever, verbose):
227
+ match response_num:
228
+ case 0:
229
+ prompt = f"[INST] {prompt}\n Lets think step by step. [/INST] {start_template}"
230
+
231
+ case 1:
232
+ if retriever == "semantic_search":
233
+ retrieved_results = semantic_search(prompt)
234
+ prompt = f"You are a helpful kubernetes professional. [INST] Use the following documentation, if it is relevant to answer the question below. [/INST]\nDocumentation: {retrieved_results} </s>\n<s> [INST] Answer the following question: {prompt} [/INST]\nAnswer: "
235
+ elif retriever == "google_search":
236
+ retrieved_results = google_search(prompt)
237
+ prompt = f"You are a helpful kubernetes professional. [INST] Use the following documentation, if it is relevant to answer the question below. [/INST]\nDocumentation: {retrieved_results} </s>\n<s> [INST] Answer the following question: {prompt} [/INST]\nAnswer: "
238
+ else:
239
+ prompt = f"[INST] Answer the following question: {prompt} [/INST]\nAnswer: "
240
+
241
+ case _:
242
+ prompt = f"[INST] {prompt} [/INST]"
243
+
244
+ print("Query:")
245
+ print(prompt)
246
+
247
+ # Generate output
248
+ model_input = tokenizer(prompt, return_tensors="pt").to("cuda")
249
+ with torch.no_grad():
250
+ response = tokenizer.decode(
251
+ model.generate(
252
+ **model_input,
253
+ max_new_tokens=256,
254
+ pad_token_id=tokenizer.eos_token_id,
255
+ repetition_penalty=1.15,
256
+ stopping_criteria=StoppingCriteriaList([eval_stop_criterion]),
257
+ )[0],
258
+ skip_special_tokens=True,
259
+ )
260
+
261
+ decoded_prompt = tokenizer.decode(tokenizer(prompt).input_ids, skip_special_tokens=True)
262
+
263
+ start = (
264
+ response.index(start_template) + len(start_template) if start_template in response else len(decoded_prompt)
265
+ )
266
+ start = response.index(command_template) + len(command_template) if command_template in response else start
267
+ end = response.index(end_template) if end_template in response else len(response)
268
+
269
+ return response if verbose else response[start:end].strip()
270
+
271
+ true_response = generate(response_num, prompt, False, verbose)
272
+ true_response_semantic_search = generate(response_num, prompt, "semantic_search", verbose)
273
+ true_response_google_search = generate(response_num, prompt, "google_search", verbose)
274
+
275
+
276
+ print("Returned: " + true_response)
277
+ print(f'{" QUERY END ":-^40}')
278
+
279
+ match response_num:
280
+ case 0:
281
+ mode = "Kubectl"
282
+ case 1:
283
+ mode = "Kubernetes"
284
+ case _:
285
+ mode = "Normal"
286
+
287
+ return (
288
+ f"*Mode*: {mode}",
289
+ f"# Answer\n\n {true_response}",
290
+ f"# Answer with RAG\n\n {true_response_semantic_search}",
291
+ f"# Answer with Google search\n\n {true_response_google_search}"
292
+ )
293
 
 
 
 
 
 
 
 
294
 
295
+ iface = gr.Interface(
296
+ fn=text_to_text_generation,
297
+ inputs=[
298
+ gr.components.Checkbox(label="Verbose"),
299
+ gr.components.Text(placeholder="prompt here ...", label="Prompt"),
300
+ ],
301
+ outputs=[
302
+ gr.components.Markdown(label="Mode"),
303
+ gr.components.Markdown(label="Answer Without Retriever"),
304
+ gr.components.Markdown(label="Answer With Retriever"),
305
+ gr.components.Markdown(label="Answer With Google search"),
306
+ ],
307
+ allow_flagging="never",
308
+ )
309
 
310
+ iface.launch()