Skip to content

feat(dedup): support batch_size/process_batch in MinHashStage - #2423

Open
Lingikaushikreddy wants to merge 2 commits into
NVIDIA-NeMo:mainfrom
Lingikaushikreddy:feat/minhash-process-batch
Open

Lingikaushikreddy wants to merge 2 commits into
NVIDIA-NeMo:mainfrom
Lingikaushikreddy:feat/minhash-process-batch

Conversation

@Lingikaushikreddy

Copy link
Copy Markdown

Description

Implements process_batch for MinHashStage, closes #1465.

GPUs do best on large blocks (1-3GB) while CPU stages do best on small ones (~256MB), but a pipeline has to pick one read blocksize for both. Saturating the GPU for minhash therefore meant risking OOM in the CPU stages upstream.

MinHashStage.process_batch coalesces several input tasks into a single minhash computation. As described in the issue, inputs are still read one at a time — that read is no more saturated than it is today — but the concatenated frame is hashed and written as one block, which decouples the read blocksize from the size of the block the GPU actually sees.

Details:

  • batch_size is a new constructor argument defaulting to 1, so existing pipelines keep the current one-task-in/one-file-out behavior. It can also be set through the existing with_(batch_size=...).
  • Both FileGroupTask and DocumentBatch inputs are supported, reusing the same per-task read path as process.
  • Inputs are read and appended one at a time before a single cudf.concat, so peak memory is one input frame plus the combined frame rather than every input frame at once.
  • The combined output file is named from get_deterministic_hash over the batch's task ids, matching how IdentifyDuplicatesStage names its fan-in output.
  • The fan-in keeps the first task's metadata plus every input's final _stage_perf record, also mirroring IdentifyDuplicatesStage, so upstream timings are not dropped.
  • The shared read/compute/write steps are factored into _read_task, _minhash_and_write and _build_output_task, used by both process and process_batch. The single-task path is unchanged.

Usage

from nemo_curator.stages.deduplication.fuzzy.minhash import MinHashStage

# Read in small blocks (CPU-friendly), minhash in large ones (GPU-friendly).
stage = MinHashStage(
    output_path="/path/to/minhash/output",
    text_field="text",
    read_format="parquet",
    batch_size=8,   # coalesce 8 input tasks into one minhash computation + one output file
)

# Equivalent, via the existing override helper:
stage = MinHashStage(output_path="...", text_field="text", read_format="parquet").with_(batch_size=8)

batch_size defaults to 1, which is the current behavior.

Testing

Added to tests/stages/deduplication/fuzzy/test_minhash_stage.py:

  • test_process_batch_matches_per_task_processing — the key one: batching changes how many files are written, never the signatures. Compares the batched output against the concatenation of per-task process outputs.
  • test_process_batch_carries_metadata_and_stage_perf — the combined task keeps the first input's metadata.
  • test_process_batch_empty_returns_empty_list, test_process_batch_without_setup — edge cases.
  • test_batch_size_defaults_to_one_and_is_configurable — the default stays 1.

These are @pytest.mark.gpu (cuDF), so they need CI to run end to end. Locally I verified the new control flow with the GPU/infra dependencies stubbed: inputs read one by one in order, exactly one write per batch, deterministic output name, _stage_perf merged as intended, and process producing the same output path, metadata and perf record as before the refactor. ruff check is clean on both files.

Checklist

  • I am familiar with the Contributing Guide.
  • New or Existing tests cover these changes.
  • The documentation is up to date with these changes. (batch_size is documented in the MinHashStage parameter docstring; process_batch has its own docstring.)

Commits are signed off (DCO). Happy to adjust the fan-in naming or the _stage_perf merge if you'd prefer different semantics here.

GPUs do best on large blocks (1-3GB), CPU stages on small ones (~256MB).
A pipeline had to pick one read blocksize for both, so saturating the GPU
for minhash meant risking OOM in the CPU stages ahead of it.

MinHashStage now implements `process_batch`, so several input tasks can be
coalesced into one minhash computation. Inputs are still read one at a
time — that read is no more saturated than before — but the concatenated
frame is hashed and written as a single block, which decouples the read
blocksize from the size of the block the GPU sees.

`batch_size` is a new constructor argument defaulting to 1, so existing
pipelines keep the previous one-task-in, one-file-out behavior. The
combined output file is named from a deterministic hash of the batch's
task ids, and the fan-in keeps the first task's metadata plus every
input's final performance record, mirroring IdentifyDuplicatesStage.

The shared read/compute/write steps are factored into helpers used by both
`process` and `process_batch`, so the single-task path is unchanged.

Fixes NVIDIA-NeMo#1465

Signed-off-by: Lingikaushikreddy <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Sep 17, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@greptile-apps

greptile-apps Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 3/5

The PR does not yet appear safe to merge because two previously reported blocking issues remain outstanding.

Findings

  1. P1 Concatenation doubles memory pressure ▶
  2. P1 Invalid batch sizes lose work ▶
  3. P1 Fan-in breaks checkpoint resumability ▶
  4. P2 Performance merging remains untested ▶

Summary

Adds configurable task batching to MinHashStage, allowing multiple file-group or document-batch inputs to be concatenated for one GPU MinHash computation and one deterministic output file.

  • Refactors shared read, MinHash, write, and output-task construction paths.
  • Preserves metadata and selected upstream performance records across fan-in.
  • Adds validation for non-positive batch sizes and marks constructor-configured fan-in stages non-resumable.
  • Expands tests for batching equivalence, metadata, performance records, validation, and resumability configuration.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
    A[Input tasks] --> B{batch_size}
    B -- 1 --> C[Read one task]
    B -- greater than 1 --> D[Read each task]
    D --> E[Concatenate GPU frames]
    C --> F[Compute MinHash]
    E --> F
    F --> G[Write Parquet]
    G --> H[Emit FileGroupTask]
Loading

Reviews (2) · Last reviewed commit: "fix(dedup): address review on MinHashSta..."

Comment on lines +375 to +379
frames = []
for task in tasks:
frames.append(self._read_task(task))
df = frames[0] if len(frames) == 1 else cudf.concat(frames, ignore_index=True)
del frames

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Concatenation doubles memory pressure

Every input frame remains referenced by frames until cudf.concat finishes allocating the combined frame. A batch near the available GPU memory can therefore require roughly twice the combined input size and OOM, contrary to the goal of retaining only one input frame plus the combined frame.

Knowledge Base Used: Exact and fuzzy deduplication

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

# Set ProcessingStage attributes
self.name = self.__class__.__name__
self.resources = Resources(gpus=1.0) # Requires 1 GPU
self.batch_size = batch_size

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Invalid batch sizes lose work

The new public batch_size argument is stored without checking that it is positive. The actor-pool executor later uses it as the step in range(0, len(tasks), batch_size), so zero fails late with a raw ValueError, while a negative value creates no batches and silently returns no output for the input tasks.

Comment on lines +347 to +391
def process_batch(self, tasks: list[FileGroupTask | DocumentBatch]) -> list[FileGroupTask]:
"""
Process several tasks as a single minhash computation.

Inputs are read one at a time (the read is not saturated any more than it is in
:meth:`process`), but the concatenated frame is hashed and written as one block. This
lets a pipeline use a small read blocksize — which CPU stages prefer, and which avoids
host OOM — while still handing the GPU a batch large enough to saturate it.

Args:
tasks: FileGroupTasks and/or DocumentBatches to coalesce.

Returns:
A single-element list holding the FileGroupTask for the combined minhash file, or an
empty list when there is nothing to process.
"""
if not tasks:
return []

self._check_setup()

for task in tasks:
if not self.validate_input(task):
msg = f"Task {task!s} failed validation for stage {self}"
raise ValueError(msg)

# Read the inputs one by one and concatenate, so peak memory is one input frame plus the
# combined frame rather than every input frame at once.
frames = []
for task in tasks:
frames.append(self._read_task(task))
df = frames[0] if len(frames) == 1 else cudf.concat(frames, ignore_index=True)
del frames

output_file = self.output_fs.sep.join(
[self.output_path, get_deterministic_hash([task.task_id for task in tasks], tasks[0].task_id) + ".parquet"]
)
self._minhash_and_write(df, output_file)

# Keep the shared history from the first task, plus each other input's final record, so
# this fan-in does not drop the upstream timings. Mirrors IdentifyDuplicatesStage.
stage_perf = list(tasks[0]._stage_perf)
stage_perf.extend(task._stage_perf[-1] for task in tasks[1:] if task._stage_perf)

return [self._build_output_task(tasks[0], output_file, stage_perf)]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Fan-in breaks checkpoint resumability

With batch_size > 1, this method collapses several inputs into one output while the stage still inherits is_resumable=True. A checkpointed pipeline therefore accepts the stage, but resumability accounting cannot attribute the merged output to its sources and skips their counter updates. Those sources never become completed and are processed again on the next run. The stage should either declare this fan-in non-resumable, as analogous aggregation stages do, or preserve attributable source lineage.

Knowledge Base Used: Deduplication systems

Comment on lines +700 to +730
tasks = []
for i in range(3):
input_file = tmp_path / f"meta-{i}.jsonl"
pd.DataFrame({"text": [f"document number {i}"]}).to_json(input_file, orient="records", lines=True)
tasks.append(
FileGroupTask(dataset_name="meta", data=[str(input_file)], _metadata={"source": f"shard-{i}"})
)

stage = MinHashStage(
output_path=str(tmp_path / "meta_out"),
text_field="text",
read_format="jsonl",
num_hashes=64,
char_ngrams=3,
pool=False,
batch_size=3,
)
stage.setup()
outputs = stage.process_batch(tasks)
stage.teardown()

assert len(outputs) == 1
assert outputs[0].dataset_name == "meta_minhash"
assert outputs[0]._metadata["source"] == "shard-0"
assert outputs[0]._metadata["num_hashes"] == 64
assert outputs[0]._metadata["minhash_field"] == "_minhash_signature"

def test_process_batch_empty_returns_empty_list(self, tmp_path: Path) -> None:
"""An empty batch is a no-op and does not require a live processor."""
stage = MinHashStage(output_path=str(tmp_path / "empty_batch"), text_field="text", read_format="jsonl")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Performance merging remains untested

This test gives every input an empty _stage_perf history and only checks metadata, so it cannot catch regressions in the new logic that selectively combines performance records. Add distinct records to the input tasks and assert the expected merged order and contents.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

- Reject a non-positive batch_size in the constructor. The actor-pool
  executor uses it as the step in range(0, len(tasks), batch_size), where
  0 fails late with a raw ValueError and a negative value produces no
  batches and silently drops the input tasks.

- Mark the stage non-resumable when batch_size > 1. Batching fans several
  inputs into one output, so the input->output mapping is no longer
  source-attributable and resumability accounting cannot credit the
  sources, which would reprocess them on every resume. Same reasoning as
  ConnectedComponentsStage and LSH. batch_size == 1 stays 1:1 and stays
  resumable, so existing checkpointed pipelines are unaffected.

- Correct the comment above the concat. It claimed peak memory was one
  input frame plus the combined frame; cudf.concat needs the inputs and
  the combined copy resident together, so the real peak is roughly twice
  the combined input size. The single concat is kept deliberately —
  concatenating incrementally would not lower that peak and would recopy
  the accumulator at every step. Documented on the batch_size parameter
  so the value can be sized against free GPU memory.

- Give the fan-in test distinct StagePerfStats records per input and
  assert the merged order, so it actually covers the perf-merging logic.

Adds tests for the rejected batch sizes and for is_resumable tracking
batch_size.

Signed-off-by: Lingikaushikreddy <[email protected]>
@Lingikaushikreddy

Copy link
Copy Markdown
Author

Thanks — three of the four were real, pushed in 9e68bdc.

Fan-in breaks checkpoint resumability (P1) — agreed, and this was the important one. MinHashStage inherited is_resumable = True, which is correct at batch_size=1 but wrong once batching fans several inputs into one output. Now self.is_resumable = batch_size == 1, so the default stays 1:1 and resumable and existing checkpointed pipelines are unaffected, while a batched stage is rejected up front by the Pipeline.run(checkpoint_path=...) check rather than silently reprocessing its sources. Matches the reasoning already spelled out on ConnectedComponentsStage and LSH.

Invalid batch sizes lose work (P1) — agreed. The constructor now rejects a non-positive batch_size. A negative value silently producing no batches was the worse half of this.

Performance merging remains untested (P2) — agreed, the test gave every input an empty history so it could not have caught a regression. Inputs now get two distinct StagePerfStats records each, and the test asserts the merged order, which distinguishes "kept the whole history" (first task) from "kept only the final record" (the rest).

Concatenation doubles memory pressure (P1) — correct about the behaviour, but the problem is my comment rather than the code, so I fixed the comment and kept the single concat. cudf.concat needs the inputs and the combined copy resident together, so peak really is ~2x the combined input size; my comment claimed one input frame plus the combined frame, which was wrong. Concatenating incrementally would not lower that peak — the accumulator and its new copy still coexist at each step — and it recopies the accumulator on every step, so it is worse on time for no memory gain. IdentifyDuplicatesStage builds a list and concats once for the same reason. Since the ~2x factor is inherent to batching rather than a bug, I documented it on the batch_size parameter so the value can be sized against free GPU memory. Happy to revisit if you would rather cap this some other way.

Commits are signed and signed off.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added the waiting-on-maintainers Waiting on maintainers to respond label Sep 20, 2026
@Lingikaushikreddy

Copy link
Copy Markdown
Author

@greptile-apps the summary says two previously reported blocking issues remain outstanding at 9e68bdc, but the findings list does not mark which two. Could you name them?

For the record, where I think each of the four stands after 9e68bdc:

  1. Concatenation doubles memory pressure — comment corrected, code deliberately unchanged. cudf.concat needs the inputs and the combined copy resident together, so ~2x the combined input size is inherent to batching. Concatenating incrementally would not lower that peak and would recopy the accumulator at every step; IdentifyDuplicatesStage builds a list and concats once for the same reason. I documented the factor on batch_size so it can be sized against free GPU memory. If this is one of the two, I am glad to discuss alternatives, but I do not think an incremental concat is one.
  2. Invalid batch sizes lose work — fixed; the constructor rejects a non-positive batch_size.
  3. Fan-in breaks checkpoint resumability — fixed; is_resumable = batch_size == 1, so batched use is rejected by the Pipeline.run(checkpoint_path=...) check while the 1:1 default stays resumable.
  4. Performance merging remains untested — fixed; inputs carry distinct StagePerfStats records and the test asserts the merged order.

If the two you mean include something I have mis-scoped above, point me at it and I will fix it.

@greptile-apps

greptile-apps Bot commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

You're right—the summary is inconsistent with the findings and is stale/misgenerated. There were not two outstanding issues at 9e68bdc.

  • Concatenation doubles memory pressure: the behavior remains intentionally unchanged and is now documented as a batching tradeoff. If the review treats the GPU memory risk itself as blocking, this is the only remaining concern; incremental concatenation would not resolve it.
  • Invalid batch sizes: fixed by constructor validation.
  • Checkpoint resumability: fixed by setting is_resumable = batch_size == 1.
  • Performance merging: fixed and covered by the updated test.

The summary should therefore not have said that two blocking issues remained. The accurate status is either no blocking findings, or one documented design concern around the inherent peak memory cost of cudf.concat, depending on the project's desired memory policy.

Tip: You can customize Greptile's behavior for this repo with .greptile/rules.md and .greptile/config.json.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added waiting-on-maintainers Waiting on maintainers to respond and removed waiting-on-maintainers Waiting on maintainers to respond labels Sep 21, 2026
@Lingikaushikreddy

Copy link
Copy Markdown
Author

@praateekmahajan @ayushdg, a gentle ping on this one when you have time. Greptile's remaining notes were resolved on 2026-09-21, and the PR is still mergeable.

I should also have mentioned earlier that #1897 targets the same issue (#1465) and has been open since April without review. The main difference is resumability: here MinHashStage reports itself as not resumable when batch_size > 1, because fanning several inputs into one output breaks the source attribution that checkpoint resume relies on, and #1897 keeps is_resumable = True in that case. I'm happy to go with whichever you prefer, or to fold the resumability part into #1897 if that's easier to review.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added waiting-on-maintainers Waiting on maintainers to respond and removed waiting-on-maintainers Waiting on maintainers to respond labels Oct 19, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-request waiting-on-maintainers Waiting on maintainers to respond

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support batchsize/process_batch in the minHash stage

2 participants