|
| 1 | +# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import argparse |
| 16 | +import os |
| 17 | + |
| 18 | +import pyarrow as pa |
| 19 | +import pyarrow.parquet as pq |
| 20 | +import ray |
| 21 | +from loguru import logger |
| 22 | + |
| 23 | +from nemo_curator.core.client import RayClient |
| 24 | +from nemo_curator.utils.file_utils import get_all_file_paths_under |
| 25 | + |
| 26 | + |
| 27 | +def _split_table(table: pa.Table, target_size: int) -> list[pa.Table]: |
| 28 | + # Split table into two chunks |
| 29 | + tables = [table.slice(0, table.num_rows // 2), table.slice(table.num_rows // 2, table.num_rows)] |
| 30 | + results = [] |
| 31 | + for t in tables: |
| 32 | + if t.nbytes > target_size: |
| 33 | + # If still above the target size, continue spliting until chunks |
| 34 | + # are below the target size |
| 35 | + results.extend(_split_table(t, target_size=target_size)) |
| 36 | + else: |
| 37 | + results.append(t) |
| 38 | + return results |
| 39 | + |
| 40 | + |
| 41 | +def _write_table_to_file(table: pa.Table, outdir: str, output_prefix: str, ext: str, file_idx: int) -> int: |
| 42 | + output_file = os.path.join(outdir, f"{output_prefix}_{file_idx}{ext}") |
| 43 | + pq.write_table(table, output_file) |
| 44 | + logger.debug(f"Saved {output_file} (~{table.nbytes / (1024 * 1024):.2f} MB)") |
| 45 | + return file_idx + 1 |
| 46 | + |
| 47 | + |
| 48 | +@ray.remote |
| 49 | +def split_parquet_file_by_size(input_file: str, outdir: str, target_size_mb: int) -> None: |
| 50 | + root, ext = os.path.splitext(input_file) |
| 51 | + if not ext: |
| 52 | + ext = ".parquet" |
| 53 | + outfile_prefix = os.path.basename(root) |
| 54 | + |
| 55 | + logger.info(f"""Splitting parquet file... |
| 56 | +
|
| 57 | +Input file: {input_file} |
| 58 | +Output directory: {outdir} |
| 59 | +Target size: {target_size_mb} MB |
| 60 | +""") |
| 61 | + |
| 62 | + pf = pq.ParquetFile(input_file) |
| 63 | + num_row_groups = pf.num_row_groups |
| 64 | + target_size_bytes = target_size_mb * 1024 * 1024 |
| 65 | + file_idx = 0 |
| 66 | + row_group_idx = 0 |
| 67 | + |
| 68 | + # Loop over all row groups in the file, splitting or merging row groups as needed |
| 69 | + # to hit the target size. |
| 70 | + while row_group_idx < num_row_groups: |
| 71 | + current_size = 0 |
| 72 | + row_groups_to_write = [] |
| 73 | + |
| 74 | + while row_group_idx < num_row_groups and current_size < target_size_bytes: |
| 75 | + row_group = pf.read_row_group(row_group_idx) |
| 76 | + |
| 77 | + if row_group.nbytes > target_size_bytes: |
| 78 | + # Large row group case. Split into smaller chunks to get below target size. |
| 79 | + chunks = _split_table(row_group, target_size=target_size_bytes) |
| 80 | + for chunk in chunks: |
| 81 | + file_idx = _write_table_to_file( |
| 82 | + chunk, outdir=outdir, output_prefix=outfile_prefix, ext=ext, file_idx=file_idx |
| 83 | + ) |
| 84 | + row_group_idx += 1 |
| 85 | + elif row_group.nbytes + current_size > target_size_bytes: |
| 86 | + # Adding the current row group will push over the desired target size, so |
| 87 | + # write current batch to a file. |
| 88 | + break |
| 89 | + else: |
| 90 | + # Case where we need to merge smaller row groups into a single table |
| 91 | + row_groups_to_write.append(row_group) |
| 92 | + current_size += row_group.nbytes |
| 93 | + row_group_idx += 1 |
| 94 | + |
| 95 | + if row_groups_to_write: |
| 96 | + sub_table = pa.concat_tables(row_groups_to_write) |
| 97 | + file_idx = _write_table_to_file( |
| 98 | + sub_table, outdir=outdir, output_prefix=outfile_prefix, ext=ext, file_idx=file_idx |
| 99 | + ) |
| 100 | + |
| 101 | + |
| 102 | +def parse_args(args: argparse.ArgumentParser | None = None) -> argparse.Namespace: |
| 103 | + parser = argparse.ArgumentParser() |
| 104 | + parser.add_argument( |
| 105 | + "--infile", type=str, required=True, help="Path to input file, or directory of files, to split" |
| 106 | + ) |
| 107 | + parser.add_argument("--outdir", type=str, required=True, help="Output directory to store split files") |
| 108 | + parser.add_argument("--target-size-mb", type=int, default=128, help="Target size (in MB) of split output files") |
| 109 | + return parser.parse_args(args) |
| 110 | + |
| 111 | + |
| 112 | +def main(args: argparse.ArgumentParser | None = None) -> None: |
| 113 | + args = parse_args(args) |
| 114 | + |
| 115 | + files = get_all_file_paths_under(args.infile) |
| 116 | + if not files: |
| 117 | + logger.error(f"No file(s) found at '{args.infile}'") |
| 118 | + return |
| 119 | + |
| 120 | + os.makedirs(args.outdir, exist_ok=True) |
| 121 | + with RayClient(): |
| 122 | + ray.get( |
| 123 | + [ |
| 124 | + split_parquet_file_by_size.remote(input_file=f, outdir=args.outdir, target_size_mb=args.target_size_mb) |
| 125 | + for f in files |
| 126 | + ] |
| 127 | + ) |
| 128 | + |
| 129 | + |
| 130 | +if __name__ == "__main__": |
| 131 | + main() |
0 commit comments