ray icon indicating copy to clipboard operation
ray copied to clipboard

[Data] read_mcap: size sample read tasks by the chunks their samples read together

Open marwan116 opened this issue 3 weeks ago • 3 comments

Problem

  • Planning sizes a sample read task by weighing each probed sample alone: the bytes of the chunks its own window reaches. The budget divided by the median weight is the number of samples per task.
  • When windows overlap, neighbouring samples share most of their chunks. A task then takes far fewer samples than fit in its budget, and every task reads the shared chunks again.
  • A file without a chunk index weighs its whole size per sample. When it is over the budget, each task gets one sample and scans the whole file again.
  • Planning runs the samples dataset to probe its first samples, and the read runs it again. A samples dataset that is not materialized, such as one that ends in a sort, therefore runs twice.

Repro

This runs on the #67189 branch (read_mcap(samples=...) is not merged yet).

The read-task budget and the frame sizes are scaled 10x down from the review's example, so this runs in seconds. The ratios match the full-size case.

import os, tempfile

# The read-task budget, scaled 10x down from 128 MiB so this runs in seconds.
os.environ["RAY_DATA_MCAP_BIN_PACKING_BYTES"] = str(int(12.8 * 2**20))

import ray
from mcap.writer import IndexType, Writer
from ray.data.datasource.mcap import TopicSpec, steps

SECOND, FPS = 1_000_000_000, 30


def write_camera(path, seconds, frame_bytes, index=True):
    """A 30 fps camera, ~1 s per chunk; without ``index``, no chunks or index."""
    with open(path, "wb") as f:
        writer = Writer(
            f,
            chunk_size=FPS * frame_bytes,
            use_chunking=index,
            index_types=IndexType.ALL if index else IndexType.NONE,
            use_summary_offsets=index,
        )
        writer.start()
        schema = writer.register_schema("Frame", "jsonschema", b"{}")
        cam = writer.register_channel("/cam", "cdr", schema)
        for k in range(seconds * FPS):
            t = k * SECOND // FPS
            writer.add_message(cam, log_time=t, publish_time=t, data=os.urandom(frame_bytes))
        writer.finish()


def read(path, anchors, spec, clip_end):
    samples = ray.data.from_items(
        [{"files": [path], "clip_start": 0, "clip_end": clip_end, "anchor": a} for a in anchors],
        override_num_blocks=1,
    )
    ds = ray.data.read_mcap(samples=samples, topics={"/cam": spec}).materialize()
    for line in ds.stats().splitlines():
        if line.startswith("Operator") and ("Repartition" in line or "ReadFiles" in line):
            print(line)


tmp = tempfile.mkdtemp()

# 1. Overlapping windows: 30 s of camera (~0.9 MiB/s), a sample at every frame
#    from 10 s to 30 s, each reading the 10 s before its anchor at 1 fps.
path = os.path.join(tmp, "camera.mcap")
write_camera(path, seconds=30, frame_bytes=3 * 1024)
anchors = [k * SECOND // FPS for k in range(10 * FPS, 30 * FPS)]
print(f"overlapping windows, file {os.path.getsize(path) / 2**20:.1f} MiB:")
read(path, anchors, TopicSpec(steps.before(10, fps=1)), 30 * SECOND)

# 2. A file without a chunk index, over the budget: 8 samples.
path = os.path.join(tmp, "no-index.mcap")
write_camera(path, seconds=16, frame_bytes=30 * 1024, index=False)
anchors = [k * SECOND for k in range(2, 10)]
print(f"no chunk index, file {os.path.getsize(path) / 2**20:.1f} MiB:")
read(path, anchors, TopicSpec(steps.before(1, fps=10)), 16 * SECOND)

Output:

overlapping windows, file 2.7 MiB:
Operator 2 StreamingRepartition[num_rows_per_block=14,strict=True]: 2 tasks executed, 43 blocks produced in 0.81s
Operator 3 ReadFilesMCAP: 43 tasks executed, 43 blocks produced in 2.67s
no chunk index, file 14.1 MiB:
Operator 2 StreamingRepartition[num_rows_per_block=1,strict=True]: 1 tasks executed, 8 blocks produced in 0s
Operator 3 ReadFilesMCAP: 8 tasks executed, 8 blocks produced in 0.1s

The bytes below were counted by running the same read tasks in one process and wrapping the reader's chunk parse and file reads.

Current Expected
Overlapping windows: each task takes 14 samples and reads about 0.9 MiB of chunks, against a 12.8 MiB budget. The 43 tasks parse 40.4 MiB of chunks for a 2.7 MiB recording. Weighed together, all 256 probed samples fit in one task. The 600 samples then take 3 tasks, which parse 4.5 MiB.
No chunk index: a 14.1 MiB file over the 12.8 MiB budget gets one sample per task. Each of the 8 tasks scans the whole file, 113 MiB read in all. The file counts once per task, because one scan serves all of a task's samples. Its 8 samples share one task and one 14.1 MiB scan.

Proposal

  • Weigh the probed samples together, as a task reads them. Walk them in file and anchor order and keep the union of the chunks they reach. Start a new task when that union passes the budget.
  • A sample that adds no new chunks never starts a new task. This covers a file without a chunk index: its size counts once per task, not once per sample.
  • The samples per task is then the median size of those groups, still capped by MAX_SAMPLES_PER_TASK.
  • The estimate needs no extra reads: it uses the same chunk indexes that planning already reads.
  • Stop running the samples dataset at planning, so it runs once whether or not the caller materializes it. The sizing above then works on the samples as the read receives them.

Follow-up to #67189 (review comments https://github.com/ray-project/ray/pull/67189#discussion_r4518086941, https://github.com/ray-project/ray/pull/67189#discussion_r4518124447 and https://github.com/ray-project/ray/pull/67189#discussion_r4518173568).

🤖 Generated with Claude Code

marwan116 avatar Nov 09 '26 23:11 marwan116

I’d strongly support this feature request. I’m currently exploring migrating my team’s sim-RL framework to Ray, one of the major blockers is the large simulation data transferring overhead, the 40M -> 4MB reduction would be a compelling justification. I’d be interested to see how much it could also reduce network I/O for remote workloads.

If time permits I'd like to to work on a code change and give it a test on some typical workload at my end. Happy to hear and learn.

Pengkun-ZHU avatar Nov 10 '26 02:11 Pengkun-ZHU

On the other hand, taking this opportunity, I'd like to mention another major concern regarding the migration:

As current NV architectures don't support a native rendering-GPGPU pipeline, the simulation data cannot be reused directly at device side by the RL module unless the NVIDIA Warp framework (to be distinguished from CUDA warps) is available. The utilization of Warp—and possibly NCCL, etc.—requires a pre-determined pipeline DAG, as runtime establishment of the related context would be too expensive. However, based on my reading of relevant docs and discussions, support for the static compile-mode DAG flow seems to have been withdrawn from active maintenance. I wonder if you could share the considerations and intuition behind that decision. For this kind of usage, is there any recommended workaround?

Kindly point me to where I should consult if this topic is inappropriate to discuss here. I tried reaching out on the forum but haven't received a response yet.

Pengkun-ZHU avatar Nov 10 '26 03:11 Pengkun-ZHU

Hi @marwan116, I'd like to take this. I'd size read_mcap sample read tasks by the union of chunks their samples read together, instead of each sample's own weight, so overlapping windows fill a task's budget, with a test on overlapping windows. Okay to pick it up?

rahulsjha avatar Nov 21 '26 16:11 rahulsjha