neura-program 0.4.0

Graph lowering, wave scheduling and device tape encoding
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
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
use crate::access::{self, Access, Reads};
use crate::fuse;
use crate::layout::{Layout, Region, store_of};
use crate::lower;
use crate::lower::Task;
use crate::schedule::{self, Dispatch};
use neura_abi::{
    BoundsFields, BoundsRecord, Element, Geometry, Kind, NO_VALUE, Placement, SegmentRecord,
    StepRecord, Store, TaskFields, TaskRecord, ValueFields, ValueRecord, WORD_BYTES,
};
use neura_graph::{Graph, GraphSnapshot, Residency, Value, ValueInfo};
use neura_profile::{AttentionTile, MatmulTile, Profile};
use std::mem::size_of;

#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Quantum {
    pub offset: u64,
    pub scale: f32,
}

#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Span {
    pub store: Store,
    pub offset: u64,
    pub elements: u32,
    pub element: Element,
    pub scale: f32,
}

struct Block {
    offset: u64,
    bytes: u64,
}

struct Blocks {
    free: Vec<Block>,
    end: u64,
}

impl Blocks {
    fn with_base(base: u64) -> Self {
        Self {
            free: Vec::new(),
            end: base,
        }
    }

    fn bytes(&self) -> u64 {
        self.end
    }

    fn reserve(&mut self, bytes: u64, alignment: u64) -> u64 {
        for index in 0..self.free.len() {
            let block = &self.free[index];
            let offset = block.offset.next_multiple_of(alignment);
            let end = block.offset + block.bytes;
            if offset + bytes > end {
                continue;
            }
            if offset + bytes == end {
                self.free.remove(index);
            } else {
                self.free[index].offset = offset + bytes;
                self.free[index].bytes = end - offset - bytes;
            }
            return offset;
        }
        let offset = self.end.next_multiple_of(alignment);
        self.end = offset + bytes;
        offset
    }

    fn release(&mut self, offset: u64, bytes: u64) {
        self.free.push(Block { offset, bytes });
        self.free.sort_by_key(|block| block.offset);
        let mut merged: Vec<Block> = Vec::with_capacity(self.free.len());
        for block in self.free.drain(..) {
            match merged.last_mut() {
                Some(last) if last.offset + last.bytes >= block.offset => {
                    last.bytes = last.bytes.max(block.offset + block.bytes - last.offset);
                }
                _ => merged.push(block),
            }
        }
        self.free = merged;
    }
}

#[derive(Clone, Copy)]
struct Live {
    first: usize,
    last: usize,
    reads: u32,
    aliased_at: Option<usize>,
}

#[derive(Clone, Copy)]
struct Active {
    live: Live,
    offset: u64,
    bytes: u64,
}

#[derive(Clone, Copy)]
struct Placed {
    store: Store,
    address: u64,
    elements: u32,
    element: Element,
    scale: f32,
}

pub struct Encoding {
    profile: Profile,
    kinds: Vec<Kind>,
    elements: Vec<Element>,
    tasks: Vec<u8>,
    values: Vec<u8>,
    bounds: Vec<u8>,
    steps: Vec<u8>,
    segments: Vec<SegmentRecord>,
    dispatches: Vec<Dispatch>,
    spans: Vec<Option<Placed>>,
    readable: Vec<bool>,
    geometries: Vec<u32>,
    attention: Vec<AttentionTile>,
    arena_bytes: u64,
    tensor_bytes: u64,
    quanta: Vec<Quantum>,
    layout: Layout,
    updates_weights: bool,
    work: u64,
}

impl Encoding {
    pub fn of(graph: &Graph<'_>, alignment: u64, profile: Profile) -> Self {
        Self::plan(&graph.snapshot(), profile, alignment)
    }

    fn plan(state: &GraphSnapshot, profile: Profile, alignment: u64) -> Self {
        assert!(
            alignment.is_power_of_two() && alignment >= 4,
            "an arena alignment of {alignment} bytes is not usable",
        );
        let plan = lower::lower(state.values(), &fuse::fuse(state), profile);
        let values = &plan.values;
        let tasks = &plan.tasks;
        let tiles = &plan;
        let matmul_tiles = profile.tiles();

        let kinds = carried_kinds(tasks);
        let elements = carried_elements(values);
        let layout = Layout::of_values(values, alignment);
        assert_writes_match_their_element(values, tasks);
        assert_quantized_scales_reconstruct(values);
        assert_writers_precede_readers(values, tasks);
        assert_units_keep_their_order(tasks);
        let schedule = schedule::Schedule::of(values, &plan.tiles, tasks, profile.workgroups());
        let order = schedule.order();
        let ends = schedule.ends();
        let live = storage_liveness(values, tasks, order);
        let reserved = layout.tensors().bytes();
        let (offsets, tensor_bytes) = allocate(values, &live, ends, alignment, reserved);
        let arena_bytes = tensor_bytes - reserved;
        assert!(
            tensor_bytes.is_multiple_of(WORD_BYTES),
            "a plan of {tensor_bytes} bytes leaves the word grid the device indexes",
        );

        let mut records = Vec::new();
        for (id, info) in values.iter().enumerate() {
            let address = layout.address(values, &offsets, id as u32);
            let record = ValueRecord::of(ValueFields {
                base: u32::try_from(address).unwrap_or_else(|_| {
                    panic!("value {id} lies at {address}, beyond the device address space")
                }),
                store: layout.store(values, id as u32).code(),
                element: layout.element(values, id as u32).code(),
                table: table_of(values, id as u32),
                dims: info.shape.dims(),
                strides: info.strides,
            });
            records.extend_from_slice(bytemuck::bytes_of(&record));
        }

        let mut tape = Vec::with_capacity(tasks.len() * size_of::<TaskRecord>());
        let mut steps = Vec::new();
        let mut updates_weights = false;
        let mut geometries = vec![0u32; matmul_tiles.len()];
        let mut work = 0;
        for index in order {
            let task = &tasks[*index as usize];
            let geometry = match task.kind.geometry() {
                Geometry::Attention => {
                    assert!(
                        (task.geometry as usize) < tiles.attention.len(),
                        "an attention names geometry {} beyond the {} tiles its plan carries",
                        task.geometry,
                        tiles.attention.len(),
                    );
                    task.geometry
                }
                Geometry::Product => {
                    assert!(
                        (task.geometry as usize) < matmul_tiles.len(),
                        "a product names geometry {} beyond the {} tiles its profile carries",
                        task.geometry,
                        matmul_tiles.len(),
                    );
                    geometries[task.geometry as usize] += 1;
                    task.geometry
                }
                Geometry::Strategy => task.geometry,
                Geometry::None => {
                    assert_eq!(
                        task.geometry,
                        0,
                        "a {} task carries geometry {} where its vocabulary declares none",
                        task.kind.name(),
                        task.geometry,
                    );
                    0
                }
            };
            assert!(
                task.chain.is_empty() || task.kind.takes_chain(),
                "a {} task carries a chain no device body of it reads",
                task.kind.name(),
            );
            assert!(
                task.prelude.is_empty() || task.kind.takes_prelude(),
                "a {} task opens with a prelude no device body of it reads",
                task.kind.name(),
            );
            assert!(
                task.kind != Kind::Matmul || task.splits == 1 || task.chain.is_empty(),
                "a product split across the depth hands its chain to the fold",
            );
            assert!(
                task.origin == NO_VALUE || task.kind.reads_origin(),
                "a {} task carries a cursor no device body of it reads",
                task.kind.name(),
            );
            let prelude = (steps.len() / size_of::<StepRecord>()) as u32;
            for step in &task.prelude {
                steps.extend_from_slice(bytemuck::bytes_of(step));
            }
            let chain = (steps.len() / size_of::<StepRecord>()) as u32;
            for step in &task.chain {
                steps.extend_from_slice(bytemuck::bytes_of(step));
            }
            let record = TaskRecord::of(TaskFields {
                kind: task.kind.code(),
                op: task.op,
                geometry,
                first: task.first,
                count: task.count,
                slot: task.slot,
                splits: task.splits,
                out: task.out,
                extra: task.extra,
                origin: task.origin,
                a: task.inputs[0],
                b: task.inputs[1],
                c: task.inputs[2],
                d: task.inputs[3],
                e: task.inputs[4],
                f: task.inputs[5],
                param: task.param,
                prelude,
                prelude_steps: task.prelude.len() as u32,
                chain,
                steps: task.chain.len() as u32,
                reach_rows: task.window.reach_rows(),
                reach_columns: task.window.reach_columns(),
                stride_rows: task.window.stride_rows(),
                stride_columns: task.window.stride_columns(),
                pad_rows: task.window.pad_rows(),
                pad_columns: task.window.pad_columns(),
                axis: task.axis,
                offset: task.offset,
            });
            if task.in_place
                && task
                    .writes()
                    .any(|out| store_of(info_of(values, out).residency) == Store::Weights)
            {
                updates_weights = true;
            }
            work += task.work;
            tape.extend_from_slice(bytemuck::bytes_of(&record));
        }

        let mut bounds = Vec::new();
        for dispatch in schedule.dispatches() {
            let record = BoundsRecord::of(BoundsFields {
                first_segment: dispatch.first_segment,
            });
            bounds.extend_from_slice(bytemuck::bytes_of(&record));
            bounds.resize(bounds.len().next_multiple_of(alignment as usize), 0);
        }
        let segments = schedule.segments().to_vec();

        let mut readable = vec![false; values.len()];
        let mut last_writer = std::collections::HashMap::<u64, u32>::new();
        for index in order {
            let task = &tasks[*index as usize];
            for out in task.writes() {
                let storage = values[out as usize].storage as usize;
                if !arena_resident(values, storage) {
                    continue;
                }
                last_writer.insert(offsets[storage], out);
            }
        }
        for (id, info) in values.iter().enumerate() {
            if !addressed_as_its_storage(values, id) {
                continue;
            }
            let storage = info.storage as usize;
            readable[id] = match values[storage].residency {
                Residency::Parameter | Residency::State | Residency::Resident => true,
                _ => match last_writer.get(&offsets[storage]) {
                    Some(writer) => *writer == storage as u32,
                    None => held(values, storage),
                },
            };
        }
        let mut spans = vec![None; values.len()];
        for (id, info) in values.iter().enumerate() {
            if !addressed_as_its_storage(values, id) {
                continue;
            }
            spans[id] = Some(Placed {
                store: layout.store(values, id as u32),
                address: layout.address(values, &offsets, id as u32),
                elements: info.shape.elements(),
                element: layout.element(values, id as u32),
                scale: layout.scale(values, id as u32),
            });
        }

        Self {
            profile,
            kinds,
            elements,
            tasks: tape,
            values: records,
            bounds,
            steps,
            segments,
            dispatches: schedule.dispatches().to_vec(),
            spans,
            readable,
            geometries,
            attention: tiles.attention.clone(),
            arena_bytes,
            tensor_bytes,
            quanta: quanta(values, &offsets),
            layout,
            updates_weights,
            work,
        }
    }

    pub fn profile(&self) -> Profile {
        self.profile
    }

    pub fn tiles(&self) -> &[MatmulTile] {
        self.profile.tiles()
    }

    pub fn kinds(&self) -> &[Kind] {
        &self.kinds
    }

    pub fn elements(&self) -> &[Element] {
        &self.elements
    }

    pub fn attention(&self) -> &[AttentionTile] {
        &self.attention
    }

    pub fn matmul_geometries(&self) -> Vec<(MatmulTile, u32)> {
        self.tiles()
            .iter()
            .copied()
            .zip(self.geometries.iter().copied())
            .filter(|(_, count)| *count > 0)
            .collect()
    }

    pub fn walked_tiles(&self) -> impl Iterator<Item = (u32, MatmulTile)> + '_ {
        self.geometries
            .iter()
            .enumerate()
            .filter(|(_, count)| **count > 0)
            .map(|(index, _)| (index as u32, self.tiles()[index]))
    }

    pub fn tasks(&self) -> &[u8] {
        &self.tasks
    }

    pub fn values(&self) -> &[u8] {
        &self.values
    }

    pub fn bounds(&self) -> &[u8] {
        &self.bounds
    }

    pub fn steps(&self) -> &[u8] {
        &self.steps
    }

    pub fn segments(&self) -> &[SegmentRecord] {
        &self.segments
    }

    pub fn dispatches(&self) -> &[Dispatch] {
        &self.dispatches
    }

    pub fn span(&self, value: Value<'_>, placement: Placement) -> Span {
        let placed = self
            .spans
            .get(value.id() as usize)
            .copied()
            .flatten()
            .unwrap_or_else(|| {
                panic!(
                    "{} elements of a view hold no storage of their own",
                    value.shape().elements(),
                )
            });
        let offset = match placed.store {
            Store::Weights => (placement.weights() + placed.address) * WORD_BYTES,
            Store::Tensors => (placement.tensors() + placed.address) * WORD_BYTES,
        };
        Span {
            store: placed.store,
            offset,
            elements: placed.elements,
            element: placed.element,
            scale: placed.scale,
        }
    }

    pub fn readable(&self, value: Value<'_>) -> bool {
        self.readable
            .get(value.id() as usize)
            .copied()
            .unwrap_or(false)
    }

    pub fn arena_bytes(&self) -> u64 {
        self.arena_bytes
    }

    pub fn quanta(&self) -> &[Quantum] {
        &self.quanta
    }

    pub fn weights(&self) -> &Region {
        self.layout.weights()
    }

    pub fn state(&self) -> &Region {
        self.layout.state()
    }

    pub fn tensors(&self) -> &Region {
        self.layout.tensors()
    }

    pub fn tensor_bytes(&self) -> u64 {
        self.tensor_bytes
    }

    pub fn resident_bytes(&self) -> u64 {
        self.layout.tensors().bytes()
    }

    pub fn updates_weights(&self) -> bool {
        self.updates_weights
    }

    pub fn task_count(&self) -> u32 {
        (self.tasks.len() / size_of::<TaskRecord>()) as u32
    }

    pub fn step_count(&self) -> u32 {
        (self.steps.len() / size_of::<StepRecord>()) as u32
    }

    pub fn value_count(&self) -> u32 {
        (self.values.len() / size_of::<ValueRecord>()) as u32
    }

    pub fn dispatch_count(&self) -> u32 {
        self.dispatches.len() as u32
    }

    pub fn work(&self) -> u64 {
        self.work
    }
}

fn carried_kinds(tasks: &[Task]) -> Vec<Kind> {
    Kind::ALL
        .iter()
        .copied()
        .filter(|kind| {
            tasks.iter().any(|task| task.kind == *kind)
                || (*kind == Kind::MatmulFold && tasks.iter().any(|task| task.kind == Kind::Matmul))
        })
        .collect()
}

fn carried_elements(values: &[ValueInfo]) -> Vec<Element> {
    Element::ALL
        .iter()
        .copied()
        .filter(|element| values.iter().any(|info| info.element == *element))
        .collect()
}

fn assert_writes_match_their_element(values: &[ValueInfo], tasks: &[Task]) {
    for task in tasks {
        for out in task.writes() {
            let out = &values[out as usize];
            assert!(
                !out.element.per_block(),
                "a {} task writes the block quantized tensor {}; a {} tensor reconstructs through the quantum its storage holds of every {} blocks, and only its host holds those",
                task.kind.name(),
                task.out,
                out.element.name(),
                out.element.block(),
            );
            if task.kind == Kind::Convert {
                assert!(
                    out.element.narrow(),
                    "a convert writes the {} tensor {} word by word, and a word holds one element",
                    out.element.name(),
                    task.out,
                );
                for source in task
                    .inputs
                    .iter()
                    .take(1)
                    .chain(task.prelude.iter().map(|step| &step.operand))
                    .chain(task.chain.iter().map(|step| &step.operand))
                    .filter(|source| **source != NO_VALUE)
                    .copied()
                {
                    assert!(
                        values[source as usize].shape.fits_within(out.shape),
                        "a convert reads {:?} through the {:?} it writes",
                        values[source as usize].shape.dims(),
                        out.shape.dims(),
                    );
                }
                continue;
            }
            assert!(
                !out.element.narrow(),
                "a {} task writes the {} tensor {} element by element, and a narrow tensor is written word by word by a convert",
                task.kind.name(),
                out.element.name(),
                task.out,
            );
        }
    }
}

fn assert_quantized_scales_reconstruct(values: &[ValueInfo]) {
    for (id, info) in values.iter().enumerate() {
        if !info.element.per_tensor() {
            continue;
        }
        assert!(
            info.scale.is_finite() && info.scale > 0.0,
            "value {id} quantum of scale {} reconstructs nothing",
            info.scale,
        );
    }
}

fn assert_writers_precede_readers(values: &[ValueInfo], tasks: &[Task]) {
    let mut last_writer = vec![None::<usize>; values.len()];
    for (position, task) in tasks.iter().enumerate() {
        let access = Access::of(values, task);
        for storage in access.reads() {
            if access.in_place() && access.writes().contains(storage) {
                continue;
            }
            match last_writer[*storage as usize] {
                Some(writer) => assert!(
                    writer < position,
                    "task {position} reads a tensor that its own tape only writes later",
                ),
                None => assert!(
                    held(values, *storage as usize),
                    "task {position} reads a tensor no task of the tape writes before it",
                ),
            }
        }
        for storage in access.writes() {
            last_writer[*storage as usize] = Some(position);
        }
    }
}

fn assert_units_keep_their_order(tasks: &[Task]) {
    for pair in tasks.windows(2) {
        assert!(
            pair[0].unit <= pair[1].unit,
            "a task of the fold that became unit {} stands before a task of unit {}",
            pair[1].unit,
            pair[0].unit,
        );
    }
}

fn storage_liveness(values: &[ValueInfo], tasks: &[Task], order: &[u32]) -> Vec<Option<Live>> {
    let mut live = vec![None::<Live>; values.len()];
    let mut readers = Vec::new();
    for (position, index) in order.iter().enumerate() {
        let task = &tasks[*index as usize];
        let writes = Access::of(values, task).writes().to_vec();
        let aliases = writes
            .first()
            .is_some_and(|write| reads_every_element_in_place(values, task, *write));
        for write in &writes {
            touch(&mut live, *write, position, false, None);
        }
        readers.clear();
        for value in task.reads() {
            if readers.contains(&value) {
                continue;
            }
            readers.push(value);
            let storage = access::storage(values, value);
            let in_place = aliases && !writes.contains(&storage);
            touch(
                &mut live,
                storage,
                position,
                true,
                in_place.then_some(position),
            );
        }
    }
    live
}

fn reads_every_element_in_place(values: &[ValueInfo], task: &Task, write: u32) -> bool {
    if !matches!(
        task.kind,
        Kind::Binary | Kind::Unary | Kind::Partial | Kind::Fill | Kind::Broadcast
    ) {
        return false;
    }
    let out = &values[write as usize];
    task.reads().all(|value| {
        let value = &values[value as usize];
        value.shape == out.shape && value.strides == out.strides && value.element == out.element
    })
}

fn touch(
    live: &mut [Option<Live>],
    storage: u32,
    position: usize,
    read: bool,
    aliased_at: Option<usize>,
) {
    match &mut live[storage as usize] {
        Some(entry) => {
            entry.first = entry.first.min(position);
            entry.last = entry.last.max(position);
            entry.reads += u32::from(read);
            entry.aliased_at = entry.aliased_at.max(aliased_at);
        }
        slot @ None => {
            *slot = Some(Live {
                first: position,
                last: position,
                reads: u32::from(read),
                aliased_at,
            });
        }
    }
}

fn storage_bytes(values: &[ValueInfo], storage: usize) -> u64 {
    let info = &values[storage];
    info.element.storage_words(u64::from(info.shape.elements())) * WORD_BYTES
}

fn table_of(values: &[ValueInfo], value: u32) -> u32 {
    let info = &values[value as usize];
    if !info.element.quantized() {
        return NO_VALUE;
    }
    let owner = &values[info.storage as usize];
    u32::try_from(
        owner
            .element
            .payload_words(u64::from(owner.shape.elements())),
    )
    .unwrap_or_else(|_| {
        panic!("the quantum table of value {value} lies beyond the device address space")
    })
}

fn quanta(values: &[ValueInfo], offsets: &[u64]) -> Vec<Quantum> {
    values
        .iter()
        .enumerate()
        .filter(|(id, info)| {
            info.storage as usize == *id && arena_resident(values, *id) && info.element.quantized()
        })
        .map(|(id, info)| Quantum {
            offset: offsets[id]
                + info.element.payload_words(u64::from(info.shape.elements())) * WORD_BYTES,
            scale: info.scale,
        })
        .collect()
}

fn info_of(values: &[ValueInfo], value: u32) -> &ValueInfo {
    &values[values[value as usize].storage as usize]
}

fn addressed_as_its_storage(values: &[ValueInfo], id: usize) -> bool {
    let info = &values[id];
    let storage = &values[info.storage as usize];
    info.shape.elements() == storage.shape.elements() && info.strides == info.shape.strides()
}

fn owns_its_quanta(values: &[ValueInfo], storage: usize) -> bool {
    values[storage].element.quantized()
}

fn arena_resident(values: &[ValueInfo], storage: usize) -> bool {
    matches!(
        values[storage].residency,
        Residency::Input | Residency::Derived
    )
}

fn held(values: &[ValueInfo], storage: usize) -> bool {
    matches!(
        values[storage].residency,
        Residency::Input | Residency::Parameter | Residency::State | Residency::Resident
    )
}

fn allocate(
    values: &[ValueInfo],
    live: &[Option<Live>],
    waves: &[u32],
    alignment: u64,
    reserved: u64,
) -> (Vec<u64>, u64) {
    let wave_of = |position: usize| waves.partition_point(|end| *end <= position as u32) as u32;
    let mut arena = Blocks::with_base(reserved);
    let mut offsets = vec![0u64; live.len()];
    let owners = (0..values.len()).filter(|id| values[*id].storage as usize == *id);
    for id in owners.clone() {
        if !arena_resident(values, id) {
            continue;
        }
        if held(values, id) || values[id].retained || owns_its_quanta(values, id) {
            offsets[id] = arena.reserve(storage_bytes(values, id), alignment);
        }
    }
    let mut pending = live
        .iter()
        .enumerate()
        .filter(|(id, _)| !held(values, *id) && !values[*id].retained)
        .filter(|(id, _)| !owns_its_quanta(values, *id))
        .filter_map(|(id, live)| live.map(|live| (id, live)))
        .collect::<Vec<_>>();
    pending.sort_by_key(|(_, live)| (live.first, live.last));
    let mut active = Vec::<Active>::new();
    for (storage, live) in pending {
        let wave = wave_of(live.first);
        let taken = active
            .iter()
            .position(|held| held.live.reads == 1 && held.live.aliased_at == Some(live.first));
        if let Some(position) = taken {
            let held = active.swap_remove(position);
            let bytes = storage_bytes(values, storage);
            assert_eq!(
                held.bytes, bytes,
                "a value read in place by one task hands that task a storage of another size",
            );
            offsets[storage] = held.offset;
            active.push(Active {
                live,
                offset: held.offset,
                bytes,
            });
            continue;
        }
        active.retain(|held| {
            if wave_of(held.live.last) < wave {
                arena.release(held.offset, held.bytes);
                false
            } else {
                true
            }
        });
        let bytes = storage_bytes(values, storage);
        let offset = arena.reserve(bytes, alignment);
        offsets[storage] = offset;
        active.push(Active {
            live,
            offset,
            bytes,
        });
    }
    (offsets, arena.bytes())
}