|
| 1 | +import logging |
| 2 | +import os |
| 3 | +import shutil |
| 4 | +import yaml |
| 5 | +import gc |
| 6 | +from langchain.docstore.document import Document |
| 7 | +from langchain.embeddings import HuggingFaceInstructEmbeddings, HuggingFaceEmbeddings, HuggingFaceBgeEmbeddings |
| 8 | +from langchain.vectorstores import Chroma |
| 9 | +from chromadb.config import Settings |
| 10 | +from document_processor import load_documents, split_documents |
| 11 | +import torch |
| 12 | +from utilities import validate_symbolic_links |
| 13 | +from termcolor import cprint |
| 14 | +# from memory_profiler import profile |
| 15 | + |
| 16 | +ENABLE_PRINT = True |
| 17 | +ENABLE_CUDA_PRINT = False |
| 18 | + |
| 19 | +torch.cuda.reset_peak_memory_stats() |
| 20 | + |
| 21 | +def my_cprint(*args, **kwargs): |
| 22 | + if ENABLE_PRINT: |
| 23 | + filename = "create_database.py" |
| 24 | + modified_message = f"{filename}: {args[0]}" |
| 25 | + cprint(modified_message, *args[1:], **kwargs) |
| 26 | + |
| 27 | +def print_cuda_memory(): |
| 28 | + if ENABLE_CUDA_PRINT: |
| 29 | + max_allocated_memory = torch.cuda.max_memory_allocated() |
| 30 | + memory_allocated = torch.cuda.memory_allocated() |
| 31 | + reserved_memory = torch.cuda.memory_reserved() |
| 32 | + |
| 33 | + my_cprint(f"Max CUDA memory allocated: {max_allocated_memory / (1024**2):.2f} MB", "green") |
| 34 | + my_cprint(f"Total CUDA memory allocated: {memory_allocated / (1024**2):.2f} MB", "yellow") |
| 35 | + my_cprint(f"Total CUDA memory reserved: {reserved_memory / (1024**2):.2f} MB", "yellow") |
| 36 | + |
| 37 | +print_cuda_memory() |
| 38 | + |
| 39 | +ROOT_DIRECTORY = os.path.dirname(os.path.realpath(__file__)) |
| 40 | +SOURCE_DIRECTORY = f"{ROOT_DIRECTORY}/Docs_for_DB" |
| 41 | +PERSIST_DIRECTORY = f"{ROOT_DIRECTORY}/Vector_DB" |
| 42 | +INGEST_THREADS = os.cpu_count() or 8 |
| 43 | + |
| 44 | +CHROMA_SETTINGS = Settings( |
| 45 | + chroma_db_impl="duckdb+parquet", |
| 46 | + persist_directory=PERSIST_DIRECTORY, |
| 47 | + anonymized_telemetry=False |
| 48 | +) |
| 49 | + |
| 50 | +# @profile |
| 51 | +def main(): |
| 52 | + print_cuda_memory() |
| 53 | + |
| 54 | + with open(os.path.join(ROOT_DIRECTORY, "config.yaml"), 'r') as stream: |
| 55 | + config_data = yaml.safe_load(stream) |
| 56 | + |
| 57 | + EMBEDDING_MODEL_NAME = config_data.get("EMBEDDING_MODEL_NAME") |
| 58 | + |
| 59 | + # calls document_processor.py |
| 60 | + my_cprint(f"Loading documents.", "cyan") |
| 61 | + documents = load_documents(SOURCE_DIRECTORY) |
| 62 | + my_cprint(f"Successfully loaded documents.", "cyan") |
| 63 | + |
| 64 | + # calls document_processory.py |
| 65 | + texts = split_documents(documents) |
| 66 | + print_cuda_memory() |
| 67 | + |
| 68 | + # calls get_embeddings function |
| 69 | + embeddings = get_embeddings(EMBEDDING_MODEL_NAME, config_data) |
| 70 | + my_cprint("Embedding model loaded.", "green") |
| 71 | + print_cuda_memory() |
| 72 | + |
| 73 | + if os.path.exists(PERSIST_DIRECTORY): |
| 74 | + shutil.rmtree(PERSIST_DIRECTORY) |
| 75 | + os.makedirs(PERSIST_DIRECTORY) |
| 76 | + |
| 77 | + my_cprint("Creating database.", "cyan") |
| 78 | + |
| 79 | + db = Chroma.from_documents( |
| 80 | + texts, embeddings, |
| 81 | + persist_directory=PERSIST_DIRECTORY, |
| 82 | + client_settings=CHROMA_SETTINGS, |
| 83 | + ) |
| 84 | + print_cuda_memory() |
| 85 | + |
| 86 | + # persist database |
| 87 | + my_cprint("Persisting database.", "cyan") |
| 88 | + db.persist() |
| 89 | + my_cprint("Database persisted.", "cyan") |
| 90 | + print_cuda_memory() |
| 91 | + |
| 92 | + del embeddings.client |
| 93 | + # my_cprint("Deleted embeddings.client.", "red") |
| 94 | + print_cuda_memory() |
| 95 | + |
| 96 | + del embeddings |
| 97 | + # my_cprint("Deleted embeddings variable.", "red") |
| 98 | + print_cuda_memory() |
| 99 | + |
| 100 | + torch.cuda.empty_cache() |
| 101 | + # my_cprint("CUDA cache emptied.", "red") |
| 102 | + print_cuda_memory() |
| 103 | + |
| 104 | + gc.collect() |
| 105 | + my_cprint("Embedding model removed from memory.", "red") |
| 106 | + print_cuda_memory() |
| 107 | + |
| 108 | + # print(torch.cuda.memory_summary()) |
| 109 | + |
| 110 | +# @profile |
| 111 | +def get_embeddings(EMBEDDING_MODEL_NAME, config_data, normalize_embeddings=False): |
| 112 | + my_cprint("Creating embeddings.", "cyan") |
| 113 | + print_cuda_memory() |
| 114 | + |
| 115 | + compute_device = config_data['Compute_Device']['database_creation'] |
| 116 | + |
| 117 | + if "instructor" in EMBEDDING_MODEL_NAME: |
| 118 | + embed_instruction = config_data['embedding-models']['instructor'].get('embed_instruction') |
| 119 | + query_instruction = config_data['embedding-models']['instructor'].get('query_instruction') |
| 120 | + |
| 121 | + return HuggingFaceInstructEmbeddings(# creating model instance |
| 122 | + model_name=EMBEDDING_MODEL_NAME, |
| 123 | + model_kwargs={"device": compute_device}, |
| 124 | + encode_kwargs={"normalize_embeddings": normalize_embeddings}, |
| 125 | + embed_instruction=embed_instruction, |
| 126 | + query_instruction=query_instruction |
| 127 | + ) |
| 128 | + |
| 129 | + elif "bge" in EMBEDDING_MODEL_NAME: |
| 130 | + query_instruction = config_data['embedding-models']['bge'].get('query_instruction') |
| 131 | + |
| 132 | + return HuggingFaceBgeEmbeddings( |
| 133 | + model_name=EMBEDDING_MODEL_NAME, |
| 134 | + model_kwargs={"device": compute_device}, |
| 135 | + query_instruction=query_instruction, |
| 136 | + encode_kwargs={"normalize_embeddings": normalize_embeddings} |
| 137 | + ) |
| 138 | + |
| 139 | + else: |
| 140 | + |
| 141 | + return HuggingFaceEmbeddings( |
| 142 | + model_name=EMBEDDING_MODEL_NAME, |
| 143 | + model_kwargs={"device": compute_device}, |
| 144 | + encode_kwargs={"normalize_embeddings": normalize_embeddings} |
| 145 | + ) |
| 146 | + |
| 147 | +if __name__ == "__main__": |
| 148 | + logging.basicConfig( |
| 149 | + format="%(asctime)s - %(levelname)s - %(filename)s:%(lineno)s - %(message)s", |
| 150 | + level=logging.INFO |
| 151 | + ) |
| 152 | + main() |
0 commit comments