Skip to main content

neura_program/
encode.rs

1use crate::access::{self, Access, Reads};
2use crate::fuse;
3use crate::graph::{GraphState, Residency, ValueInfo};
4use crate::layout::{Layout, Region, store_of};
5use crate::lower;
6use crate::lower::Task;
7use crate::schedule::{self, Dispatch};
8use neura_abi::{
9    BoundsFields, BoundsRecord, Kind, MatmulTile, Placement, Precision, Profile, SegmentRecord,
10    StepRecord, Store, TaskFields, TaskRecord, ValueFields, ValueRecord, WORD_BYTES,
11};
12use std::mem::size_of;
13
14#[derive(Clone, Copy, PartialEq, Eq, Debug)]
15pub struct Span {
16    pub store: Store,
17    pub offset: u64,
18    pub elements: u32,
19}
20
21struct Block {
22    offset: u64,
23    bytes: u64,
24}
25
26struct Blocks {
27    free: Vec<Block>,
28    end: u64,
29}
30
31impl Blocks {
32    fn with_base(base: u64) -> Self {
33        Self {
34            free: Vec::new(),
35            end: base,
36        }
37    }
38
39    fn bytes(&self) -> u64 {
40        self.end
41    }
42
43    fn reserve(&mut self, bytes: u64, alignment: u64) -> u64 {
44        for index in 0..self.free.len() {
45            let block = &self.free[index];
46            let offset = block.offset.next_multiple_of(alignment);
47            let end = block.offset + block.bytes;
48            if offset + bytes > end {
49                continue;
50            }
51            if offset + bytes == end {
52                self.free.remove(index);
53            } else {
54                self.free[index].offset = offset + bytes;
55                self.free[index].bytes = end - offset - bytes;
56            }
57            return offset;
58        }
59        let offset = self.end.next_multiple_of(alignment);
60        self.end = offset + bytes;
61        offset
62    }
63
64    fn release(&mut self, offset: u64, bytes: u64) {
65        self.free.push(Block { offset, bytes });
66        self.free.sort_by_key(|block| block.offset);
67        let mut merged: Vec<Block> = Vec::with_capacity(self.free.len());
68        for block in self.free.drain(..) {
69            match merged.last_mut() {
70                Some(last) if last.offset + last.bytes >= block.offset => {
71                    last.bytes = last.bytes.max(block.offset + block.bytes - last.offset);
72                }
73                _ => merged.push(block),
74            }
75        }
76        self.free = merged;
77    }
78}
79
80#[derive(Clone, Copy)]
81struct Live {
82    first: usize,
83    last: usize,
84    reads: u32,
85    aliased_at: Option<usize>,
86}
87
88#[derive(Clone, Copy)]
89struct Active {
90    live: Live,
91    offset: u64,
92    bytes: u64,
93}
94
95#[derive(Clone, Copy)]
96struct Placed {
97    store: Store,
98    address: u64,
99    elements: u32,
100}
101
102pub struct Encoding {
103    profile: Profile,
104    kinds: Vec<Kind>,
105    tasks: Vec<u8>,
106    values: Vec<u8>,
107    bounds: Vec<u8>,
108    steps: Vec<u8>,
109    segments: Vec<SegmentRecord>,
110    dispatches: Vec<Dispatch>,
111    spans: Vec<Option<Placed>>,
112    readable: Vec<bool>,
113    geometries: Vec<u32>,
114    arena_bytes: u64,
115    tensor_bytes: u64,
116    layout: Layout,
117    updates_weights: bool,
118    work: u64,
119}
120
121impl Encoding {
122    pub(crate) fn plan(
123        state: &GraphState,
124        profile: Profile,
125        alignment: u64,
126        precision: Precision,
127    ) -> Self {
128        assert!(
129            alignment.is_power_of_two() && alignment >= 4,
130            "an arena alignment of {alignment} bytes is not usable",
131        );
132        let plan = lower::lower(&state.values, &fuse::fuse(state), profile);
133        let values = &plan.values;
134        let tasks = &plan.tasks;
135        let kinds = carried_kinds(tasks);
136        let layout = Layout::of(values, precision, alignment);
137        assert_writers_precede_readers(values, tasks);
138        assert_units_keep_their_order(tasks);
139        let schedule = schedule::Schedule::of(values, tasks);
140        let order = schedule.order();
141        let ends = schedule.ends();
142        let live = storage_liveness(values, tasks, order);
143        let reserved = layout.tensors().bytes();
144        let (offsets, tensor_bytes) = allocate(values, &live, ends, alignment, reserved);
145        let arena_bytes = tensor_bytes - reserved;
146        assert!(
147            tensor_bytes.is_multiple_of(WORD_BYTES),
148            "a plan of {tensor_bytes} bytes leaves the word grid the device indexes",
149        );
150
151        let mut records = Vec::new();
152        for (id, info) in values.iter().enumerate() {
153            let address = layout.address(values, &offsets, id as u32);
154            let record = ValueRecord::of(ValueFields {
155                base: u32::try_from(address).unwrap_or_else(|_| {
156                    panic!("value {id} lies at {address}, beyond the device address space")
157                }),
158                store: layout.store(values, id as u32).code(),
159                dims: info.shape.dims(),
160                strides: info.strides,
161            });
162            records.extend_from_slice(bytemuck::bytes_of(&record));
163        }
164
165        let mut tape = Vec::with_capacity(tasks.len() * size_of::<TaskRecord>());
166        let mut steps = Vec::new();
167        let mut updates_weights = false;
168        let mut geometries = vec![0u32; profile.tiles().len()];
169        let mut work = 0;
170        for index in order {
171            let task = &tasks[*index as usize];
172            let geometry = match task.kind {
173                Kind::Matmul => {
174                    assert!(
175                        (task.geometry as usize) < profile.tiles().len(),
176                        "a product names geometry {} beyond the {} tiles a profile offers",
177                        task.geometry,
178                        profile.tiles().len(),
179                    );
180                    geometries[task.geometry as usize] += 1;
181                    task.geometry
182                }
183                Kind::Argmax | Kind::Categorical | Kind::SumAxis | Kind::Conv2dWeightGrad => {
184                    task.geometry
185                }
186                Kind::Binary
187                | Kind::Unary
188                | Kind::Partial
189                | Kind::Fill
190                | Kind::Broadcast
191                | Kind::SumChunk
192                | Kind::Softmax
193                | Kind::SoftmaxGrad
194                | Kind::LogSoftmax
195                | Kind::LogSoftmaxGrad
196                | Kind::OneHot
197                | Kind::Gather
198                | Kind::Scatter
199                | Kind::Conv2d
200                | Kind::Conv2dInputGrad
201                | Kind::MatmulFold => 0,
202            };
203            assert!(
204                task.kind != Kind::SumChunk || task.chain.is_empty(),
205                "a reduction task writes one slot per task and carries no chain",
206            );
207            assert!(
208                task.kind != Kind::Matmul || task.splits == 1 || task.chain.is_empty(),
209                "a product split across the depth hands its chain to the fold",
210            );
211            let record = TaskRecord::of(TaskFields {
212                kind: task.kind.code(),
213                op: task.op,
214                geometry,
215                first: task.first,
216                count: task.count,
217                slot: task.slot,
218                splits: task.splits,
219                out: task.out,
220                a: task.inputs[0],
221                b: task.inputs[1],
222                c: task.inputs[2],
223                param: task.param,
224                chain: (steps.len() / size_of::<StepRecord>()) as u32,
225                steps: task.chain.len() as u32,
226                stride_rows: task.window.stride_rows(),
227                stride_columns: task.window.stride_columns(),
228                pad_rows: task.window.pad_rows(),
229                pad_columns: task.window.pad_columns(),
230            });
231            for step in &task.chain {
232                steps.extend_from_slice(bytemuck::bytes_of(step));
233            }
234            if task.in_place && store_of(info_of(values, task.out).residency) == Store::Weights {
235                updates_weights = true;
236            }
237            work += task.work;
238            tape.extend_from_slice(bytemuck::bytes_of(&record));
239        }
240
241        let mut bounds = Vec::new();
242        for dispatch in schedule.dispatches() {
243            let record = BoundsRecord::of(BoundsFields {
244                first_segment: dispatch.first_segment,
245            });
246            bounds.extend_from_slice(bytemuck::bytes_of(&record));
247            bounds.resize(bounds.len().next_multiple_of(alignment as usize), 0);
248        }
249        let segments = schedule.segments().to_vec();
250
251        let mut readable = vec![false; values.len()];
252        let mut last_writer = std::collections::HashMap::<u64, u32>::new();
253        for index in order {
254            let task = &tasks[*index as usize];
255            let storage = values[task.out as usize].storage as usize;
256            if !arena_resident(values, storage) {
257                continue;
258            }
259            last_writer.insert(offsets[storage], task.out);
260        }
261        for (id, info) in values.iter().enumerate() {
262            if info.storage as usize != id {
263                continue;
264            }
265            readable[id] = match info.residency {
266                Residency::Parameter | Residency::Resident => true,
267                _ => match last_writer.get(&offsets[id]) {
268                    Some(writer) => *writer == id as u32,
269                    None => held(values, id),
270                },
271            };
272        }
273        let mut spans = vec![None; values.len()];
274        for (id, info) in values.iter().enumerate() {
275            if info.storage as usize != id {
276                continue;
277            }
278            spans[id] = Some(Placed {
279                store: layout.store(values, id as u32),
280                address: layout.address(values, &offsets, id as u32),
281                elements: info.shape.elements(),
282            });
283        }
284
285        Self {
286            profile,
287            kinds,
288            tasks: tape,
289            values: records,
290            bounds,
291            steps,
292            segments,
293            dispatches: schedule.dispatches().to_vec(),
294            spans,
295            readable,
296            geometries,
297            arena_bytes,
298            tensor_bytes,
299            layout,
300            updates_weights,
301            work,
302        }
303    }
304
305    pub fn profile(&self) -> Profile {
306        self.profile
307    }
308
309    pub fn tiles(&self) -> &[MatmulTile] {
310        self.profile.tiles()
311    }
312
313    pub fn kinds(&self) -> &[Kind] {
314        &self.kinds
315    }
316
317    pub fn matmul_geometries(&self) -> Vec<(MatmulTile, u32)> {
318        self.tiles()
319            .iter()
320            .copied()
321            .zip(self.geometries.iter().copied())
322            .filter(|(_, count)| *count > 0)
323            .collect()
324    }
325
326    pub fn tasks(&self) -> &[u8] {
327        &self.tasks
328    }
329
330    pub fn values(&self) -> &[u8] {
331        &self.values
332    }
333
334    pub fn bounds(&self) -> &[u8] {
335        &self.bounds
336    }
337
338    pub fn steps(&self) -> &[u8] {
339        &self.steps
340    }
341
342    pub fn segments(&self) -> &[SegmentRecord] {
343        &self.segments
344    }
345
346    pub fn dispatches(&self) -> &[Dispatch] {
347        &self.dispatches
348    }
349
350    pub fn span(&self, value: crate::graph::Value, placement: Placement) -> Span {
351        let placed = self
352            .spans
353            .get(value.id() as usize)
354            .copied()
355            .flatten()
356            .unwrap_or_else(|| {
357                panic!(
358                    "{} elements of a view hold no storage of their own",
359                    value.shape().elements(),
360                )
361            });
362        let offset = match placed.store {
363            Store::Weights => self.layout.weight_bytes(placement, placed.address),
364            Store::Tensors => (placement.tensors() + placed.address) * WORD_BYTES,
365        };
366        Span {
367            store: placed.store,
368            offset,
369            elements: placed.elements,
370        }
371    }
372
373    pub fn readable(&self, value: crate::graph::Value) -> bool {
374        self.readable
375            .get(value.id() as usize)
376            .copied()
377            .unwrap_or(false)
378    }
379
380    pub fn arena_bytes(&self) -> u64 {
381        self.arena_bytes
382    }
383
384    pub fn weights(&self) -> &Region {
385        self.layout.weights()
386    }
387
388    pub fn tensors(&self) -> &Region {
389        self.layout.tensors()
390    }
391
392    pub fn tensor_bytes(&self) -> u64 {
393        self.tensor_bytes
394    }
395
396    pub fn resident_bytes(&self) -> u64 {
397        self.layout.tensors().bytes()
398    }
399
400    pub fn updates_weights(&self) -> bool {
401        self.updates_weights
402    }
403
404    pub fn task_count(&self) -> u32 {
405        (self.tasks.len() / size_of::<TaskRecord>()) as u32
406    }
407
408    pub fn step_count(&self) -> u32 {
409        (self.steps.len() / size_of::<StepRecord>()) as u32
410    }
411
412    pub fn value_count(&self) -> u32 {
413        (self.values.len() / size_of::<ValueRecord>()) as u32
414    }
415
416    pub fn dispatch_count(&self) -> u32 {
417        self.dispatches.len() as u32
418    }
419
420    pub fn work(&self) -> u64 {
421        self.work
422    }
423}
424
425fn carried_kinds(tasks: &[Task]) -> Vec<Kind> {
426    Kind::ALL
427        .iter()
428        .copied()
429        .filter(|kind| tasks.iter().any(|task| task.kind == *kind))
430        .collect()
431}
432
433fn assert_writers_precede_readers(values: &[ValueInfo], tasks: &[Task]) {
434    let mut last_writer = vec![None::<usize>; values.len()];
435    for (position, task) in tasks.iter().enumerate() {
436        let access = Access::of(values, task);
437        for storage in access.reads() {
438            if access.in_place() && *storage == access.write() {
439                continue;
440            }
441            match last_writer[*storage as usize] {
442                Some(writer) => assert!(
443                    writer < position,
444                    "task {position} reads a tensor that its own tape only writes later",
445                ),
446                None => assert!(
447                    held(values, *storage as usize),
448                    "task {position} reads a tensor no task of the tape writes before it",
449                ),
450            }
451        }
452        last_writer[access.write() as usize] = Some(position);
453    }
454}
455
456fn assert_units_keep_their_order(tasks: &[Task]) {
457    for pair in tasks.windows(2) {
458        assert!(
459            pair[0].unit <= pair[1].unit,
460            "a task of the fold that became unit {} stands before a task of unit {}",
461            pair[1].unit,
462            pair[0].unit,
463        );
464    }
465}
466
467fn storage_liveness(values: &[ValueInfo], tasks: &[Task], order: &[u32]) -> Vec<Option<Live>> {
468    let mut live = vec![None::<Live>; values.len()];
469    let mut readers = Vec::new();
470    for (position, index) in order.iter().enumerate() {
471        let task = &tasks[*index as usize];
472        let write = access::storage(values, task.out);
473        let aliases = reads_every_element_in_place(values, task, write);
474        touch(&mut live, write, position, false, None);
475        readers.clear();
476        for value in task.reads() {
477            if readers.contains(&value) {
478                continue;
479            }
480            readers.push(value);
481            let storage = access::storage(values, value);
482            let in_place = aliases && storage != write;
483            touch(
484                &mut live,
485                storage,
486                position,
487                true,
488                in_place.then_some(position),
489            );
490        }
491    }
492    live
493}
494
495fn reads_every_element_in_place(values: &[ValueInfo], task: &Task, write: u32) -> bool {
496    if !task.kind.pointwise() {
497        return false;
498    }
499    let out = &values[write as usize];
500    task.reads().all(|value| {
501        let value = &values[value as usize];
502        value.shape == out.shape && value.strides == out.strides
503    })
504}
505
506fn touch(
507    live: &mut [Option<Live>],
508    storage: u32,
509    position: usize,
510    read: bool,
511    aliased_at: Option<usize>,
512) {
513    match &mut live[storage as usize] {
514        Some(entry) => {
515            entry.first = entry.first.min(position);
516            entry.last = entry.last.max(position);
517            entry.reads += u32::from(read);
518            entry.aliased_at = entry.aliased_at.max(aliased_at);
519        }
520        slot @ None => {
521            *slot = Some(Live {
522                first: position,
523                last: position,
524                reads: u32::from(read),
525                aliased_at,
526            });
527        }
528    }
529}
530
531fn storage_bytes(values: &[ValueInfo], storage: usize) -> u64 {
532    u64::from(values[storage].shape.elements()) * WORD_BYTES
533}
534
535fn info_of(values: &[ValueInfo], value: u32) -> &ValueInfo {
536    &values[values[value as usize].storage as usize]
537}
538
539fn arena_resident(values: &[ValueInfo], storage: usize) -> bool {
540    matches!(
541        values[storage].residency,
542        Residency::Input | Residency::Derived
543    )
544}
545
546fn held(values: &[ValueInfo], storage: usize) -> bool {
547    matches!(
548        values[storage].residency,
549        Residency::Input | Residency::Parameter | Residency::Resident
550    )
551}
552
553fn allocate(
554    values: &[ValueInfo],
555    live: &[Option<Live>],
556    waves: &[u32],
557    alignment: u64,
558    reserved: u64,
559) -> (Vec<u64>, u64) {
560    let wave_of = |position: usize| waves.partition_point(|end| *end <= position as u32) as u32;
561    let mut arena = Blocks::with_base(reserved);
562    let mut offsets = vec![0u64; live.len()];
563    let owners = (0..values.len()).filter(|id| values[*id].storage as usize == *id);
564    for id in owners.clone() {
565        if !arena_resident(values, id) {
566            continue;
567        }
568        if held(values, id) || values[id].retained {
569            offsets[id] = arena.reserve(storage_bytes(values, id), alignment);
570        }
571    }
572    let mut pending = live
573        .iter()
574        .enumerate()
575        .filter(|(id, _)| !held(values, *id) && !values[*id].retained)
576        .filter_map(|(id, live)| live.map(|live| (id, live)))
577        .collect::<Vec<_>>();
578    pending.sort_by_key(|(_, live)| (live.first, live.last));
579    let mut active = Vec::<Active>::new();
580    for (storage, live) in pending {
581        let wave = wave_of(live.first);
582        let taken = active
583            .iter()
584            .position(|held| held.live.reads == 1 && held.live.aliased_at == Some(live.first));
585        if let Some(position) = taken {
586            let held = active.swap_remove(position);
587            let bytes = storage_bytes(values, storage);
588            assert_eq!(
589                held.bytes, bytes,
590                "a value read in place by one task hands that task a storage of another size",
591            );
592            offsets[storage] = held.offset;
593            active.push(Active {
594                live,
595                offset: held.offset,
596                bytes,
597            });
598            continue;
599        }
600        active.retain(|held| {
601            if wave_of(held.live.last) < wave {
602                arena.release(held.offset, held.bytes);
603                false
604            } else {
605                true
606            }
607        });
608        let bytes = storage_bytes(values, storage);
609        let offset = arena.reserve(bytes, alignment);
610        offsets[storage] = offset;
611        active.push(Active {
612            live,
613            offset,
614            bytes,
615        });
616    }
617    (offsets, arena.bytes())
618}