1use std::sync::Arc;
2
3use std::{
4 cell::{Cell, RefCell},
5 fmt,
6};
7
8use crate::{Error, Matrix, Result, core::Element};
9
10use super::{
11 Buffer, BufferAccess, Device, EngineHandle, Event, RecordedCommandBuffer, ReusableCommandBuffer,
12 SemanticGraph, SemanticLoweringAnalysis, Storage,
13 device::NativeFlagBits,
14 dna::{DnnPlan, DnnPolicy, fusion},
15 graph::executable::{AccessState, ExecutableGraph, GraphNode},
16 session::{PendingExecution, SemanticStorageSnapshot, StableResourceSnapshot},
17};
18
19pub(super) mod serialization;
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub struct ExecutionPlanDiagnostics {
24 graph_id: u64,
25 device_capability_identity: u64,
26 node_count: usize,
27 barrier_count: usize,
28 semantic_operation_count: usize,
29 semantic_autograd_attachment_count: usize,
30 semantic_autograd_expanded_count: usize,
31 semantic_backward_operation_count: usize,
32 schema_owned_node_count: usize,
33 compatibility_node_count: usize,
34 semantic_fused_operation_count: usize,
35 semantic_fused_node_count: usize,
36 maximum_semantic_operations_per_node: usize,
37 dnn_graph_hash: u64,
38 dnn_value_count: usize,
39 dnn_external_value_count: usize,
40 dnn_virtual_value_count: usize,
41 dnn_partition_count: usize,
42 dnn_recognized_partition_count: u32,
43 dnn_portable_partition_count: usize,
44 dnn_captured_operation_count: u32,
45 dnn_applied_partition_count: u32,
46 dnn_inherited_partition_count: u32,
47 dnn_fallback_partition_count: u32,
48 dnn_unexpected_fallback_count: u32,
49 input_binding_count: usize,
50 captured_resource_count: usize,
51 physical_resource_count: usize,
52 stable_replay_input_count: usize,
53 stable_transient_count: usize,
54 semantic_binding_count: usize,
55 observed_output_count: usize,
56 alias_candidate_count: usize,
57 alias_materialized_count: usize,
58 planned_alias_group_count: usize,
59 potential_alias_savings: usize,
60 materialized_alias_savings: usize,
61 descriptor_write_count: u64,
62 push_byte_count: usize,
63 peak_memory_bytes: usize,
64 cross_queue_edge_count: usize,
65 ownership_transfer_count: usize,
66 queue_run_count: usize,
67 command_recording_count: u64,
68 command_cache_hit_count: u64,
69 submission_count: u64,
70 input_rebinding_count: u64,
71 input_upload_count: u64,
72 fallback_count: u64,
73}
74
75impl ExecutionPlanDiagnostics {
76 pub const fn graph_id(self) -> u64 {
78 self.graph_id
79 }
80
81 pub const fn device_capability_identity(self) -> u64 {
83 self.device_capability_identity
84 }
85
86 pub const fn node_count(self) -> usize {
88 self.node_count
89 }
90
91 pub const fn barrier_count(self) -> usize {
93 self.barrier_count
94 }
95
96 pub const fn semantic_operation_count(self) -> usize {
98 self.semantic_operation_count
99 }
100
101 pub const fn semantic_autograd_attachment_count(self) -> usize {
103 self.semantic_autograd_attachment_count
104 }
105
106 pub const fn semantic_autograd_expanded_count(self) -> usize {
108 self.semantic_autograd_expanded_count
109 }
110
111 pub const fn semantic_backward_operation_count(self) -> usize {
113 self.semantic_backward_operation_count
114 }
115
116 pub const fn schema_owned_node_count(self) -> usize {
118 self.schema_owned_node_count
119 }
120
121 pub const fn compatibility_node_count(self) -> usize {
123 self.compatibility_node_count
124 }
125
126 pub const fn semantic_fused_operation_count(self) -> usize {
128 self.semantic_fused_operation_count
129 }
130
131 pub const fn semantic_fused_node_count(self) -> usize {
133 self.semantic_fused_node_count
134 }
135
136 pub const fn maximum_semantic_operations_per_node(self) -> usize {
138 self.maximum_semantic_operations_per_node
139 }
140
141 pub const fn dnn_graph_hash(self) -> u64 {
143 self.dnn_graph_hash
144 }
145
146 pub const fn dnn_value_count(self) -> usize {
148 self.dnn_value_count
149 }
150
151 pub const fn dnn_external_value_count(self) -> usize {
153 self.dnn_external_value_count
154 }
155
156 pub const fn dnn_virtual_value_count(self) -> usize {
158 self.dnn_virtual_value_count
159 }
160
161 pub const fn dnn_partition_count(self) -> usize {
163 self.dnn_partition_count
164 }
165
166 pub const fn dnn_recognized_partition_count(self) -> u32 {
168 self.dnn_recognized_partition_count
169 }
170
171 pub const fn dnn_portable_partition_count(self) -> usize {
173 self.dnn_portable_partition_count
174 }
175
176 pub const fn dnn_captured_operation_count(self) -> u32 {
178 self.dnn_captured_operation_count
179 }
180
181 pub const fn dnn_applied_partition_count(self) -> u32 {
183 self.dnn_applied_partition_count
184 }
185
186 pub const fn dnn_inherited_partition_count(self) -> u32 {
188 self.dnn_inherited_partition_count
189 }
190
191 pub const fn dnn_fallback_partition_count(self) -> u32 {
193 self.dnn_fallback_partition_count
194 }
195
196 pub const fn dnn_unexpected_fallback_count(self) -> u32 {
198 self.dnn_unexpected_fallback_count
199 }
200
201 pub const fn input_binding_count(self) -> usize {
203 self.input_binding_count
204 }
205
206 pub const fn captured_resource_count(self) -> usize {
208 self.captured_resource_count
209 }
210
211 pub const fn physical_resource_count(self) -> usize {
213 self.physical_resource_count
214 }
215
216 pub const fn stable_replay_input_count(self) -> usize {
218 self.stable_replay_input_count
219 }
220
221 pub const fn stable_transient_count(self) -> usize {
226 self.stable_transient_count
227 }
228
229 pub const fn semantic_binding_count(self) -> usize {
231 self.semantic_binding_count
232 }
233
234 pub const fn observed_output_count(self) -> usize {
236 self.observed_output_count
237 }
238
239 pub const fn alias_candidate_count(self) -> usize {
242 self.alias_candidate_count
243 }
244
245 pub const fn alias_materialized_count(self) -> usize {
247 self.alias_materialized_count
248 }
249
250 pub const fn planned_alias_group_count(self) -> usize {
252 self.planned_alias_group_count
253 }
254
255 pub const fn potential_alias_savings(self) -> usize {
257 self.potential_alias_savings
258 }
259
260 pub const fn materialized_alias_savings(self) -> usize {
262 self.materialized_alias_savings
263 }
264
265 pub const fn command_recording_count(self) -> u64 {
267 self.command_recording_count
268 }
269
270 pub const fn descriptor_write_count(self) -> u64 {
276 self.descriptor_write_count
277 }
278
279 pub const fn push_byte_count(self) -> usize {
281 self.push_byte_count
282 }
283
284 pub const fn peak_memory_bytes(self) -> usize {
290 self.peak_memory_bytes
291 }
292
293 pub const fn cross_queue_edge_count(self) -> usize {
296 self.cross_queue_edge_count
297 }
298
299 pub const fn ownership_transfer_count(self) -> usize {
302 self.ownership_transfer_count
303 }
304
305 pub const fn queue_run_count(self) -> usize {
309 self.queue_run_count
310 }
311
312 pub const fn command_cache_hit_count(self) -> u64 {
314 self.command_cache_hit_count
315 }
316
317 pub const fn submission_count(self) -> u64 {
319 self.submission_count
320 }
321
322 pub const fn input_rebinding_count(self) -> u64 {
324 self.input_rebinding_count
325 }
326
327 pub const fn input_upload_count(self) -> u64 {
329 self.input_upload_count
330 }
331
332 pub const fn fallback_count(self) -> u64 {
334 self.fallback_count
335 }
336}
337
338struct InputStagingSlot {
343 buffer: Buffer,
344 consumer: RefCell<Option<Event>>,
345}
346
347struct MatrixInputBinding {
348 original: Buffer,
349 current: Buffer,
350 staging: Vec<InputStagingSlot>,
353}
354
355#[derive(Clone, Copy, Debug, PartialEq, Eq)]
362pub struct CapturedResourceDesc {
363 resource: u32,
364 byte_len: usize,
365 first_access: usize,
366 last_access: usize,
367 stable_replay_input: bool,
368 stable_transient: bool,
369 semantic_external: bool,
370 observed_output: bool,
371 capture_retained_owner_count: usize,
372 unaccounted_owner_count: usize,
373 alias_candidate: bool,
374 alias_materialized: bool,
375}
376
377impl CapturedResourceDesc {
378 pub const fn resource(self) -> u32 {
379 self.resource
380 }
381
382 pub const fn byte_len(self) -> usize {
383 self.byte_len
384 }
385
386 pub const fn first_access(self) -> usize {
387 self.first_access
388 }
389
390 pub const fn last_access(self) -> usize {
391 self.last_access
392 }
393
394 pub const fn stable_replay_input(self) -> bool {
395 self.stable_replay_input
396 }
397
398 pub const fn stable_transient(self) -> bool {
399 self.stable_transient
400 }
401
402 pub const fn semantic_external(self) -> bool {
403 self.semantic_external
404 }
405
406 pub const fn observed_output(self) -> bool {
407 self.observed_output
408 }
409
410 pub const fn is_externally_live(self) -> bool {
413 self.semantic_external || self.stable_replay_input || self.observed_output
414 }
415
416 pub const fn capture_retained_owner_count(self) -> usize {
418 self.capture_retained_owner_count
419 }
420
421 pub const fn unaccounted_owner_count(self) -> usize {
423 self.unaccounted_owner_count
424 }
425
426 pub const fn alias_candidate(self) -> bool {
431 self.alias_candidate
432 }
433
434 pub const fn alias_materialized(self) -> bool {
435 self.alias_materialized
436 }
437}
438
439#[derive(Clone, Copy, Debug, PartialEq, Eq)]
444pub enum ExecutionBindingRole {
445 Input,
447 Output,
449}
450
451#[derive(Clone, Debug, PartialEq, Eq)]
459pub struct ExecutionBindingDesc {
460 slot: u32,
461 semantic_value: super::SemanticValueId,
462 kind: crate::OpValueKind,
463 role: ExecutionBindingRole,
464 shape: Vec<usize>,
465 strides: Vec<isize>,
466 dtype: crate::DType,
467 byte_offset: u64,
468}
469
470impl ExecutionBindingDesc {
471 #[allow(clippy::too_many_arguments)]
473 pub(super) fn new(
474 slot: u32,
475 semantic_value: super::SemanticValueId,
476 kind: crate::OpValueKind,
477 role: ExecutionBindingRole,
478 shape: Vec<usize>,
479 strides: Vec<isize>,
480 dtype: crate::DType,
481 byte_offset: u64,
482 ) -> Self {
483 Self {
484 slot,
485 semantic_value,
486 kind,
487 role,
488 shape,
489 strides,
490 dtype,
491 byte_offset,
492 }
493 }
494
495 pub const fn slot(&self) -> u32 {
497 self.slot
498 }
499
500 pub const fn semantic_value(&self) -> super::SemanticValueId {
502 self.semantic_value
503 }
504
505 pub const fn kind(&self) -> crate::OpValueKind {
507 self.kind
508 }
509
510 pub const fn role(&self) -> ExecutionBindingRole {
512 self.role
513 }
514
515 pub fn shape(&self) -> &[usize] {
517 &self.shape
518 }
519
520 pub fn strides(&self) -> &[isize] {
522 &self.strides
523 }
524
525 pub const fn dtype(&self) -> crate::DType {
527 self.dtype
528 }
529
530 pub const fn byte_offset(&self) -> u64 {
532 self.byte_offset
533 }
534}
535
536#[derive(Clone, Copy, Debug, PartialEq, Eq)]
538pub struct SemanticStorageBinding {
539 value: super::SemanticValueId,
540 resource: u32,
541 semantic_external: bool,
542 stable_replay_input: bool,
543 observed_output: bool,
544}
545
546impl SemanticStorageBinding {
547 pub const fn value(self) -> super::SemanticValueId {
548 self.value
549 }
550
551 pub const fn resource(self) -> u32 {
552 self.resource
553 }
554
555 pub const fn semantic_external(self) -> bool {
556 self.semantic_external
557 }
558
559 pub const fn stable_replay_input(self) -> bool {
560 self.stable_replay_input
561 }
562
563 pub const fn observed_output(self) -> bool {
564 self.observed_output
565 }
566}
567
568const MAX_CACHED_BINDING_COMMANDS: usize = 8;
569const STABLE_INPUT_STAGING_DEPTH: usize = 3;
570
571#[derive(Default)]
572struct PlanCounters {
573 command_recordings: Cell<u64>,
574 command_cache_hits: Cell<u64>,
575 submissions: Cell<u64>,
576 input_rebindings: Cell<u64>,
577 input_uploads: Cell<u64>,
578 fallbacks: Cell<u64>,
579}
580
581#[must_use]
589pub struct ExecutionPlan {
590 engine: EngineHandle,
591 graph_id: u64,
592 device_capability_identity: u64,
593 graph: ExecutableGraph,
594 outputs: Vec<Storage>,
595 semantic: SemanticGraph,
596 semantic_lowering: SemanticLoweringAnalysis,
597 dnn: DnnPlan,
598 input_bindings: Vec<MatrixInputBinding>,
599 bindings: Vec<ExecutionBindingDesc>,
600 binding_contract_hash: u64,
601 captured_resources: Vec<CapturedResourceDesc>,
602 semantic_bindings: Vec<SemanticStorageBinding>,
603 descriptor_write_count: u64,
604 materialized_alias_savings: usize,
605 alias_materialization_fallback_reason: Option<String>,
606 cached_commands: RefCell<Vec<(Vec<u32>, Vec<ReusableCommandBuffer>)>>,
607 last_submission: RefCell<Option<Event>>,
608 counters: PlanCounters,
609}
610
611impl ExecutionPlan {
612 pub(super) fn new(
613 engine: EngineHandle,
614 pending: PendingExecution,
615 source_recording_retained: bool,
616 ) -> Result<Self> {
617 let (mut graph, mut outputs, semantic, stable_resources, semantic_storage, observed_outputs) =
618 pending.into_parts();
619 let device_capability_identity = engine.device_info().capability_identity();
620 let mut dnn = DnnPlan::plan(&semantic, DnnPolicy::default())?;
621 if dnn.source_operation_count() as usize != semantic.operations().len() {
622 return Err(Error::internal(
623 "DNN plan source operation count does not match the semantic graph",
624 ));
625 }
626 let (bindings, binding_contract_hash) = dnn.build_binding_contract(&semantic)?;
627 let input_bindings = graph
628 .read_only_buffers()
629 .into_iter()
630 .map(|buffer| MatrixInputBinding {
631 original: buffer.clone(),
632 current: buffer.clone(),
633 staging: vec![InputStagingSlot {
634 buffer,
635 consumer: RefCell::new(None),
636 }],
637 })
638 .collect();
639 let mut resource_lifetimes = graph.resource_lifetimes();
640 for binding in &semantic_storage {
646 let Some(buffer) = binding.storage.buffer() else {
647 continue;
648 };
649 if !resource_lifetimes
650 .iter()
651 .any(|lifetime| lifetime.buffer.same_as(buffer))
652 {
653 resource_lifetimes.push(super::graph::executable::ResourceLifetime {
654 buffer: buffer.clone(),
655 first_access: 0,
656 last_access: 0,
657 });
658 }
659 }
660 let mut captured_resources = resource_lifetimes
661 .iter()
662 .enumerate()
663 .map(|(resource, lifetime)| {
664 let stable = stable_resources.iter().find(|candidate| {
665 candidate
666 .storage
667 .buffer()
668 .is_some_and(|buffer| buffer.same_as(&lifetime.buffer))
669 });
670 let owner = find_resource_storage(
671 &lifetime.buffer,
672 &stable_resources,
673 &semantic_storage,
674 &observed_outputs,
675 &outputs,
676 );
677 let stable_owner_count = stable_resources
678 .iter()
679 .filter(|candidate| owner.is_some_and(|owner| candidate.storage.same_as(owner)))
680 .count()
681 .saturating_mul(2);
682 let source_copy_count = usize::from(source_recording_retained);
683 let capture_retained_owner_count = stable_owner_count
684 .saturating_add(
685 semantic_storage
686 .iter()
687 .filter(|candidate| owner.is_some_and(|owner| candidate.storage.same_as(owner)))
688 .count()
689 .saturating_mul(1 + source_copy_count),
690 )
691 .saturating_add(
692 observed_outputs
693 .iter()
694 .filter(|candidate| owner.is_some_and(|owner| candidate.same_as(owner)))
695 .count(),
696 )
697 .saturating_add(
698 outputs
699 .iter()
700 .filter(|candidate| owner.is_some_and(|owner| candidate.same_as(owner)))
701 .count()
702 .saturating_mul(1 + source_copy_count),
703 );
704 let unaccounted_owner_count = owner.map_or(0, |owner| {
705 owner
706 .owner_count()
707 .saturating_sub(capture_retained_owner_count)
708 });
709 Ok(CapturedResourceDesc {
710 resource: u32::try_from(resource)
711 .map_err(|_| Error::resource_exhausted("captured resource identity exceeds u32"))?,
712 byte_len: lifetime.buffer.byte_len(),
713 first_access: lifetime.first_access,
714 last_access: lifetime.last_access,
715 stable_replay_input: stable.is_some_and(|value| value.replay_input),
716 stable_transient: stable.is_some_and(|value| value.transient),
717 semantic_external: false,
718 observed_output: false,
719 capture_retained_owner_count,
720 unaccounted_owner_count,
721 alias_candidate: false,
722 alias_materialized: false,
723 })
724 })
725 .collect::<Result<Vec<_>>>()?;
726 let mut semantic_bindings = Vec::with_capacity(semantic_storage.len());
727 for binding in &semantic_storage {
728 let value = semantic
729 .values()
730 .get(binding.value.index() as usize)
731 .ok_or_else(|| Error::internal("semantic storage binding value is out of range"))?;
732 let resource = find_resource(&resource_lifetimes, &binding.storage)?;
733 let resource_id = u32::try_from(resource)
734 .map_err(|_| Error::resource_exhausted("captured resource identity exceeds u32"))?;
735 captured_resources[resource].semantic_external |= value.is_external();
736 semantic_bindings.push(SemanticStorageBinding {
737 value: binding.value,
738 resource: resource_id,
739 semantic_external: value.is_external(),
740 stable_replay_input: captured_resources[resource].stable_replay_input,
741 observed_output: false,
742 });
743 }
744 for output in &observed_outputs {
745 let resource = find_resource(&resource_lifetimes, output)?;
746 captured_resources[resource].observed_output = true;
747 for binding in &mut semantic_bindings {
748 if binding.resource as usize == resource {
749 binding.observed_output = true;
750 }
751 }
752 }
753 graph = dnn.lower_captured_plan(
754 &engine,
755 &semantic,
756 &semantic_bindings,
757 &resource_lifetimes,
758 &captured_resources,
759 !source_recording_retained,
760 &graph,
761 )?;
762 engine.record_dnn_partitions(
763 dnn.applied_partition_count(),
764 dnn.fallback_partition_count(),
765 );
766 let graph_id = graph.identity();
767 let semantic_lowering = graph.analyze_semantic_lowering(&semantic)?;
768 let mut first_access: std::collections::BTreeMap<u32, BufferAccess> =
772 std::collections::BTreeMap::new();
773 let mut last_access: std::collections::BTreeMap<u32, BufferAccess> =
774 std::collections::BTreeMap::new();
775 for node in graph.nodes() {
776 if let Some(indirect) = node.indirect() {
777 let identity = indirect.buffer.descriptor_index();
778 first_access.entry(identity).or_insert(BufferAccess::Read);
779 last_access.insert(identity, BufferAccess::Read);
780 }
781 for usage in node.buffers() {
782 let identity = usage.buffer.descriptor_index();
783 first_access.entry(identity).or_insert(usage.access);
784 last_access.insert(identity, usage.access);
785 }
786 }
787 for (index, resource) in captured_resources.iter_mut().enumerate() {
788 let buffer = &resource_lifetimes[index].buffer;
789 let identity = buffer.descriptor_index();
790 resource.alias_candidate = matches!(first_access.get(&identity), Some(BufferAccess::Write))
792 && (resource.stable_transient
793 || matches!(last_access.get(&identity), Some(BufferAccess::Read)))
794 && !resource.is_externally_live()
795 && resource.unaccounted_owner_count == 0
796 && !fusion::buffer_is_fused_binding(graph.compute_nodes(), buffer);
797 }
798 let materialization = materialize_aliases(
799 &engine,
800 &graph,
801 &outputs,
802 &resource_lifetimes,
803 &captured_resources,
804 );
805 let (retired, materialized_alias_savings, alias_materialization_fallback_reason) =
806 match materialization {
807 Ok(materialized) => {
808 graph = materialized.graph;
809 outputs = materialized.outputs;
810 captured_resources = materialized.captured_resources;
811 (materialized.retired, materialized.savings, None)
812 }
813 Err(error) => (
814 Vec::new(),
815 0,
816 Some(format!("transient alias materialization failed: {error}")),
817 ),
818 };
819 engine.release_stable_transient_resources(&retired);
820 let initial_fallback_count = u64::from(alias_materialization_fallback_reason.is_some())
821 .saturating_add(u64::from(dnn.fallback_partition_count()));
822 Ok(Self {
823 engine,
824 graph_id,
825 device_capability_identity,
826 graph,
827 outputs,
828 semantic,
829 semantic_lowering,
830 dnn,
831 input_bindings,
832 bindings,
833 binding_contract_hash,
834 captured_resources,
835 semantic_bindings,
836 descriptor_write_count: 0,
837 materialized_alias_savings,
838 alias_materialization_fallback_reason,
839 cached_commands: RefCell::new(Vec::new()),
840 last_submission: RefCell::new(None),
841 counters: PlanCounters {
842 fallbacks: Cell::new(initial_fallback_count),
843 ..PlanCounters::default()
844 },
845 })
846 }
847
848 pub(super) fn set_descriptor_write_count(&mut self, count: u64) {
850 self.descriptor_write_count = count;
851 }
852
853 pub const fn semantic_graph(&self) -> &SemanticGraph {
855 &self.semantic
856 }
857
858 pub const fn semantic_lowering(&self) -> &SemanticLoweringAnalysis {
860 &self.semantic_lowering
861 }
862
863 pub fn captured_resources(&self) -> &[CapturedResourceDesc] {
865 &self.captured_resources
866 }
867
868 pub fn semantic_bindings(&self) -> &[SemanticStorageBinding] {
870 &self.semantic_bindings
871 }
872
873 pub fn alias_materialization_fallback_reason(&self) -> Option<&str> {
878 self.alias_materialization_fallback_reason.as_deref()
879 }
880
881 pub fn upload_matrix_input<T: Element>(&mut self, captured: &Matrix, values: &[T]) -> Result<()> {
897 if !self.engine.same_as(captured.engine_handle()) {
898 return Err(Error::invalid_argument(
899 "execution-plan Matrix input belongs to another engine",
900 ));
901 }
902 let captured_buffer = captured.storage().buffer().ok_or_else(|| {
903 Error::invalid_argument("zero-sized Matrix storage cannot identify a captured plan input")
904 })?;
905 let binding_index = self
906 .input_bindings
907 .iter()
908 .position(|binding| binding.original.same_as(captured_buffer))
909 .ok_or_else(|| {
910 Error::invalid_argument("captured Matrix is not a read-only input of this execution plan")
911 })?;
912 if captured.dtype() != T::DTYPE {
913 return Err(Error::invalid_argument(format!(
914 "matrix element type {} does not match dtype {}",
915 T::DTYPE.token(),
916 captured.dtype().token()
917 )));
918 }
919 if values.len() != captured.element_count() {
920 return Err(Error::invalid_argument(format!(
921 "matrix upload requires {} elements; received {}",
922 captured.element_count(),
923 values.len()
924 )));
925 }
926 let binding = &mut self.input_bindings[binding_index];
927 let current_slot = binding
928 .staging
929 .iter()
930 .position(|slot| slot.buffer.same_as(&binding.current))
931 .ok_or_else(|| {
932 Error::failed_precondition(
933 "execution-plan host upload requires a ring-bound stable input slot",
934 )
935 })?;
936 let next_slot = (current_slot + 1) % STABLE_INPUT_STAGING_DEPTH;
937 if next_slot == binding.staging.len() {
938 let buffer =
939 Buffer::host_visible_storage(binding.original.device(), binding.original.byte_len())?;
940 binding.staging.push(InputStagingSlot {
941 buffer,
942 consumer: RefCell::new(None),
943 });
944 }
945 let slot = &binding.staging[next_slot];
946 if let Some(event) = slot.consumer.borrow().as_ref() {
947 event.wait()?;
948 }
949 binding.original.wait_bound_consumer()?;
954 if slot.buffer.same_as(&binding.original) {
955 captured.write_values(values)?;
956 } else {
957 let byte_len = values
958 .len()
959 .checked_mul(std::mem::size_of::<T>())
960 .ok_or_else(|| Error::invalid_argument("matrix byte size overflows usize"))?;
961 let bytes = unsafe { std::slice::from_raw_parts(values.as_ptr().cast(), byte_len) };
964 if T::DTYPE == crate::DType::U8 {
965 let mut padded = vec![0_u8; crate::matrix::byte_storage_len(byte_len, T::DTYPE)?];
966 padded[..byte_len].copy_from_slice(bytes);
967 slot.buffer.write(0, &padded)?;
968 } else {
969 slot.buffer.write(0, bytes)?;
970 }
971 captured.write_values(values)?;
977 }
978 if !binding.current.same_as(&slot.buffer) {
979 self.graph.rebind_read_only(
980 &binding.current,
981 &slot.buffer,
982 self.engine.execution_profile(),
983 )?;
984 binding.current = slot.buffer.clone();
985 }
986 increment(&self.counters.input_uploads);
987 Ok(())
988 }
989
990 pub fn bind_matrix_input(&mut self, captured: &Matrix, replacement: &Matrix) -> Result<()> {
1004 if !self.engine.same_as(captured.engine_handle())
1005 || !self.engine.same_as(replacement.engine_handle())
1006 {
1007 return Err(Error::invalid_argument(
1008 "execution-plan Matrix bindings must belong to the plan's engine",
1009 ));
1010 }
1011 if captured.shape() != replacement.shape() || captured.dtype() != replacement.dtype() {
1012 return Err(Error::invalid_argument(format!(
1013 "execution-plan Matrix input requires shape {:?} and dtype {}; replacement has shape {:?} and dtype {}",
1014 captured.shape(),
1015 captured.dtype().token(),
1016 replacement.shape(),
1017 replacement.dtype().token()
1018 )));
1019 }
1020 replacement
1021 .storage()
1022 .validate_recording_access(BufferAccess::Read)?;
1023 let captured_buffer = captured.storage().buffer().ok_or_else(|| {
1024 Error::invalid_argument("zero-sized Matrix storage cannot identify a captured plan input")
1025 })?;
1026 let replacement_buffer = replacement.storage().buffer().ok_or_else(|| {
1027 Error::invalid_argument("zero-sized Matrix storage cannot replace a captured plan input")
1028 })?;
1029
1030 let existing = self
1031 .input_bindings
1032 .iter()
1033 .position(|binding| binding.original.same_as(captured_buffer))
1034 .ok_or_else(|| {
1035 Error::invalid_argument("captured Matrix is not a read-only input of this execution plan")
1036 })?;
1037 let current = self.input_bindings[existing].current.clone();
1038 if current.same_as(replacement_buffer) {
1039 return Ok(());
1040 }
1041 self.graph.rebind_read_only(
1042 ¤t,
1043 replacement_buffer,
1044 self.engine.execution_profile(),
1045 )?;
1046 self.input_bindings[existing].current = replacement_buffer.clone();
1047 increment(&self.counters.input_rebindings);
1048 Ok(())
1049 }
1050
1051 pub const fn binding_count(&self) -> usize {
1055 self.bindings.len()
1056 }
1057
1058 pub fn input_binding_count(&self) -> usize {
1062 self
1063 .bindings
1064 .iter()
1065 .filter(|binding| binding.role() == ExecutionBindingRole::Input)
1066 .count()
1067 }
1068
1069 pub fn output_binding_count(&self) -> usize {
1073 self.bindings.len() - self.input_binding_count()
1074 }
1075
1076 pub fn binding(&self, slot: u32) -> Result<ExecutionBindingDesc> {
1084 self
1085 .bindings
1086 .get(slot as usize)
1087 .cloned()
1088 .ok_or_else(|| Error::invalid_argument("execution plan binding slot is out of range"))
1089 }
1090
1091 pub const fn binding_contract_hash(&self) -> u64 {
1095 self.binding_contract_hash
1096 }
1097
1098 pub fn validate_specialization_inputs(&self, inputs: &[crate::Matrix]) -> Result<()> {
1113 if inputs.len() != self.input_binding_count() {
1114 return Err(Error::invalid_argument(
1115 "specialization input count does not match the compiled plan",
1116 ));
1117 }
1118 let mut input_index = 0_usize;
1119 for binding in &self.bindings {
1120 if binding.role() != ExecutionBindingRole::Input {
1121 continue;
1122 }
1123 if binding.kind() != crate::OpValueKind::Matrix {
1124 return Err(Error::failed_precondition(
1125 "matrix specialization validation cannot bind a non-Matrix input",
1126 ));
1127 }
1128 let input = &inputs[input_index];
1129 input_index += 1;
1130 let absolute_offset = {
1131 let mut offset = 0_i64;
1132 let mut semantic = input.semantic().clone();
1133 loop {
1134 offset = offset
1135 .checked_add(semantic.view_byte_offset())
1136 .ok_or_else(|| Error::internal("matrix view byte offset overflows i64"))?;
1137 match semantic.view_source() {
1138 Some(source) => semantic = source.clone(),
1139 None => break,
1140 }
1141 }
1142 offset
1143 };
1144 if input.shape() != binding.shape()
1145 || input.dtype() != binding.dtype()
1146 || absolute_offset < 0
1147 || absolute_offset as u64 != binding.byte_offset()
1148 {
1149 return Err(Error::failed_precondition(
1150 "specialization input shape, dtype or offset requires another plan",
1151 ));
1152 }
1153 if super::graph::semantic::dense_strides(input.shape())? != binding.strides() {
1154 return Err(Error::failed_precondition(
1155 "specialization input strides require another plan",
1156 ));
1157 }
1158 }
1159 Ok(())
1160 }
1161
1162 pub fn diagnostics(&self) -> ExecutionPlanDiagnostics {
1164 let (planned_alias_group_count, potential_alias_savings) =
1165 alias_analysis(&self.captured_resources);
1166 ExecutionPlanDiagnostics {
1167 graph_id: self.graph_id,
1168 device_capability_identity: self.device_capability_identity,
1169 node_count: self.graph.nodes().len(),
1170 barrier_count: self.graph.barrier_count(),
1171 cross_queue_edge_count: self.graph.cross_queue_edge_count(),
1172 ownership_transfer_count: self.graph.ownership_transfer_count(),
1173 queue_run_count: self.graph.queue_runs().len(),
1174 semantic_operation_count: self.semantic.operations().len(),
1175 semantic_autograd_attachment_count: self.semantic.autograd().len(),
1176 semantic_autograd_expanded_count: self
1177 .semantic
1178 .autograd()
1179 .iter()
1180 .filter(|entry| entry.is_backward_expanded())
1181 .count(),
1182 semantic_backward_operation_count: self
1183 .semantic
1184 .autograd()
1185 .iter()
1186 .map(|entry| entry.backward_op_count())
1187 .sum(),
1188 schema_owned_node_count: self.semantic_lowering.schema_owned_node_count() as usize,
1189 compatibility_node_count: self.semantic_lowering.compatibility_node_count() as usize,
1190 semantic_fused_operation_count: self.semantic_lowering.fused_op_count() as usize,
1191 semantic_fused_node_count: self.semantic_lowering.fused_node_count() as usize,
1192 maximum_semantic_operations_per_node: self.semantic_lowering.maximum_ops_per_node() as usize,
1193 dnn_graph_hash: self.dnn.graph_hash(),
1194 dnn_value_count: self.dnn.value_count(),
1195 dnn_external_value_count: self.dnn.external_value_count(),
1196 dnn_virtual_value_count: self.dnn.virtual_value_count(),
1197 dnn_partition_count: self.dnn.partition_count(),
1198 dnn_recognized_partition_count: self.dnn.recognized_partition_count(),
1199 dnn_portable_partition_count: self.dnn.portable_partition_count(),
1200 dnn_captured_operation_count: self.dnn.captured_operation_count(),
1201 dnn_applied_partition_count: self.dnn.applied_partition_count(),
1202 dnn_inherited_partition_count: self.dnn.inherited_partition_count(),
1203 dnn_fallback_partition_count: self.dnn.fallback_partition_count(),
1204 dnn_unexpected_fallback_count: self.dnn.unexpected_fallback_count(),
1205 input_binding_count: self.input_bindings.len(),
1206 captured_resource_count: self.captured_resources.len(),
1207 physical_resource_count: self.graph.resource_lifetimes().len(),
1208 stable_replay_input_count: self
1209 .captured_resources
1210 .iter()
1211 .filter(|resource| resource.stable_replay_input)
1212 .count(),
1213 stable_transient_count: self
1214 .captured_resources
1215 .iter()
1216 .filter(|resource| resource.stable_transient)
1217 .count(),
1218 semantic_binding_count: self.semantic_bindings.len(),
1219 observed_output_count: self
1220 .captured_resources
1221 .iter()
1222 .filter(|resource| resource.observed_output)
1223 .count(),
1224 alias_candidate_count: self
1225 .captured_resources
1226 .iter()
1227 .filter(|resource| resource.alias_candidate)
1228 .count(),
1229 alias_materialized_count: self
1230 .captured_resources
1231 .iter()
1232 .filter(|resource| resource.alias_materialized)
1233 .count(),
1234 planned_alias_group_count,
1235 potential_alias_savings,
1236 materialized_alias_savings: self.materialized_alias_savings,
1237 descriptor_write_count: self.descriptor_write_count,
1238 peak_memory_bytes: {
1239 let mut lifetimes = self.graph.resource_lifetimes();
1240 lifetimes.sort_by_key(|lifetime| lifetime.first_access);
1241 let mut active: Vec<(usize, u32, usize)> = Vec::new();
1242 let mut peak = 0_usize;
1243 for lifetime in lifetimes {
1244 active.retain(|(last, _, _)| *last >= lifetime.first_access);
1245 let index = lifetime.buffer.descriptor_index();
1246 if !active.iter().any(|(_, live, _)| *live == index) {
1247 active.push((lifetime.last_access, index, lifetime.buffer.byte_len()));
1248 }
1249 peak = peak.max(active.iter().map(|(_, _, bytes)| *bytes).sum::<usize>());
1250 }
1251 peak
1252 },
1253 push_byte_count: self
1254 .graph
1255 .compute_nodes()
1256 .map(|node| node.push_constants.len() * 4)
1257 .sum(),
1258 command_recording_count: self.counters.command_recordings.get(),
1259 command_cache_hit_count: self.counters.command_cache_hits.get(),
1260 submission_count: self.counters.submissions.get(),
1261 input_rebinding_count: self.counters.input_rebindings.get(),
1262 input_upload_count: self.counters.input_uploads.get(),
1263 fallback_count: self.counters.fallbacks.get(),
1264 }
1265 }
1266
1267 pub(crate) fn dnn_fallback_reasons(&self) -> impl Iterator<Item = &str> {
1268 self.dnn.fallback_reasons()
1269 }
1270
1271 pub fn is_complete(&self) -> Result<bool> {
1279 let event = self.last_submission.borrow().clone();
1280 event.map_or(Ok(true), |event| event.is_complete())
1281 }
1282
1283 pub fn wait(&self) -> Result<()> {
1292 let event = self.last_submission.borrow().clone();
1293 if let Some(event) = event {
1294 event.wait()?;
1295 }
1296 Ok(())
1297 }
1298
1299 pub fn reset(self) -> Result<()> {
1310 self.wait()
1311 }
1312
1313 pub fn debug_report_json(&self, name: &str) -> String {
1318 let diagnostics = self.diagnostics();
1319 let lifetimes = self.graph.resource_lifetimes();
1320 let compiled = self
1321 .cached_commands
1322 .borrow()
1323 .iter()
1324 .any(|(cached_key, _)| *cached_key == self.binding_key());
1325 let last_event = self.last_submission.borrow().clone();
1326 let mut output = String::new();
1327 output.push_str("{\n \"schema\": \"oa.execution_graph.v3\",\n \"name\": ");
1328 crate::core::push_json_string(&mut output, name);
1329 crate::core::push_format(
1330 &mut output,
1331 format_args!(
1332 ",\n \"compiled\": {},\n \"completion\": {{\"submitted\": {}, \"timeline_value\": {}}},\n",
1333 compiled,
1334 last_event.is_some(),
1335 last_event.as_ref().map_or(0, Event::epoch),
1336 ),
1337 );
1338 let mut war_barriers = 0;
1339 let mut indirect_barriers = 0;
1340 for barrier in (0..self.graph.nodes().len()).flat_map(|node| self.graph.barriers_before(node)) {
1341 war_barriers += usize::from(!barrier.source.writes() && barrier.destination.writes());
1342 indirect_barriers += usize::from(barrier.destination.uses_indirect_commands());
1343 }
1344 let dispatches = self.graph.compute_nodes().count();
1345 let copies = self
1346 .graph
1347 .nodes()
1348 .iter()
1349 .filter(|node| matches!(node, GraphNode::BufferCopy(_)))
1350 .count();
1351 let video_commands = diagnostics.node_count() - dispatches - copies;
1352 let buffer_bytes = lifetimes.iter().fold(0_usize, |total, lifetime| {
1353 total.saturating_add(lifetime.buffer.byte_len())
1354 });
1355 crate::core::push_format(
1356 &mut output,
1357 format_args!(
1358 " \"stats\": {{\"dispatches\": {dispatches}, \"barriers\": {}, \"war_barriers\": {}, \"indirect_barriers\": {}, \"alias_barriers\": 0, \"host_barriers\": 0, \"descriptor_sets\": 0, \"kernel_selections\": {dispatches}, \"kernel_fallbacks\": 0, \"precision_fallbacks\": 0, \"layout_fallbacks\": 0, \"naive_fallbacks\": 0, \"buffer_bytes\": {}, \"potential_alias_savings\": {}, \"materialized_alias_savings\": {}",
1359 diagnostics.barrier_count(),
1360 war_barriers,
1361 indirect_barriers,
1362 buffer_bytes,
1363 diagnostics.potential_alias_savings(),
1364 diagnostics.materialized_alias_savings(),
1365 ),
1366 );
1367 if copies != 0 {
1368 crate::core::push_format(&mut output, format_args!(r#", "copies": {copies}"#));
1369 }
1370 if video_commands != 0 {
1371 let image_transfers = self.graph.image_transfer_count();
1372 crate::core::push_format(
1373 &mut output,
1374 format_args!(
1375 r#", "video_commands": {video_commands}, "image_transfers": {image_transfers}"#
1376 ),
1377 );
1378 }
1379 output.push_str("},\n \"resources\": [");
1380 for (resource, lifetime) in lifetimes.iter().enumerate() {
1381 output.push_str(if resource == 0 { "\n" } else { ",\n" });
1382 crate::core::push_format(
1383 &mut output,
1384 format_args!(
1385 " {{\"id\": {resource}, \"hazard_domain\": {resource}, \"bytes\": {}, \"first_node\": {}, \"last_node\": {}}}",
1386 lifetime.buffer.byte_len(),
1387 lifetime.first_access,
1388 lifetime.last_access,
1389 ),
1390 );
1391 }
1392 if !lifetimes.is_empty() {
1393 output.push('\n');
1394 }
1395 output.push_str(" ],\n \"alias_groups\": [],\n \"barriers\": [");
1398 let mut barrier_index = 0_usize;
1399 for destination_node in 0..self.graph.nodes().len() {
1400 let barriers = self.graph.barriers_before(destination_node);
1401 for barrier in barriers {
1402 output.push_str(if barrier_index == 0 { "\n" } else { ",\n" });
1403 barrier_index = barrier_index.saturating_add(1);
1404 let resource = graph_resource_id(&lifetimes, &barrier.buffer)
1405 .expect("planned barrier resource must have a lifetime");
1406 let [first_source, last_source] = barrier.source_nodes;
1407 let source_stage = barrier.source.vk_stages().as_raw();
1408 let destination_stage = barrier.destination.vk_stages().as_raw();
1409 let source_access = barrier.source.vk_access().as_raw();
1410 let destination_access = barrier.destination.vk_access().as_raw();
1411 crate::core::push_format(
1412 &mut output,
1413 format_args!(
1414 " {{\"reason\": \"{}\", \"scope\": \"buffer\", \"source_nodes\": [{first_source}, {last_source}], \"destination_node\": {destination_node}, \"source_resource\": {resource}, \"destination_resource\": {resource}, \"hazard_domain\": {resource}, \"range\": {{\"offset\": 0, \"bytes\": {}}}, \"source_queue\": \"{}\", \"destination_queue\": \"{}\", \"source_family\": {}, \"destination_family\": {}, \"cross_queue\": {}, \"ownership_transfer\": {}, \"source_stage_mask\": \"0x{source_stage:016x}\", \"source_stages\": [",
1415 hazard_reason(barrier.source, barrier.destination),
1416 barrier.buffer.byte_len(),
1417 barrier.source_queue.name(),
1418 barrier.destination_queue.name(),
1419 barrier.source_family,
1420 barrier.destination_family,
1421 barrier.is_cross_queue(),
1422 barrier.is_ownership_transfer(),
1423 ),
1424 );
1425 push_stage_names(&mut output, barrier.source);
1426 crate::core::push_format(
1427 &mut output,
1428 format_args!(
1429 "], \"source_access_mask\": \"0x{source_access:016x}\", \"source_accesses\": ["
1430 ),
1431 );
1432 push_access_names(&mut output, barrier.source);
1433 crate::core::push_format(
1434 &mut output,
1435 format_args!(
1436 "], \"destination_stage_mask\": \"0x{destination_stage:016x}\", \"destination_stages\": ["
1437 ),
1438 );
1439 push_stage_names(&mut output, barrier.destination);
1440 crate::core::push_format(
1441 &mut output,
1442 format_args!(
1443 "], \"destination_access_mask\": \"0x{destination_access:016x}\", \"destination_accesses\": ["
1444 ),
1445 );
1446 push_access_names(&mut output, barrier.destination);
1447 output.push_str("]}");
1448 }
1449 }
1450 if barrier_index != 0 {
1451 output.push('\n');
1452 }
1453 output.push_str(" ],\n \"nodes\": [");
1454 for (index, graph_node) in self.graph.nodes().iter().enumerate() {
1455 let (operation, semantic_ops, contract) = graph_node.semantic();
1456 output.push_str(if index == 0 { "\n" } else { ",\n" });
1457 crate::core::push_format(
1458 &mut output,
1459 format_args!(" {{\"index\": {index}, \"operation\": "),
1460 );
1461 crate::core::push_json_string(&mut output, operation);
1462 output.push_str(", \"semantic_operations\": [");
1463 for (owner_index, owner) in semantic_ops.iter().enumerate() {
1464 if owner_index != 0 {
1465 output.push_str(", ");
1466 }
1467 crate::core::push_format(&mut output, format_args!("{}", owner.index()));
1468 }
1469 match graph_node {
1470 GraphNode::Compute(node) => {
1471 let implementation_id = node.kernel.artifact().content_id();
1472 crate::core::push_format(
1473 &mut output,
1474 format_args!(
1475 "], \"implementation_id\": \"0x{implementation_id:016x}\", \"operation_contract_hash\": "
1476 ),
1477 );
1478 push_optional_hex(&mut output, contract);
1479 crate::core::push_format(
1480 &mut output,
1481 format_args!(
1482 ", \"problem_contract_hash\": null, \"kernel_content_hash\": \"0x{implementation_id:016x}\", \"kernel_selection\": \"direct\", \"kernel\": "
1483 ),
1484 );
1485 crate::core::push_json_string(&mut output, node.kernel.report_name());
1486 output.push_str(", \"dtype_class\": null, \"dtype\": ");
1487 crate::core::push_json_string(&mut output, node.kernel.dtype_report_token());
1488 output.push_str(", \"physical_write\": ");
1489 match node.kernel.artifact().physical_write {
1490 None => output.push_str("null"),
1491 Some(contract) => {
1492 output.push_str("{\"writes\": [");
1493 for (write_index, write) in contract.writes.iter().enumerate() {
1494 if write_index != 0 {
1495 output.push_str(", ");
1496 }
1497 crate::core::push_format(
1498 &mut output,
1499 format_args!(
1500 "{{\"binding\": {}, \"domain\": \"{}\", \"partition\": \"{}\", \"extent\": \"{}\", \"collision\": \"{}\", \"tail\": \"{}\"}}",
1501 write.binding,
1502 write.domain.token(),
1503 write.partition.token(),
1504 write.extent.token(),
1505 write.collision.token(),
1506 write.tail.token(),
1507 ),
1508 );
1509 }
1510 output.push_str("], \"uniform_store\": ");
1511 match contract.uniform_store {
1512 None => output.push_str("null"),
1513 Some(proof) => crate::core::push_format(
1514 &mut output,
1515 format_args!(
1516 "{{\"domain\": \"{}\", \"partition\": \"{}\", \"extent\": \"{}\", \"collision\": \"{}\", \"tail\": \"{}\"}}",
1517 proof.domain.token(),
1518 proof.partition.token(),
1519 proof.extent.token(),
1520 proof.collision.token(),
1521 proof.tail.token(),
1522 ),
1523 ),
1524 }
1525 crate::core::push_format(
1526 &mut output,
1527 format_args!(", \"workspace\": \"{}\"}}", contract.workspace.token()),
1528 );
1529 }
1530 }
1531 crate::core::push_format(
1532 &mut output,
1533 format_args!(
1534 ", \"groups\": [{}, {}, {}], \"queue\": \"{}\", \"family\": {}, \"indirect\": {}",
1535 node.workgroups[0],
1536 node.workgroups[1],
1537 node.workgroups[2],
1538 graph_node.queue().name(),
1539 self.graph.node_families()[index],
1540 node.indirect.is_some()
1541 ),
1542 );
1543 }
1544 GraphNode::BufferCopy(copy) => {
1545 output.push_str(
1546 r#"], "kind": "buffer_copy", "implementation_id": "0x4255465f434f5059", "operation_contract_hash": "#,
1547 );
1548 push_optional_hex(&mut output, contract);
1549 crate::core::push_format(
1550 &mut output,
1551 format_args!(
1552 r#", "problem_contract_hash": null, "kernel_content_hash": "0x0000000000000000", "kernel_selection": "native", "kernel": "vk.copy_buffer", "dtype_class": null, "dtype": "float32", "physical_write": null, "groups": [0, 0, 0], "queue": "{}", "family": {}, "indirect": false, "copy_bytes": {}"#,
1553 graph_node.queue().name(),
1554 self.graph.node_families()[index],
1555 copy.bytes,
1556 ),
1557 );
1558 }
1559 GraphNode::VideoDecode(video) => {
1560 crate::core::push_format(
1561 &mut output,
1562 format_args!(
1563 r#"], "kind": "video_decode", "implementation_id": "0x5649444445434f44", "operation_contract_hash": null, "problem_contract_hash": null, "kernel_content_hash": "0x0000000000000000", "kernel_selection": "native", "kernel": "{operation}", "dtype_class": null, "dtype": "uint8", "physical_write": null, "groups": [0, 0, 0], "queue": "{}", "family": {}, "indirect": false, "decode_picture": ["#,
1564 graph_node.queue().name(),
1565 self.graph.node_families()[index],
1566 ),
1567 );
1568 for (index, word) in video.descriptor_words().into_iter().enumerate() {
1569 if index != 0 {
1570 output.push_str(", ");
1571 }
1572 crate::core::push_format(&mut output, format_args!("{word}"));
1573 }
1574 output.push(']');
1575 }
1576
1577 GraphNode::VideoEncode(video) => {
1578 crate::core::push_format(
1579 &mut output,
1580 format_args!(
1581 r#"], "kind": "video_encode", "implementation_id": "0x564944454e434f44", "operation_contract_hash": null, "problem_contract_hash": null, "kernel_content_hash": "0x0000000000000000", "kernel_selection": "native", "kernel": "{operation}", "dtype_class": null, "dtype": "uint8", "physical_write": null, "groups": [0, 0, 0], "queue": "{}", "family": {}, "indirect": false, "encode_picture": ["#,
1582 graph_node.queue().name(),
1583 self.graph.node_families()[index],
1584 ),
1585 );
1586 for (index, word) in video.descriptor_words().into_iter().enumerate() {
1587 if index != 0 {
1588 output.push_str(", ");
1589 }
1590 crate::core::push_format(&mut output, format_args!("{word}"));
1591 }
1592 output.push(']');
1593 }
1594 GraphNode::VideoEncodeInput(video) => {
1595 crate::core::push_format(
1596 &mut output,
1597 format_args!(
1598 r#"], "kind": "video_encode_input", "implementation_id": "0x564944454e43494e", "operation_contract_hash": null, "problem_contract_hash": null, "kernel_content_hash": "0x0000000000000000", "kernel_selection": "native", "kernel": "{}", "dtype_class": null, "dtype": "uint8", "physical_write": null, "groups": [0, 0, 0], "queue": "{}", "family": {}, "indirect": false, "image_geometry": ["#,
1599 video.copy.name(),
1600 graph_node.queue().name(),
1601 self.graph.node_families()[index],
1602 ),
1603 );
1604 for (index, word) in video.copy.descriptor_words().enumerate() {
1605 if index != 0 {
1606 output.push_str(", ");
1607 }
1608 crate::core::push_format(&mut output, format_args!("{word}"));
1609 }
1610 output.push(']');
1611 }
1612 GraphNode::VideoPlanes(video) => {
1613 crate::core::push_format(
1614 &mut output,
1615 format_args!(
1616 r#"], "kind": "video_plane_command", "implementation_id": "0x564944504c414e45", "operation_contract_hash": null, "problem_contract_hash": null, "kernel_content_hash": "0x0000000000000000", "kernel_selection": "native", "kernel": "{}", "dtype_class": null, "dtype": "uint8", "physical_write": null, "groups": [0, 0, 0], "queue": "{}", "family": {}, "indirect": false, "image_geometry": ["#,
1617 video.phase.name(),
1618 graph_node.queue().name(),
1619 self.graph.node_families()[index],
1620 ),
1621 );
1622 for (index, word) in video.copy.descriptor_words().enumerate() {
1623 if index != 0 {
1624 output.push_str(", ");
1625 }
1626 crate::core::push_format(&mut output, format_args!("{word}"));
1627 }
1628 output.push(']');
1629 }
1630 }
1631 output.push_str(r#", "effects": ["#);
1632 for (effect_index, effect) in graph_node.buffers().iter().enumerate() {
1633 if effect_index != 0 {
1634 output.push_str(", ");
1635 }
1636 let resource = graph_resource_id(&lifetimes, &effect.buffer)
1637 .expect("node buffer must have a resource lifetime");
1638 crate::core::push_format(
1639 &mut output,
1640 format_args!(
1641 "{{\"resource\": {resource}, \"access\": \"{}\"}}",
1642 buffer_access_token(effect.access)
1643 ),
1644 );
1645 }
1646 output.push_str("]}");
1647 }
1648 if !self.graph.nodes().is_empty() {
1649 output.push('\n');
1650 }
1651 output.push_str(" ]\n}\n");
1652 output
1653 }
1654
1655 pub(super) fn belongs_to(&self, engine: &EngineHandle) -> bool {
1656 self.engine.same_as(engine)
1657 }
1658
1659 pub(crate) fn validate_training_replay_safety(&self) -> Result<()> {
1660 self.graph.validate_training_replay_safety()
1661 }
1662
1663 fn binding_key(&self) -> Vec<u32> {
1664 self
1665 .input_bindings
1666 .iter()
1667 .map(|binding| binding.current.descriptor_index())
1668 .collect()
1669 }
1670
1671 pub(super) fn submission_ranges(
1679 &self,
1680 device: &Arc<Device>,
1681 ) -> Result<Vec<std::ops::Range<usize>>> {
1682 let budget = device.submission_budget_ns();
1683 let mut ranges = Vec::new();
1684 for run in self.graph.queue_runs() {
1685 for range in
1686 self
1687 .graph
1688 .budget_ranges_within(run.nodes, budget)
1689 .map_err(|(index, estimate)| {
1690 Error::resource_exhausted(format!(
1691 "node {} ({}) estimated {:.1}ms exceeds the {:.1}ms submission budget",
1692 index,
1693 self.graph.nodes()[index].semantic().0,
1694 estimate as f64 / 1e6,
1695 budget as f64 / 1e6,
1696 ))
1697 })? {
1698 if !range.is_empty() {
1699 ranges.push(range);
1700 }
1701 }
1702 }
1703 Ok(ranges)
1704 }
1705
1706 pub(super) fn graph(&self) -> &ExecutableGraph {
1707 &self.graph
1708 }
1709
1710 pub(super) fn reusable_commands(
1714 &self,
1715 device: &Arc<Device>,
1716 ) -> Result<Vec<RecordedCommandBuffer>> {
1717 let key = self.binding_key();
1718 if let Some((_, commands)) = self
1719 .cached_commands
1720 .borrow()
1721 .iter()
1722 .find(|(cached_key, _)| *cached_key == key)
1723 {
1724 increment(&self.counters.command_cache_hits);
1725 return Ok(
1726 commands
1727 .iter()
1728 .map(|command| command.submission())
1729 .collect(),
1730 );
1731 }
1732 let runs = self.graph.queue_runs();
1733 let commands = if runs.len() == 1 {
1734 vec![device.record_reusable_compute_graph(&self.graph)?]
1735 } else {
1736 runs
1737 .into_iter()
1738 .map(|run| device.record_reusable_graph_range(&self.graph, run.nodes))
1739 .collect::<Result<Vec<_>>>()?
1740 };
1741 increment(&self.counters.command_recordings);
1742 let submissions = commands
1743 .iter()
1744 .map(|command| command.submission())
1745 .collect();
1746 let mut cache = self.cached_commands.borrow_mut();
1747 if cache.len() == MAX_CACHED_BINDING_COMMANDS {
1748 cache.remove(0);
1749 }
1750 cache.push((key, commands));
1751 Ok(submissions)
1752 }
1753
1754 pub(super) fn count_command_recording(&self) {
1755 increment(&self.counters.command_recordings);
1756 }
1757
1758 pub(super) fn precompile(&self, device: &Arc<Device>) -> Result<()> {
1759 if self.graph.has_video() {
1760 let mut commands = super::device::logical::command::RecordedBatch::new(device);
1761 for range in self.submission_ranges(device)? {
1762 commands.push(device.record_fresh_graph_range(&self.graph, range, false)?);
1763 }
1764 } else {
1765 let _ = self.reusable_commands(device)?;
1766 }
1767 Ok(())
1768 }
1769
1770 pub(super) fn mark_submitted(&self, event: &Event) {
1771 for output in &self.outputs {
1772 output.mark_submitted(event.clone());
1773 }
1774 for binding in &self.input_bindings {
1775 if let Some(slot) = binding
1776 .staging
1777 .iter()
1778 .find(|slot| slot.buffer.same_as(&binding.current))
1779 {
1780 slot.consumer.replace(Some(event.clone()));
1781 }
1782 binding.current.record_bound_consumer(event);
1783 }
1784 self.last_submission.replace(Some(event.clone()));
1785 increment(&self.counters.submissions);
1786 }
1787
1788 pub(super) fn mark_failed(&self) {
1789 for output in &self.outputs {
1790 output.mark_failed();
1791 }
1792 }
1793}
1794
1795fn increment(counter: &Cell<u64>) {
1796 counter.set(counter.get().saturating_add(1));
1797}
1798
1799fn graph_resource_id(
1800 lifetimes: &[super::graph::executable::ResourceLifetime],
1801 buffer: &Buffer,
1802) -> Option<usize> {
1803 lifetimes
1804 .iter()
1805 .position(|lifetime| lifetime.buffer.same_as(buffer))
1806}
1807
1808const fn hazard_reason(source: AccessState, destination: AccessState) -> &'static str {
1809 match (source.writes(), destination.writes()) {
1810 (true, true) => "write_after_write",
1811 (true, false) => "read_after_write",
1812 (false, true) => "write_after_read",
1813 (false, false) => "queue_ownership",
1814 }
1815}
1816
1817fn push_stage_names(output: &mut String, access: AccessState) {
1818 let mask = access.vk_stages();
1819 push_names(
1820 output,
1821 [
1822 (
1823 mask.contains(vk::PipelineStageFlagBits2::COMPUTE_SHADER_BIT),
1824 "compute_shader",
1825 ),
1826 (
1827 mask.contains(vk::PipelineStageFlagBits2::DRAW_INDIRECT_BIT),
1828 "draw_indirect",
1829 ),
1830 (mask.contains(vk::PipelineStageFlagBits2::COPY_BIT), "copy"),
1831 ],
1832 );
1833}
1834
1835fn push_access_names(output: &mut String, access: AccessState) {
1836 let mask = access.vk_access();
1837 push_names(
1838 output,
1839 [
1840 (
1841 mask.contains(vk::AccessFlagBits2::SHADER_STORAGE_READ_BIT),
1842 "shader_storage_read",
1843 ),
1844 (
1845 mask.contains(vk::AccessFlagBits2::SHADER_STORAGE_WRITE_BIT),
1846 "shader_storage_write",
1847 ),
1848 (
1849 mask.contains(vk::AccessFlagBits2::INDIRECT_COMMAND_READ_BIT),
1850 "indirect_command_read",
1851 ),
1852 (
1853 mask.contains(vk::AccessFlagBits2::TRANSFER_READ_BIT),
1854 "transfer_read",
1855 ),
1856 (
1857 mask.contains(vk::AccessFlagBits2::TRANSFER_WRITE_BIT),
1858 "transfer_write",
1859 ),
1860 ],
1861 );
1862}
1863
1864fn push_names(output: &mut String, names: impl IntoIterator<Item = (bool, &'static str)>) {
1865 let mut separator = "";
1866 for (_, name) in names.into_iter().filter(|(present, _)| *present) {
1867 output.push_str(separator);
1868 crate::core::push_json_string(output, name);
1869 separator = ", ";
1870 }
1871}
1872
1873const fn buffer_access_token(access: super::BufferAccess) -> &'static str {
1874 match access {
1875 super::BufferAccess::Read => "read",
1876 super::BufferAccess::Write => "write",
1877 super::BufferAccess::ReadWrite => "read_write",
1878 }
1879}
1880
1881fn push_optional_hex(output: &mut String, value: u64) {
1882 if value == 0 {
1883 output.push_str("null");
1884 } else {
1885 crate::core::push_format(output, format_args!("\"0x{value:016x}\""));
1886 }
1887}
1888
1889fn find_resource(
1890 lifetimes: &[super::graph::executable::ResourceLifetime],
1891 storage: &Storage,
1892) -> Result<usize> {
1893 let buffer = storage.buffer().ok_or_else(|| {
1894 Error::failed_precondition("captured semantic resource has no allocated storage")
1895 })?;
1896 lifetimes
1897 .iter()
1898 .position(|lifetime| lifetime.buffer.same_as(buffer))
1899 .ok_or_else(|| Error::failed_precondition("captured resource does not appear in the graph"))
1900}
1901
1902fn find_resource_storage<'a>(
1903 buffer: &Buffer,
1904 stable_resources: &'a [StableResourceSnapshot],
1905 semantic_storage: &'a [SemanticStorageSnapshot],
1906 observed_outputs: &'a [Storage],
1907 outputs: &'a [Storage],
1908) -> Option<&'a Storage> {
1909 stable_resources
1914 .iter()
1915 .map(|candidate| &candidate.storage)
1916 .chain(semantic_storage.iter().map(|candidate| &candidate.storage))
1917 .chain(observed_outputs.iter())
1918 .chain(outputs.iter())
1919 .find(|storage| {
1920 storage
1921 .buffer()
1922 .is_some_and(|candidate| candidate.same_as(buffer))
1923 })
1924}
1925
1926struct AliasGroup {
1927 resources: Vec<usize>,
1928 required_size: usize,
1929}
1930
1931struct AliasMaterialization {
1932 graph: ExecutableGraph,
1933 outputs: Vec<Storage>,
1934 captured_resources: Vec<CapturedResourceDesc>,
1935 retired: Vec<Buffer>,
1936 savings: usize,
1937}
1938
1939fn materialize_aliases(
1940 engine: &EngineHandle,
1941 graph: &ExecutableGraph,
1942 outputs: &[Storage],
1943 resource_lifetimes: &[super::graph::executable::ResourceLifetime],
1944 captured_resources: &[CapturedResourceDesc],
1945) -> Result<AliasMaterialization> {
1946 let mut graph = graph.clone();
1947 let mut outputs = outputs.to_vec();
1948 let mut captured_resources = captured_resources.to_vec();
1949 let groups = alias_groups(&captured_resources);
1950 let mut replacements = Vec::new();
1951 let mut retired = Vec::new();
1952 let mut savings = 0_usize;
1953 for group in groups.iter().filter(|group| group.resources.len() > 1) {
1954 let arena = engine.create_alias_arena(group.required_size)?;
1955 let original_bytes = group.resources.iter().try_fold(0_usize, |sum, resource| {
1956 sum
1957 .checked_add(captured_resources[*resource].byte_len)
1958 .ok_or_else(|| Error::resource_exhausted("materialized alias byte accounting overflowed"))
1959 })?;
1960 savings = savings
1961 .checked_add(original_bytes.saturating_sub(group.required_size))
1962 .ok_or_else(|| Error::resource_exhausted("alias savings accounting overflowed"))?;
1963 for resource in &group.resources {
1964 let source = resource_lifetimes[*resource].buffer.clone();
1965 retired.push(source.clone());
1966 replacements.push((source, arena.clone()));
1967 captured_resources[*resource].alias_materialized = true;
1968 }
1969 }
1970 if !replacements.is_empty() {
1971 graph.materialize_alias_replacements(&replacements)?;
1972 outputs.retain(|storage| {
1973 storage
1974 .buffer()
1975 .is_none_or(|buffer| !retired.iter().any(|candidate| candidate.same_as(buffer)))
1976 });
1977 }
1978 Ok(AliasMaterialization {
1979 graph,
1980 outputs,
1981 captured_resources,
1982 retired,
1983 savings,
1984 })
1985}
1986
1987fn alias_groups(resources: &[CapturedResourceDesc]) -> Vec<AliasGroup> {
1988 let mut eligible = resources
1989 .iter()
1990 .enumerate()
1991 .filter_map(|(index, resource)| resource.alias_candidate.then_some(index))
1992 .collect::<Vec<_>>();
1993 eligible.sort_by_key(|index| (resources[*index].first_access, resources[*index].resource));
1994 let mut groups = Vec::<AliasGroup>::new();
1995 for resource in eligible {
1996 let desc = resources[resource];
1997 if let Some(group) = groups.iter_mut().find(|group| {
1998 group.resources.iter().all(|member| {
1999 let member = resources[*member];
2000 desc.first_access > member.last_access || desc.last_access < member.first_access
2001 })
2002 }) {
2003 group.required_size = group.required_size.max(desc.byte_len);
2004 group.resources.push(resource);
2005 } else {
2006 groups.push(AliasGroup {
2007 resources: vec![resource],
2008 required_size: desc.byte_len,
2009 });
2010 }
2011 }
2012 groups
2013}
2014
2015fn alias_analysis(resources: &[CapturedResourceDesc]) -> (usize, usize) {
2016 let groups = alias_groups(resources);
2017 let mut count = 0_usize;
2018 let mut savings = 0_usize;
2019 for group in groups.iter().filter(|group| group.resources.len() > 1) {
2020 count = count.saturating_add(1);
2021 let bytes = group.resources.iter().fold(0_usize, |total, resource| {
2022 total.saturating_add(resources[*resource].byte_len)
2023 });
2024 savings = savings.saturating_add(bytes.saturating_sub(group.required_size));
2025 }
2026 (count, savings)
2027}
2028
2029impl fmt::Debug for ExecutionPlan {
2030 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2031 formatter
2032 .debug_struct("ExecutionPlan")
2033 .field("graph_id", &format_args!("{:016x}", self.graph_id))
2034 .field("node_count", &self.graph.nodes().len())
2035 .finish_non_exhaustive()
2036 }
2037}
2038
2039#[cfg(test)]
2040#[path = "../../../../test/rs/runtime/plan_binding_unit.rs"]
2041mod tests;