plaggy commited on
Commit
fde33b3
1 Parent(s): 8af7d40

refactoring

Browse files
.env ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export TABLE_NAME=minilm_table
2
+ export EMB_MODEL=sentence-transformers/all-MiniLM-L6-v2
3
+ export TOP_K=5
4
+ export HF_MODEL=mistralai/Mistral-7B-Instruct-v0.2
5
+ export OPENAI_MODEL=gpt-4-turbo-preview
6
+
7
+ #### SECRETS ####
8
+ export OPENAI_API_KEY=
9
+ export HF_TOKEN=
10
+ ################
11
+
12
+ export TEMPERATURE=
13
+ export MAX_NEW_TOKENS=
14
+ export TOP_P=
15
+ export REP_PENALTY=
16
+ export DO_SAMPLE=
17
+ export FREQ_PENALTY=
18
+ export VECTOR_COLUMN=
19
+ export TEXT_COLUMN=
20
+ export BATCH_SIZE=
README.md CHANGED
@@ -1,12 +1,7 @@
1
- ---
2
- title: Test
3
- emoji: 🏃
4
- colorFrom: red
5
- colorTo: indigo
6
- sdk: gradio
7
- sdk_version: 4.16.0
8
- app_file: app.py
9
- pinned: false
10
- ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
1
+ ## A template for a RAG system with Gradio UI
2
+ Deliberately stripped down for the sake of an exercise.
 
 
 
 
 
 
 
 
3
 
4
+ For https://ydataschool.com/
5
+
6
+ ## Setup
7
+ Clone the repo and follow **rag-homework.ipynb**
gradio_app/app.py CHANGED
@@ -1,11 +1,7 @@
1
  """
2
  Credit to Derek Thomas, derek@huggingface.co
3
  """
4
-
5
- import subprocess
6
-
7
- subprocess.run(["pip", "install", "--upgrade", "transformers[torch,sentencepiece]==4.34.1"])
8
-
9
  import logging
10
  from pathlib import Path
11
  from time import perf_counter
@@ -14,10 +10,10 @@ import gradio as gr
14
  from jinja2 import Environment, FileSystemLoader
15
 
16
  from backend.query_llm import generate_hf, generate_openai
17
- from backend.semantic_search import table, retriever
18
 
19
- VECTOR_COLUMN_NAME = ""
20
- TEXT_COLUMN_NAME = ""
21
 
22
  proj_dir = Path(__file__).parent
23
  # Setting up the logging
@@ -31,11 +27,6 @@ env = Environment(loader=FileSystemLoader(proj_dir / 'templates'))
31
  template = env.get_template('template.j2')
32
  template_html = env.get_template('template_html.j2')
33
 
34
- # Examples
35
- examples = ['What is the capital of China?',
36
- 'Why is the sky blue?',
37
- 'Who won the mens world cup in 2014?', ]
38
-
39
 
40
  def add_text(history, text):
41
  history = [] if history is None else history
@@ -44,23 +35,19 @@ def add_text(history, text):
44
 
45
 
46
  def bot(history, api_kind):
47
- top_k_rank = 4
48
  query = history[-1][0]
49
 
50
  if not query:
51
- gr.Warning("Please submit a non-empty string as a prompt")
52
- raise ValueError("Empty string was submitted")
53
 
54
- logger.warning('Retrieving documents...')
55
  # Retrieve documents relevant to query
56
  document_start = perf_counter()
57
 
58
- query_vec = retriever.encode(query)
59
- documents = table.search(query_vec, vector_column_name=VECTOR_COLUMN_NAME).limit(top_k_rank).to_list()
60
- documents = [doc[TEXT_COLUMN_NAME] for doc in documents]
61
 
62
  document_time = perf_counter() - document_start
63
- logger.warning(f'Finished Retrieving documents in {round(document_time, 2)} seconds...')
64
 
65
  # Create Prompt
66
  prompt = template.render(documents=documents, query=query)
@@ -70,12 +57,8 @@ def bot(history, api_kind):
70
  generate_fn = generate_hf
71
  elif api_kind == "OpenAI":
72
  generate_fn = generate_openai
73
- elif api_kind is None:
74
- gr.Warning("API name was not provided")
75
- raise ValueError("API name was not provided")
76
  else:
77
- gr.Warning(f"API {api_kind} is not supported")
78
- raise ValueError(f"API {api_kind} is not supported")
79
 
80
  history[-1][1] = ""
81
  for character in generate_fn(prompt, history[:-1]):
@@ -120,8 +103,5 @@ with gr.Blocks() as demo:
120
  # Turn it back on
121
  txt_msg.then(lambda: gr.Textbox(interactive=True), None, [txt], queue=False)
122
 
123
- # Examples
124
- gr.Examples(examples, txt)
125
-
126
  demo.queue()
127
  demo.launch(debug=True)
 
1
  """
2
  Credit to Derek Thomas, derek@huggingface.co
3
  """
4
+ import os
 
 
 
 
5
  import logging
6
  from pathlib import Path
7
  from time import perf_counter
 
10
  from jinja2 import Environment, FileSystemLoader
11
 
12
  from backend.query_llm import generate_hf, generate_openai
13
+ from backend.semantic_search import retrieve
14
 
15
+
16
+ TOP_K = int(os.getenv("TOP_K", 4))
17
 
18
  proj_dir = Path(__file__).parent
19
  # Setting up the logging
 
27
  template = env.get_template('template.j2')
28
  template_html = env.get_template('template_html.j2')
29
 
 
 
 
 
 
30
 
31
  def add_text(history, text):
32
  history = [] if history is None else history
 
35
 
36
 
37
  def bot(history, api_kind):
 
38
  query = history[-1][0]
39
 
40
  if not query:
41
+ raise gr.Warning("Please submit a non-empty string as a prompt")
 
42
 
43
+ logger.info('Retrieving documents...')
44
  # Retrieve documents relevant to query
45
  document_start = perf_counter()
46
 
47
+ documents = retrieve(query, TOP_K)
 
 
48
 
49
  document_time = perf_counter() - document_start
50
+ logger.info(f'Finished Retrieving documents in {round(document_time, 2)} seconds...')
51
 
52
  # Create Prompt
53
  prompt = template.render(documents=documents, query=query)
 
57
  generate_fn = generate_hf
58
  elif api_kind == "OpenAI":
59
  generate_fn = generate_openai
 
 
 
60
  else:
61
+ raise gr.Error(f"API {api_kind} is not supported")
 
62
 
63
  history[-1][1] = ""
64
  for character in generate_fn(prompt, history[:-1]):
 
103
  # Turn it back on
104
  txt_msg.then(lambda: gr.Textbox(interactive=True), None, [txt], queue=False)
105
 
 
 
 
106
  demo.queue()
107
  demo.launch(debug=True)
gradio_app/backend/__pycache__/query_llm.cpython-310.pyc CHANGED
Binary files a/gradio_app/backend/__pycache__/query_llm.cpython-310.pyc and b/gradio_app/backend/__pycache__/query_llm.cpython-310.pyc differ
 
gradio_app/backend/__pycache__/semantic_search.cpython-310.pyc CHANGED
Binary files a/gradio_app/backend/__pycache__/semantic_search.cpython-310.pyc and b/gradio_app/backend/__pycache__/semantic_search.cpython-310.pyc differ
 
gradio_app/backend/query_llm.py CHANGED
@@ -1,25 +1,37 @@
1
  import openai
2
  import gradio as gr
 
3
 
4
- from os import getenv
5
  from typing import Any, Dict, Generator, List
6
 
7
  from huggingface_hub import InferenceClient
8
  from transformers import AutoTokenizer
9
 
10
- tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.1")
11
 
12
- temperature = 0.9
13
- top_p = 0.6
14
- repetition_penalty = 1.2
15
 
16
- OPENAI_KEY = getenv("OPENAI_API_KEY")
17
- HF_TOKEN = getenv("HUGGING_FACE_HUB_TOKEN")
 
 
 
18
 
19
- hf_client = InferenceClient(
20
- "mistralai/Mistral-7B-Instruct-v0.1",
21
- token=HF_TOKEN
22
- )
 
 
 
 
 
 
 
 
 
 
23
 
24
 
25
  def format_prompt(message: str, api_kind: str):
@@ -28,7 +40,7 @@ def format_prompt(message: str, api_kind: str):
28
 
29
  Args:
30
  message (str): The user message to be formatted.
31
-
32
  Returns:
33
  str: Formatted message after applying the chat template.
34
  """
@@ -39,46 +51,34 @@ def format_prompt(message: str, api_kind: str):
39
  if api_kind == "openai":
40
  return messages
41
  elif api_kind == "hf":
42
- return tokenizer.apply_chat_template(messages, tokenize=False)
43
  elif api_kind:
44
  raise ValueError("API is not supported")
45
 
46
 
47
- def generate_hf(prompt: str, history: str, temperature: float = 0.9, max_new_tokens: int = 256,
48
- top_p: float = 0.95, repetition_penalty: float = 1.0) -> Generator[str, None, str]:
49
  """
50
  Generate a sequence of tokens based on a given prompt and history using Mistral client.
51
 
52
  Args:
53
- prompt (str): The initial prompt for the text generation.
54
  history (str): Context or history for the text generation.
55
- temperature (float, optional): The softmax temperature for sampling. Defaults to 0.9.
56
- max_new_tokens (int, optional): Maximum number of tokens to be generated. Defaults to 256.
57
- top_p (float, optional): Nucleus sampling probability. Defaults to 0.95.
58
- repetition_penalty (float, optional): Penalty for repeated tokens. Defaults to 1.0.
59
-
60
  Returns:
61
  Generator[str, None, str]: A generator yielding chunks of generated text.
62
  Returns a final string if an error occurs.
63
  """
64
 
65
- temperature = max(float(temperature), 1e-2) # Ensure temperature isn't too low
66
- top_p = float(top_p)
67
-
68
- generate_kwargs = {
69
- 'temperature': temperature,
70
- 'max_new_tokens': max_new_tokens,
71
- 'top_p': top_p,
72
- 'repetition_penalty': repetition_penalty,
73
- 'do_sample': True,
74
- 'seed': 42,
75
- }
76
-
77
  formatted_prompt = format_prompt(prompt, "hf")
 
78
 
79
  try:
80
- stream = hf_client.text_generation(formatted_prompt, **generate_kwargs,
81
- stream=True, details=True, return_full_text=False)
 
 
 
 
 
82
  output = ""
83
  for response in stream:
84
  output += response.token.text
@@ -86,69 +86,43 @@ def generate_hf(prompt: str, history: str, temperature: float = 0.9, max_new_tok
86
 
87
  except Exception as e:
88
  if "Too Many Requests" in str(e):
89
- print("ERROR: Too many requests on Mistral client")
90
- gr.Warning("Unfortunately Mistral is unable to process")
91
- return "Unfortunately, I am not able to process your request now."
92
  elif "Authorization header is invalid" in str(e):
93
- print("Authetification error:", str(e))
94
- gr.Warning("Authentication error: HF token was either not provided or incorrect")
95
- return "Authentication error"
96
  else:
97
- print("Unhandled Exception:", str(e))
98
- gr.Warning("Unfortunately Mistral is unable to process")
99
- return "I do not know what happened, but I couldn't understand you."
100
 
101
 
102
- def generate_openai(prompt: str, history: str, temperature: float = 0.9, max_new_tokens: int = 256,
103
- top_p: float = 0.95, repetition_penalty: float = 1.0) -> Generator[str, None, str]:
104
  """
105
  Generate a sequence of tokens based on a given prompt and history using Mistral client.
106
 
107
  Args:
108
  prompt (str): The initial prompt for the text generation.
109
  history (str): Context or history for the text generation.
110
- temperature (float, optional): The softmax temperature for sampling. Defaults to 0.9.
111
- max_new_tokens (int, optional): Maximum number of tokens to be generated. Defaults to 256.
112
- top_p (float, optional): Nucleus sampling probability. Defaults to 0.95.
113
- repetition_penalty (float, optional): Penalty for repeated tokens. Defaults to 1.0.
114
-
115
  Returns:
116
  Generator[str, None, str]: A generator yielding chunks of generated text.
117
  Returns a final string if an error occurs.
118
  """
119
-
120
- temperature = max(float(temperature), 1e-2) # Ensure temperature isn't too low
121
- top_p = float(top_p)
122
-
123
- generate_kwargs = {
124
- 'temperature': temperature,
125
- 'max_tokens': max_new_tokens,
126
- 'top_p': top_p,
127
- 'frequency_penalty': max(-2., min(repetition_penalty, 2.)),
128
- }
129
-
130
  formatted_prompt = format_prompt(prompt, "openai")
131
 
132
  try:
133
- stream = openai.ChatCompletion.create(model="gpt-3.5-turbo-0301",
134
- messages=formatted_prompt,
135
- **generate_kwargs,
136
- stream=True)
 
 
137
  output = ""
138
  for chunk in stream:
139
- output += chunk.choices[0].delta.get("content", "")
140
- yield output
 
141
 
142
  except Exception as e:
143
  if "Too Many Requests" in str(e):
144
- print("ERROR: Too many requests on OpenAI client")
145
- gr.Warning("Unfortunately OpenAI is unable to process")
146
- return "Unfortunately, I am not able to process your request now."
147
  elif "You didn't provide an API key" in str(e):
148
- print("Authetification error:", str(e))
149
- gr.Warning("Authentication error: OpenAI key was either not provided or incorrect")
150
- return "Authentication error"
151
  else:
152
- print("Unhandled Exception:", str(e))
153
- gr.Warning("Unfortunately OpenAI is unable to process")
154
- return "I do not know what happened, but I couldn't understand you."
 
1
  import openai
2
  import gradio as gr
3
+ import os
4
 
 
5
  from typing import Any, Dict, Generator, List
6
 
7
  from huggingface_hub import InferenceClient
8
  from transformers import AutoTokenizer
9
 
 
10
 
11
+ OPENAI_KEY = os.getenv("OPENAI_API_KEY")
12
+ HF_TOKEN = os.getenv("HF_TOKEN")
13
+ TOKENIZER = AutoTokenizer.from_pretrained(os.getenv("HF_MODEL"))
14
 
15
+ HF_CLIENT = InferenceClient(
16
+ os.getenv("HF_MODEL"),
17
+ token=HF_TOKEN
18
+ )
19
+ OAI_CLIENT = openai.Client(api_key=OPENAI_KEY)
20
 
21
+ HF_GENERATE_KWARGS = {
22
+ 'temperature': max(float(os.getenv("TEMPERATURE", 0.9)), 1e-2),
23
+ 'max_new_tokens': int(os.getenv("MAX_NEW_TOKENS", 256)),
24
+ 'top_p': float(os.getenv("TOP_P", 0.6)),
25
+ 'repetition_penalty': float(os.getenv("REP_PENALTY", 1.2)),
26
+ 'do_sample': bool(os.getenv("DO_SAMPLE", True))
27
+ }
28
+
29
+ OAI_GENERATE_KWARGS = {
30
+ 'temperature': max(float(os.getenv("TEMPERATURE", 0.9)), 1e-2),
31
+ 'max_tokens': int(os.getenv("MAX_NEW_TOKENS", 256)),
32
+ 'top_p': float(os.getenv("TOP_P", 0.6)),
33
+ 'frequency_penalty': max(-2, min(float(os.getenv("FREQ_PENALTY", 0)), 2))
34
+ }
35
 
36
 
37
  def format_prompt(message: str, api_kind: str):
 
40
 
41
  Args:
42
  message (str): The user message to be formatted.
43
+ api_kind (str): LLM API provider.
44
  Returns:
45
  str: Formatted message after applying the chat template.
46
  """
 
51
  if api_kind == "openai":
52
  return messages
53
  elif api_kind == "hf":
54
+ return TOKENIZER.apply_chat_template(messages, tokenize=False)
55
  elif api_kind:
56
  raise ValueError("API is not supported")
57
 
58
 
59
+ def generate_hf(prompt: str, history: str) -> Generator[str, None, str]:
 
60
  """
61
  Generate a sequence of tokens based on a given prompt and history using Mistral client.
62
 
63
  Args:
64
+ prompt (str): The prompt for the text generation.
65
  history (str): Context or history for the text generation.
 
 
 
 
 
66
  Returns:
67
  Generator[str, None, str]: A generator yielding chunks of generated text.
68
  Returns a final string if an error occurs.
69
  """
70
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  formatted_prompt = format_prompt(prompt, "hf")
72
+ formatted_prompt = formatted_prompt.encode("utf-8").decode("utf-8")
73
 
74
  try:
75
+ stream = HF_CLIENT.text_generation(
76
+ formatted_prompt,
77
+ **HF_GENERATE_KWARGS,
78
+ stream=True,
79
+ details=True,
80
+ return_full_text=False
81
+ )
82
  output = ""
83
  for response in stream:
84
  output += response.token.text
 
86
 
87
  except Exception as e:
88
  if "Too Many Requests" in str(e):
89
+ raise gr.Error(f"Too many requests: {str(e)}")
 
 
90
  elif "Authorization header is invalid" in str(e):
91
+ raise gr.Error("Authentication error: HF token was either not provided or incorrect")
 
 
92
  else:
93
+ raise gr.Error(f"Unhandled Exception: {str(e)}")
 
 
94
 
95
 
96
+ def generate_openai(prompt: str, history: str) -> Generator[str, None, str]:
 
97
  """
98
  Generate a sequence of tokens based on a given prompt and history using Mistral client.
99
 
100
  Args:
101
  prompt (str): The initial prompt for the text generation.
102
  history (str): Context or history for the text generation.
 
 
 
 
 
103
  Returns:
104
  Generator[str, None, str]: A generator yielding chunks of generated text.
105
  Returns a final string if an error occurs.
106
  """
 
 
 
 
 
 
 
 
 
 
 
107
  formatted_prompt = format_prompt(prompt, "openai")
108
 
109
  try:
110
+ stream = OAI_CLIENT.chat.completions.create(
111
+ model=os.getenv("OPENAI_MODEL"),
112
+ messages=formatted_prompt,
113
+ **OAI_GENERATE_KWARGS,
114
+ stream=True
115
+ )
116
  output = ""
117
  for chunk in stream:
118
+ if chunk.choices[0].delta.content:
119
+ output += chunk.choices[0].delta.content
120
+ yield output
121
 
122
  except Exception as e:
123
  if "Too Many Requests" in str(e):
124
+ raise gr.Error("ERROR: Too many requests on OpenAI client")
 
 
125
  elif "You didn't provide an API key" in str(e):
126
+ raise gr.Error("Authentication error: OpenAI key was either not provided or incorrect")
 
 
127
  else:
128
+ raise gr.Error(f"Unhandled Exception: {str(e)}")
 
 
gradio_app/backend/semantic_search.py CHANGED
@@ -1,18 +1,26 @@
1
- import logging
2
  import lancedb
3
  import os
4
- from pathlib import Path
5
  from sentence_transformers import SentenceTransformer
6
 
7
- EMB_MODEL_NAME = ""
8
- DB_TABLE_NAME = ""
9
 
10
- # Setting up the logging
11
- logging.basicConfig(level=logging.INFO)
12
- logger = logging.getLogger(__name__)
13
- retriever = SentenceTransformer(EMB_MODEL_NAME)
14
 
15
- # db
16
- db_uri = os.path.join(Path(__file__).parents[1], ".lancedb")
17
- db = lancedb.connect(db_uri)
18
- table = db.open_table(DB_TABLE_NAME)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import lancedb
2
  import os
3
+ import gradio as gr
4
  from sentence_transformers import SentenceTransformer
5
 
 
 
6
 
7
+ db = lancedb.connect(".lancedb")
 
 
 
8
 
9
+ TABLE = db.open_table(os.getenv("TABLE_NAME"))
10
+ VECTOR_COLUMN = os.getenv("VECTOR_COLUMN", "vector")
11
+ TEXT_COLUMN = os.getenv("TEXT_COLUMN", "text")
12
+ BATCH_SIZE = int(os.getenv("BATCH_SIZE", 32))
13
+
14
+ retriever = SentenceTransformer(os.getenv("EMB_MODEL"))
15
+
16
+
17
+ def retrieve(query, k):
18
+ query_vec = retriever.encode(query)
19
+ try:
20
+ documents = TABLE.search(query_vec, vector_column_name=VECTOR_COLUMN).limit(k).to_list()
21
+ documents = [doc[TEXT_COLUMN] for doc in documents]
22
+
23
+ return documents
24
+
25
+ except Exception as e:
26
+ raise gr.Error(str(e))
gradio_app/requirements.txt CHANGED
@@ -1,9 +1,7 @@
1
- # transformers[torch,sentencepiece]==4.34.1
2
- wikiextractor==3.0.6
3
- sentence-transformers>2.2.0
4
- ipywidgets==8.1.1
5
  tqdm==4.66.1
6
- aiohttp==3.8.6
7
- huggingface-hub==0.17.3
8
- lancedb==0.3.1
9
- openai==0.28
 
1
+ lancedb==0.5.3
2
+ openai==1.11.1
3
+ sentence-transformers==2.3.1
 
4
  tqdm==4.66.1
5
+ torch==2.1.1
6
+ transformers==4.37.2
7
+
 
prep_scripts/lancedb_setup.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import lancedb
2
  import torch
3
  import pyarrow as pa
@@ -5,61 +6,91 @@ import pandas as pd
5
  from pathlib import Path
6
  import tqdm
7
  import numpy as np
 
8
 
 
9
  from sentence_transformers import SentenceTransformer
10
 
 
 
11
 
12
- EMB_MODEL_NAME = ""
13
- DB_TABLE_NAME = ""
14
- VECTOR_COLUMN_NAME = ""
15
- TEXT_COLUMN_NAME = ""
16
- INPUT_DIR = "<chunked docs directory>"
17
- db = lancedb.connect(".lancedb") # db location
18
- batch_size = 32
19
-
20
- model = SentenceTransformer(EMB_MODEL_NAME)
21
- model.eval()
22
-
23
- if torch.backends.mps.is_available():
24
- device = "mps"
25
- elif torch.cuda.is_available():
26
- device = "cuda"
27
- else:
28
- device = "cpu"
29
-
30
- schema = pa.schema(
31
- [
32
- pa.field(VECTOR_COLUMN_NAME, pa.list_(pa.float32(), 768)),
33
- pa.field(TEXT_COLUMN_NAME, pa.string())
34
- ])
35
- tbl = db.create_table(DB_TABLE_NAME, schema=schema, mode="overwrite")
36
-
37
- input_dir = Path(INPUT_DIR)
38
- files = list(input_dir.rglob("*"))
39
-
40
- sentences = []
41
- for file in files:
42
- with open(file) as f:
43
- sentences.append(f.read())
44
-
45
- for i in tqdm.tqdm(range(0, int(np.ceil(len(sentences) / batch_size)))):
46
- try:
47
- batch = [sent for sent in sentences[i * batch_size:(i + 1) * batch_size] if len(sent) > 0]
48
- encoded = model.encode(batch, normalize_embeddings=True, device=device)
49
- encoded = [list(vec) for vec in encoded]
50
-
51
- df = pd.DataFrame({
52
- VECTOR_COLUMN_NAME: encoded,
53
- TEXT_COLUMN_NAME: batch
54
- })
55
-
56
- tbl.add(df)
57
- except:
58
- print(f"batch {i} was skipped")
59
-
60
- '''
61
- create ivf-pd index https://lancedb.github.io/lancedb/ann_indexes/
62
- with the size of the transformer docs, index is not really needed
63
- but we'll do it for demonstrational purposes
64
- '''
65
- tbl.create_index(num_partitions=256, num_sub_vectors=96, vector_column_name=VECTOR_COLUMN_NAME)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
  import lancedb
3
  import torch
4
  import pyarrow as pa
 
6
  from pathlib import Path
7
  import tqdm
8
  import numpy as np
9
+ import logging
10
 
11
+ from transformers import AutoConfig
12
  from sentence_transformers import SentenceTransformer
13
 
14
+ logging.basicConfig(level=logging.INFO)
15
+ logger = logging.getLogger(__name__)
16
 
17
+
18
+ def main():
19
+ parser = argparse.ArgumentParser()
20
+ parser.add_argument("--emb-model", help="embedding model name on HF hub", type=str)
21
+ parser.add_argument("--table", help="table name in DB", type=str)
22
+ parser.add_argument("--input-dir", help="input directory with documents to ingest", type=str)
23
+ parser.add_argument("--vec-column", help="vector column name in the table", type=str, default="vector")
24
+ parser.add_argument("--text-column", help="text column name in the table", type=str, default="text")
25
+ parser.add_argument("--db-loc", help="database location", type=str,
26
+ default=str(Path().resolve() / "gradio_app" / ".lancedb"))
27
+ parser.add_argument("--batch-size", help="batch size for embedding model", type=int, default=32)
28
+ parser.add_argument("--num-partitions", help="number of partitions for index", type=int, default=256)
29
+ parser.add_argument("--num-sub-vectors", help="number of sub-vectors for index", type=int, default=96)
30
+
31
+ args = parser.parse_args()
32
+
33
+ emb_config = AutoConfig.from_pretrained(args.emb_model)
34
+ emb_dimension = emb_config.hidden_size
35
+
36
+ assert emb_dimension % args.num_sub_vectors == 0, \
37
+ "Embedding size must be divisible by the num of sub vectors"
38
+
39
+ model = SentenceTransformer(args.emb_model)
40
+ model.eval()
41
+
42
+ if torch.backends.mps.is_available():
43
+ device = "mps"
44
+ elif torch.cuda.is_available():
45
+ device = "cuda"
46
+ else:
47
+ device = "cpu"
48
+ logger.info(f"using {str(device)} device")
49
+
50
+ db = lancedb.connect(args.db_loc)
51
+
52
+ schema = pa.schema(
53
+ [
54
+ pa.field(args.vec_column, pa.list_(pa.float32(), emb_dimension)),
55
+ pa.field(args.text_column, pa.string())
56
+ ]
57
+ )
58
+ tbl = db.create_table(args.table, schema=schema, mode="overwrite")
59
+
60
+ input_dir = Path(args.input_dir)
61
+ files = list(input_dir.rglob("*"))
62
+
63
+ sentences = []
64
+ for file in files:
65
+ with open(file) as f:
66
+ sentences.append(f.read())
67
+
68
+ for i in tqdm.tqdm(range(0, int(np.ceil(len(sentences) / args.batch_size)))):
69
+ try:
70
+ batch = [sent for sent in sentences[i * args.batch_size:(i + 1) * args.batch_size] if len(sent) > 0]
71
+ encoded = model.encode(batch, normalize_embeddings=True, device=device)
72
+ encoded = [list(vec) for vec in encoded]
73
+
74
+ df = pd.DataFrame({
75
+ args.vec_column: encoded,
76
+ args.text_column: batch
77
+ })
78
+
79
+ tbl.add(df)
80
+ except:
81
+ logger.info(f"batch {i} was skipped")
82
+
83
+ '''
84
+ create ivf-pd index https://lancedb.github.io/lancedb/ann_indexes/
85
+ with the size of the transformer docs, index is not really needed
86
+ but we'll do it for demonstrational purposes
87
+ '''
88
+ tbl.create_index(
89
+ num_partitions=args.num_partitions,
90
+ num_sub_vectors=args.num_sub_vectors,
91
+ vector_column_name=args.vec_column
92
+ )
93
+
94
+
95
+ if __name__ == "__main__":
96
+ main()
prep_scripts/markdown_to_text.py CHANGED
@@ -1,12 +1,11 @@
1
- from bs4 import BeautifulSoup
2
- from markdown import markdown
3
  import os
4
  import re
5
- from pathlib import Path
6
 
7
-
8
- DIR_TO_SCRAPE = "transformers/docs/source/en/"
9
- OUTPUT_DIR = str(Path().resolve() / "docs_dump")
 
10
 
11
 
12
  def markdown_to_text(markdown_string):
@@ -31,19 +30,33 @@ def markdown_to_text(markdown_string):
31
  return text
32
 
33
 
34
- dir_to_scrape = Path(DIR_TO_SCRAPE)
35
- files = list(dir_to_scrape.rglob("*"))
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
- os.makedirs(OUTPUT_DIR, exist_ok=True)
 
 
 
 
38
 
39
- for file in files:
40
- parent = file.parent.stem if file.parent.stem != dir_to_scrape.stem else ""
41
- if file.is_file():
42
- with open(file) as f:
43
- md = f.read()
44
 
45
- text = markdown_to_text(md)
 
46
 
47
- with open(os.path.join(OUTPUT_DIR, f"{parent}_{file.stem}.txt"), "w") as f:
48
- f.write(text)
49
 
 
 
 
1
+ import argparse
 
2
  import os
3
  import re
 
4
 
5
+ from tqdm import tqdm
6
+ from bs4 import BeautifulSoup
7
+ from markdown import markdown
8
+ from pathlib import Path
9
 
10
 
11
  def markdown_to_text(markdown_string):
 
30
  return text
31
 
32
 
33
+ def main():
34
+ parser = argparse.ArgumentParser()
35
+ parser.add_argument("--input-dir", help="input directory with markdown", type=str,
36
+ default="transformers/docs/source/en/")
37
+ parser.add_argument("--output-dir", help="output directory to store raw texts", type=str,
38
+ default="docs")
39
+
40
+ args = parser.parse_args()
41
+ input_dir = Path(args.input_dir)
42
+ output_dir = Path(args.output_dir)
43
+
44
+ assert os.path.isdir(input_dir), "Input directory doesn't exist"
45
+
46
+ files = input_dir.rglob("*")
47
+ os.makedirs(output_dir, exist_ok=True)
48
 
49
+ for file in tqdm(files):
50
+ parent = file.parent.stem if file.parent.stem != input_dir.stem else ""
51
+ if file.is_file():
52
+ with open(file) as f:
53
+ md = f.read()
54
 
55
+ text = markdown_to_text(md)
 
 
 
 
56
 
57
+ with open(output_dir / f"{parent}_{file.stem}.txt", "w") as f:
58
+ f.write(text)
59
 
 
 
60
 
61
+ if __name__ == "__main__":
62
+ main()
rag-homework.ipynb ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "844fe3af-9cf1-4c66-aa78-b88a3429acc6",
6
+ "metadata": {},
7
+ "source": [
8
+ "### 0. Setup\n",
9
+ "- Clone https://github.com/plaggy/rag-gradio-sample-project and set up an environment with gradio_app/requirements.txt.\n",
10
+ "\n",
11
+ "A convenient way to work through the project is to test locally and keep committing the changes to the [HF Spaces](https://huggingface.co/spaces) repo. A space gets automatically rebuilt after each commit and you get a new version of your application up and running.\n",
12
+ "\n",
13
+ "- Create a new space with Gradio SDK. You'll get an almost empty repo, the only thing you'll need from it is README.md which has a config letting a space builder know that it's a Gradio app. Reset a remote upstream of your local rag-gradio-sample-project clone to be your freshly created Spaces repository.\n",
14
+ "\n",
15
+ "The easiest way to set your space up is to set up the gradio_app folder as a git repo, set remote origin to your space repo and checkout the remote README:\n",
16
+ "\n",
17
+ "```\n",
18
+ "cd gradio_app\n",
19
+ "git init\n",
20
+ "git remote add origin <your spaces repo url>\n",
21
+ "git fetch\n",
22
+ "git checkout origin/main README.md\n",
23
+ "```\n",
24
+ "\n",
25
+ "The space is not working yet. You'll get the first working version after the Step 3.\n",
26
+ "\n",
27
+ "- Clone https://github.com/huggingface/transformers to a local machine and run prep_scripts/markdown_to_text.py script to extract raw text from transformers/docs/source/en/. This will be your knowledge base, you don't need it to be a part of your repository\n",
28
+ "\n",
29
+ "Run the command as follows (pass arguments that work for you)\n",
30
+ "```\n",
31
+ "python prep_scripts/markdown_to_text.py --input-dir transformers/docs/source/en/ --output-dir docs\n",
32
+ "```\n"
33
+ ]
34
+ },
35
+ {
36
+ "cell_type": "markdown",
37
+ "id": "762e9fde-c1f4-464c-b12b-dca602fac5ba",
38
+ "metadata": {},
39
+ "source": [
40
+ "**By design, you'll be running your experiments in a [Gradio space](https://huggingface.co/docs/hub/en/spaces-sdks-gradio). Apart from deliverables for each step you'll need to provide a link to a functioning RAG space in it final state!**"
41
+ ]
42
+ },
43
+ {
44
+ "cell_type": "code",
45
+ "execution_count": 1,
46
+ "id": "6c813d03-33a7-4ce1-836f-11afc541f291",
47
+ "metadata": {},
48
+ "outputs": [],
49
+ "source": [
50
+ "# Add the link to the space you've just created here:"
51
+ ]
52
+ },
53
+ {
54
+ "cell_type": "markdown",
55
+ "id": "c970d0a4-fee8-48ac-9377-4a6def7712b2",
56
+ "metadata": {},
57
+ "source": [
58
+ "### Step 1: Chunk Your Data\n",
59
+ "\n",
60
+ "To efficiently pull up documents relevant to a query from a knowledge base documents are embedded and stored as vectors. Documents in your knowledge base are not expected to fit into the context length of an embedding model (most have 512 token limit). Hence chunking your documents into smaller pieces is required. Take a deeper dive into why chunking is imoprtant and what are the options [here](https://www.pinecone.io/learn/chunking-strategies/).\n",
61
+ "\n",
62
+ "Your task is to implement and compare two chunking strategies: fixed-sized chunking and content-aware chunking. For content-aware you could split by sentences, paragraphs or in some other way that makes sence.\n",
63
+ "\n",
64
+ "The deliverables are:\n",
65
+ "\n",
66
+ "1. The code for chunk splitting\n",
67
+ "2. The illustrative examples of how retrived chunks differ depending on the chunking strategy.\n",
68
+ "3. The analysis of pros and cons of each strategy\n"
69
+ ]
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "execution_count": null,
74
+ "id": "f7bad8c8",
75
+ "metadata": {},
76
+ "outputs": [],
77
+ "source": [
78
+ "# chunk splitting"
79
+ ]
80
+ },
81
+ {
82
+ "cell_type": "markdown",
83
+ "id": "5e5ebaad-8d42-430c-b00b-18198cdb9ce8",
84
+ "metadata": {},
85
+ "source": [
86
+ "### Step 2: Ingest chunks into a database and create an index\n",
87
+ "\n",
88
+ "Chunks need to be vectorized and made accessible to an LLM to enable semantic search with embedding models. A current industry standard is to use a vector database to store and retrieve texts both conveniently and efficiently. There are many products out there, we'll be using [LanceDB](https://lancedb.github.io/lancedb/). LanceDB is a young product, one way it stands out is that it's embedded - it's designed not to be a standalone service but rather a part of an application, more on this [here](https://lancedb.github.io/lancedb/basic/).\n",
89
+ "\n",
90
+ "Your task is to vectorize and ingest chunked documents into the database. Use prep_scrips/lancedb_setup.py to vectorize chunks and store vector representations along with raw text in a Lancedb instance. The script also creates an index for fast ANN retrieval (not really needed for this exercise but necessary at scale). Try different embedding models and see how results differ. The options are:\n",
91
+ "\n",
92
+ "- `sentence-transformers/all-MiniLM-L6-v2`: a light model, produces vectors of length 384\n",
93
+ "- `BAAI/bge-large-en-v1.5`: a much heavier model, embedding vector length is 1024\n",
94
+ "\n",
95
+ "Feel free to explore other embedding models and justify your choice.\n",
96
+ "For different embedding model create different tables in the database so you can easily switch between them and compare.\n",
97
+ "\n",
98
+ "Run the embedding+ingestion script as follows, make sure to look into the script and see all the arguments. Note that the number of sub-vectors for indexing must be a divisor of the model embedding size.\n",
99
+ "\n",
100
+ "```\n",
101
+ "python prep_scrips/lancedb_setup.py --emb-model <model name> --table <db table name> --input-dir <folder with docs> --num-sub-vectors <a number which is a divisor of the embedding dim>\n",
102
+ "```\n",
103
+ "\n",
104
+ "Before committing to your space set up environment variables on the settings tab of your space, use `.env` as a ference list of all the things you can customize. Make sure to add HF_TOKEN and OPENAI_API_KEY as secrets.\n",
105
+ "Not all the parameters are required to set via environment variables, most have default values.\n",
106
+ "\n",
107
+ "!!The database is expected to be in the `gradio_app` folder under `.lancedb`, make sure to move it there if was initialized elsewhere. It can be parametrized but it's unnecessary here.\n",
108
+ "\n",
109
+ "To commit large files to Github use `git lfs`:\n",
110
+ "```\n",
111
+ "git lfs install\n",
112
+ "git lfs track \"*.lance\"\n",
113
+ "git lfs track \"*.idx\"\n",
114
+ "git add .gitattributes\n",
115
+ "```\n",
116
+ "Then proceed as usual.\n",
117
+ "\n",
118
+ "For experimenting you can easily switch between embedding models/tables by changing the values of the corresponding env variables in your space (EMB_MODEL, TABLE_NAME). Overall, every time you change the value of an environment variable a space gets automatically rebuilt.\n",
119
+ "\n",
120
+ "The deliverables are:\n",
121
+ "1. The illustration of how retrieved documents differ depending on the embedding model\n",
122
+ "2. The analysis of how the embedding time differs between models\n"
123
+ ]
124
+ },
125
+ {
126
+ "cell_type": "code",
127
+ "execution_count": null,
128
+ "id": "f7db282e-e03c-41de-9c03-54abf455481f",
129
+ "metadata": {},
130
+ "outputs": [],
131
+ "source": [
132
+ "# Embed documents and ingest into the database "
133
+ ]
134
+ },
135
+ {
136
+ "cell_type": "markdown",
137
+ "id": "c929fe99-7f3f-49cf-af9f-07bac9668c2f",
138
+ "metadata": {},
139
+ "source": [
140
+ "### Step 3: DB retrieval\n",
141
+ "\n",
142
+ "To augment an LLM with a knowledge base the context provided in a prompt is enriched with relevant pieces from a DB. An incoming query is vectorized with an embedding model and top-k relevant pieces are retrieved based on similarity to a query vector. Your task is to implement database retrieval and adjust the prompt to include the documents from the DB.\n",
143
+ "\n",
144
+ "The deliverables are:\n",
145
+ "\n",
146
+ "1. The new code that enables RAG. Paste the code added and some surrounding context; indicate which file it comes from.\n",
147
+ "2. A new prompt template\n",
148
+ "3. Examples of how the output changes\n"
149
+ ]
150
+ },
151
+ {
152
+ "cell_type": "code",
153
+ "execution_count": null,
154
+ "id": "5bc1399d-1c3b-48b7-a9fb-ed48a0dfaa6a",
155
+ "metadata": {},
156
+ "outputs": [],
157
+ "source": [
158
+ "# DB retrieval implementation"
159
+ ]
160
+ },
161
+ {
162
+ "cell_type": "markdown",
163
+ "id": "7d818b4f-ba5a-4c81-b6d7-f3474c398d9c",
164
+ "metadata": {},
165
+ "source": [
166
+ "### Step 4: Add a reranker\n",
167
+ "\n",
168
+ "A reranker is a second-level model which produces similarity scores for pairs of (input query + retrieved document). Cross-encoders are conventionally used for reranking, their architecture is slightly different from retrieval models (more on it [here]). Cross-encoders are much more costly to run, therefore a retrieval model is used to get a few (dozens) highest-scoring items, and a reranker picks the best among these. The overall pipeline is similar to the recommender system indudustry standard: a light model retrieves top-n, a precise and heavy model reranks n to get top k, n is orders of magnitude larger than k.\n",
169
+ "\n",
170
+ "Cross-encoders are optional because of the overhead their usage implies. Your task is to implement a reranker using a cross-encoder and assess pros and cons of having it. Do not forget that the process of pulling the most relevant documents becomes two-staged: retrieve a larger number of items first, than rerank and keep the best top-k for context.\n",
171
+ "\n",
172
+ "The models fit for the task:\n",
173
+ "1. BAAI/bge-reranker-large\n",
174
+ "2. cross-encoder/ms-marco-MiniLM-L-6-v2\n",
175
+ "\n",
176
+ "As usual, feel free to pick another model and provide some description to it.\n",
177
+ "\n",
178
+ "The deliverables are:\n",
179
+ "\n",
180
+ "1. The code that enables a reranker.\n",
181
+ "2. A comparison of how the prompt and the model output change after adding a reranker\n",
182
+ "3. The analysis of pros and cons. The evaluation aspects should include the relevance of the top-k documents, the response time.\n"
183
+ ]
184
+ },
185
+ {
186
+ "cell_type": "code",
187
+ "execution_count": null,
188
+ "id": "ee1b0160-0ba0-4b5f-81c4-ef3ea76850e5",
189
+ "metadata": {},
190
+ "outputs": [],
191
+ "source": [
192
+ "# Implement code for selecting the final documents using a cross-encoder"
193
+ ]
194
+ },
195
+ {
196
+ "cell_type": "markdown",
197
+ "id": "f5816c54-a290-4cb0-b7db-3b8901998cb0",
198
+ "metadata": {},
199
+ "source": [
200
+ "### Step 5: Try a different LLM\n",
201
+ "\n",
202
+ "The suggested Mistral-7b is a great but small model for an LLM. A larger model can be applied to a wider range of problems and do more complex reasoning. Within the scope of this project a larger model may not be beneficial but for more complex cases the difference would become apparent. \n",
203
+ "\n",
204
+ "A good option for a large model is gpt-4 but the inference time comparison will not be representative due to the hosting infrastructure differences. Try a larger model hosted by HF if you have access.\n",
205
+ "\n",
206
+ "The task here is to try out a large LLM and describe the differencies.\n",
207
+ "\n",
208
+ "The deliverables are:\n",
209
+ "\n",
210
+ "1. The comparison between outputs with Mistral-7b and a larger model\n",
211
+ "2. The difference in response times\n"
212
+ ]
213
+ },
214
+ {
215
+ "cell_type": "code",
216
+ "execution_count": null,
217
+ "id": "942f39d4-eb27-4f2d-ae47-a5d65f102faa",
218
+ "metadata": {},
219
+ "outputs": [],
220
+ "source": [
221
+ "# Analysis of the difference between LLMs"
222
+ ]
223
+ },
224
+ {
225
+ "cell_type": "markdown",
226
+ "id": "70c16440",
227
+ "metadata": {},
228
+ "source": [
229
+ "### Step 6 (Bonus): Use an LLM to quantitatively compare outputs of different variants of the system (LLM as a Judge)\n",
230
+ "\n",
231
+ "Use a powerful LLM (e.g. GPT-4) to quantitatively evaluate outputs of two alternative setups (different embedding models, different LLMs, both etc.). For inspiration and for prompts refer to [1](https://arxiv.org/pdf/2306.05685.pdf), [2](https://arxiv.org/pdf/2401.10020.pdf), [3](https://www.airtrain.ai/blog/the-comprehensive-guide-to-llm-evaluation#high-level-approach)\n",
232
+ "\n",
233
+ "The deliverables:\n",
234
+ "\n",
235
+ "1. The code you put together\n",
236
+ "2. The high-level description of the setup\n",
237
+ "3. The results of the qualitative comparison\n"
238
+ ]
239
+ },
240
+ {
241
+ "cell_type": "code",
242
+ "execution_count": null,
243
+ "id": "39c18ba0-e54a-478f-9e60-0ea65c29238a",
244
+ "metadata": {},
245
+ "outputs": [],
246
+ "source": []
247
+ }
248
+ ],
249
+ "metadata": {
250
+ "kernelspec": {
251
+ "display_name": "Python 3 (ipykernel)",
252
+ "language": "python",
253
+ "name": "python3"
254
+ },
255
+ "language_info": {
256
+ "codemirror_mode": {
257
+ "name": "ipython",
258
+ "version": 3
259
+ },
260
+ "file_extension": ".py",
261
+ "mimetype": "text/x-python",
262
+ "name": "python",
263
+ "nbconvert_exporter": "python",
264
+ "pygments_lexer": "ipython3",
265
+ "version": "3.10.11"
266
+ }
267
+ },
268
+ "nbformat": 4,
269
+ "nbformat_minor": 5
270
+ }