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
| 2 |
+
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
|
| 3 |
+
import warnings
|
| 4 |
+
warnings.filterwarnings('ignore')
|
| 5 |
+
# Input data files are available in the read-only "../input/" directory
|
| 6 |
+
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory
|
| 7 |
+
|
| 8 |
+
!pip install pyMuPDF
|
| 9 |
+
|
| 10 |
+
import fitz
|
| 11 |
+
from tqdm.auto import tqdm
|
| 12 |
+
|
| 13 |
+
pdf_path = '/kaggle/input/deep-learning-by-ian-goodfellow/Deep Learning by Ian Goodfellow Yoshua Bengio Aaron Courville (z-lib.org).pdf'
|
| 14 |
+
|
| 15 |
+
def text_formatter(text: str) -> str:
|
| 16 |
+
cleaned_test = text.replace("\n"," ").strip()
|
| 17 |
+
|
| 18 |
+
# Potentially more text formatting functions can go here
|
| 19 |
+
return cleaned_test
|
| 20 |
+
|
| 21 |
+
def open_and_read_pdf(pdf_path: str) -> list[dict]:
|
| 22 |
+
doc = fitz.open(pdf_path)
|
| 23 |
+
pages_and_texts = []
|
| 24 |
+
for page_number, page in tqdm(enumerate(doc)):
|
| 25 |
+
text = page.get_text()
|
| 26 |
+
text = text_formatter(text=text)
|
| 27 |
+
pages_and_texts.append({"page_number": page_number -15,
|
| 28 |
+
"page_char_count": len(text),
|
| 29 |
+
"page_word_count":len(text.split(" ")),
|
| 30 |
+
"page_sentence_count_raw": len(text.split(". ")),
|
| 31 |
+
"page_token_count": len(text)/4,
|
| 32 |
+
"text": text})
|
| 33 |
+
return pages_and_texts
|
| 34 |
+
|
| 35 |
+
pages_and_texts = open_and_read_pdf(pdf_path=pdf_path)
|
| 36 |
+
pages_and_texts[:2]
|
| 37 |
+
|
| 38 |
+
import random
|
| 39 |
+
|
| 40 |
+
random.sample(pages_and_texts,k=3)
|
| 41 |
+
|
| 42 |
+
import pandas as pd
|
| 43 |
+
|
| 44 |
+
df = pd.DataFrame(pages_and_texts)
|
| 45 |
+
df.head()
|
| 46 |
+
|
| 47 |
+
df.describe()
|
| 48 |
+
|
| 49 |
+
! pip install spacy
|
| 50 |
+
|
| 51 |
+
from spacy.lang.en import English
|
| 52 |
+
|
| 53 |
+
nlp = English()
|
| 54 |
+
|
| 55 |
+
# Add a sentencizer pipeline
|
| 56 |
+
nlp.add_pipe("sentencizer")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# Create Document instance as an example
|
| 60 |
+
doc = nlp("This is a sentence. This another sentence. the deep Boltzmann machine")
|
| 61 |
+
assert len(list(doc.sents)) == 3
|
| 62 |
+
|
| 63 |
+
# print out out sentences split
|
| 64 |
+
list(doc.sents)
|
| 65 |
+
|
| 66 |
+
pages_and_texts[55]
|
| 67 |
+
|
| 68 |
+
for item in tqdm(pages_and_texts):
|
| 69 |
+
item['sentences'] = list(nlp(item["text"]).sents)
|
| 70 |
+
|
| 71 |
+
# Make sure all senteces are strings (the default type is a spacy datatype)
|
| 72 |
+
item["sentences"] = [str(sentence) for sentence in item["sentences"]]
|
| 73 |
+
|
| 74 |
+
# Count the sentences
|
| 75 |
+
item["pages_sentence_count_spacy"] = len(item["sentences"])
|
| 76 |
+
|
| 77 |
+
random.sample(pages_and_texts,k=1)
|
| 78 |
+
|
| 79 |
+
df = pd.DataFrame(pages_and_texts)
|
| 80 |
+
df.describe().round(2)
|
| 81 |
+
|
| 82 |
+
# Define spliit size to turn groups of sentences into chunks
|
| 83 |
+
num_sentence_chunk_size = 10
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# Create a fuction to split lists of texts recursively into chunk size
|
| 87 |
+
# eg. [20] -> [10,10] or [25] -> [10,10,5]
|
| 88 |
+
def split_list(input_list: list,
|
| 89 |
+
slice_size: int= num_sentence_chunk_size)->list[list[str]]:
|
| 90 |
+
return [input_list[i:i + slice_size] for i in range(0,len(input_list),slice_size)]
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
test_list = list(range(25))
|
| 94 |
+
split_list(test_list)
|
| 95 |
+
|
| 96 |
+
# Loop through pagaes and texts and split sentences into chunks
|
| 97 |
+
for item in tqdm(pages_and_texts):
|
| 98 |
+
item["sentence_chunks"] = split_list(input_list=item["sentences"],
|
| 99 |
+
slice_size=num_sentence_chunk_size)
|
| 100 |
+
|
| 101 |
+
item["num_chunks"] = len(item["sentence_chunks"])
|
| 102 |
+
|
| 103 |
+
random.sample(pages_and_texts,k=1)
|
| 104 |
+
|
| 105 |
+
df = pd.DataFrame(pages_and_texts)
|
| 106 |
+
df.describe().round(2)
|
| 107 |
+
|
| 108 |
+
import re
|
| 109 |
+
|
| 110 |
+
# Split each chunks into its own item
|
| 111 |
+
pages_and_chunks = []
|
| 112 |
+
for item in tqdm(pages_and_texts):
|
| 113 |
+
for sentence_chunk in item["sentence_chunks"]:
|
| 114 |
+
chunk_dict = {}
|
| 115 |
+
chunk_dict["page_number"] = item["page_number"]
|
| 116 |
+
|
| 117 |
+
# join the sentence together into a paragraph-like structure, aka join the list of sentences into one paragraph
|
| 118 |
+
joined_sentence_chunk = "".join(sentence_chunk).replace(" "," ").strip()
|
| 119 |
+
joined_sentence_chunk = re.sub(r'\.([A-Z])',r'. \1',joined_sentence_chunk) # ".A" => ". A"(will work for any capital letter)
|
| 120 |
+
|
| 121 |
+
chunk_dict["sentence_chunk"] = joined_sentence_chunk
|
| 122 |
+
|
| 123 |
+
# Get some stats on one chunks
|
| 124 |
+
chunk_dict["chunk_char_count"] = len(joined_sentence_chunk)
|
| 125 |
+
chunk_dict["chunk_word_count"] = len([word for word in joined_sentence_chunk.split(" ")])
|
| 126 |
+
chunk_dict["chunk_token_count"] = len(joined_sentence_chunk)/4 # 1 token is equal to 4 chars
|
| 127 |
+
|
| 128 |
+
pages_and_chunks.append(chunk_dict)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
len(pages_and_chunks)
|
| 132 |
+
|
| 133 |
+
random.sample(pages_and_chunks,k=1)
|
| 134 |
+
|
| 135 |
+
df = pd.DataFrame(pages_and_chunks)
|
| 136 |
+
df.describe().round(2)
|
| 137 |
+
|
| 138 |
+
# Show random chunks with under 30 tokens in length
|
| 139 |
+
min_token_length = 30
|
| 140 |
+
for row in df[df["chunk_token_count"]<=min_token_length].sample(5).iterrows():
|
| 141 |
+
print(f'Chunk token count:{row[1]["chunk_token_count"]} | Text: {row[1]["sentence_chunk"]}')
|
| 142 |
+
|
| 143 |
+
# Filter our DataFrame for row with under 30 tokens
|
| 144 |
+
pages_and_chunks_over_min_token_len = df[df["chunk_token_count"]> min_token_length].to_dict(orient="records")
|
| 145 |
+
pages_and_chunks_over_min_token_len[:2]
|
| 146 |
+
|
| 147 |
+
random.sample(pages_and_chunks_over_min_token_len,k=1)
|
| 148 |
+
|
| 149 |
+
from sentence_transformers import SentenceTransformer
|
| 150 |
+
embedding_model = SentenceTransformer(model_name_or_path="all-mpnet-base-v2",
|
| 151 |
+
device="cpu")
|
| 152 |
+
|
| 153 |
+
# Create a list of sentences
|
| 154 |
+
sentences = ["The Sentence Transformer library provides an easy way to create embeddings",
|
| 155 |
+
"Sentences can be embedded one by one or in a list.",
|
| 156 |
+
"I like horses!"]
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
# Sentecnes are encoded/embedded by calling model.encode()
|
| 160 |
+
embeddings = embedding_model.encode(sentences)
|
| 161 |
+
embeddings_dict = dict(zip(sentences,embeddings))
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
# See the embeddings
|
| 165 |
+
for sentence,embedding in embeddings_dict.items():
|
| 166 |
+
print(f"Sentence: {sentence}")
|
| 167 |
+
print(f"Embddings: {embedding}")
|
| 168 |
+
print("")
|
| 169 |
+
|
| 170 |
+
embeddings[0].shape
|
| 171 |
+
|
| 172 |
+
embedding = embedding_model.encode("My smartphone color is Blue. ")
|
| 173 |
+
embedding
|
| 174 |
+
|
| 175 |
+
# Commented out IPython magic to ensure Python compatibility.
|
| 176 |
+
# %%time
|
| 177 |
+
#
|
| 178 |
+
# embedding_model.to("cuda")
|
| 179 |
+
#
|
| 180 |
+
# for item in tqdm(pages_and_chunks_over_min_token_len):
|
| 181 |
+
# item["embedding"] = embedding_model.encode(item["sentence_chunk"])
|
| 182 |
+
|
| 183 |
+
# Commented out IPython magic to ensure Python compatibility.
|
| 184 |
+
# %%time
|
| 185 |
+
#
|
| 186 |
+
# text_chunks = [item["sentence_chunk"] for item in pages_and_chunks_over_min_token_len]
|
| 187 |
+
# text_chunks[450]
|
| 188 |
+
|
| 189 |
+
len(text_chunks)
|
| 190 |
+
|
| 191 |
+
# Commented out IPython magic to ensure Python compatibility.
|
| 192 |
+
# %%time
|
| 193 |
+
#
|
| 194 |
+
# # Embedd all texts in batches
|
| 195 |
+
# text_chunk_embeddings = embedding_model.encode(text_chunks,
|
| 196 |
+
# batch_size=32,
|
| 197 |
+
# convert_to_tensor=True)
|
| 198 |
+
#
|
| 199 |
+
# text_chunk_embeddings
|
| 200 |
+
|
| 201 |
+
# Save embeddings to file
|
| 202 |
+
text_chunk_embeddings_df = pd.DataFrame(pages_and_chunks_over_min_token_len)
|
| 203 |
+
embedding_df_save_path = "text_chunks_and_embeddings_df.csv"
|
| 204 |
+
text_chunk_embeddings_df.to_csv(embedding_df_save_path,index=False)
|
| 205 |
+
|
| 206 |
+
# Import Saved file and view
|
| 207 |
+
text_chunk_embeddings_df_load = pd.read_csv(embedding_df_save_path)
|
| 208 |
+
text_chunk_embeddings_df_load.head()
|
| 209 |
+
|
| 210 |
+
import random
|
| 211 |
+
import torch
|
| 212 |
+
import numpy as np
|
| 213 |
+
import pandas as pd
|
| 214 |
+
|
| 215 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 216 |
+
|
| 217 |
+
# Import texts and embedding df
|
| 218 |
+
text_chunks_and_embedding_df = pd.read_csv('/kaggle/working/text_chunks_and_embeddings_df.csv')
|
| 219 |
+
|
| 220 |
+
# Convert embeddings column back to np.array(it got converted to string when it saved to csv)
|
| 221 |
+
text_chunks_and_embedding_df["embedding"] = text_chunks_and_embedding_df["embedding"].apply(lambda x: np.fromstring(x.strip("[]"),sep=" "))
|
| 222 |
+
|
| 223 |
+
# Convert our embeddings into a torch.tensor
|
| 224 |
+
embeddings = torch.tensor(np.stack(text_chunks_and_embedding_df["embedding"].tolist(),axis=0),dtype=torch.float32).to(device)
|
| 225 |
+
|
| 226 |
+
# Convert texts and embeddings df to list of dicts
|
| 227 |
+
pages_and_chunks = text_chunks_and_embedding_df.to_dict(orient="records")
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
text_chunk_embeddings_df
|
| 231 |
+
|
| 232 |
+
embeddings.shape
|
| 233 |
+
|
| 234 |
+
# Create model
|
| 235 |
+
from sentence_transformers import util, SentenceTransformer
|
| 236 |
+
|
| 237 |
+
embedding_model = SentenceTransformer(model_name_or_path="all-mpnet-base-v2",
|
| 238 |
+
device=device)
|
| 239 |
+
|
| 240 |
+
# 1. Define the query
|
| 241 |
+
query = "Bagging and Other Ensemble Methods"
|
| 242 |
+
print(f"Qurery: {query}")
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
# 2. Embed the query
|
| 246 |
+
# Note: it's import to embed you query with the same model you embeding your passagaes.
|
| 247 |
+
query_embedding = embedding_model.encode(query, convert_to_tensor= True).to("cuda")
|
| 248 |
+
|
| 249 |
+
#3. Get similarity scores with the dot product(use cosine similaryity if outputs of model aren't normalized)
|
| 250 |
+
from time import perf_counter as timer
|
| 251 |
+
|
| 252 |
+
start_time = timer()
|
| 253 |
+
dot_score = util.dot_score(a=query_embedding,b= embeddings)[0]
|
| 254 |
+
end_time = timer()
|
| 255 |
+
|
| 256 |
+
print(f"[INFO] Time taken to get scores on {len(embeddings)} embeddings: {end_time-start_time:.5f} seconds.")
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
# 4. Get the top k results(we'll keep top 5)
|
| 260 |
+
top_results_dot_product = torch.topk(dot_score,k=5)
|
| 261 |
+
top_results_dot_product
|
| 262 |
+
|
| 263 |
+
larger_embeddings = torch.randn(1000*embeddings.shape[0],768).to(device)
|
| 264 |
+
print(f"Embedding shape: {larger_embeddings.shape}")
|
| 265 |
+
|
| 266 |
+
# Perform dot product across 187,400 embedding
|
| 267 |
+
|
| 268 |
+
start_time = timer()
|
| 269 |
+
dot_score = util.dot_score(a=query_embedding,b= larger_embeddings)[0]
|
| 270 |
+
end_time = timer()
|
| 271 |
+
|
| 272 |
+
print(f"[INFO] Time taken to get scores on {len(larger_embeddings)} embeddings: {end_time-start_time:.5f} seconds.")
|
| 273 |
+
|
| 274 |
+
# let's make our vector Secrch results pretty
|
| 275 |
+
|
| 276 |
+
import textwrap
|
| 277 |
+
|
| 278 |
+
def print_wrapped(text,wrap_length=80):
|
| 279 |
+
wrapped_text = textwrap.fill(text,wrap_length)
|
| 280 |
+
print(wrapped_text)
|
| 281 |
+
|
| 282 |
+
query = "Bagging and Other Ensemble Methods"
|
| 283 |
+
print(f"Query: '{query}'\n")
|
| 284 |
+
print("Results:")
|
| 285 |
+
|
| 286 |
+
# Loop through zipped together scores and indices from torch.topk
|
| 287 |
+
for score,idx in zip(top_results_dot_product[0],top_results_dot_product[1]):
|
| 288 |
+
print(f"Score: {score:.4f}")
|
| 289 |
+
print("Text:")
|
| 290 |
+
print_wrapped(pages_and_chunks[idx]["sentence_chunk"])
|
| 291 |
+
print(f"Page number: {pages_and_chunks[idx]['page_number']}")
|
| 292 |
+
print("\n")
|
| 293 |
+
|
| 294 |
+
"""# Note:
|
| 295 |
+
we could potentially improve the order of these results with a reranking model. A model that has been trained specifically to take search results(eg. the top 25 Sementic results) and rank them in order from most likely top-1 to least likely.
|
| 296 |
+
"""
|
| 297 |
+
|
| 298 |
+
import fitz # pymypdf library
|
| 299 |
+
|
| 300 |
+
# open the PDF and load target
|
| 301 |
+
|
| 302 |
+
pdf_path = "/kaggle/input/deep-learning-by-ian-goodfellow/Deep Learning by Ian Goodfellow Yoshua Bengio Aaron Courville (z-lib.org).pdf"
|
| 303 |
+
doc = fitz.open(pdf_path)
|
| 304 |
+
page = doc.load_page(256 + 15)
|
| 305 |
+
|
| 306 |
+
# Get the image of the page
|
| 307 |
+
img = page.get_pixmap(dpi=300)
|
| 308 |
+
|
| 309 |
+
# save image
|
| 310 |
+
img.save("output_filename.png")
|
| 311 |
+
doc.close()
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
# Convert the pixmap to a numpy array
|
| 315 |
+
img_array = np.frombuffer(img.samples_mv,
|
| 316 |
+
dtype=np.uint8).reshape((img.h,img.w,img.n))
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
#Display the image using matplotlib
|
| 320 |
+
import matplotlib.pyplot as plt
|
| 321 |
+
plt.figure(figsize=(13,10))
|
| 322 |
+
plt.imshow(img_array)
|
| 323 |
+
plt.title(f"Query: '{query}' | Most relevant page:")
|
| 324 |
+
plt.axis('off')
|
| 325 |
+
plt.show()
|
| 326 |
+
|
| 327 |
+
"""# Similarity measures: dot product and cosine similarity
|
| 328 |
+
|
| 329 |
+
- Two of the most commmon similarity measures between vectors are dot products and cosine similarity.
|
| 330 |
+
|
| 331 |
+
- In essence, closer vectores will have high socres, further away vectors will have lower scores.
|
| 332 |
+
|
| 333 |
+
- vectors have direction(which way is it going?) and magnitude (how long is it?)
|
| 334 |
+
"""
|
| 335 |
+
|
| 336 |
+
import torch
|
| 337 |
+
|
| 338 |
+
def dot_product(vector1, vector2):
|
| 339 |
+
return torch.dot(vector1,vector2)
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def cosine_similarity(vector1,vector2):
|
| 343 |
+
dot_product = torch.dot(vector1, vector2)
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
# Get Euclidean/ L2 norm
|
| 348 |
+
norm_vector1 = torch.sqrt(torch.sum(vector1**2))
|
| 349 |
+
norm_vector2 = torch.sqrt(torch.sum(vector2**2))
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
return dot_product / (norm_vector1 * norm_vector2)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
# Example vectors/tensors
|
| 357 |
+
vector1 = torch.tensor([1,2,3],dtype = torch.float32)
|
| 358 |
+
vector2 = torch.tensor([1,2,3],dtype = torch.float32)
|
| 359 |
+
vector3 = torch.tensor([4,5,6],dtype = torch.float32)
|
| 360 |
+
vector4 = torch.tensor([-1,-2,-3],dtype = torch.float32)
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
# Calculate dot product
|
| 364 |
+
print("Dot Product Between Vector1 and Vector2:",dot_product(vector1,vector2))
|
| 365 |
+
print("Dot Product Between Vector1 and Vector3:",dot_product(vector1,vector3))
|
| 366 |
+
print("Dot Product Between Vector1 and Vector4:",dot_product(vector1,vector4))
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
# Cosine similarity
|
| 370 |
+
print("Cosine similarity Between Vector1 and Vector2:",cosine_similarity(vector1,vector2))
|
| 371 |
+
print("Cosine similarity Between Vector1 and Vector3:",cosine_similarity(vector1,vector3))
|
| 372 |
+
print("Cosine similarity Between Vector1 and Vector4:",cosine_similarity(vector1,vector4))
|
| 373 |
+
|
| 374 |
+
"""# Functionizing our Semantic Search pipeline
|
| 375 |
+
|
| 376 |
+
- Let's put all the steps from above for semantic search into a function two so we can repeat the workflow
|
| 377 |
+
"""
|
| 378 |
+
|
| 379 |
+
def retrieve_relevant_resources(query: str,
|
| 380 |
+
embeddings : torch.tensor,
|
| 381 |
+
model: SentenceTransformer = embedding_model,
|
| 382 |
+
n_resources_to_return: int = 5,
|
| 383 |
+
print_time: bool=True):
|
| 384 |
+
"""
|
| 385 |
+
Embeds a query with model and return top k scores and indices from embeddings.
|
| 386 |
+
"""
|
| 387 |
+
|
| 388 |
+
# Embed the query
|
| 389 |
+
query_embedding = model.encode(query,convert_to_tensor=True)
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
# Get dot products scores on embeddings
|
| 393 |
+
start_time= timer()
|
| 394 |
+
dot_scores = util.dot_score(query_embedding,embeddings)[0]
|
| 395 |
+
end_time = timer()
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
if print_time:
|
| 399 |
+
print(f"[INFO] Time taken to get scores on ({len(embeddings)} embeddings: {end_time-start_time:.5f} seconds.")
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
scores, indices = torch.topk(input=dot_scores,k = n_resources_to_return)
|
| 403 |
+
|
| 404 |
+
return scores,indices
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def print_top_results_and_scores(query:str,
|
| 408 |
+
embeddings: torch.tensor,
|
| 409 |
+
pages_and_chunks: list[dict]=pages_and_chunks,
|
| 410 |
+
n_resources_to_return: int=5):
|
| 411 |
+
"""
|
| 412 |
+
Finds relevant passages given a query and prints them out along with their Scores.
|
| 413 |
+
"""
|
| 414 |
+
|
| 415 |
+
scores, indices = retrieve_relevant_resources(query=query,
|
| 416 |
+
embeddings=embeddings,
|
| 417 |
+
n_resources_to_return=n_resources_to_return)
|
| 418 |
+
# Loop through zipped together scores and indices from torch.topk
|
| 419 |
+
for score,idx in zip(scores,indices):
|
| 420 |
+
print(f"Score: {score:.4f}")
|
| 421 |
+
print("Text:")
|
| 422 |
+
print_wrapped(pages_and_chunks[idx]["sentence_chunk"])
|
| 423 |
+
print(f"Page number: {pages_and_chunks[idx]['page_number']}")
|
| 424 |
+
print("\n")
|
| 425 |
+
|
| 426 |
+
query="Algorithms with Adaptive Learning Rates"
|
| 427 |
+
# retrieve_relevant_resources(query=query,embeddings = embeddings)
|
| 428 |
+
print_top_results_and_scores(query=query,embeddings = embeddings)
|
| 429 |
+
|
| 430 |
+
# Get GPU available memory
|
| 431 |
+
import torch
|
| 432 |
+
gpu_memory_bytes = torch.cuda.get_device_properties(0).total_memory
|
| 433 |
+
gpu_memory_gb = round(gpu_memory_bytes / (2**30))
|
| 434 |
+
print(f"Available GPU memory: {gpu_memory_gb} GB")
|
| 435 |
+
|
| 436 |
+
!pip install ipywidgets==7.7.1
|
| 437 |
+
|
| 438 |
+
pip install -U "huggingface_hub[cli]"
|
| 439 |
+
|
| 440 |
+
from kaggle_secrets import UserSecretsClient
|
| 441 |
+
user_secrets = UserSecretsClient()
|
| 442 |
+
secret_value_0 = user_secrets.get_secret("HUGGINGFACE_TOKEN")
|
| 443 |
+
|
| 444 |
+
# import os
|
| 445 |
+
# from huggingface_hub import login
|
| 446 |
+
|
| 447 |
+
# # The token is automatically injected into the environment variable
|
| 448 |
+
# token = os.environ["HUGGINGFACE_TOKEN"]
|
| 449 |
+
# login(token=token)
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
from kaggle_secrets import UserSecretsClient
|
| 453 |
+
from huggingface_hub import login
|
| 454 |
+
|
| 455 |
+
# Retrieve the token securely
|
| 456 |
+
user_secrets = UserSecretsClient()
|
| 457 |
+
hf_token = user_secrets.get_secret("HUGGINGFACE_TOKEN")
|
| 458 |
+
|
| 459 |
+
# Login to Hugging Face
|
| 460 |
+
login(token=hf_token)
|
| 461 |
+
|
| 462 |
+
# Note: the following is Gemma focused, however, there are more and more LLMs of the 2B and 7B size appearing for local use.
|
| 463 |
+
if gpu_memory_gb < 5.1:
|
| 464 |
+
print(f"Your available GPU memory is {gpu_memory_gb}GB, you may not have enough memory to run a Gemma LLM locally without quantization.")
|
| 465 |
+
elif gpu_memory_gb < 8.1:
|
| 466 |
+
print(f"GPU memory: {gpu_memory_gb} | Recommended model: Gemma 2B in 4-bit precision.")
|
| 467 |
+
use_quantization_config = True
|
| 468 |
+
model_id = "google/gemma-2b-it"
|
| 469 |
+
elif gpu_memory_gb < 19.0:
|
| 470 |
+
print(f"GPU memory: {gpu_memory_gb} | Recommended model: Gemma 2B in float16 or Gemma 7B in 4-bit precision.")
|
| 471 |
+
use_quantization_config = False
|
| 472 |
+
model_id = "google/gemma-2b-it"
|
| 473 |
+
elif gpu_memory_gb > 19.0:
|
| 474 |
+
print(f"GPU memory: {gpu_memory_gb} | Recommend model: Gemma 7B in 4-bit or float16 precision.")
|
| 475 |
+
use_quantization_config = False
|
| 476 |
+
model_id = "google/gemma-7b-it"
|
| 477 |
+
|
| 478 |
+
print(f"use_quantization_config set to: {use_quantization_config}")
|
| 479 |
+
print(f"model_id set to: {model_id}")
|
| 480 |
+
|
| 481 |
+
!pip install transformers
|
| 482 |
+
|
| 483 |
+
!pip install transformers bitsandbytes accelerate
|
| 484 |
+
|
| 485 |
+
import torch
|
| 486 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 487 |
+
from transformers.utils import is_flash_attn_2_available
|
| 488 |
+
|
| 489 |
+
# 1. Create a quantization config
|
| 490 |
+
# Note : requires !pip install bitsandbytes accelerate
|
| 491 |
+
from transformers import BitsAndBytesConfig
|
| 492 |
+
quantization_config = BitsAndBytesConfig(load_in_4bit=True,
|
| 493 |
+
bnb_4bit_compute_dtype=torch.float16)
|
| 494 |
+
|
| 495 |
+
# Bonus: flash attention 2 = faster attention mechanism
|
| 496 |
+
# Flash Attention 2 reauires a GPU with a computer capability score of 8.0+
|
| 497 |
+
if (is_flash_attn_2_available()) and (torch.cuda.get_device_capability(0)[0] >=8):
|
| 498 |
+
attn_implementation = "flash_attention_2"
|
| 499 |
+
else:
|
| 500 |
+
attn_implementation = "sdpa"
|
| 501 |
+
|
| 502 |
+
print(f"Using attention implementation: {attn_implementation}")
|
| 503 |
+
|
| 504 |
+
# 2 pick a model we'd like to use
|
| 505 |
+
# model_id = "google/gemma-2b-it"
|
| 506 |
+
model_id = model_id
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
# 3. Instantiate tokenizer( tokeniszer turns text into tokens)
|
| 510 |
+
tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path = model_id)
|
| 511 |
+
|
| 512 |
+
# 4. Intantiate the model
|
| 513 |
+
llm_model = AutoModelForCausalLM.from_pretrained(pretrained_model_name_or_path= model_id,
|
| 514 |
+
torch_dtype= torch.float16,
|
| 515 |
+
quantization_config = quantization_config if use_quantization_config else None,
|
| 516 |
+
low_cpu_mem_usage=False,
|
| 517 |
+
attn_implementation= attn_implementation)
|
| 518 |
+
|
| 519 |
+
if not use_quantization_config:
|
| 520 |
+
llm_model.to("cuda")
|
| 521 |
+
|
| 522 |
+
attn_implementation = "flash_attention_2" # or "eager"
|
| 523 |
+
print(f"Using attention implementation: {attn_implementation}")
|
| 524 |
+
|
| 525 |
+
!nvidia-smi
|
| 526 |
+
|
| 527 |
+
llm_model
|
| 528 |
+
|
| 529 |
+
def get_model_num_params(model: torch.nn.Module):
|
| 530 |
+
return sum([param.numel() for param in model.parameters()])
|
| 531 |
+
|
| 532 |
+
get_model_num_params(llm_model)
|
| 533 |
+
|
| 534 |
+
def get_model_mem_size(model: torch.nn.Module):
|
| 535 |
+
# Get model parameters and buffer sizes
|
| 536 |
+
mem_params = sum([param.nelement()*param.element_size() for param in model.parameters()])
|
| 537 |
+
mem_buffers = sum([buf.nelement() * buf.element_size() for buf in model.buffers()])
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
# Calculate model sizes
|
| 541 |
+
model_mem_bytes = mem_params + mem_buffers
|
| 542 |
+
model_mem_mb = model_mem_bytes / (1024**2)
|
| 543 |
+
model_mem_gb = model_mem_bytes / (1024**3)
|
| 544 |
+
|
| 545 |
+
return {"model_mem_bytes": model_mem_bytes,
|
| 546 |
+
"model_mem_mb": round(model_mem_mb,2),
|
| 547 |
+
"model_mem_gb": round(model_mem_gb,2)}
|
| 548 |
+
|
| 549 |
+
get_model_mem_size(llm_model)
|
| 550 |
+
|
| 551 |
+
"""* We got the size our model,
|
| 552 |
+
|
| 553 |
+
* This means to load Gemma 2b-it in float16 we need a minimum of ~5GB of VRAM, however due to the calcuation that take place in the forward pass, we actually need closer to 11GB
|
| 554 |
+
|
| 555 |
+
# Generate text with out LLM
|
| 556 |
+
|
| 557 |
+
* Let's generate text with out local LLM!
|
| 558 |
+
|
| 559 |
+
# Note:
|
| 560 |
+
* Some models have been trained/tuned to generate text with a specific template in mind.
|
| 561 |
+
|
| 562 |
+
* Because `Gemma 2b-it` has been trained in instruction tuned meanner, we should follow the instruction template for the best results.
|
| 563 |
+
"""
|
| 564 |
+
|
| 565 |
+
input_text = "Why the Gradient-Based Learning is used, what is the mathematics behind the Gradient-Based Learning?"
|
| 566 |
+
print(f"Input text:\n{input_text}")
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
# Create prompt template for instruction tuned model.
|
| 570 |
+
dialogue_template=[
|
| 571 |
+
{"role": "user",
|
| 572 |
+
"content": input_text}
|
| 573 |
+
]
|
| 574 |
+
|
| 575 |
+
# Apply the chat template
|
| 576 |
+
prompt = tokenizer.apply_chat_template(conversation=dialogue_template,
|
| 577 |
+
tokenize=False,
|
| 578 |
+
add_generation_prompt=True)
|
| 579 |
+
|
| 580 |
+
print(f"\nPrompt (formatted):\n{prompt}")
|
| 581 |
+
|
| 582 |
+
# Commented out IPython magic to ensure Python compatibility.
|
| 583 |
+
# %%time
|
| 584 |
+
# # Tokenize the input text (turn it into number) and send it to GPU
|
| 585 |
+
# input_ids = tokenizer(prompt,
|
| 586 |
+
# return_tensors = "pt").to("cuda")
|
| 587 |
+
#
|
| 588 |
+
# input_ids
|
| 589 |
+
#
|
| 590 |
+
# # Generate outputs from local LLm
|
| 591 |
+
# outputs = llm_model.generate(**input_ids,
|
| 592 |
+
# max_new_tokens=1000)
|
| 593 |
+
# print(f"Model output (tokens:\n{outputs[0]}\n")
|
| 594 |
+
|
| 595 |
+
"""# Decode the outputs tokens to text"""
|
| 596 |
+
|
| 597 |
+
# outputs_decoded = tokenizer.decode(outputs[0])
|
| 598 |
+
# print(f"Model output (decoded):\n {outputs_decoded}\n")
|
| 599 |
+
# Decode the output tokens to text
|
| 600 |
+
outputs_decoded = tokenizer.decode(outputs[0])
|
| 601 |
+
print(f"Model output (decoded):\n{outputs_decoded}\n")
|
| 602 |
+
|
| 603 |
+
#Generated question by use of Gpt
|
| 604 |
+
gpt_questions = [
|
| 605 |
+
"What are the main differences between bagging and boosting in ensemble learning?",
|
| 606 |
+
"How does the bias-variance tradeoff affect model performance?",
|
| 607 |
+
"What is the difference between parametric and non-parametric models?",
|
| 608 |
+
"Explain the concept of feature selection and its importance in model training.",
|
| 609 |
+
"How would you handle class imbalance in a binary classification problem?",
|
| 610 |
+
"Compare supervised and unsupervised learning with real-world examples.",
|
| 611 |
+
"What are some common clustering algorithms and their use cases?",
|
| 612 |
+
"How does k-means clustering work, and what are its limitations?",
|
| 613 |
+
"When would you prefer dimensionality reduction over feature selection?",
|
| 614 |
+
"What is the vanishing gradient problem and how do activation functions like ReLU help solve it?",
|
| 615 |
+
"Explain how dropout works and why it is used in neural networks.",
|
| 616 |
+
"What is the role of backpropagation in training a neural network?",
|
| 617 |
+
"How does a convolutional neural network (CNN) differ from a fully connected neural network?",
|
| 618 |
+
"Describe how a recurrent neural network (RNN) handles sequential data.",
|
| 619 |
+
]
|
| 620 |
+
|
| 621 |
+
# Maually created question list
|
| 622 |
+
manual_questions = [
|
| 623 |
+
"What is the architecture of a transformer and how does self-attention work?",
|
| 624 |
+
"How do positional encodings help transformers understand word order?",
|
| 625 |
+
"What are the differences between GPT and BERT in terms of architecture and use case?",
|
| 626 |
+
"Why is layer normalization important in transformer models?",
|
| 627 |
+
"How does masked language modeling work in pretraining?",
|
| 628 |
+
"What are learning rate schedules and how do they impact model convergence?",
|
| 629 |
+
"Compare Adam and SGD optimizers—when would you use each?",
|
| 630 |
+
"What is early stopping and how can it help with overfitting?",
|
| 631 |
+
"What is transfer learning and how is it applied in deep learning?",
|
| 632 |
+
"How is machine learning used in recommendation systems?",
|
| 633 |
+
"What challenges exist in deploying AI models in real-world environments?",
|
| 634 |
+
"Explain the concept of explainable AI (XAI) and why it's important.",
|
| 635 |
+
"What are hallucinations in large language models, and how can they be mitigated?",
|
| 636 |
+
"How do retrieval-augmented generation (RAG) models differ from traditional LLMs?"
|
| 637 |
+
]
|
| 638 |
+
|
| 639 |
+
query_list = gpt_questions + manual_questions
|
| 640 |
+
query_list
|
| 641 |
+
|
| 642 |
+
import random
|
| 643 |
+
|
| 644 |
+
query = random.choice(query_list)
|
| 645 |
+
|
| 646 |
+
print(f"Query:{query}")
|
| 647 |
+
|
| 648 |
+
# Get just the scores and indices of top related results
|
| 649 |
+
scores, indices = retrieve_relevant_resources(query=query, embeddings=embeddings)
|
| 650 |
+
|
| 651 |
+
scores,indices
|
| 652 |
+
|
| 653 |
+
"""# Augmenting our prompt with context items
|
| 654 |
+
|
| 655 |
+
* we have done retrieval.
|
| 656 |
+
* we have done generation
|
| 657 |
+
|
| 658 |
+
* time to augment!
|
| 659 |
+
|
| 660 |
+
* the concept of augmenting a prompt with context items is also referred as prompt engineering.
|
| 661 |
+
|
| 662 |
+
* prompt engineering is an active field of reserarch and may new styles and techniques are being found out.
|
| 663 |
+
* However, there are a fair few techniques that work quite well.
|
| 664 |
+
|
| 665 |
+
* Resources:
|
| 666 |
+
* Prompltingguide.ai
|
| 667 |
+
* Anthropic.com/prompt engineering
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
* we are going to use couple of promplting techniques:
|
| 671 |
+
1. give clear instruction.
|
| 672 |
+
2. Give a few examples of input/output (eg.give thsi input, i'd like this output).
|
| 673 |
+
3. give room to think(e.g. create a scratchpad/"show your working space"/"let's think step by step...."
|
| 674 |
+
|
| 675 |
+
let's create a function to format a prompt with context items.
|
| 676 |
+
"""
|
| 677 |
+
|
| 678 |
+
pages_and_chunks[320]
|
| 679 |
+
|
| 680 |
+
def prompt_formatter(query: str,
|
| 681 |
+
context_items: list[dict])-> str:
|
| 682 |
+
context = "- " + "\n- ".join([item["sentence_chunk"] for item in context_items])
|
| 683 |
+
base_prompt = """Based on the following context items, please answer the query.
|
| 684 |
+
Give yourself room to think by extracting relevant passages from the context before answering the query.
|
| 685 |
+
Don't return the thinking, only return the answer.
|
| 686 |
+
Make sure your answers are clear, technically accurate, and explanatory—suitable for someone learning or working in the AI/ML field.
|
| 687 |
+
Use the following examples as reference for the ideal answer style.
|
| 688 |
+
|
| 689 |
+
\nExample 1:
|
| 690 |
+
Query: What is overfitting in machine learning?
|
| 691 |
+
Answer: Overfitting occurs when a machine learning model learns the noise or random fluctuations in the training data rather than the underlying pattern. As a result, it performs very well on the training data but poorly on unseen or test data. This usually happens when the model is too complex relative to the amount of training data. Techniques such as regularization, cross-validation, and pruning can help mitigate overfitting.
|
| 692 |
+
|
| 693 |
+
\nExample 2:
|
| 694 |
+
Query: How does backpropagation work in training a neural network?
|
| 695 |
+
Answer: Backpropagation is an algorithm used to train neural networks by minimizing the loss function. It works by computing the gradient of the loss with respect to each weight in the network using the chain rule of calculus. The algorithm propagates the error backward from the output layer to the input layer, updating the weights using an optimizer like stochastic gradient descent. This process allows the network to learn patterns in data by iteratively reducing prediction error.
|
| 696 |
+
|
| 697 |
+
\nExample 3:
|
| 698 |
+
Query: What is transfer learning and why is it useful in deep learning?
|
| 699 |
+
Answer: Transfer learning is a technique in deep learning where a pre-trained model, trained on a large dataset like ImageNet, is fine-tuned on a smaller, task-specific dataset. This is especially useful when you don't have enough labeled data to train a model from scratch. Transfer learning leverages learned features from the pre-trained model, such as edges and textures, and adapts them to the new task, often improving accuracy and reducing training time.
|
| 700 |
+
|
| 701 |
+
\nNow use the following context items to answer the user query:
|
| 702 |
+
{context}
|
| 703 |
+
|
| 704 |
+
\nRelevant passages: <extract relevant passages from the context here>
|
| 705 |
+
User query: {query}
|
| 706 |
+
Answer:
|
| 707 |
+
|
| 708 |
+
"""
|
| 709 |
+
base_prompt = base_prompt.format(context=context,
|
| 710 |
+
query=query)
|
| 711 |
+
|
| 712 |
+
# Create prompt template for conversation for instruction tune model
|
| 713 |
+
dialogue_template = [
|
| 714 |
+
{"role": "user",
|
| 715 |
+
"content" : base_prompt}
|
| 716 |
+
]
|
| 717 |
+
|
| 718 |
+
# Apply the chat template
|
| 719 |
+
prompt = tokenizer.apply_chat_template(conversation=dialogue_template,
|
| 720 |
+
tokenize = False,
|
| 721 |
+
add_generation_prompt=True)
|
| 722 |
+
|
| 723 |
+
return prompt
|
| 724 |
+
|
| 725 |
+
query = random.choice(query_list)
|
| 726 |
+
print(f"Qurey: {query}")
|
| 727 |
+
|
| 728 |
+
# Get relevant resources
|
| 729 |
+
socres, indices = retrieve_relevant_resources(query=query,
|
| 730 |
+
embeddings=embeddings)
|
| 731 |
+
|
| 732 |
+
|
| 733 |
+
# Create a list of context items
|
| 734 |
+
context_items = [pages_and_chunks[i] for i in indices]
|
| 735 |
+
|
| 736 |
+
# format our prompt
|
| 737 |
+
prompt = prompt_formatter(query=query,
|
| 738 |
+
context_items = context_items)
|
| 739 |
+
|
| 740 |
+
print(prompt)
|
| 741 |
+
|
| 742 |
+
# Commented out IPython magic to ensure Python compatibility.
|
| 743 |
+
# %%time
|
| 744 |
+
#
|
| 745 |
+
# # input_ids = tokenizer(prompt,return_tensors="pt").to("cuda")
|
| 746 |
+
#
|
| 747 |
+
#
|
| 748 |
+
# # # Generate an output of tokens
|
| 749 |
+
# # outputs = llm_model.generate(**input_ids,
|
| 750 |
+
# # temperature=0.7, # from 0 to q the lower the value, the more deterministic the text, the higher the value, the more creative)
|
| 751 |
+
# # do_sample = True, # Wheather or not to use smapling
|
| 752 |
+
# # max_new_tokens= 1000)
|
| 753 |
+
#
|
| 754 |
+
# # # Turn the output tokens into text
|
| 755 |
+
# # output_text = tokenizer.decode(outputs[0])
|
| 756 |
+
# # print(f"Query:{query}")
|
| 757 |
+
# # print(f"RAG Answer:\n {output_text.replace(prompt,'')}")
|
| 758 |
+
# # %%time
|
| 759 |
+
#
|
| 760 |
+
# input_ids = tokenizer(prompt, return_tensors="pt").to("cuda")
|
| 761 |
+
#
|
| 762 |
+
# # Generate an output of tokens
|
| 763 |
+
# outputs = llm_model.generate(**input_ids,
|
| 764 |
+
# temperature=0.7, # lower temperature = more deterministic outputs, higher temperature = more creative outputs
|
| 765 |
+
# do_sample=True, # whether or not to use sampling, see https://huyenchip.com/2024/01/16/sampling.html for more
|
| 766 |
+
# max_new_tokens=256) # how many new tokens to generate from prompt
|
| 767 |
+
#
|
| 768 |
+
# # Turn the output tokens into text
|
| 769 |
+
# output_text = tokenizer.decode(outputs[0])
|
| 770 |
+
#
|
| 771 |
+
# print(f"Query: {query}")
|
| 772 |
+
# print(f"RAG answer:\n{output_text.replace(prompt, '')}")
|
| 773 |
+
|
| 774 |
+
"""# Functionize our LLM Answering feature
|
| 775 |
+
|
| 776 |
+
* Wouldn't it be cool if our RAG pipeline worked from a single function?
|
| 777 |
+
|
| 778 |
+
* E.g. you input a query and you get a generrated answer + optionally also get the source documents(the context) where that answer was generated from.
|
| 779 |
+
|
| 780 |
+
* Let's make a function to do it!
|
| 781 |
+
"""
|
| 782 |
+
|
| 783 |
+
def ask(query,
|
| 784 |
+
temperature=0.7,
|
| 785 |
+
max_new_tokens=512,
|
| 786 |
+
format_answer_text=True,
|
| 787 |
+
return_answer_only=True):
|
| 788 |
+
"""
|
| 789 |
+
Takes a query, finds relevant resources/context and generates an answer to the query based on the relevant resources.
|
| 790 |
+
"""
|
| 791 |
+
|
| 792 |
+
# Get just the scores and indices of top related results
|
| 793 |
+
scores, indices = retrieve_relevant_resources(query=query,
|
| 794 |
+
embeddings=embeddings)
|
| 795 |
+
|
| 796 |
+
# Create a list of context items
|
| 797 |
+
context_items = [pages_and_chunks[i] for i in indices]
|
| 798 |
+
|
| 799 |
+
# Add score to context item
|
| 800 |
+
for i, item in enumerate(context_items):
|
| 801 |
+
item["score"] = scores[i].cpu() # return score back to CPU
|
| 802 |
+
|
| 803 |
+
# Format the prompt with context items
|
| 804 |
+
prompt = prompt_formatter(query=query,
|
| 805 |
+
context_items=context_items)
|
| 806 |
+
|
| 807 |
+
# Tokenize the prompt
|
| 808 |
+
input_ids = tokenizer(prompt, return_tensors="pt").to("cuda")
|
| 809 |
+
|
| 810 |
+
# Generate an output of tokens
|
| 811 |
+
outputs = llm_model.generate(**input_ids,
|
| 812 |
+
temperature=temperature,
|
| 813 |
+
do_sample=True,
|
| 814 |
+
max_new_tokens=max_new_tokens)
|
| 815 |
+
|
| 816 |
+
# Turn the output tokens into text
|
| 817 |
+
output_text = tokenizer.decode(outputs[0])
|
| 818 |
+
|
| 819 |
+
if format_answer_text:
|
| 820 |
+
# Replace special tokens and unnecessary help message
|
| 821 |
+
output_text = output_text.replace(prompt, "").replace("<bos>", "").replace("<eos>", "").replace("Sure, here is the answer to the user query:\n\n", "")
|
| 822 |
+
|
| 823 |
+
# Only return the answer without the context items
|
| 824 |
+
if return_answer_only:
|
| 825 |
+
return output_text
|
| 826 |
+
|
| 827 |
+
return output_text, context_items
|
| 828 |
+
|
| 829 |
+
query = random.choice(query_list)
|
| 830 |
+
print(f"Query: {query}")
|
| 831 |
+
|
| 832 |
+
# Answer query with context and return context
|
| 833 |
+
answer, context_items = ask(query=query,
|
| 834 |
+
temperature=0.7,
|
| 835 |
+
max_new_tokens=512,
|
| 836 |
+
return_answer_only=False)
|
| 837 |
+
|
| 838 |
+
print(f"Answer:\n")
|
| 839 |
+
print_wrapped(answer)
|
| 840 |
+
print(f"Context items:")
|
| 841 |
+
context_items
|
| 842 |
+
|