Repository navigation
feat(dedup): support batch_size/process_batch in MinHashStage - #2423
Lingikaushikreddy wants to merge 2 commits into
Conversation
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]>
|
| 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 |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
| 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)] |
There was a problem hiding this comment.
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
| 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") | ||
|
|
There was a problem hiding this comment.
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]>
|
Thanks — three of the four were real, pushed in 9e68bdc. Fan-in breaks checkpoint resumability (P1) — agreed, and this was the important one. Invalid batch sizes lose work (P1) — agreed. The constructor now rejects a non-positive 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 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. Commits are signed and signed off. |
|
@greptile-apps the summary says two previously reported blocking issues remain outstanding at For the record, where I think each of the four stands after
If the two you mean include something I have mis-scoped above, point me at it and I will fix it. |
|
You're right—the summary is inconsistent with the findings and is stale/misgenerated. There were not two outstanding issues at
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 Tip: You can customize Greptile's behavior for this repo with |
|
@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 |
Description
Implements
process_batchforMinHashStage, 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_batchcoalesces 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_sizeis a new constructor argument defaulting to1, so existing pipelines keep the current one-task-in/one-file-out behavior. It can also be set through the existingwith_(batch_size=...).FileGroupTaskandDocumentBatchinputs are supported, reusing the same per-task read path asprocess.cudf.concat, so peak memory is one input frame plus the combined frame rather than every input frame at once.get_deterministic_hashover the batch's task ids, matching howIdentifyDuplicatesStagenames its fan-in output._stage_perfrecord, also mirroringIdentifyDuplicatesStage, so upstream timings are not dropped._read_task,_minhash_and_writeand_build_output_task, used by bothprocessandprocess_batch. The single-task path is unchanged.Usage
batch_sizedefaults to1, 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-taskprocessoutputs.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_perfmerged as intended, andprocessproducing the same output path, metadata and perf record as before the refactor.ruff checkis clean on both files.Checklist
batch_sizeis documented in theMinHashStageparameter docstring;process_batchhas its own docstring.)Commits are signed off (DCO). Happy to adjust the fan-in naming or the
_stage_perfmerge if you'd prefer different semantics here.