-
Notifications
You must be signed in to change notification settings - Fork 109
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
Fix bugs in retriever sdg notebook #522
Open
vinay-raman
wants to merge
17
commits into
NVIDIA:main
Choose a base branch
from
vinay-raman:vinayraman/nvbug_5025154_fix
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
e5a88c9
Signed-off by [email protected]
vinay-raman f6a47f9
Merge branch 'main' into vinayraman/nvbug_5025154_fix
vinay-raman 8a6deb9
Signed-off by [email protected]
vinay-raman 75c869e
fixed qa bug 5008113, Signed-off by [email protected]
vinay-raman 547c849
bug fixes for generator, Signed-off by [email protected]
vinay-raman cf0ec14
fixed precommit, Signed-off by [email protected]
vinay-raman d9f7be3
fixed filters, Signed-off by [email protected]
vinay-raman d9ee0ee
fixed all issues, Signed-off by [email protected]
vinay-raman d892288
fixed bug with document id, Signed-off by [email protected]
vinay-raman 9fa6144
check if filtering pipeline is present, Signed-off by [email protected]
vinay-raman b05f61a
fixed notebook, Signed-off by [email protected]
vinay-raman 2623d0c
added functionality to filter pre-generated datasets, Signed-off by v…
vinay-raman 6be54ef
separated generation & filtering pipelines, Signed-off by viraman@nvi…
vinay-raman 49d8eb1
fixed pre-commit, Signed-off by [email protected]
vinay-raman 6ac6fd9
minor changes, Signed-off by [email protected]
vinay-raman 54e54be
Merge branch 'main' into vinayraman/nvbug_5025154_fix
vinay-raman 0e45f13
fixed Ryan Wolf's comments, Signed-off by [email protected]
vinay-raman File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
205 changes: 205 additions & 0 deletions
205
tutorials/nemo-retriever-synthetic-data-generation/filter.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,205 @@ | ||
# 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 importlib | ||
import os | ||
import shutil | ||
import time | ||
from typing import Any, List | ||
|
||
import numpy as np | ||
from dask.diagnostics import ProgressBar | ||
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 ( | ||
AnswerabilityFilter, | ||
EasinessFilter, | ||
NonAlphaNumericFilter, | ||
) | ||
from nemo_curator.modules.filter import Score, ScoreFilter | ||
from nemo_curator.utils.file_utils import get_all_files_paths_under | ||
|
||
|
||
def get_pipeline(args: Any) -> Any: | ||
|
||
cfg = RetrieverEvalSDGConfig.from_yaml(args.pipeline_config) | ||
# update api_key from input args | ||
cfg.api_key = args.api_key | ||
|
||
filters = [] | ||
if cfg.easiness_filter: | ||
filters.append( | ||
ScoreFilter( | ||
EasinessFilter( | ||
cfg.base_url, | ||
cfg.api_key, | ||
cfg.easiness_filter, | ||
cfg.percentile, | ||
cfg.truncate, | ||
cfg.batch_size, | ||
), | ||
text_field=["text", "question"], | ||
score_field="easiness_scores", | ||
) | ||
) | ||
if cfg.answerability_filter: | ||
filters.append( | ||
ScoreFilter( | ||
AnswerabilityFilter( | ||
cfg.base_url, | ||
cfg.api_key, | ||
cfg.answerability_filter, | ||
cfg.answerability_system_prompt, | ||
cfg.answerability_user_prompt_template, | ||
cfg.num_criteria, | ||
), | ||
text_field=["text", "question"], | ||
score_field="answerability_scores", | ||
) | ||
) | ||
|
||
if filters: | ||
filtering_pipeline = Sequential(filters) | ||
else: | ||
filtering_pipeline = None | ||
|
||
return filtering_pipeline | ||
|
||
|
||
def write_to_beir( | ||
args: Any, filtered_dataset: DocumentDataset, input_dataset: DocumentDataset | ||
): | ||
|
||
df = filtered_dataset.df | ||
df = df.compute() | ||
|
||
save_dir = os.path.join(args.output_dir, "beir", "filtered") | ||
qrels_save_dir = os.path.join(args.output_dir, "beir", "filtered", "qrels") | ||
corpus_save_path = os.path.join(args.output_dir, "beir", "filtered", "corpus.jsonl") | ||
queries_save_path = os.path.join( | ||
args.output_dir, "beir", "filtered", "queries.jsonl" | ||
) | ||
|
||
os.makedirs(save_dir) | ||
os.makedirs(qrels_save_dir) | ||
|
||
df[["question-id", "question"]].rename( | ||
columns={"question-id": "_id", "question": "text"} | ||
).to_json(queries_save_path, lines=True, orient="records") | ||
|
||
corpus_file_path = os.path.join(args.output_dir, "beir", "filtered", "corpus.jsonl") | ||
input_df = input_dataset.df.compute() # we need the full corpus of documents | ||
input_df[["_id", "text"]].to_json(corpus_save_path, lines=True, orient="records") | ||
|
||
df[["question-id", "_id", "score"]].rename( | ||
columns={"question-id": "query-id", "_id": "corpus-id"} | ||
).to_csv(os.path.join(qrels_save_dir, "test.tsv"), sep="\t", index=False) | ||
|
||
|
||
def main(): | ||
parser = argparse.ArgumentParser() | ||
parser.add_argument( | ||
"--input-dir", | ||
type=str, | ||
default="", | ||
help="File path of input file containing document chunks for synthetic data generation", | ||
) | ||
parser.add_argument( | ||
"--pipeline-config", | ||
type=str, | ||
default="", | ||
help="Pipeline configuartion yaml file path", | ||
) | ||
parser.add_argument( | ||
"--output-dir", | ||
type=str, | ||
default="", | ||
help="Output dir for generated data", | ||
) | ||
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.", | ||
) | ||
parser.add_argument( | ||
"--n-partitions", | ||
type=int, | ||
default=1, | ||
help="Number of partitions for parallel processing of data.", | ||
) | ||
|
||
args = parser.parse_args() | ||
|
||
if not os.path.exists(args.output_dir): | ||
os.makedirs(args.output_dir) | ||
elif not any(os.scandir(args.output_dir)): | ||
print("Provided directory exists but is empty, using the empty directory") | ||
else: | ||
raise ValueError("Output directory exists already, use a new directory!") | ||
|
||
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( | ||
"Input directory not provided, should contain files in jsonl format" | ||
) | ||
|
||
if args.n_partitions: | ||
ddf = input_dataset.df | ||
n_data = len(ddf) | ||
if args.n_partitions < n_data: | ||
ddf = ddf.repartition(npartitions=args.n_partitions) | ||
input_dataset = DocumentDataset(ddf) | ||
else: | ||
print("Number of partitions greater than data size, using 1 partition") | ||
|
||
filtering_pipeline = get_pipeline(args) | ||
|
||
if filtering_pipeline: | ||
print("Filtering data ...") | ||
st_time = time.time() | ||
filtered_dataset = filtering_pipeline(input_dataset) | ||
filtered_dataset.persist() | ||
print("Writing filtered data to disk ...") | ||
all_save_dir = os.path.join(args.output_dir, "jsonl", "filtered") | ||
os.makedirs(all_save_dir) | ||
filtered_dataset.to_json(all_save_dir) | ||
print("Time taken to filter data = {:.2f} s".format(time.time() - st_time)) | ||
|
||
print("Writing filtered data in beir format") | ||
# saving in beir format | ||
write_to_beir(args, filtered_dataset, input_dataset) | ||
else: | ||
print("Filtering config not correct, filtering pipeline is empty") | ||
|
||
print("Filtering complete!") | ||
|
||
|
||
if __name__ == "__main__": | ||
dask_client = get_client() | ||
main() | ||
# dask_client.cancel(dask_client.futures, force=True) | ||
vinay-raman marked this conversation as resolved.
Show resolved
Hide resolved
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What is the difference between this
filter.py
,generate.py
, andmain.py
? They look nearly identical. They also all look to be CLI scripts but onlymain.py
is mentioned in the README.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
README has both generate.py and filter.py mentioned, please have a look.
This is needed if the user just needs to generate data or filter pre-generated data.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Instead of adding two files, can you just add two command line arguments like so?
--generate-only
--filter-only
With two new files, it's very hard to tell if the differences between them are correct or buggy. CLI args in a single file make it much easier to maintain.