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