Skip to content

Commit

Permalink
petit vulture des familles
Browse files Browse the repository at this point in the history
  • Loading branch information
linogaliana committed Dec 4, 2024
1 parent 15d74b3 commit 13aded0
Show file tree
Hide file tree
Showing 8 changed files with 61 additions and 498 deletions.
13 changes: 0 additions & 13 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,19 +59,6 @@
# CHAT START -------------------------------


def format_docs2(docs: list):
return "\n\n".join(
[
f"""
Doc {i + 1}:\nTitle: {doc.metadata.get("Header 1")}\n
Source: {doc.metadata.get("url")}\n
Content:\n{doc.page_content}
"""
for i, doc in enumerate(docs)
]
)


@cl.on_chat_start
async def on_chat_start():
# Initial message
Expand Down
119 changes: 61 additions & 58 deletions minimal-rag-in-notebook.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -94,13 +94,14 @@
"# Create a custom confz configuration\n",
"config = custom_config(\n",
" defaults = { # These defaults can be overriden with env variables\n",
" \"MAX_NEW_TOKENS\": 10,\n",
" \"MAX_NEW_TOKENS\": 2000,\n",
" \"MODEL_TEMPERATURE\": 1.0,\n",
" \"quantization\": True,\n",
" \"mlflow_run_id\": DATABASE_RUN_ID,\n",
" },\n",
" overrides = { # These values are going to be used no matter what\n",
" \"UVICORN_TIMEOUT_KEEP_ALIVE\": 0,\n",
" \"MAX_NEW_TOKENS\": 2000,\n",
" \"LLM_MODEL\": LLM_MODEL,\n",
" \"EMB_MODEL_NAME\": EMB_MODEL_NAME,\n",
" \"mlflow_run_id\": DATABASE_RUN_ID,\n",
Expand All @@ -116,32 +117,20 @@
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"from src.db_building.loading import _load_vector_database_from_mlflow\n",
"db = load_vector_database(filesystem=fs, config=config)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Nombre de documents dans la vector db: 286427'"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"outputs": [],
"source": [
"f\"Nombre de documents dans la vector db: {len(db.get()['documents'])}\""
"#f\"Nombre de documents dans la vector db: {len(db.get()['documents'])}\""
]
},
{
Expand All @@ -153,22 +142,22 @@
},
{
"cell_type": "code",
"execution_count": 6,
"execution_count": null,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"2024-12-03 19:04:15,561\tINFO util.py:154 -- Missing packages: ['ipywidgets']. Run `pip install -U ipywidgets`, then restart the notebook server for rich notebook output.\n"
"2024-12-04 09:47:22,910\tINFO util.py:154 -- Missing packages: ['ipywidgets']. Run `pip install -U ipywidgets`, then restart the notebook server for rich notebook output.\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"INFO 12-03 19:04:22 config.py:350] This model supports multiple tasks: {'embedding', 'generate'}. Defaulting to 'generate'.\n",
"INFO 12-03 19:04:22 llm_engine.py:249] Initializing an LLM engine (v0.6.4.post1) with config: model='mistralai/Mistral-7B-Instruct-v0.3', speculative_config=None, tokenizer='mistralai/Mistral-7B-Instruct-v0.3', skip_tokenizer_init=False, tokenizer_mode=auto, revision=None, override_neuron_config=None, tokenizer_revision=None, trust_remote_code=False, dtype=torch.bfloat16, max_seq_len=32768, download_dir=None, load_format=LoadFormat.AUTO, tensor_parallel_size=1, pipeline_parallel_size=1, disable_custom_all_reduce=False, quantization=None, enforce_eager=False, kv_cache_dtype=auto, quantization_param_path=None, device_config=cuda, decoding_config=DecodingConfig(guided_decoding_backend='outlines'), observability_config=ObservabilityConfig(otlp_traces_endpoint=None, collect_model_forward_time=False, collect_model_execute_time=False), seed=0, served_model_name=mistralai/Mistral-7B-Instruct-v0.3, num_scheduler_steps=1, chunked_prefill_enabled=False multi_step_stream_outputs=True, enable_prefix_caching=False, use_async_output_proc=True, use_cached_outputs=False, chat_template_text_format=string, mm_processor_kwargs=None, pooler_config=None)\n"
"INFO 12-04 09:47:29 config.py:350] This model supports multiple tasks: {'embedding', 'generate'}. Defaulting to 'generate'.\n",
"INFO 12-04 09:47:29 llm_engine.py:249] Initializing an LLM engine (v0.6.4.post1) with config: model='mistralai/Mistral-7B-Instruct-v0.3', speculative_config=None, tokenizer='mistralai/Mistral-7B-Instruct-v0.3', skip_tokenizer_init=False, tokenizer_mode=auto, revision=None, override_neuron_config=None, tokenizer_revision=None, trust_remote_code=False, dtype=torch.bfloat16, max_seq_len=32768, download_dir=None, load_format=LoadFormat.AUTO, tensor_parallel_size=1, pipeline_parallel_size=1, disable_custom_all_reduce=False, quantization=None, enforce_eager=False, kv_cache_dtype=auto, quantization_param_path=None, device_config=cuda, decoding_config=DecodingConfig(guided_decoding_backend='outlines'), observability_config=ObservabilityConfig(otlp_traces_endpoint=None, collect_model_forward_time=False, collect_model_execute_time=False), seed=0, served_model_name=mistralai/Mistral-7B-Instruct-v0.3, num_scheduler_steps=1, chunked_prefill_enabled=False multi_step_stream_outputs=True, enable_prefix_caching=False, use_async_output_proc=True, use_cached_outputs=False, chat_template_text_format=string, mm_processor_kwargs=None, pooler_config=None)\n"
]
},
{
Expand All @@ -183,34 +172,34 @@
"name": "stdout",
"output_type": "stream",
"text": [
"INFO 12-03 19:04:23 selector.py:135] Using Flash Attention backend.\n",
"INFO 12-03 19:04:24 model_runner.py:1072] Starting to load model mistralai/Mistral-7B-Instruct-v0.3...\n",
"INFO 12-03 19:04:24 weight_utils.py:243] Using model weights format ['*.safetensors']\n"
"INFO 12-04 09:47:30 selector.py:135] Using Flash Attention backend.\n",
"INFO 12-04 09:47:30 model_runner.py:1072] Starting to load model mistralai/Mistral-7B-Instruct-v0.3...\n",
"INFO 12-04 09:47:30 weight_utils.py:243] Using model weights format ['*.safetensors']\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"Loading safetensors checkpoint shards: 0% Completed | 0/3 [00:00<?, ?it/s]\n",
"Loading safetensors checkpoint shards: 33% Completed | 1/3 [00:00<00:01, 1.21it/s]\n",
"Loading safetensors checkpoint shards: 67% Completed | 2/3 [00:01<00:00, 1.15it/s]\n",
"Loading safetensors checkpoint shards: 100% Completed | 3/3 [00:02<00:00, 1.16it/s]\n",
"Loading safetensors checkpoint shards: 100% Completed | 3/3 [00:02<00:00, 1.17it/s]\n",
"Loading safetensors checkpoint shards: 33% Completed | 1/3 [00:00<00:01, 1.15it/s]\n",
"Loading safetensors checkpoint shards: 67% Completed | 2/3 [00:01<00:00, 1.10it/s]\n",
"Loading safetensors checkpoint shards: 100% Completed | 3/3 [00:02<00:00, 1.12it/s]\n",
"Loading safetensors checkpoint shards: 100% Completed | 3/3 [00:02<00:00, 1.12it/s]\n",
"\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"INFO 12-03 19:04:27 model_runner.py:1077] Loading model weights took 13.5083 GB\n",
"INFO 12-03 19:04:28 worker.py:232] Memory profiling results: total_gpu_memory=93.00GiB initial_memory_usage=22.98GiB peak_torch_memory=19.00GiB memory_usage_post_profile=23.08GiB non_torch_memory=7.45GiB kv_cache_size=57.25GiB gpu_memory_utilization=0.90\n",
"INFO 12-03 19:04:29 gpu_executor.py:113] # GPU blocks: 29311, # CPU blocks: 2048\n",
"INFO 12-03 19:04:29 gpu_executor.py:117] Maximum concurrency for 32768 tokens per request: 14.31x\n",
"INFO 12-03 19:04:30 model_runner.py:1400] Capturing cudagraphs for decoding. This may lead to unexpected consequences if the model is not static. To run the model in eager mode, set 'enforce_eager=True' or use '--enforce-eager' in the CLI.\n",
"INFO 12-03 19:04:30 model_runner.py:1404] If out-of-memory error occurs during cudagraph capture, consider decreasing `gpu_memory_utilization` or switching to eager mode. You can also reduce the `max_num_seqs` as needed to decrease memory usage.\n",
"INFO 12-03 19:04:46 model_runner.py:1518] Graph capturing finished in 16 secs, took 0.32 GiB\n"
"INFO 12-04 09:47:34 model_runner.py:1077] Loading model weights took 13.5083 GB\n",
"INFO 12-04 09:47:35 worker.py:232] Memory profiling results: total_gpu_memory=93.00GiB initial_memory_usage=16.20GiB peak_torch_memory=19.00GiB memory_usage_post_profile=16.29GiB non_torch_memory=0.67GiB kv_cache_size=64.03GiB gpu_memory_utilization=0.90\n",
"INFO 12-04 09:47:35 gpu_executor.py:113] # GPU blocks: 32784, # CPU blocks: 2048\n",
"INFO 12-04 09:47:35 gpu_executor.py:117] Maximum concurrency for 32768 tokens per request: 16.01x\n",
"INFO 12-04 09:47:37 model_runner.py:1400] Capturing cudagraphs for decoding. This may lead to unexpected consequences if the model is not static. To run the model in eager mode, set 'enforce_eager=True' or use '--enforce-eager' in the CLI.\n",
"INFO 12-04 09:47:37 model_runner.py:1404] If out-of-memory error occurs during cudagraph capture, consider decreasing `gpu_memory_utilization` or switching to eager mode. You can also reduce the `max_num_seqs` as needed to decrease memory usage.\n",
"INFO 12-04 09:47:57 model_runner.py:1518] Graph capturing finished in 20 secs, took 0.32 GiB\n"
]
}
],
Expand Down Expand Up @@ -276,7 +265,7 @@
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
Expand Down Expand Up @@ -316,7 +305,7 @@
},
{
"cell_type": "code",
"execution_count": 8,
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
Expand All @@ -331,37 +320,51 @@
},
{
"cell_type": "code",
"execution_count": 13,
"execution_count": 10,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Batches: 100%|██████████| 1/1 [00:00<00:00, 90.72it/s]"
"Batches: 100%|██████████| 1/1 [00:00<00:00, 82.09it/s]\n",
"Processed prompts: 100%|██████████| 1/1 [00:01<00:00, 1.56s/it, est. speed input: 612.17 toks/s, output: 137.17 toks/s]\n"
]
},
}
],
"source": [
"answer_pib = rag_chain.invoke(\"Quelle est la définition du PIB ?\")"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"\n",
"Processed prompts: 100%|██████████| 1/1 [00:02<00:00, 2.27s/it, est. speed input: 421.12 toks/s, output: 139.34 toks/s]\n"
]
},
"data": {
"text/plain": [
"\" Le PIB (Produit Intérieur Brut) représente la somme des valeurs marchandes des produits et des services, qu'ils soient encore en phase de production ou non, qui sont produits et consommés dans un territoire donné durant une période donnée. C'est donc la quantification de l'activité économique du pays, globalement monétaire, évaluée au cours d'un certain temps.\\n\\n La source de cette définition se trouve dans la [présentation des définitions sur le site internet de l'Insee](https://www.insee.fr/fr/statistiques/4162165). Plus précisément, elle est décrite lors de la présentation du bilan économique pour l'année 2018.\\n\\n Il est à noter que la définition du PIB varie énormément selon les contextes. L'Insee présente des détails supplémentaires dans uneINTRODUCTION GAOM PAR ÎTÉLÉPHÉRIE RAGADEAU, [AUTRE SOURCE](https://www.insee.fr/fr/statistiques/4258088). En effet, la source fournit une introduction détaillée sur la théorie économique du PIB et son histoire.\\n\\n Pour en savoir plus sur le PIB, il est possible de consulter la page [Définitions, pour en savoir plus](https://www.insee.fr/fr/statistiques/5651387), qui présente notamment la distinction entre PIB courant et PIB constant et les differents complexes imputés.\\n\\n De plus, il est important de noter que le PIB est calculé annuellement pour chaque année. Les données pour le PIB 2018 peuvent être consultées dans la page [Définitions](https://www.insee.fr/fr/statistiques/4162165). De même, les données pour les années précédentes sont disponibles via des pages similaires, comme celles pour le PIB de 2019 [ici](https://www.insee.fr/fr/statistiques/3548949), 2017 [ici](https://www.insee.fr/fr/statistiques/3548949) et 2016 [ici](https://www.insee.fr/fr/statistiques/2852600).\\n\\n Les méthodes exactes pour calculer le PIB sont présentées dans la [source Sources et définitions](https://www.insee.fr/fr/statistiques/5426903).\\n\\n Enfin, il est possible de consulter la bibliographie sur la définition du PIB [ici](https://www.insee.fr/fr/statistiques/3196937). Des travaux théoriques et détaillés sur le PIB sont également disponibles [ici](https://www.insee.fr/fr/statistiques/3600202).\\n\\n Références :\\n - [Définitions](https://www.insee.fr/fr/statistiques/4162165)\\n - [Définitions et bibliographie](https://www.insee.fr/fr/statistiques/3196937)\\n - [Définitions et sources](https://www.insee.fr/fr/statistiques/4258088)\\n - [Définitions, pour en savoir plus](https://www.insee.fr/fr/statistiques/5651387)\\n - [Sources et définitions](https://www.insee.fr/fr/statistiques/5426903)\\n - [Définitions, bibliographie](https://www.insee.fr/fr/statistiques/3600202)\""
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"answer_pib"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"� Le PIB (Produit intérieur brut) est une mesure économique qui mesure le volume du produit économique d'une nation ou d'un territoire économique durant une période donnée. Ce produit intérieur brut représente la valeur du résultat de la transformation de matières premières, d'énergie ainsi que de services en biens et services finis.\n",
"\n",
"  Les mesures de PIB sont élaborées à travers différentes méthodes : la méthode des produits et des gains, la méthode des entreprises, et la méthode de la consommation finale. Le PIB à la conception des produits et des gains est le plus utilisé pour les mesures de produit intérieur brut du gouvernement français.\n",
"\n",
"  Il est important de noter que le PIB est un indicateur central pour peut-être entre autres de mesurer le niveau d'emploi, la croissance économique, et l'inflation dans une économie.\n",
"\n",
" Sources :\n",
" - <https://www.insee.fr/fr/statistiques/4162165>\n",
" - <https://www.insee.fr/fr/statistiques/2852600>\n",
" - <https://www.insee.fr/fr/statistiques/4258088>"
" Le PIB (Produit intérieur brut) est un indicateur économique important qui mesure l'ensemble des biens et des services produits par une économie en un fonctionnement normal sur un laps de temps donné. Il est calculé, à l'échelle nationale, sur la base des propriétés des entreprises, appels de mine, fermes, partenaires du secteur non marchand, statistiques harmonisées de la production de petites entreprises et de la consommation de ménages, régionaux et fins de compte. La (source pour la définition du PIB) donne plus de details sur cette définition économique. En outre, il est possible de trouver des exemples à partir de la définition de la publication (Doc 1 et Doc 5) sur le bilan économique de l'année 2016, 2017, 2018."
],
"text/plain": [
"<IPython.core.display.Markdown object>"
Expand All @@ -376,7 +379,7 @@
"\n",
"display(\n",
" Markdown(\n",
" rag_chain.invoke(\"Quelle est la définition du PIB ?\")\n",
" answer_pib.replace(\" \", \"\")\n",
" )\n",
")"
]
Expand Down
81 changes: 0 additions & 81 deletions src/data/ner.py

This file was deleted.

30 changes: 0 additions & 30 deletions src/db_building/build_database.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,36 +17,6 @@
logger = logging.getLogger(__name__)


def parse_collection_name(collection_name: str) -> dict[str, str | int] | None:
"""
Parse a concatenated string to extract the embedding model name, chunk size, and overlap size.
:param concatenated_string: A string in the format 'embeddingmodelname_chunkSize_overlapSize'
:return: A dictionary with the parsed values
"""
try:
# Split the string by the underscore delimiter
parts = collection_name.split("_")

# Ensure there are exactly three parts
if len(parts) != 3:
raise ValueError("String format is incorrect." "Expected format: 'modelname_chunkSize_overlapSize'")

# Extract and assign the parts
model_name = parts[0]
chunk_size = int(parts[1])
overlap_size = int(parts[2])

# Return the parsed values in a dictionary
return {
"model_name": model_name,
"chunk_size": chunk_size,
"overlap_size": overlap_size,
}
except Exception as e:
logger.error(f"Error parsing string: {e}")
return None


# BUILD VECTOR DATABASE FROM COLLECTION -------------------------


Expand Down
2 changes: 0 additions & 2 deletions src/model_building/build_llm_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import sys
from typing import Any

from langchain_huggingface import HuggingFacePipeline
from transformers import (
AutoConfig,
AutoModelForCausalLM,
Expand All @@ -14,7 +13,6 @@

from src.config import Configurable, DefaultFullConfig, FullConfig

# from src.model_building.custom_hf_pipeline import CustomHuggingFacePipeline
from .fetch_llm_model import cache_model_from_hf_hub

# Add the project root directory to sys.path
Expand Down
Loading

0 comments on commit 13aded0

Please sign in to comment.