vyre-driver 0.6.1

Driver layer: registry, runtime, pipeline, routing, diagnostics. Substrate-agnostic backend machinery. Part of the vyre GPU compiler.
Documentation
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
//! Backend-neutral frontier memory planning for dependency-aware megakernels.
//!
//! Backends can choose different execution topologies, but the memory envelope
//! of dependency-layered frontier waves is a backend-neutral contract. This
//! module plans that envelope once, including dependency barriers, fused-group
//! splitting under an explicit byte budget, peak byte accounting, and readback
//! pressure amortization.

use crate::accounting::{
    checked_add_u64_count as checked_add, checked_mul_u64_count as checked_mul,
};
use crate::megakernel_barrier::{
    plan_megakernel_barriers_with_scratch, MegakernelBarrierGroup, MegakernelBarrierPlan,
    MegakernelBarrierPlanError, MegakernelBarrierScratch, MegakernelWaveDependency,
};
use crate::reservation_policy::{
    reserve_typed_vec_to_capacity as reserve_vec_to_capacity, ReservationPolicy,
};

const MEGAKERNEL_FRONTIER_RESERVATION: ReservationPolicy = ReservationPolicy::new(
    "megakernel frontier memory planner",
    "shard the frontier wave group or split the fused phase",
);

/// Frontier-typed megakernel wave memory envelope.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MegakernelFrontierWave {
    /// Resident frontier bytes touched by this wave.
    pub frontier_bytes: u64,
    /// Temporary scratch bytes required by this wave before topology scaling.
    pub scratch_bytes: u64,
    /// Output bytes produced by this wave.
    pub output_bytes: u64,
}

/// Dependency-aware megakernel frontier memory plan.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MegakernelFrontierMemoryPlan {
    /// Minimum global-barrier grouping after memory-budget splitting.
    pub barriers: MegakernelBarrierPlan,
    /// Peak frontier bytes across any fused barrier-free group.
    pub peak_frontier_bytes: u64,
    /// Peak scratch bytes across any fused barrier-free group.
    pub peak_scratch_bytes: u64,
    /// Peak output bytes across any fused barrier-free group.
    pub peak_output_bytes: u64,
    /// Readback pressure after combining runtime telemetry with static
    /// fused-wave output volume.
    pub amortized_readback_bytes: u64,
    /// Widest barrier-free group in wave count.
    pub max_group_width: usize,
}

/// Frontier memory planning failure.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum MegakernelFrontierMemoryPlanError {
    /// Dependency graph cannot be barrier-planned.
    Barrier(MegakernelBarrierPlanError),
    /// Peak wave bytes overflowed while grouping a barrier-free phase.
    ByteCountOverflow {
        /// Field being accumulated.
        field: &'static str,
    },
    /// Static graph or fused frontier bytes exceed the caller-approved budget.
    GroupOverBudget {
        /// Required bytes before topology selection.
        required_bytes: u64,
        /// Caller-provided budget.
        budget_bytes: u64,
        /// Budget region being checked.
        field: &'static str,
    },
    /// Frontier planning result storage could not be reserved.
    StorageReserveFailed {
        /// Field being reserved.
        field: &'static str,
        /// Number of elements requested.
        requested: usize,
        /// Allocator error text.
        message: String,
    },
}

impl crate::accounting::ArithmeticOverflow for MegakernelFrontierMemoryPlanError {
    fn arithmetic_overflow(field: &'static str) -> Self {
        Self::ByteCountOverflow { field }
    }
}

impl std::fmt::Display for MegakernelFrontierMemoryPlanError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Barrier(error) => error.fmt(f),
            Self::ByteCountOverflow { field } => write!(
                f,
                "megakernel frontier memory planner overflowed while accumulating {field}. Fix: shard the frontier wave group or split the fused phase."
            ),
            Self::GroupOverBudget {
                required_bytes,
                budget_bytes,
                field,
            } => write!(
                f,
                "megakernel frontier memory planner requires {required_bytes} bytes for {field} but budget allows {budget_bytes}. Fix: shard the graph/frontier waves or raise the explicit megakernel budget."
            ),
            Self::StorageReserveFailed {
                field,
                requested,
                message,
            } => write!(
                f,
                "megakernel frontier memory planner could not reserve {requested} {field} entries: {message}. Fix: shard the frontier waves before planning."
            ),
        }
    }
}

impl std::error::Error for MegakernelFrontierMemoryPlanError {}

impl From<MegakernelBarrierPlanError> for MegakernelFrontierMemoryPlanError {
    fn from(error: MegakernelBarrierPlanError) -> Self {
        Self::Barrier(error)
    }
}

/// Plan dependency-aware frontier memory using caller-owned barrier scratch.
///
/// # Errors
///
/// Returns [`MegakernelFrontierMemoryPlanError`] when dependencies are invalid,
/// counters overflow, or the requested graph/frontier envelope cannot fit the
/// explicit budget.
pub fn plan_megakernel_frontier_memory_with_scratch(
    waves: &[MegakernelFrontierWave],
    dependencies: &[MegakernelWaveDependency],
    resident_graph_bytes: u64,
    budget_bytes: u64,
    readback_bytes: u64,
    scratch: &mut MegakernelBarrierScratch,
) -> Result<MegakernelFrontierMemoryPlan, MegakernelFrontierMemoryPlanError> {
    let barriers = plan_megakernel_barriers_with_scratch(waves.len(), dependencies, scratch)?;
    let group_budget_bytes = budget_bytes.checked_sub(resident_graph_bytes).ok_or(
        MegakernelFrontierMemoryPlanError::GroupOverBudget {
            required_bytes: resident_graph_bytes,
            budget_bytes,
            field: "resident graph bytes",
        },
    )?;
    let barriers = split_barrier_groups_to_memory_budget(barriers, waves, group_budget_bytes)?;
    let mut peak_frontier_bytes = 0u64;
    let mut peak_scratch_bytes = 0u64;
    let mut peak_output_bytes = 0u64;
    let mut max_group_width = 0usize;
    for group in &barriers.groups {
        let mut group_frontier_bytes = 0u64;
        let mut group_scratch_bytes = 0u64;
        let mut group_output_bytes = 0u64;
        max_group_width = max_group_width.max(group.waves.len());
        for &wave_index in &group.waves {
            let wave = waves[wave_index];
            group_frontier_bytes = checked_add::<MegakernelFrontierMemoryPlanError>(
                group_frontier_bytes,
                wave.frontier_bytes,
                "frontier wave bytes",
            )?;
            group_scratch_bytes = checked_add::<MegakernelFrontierMemoryPlanError>(
                group_scratch_bytes,
                wave.scratch_bytes,
                "scratch wave bytes",
            )?;
            group_output_bytes = checked_add::<MegakernelFrontierMemoryPlanError>(
                group_output_bytes,
                wave.output_bytes,
                "output wave bytes",
            )?;
        }
        peak_frontier_bytes = peak_frontier_bytes.max(group_frontier_bytes);
        peak_scratch_bytes = peak_scratch_bytes.max(group_scratch_bytes);
        peak_output_bytes = peak_output_bytes.max(group_output_bytes);
    }

    Ok(MegakernelFrontierMemoryPlan {
        barriers,
        peak_frontier_bytes,
        peak_scratch_bytes,
        peak_output_bytes,
        amortized_readback_bytes: readback_bytes.max(peak_output_bytes),
        max_group_width,
    })
}

fn split_barrier_groups_to_memory_budget(
    barriers: MegakernelBarrierPlan,
    waves: &[MegakernelFrontierWave],
    group_budget_bytes: u64,
) -> Result<MegakernelBarrierPlan, MegakernelFrontierMemoryPlanError> {
    let mut groups = Vec::new();
    reserve_vec::<MegakernelBarrierGroup>(
        &mut groups,
        barriers.groups.len(),
        "split barrier groups",
    )?;
    for group in barriers.groups {
        split_one_barrier_group_to_memory_budget(group, waves, group_budget_bytes, &mut groups)?;
    }
    Ok(MegakernelBarrierPlan {
        global_barriers: if groups.is_empty() {
            0
        } else {
            groups.len() - 1
        },
        groups,
    })
}

fn split_one_barrier_group_to_memory_budget(
    group: MegakernelBarrierGroup,
    waves: &[MegakernelFrontierWave],
    group_budget_bytes: u64,
    groups: &mut Vec<MegakernelBarrierGroup>,
) -> Result<(), MegakernelFrontierMemoryPlanError> {
    let mut current = Vec::new();
    reserve_vec::<usize>(
        &mut current,
        group.waves.len().min(8),
        "current split barrier group",
    )?;
    let mut current_bytes = 0u64;
    for wave_index in group.waves {
        let wave_bytes = fused_wave_budget_bytes(waves[wave_index])?;
        let combined = checked_add::<MegakernelFrontierMemoryPlanError>(
            current_bytes,
            wave_bytes,
            "barrier group fused wave budget bytes",
        )?;
        if current.is_empty() && wave_bytes > group_budget_bytes {
            return Err(MegakernelFrontierMemoryPlanError::GroupOverBudget {
                required_bytes: wave_bytes,
                budget_bytes: group_budget_bytes,
                field: "single fused frontier wave bytes",
            });
        }
        if !current.is_empty() && combined > group_budget_bytes {
            groups.push(MegakernelBarrierGroup {
                waves: std::mem::take(&mut current),
            });
            current_bytes = 0;
        }
        current.push(wave_index);
        current_bytes = checked_add::<MegakernelFrontierMemoryPlanError>(
            current_bytes,
            wave_bytes,
            "barrier group fused wave budget bytes",
        )?;
    }
    if !current.is_empty() {
        groups.push(MegakernelBarrierGroup { waves: current });
    }
    Ok(())
}

fn fused_wave_budget_bytes(
    wave: MegakernelFrontierWave,
) -> Result<u64, MegakernelFrontierMemoryPlanError> {
    let fused_scratch_bytes = checked_mul::<MegakernelFrontierMemoryPlanError>(
        wave.scratch_bytes,
        4,
        "fused wave scratch bytes",
    )?;
    let bytes = checked_add::<MegakernelFrontierMemoryPlanError>(
        wave.frontier_bytes,
        fused_scratch_bytes,
        "fused wave bytes",
    )?;
    checked_add::<MegakernelFrontierMemoryPlanError>(bytes, wave.output_bytes, "fused wave bytes")
}

fn reserve_vec<T>(
    vec: &mut Vec<T>,
    target_capacity: usize,
    item: &'static str,
) -> Result<(), MegakernelFrontierMemoryPlanError> {
    reserve_vec_to_capacity(
        MEGAKERNEL_FRONTIER_RESERVATION,
        vec,
        target_capacity,
        item,
        storage_reserve_failed,
    )
}

fn storage_reserve_failed(
    field: &'static str,
    requested: usize,
    message: String,
) -> MegakernelFrontierMemoryPlanError {
    MegakernelFrontierMemoryPlanError::StorageReserveFailed {
        field,
        requested,
        message,
    }
}

#[cfg(test)]
mod tests {
    use super::{
        plan_megakernel_frontier_memory_with_scratch, MegakernelFrontierMemoryPlanError,
        MegakernelFrontierWave,
    };
    use crate::megakernel_barrier::{MegakernelBarrierScratch, MegakernelWaveDependency};

    #[test]
    fn frontier_memory_plan_uses_peak_barrier_group_memory() {
        let mut scratch = MegakernelBarrierScratch::default();
        let plan = plan_megakernel_frontier_memory_with_scratch(
            &[
                MegakernelFrontierWave {
                    frontier_bytes: 1_024,
                    scratch_bytes: 512,
                    output_bytes: 256,
                },
                MegakernelFrontierWave {
                    frontier_bytes: 2_048,
                    scratch_bytes: 1_024,
                    output_bytes: 512,
                },
                MegakernelFrontierWave {
                    frontier_bytes: 4_096,
                    scratch_bytes: 2_048,
                    output_bytes: 1_024,
                },
                MegakernelFrontierWave {
                    frontier_bytes: 8_192,
                    scratch_bytes: 4_096,
                    output_bytes: 2_048,
                },
            ],
            &[
                MegakernelWaveDependency {
                    before: 0,
                    after: 1,
                },
                MegakernelWaveDependency {
                    before: 0,
                    after: 2,
                },
                MegakernelWaveDependency {
                    before: 1,
                    after: 3,
                },
                MegakernelWaveDependency {
                    before: 2,
                    after: 3,
                },
            ],
            16_000,
            128 * 1024,
            1 << 20,
            &mut scratch,
        )
        .expect("Fix: frontier-typed megakernel memory plan should fit the budget.");

        assert_eq!(plan.barriers.global_barriers, 2);
        assert_eq!(plan.barriers.groups[1].waves, vec![1, 2]);
        assert_eq!(plan.peak_frontier_bytes, 8_192);
        assert_eq!(plan.peak_scratch_bytes, 4_096);
        assert_eq!(plan.peak_output_bytes, 2_048);
        assert_eq!(plan.amortized_readback_bytes, 1 << 20);
        assert_eq!(plan.max_group_width, 2);
    }

    #[test]
    fn frontier_memory_uses_static_group_output_to_amortize_readback() {
        let mut scratch = MegakernelBarrierScratch::default();
        let plan = plan_megakernel_frontier_memory_with_scratch(
            &[
                MegakernelFrontierWave {
                    frontier_bytes: 1_024,
                    scratch_bytes: 512,
                    output_bytes: 3_072,
                },
                MegakernelFrontierWave {
                    frontier_bytes: 1_024,
                    scratch_bytes: 512,
                    output_bytes: 3_072,
                },
            ],
            &[],
            16_000,
            128 * 1024,
            0,
            &mut scratch,
        )
        .expect("Fix: static output-amortized frontier memory plan should fit the budget.");

        assert_eq!(plan.peak_output_bytes, 6_144);
        assert_eq!(plan.amortized_readback_bytes, 6_144);
    }

    #[test]
    fn frontier_memory_splits_independent_layers_to_fit_fused_budget() {
        let mut scratch = MegakernelBarrierScratch::default();
        let waves = [
            MegakernelFrontierWave {
                frontier_bytes: 10,
                scratch_bytes: 10,
                output_bytes: 10,
            },
            MegakernelFrontierWave {
                frontier_bytes: 10,
                scratch_bytes: 10,
                output_bytes: 10,
            },
            MegakernelFrontierWave {
                frontier_bytes: 10,
                scratch_bytes: 10,
                output_bytes: 10,
            },
        ];
        let plan =
            plan_megakernel_frontier_memory_with_scratch(&waves, &[], 0, 100, 4_096, &mut scratch)
                .expect("Fix: independent frontier waves should split into budget-fit chunks.");

        assert_eq!(plan.barriers.groups.len(), 3);
        assert_eq!(plan.barriers.global_barriers, 2);
        assert_eq!(plan.max_group_width, 1);
        assert_eq!(plan.peak_frontier_bytes, 10);
        assert_eq!(plan.peak_scratch_bytes, 10);
        assert_eq!(plan.peak_output_bytes, 10);
    }

    #[test]
    fn frontier_memory_rejects_graph_and_single_wave_over_budget() {
        let mut scratch = MegakernelBarrierScratch::default();
        let graph_error = plan_megakernel_frontier_memory_with_scratch(
            &[MegakernelFrontierWave {
                frontier_bytes: 1,
                scratch_bytes: 1,
                output_bytes: 1,
            }],
            &[],
            1_600,
            1_000,
            0,
            &mut scratch,
        )
        .expect_err("resident graph bytes above budget must fail before split planning");
        assert_eq!(
            graph_error,
            MegakernelFrontierMemoryPlanError::GroupOverBudget {

                required_bytes: 1_600,
                budget_bytes: 1_000,
                field: "resident graph bytes",
            }
        );

        let wave_error = plan_megakernel_frontier_memory_with_scratch(
            &[MegakernelFrontierWave {
                frontier_bytes: 100,
                scratch_bytes: 100,
                output_bytes: 100,
            }],
            &[],
            0,
            500,
            0,
            &mut scratch,
        )
        .expect_err("single fused wave above group budget must fail before topology planning");
        assert_eq!(
            wave_error,
            MegakernelFrontierMemoryPlanError::GroupOverBudget {
                required_bytes: 600,
                budget_bytes: 500,
                field: "single fused frontier wave bytes",
            }
        );
    }

    #[test]
    fn frontier_memory_fails_loudly_on_wave_byte_overflow() {
        let mut scratch = MegakernelBarrierScratch::default();
        let error = plan_megakernel_frontier_memory_with_scratch(
            &[
                MegakernelFrontierWave {
                    frontier_bytes: u64::MAX,
                    scratch_bytes: 1,
                    output_bytes: 1,
                },
                MegakernelFrontierWave {
                    frontier_bytes: 1,
                    scratch_bytes: 1,
                    output_bytes: 1,
                },
            ],
            &[],
            2,
            u64::MAX,
            0,
            &mut scratch,
        )
        .expect_err("Fix: overflowed frontier wave bytes must fail before launch planning.");

        assert_eq!(
            error,
            MegakernelFrontierMemoryPlanError::ByteCountOverflow {
                field: "fused wave bytes"
            }
        );
    }

    #[test]
    fn generated_frontier_memory_profiles_preserve_peak_and_budget_for_1024_shapes() {
        let mut scratch = MegakernelBarrierScratch::default();
        for width in 1u64..=32 {
            for depth in 1u64..=32 {
                let mut waves = Vec::new();
                let mut dependencies = Vec::new();
                for layer in 0..depth {
                    for slot in 0..width {
                        waves.push(MegakernelFrontierWave {
                            frontier_bytes: width,
                            scratch_bytes: slot + 1,
                            output_bytes: layer + 1,
                        });
                        if layer + 1 < depth {
                            dependencies.push(MegakernelWaveDependency {
                                before: (layer * width + slot) as usize,
                                after: ((layer + 1) * width + slot) as usize,
                            });
                        }
                    }
                }

                let plan = plan_megakernel_frontier_memory_with_scratch(
                    &waves,
                    &dependencies,
                    256,
                    u64::MAX / 2,
                    7,
                    &mut scratch,
                )
                .expect("Fix: generated frontier memory DAG should plan under large budget.");

                assert_eq!(plan.barriers.groups.len(), depth as usize);
                assert_eq!(plan.max_group_width, width as usize);
                assert_eq!(plan.peak_frontier_bytes, width * width);
                assert_eq!(plan.peak_scratch_bytes, width * (width + 1) / 2);
                assert_eq!(plan.peak_output_bytes, width * depth);
                assert_eq!(plan.amortized_readback_bytes, 7.max(width * depth));
            }
        }
    }
}