-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmulti.py
More file actions
3325 lines (2974 loc) · 146 KB
/
Copy pathmulti.py
File metadata and controls
3325 lines (2974 loc) · 146 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright Xingyu Chen.
# Implements shared Python support for multi.
"""Private replicated multi-device orchestration for `Scene(devices=[...])`.
This is Phases 2a, 2b, 2d and the grid-reduce half of 2c of
`docs/dev/multi_gpu_plan.md`, and the layer it builds is governed by
`docs/adr/0038-replicated-multi-device-execution.md`: decision D1 (one full
scene replica per device, work sharded along the batch axis), D4 (replica
vertices are `master.to(device_k)`, so torch autograd reduces every replica
gradient back onto the master leaf), D7 (a large batch is executed as a stream
of chunks per device), D8 (no parallel public surface -- `Scene` gains
`devices=` and `MultiDeviceOptions`, and everything else stays where it was)
and D9 (a `Scene` that asks for neither several devices nor chunking never
reaches this module at all: `Scene` imports it only when `devices=` is passed,
and it still declines to orchestrate a one-device scene that wants nothing
from the chunked executor).
Two of the plan's shardability classes are wrapped here. The `per_ray`
operations shard the batch axis and their sharded result is field-for-field the
single-device result. Reflection accumulation shards its ray batch, while the
`grid_reduce` diffraction accumulation operations shard the Monte-Carlo
*sample* axis instead (see below); both merge partial grids in device order and
match a single-device grid up to float32 summation order. `trace_dfr_paths`
shards whole transmitter row blocks in `SourceLane` layout, which preserves
the global `(tx, rx, state)` row order without compaction.
`accum_dfr_coherent_direct` shards its deterministic `(state, grid-cell)` lane
space and merges the partial grids on the master.
Execution is deliberately single-threaded on the host: every device is driven
from the calling thread, and overlap comes from streams and events rather than
from threads. Concurrent host threads are supported by the native layer since
the `destroy_scene` lock-order fix of 2026-07-27
(`docs/dev/multi_gpu_operations.md` section 2), but they would buy nothing
here, because an op wrapper holds the GIL for the whole native call.
Pipelined dispatch (Phase 2d)
-----------------------------
Torch runs a cross-device copy on the *source* device's current stream and
barriers it against the *destination* device's current stream. Left alone,
that puts both the scatter to the other devices and the gather back on the
master's own stream, in front of the master's compute: measured on this
repository's 2x RTX A6000 (NV4, 52.6 GB/s per direction, 101 GB/s both ways at
once), a 4M-ray `intersect` landed at 0.21x of one device and a 4M-ray
`trace_reflections` at 0.48x -- the layer was correct and slower than not
having it.
So a multi-device `per_ray` operation now runs through the chunked executor by
default, with a chunk size chosen for overlap rather than for a memory budget,
and every copy on a stream of its own: one per device *pair direction*, plus an
otherwise unused stream on each destination so the copy's two-way barrier never
lands on the caller's stream or on a compute stream. The master's shard is one
launch -- it has no copy to overlap -- and every other shard is cut into
`pipeline_chunks_per_device` chunks, so chunk `k`'s scatter and chunk `k-1`'s
gather run while chunk `k` computes. The operation's whole output is allocated
once on the master and each chunk copies its rows straight into it, which is
what keeps the host (one native launch plus one copy per output field per
chunk, ~0.3 ms whatever the chunk's size) from becoming the bound.
What that buys, on the same machine, at default options, min-of-9 and
interleaved against the single-device run (4M rays each):
| Configuration | 1 GPU | 2 GPUs | ratio |
| ---------------------------------------------- | -----: | ------: | ----: |
| `intersect`, 2M-triangle cloud, incoherent | 25.3 ms | 14.8 ms | 1.71x |
| `trace_reflections`, 4 bounces, 3.1M triangles | 18.2 ms | 10.4 ms | 1.75x |
| `intersect`, 192-grid mesh (transfer-bound) | 1.18 ms | 1.21 ms | 0.97x |
The first two were 1.42x and 1.52x on the Phase 2a path. The third was 0.21x
there and is 0.27x through the pipeline on its own.
That third row is the point of `calibrate()` and of `min_rays_per_device`, not
a failure of the pipeline: two devices can only beat one when a row's compute
costs more than its bytes cost to move. A full `Intersection` row is 76 bytes,
which is 1.44 ns of one NVLink direction, so an `intersect` cheaper than that
per ray is faster on the master alone however well the copies overlap.
Calibration measures exactly that and answers with a zero remote weight, which
the dispatcher runs as the single-device call it is -- which is what puts the
third row at parity rather than at 0.31x.
Where the remaining distance to 2x goes, for the first row: half the batch is
12.6 ms of compute per device, the pipeline finishes in 14.8 ms, and the 2.2 ms
of difference is the first chunk's scatter (500k rows x 24 B = 0.23 ms), the
last chunk's gather (500k x 76 B = 0.72 ms), the master's copy of its own 2M
rows into the output (~0.4 ms), and the interconnect and the traversal kernels
competing for the same memory system for the rest. The second row's gather is
36 B per row instead of 76, and it lands correspondingly closer.
Nothing in the pipeline changes a result: it is the same launches on the same
per-shard inputs, with the ordering expressed as events instead of as stream
serialization, so a pipelined result is bitwise the unpipelined one and a fixed
(devices, weights, chunking) reproduces itself.
Private streams mean every edge to the caller's streams has to be written down,
on *every* device rather than only on the master. A replica's own state is
mutated on its own device: `build()` ends with a stream-ordered acceleration
structure build, `sync()` enqueues the triangle GAS refit, the IAS rebuild and
the edge-GAS build on the scene's stream and returns without a host
synchronization, and `set_edge_mask` is the same shape. So the executor enters
by making each device's compute stream wait on an event recorded on *that*
device's current stream (as well as on the master's, where the inputs were
produced), and leaves by making each device's current stream wait on an event
recorded on our compute stream. Without the first edge a query issued straight
after `update_mesh_vertices()` + `sync()` traverses a half-rebuilt structure
and answers, silently, from partly stale geometry; without the second a
mutation can overwrite geometry a shard is still traversing. Both are covered
by `PipelinedStreamOrderingTests`. The copy streams need neither edge: they
touch caller and chunk tensors, whose cross-stream lifetime the caching
allocator already tracks through `record_stream`.
Chunked execution (Phase 2b)
----------------------------
`MultiDeviceOptions.chunk_rays` sets an explicit launch size;
`.tape_memory_budget_bytes` asks the same executor for the largest chunk whose
estimated incremental peak fits a hard budget; `.offload` streams each retired
result. These controls are honoured at every batch size, and the small-batch
floor does not override them. Ordering is the pipelined one described above:
chunk `k`'s gather runs on that pair's copy stream while chunk `k+1`'s compute
already runs on the compute stream, tied by events, never by a device or host
synchronization. The master's stream is made to wait on a chunk's gather event
before anything reads it, which is the only ordering a caller can observe.
Chunking is engaged for a one-device scene too (`Scene(devices=[d],
options=MultiDeviceOptions(chunk_rays=...))`): at extreme N the binding
constraint is tape and output memory rather than scene memory (D7), so
splitting one device's batch is the memory story even when there is nothing to
shard. A `Scene` that asks for chunking on neither axis keeps the untouched
single-device path.
With `offload` set, per-ray results are streamed rather than concatenated: the
hook is called once per chunk as `offload(chunk_start_row, chunk_result)` with
the chunk's fields already on the master device, and the operation itself
returns `None`. Without it, the chunks are concatenated on the master, which
is bitwise the unchunked result because every wrapped operation is `per_ray`.
Chunking for memory buys memory, not speed: every chunk is one more native
call, and a native call's host cost does not shrink with its batch (measured on
one RTX A6000, a 4M-ray 3-bounce `trace_reflections` costs 0.31 ms of host time
and 0.92 ms of wall time; split into 16 chunks the same batch costs 3.8 ms,
host bound). That is what `calibrate_chunk_size()` is for -- the right chunk is
the largest one the budget allows, never the smallest one that fits -- and it
is why the pipelined path counts its chunks per shard instead of asking for a
size.
Chunking reaches exactly the operations sharding reaches, for the same reason:
a chunk of a `grid_reduce` operation is a partial grid, and merging those needs
the per-shard semantics of Phase 2c.
Training at extreme N pairs chunking with a *per-chunk* backward: a chunked
forward keeps one tape per chunk, so the memory bound only holds if the caller
reduces and backpropagates each chunk inside the `offload` hook instead of
holding the whole batch's graph. That is ordinary gradient accumulation and is
exact for RayD geometry gradients, which land in `grad_vertices` by summation
(D4); only float32 summation order differs from the unchunked backward.
Diffraction accumulation (Phase 2c, `grid_reduce`)
--------------------------------------------------
`accum_dfr_direct` and `accum_dfr` have no batch axis to shard: their cost is
the Monte-Carlo lane space of `direct_samples + keller_samples +
suffix_samples` samples, and their output is a grid whose size is independent
of it. They are therefore sharded along the *sample* axis, using the
`lane_offset` / `lane_count` window of D5: device `k` runs the sub-window
`(begin_k, count_k)` of the window the caller asked for, the windows are
contiguous and disjoint and cover it exactly, and every launch keeps the
caller's `direct/keller/suffix` counts so a local lane still runs the global
lane the single launch would have run. The per-shard result is a partial grid,
never a slice of one.
Merge-layer semantics (D3/D6). Chunks accumulate into their device's running
partial grid, in ascending lane order, on that device; the per-device partials
are then moved to the master and summed in `devices` order. Both the float and
the integer counters are summed the same way, so the sample counts merge
exactly while the grids merge in float32: a merged grid equals the
single-launch grid only up to float32 summation order, and the deviation grows
with the number of shards and chunks, not with the sample count. Nothing here
re-associates a *within-launch* reduction, which stays exactly the atomics the
single-device kernel has always run (D3). A run with the same devices, weights,
chunk size and inputs merges in a fixed order and therefore reproduces itself
as exactly as one device does -- which for the order-1 direct path is bitwise
and for the atomics-reducing order-2 chain path is to within the last ULP.
Shard and chunk boundaries are aligned to the 32-lane warp, relative to the
caller's window. Grid accumulation aggregates a warp's contributions before
the atomic, and a partially filled warp already loses contributions on one
device (a plain `direct_samples=20` launch accumulates fewer samples than it
tapes -- a defect that predates sharding and is not corrected here), so an
unaligned split would drop a fraction of a warp per shard *in addition* to
that. Aligned windows give every shard and chunk the same warp partition the
single launch has, including its trailing partial warp, which is why the
merged grid reproduces it. A window narrower than one warp per device is legal
and simply leaves the leading devices idle.
Gradients follow the same route as the `per_ray` ops (D4): a shard's states
and material are `master.to(device_k)`, so every shard's backward reduces onto
the caller's master leaves, and the merged grid's backward runs one native
backward per (device, chunk) launch against that launch's own tape.
"""
from __future__ import annotations
import sys
import time
from collections import deque
from dataclasses import dataclass, replace
from typing import Any, Callable, Mapping, NamedTuple, Sequence
import torch
from .geometry import (
AccumOptions,
AccumResult,
AxialEdgeVisibility,
DfrAccum,
DfrCoherentAccum,
DfrMaterial,
DfrPathLayout,
DfrPaths,
DfrStates,
Intersection,
NearestEdgesTopK,
NearestPointEdge,
NearestRayEdge,
Ray,
RayFlags,
ReflEpcField,
ReflMaterial,
ReflectionChain,
SegmentChainVisibility,
SegmentPairVisibility,
WedgeEvents,
_ReducedIntersection,
)
# Everything the multi-device layer cannot do yet points at the phase that owns
# it, so a caller who hits the wall knows what would have to land first.
_PHASE_2C = "docs/dev/multi_gpu_plan.md Phase 2c"
@dataclass(frozen=True)
class MultiDeviceOptions:
"""Tuning knobs for `Scene(devices=[...])`; every field is optional.
`weights` is the fallback shard split of decision D1: one non-negative
weight per device, in `devices` order, defaulting to an equal split. It is
a ratio, not a count, so `[9.0, 1.0]` and `[0.9, 0.1]` mean the same thing,
and a zero weight is legal and simply leaves that device idle.
`operation_weights` optionally replaces that fallback for one operation
family (for example `intersect`) or exact shape (for example
`trace_reflections:4`). Exact keys win over family keys.
`require_peer_access=True` rejects a topology without bidirectional CUDA
peer access between the master and every replica. Set it to `False` only
to explicitly accept PyTorch's host-staged cross-device copies and the
resulting loss of the overlap assumptions used by this executor.
`require_homogeneous_devices=True` likewise keeps the bitwise per-ray
contract inside the identical-model/capability topology for which it was
verified. Set it to `False` to permit a mixed set, with no cross-device
bitwise claim.
`warm_up` pre-links each device's OptiX pipelines through
`rayd._impl.runtime` while the scene is being built, so the first real
launch does not pay `len(devices)` module JITs in a row.
`chunk_rays`, `tape_memory_budget_bytes` and `offload` are the chunked
executor of D7. `chunk_rays` is the number of batch rows per launch and
wins over automatic sizing. `tape_memory_budget_bytes` is the hard
incremental peak estimate: it reserves the returned output, per-row input,
output and tape storage, and every concurrently resident chunk. `offload`
is called once per chunk as `offload(chunk_start_row, chunk_result)` with
the chunk's fields already on the master device; setting it means per-ray
results are streamed instead of concatenated and the operation returns
`None`. Differentiable multi-chunk execution needs per-chunk backward in
this hook for a memory budget to be meaningful. Any of the three engages
the chunked path, including on a one-device scene.
`pipeline`, `pipeline_chunks_per_device`, `min_rays_per_device` and
`min_lanes_per_device` are the throughput half of the executor (Phase 2d),
and only ever apply to a scene with more than one device. `pipeline` (on
by default) runs every `per_ray` operation through the double-buffered
executor so scatter, compute and gather overlap; `pipeline=False` keeps the
Phase 2a one-launch-per-shard path, which is the reference the pipelined
results are compared against.
`pipeline_chunks_per_device` is how many chunks the *widest* remote shard
is cut into: more chunks hide more of the pipeline's first scatter and last
gather, fewer chunks pay less per-launch host cost. The master's shard is
always one launch, because it has no copy to overlap.
`min_rays_per_device` is the baseline floor for each actual remote shard;
wider transfers raise it proportionally. `min_lanes_per_device` is the
corresponding floor for each remote accumulation window. If any active
remote shard is smaller, the complete call runs on the master replica.
Explicit chunk sizing or a memory budget is honoured whatever the batch
size.
"""
weights: Sequence[float] | None = None
# Optional operation-local splits. Exact keys (for example
# ``trace_reflections:4``) win over their family key
# (``trace_reflections``), and both win over ``weights``.
operation_weights: Mapping[str, Sequence[float]] | None = None
# Cross-device tensor copies without CUDA peer access are host staged and
# invalidate the overlap assumptions this executor is built around.
require_peer_access: bool = True
require_homogeneous_devices: bool = True
warm_up: bool = True
chunk_rays: int | None = None
# `Any`, not `object`: the second argument is the chunk's own result record
# (`Intersection`, `ReflectionChain`, ... -- whichever operation is running),
# so a hook written against a concrete record has to stay assignable here.
offload: Callable[[int, Any], None] | None = None
tape_memory_budget_bytes: int | None = None
pipeline: bool = True
pipeline_chunks_per_device: int = 4
min_rays_per_device: int = 262144
min_lanes_per_device: int = 262144
@dataclass
class ChunkPlan:
"""What the chunked executor decided, and what it then saw.
This is a debug surface, not API: it is what a test (or a caller sizing a
budget) reads off `Scene._multi.last_chunk_plan` to check that a memory
budget really did shrink the launches. `chunk_rays` is the effective size
after clamping to the batch, `row_bytes` the estimate that drove the
decision, and `measured_row_bytes` the output bytes per row the first
retired chunk actually produced -- the estimate covers the tape too, so the
two are only expected to agree in order of magnitude.
The lane-windowed `grid_reduce` operations reuse it for their sample-axis
chunking, where a row is a Monte-Carlo lane rather than a batch row, and
where `measured_row_bytes` stays `None` because a chunk produces a whole
grid rather than a slab of rows.
"""
operation: str
total_rows: int
chunk_rays: int
source: str
row_bytes: int
budget_bytes: int | None = None
resident_chunks: int = 1
fixed_output_bytes: int = 0
chunk_count: int = 0
measured_row_bytes: float | None = None
@dataclass
class DeviceCalibration:
"""What `calibrate()` measured, and the weights it derived from it.
`seconds` is the best of the timed runs per device, in `devices` order, for
a probe of `rows` rows, and `throughput_weights` is the split those timings
imply. `candidates` and `candidate_seconds` are the refinement stage's
ladder of remote shares and what the real dispatch cost at each of them;
`weights` is the rung it kept, and is what the scene has been using since
the call returned. It is a readable record on purpose -- calibration is the
one thing in this module that is allowed to depend on the machine's mood,
so a caller (or a bug report) can see exactly which numbers produced the
split.
"""
operation: str
rows: int
devices: tuple[int, ...] = ()
seconds: tuple[float, ...] = ()
weights: tuple[float, ...] = ()
samples: tuple[tuple[float, ...], ...] = ()
throughput_weights: tuple[float, ...] = ()
candidates: tuple[tuple[float, ...], ...] = ()
candidate_seconds: tuple[float, ...] = ()
@property
def rows_per_second(self) -> tuple[float, ...]:
return tuple(self.rows / value if value > 0.0 else 0.0 for value in self.seconds)
def describe(self) -> str:
"""A human-readable block, for logging: one line per device, then the ladder."""
lines = [
f"{self.operation} probe, {self.rows} rows",
*(
f" cuda:{index} {seconds * 1e3:8.3f} ms {self.rows / seconds / 1e6:8.2f} Mrow/s weight {weight:.4f}"
if seconds > 0.0
else f" cuda:{index} (no timing) weight {weight:.4f}"
for index, seconds, weight in zip(self.devices, self.seconds, self.throughput_weights or self.weights)
),
]
for weights, seconds in zip(self.candidates, self.candidate_seconds):
chosen = " <-- chosen" if weights == self.weights else ""
split = ", ".join(f"{weight:.4f}" for weight in weights)
lines.append(f" dispatch [{split}] {seconds * 1e3:8.3f} ms{chosen}")
return "\n".join(lines)
# `docs/dev/multi_gpu_plan.md` D7 sizes the reflection tape at 40-50 bytes per
# ray per bounce; the executor takes the pessimistic end so a budget is a bound
# rather than a hope. The output row of a reflection chain is separate: one
# `valid` byte, one float `t`, one int `prim_id` and three floats of image
# source, per bounce.
_REFLECTION_TAPE_BYTES_PER_RAY_BOUNCE = 50
_REFLECTION_OUTPUT_BYTES_PER_RAY_BOUNCE = 21
# Per-row output sizes of the remaining wrapped operations, summed field by
# field from their result schemas (float32 and int32 are 4 bytes, bool is 1).
_INTERSECT_REDUCED_ROW_BYTES = 4
_INTERSECT_FULL_ROW_BYTES = 76
_NEAREST_POINT_EDGE_ROW_BYTES = 32
_NEAREST_RAY_EDGE_ROW_BYTES = 48
_NEAREST_EDGES_ROW_BYTES_PER_K = 46
_VISIBLE_ROW_BYTES = 1
_VISIBLE_PAIR_ROW_BYTES = 2
_VISIBLE_EDGE_ROW_BYTES = 1
_VISIBLE_CHAIN_ROW_BYTES = 9
_REFL_EPC_FIELD_ROW_BYTES = 13
# Reflection accumulation copies four vec3 rows plus tmax/active (53 bytes) and
# the native facade splits those vec3 tensors into another four SoA rows. The
# staged strategy additionally keeps one int32 cell and eight float32 values
# for each ray/depth pair. Charging all of it makes a memory budget conservative
# for either accumulation strategy.
_REFL_ACCUM_INPUT_AND_SOA_BYTES = 101
_REFL_ACCUM_STAGED_BYTES_PER_RAY_DEPTH = 36
# Diffraction accumulation's per-row cost is per Monte-Carlo lane, not per ray:
# the AD tape (1 + 4 + 4 + 4 + 4 bytes) plus the visibility scratch byte, or the
# no-AD staging pair (4 + 16 bytes) plus that same byte, whichever is larger.
_DFR_ACCUM_LANE_BYTES = 21
# Coherent staging stores one int32 key and eight float32 values per lane.
# Smaller launches bypass staging, so this remains a conservative hard-budget
# charge for every coherent chunk.
_DFR_COHERENT_STAGED_LANE_BYTES = 36
# The shipped small-batch floor was measured for a full intersection row:
# 24 input bytes plus 76 output bytes. Wider rows need proportionally more
# remote work to amortize their copy; narrower rows still pay the same ~3 ms
# host/launch floor and therefore never lower the minimum.
_DISPATCH_BASELINE_TRANSFER_BYTES = 100
# Grid accumulation aggregates within a warp before its atomic, so every lane
# window this module cuts is a whole number of warps (see the module docstring).
_LANE_ALIGNMENT = 32
# The pipelined dispatch of Phase 2d. Both numbers are measured, not guessed;
# `docs/dev/multi_gpu_plan.md` Phase 2d and the module docstring record the
# sweep they come from (2x RTX A6000, NV4 at 52.6 GB/s per direction).
_PIPELINE_CHUNKS_PER_DEVICE = 4
_MIN_RAYS_PER_DEVICE = 262144
_MIN_LANES_PER_DEVICE = 262144
# The probe `calibrate()` runs when the caller does not supply one: a batch big
# enough to be dominated by the device rather than by the launch, small enough
# that calibrating a scene costs milliseconds.
_CALIBRATION_ROWS = 1 << 20
# What share of its throughput-implied weight each non-master device is offered
# in the refinement stage. The rungs are coarse on purpose -- the curve between
# them is flat compared with the difference between "shard it" and "do not" --
# and the last one is the master alone.
_REFINE_SHARES = (1.0, 0.5, 0.25, 0.1, 0.0)
# How much slower than the best rung a larger share may be and still be kept.
# The ladder is walked from the largest share down, so a tie -- or a
# neighbouring tenant's spike during one candidate's turn -- resolves towards
# using the devices rather than towards giving up on them.
_REFINE_TOLERANCE = 0.03
def calibrate_chunk_size(
operation: str,
total_rows: int,
*,
row_bytes: int,
chunk_rays: int | None = None,
budget_bytes: int | None = None,
resident_chunks: int = 1,
fixed_output_bytes: int = 0,
) -> ChunkPlan:
"""Pick the largest chunk that fits the tape budget, and record why.
An explicit `chunk_rays` is honoured verbatim (clamped to the batch, so a
chunk larger than the batch is simply one launch). Otherwise a
`budget_bytes` is divided by the operation's per-row cost -- the D7 tape
estimate for `trace_reflections`, the result schema's own row size for the
operations whose tape is not the binding term -- and never falls below a
single row, because a batch has to make progress even under an absurd
budget. With neither, a chunk is a whole shard and the executor's only job
is the double-buffered gather.
"""
rows = max(int(total_rows), 0)
cost = max(int(row_bytes), 1)
resident = _positive_int(resident_chunks, "resident_chunks")
fixed = max(int(fixed_output_bytes), 0)
if chunk_rays is not None:
size = int(chunk_rays)
source = "requested"
if budget_bytes is not None:
effective = min(size, rows) if rows else size
required = fixed + effective * cost * resident
if required > int(budget_bytes):
raise RuntimeError(
f"{operation}: chunk_rays={size} requires an estimated "
f"{required} bytes with {resident} resident chunk(s), exceeding "
f"tape_memory_budget_bytes={int(budget_bytes)}."
)
elif budget_bytes is not None:
available = int(budget_bytes) - fixed
if available < cost * resident:
raise RuntimeError(
f"{operation}: tape_memory_budget_bytes={int(budget_bytes)} cannot "
f"hold the fixed {fixed}-byte returned output plus one row across "
f"{resident} resident chunk(s); at least {fixed + cost * resident} "
"bytes are required."
)
size = max(available // (cost * resident), 1)
source = "budget"
else:
size = max(rows, 1)
source = "shard"
if rows:
size = min(size, rows)
return ChunkPlan(
operation=operation,
total_rows=rows,
chunk_rays=max(size, 1),
source=source,
row_bytes=cost,
budget_bytes=None if budget_bytes is None else int(budget_bytes),
resident_chunks=resident,
fixed_output_bytes=fixed,
)
def _resolve_lane_window(lane_offset: int, lane_count: int, total_samples: int) -> tuple[int, int]:
"""The `(begin, count)` window a diffraction accumulation call asks for.
This is the host-side twin of `resolve_lane_window()` in
`diffraction/ops.cpp`, including its messages: the orchestrator has to know
the width of the window before it can split it, and a caller must see the
same rejection on a multi-device scene as on a single-device one.
"""
total = int(total_samples)
begin = int(lane_offset)
count = int(lane_count)
if begin < 0:
raise RuntimeError("lane_offset must be non-negative.")
if begin > total:
raise RuntimeError("lane_offset must not exceed the total sample count.")
remaining = total - begin
if count < 0:
return begin, remaining
if count > remaining:
raise RuntimeError("lane_offset + lane_count must not exceed the total sample count.")
return begin, count
def _pick_candidate(seconds: Sequence[float]) -> int:
"""The first rung within `_REFINE_TOLERANCE` of the fastest one.
"First" is the largest remote share, because the ladder is built that way:
shrinking a device's shard is only worth doing when it is *measurably*
faster, and a run whose candidates all land within a few percent of each
other has not measured a reason to.
"""
best = min(seconds)
threshold = best * (1.0 + _REFINE_TOLERANCE)
for index, value in enumerate(seconds):
if value <= threshold:
return index
return int(seconds.index(best))
def _align_lanes(value: int) -> int:
"""Round a lane count to the nearest whole warp, halves upwards."""
return ((value + _LANE_ALIGNMENT // 2) // _LANE_ALIGNMENT) * _LANE_ALIGNMENT
def _lane_chunk_size(chunk_rays: int, count: int) -> int:
"""A chunk of lanes: at least one warp, never wider than the window.
A requested chunk is rounded *up* to a whole warp so that no chunk boundary
falls inside one, and the trailing chunk is simply short -- exactly as the
single launch's trailing warp is.
"""
size = max(int(chunk_rays), 1)
if size % _LANE_ALIGNMENT:
size += _LANE_ALIGNMENT - size % _LANE_ALIGNMENT
if count > 0:
size = min(size, count)
return size
def _finalize_lane_chunk_plan(plan: ChunkPlan, count: int) -> None:
"""Align a lane chunk without violating a hard memory budget."""
rows = max(int(count), 0)
if plan.source == "budget" and 0 < plan.chunk_rays < rows:
aligned = (plan.chunk_rays // _LANE_ALIGNMENT) * _LANE_ALIGNMENT
if aligned == 0:
minimum_rows = min(rows, _LANE_ALIGNMENT)
minimum_bytes = plan.fixed_output_bytes + minimum_rows * plan.row_bytes * plan.resident_chunks
raise RuntimeError(
f"{plan.operation}: tape_memory_budget_bytes={plan.budget_bytes} cannot hold one "
f"warp-aligned lane chunk; at least {minimum_bytes} bytes are required."
)
plan.chunk_rays = aligned
else:
plan.chunk_rays = _lane_chunk_size(plan.chunk_rays, rows)
if plan.budget_bytes is not None:
effective = min(plan.chunk_rays, rows) if rows else plan.chunk_rays
required = plan.fixed_output_bytes + effective * plan.row_bytes * plan.resident_chunks
if required > plan.budget_bytes:
raise RuntimeError(
f"{plan.operation}: the warp-aligned lane chunk requires an estimated {required} bytes, "
f"exceeding tape_memory_budget_bytes={plan.budget_bytes}."
)
def _to(value: torch.Tensor | None, device: torch.device) -> torch.Tensor | None:
"""Replicate one whole (unsharded) input onto `device`."""
if value is None or value.device == device:
return value
return value.to(device, non_blocking=True)
def _validate_source_lane_active(active: torch.Tensor, state_limit: int, master: torch.device) -> None:
"""Preserve the native path export mask contract before replication."""
if not active.is_cuda:
raise RuntimeError("active must be CUDA.")
if not active.is_contiguous():
raise RuntimeError("active must be contiguous.")
if active.dtype != torch.bool:
raise RuntimeError("active has the wrong dtype.")
if active.dim() != 1:
raise RuntimeError("active has the wrong rank.")
if active.size(0) != state_limit:
raise RuntimeError("active must have shape [state_limit].")
if active.device != master:
raise RuntimeError("active must share one CUDA device.")
def _validate_source_lane_devices(
tx_positions: torch.Tensor,
rx_positions: torch.Tensor,
states: DfrStates,
material: DfrMaterial,
master: torch.device,
) -> None:
"""Reject inputs that replication would otherwise move onto a valid device."""
named = (
("tx_positions", tx_positions),
("rx_positions", rx_positions),
("state_edge_index", states.edge_index),
("state_edge_pos", states.edge_pos),
("state_edge_dir", states.edge_dir),
("state_edge_t_min", states.edge_t_min),
("state_edge_t_max", states.edge_t_max),
("state_n0", states.n0),
("state_n1", states.n1),
("state_prim0", states.prim0),
("state_prim1", states.prim1),
("state_exterior_angle", states.exterior_angle),
("state_src", states.src),
("state_src_power", states.src_power),
("material_eta_r", material.eta_r),
("material_sigma", material.sigma),
("material_mu_r", material.mu_r),
("material_gain", material.gain),
("material_valid", material.valid),
)
for name, value in named:
if not value.is_cuda:
raise RuntimeError(f"{name} must be CUDA.")
if value.device != master:
raise RuntimeError(f"{name} must share one CUDA device.")
def _states_to(states: DfrStates, device: torch.device) -> DfrStates:
"""One replica's view of caller-owned diffraction states.
Every field is whole: the lane split is over Monte-Carlo samples, not over
states, so a shard sees the same states the single launch sees. The copy is
autograd-recorded, which is what reduces a shard's state gradients back onto
the caller's master leaves (D4).
"""
if states.edge_pos.device == device:
return states
return DfrStates(
edge_index=_to(states.edge_index, device),
edge_pos=_to(states.edge_pos, device),
edge_dir=_to(states.edge_dir, device),
edge_t_min=_to(states.edge_t_min, device),
edge_t_max=_to(states.edge_t_max, device),
n0=_to(states.n0, device),
n1=_to(states.n1, device),
prim0=_to(states.prim0, device),
prim1=_to(states.prim1, device),
exterior_angle=_to(states.exterior_angle, device),
src=_to(states.src, device),
src_power=_to(states.src_power, device),
wi=_to(states.wi, device),
d0=_to(states.d0, device),
count=states.count,
)
def _states_require_grad(states: DfrStates) -> bool:
return any(
value is not None and value.requires_grad
for value in (
states.edge_pos,
states.edge_dir,
states.edge_t_min,
states.edge_t_max,
states.n0,
states.n1,
states.exterior_angle,
states.src,
states.src_power,
states.wi,
states.d0,
)
)
def _material_to(material: DfrMaterial, device: torch.device) -> DfrMaterial:
if material.eta_r.device == device:
return material
return DfrMaterial(
eta_r=_to(material.eta_r, device),
sigma=_to(material.sigma, device),
mu_r=_to(material.mu_r, device),
gain=_to(material.gain, device),
valid=_to(material.valid, device),
)
def _material_requires_grad(material: DfrMaterial) -> bool:
return any(value.requires_grad for value in (material.eta_r, material.sigma, material.mu_r, material.gain))
def _refl_material_to(material: ReflMaterial, device: torch.device) -> ReflMaterial:
if material.eta_r.device == device:
return material
return ReflMaterial(
eta_r=_to(material.eta_r, device),
sigma=_to(material.sigma, device),
mu_r=_to(material.mu_r, device),
gain=_to(material.gain, device),
valid=_to(material.valid, device),
)
def _refl_material_bytes(material: ReflMaterial) -> int:
return sum(_tensor_bytes(getattr(material, name)) for name in ("eta_r", "sigma", "mu_r", "gain", "valid"))
def _add_accum(left: DfrAccum, right: DfrAccum) -> DfrAccum:
"""Sum two partial accumulation results field by field, on their device."""
return DfrAccum(left.grid_cell_count, *(getattr(left, name) + getattr(right, name) for name in _DFR_ACCUM_FIELDS))
def _accum_requires_grad(result: DfrAccum) -> bool:
return any(getattr(result, name).requires_grad for name in _DFR_ACCUM_FIELDS)
def _add_accum_in_place(left: DfrAccum, right: DfrAccum) -> DfrAccum:
"""Inference-only partial merge without allocating another full grid."""
if _accum_requires_grad(left) or _accum_requires_grad(right):
raise RuntimeError("in-place diffraction accumulation cannot carry autograd.")
for name in _DFR_ACCUM_FIELDS:
getattr(left, name).add_(getattr(right, name))
return left
def _accum_to(result: DfrAccum, device: torch.device) -> DfrAccum:
if result.power.device == device:
return result
return DfrAccum(
result.grid_cell_count, *(getattr(result, name).to(device, non_blocking=True) for name in _DFR_ACCUM_FIELDS)
)
def _add_coherent_accum(left: DfrCoherentAccum, right: DfrCoherentAccum) -> DfrCoherentAccum:
"""Sum two forward-only coherent partial grids on their current device."""
return DfrCoherentAccum(
left.grid_cell_count, *(getattr(left, name) + getattr(right, name) for name in _DFR_COHERENT_ACCUM_FIELDS)
)
def _add_coherent_accum_in_place(left: DfrCoherentAccum, right: DfrCoherentAccum) -> DfrCoherentAccum:
"""Merge coherent partials without another full-grid allocation."""
for name in _DFR_COHERENT_ACCUM_FIELDS:
getattr(left, name).add_(getattr(right, name))
return left
def _coherent_accum_to(result: DfrCoherentAccum, device: torch.device) -> DfrCoherentAccum:
first = getattr(result, _DFR_COHERENT_ACCUM_FIELDS[0])
if first.device == device:
return result
return DfrCoherentAccum(
result.grid_cell_count,
*(getattr(result, name).to(device, non_blocking=True) for name in _DFR_COHERENT_ACCUM_FIELDS),
)
def _wedge_events_to(events: WedgeEvents, device: torch.device) -> WedgeEvents:
first = events.count
if first.device == device:
return events
return WedgeEvents(
events.capacity, *(getattr(events, name).to(device, non_blocking=True) for name in _WEDGE_EVENT_FIELDS)
)
def _reflection_accum_to(result: AccumResult, device: torch.device) -> AccumResult:
if result.reflection_power.device == device:
return result
return AccumResult(
result.ray_count,
result.max_bounces,
result.grid_cell_count,
*(getattr(result, name).to(device, non_blocking=True) for name in _REFL_ACCUM_FIELDS),
_wedge_events_to(result.wedge_events, device),
)
def _add_reflection_accum(left: AccumResult, right: AccumResult) -> AccumResult:
"""Merge forward-only partial reflection grids in the caller's order."""
if left.max_bounces != right.max_bounces or left.grid_cell_count != right.grid_cell_count:
raise RuntimeError("reflection accumulation partials have incompatible result metadata.")
if left.wedge_events.capacity != 0 or right.wedge_events.capacity != 0:
raise RuntimeError("sharded reflection accumulation cannot merge bounded wedge-event buffers.")
wedges = WedgeEvents(
0,
left.wedge_events.count + right.wedge_events.count,
*(getattr(left.wedge_events, name) for name in _WEDGE_EVENT_PAYLOAD_FIELDS),
)
return AccumResult(
left.ray_count + right.ray_count,
left.max_bounces,
left.grid_cell_count,
*(getattr(left, name) + getattr(right, name) for name in _REFL_ACCUM_FIELDS),
wedges,
)
def _add_reflection_accum_in_place(left: AccumResult, right: AccumResult) -> AccumResult:
"""Merge a forward-only partial without allocating another full grid."""
if left.max_bounces != right.max_bounces or left.grid_cell_count != right.grid_cell_count:
raise RuntimeError("reflection accumulation partials have incompatible result metadata.")
if left.wedge_events.capacity != 0 or right.wedge_events.capacity != 0:
raise RuntimeError("sharded reflection accumulation cannot merge bounded wedge-event buffers.")
for name in _REFL_ACCUM_FIELDS:
getattr(left, name).add_(getattr(right, name))
left.wedge_events.count.add_(right.wedge_events.count)
return AccumResult(
left.ray_count + right.ray_count,
left.max_bounces,
left.grid_cell_count,
*(getattr(left, name) for name in _REFL_ACCUM_FIELDS),
left.wedge_events,
)
def _resolved_reflection_accum_options(
options: AccumOptions, ray_count: int, max_bounces: int, grid_cell_count: int
) -> AccumOptions:
"""Pin auto strategy to the choice the unsplit batch would make."""
if int(options.accumulation_strategy) != 0:
return options
depth_count = max(int(max_bounces) + 1, 1)
sample_count = int(ray_count) * depth_count
staged_min = int(options.compact_min_samples) if int(options.compact_min_samples) > 0 else 2048
staged_per_cell = int(options.staged_min_samples_per_cell) if int(options.staged_min_samples_per_cell) > 0 else 4
staged = (
sample_count <= 2**31 - 1 and sample_count >= staged_min and sample_count >= grid_cell_count * staged_per_cell
)
return replace(options, accumulation_strategy=2 if staged else 1)
def _merge_source_lane_paths(parts: Sequence[tuple[int, DfrPaths]], *, capacity: int, master: torch.device) -> DfrPaths:
"""Join transmitter-aligned SourceLane blocks without compacting rows."""
def gather(name: str) -> torch.Tensor:
values = [getattr(result, name).to(master, non_blocking=True) for _start, result in parts]
return values[0] if len(values) == 1 else torch.cat(values, dim=0)
counts = [result.count.to(master, non_blocking=True) for _start, result in parts]
count = torch.stack(counts).sum(dim=0, dtype=counts[0].dtype)
tx_ids = [
torch.where(result.valid, result.tx_id + int(start), result.tx_id).to(master, non_blocking=True)
for start, result in parts
]
tx_id = tx_ids[0] if len(tx_ids) == 1 else torch.cat(tx_ids, dim=0)
return DfrPaths(
int(capacity),
count,
gather("valid"),
tx_id,
gather("rx_id"),
gather("order"),
gather("edge0"),
gather("edge1"),
gather("edge2"),
gather("delay"),
gather("field_x_re"),
gather("field_x_im"),
gather("field_y_re"),
gather("field_y_im"),
gather("field_z_re"),
gather("field_z_im"),
gather("p0"),
gather("p1"),
gather("p2"),
layout=DfrPathLayout.SourceLane,
)
def _tensor_bytes(value: torch.Tensor | None) -> int:
if value is None:
return 0
return int(value.numel()) * int(value.element_size())
def _states_bytes(states: DfrStates) -> int:
return sum(
_tensor_bytes(getattr(states, name))
for name in (
"edge_index",
"edge_pos",
"edge_dir",
"edge_t_min",
"edge_t_max",
"n0",
"n1",
"prim0",
"prim1",
"exterior_angle",
"src",
"src_power",
"wi",
"d0",
)
)
def _material_bytes(material: DfrMaterial) -> int:
return sum(_tensor_bytes(getattr(material, name)) for name in ("eta_r", "sigma", "mu_r", "gain", "valid"))
def _device_index(value: object, position: int) -> int:
"""One `devices` entry as a plain CUDA device index."""
if isinstance(value, torch.device):
device = value
elif isinstance(value, str):
device = torch.device(value)
elif isinstance(value, int) and not isinstance(value, bool):
device = torch.device("cuda", value)
else:
raise TypeError(
"Scene(devices=...) entries must be int, str, or torch.device, got "
f"{type(value).__name__} at position {position}."
)
if device.type != "cuda":
raise ValueError(f"Scene(devices=...) only accepts CUDA devices, got {device!r} at position {position}.")
# Bare ``"cuda"`` follows PyTorch's current-device semantics. Treating it
# as cuda:0 silently selects the wrong master after ``set_device()``.
return torch.cuda.current_device() if device.index is None else device.index
def _normalize_devices(devices: Sequence[object]) -> list[int]:
if isinstance(devices, (int, str, torch.device)):
raise TypeError(f"Scene(devices=...) expects a sequence of devices; pass [{devices!r}] instead of {devices!r}.")
indices = [_device_index(value, position) for position, value in enumerate(devices)]
if not indices:
raise ValueError("Scene(devices=...) needs at least one device.")
duplicates = sorted({index for index in indices if indices.count(index) > 1})
if duplicates:
raise ValueError(
f"Scene(devices=...) received duplicate devices {duplicates}; each device holds exactly one replica."
)
if not torch.cuda.is_available():
raise RuntimeError("Scene(devices=...) needs CUDA, but torch.cuda.is_available() is False.")
count = torch.cuda.device_count()
for index in indices:
if index < 0 or index >= count:
raise ValueError(
f"Scene(devices=...) got device index {index}, but only {count} CUDA device(s) are visible."
)
return indices