Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hard negative mining for Retriever fine-tuning #523

Open
wants to merge 19 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
e5a88c9
Signed-off by viraman@nvidia.com
vinay-raman Feb 5, 2025
f6a47f9
Merge branch 'main' into vinayraman/nvbug_5025154_fix
vinay-raman Feb 5, 2025
971df10
Signed-off by viraman@nvidia.com
vinay-raman Feb 5, 2025
8a6deb9
Signed-off by viraman@nvidia.com
vinay-raman Feb 5, 2025
75c869e
fixed qa bug 5008113, Signed-off by viraman@nvidia.com
vinay-raman Feb 6, 2025
547c849
bug fixes for generator, Signed-off by viraman@nvidia.com
vinay-raman Feb 10, 2025
cf0ec14
fixed precommit, Signed-off by viraman@nvidia.com
vinay-raman Feb 10, 2025
d9f7be3
fixed filters, Signed-off by viraman@nvidia.com
vinay-raman Feb 11, 2025
d9ee0ee
fixed all issues, Signed-off by viraman@nvidia.com
vinay-raman Feb 11, 2025
0e69b74
fixed model caching in hard negative mining, Signed-off by viraman@nv…
vinay-raman Feb 11, 2025
d5d051a
fixed minor issues, Signed-off by viraman@nvidia.com
vinay-raman Feb 11, 2025
f512886
fixed merge conflicts, Signed-off by viraman@nvidia.com
vinay-raman Feb 11, 2025
794ef20
fixed minor bug, Signed-off by viraman@nvidia.com
vinay-raman Feb 11, 2025
531b5ac
fixed minor issues, Signed-off by viraman@nvidia.com
vinay-raman Feb 11, 2025
2082f16
removed duplicates in pos_docs, Signed-off by viraman@nvidia.com
vinay-raman Feb 11, 2025
bb9ed81
Merge branch 'main' into vinayraman/hardnegativemining
vinay-raman Feb 11, 2025
94800e5
Merge branch 'main' into vinayraman/hardnegativemining
vinay-raman Feb 19, 2025
1b122f0
Merge branch 'main' into vinayraman/hardnegativemining
vinay-raman Feb 26, 2025
6acaa62
fixed some comments, added input file for hard negative mining & test…
vinay-raman Feb 27, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion nemo_curator/modules/semantic_dedup/clusteringmodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

import logging
import os
import pdb
import shutil
import time
from typing import Optional, Union
Expand Down Expand Up @@ -124,7 +125,9 @@ def __call__(self, embeddings_dataset: DocumentDataset):
)

with performance_report_if_with_ts_suffix(self.profile_dir, "clustering-model"):
embeddings_df = embeddings_df[[self.id_col, self.embedding_column]]

# embeddings_df = embeddings_df[[self.id_col, self.embedding_col]]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why was this change made?


embeddings_df = embeddings_df.repartition(
partition_size=self.clustering_input_partition_size
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,30 @@ class RetrieverEvalSDGConfig(BaseConfig):
Question:
{question}
"""


@dataclass
class RetrieverHardNegativeMiningConfig(BaseConfig):
"""
Configuration for mining hard negatives

Attributes:

"""

model_name: str = "nvdev/nvidia/llama-3.2-nv-embedqa-1b-v2"
model_type: str = "nvidia"
base_url: str = "https://integrate.api.nvidia.com/v1"
api_key: str = None
truncate: str = "END"
hard_negatives_to_mine: int = 4
hard_neg_mining_algorithm: str = "topk_abs"
max_hardness_threshold: float = 0.75
min_hardness_threshold: float = 0
query_prefix: str = ""
passage_prefix: str = ""
percpos: float = 0.95
min_cluster_size: int = 50
max_number_clusters: int = 200
cluster_output_dir: str = "/tmp/clusters"
logger_output_dir: str = "/tmp/logs"
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# HARD-NEGATIVE MINING parameters

# base_url: "https://integrate.api.nvidia.com/v1"
model_name: "sentence-transformers/all-MiniLM-L6-v2"
model_type: "hf"
query_prefix: "query:"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason why the defaults in the dataclass don't match the defaults in the yaml?

passage_prefix: "passage:"
api_key: "your api key here"
truncate: "END"
hard_negatives_to_mine: 4
hard_neg_mining_algorithm: "topk_percpos"
percpos: 0.95


# SEMANTIC CLUSTERING parameters
min_cluster_size: 100
max_number_clusters: 200
cluster_output_dir: "/workspace/hnm/clusters"
logger_output_dir: "/workspace/hnm/logs"
7 changes: 6 additions & 1 deletion tutorials/nemo-retriever-synthetic-data-generation/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
from dask.distributed import progress
from retriever_evalset_generator import RetrieverEvalSetGenerator

from config.config import RetrieverEvalSDGConfig
from nemo_curator import AsyncOpenAIClient, ScoreFilter, Sequential, get_client
from nemo_curator.datasets import DocumentDataset
from nemo_curator.filters import (
Expand All @@ -36,6 +35,11 @@
from nemo_curator.modules.filter import Score, ScoreFilter
from nemo_curator.utils.file_utils import get_all_files_paths_under

config = importlib.import_module(
"tutorials.nemo-retriever-synthetic-data-generation.config.config"
)
RetrieverEvalSDGConfig = config.RetrieverEvalSDGConfig


def get_pipeline(args: Any) -> Any:

Expand All @@ -53,6 +57,7 @@ def get_pipeline(args: Any) -> Any:
sdg_pipeline = None

filters = []

if args.pipeline_type == "filter":
if cfg.easiness_filter:
filters.append(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import glob
import importlib
import os
import pdb
import shutil
import time
from pathlib import Path
from typing import Any, List

from retriever_hardnegative_miner import HardNegativeMiner
from tqdm.dask import TqdmCallback

from config.config import RetrieverHardNegativeMiningConfig
from nemo_curator.datasets import DocumentDataset
from nemo_curator.utils.distributed_utils import get_client
from nemo_curator.utils.file_utils import get_all_files_paths_under


def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"--input-dir",
type=str,
default="",
help="Input dir path containing annotated data files in jsonl format",
)
parser.add_argument(
"--hard-negative-mining-config",
type=str,
default="",
help="Configuration yaml file path containing config for hard negative mining",
)
parser.add_argument(
"--output-dir",
type=str,
default="",
help="Output file containing hard negatives",
)
parser.add_argument(
"--api-key",
type=str,
default=None,
help="The API key to use for the synthetic data generation LLM client.",
)
parser.add_argument(
"--api-timeout",
type=int,
default=120,
help="The timeout value for API calls in seconds.",
)
args = parser.parse_args()

if not os.path.exists(args.input_dir):
raise ValueError("Input directory not found")

if os.path.exists(args.output_dir):
raise ValueError("Output dir exists already, use a new file name!")

if args.input_dir:
input_files = get_all_files_paths_under(args.input_dir, keep_extensions="part")
input_dataset = DocumentDataset.read_json(input_files)
else:
raise ValueError("provide input file path")

if args.hard_negative_mining_config:
cfg = RetrieverHardNegativeMiningConfig.from_yaml(
args.hard_negative_mining_config
)

else:
raise ValueError("provide config for hard negative mining")
if args.api_key:
cfg.api_key = args.api_key

mine_hard_negatives = HardNegativeMiner(cfg)
print("Mining hard negatives ...")
st_time = time.time()
mined_dataset = mine_hard_negatives(input_dataset)

print("Time taken = {:.2f} s".format(time.time() - st_time))
print("Saving data in jsonl format ...")
mined_dataset.df.to_json(
os.path.join(args.output_dir), lines=True, orient="records"
)


if __name__ == "__main__":
dask_client = get_client(cluster_type="gpu")
main()
100 changes: 100 additions & 0 deletions tutorials/nemo-retriever-synthetic-data-generation/repartition.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import glob
import importlib
import os
import pdb
import shutil
import time
from typing import Any, List

from retriever_hardnegative_miner import HardNegativeMiner
from tqdm.dask import TqdmCallback

from config.config import RetrieverHardNegativeMiningConfig
from nemo_curator.datasets import DocumentDataset
from nemo_curator.utils.distributed_utils import get_client
from nemo_curator.utils.file_utils import get_all_files_paths_under


def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"--input-dir",
type=str,
default="",
help="Input dir path containing annotated data files in jsonl format",
)
parser.add_argument(
"--hard-negative-mining-config",
type=str,
default="",
help="Configuration yaml file path containing config for hard negative mining",
)
parser.add_argument(
"--output-dir",
type=str,
default="",
help="Output file containing clustered dataset",
)
parser.add_argument(
"--api-key",
type=str,
default=None,
help="The API key to use for the synthetic data generation LLM client.",
)
parser.add_argument(
"--api-timeout",
type=int,
default=120,
help="The timeout value for API calls in seconds.",
)
args = parser.parse_args()

if not os.path.exists(args.input_dir):
raise ValueError("Input directory not found")

if os.path.exists(args.output_dir):
raise ValueError("Output dir exists already, use a new file name!")

if args.input_dir:
input_files = get_all_files_paths_under(args.input_dir, keep_extensions="jsonl")
input_dataset = DocumentDataset.read_json(input_files)
else:
raise ValueError("provide input file path")
if args.hard_negative_mining_config:
cfg = RetrieverHardNegativeMiningConfig.from_yaml(
args.hard_negative_mining_config
)
else:
raise ValueError("provide config for hard negative mining")
if args.api_key:
cfg.api_key = args.api_key

st_time = time.time()
miner = HardNegativeMiner(cfg)
clustered_dataset = miner.repartition_semantic_similarity(input_dataset)
clustered_dataset.persist()

# saving clustered dataset
print("saving clustered dataset")
clustered_dataset.df.to_json(os.path.join(args.output_dir, "clustered_dataset"))
print("Time taken to cluster data = {:.2f} s".format(time.time() - st_time))


if __name__ == "__main__":
dask_client = get_client(cluster_type="gpu")
main()
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@
from tqdm import tqdm

tqdm.pandas()

# from tqdm.dask import TqdmCallback
import importlib

import dask.array as da
Expand Down Expand Up @@ -145,7 +143,6 @@ def _process_on_partition(self, df: pd.DataFrame) -> pd.DataFrame:

df = df.explode("qa_pairs").reset_index(drop=True)
df["question"] = df["qa_pairs"].apply(lambda x: x["question"])

df["question-id"] = df["question"].apply(self._get_random_hash)
df["answer"] = df["qa_pairs"].apply(lambda x: x["answer"])
df["score"] = df["question"].apply(lambda x: 1)
Expand Down
Loading