neura-program 0.1.0

Host graph, wave schedule, arena plan and autograd over the device tape
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
use crate::access::{self, Access, Reads};
use crate::fuse;
use crate::graph::{GraphState, Residency, ValueInfo};
use crate::layout::{Layout, Region, store_of};
use crate::lower;
use crate::lower::Task;
use crate::schedule::{self, Dispatch};
use neura_abi::{
    BoundsFields, BoundsRecord, Kind, MatmulTile, Placement, Precision, Profile, SegmentRecord,
    StepRecord, Store, TaskFields, TaskRecord, ValueFields, ValueRecord, WORD_BYTES,
};
use std::mem::size_of;

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

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,
}

pub struct Encoding {
    profile: Profile,
    kinds: Vec<Kind>,
    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>,
    arena_bytes: u64,
    tensor_bytes: u64,
    layout: Layout,
    updates_weights: bool,
    work: u64,
}

impl Encoding {
    pub(crate) fn plan(
        state: &GraphState,
        profile: Profile,
        alignment: u64,
        precision: Precision,
    ) -> 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 kinds = carried_kinds(tasks);
        let layout = Layout::of(values, precision, alignment);
        assert_writers_precede_readers(values, tasks);
        assert_units_keep_their_order(tasks);
        let schedule = schedule::Schedule::of(values, tasks);
        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(),
                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; profile.tiles().len()];
        let mut work = 0;
        for index in order {
            let task = &tasks[*index as usize];
            let geometry = match task.kind {
                Kind::Matmul => {
                    assert!(
                        (task.geometry as usize) < profile.tiles().len(),
                        "a product names geometry {} beyond the {} tiles a profile offers",
                        task.geometry,
                        profile.tiles().len(),
                    );
                    geometries[task.geometry as usize] += 1;
                    task.geometry
                }
                Kind::Argmax | Kind::Categorical | Kind::SumAxis | Kind::Conv2dWeightGrad => {
                    task.geometry
                }
                Kind::Binary
                | Kind::Unary
                | Kind::Partial
                | Kind::Fill
                | Kind::Broadcast
                | Kind::SumChunk
                | Kind::Softmax
                | Kind::SoftmaxGrad
                | Kind::LogSoftmax
                | Kind::LogSoftmaxGrad
                | Kind::OneHot
                | Kind::Gather
                | Kind::Scatter
                | Kind::Conv2d
                | Kind::Conv2dInputGrad
                | Kind::MatmulFold => 0,
            };
            assert!(
                task.kind != Kind::SumChunk || task.chain.is_empty(),
                "a reduction task writes one slot per task and carries no chain",
            );
            assert!(
                task.kind != Kind::Matmul || task.splits == 1 || task.chain.is_empty(),
                "a product split across the depth hands its chain to the fold",
            );
            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,
                a: task.inputs[0],
                b: task.inputs[1],
                c: task.inputs[2],
                param: task.param,
                chain: (steps.len() / size_of::<StepRecord>()) as u32,
                steps: task.chain.len() as u32,
                stride_rows: task.window.stride_rows(),
                stride_columns: task.window.stride_columns(),
                pad_rows: task.window.pad_rows(),
                pad_columns: task.window.pad_columns(),
            });
            for step in &task.chain {
                steps.extend_from_slice(bytemuck::bytes_of(step));
            }
            if task.in_place && store_of(info_of(values, task.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];
            let storage = values[task.out as usize].storage as usize;
            if !arena_resident(values, storage) {
                continue;
            }
            last_writer.insert(offsets[storage], task.out);
        }
        for (id, info) in values.iter().enumerate() {
            if info.storage as usize != id {
                continue;
            }
            readable[id] = match info.residency {
                Residency::Parameter | Residency::Resident => true,
                _ => match last_writer.get(&offsets[id]) {
                    Some(writer) => *writer == id as u32,
                    None => held(values, id),
                },
            };
        }
        let mut spans = vec![None; values.len()];
        for (id, info) in values.iter().enumerate() {
            if info.storage as usize != 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(),
            });
        }

        Self {
            profile,
            kinds,
            tasks: tape,
            values: records,
            bounds,
            steps,
            segments,
            dispatches: schedule.dispatches().to_vec(),
            spans,
            readable,
            geometries,
            arena_bytes,
            tensor_bytes,
            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 matmul_geometries(&self) -> Vec<(MatmulTile, u32)> {
        self.tiles()
            .iter()
            .copied()
            .zip(self.geometries.iter().copied())
            .filter(|(_, count)| *count > 0)
            .collect()
    }

    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: crate::graph::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 => self.layout.weight_bytes(placement, placed.address),
            Store::Tensors => (placement.tensors() + placed.address) * WORD_BYTES,
        };
        Span {
            store: placed.store,
            offset,
            elements: placed.elements,
        }
    }

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

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

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

    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))
        .collect()
}

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() && *storage == access.write() {
                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",
                ),
            }
        }
        last_writer[access.write() 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 write = access::storage(values, task.out);
        let aliases = reads_every_element_in_place(values, task, write);
        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 && storage != write;
            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 !task.kind.pointwise() {
        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
    })
}

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 {
    u64::from(values[storage].shape.elements()) * WORD_BYTES
}

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

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::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 {
            offsets[id] = arena.reserve(storage_bytes(values, id), alignment);
        }
    }
    let mut pending = live
        .iter()
        .enumerate()
        .filter(|(id, _)| !held(values, *id) && !values[*id].retained)
        .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())
}