Batches#

A synchronous call answers one query on the calling thread. A batch plan answers many queries of one family per launch, on the CPU or on one CUDA device. It returns its results as DLPack columns that a CUDA consumer can read without a round trip through the host.

The following figure compares four rays cast one call at a time with the same four rays enqueued as one launch of a plan, on the CPU and on a CUDA device:

A launch pays the overhead once, and its rows can run in parallel on idle CPU workers or on a CUDA device.

The work for each row is the same in every lane. A CPU launch runs as one job. When a launch has 128 rows or more, the instance’s idle workers evaluate parts of it beside that job. A shorter launch, such as the four rows in the figure, evaluates its rows in order. The results are the same as evaluating the rows in order, including which rows are truncated when the slot is full. Separate launches, from one plan or several, run at the same time on up to max_cpu_concurrency workers. A worker that is helping another launch moves to a waiting launch first, and the instance starts no other threads. A CUDA launch evaluates its rows in parallel on the device. How much a batch saves depends on the row count, the device, the free workers, and the scene, so measure it for your workload.

Plan Lifecycle#

A plan is created once and then launched many times. Each launch goes through these steps:

  1. Create a plan. The plan fixes the family (raycast, sphere sweep, box sweep, or overlap), the target, the device, and the precision. It also fixes the maximum rows per launch and the number of result slots it reserves.

  2. Enqueue a launch with this frame’s rows and the population version to read. Admission pins the version and takes a free slot. The call returns an operation, the handle of the pending work, and a reservation, which describes the columns that the results land in.

  3. Wait for the operation, then fetch the results. The fetched columns are the reservation’s storage. Per-query columns keep Q rows. Per-hit columns contain only the H stored hits.

  4. Destroy the operation to return its slot to the plan. While every slot is in use, the next launch is refused with RESULT_CAPACITY.

The following figure shows two result slots shared by three launches. Operation 1 is the launch of the program in Raycast Batch Example:

Slots bound how many launches' results can exist at once. A miss is a count of zero.

Note

A version is an immutable snapshot of a population, numbered by its ordinal. For how a launch selects one and how long it stays readable, refer to Versions and Retention.

Raycast Batch Example#

The following program casts four rays through a CPU plan. Ray 2 misses because nothing lies on its line.

import warp as wp

from ovspatialquery import (
    BatchResultField,
    GeometryType,
    HitMode,
    Library,
    QueryPrecision,
    RaycastPlanConfig,
)

wp.config.log_level = wp.LOG_WARNING  # skip Warp's start-up banner
CPU = "cpu"  # this program and its plan run on the CPU

with Library.open() as library, library.instance() as instance:
    # A row of four unit boxes at x = 4, 6, 8, 10 on y = 0, 1, 2, 3.
    adapter = instance.explicit()
    adapter.register_boxes(
        definition_values=wp.array([1], dtype=wp.uint64, device=CPU),
        half_extents=wp.full((1, 3), 0.5, dtype=wp.float64, device=CPU),
    ).finish()
    population = adapter.create_population()
    population.enqueue_set(
        1,
        object_values=wp.array([20, 21, 22, 23], dtype=wp.uint64, device=CPU),
        geometry_types=wp.full(4, int(GeometryType.BOX), dtype=wp.int32, device=CPU),
        geometry_values=wp.ones(4, dtype=wp.uint64, device=CPU),
        translations=wp.array(
            [[4.0, 0, 0], [6, 1, 0], [8, 2, 0], [10, 3, 0]], dtype=wp.float64, device=CPU
        ),
        rotations_xyzw=wp.array([[0.0, 0, 0, 1]] * 4, dtype=wp.float32, device=CPU),
    ).finish()

    # The plan fixes the family, target, device and capacities once.
    plan = instance.create_raycast_plan(
        RaycastPlanConfig(
            target=population.target.reference,
            hit_mode=HitMode.CLOSEST,
            precision=QueryPrecision.EXACT,
            maximum_query_count=8,
            maximum_hits_per_query=1,
            hit_capacity_per_slot=8,
            result_slot_count=2,
            result_fields=BatchResultField.DISTANCE,
        )
    )

    # Each launch passes its rows as columns and reads the head by default.
    # Ray 2 misses: nothing lies on y = 5.
    operation, reservation = plan.enqueue(
        origins=wp.array(
            [[0.0, 0, 0], [0, 1, 0], [0, 5, 0], [0, 3, 0]], dtype=wp.float64, device=CPU
        ),
        unit_directions=wp.array([[1.0, 0, 0]] * 4, dtype=wp.float32, device=CPU),
        max_distances=wp.full(4, 20.0, dtype=wp.float64, device=CPU),
        copy=True,
    )
    # Leaving the block closes the operation, which returns its result slot to
    # the plan. For a CPU result, to_numpy() copies the columns so they outlive it.
    with operation:
        operation.wait()
        result = operation.fetch_raycast_batch().to_numpy()

    counts, offsets = result.hit_ranges.hit_counts, result.hit_ranges.hit_offsets
    print("source ordinal", result.common.source_ordinal)
    for row, (count, offset) in enumerate(zip(counts, offsets)):
        if count == 0:
            print(f"ray {row}: miss")
        else:
            distance = result.exact.distances[offset]
            print(f"ray {row}: object {result.object_ids[offset]} at {distance:.2f}")

It prints this output:

Output#
source ordinal 1
ray 0: object 20 at 3.50
ray 1: object 21 at 5.50
ray 2: miss
ray 3: object 23 at 9.50

Input Columns#

A launch passes one tensor per input column, and every column has Q rows. In Python, each column is a keyword argument of the plan’s enqueue and accepts any array that implements __dlpack__. The wrapper checks dtypes, shapes, devices, and row counts before it calls the library.

By default, the operation borrows the columns and keeps them alive until it is closed, so the library reads them without a copy. With copy=True, CPU inputs are copied before enqueue returns, so you can change those arrays immediately. CUDA copies are queued on cuda_stream. Later writes on that stream follow the copy. Before writing from another stream, record an event on cuda_stream after enqueue returns and make the writing stream wait for it.

Each family takes the columns in the following tables:

Raycast Input Columns#

Column

Type

Use

origins

float64[Q,3]

Required. Start point of each ray.

unit_directions

float32[Q,3]

Required. Unit-length direction of each ray.

max_distances

float64[Q]

Required. End of each ray’s distance interval.

min_distances

float64[Q]

Optional. Start of each ray’s distance interval.

query_bits

uint64[Q,2]

Optional. Bits matched against each object’s bits.

maximum_hits

uint64[Q]

Optional. Hit limit per row, for MULTIPLE plans only.

Sphere Sweep Input Columns#

Column

Type

Use

centers

float64[Q,3]

Required. Start center of each sphere.

unit_directions

float32[Q,3]

Required. Unit-length direction of each sweep.

max_distances

float64[Q]

Required. End of each sweep’s distance interval.

min_distances

float64[Q]

Optional. Start of each sweep’s distance interval.

radii

float64[Q]

Optional. Radius per row, replacing the plan’s radius.

query_bits

uint64[Q,2]

Optional. Bits matched against each object’s bits.

Box Sweep Input Columns#

Column

Type

Use

centers

float64[Q,3]

Required. Start center of each box.

rotations_xyzw

float32[Q,4]

Required. Orientation of each box as a unit quaternion.

unit_directions

float32[Q,3]

Required. Unit-length direction of each sweep.

max_distances

float64[Q]

Required. End of each sweep’s distance interval.

min_distances

float64[Q]

Optional. Start of each sweep’s distance interval.

half_extents

float64[Q,3]

Optional. Half extents per row, replacing the plan’s.

query_bits

uint64[Q,2]

Optional. Bits matched against each object’s bits.

Overlap Input Columns#

Column

Type

Use

translations

float64[Q,3]

Required. Center of each query shape.

rotations_xyzw

float32[Q,4] or float64[Q,4]

Required for BOX plans. Omitted for SPHERE and AABB plans.

half_extents

float64[Q,3]

Optional for BOX and AABB plans. Replaces the plan’s half extents.

radii

float64[Q]

Optional for SPHERE plans. Replaces the plan’s radius.

query_bits

uint64[Q,2]

Optional. Bits matched against each object’s bits.

maximum_hits

uint64[Q]

Optional. Hit limit per row, for MULTIPLE plans only.

Tip

Column 0 of query_bits holds bits 0 to 63 and column 1 bits 64 to 127. A row whose two words are zero accepts every object. For how query bits and object bits select objects, refer to Views and Participation Bits.

Result Columns#

Every result has two kinds of column:

  • Per query, with Q rows:

    • query_status, the status of the row. A row that failed has a non-success status and no hits.

    • hit_offsets and hit_counts. Row i’s hits are rows hit_offsets[i] to hit_offsets[i] + hit_counts[i] of the per-hit columns. A miss is a count of zero.

    • truncated, nonzero when the row’s hit limit or the slot’s remaining capacity left out a match.

  • Per hit, with H rows:

    • object_ids, always present.

    • The columns that the plan requests with result_fields. Columns that are not requested are absent. A raycast or sweep plan can request:

      • POSITION, NORMAL, and DISTANCE.

      • SOURCE_FEATURE, for exact plans only.

      • GEOMETRY_IDENTITY.

      • MATERIAL, a material_ids column with each hit’s material.

      • QUERY_POSITION, the query shape’s position at contact, for sweeps only.

      An overlap plan can request only GEOMETRY_IDENTITY and MATERIAL.

In Python, every result column is a DLPack producer on the plan’s device. wp.from_dlpack(column) wraps it as a Warp array without a copy, so a Warp kernel can consume the results where they were computed. CUDA Plans shows a kernel that reads them on the GPU. Any other DLPack consumer, such as torch.from_dlpack(column), reads device columns the same way.

Tip

For a CPU result, or a CUDA result kept in host memory, result.to_numpy() copies every column into NumPy arrays with the same field names, so they outlive the operation.

Important

A DLPack view borrows the operation’s storage. Closing the operation while such a view is alive raises BufferError, so copy what must outlive the operation.

CUDA Plans#

To run a plan on a CUDA device, create the instance with a byte budget for the device and create the plan with that device. A CUDA plan never runs on the CPU. If CUDA or the family is unavailable, creating the plan returns NOT_SUPPORTED.

A CUDA launch is ordered with CUDA events, so the host thread never blocks on the device. The following figure shows one launch, from its inputs to the release of its result storage:

The host only queues work. Every wait happens on a device stream.

The steps in the figure are:

  1. Produce the inputs. Pass your stream as cuda_stream. In C, set cuda_sync.has_stream to 1 and cuda_sync.stream to the stream. Stream 0 is CUDA’s legacy default stream, not “no stream.” The library reads the input columns on it after the work already queued there. If another stream writes the inputs, also pass an event that it records after those writes as cuda_wait_event. The library waits on that event before it reads.

  2. Enqueue the launch. enqueue returns the operation and the reservation at once, without waiting for the device.

  3. Queue the consumers. The reservation’s columns and the fetched columns share the same storage. You can therefore queue consumer kernels on the reservation’s columns before the query has run. Each consumer waits on result_ready, one event that covers every column of the launch.

  4. Observe completion without blocking. Later, for example on the next frame, poll the operation with status() or wait(0) until it reports a terminal state.

  5. Retire the operation with an event. Record one event, consumer_done, after all consumers, and pass it to destroy_op_after_cuda. In Python, call close_after_cuda(consumer_done). The library releases the result storage after that event completes.

In Python, enqueue’s cuda_stream and cuda_wait_event take a handle or an object that exposes one, such as a Warp stream. The wrapper hands the stream to each input column’s __dlpack__, so the producer’s pending writes are ordered before the library reads. Exporting a result or reservation column with __dlpack__(stream=...) queues the wait on result_ready on the consumer’s stream. wp.from_dlpack(column) passes Warp’s current stream, so a kernel launched on that stream reads the results after the query.

CUDA Example#

The following program runs the four rays of the CPU example on a CUDA device. A Warp kernel reads the result columns on the GPU, and the host copies only the kernel’s output, to print it:

import warp as wp

from ovspatialquery import (
    BatchResultField,
    Device,
    DeviceBudget,
    GeometryType,
    HitMode,
    InstanceConfig,
    Library,
    RaycastPlanConfig,
)

wp.config.log_level = wp.LOG_WARNING  # skip Warp's start-up banner
CPU, GPU = "cpu", "cuda:0"


@wp.kernel
def closest_distance(
    counts: wp.array(dtype=wp.uint64),
    offsets: wp.array(dtype=wp.uint64),
    distances: wp.array(dtype=wp.float64),
    out: wp.array(dtype=wp.float64),
):
    ray = wp.tid()
    out[ray] = wp.float64(-1.0)  # a miss stores no hit
    if counts[ray] > wp.uint64(0):
        out[ray] = distances[wp.int32(offsets[ray])]


def consume(reservation, stream):
    """Reads the result columns on the GPU, ordered after the query, without a copy."""
    # from_dlpack exports each column on the current stream, which then waits on result_ready.
    with wp.ScopedStream(stream):
        out = wp.empty(4, dtype=wp.float64, device=GPU)
        wp.launch(
            closest_distance,
            dim=4,
            inputs=[
                wp.from_dlpack(reservation.hit_ranges.hit_counts),
                wp.from_dlpack(reservation.hit_ranges.hit_offsets),
                wp.from_dlpack(reservation.candidate.distances),
                out,
            ],
        )
    return out  # the column views end here, before the operation is retired


# CUDA work needs a byte budget for the device.
config = InstanceConfig(device_budgets=(DeviceBudget(Device.cuda(0), 256 << 20),))
with Library.open() as library, library.instance(config) as instance:
    # The same four unit boxes as the CPU example, published from CPU arrays.
    adapter = instance.explicit()
    adapter.register_boxes(
        definition_values=wp.array([1], dtype=wp.uint64, device=CPU),
        half_extents=wp.full((1, 3), 0.5, dtype=wp.float64, device=CPU),
    ).finish()
    population = adapter.create_population()
    population.enqueue_set(
        1,
        object_values=wp.array([20, 21, 22, 23], dtype=wp.uint64, device=CPU),
        geometry_types=wp.full(4, int(GeometryType.BOX), dtype=wp.int32, device=CPU),
        geometry_values=wp.ones(4, dtype=wp.uint64, device=CPU),
        translations=wp.array(
            [[4.0, 0, 0], [6, 1, 0], [8, 2, 0], [10, 3, 0]], dtype=wp.float64, device=CPU
        ),
        rotations_xyzw=wp.array([[0.0, 0, 0, 1]] * 4, dtype=wp.float32, device=CPU),
    ).finish()

    plan = instance.create_raycast_plan(
        RaycastPlanConfig(
            target=population.target.reference,
            hit_mode=HitMode.CLOSEST,
            maximum_query_count=8,
            maximum_hits_per_query=1,
            hit_capacity_per_slot=8,
            result_fields=BatchResultField.DISTANCE,
            device=Device.cuda(0),
        )
    )

    # The rays are written on a Warp stream, and the launch is queued on the same stream.
    stream = wp.Stream(GPU)
    with wp.ScopedStream(stream):
        origins = wp.array(
            [[0.0, 0, 0], [0, 1, 0], [0, 5, 0], [0, 3, 0]], dtype=wp.float64, device=GPU
        )
        directions = wp.array([[1.0, 0, 0]] * 4, dtype=wp.float32, device=GPU)
        max_distances = wp.full(4, 20.0, dtype=wp.float64, device=GPU)
    operation, reservation = plan.enqueue(
        origins=origins,
        unit_directions=directions,
        max_distances=max_distances,
        cuda_stream=stream,
    )

    # The reservation's columns exist at enqueue, so the consumer is queued before the query
    # has run. The host has not waited for the GPU yet.
    distances = consume(reservation, stream)
    consumer_done = stream.record_event()

    # Retire the operation after its consumer. The library takes the event and releases the
    # result slot once it completes; leaving the block waits for that release.
    operation.wait()
    operation.close_after_cuda(consumer_done.cuda_event)
    consumer_done.owner = False  # the library now owns the event

    for ray, distance in enumerate(distances.numpy()):  # copy to the host only to print
        print(f"ray {ray}: miss" if distance < 0 else f"ray {ray}: {distance:.2f}")

It prints this output:

Output#
ray 0: 3.50
ray 1: 5.50
ray 2: miss
ray 3: 9.50

The program never waits on the host for the query before it queues the consumer. Closing the plan, here by leaving the instance’s block, waits for the library to release the slot retired with close_after_cuda.

Important

Retire every CUDA operation that returned result columns with destroy_op_after_cuda, even after a failure, unless its plan keeps its results in host memory. In Python, close() and leaving the operation’s with block refuse any other CUDA operation. Release the consumer’s DLPack views first, because close_after_cuda raises BufferError while one is alive. close_after_cuda takes ownership of the event, so a Warp event passed to it sets owner = False.

Note

With copy=True on a CUDA plan, the library queues the copy on cuda_stream before enqueue returns. Later writes on the same stream are ordered after the copy. Before you overwrite an input from another stream, make that stream wait on an event that you record on cuda_stream after enqueue.

Results Read on the Host#

Some programs run a CUDA plan but read every hit on the host, for example a tool or a sensor whose consumer is CPU code. Copying each result column from the device costs one copy call per column on every launch. Two patterns avoid most of that cost:

  1. Keep the results in host memory. Add HOST_MAPPED to the plan’s result_fields. The GPU writes every result column into page-locked host memory, and the host reads it in place.

  2. Copy only the stored rows. For a plan whose results stay on the GPU and that the host reads only occasionally, wait for the operation and read H from stored_hit_count. Then copy the per-query columns and only the first H rows of each per-hit column into pinned host buffers that you allocate once. Synchronize once after the copies. This is faster than queuing full-capacity copies on cuda_stream immediately after enqueue.

A plan with HOST_MAPPED behaves as follows:

  • Each result column reports the DLPack device kDLCUDAHost, pinned host memory that the plan’s device can also address. execution_device stays the plan’s CUDA device.

  • The host can read the columns after a wait, a status poll, or a fetch reports that the operation completed or failed. No stream synchronization is needed. A failed launch leaves the same failed rows with no hits that a device result shows. DEVICE_LOST is the exception: it makes no promise about the columns.

  • When no work that you queued on the GPU reads the columns, retire the operation with destroy_op and no event. In Python, call close() or leave the operation’s with block. A GPU consumer of the columns still works, reading them over the bus, and then retires the operation with destroy_op_after_cuda.

  • Creating the plan charges the columns to the instance’s host_byte_budget and returns HOST_BUDGET when they do not fit. The plan keeps its device working storage as well.

  • Each launch adds one copy pass on the GPU, and reading pinned host memory is slower than reading ordinary memory. For a plan whose results stay on the GPU, do not set the bit.

  • A CPU plan accepts HOST_MAPPED and ignores it, so one plan configuration serves both devices.

The following program runs the four rays of the CUDA example with HOST_MAPPED and reads the results on the host:

import warp as wp

from ovspatialquery import (
    BatchResultField,
    Device,
    DeviceBudget,
    GeometryType,
    HitMode,
    InstanceConfig,
    Library,
    RaycastPlanConfig,
)

wp.config.log_level = wp.LOG_WARNING  # skip Warp's start-up banner
CPU, GPU = "cpu", "cuda:0"

config = InstanceConfig(device_budgets=(DeviceBudget(Device.cuda(0), 256 << 20),))
with Library.open() as library, library.instance(config) as instance:
    # The same four unit boxes as the CUDA example.
    adapter = instance.explicit()
    adapter.register_boxes(
        definition_values=wp.array([1], dtype=wp.uint64, device=CPU),
        half_extents=wp.full((1, 3), 0.5, dtype=wp.float64, device=CPU),
    ).finish()
    population = adapter.create_population()
    population.enqueue_set(
        1,
        object_values=wp.array([20, 21, 22, 23], dtype=wp.uint64, device=CPU),
        geometry_types=wp.full(4, int(GeometryType.BOX), dtype=wp.int32, device=CPU),
        geometry_values=wp.ones(4, dtype=wp.uint64, device=CPU),
        translations=wp.array(
            [[4.0, 0, 0], [6, 1, 0], [8, 2, 0], [10, 3, 0]], dtype=wp.float64, device=CPU
        ),
        rotations_xyzw=wp.array([[0.0, 0, 0, 1]] * 4, dtype=wp.float32, device=CPU),
    ).finish()

    # HOST_MAPPED keeps the result columns in pinned host memory the GPU writes.
    plan = instance.create_raycast_plan(
        RaycastPlanConfig(
            target=population.target.reference,
            hit_mode=HitMode.CLOSEST,
            maximum_query_count=8,
            maximum_hits_per_query=1,
            hit_capacity_per_slot=8,
            result_fields=BatchResultField.DISTANCE | BatchResultField.HOST_MAPPED,
            device=Device.cuda(0),
        )
    )

    stream = wp.Stream(GPU)
    with wp.ScopedStream(stream):
        origins = wp.array(
            [[0.0, 0, 0], [0, 1, 0], [0, 5, 0], [0, 3, 0]], dtype=wp.float64, device=GPU
        )
        directions = wp.array([[1.0, 0, 0]] * 4, dtype=wp.float32, device=GPU)
        max_distances = wp.full(4, 20.0, dtype=wp.float64, device=GPU)
    operation, _ = plan.enqueue(
        origins=origins,
        unit_directions=directions,
        max_distances=max_distances,
        cuda_stream=stream,
    )

    # The host may read the columns once the wait has observed the end; to_numpy() copies
    # them so they outlive the operation. Nothing on the GPU reads them, so leaving the
    # block closes the operation without a consumer event.
    with operation:
        operation.wait()
        result = operation.fetch_raycast_batch().to_numpy()

    counts, offsets = result.hit_ranges.hit_counts, result.hit_ranges.hit_offsets
    for ray, count in enumerate(counts):
        distance = result.candidate.distances[offsets[ray]] if count else None
        print(f"ray {ray}: miss" if distance is None else f"ray {ray}: {distance:.2f}")

It prints this output:

Output#
ray 0: 3.50
ray 1: 5.50
ray 2: miss
ray 3: 9.50

Python array libraries differ in whether they accept pinned host memory. The following table lists what each library does with a HOST_MAPPED column:

Library

Version

Reads a kDLCUDAHost Column

NumPy

2.2.6

Yes, with numpy.from_dlpack

Warp

1.18.0

Yes, as a CPU array, with wp.from_dlpack

PyTorch

2.11.0

No, torch.from_dlpack refuses the device type

CuPy

14.2.0

No, cupy.from_dlpack refuses the device type

A column exports only after the operation is terminal. It ignores the stream that a consumer passes to __dlpack__, other than the ambiguous 0, because no device work remains to wait for.