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:
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:
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.
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.
Wait for the operation, then fetch the results. The fetched columns are the reservation’s storage. Per-query columns keep
Qrows. Per-hit columns contain only theHstored hits.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:
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:
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:
Column |
Type |
Use |
|---|---|---|
|
|
Required. Start point of each ray. |
|
|
Required. Unit-length direction of each ray. |
|
|
Required. End of each ray’s distance interval. |
|
|
Optional. Start of each ray’s distance interval. |
|
|
Optional. Bits matched against each object’s bits. |
|
|
Optional. Hit limit per row, for |
Column |
Type |
Use |
|---|---|---|
|
|
Required. Start center of each sphere. |
|
|
Required. Unit-length direction of each sweep. |
|
|
Required. End of each sweep’s distance interval. |
|
|
Optional. Start of each sweep’s distance interval. |
|
|
Optional. Radius per row, replacing the plan’s radius. |
|
|
Optional. Bits matched against each object’s bits. |
Column |
Type |
Use |
|---|---|---|
|
|
Required. Start center of each box. |
|
|
Required. Orientation of each box as a unit quaternion. |
|
|
Required. Unit-length direction of each sweep. |
|
|
Required. End of each sweep’s distance interval. |
|
|
Optional. Start of each sweep’s distance interval. |
|
|
Optional. Half extents per row, replacing the plan’s. |
|
|
Optional. Bits matched against each object’s bits. |
Column |
Type |
Use |
|---|---|---|
|
|
Required. Center of each query shape. |
|
|
Required for |
|
|
Optional for |
|
|
Optional for |
|
|
Optional. Bits matched against each object’s bits. |
|
|
Optional. Hit limit per row, for |
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
Qrows:query_status, the status of the row. A row that failed has a non-success status and no hits.hit_offsetsandhit_counts. Rowi’s hits are rowshit_offsets[i]tohit_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
Hrows: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, andDISTANCE.SOURCE_FEATURE, for exact plans only.GEOMETRY_IDENTITY.MATERIAL, amaterial_idscolumn with each hit’s material.QUERY_POSITION, the query shape’s position at contact, for sweeps only.
An overlap plan can request only
GEOMETRY_IDENTITYandMATERIAL.
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 steps in the figure are:
Produce the inputs. Pass your stream as
cuda_stream. In C, setcuda_sync.has_streamto 1 andcuda_sync.streamto 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 ascuda_wait_event. The library waits on that event before it reads.Enqueue the launch.
enqueuereturns the operation and the reservation at once, without waiting for the device.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.Observe completion without blocking. Later, for example on the next frame, poll the operation with
status()orwait(0)until it reports a terminal state.Retire the operation with an event. Record one event,
consumer_done, after all consumers, and pass it todestroy_op_after_cuda. In Python, callclose_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:
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:
Keep the results in host memory. Add
HOST_MAPPEDto the plan’sresult_fields. The GPU writes every result column into page-locked host memory, and the host reads it in place.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
Hfromstored_hit_count. Then copy the per-query columns and only the firstHrows 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 oncuda_streamimmediately afterenqueue.
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_devicestays 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_LOSTis 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_opand no event. In Python, callclose()or leave the operation’swithblock. A GPU consumer of the columns still works, reading them over the bus, and then retires the operation withdestroy_op_after_cuda.Creating the plan charges the columns to the instance’s
host_byte_budgetand returnsHOST_BUDGETwhen 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_MAPPEDand 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:
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 |
|---|---|---|
NumPy |
2.2.6 |
Yes, with |
Warp |
1.18.0 |
Yes, as a CPU array, with |
PyTorch |
2.11.0 |
No, |
CuPy |
14.2.0 |
No, |
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.