interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-heartbeat / src / pager / pipeline.rs

328 lines · 13823 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2//! Transport adapter for om/ribbon/pipeline.om. The Omega unit owns admission,
3//! stage transitions, buffer budgets and publication. This adapter attaches the
4//! existing read workers and GPU slot implementation to its returned actions.
5
6use super::*;
7use crate::reader::{Ticket, VerifiedExpert};
8
9mod native {
10 // Generated from pipeline.om by Omega Bridge, never handwritten declarations.
11 include!(env!("AIEN_RIBBON_BINDINGS"));
12}
13
14struct Controller {
15 state: Box<[u64; 4096]>,
16 start: Instant,
17}
18
19impl Controller {
20 fn call(
21 &mut self,
22 op: u64,
23 key: u64,
24 bytes: u64,
25 deadline: u64,
26 ok: u64,
27 ) -> Result<(u64, [u64; 8]), PagerError> {
28 let now = u64::try_from(self.start.elapsed().as_nanos())
29 .map_err(|_| PagerError::Layout("ribbon clock overflow".into()))?;
30 let request = [op, key, bytes, deadline, ok, 0, now, 0];
31 let mut out = [0; 8];
32 let mut result = 0;
33 // SAFETY: generated binding; distinct, aligned, live arrays of the declared lengths.
34 let trap = unsafe {
35 native::omega_pipeline(
36 &mut result,
37 self.state.as_mut_ptr(),
38 4096,
39 request.as_ptr(),
40 8,
41 out.as_mut_ptr(),
42 8,
43 )
44 };
45 if trap != 0 {
46 return Err(PagerError::Layout(format!("Omega ribbon trap {trap}")));
47 }
48 Ok((result, out))
49 }
50
51 fn exact(
52 &mut self,
53 op: u64,
54 key: u64,
55 bytes: u64,
56 deadline: u64,
57 ok: u64,
58 ) -> Result<[u64; 8], PagerError> {
59 let (code, out) = self.call(op, key, bytes, deadline, ok)?;
60 if code != 0 {
61 return Err(PagerError::Layout(format!(
62 "Omega ribbon operation {op} refused {code}"
63 )));
64 }
65 Ok(out)
66 }
67}
68
69impl ExpertPager {
70 fn pipeline_submit(
71 &self,
72 ctrl: &mut Controller,
73 reads: &mut [Option<Ticket>],
74 layer: u16,
75 experts: &[u16],
76 ) -> Result<bool, PagerError> {
77 let mut submitted = false;
78 loop {
79 let (code, action) = ctrl.call(3, 0, 0, 0, 0)?;
80 if code == 1 {
81 return Ok(submitted);
82 }
83 if code != 0 {
84 return Err(PagerError::Layout(format!("ribbon read refused {code}")));
85 }
86 let pos = action[1] as usize;
87 let idx = self.index_of[&(layer, experts[pos])];
88 reads[pos] = Some(self.reader.submit(idx).map_err(|err| PagerError::Read {
89 id: (layer, experts[pos]),
90 err,
91 })?);
92 submitted = true;
93 }
94 }
95 /// Run each exact expert as soon as its verified copy is visible. The caller
96 /// writes results by router position; completion order never changes routing
97 /// or the final reduction order. All slots remain pinned until this call ends.
98 pub fn for_each_ready(
99 &self,
100 layer: u16,
101 experts: &[u16],
102 buffers: usize,
103 mut consume: impl FnMut(usize, u32, SlotVersion) -> Result<(), String>,
104 ) -> Result<(), PagerError> {
105 if experts.is_empty()
106 || experts.len() > 64
107 || !(1..=2).contains(&buffers)
108 || self.reader.queue_depth() < buffers
109 {
110 return Err(PagerError::Layout("invalid Omega ribbon bounds".into()));
111 }
112 let mut out = vec![None; experts.len()];
113 let mut fetch = Vec::new();
114 let wait_start = Instant::now();
115 {
116 let mut r = self.res.lock().unwrap();
117 for (pos, &expert) in experts.iter().enumerate() {
118 let id = (layer, expert);
119 if !self.index_of.contains_key(&id) {
120 self.undo(&mut r, &out, &fetch);
121 return Err(PagerError::UnknownExpert(id));
122 }
123 loop {
124 match r.acquire(id) {
125 Acquire::Hit { slot, ver } => {
126 out[pos] = Some((slot, ver));
127 break;
128 }
129 Acquire::Fetch { slot, .. } => {
130 fetch.push((pos, slot, id));
131 break;
132 }
133 Acquire::Pending => {
134 let Some(left) = self.read_deadline.checked_sub(wait_start.elapsed())
135 else {
136 self.undo(&mut r, &out, &fetch);
137 return Err(PagerError::Read {
138 id,
139 err: ReadError::Deadline,
140 });
141 };
142 r = self.fetch_done.wait_timeout(r, left).unwrap().0;
143 }
144 Acquire::Exhausted => {
145 let capacity = r.capacity();
146 self.undo(&mut r, &out, &fetch);
147 return Err(PagerError::Exhausted { id, capacity });
148 }
149 }
150 }
151 }
152 }
153 let mut reads: Vec<Option<Ticket>> = (0..experts.len()).map(|_| None).collect();
154 let mut ready: Vec<Option<VerifiedExpert>> = (0..experts.len()).map(|_| None).collect();
155 let mut tickets = vec![0; experts.len()];
156 let start = Instant::now();
157 let mut consumed_ns = 0;
158 let mut ctrl = Controller {
159 state: Box::new([0; 4096]),
160 start,
161 };
162 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
163 let deadline = u64::try_from(self.read_deadline.as_nanos())
164 .map_err(|_| PagerError::Layout("ribbon deadline overflow".into()))?;
165 let bytes = self.reader.staging_capacity() as u64;
166 if !fetch.is_empty() {
167 ctrl.exact(
168 1,
169 fetch.len() as u64,
170 bytes
171 .checked_mul(buffers as u64)
172 .ok_or_else(|| PagerError::Layout("ribbon byte budget overflow".into()))?,
173 buffers as u64,
174 0,
175 )?;
176 for &(pos, _, _) in &fetch {
177 tickets[pos] = ctrl.exact(2, pos as u64, bytes, deadline, 0)?[0];
178 }
179 }
180 let mut done = vec![false; experts.len()];
181 let mut count = 0;
182 // The synchronous control must also serialize cache-hit computation
183 // against reads for misses. Consume its hits before starting any I/O.
184 if buffers == 1 {
185 for pos in 0..experts.len() {
186 if tickets[pos] == 0 {
187 let (slot, ver) = out[pos].unwrap();
188 let consuming = Instant::now();
189 consume(pos, slot, ver).map_err(PagerError::Layout)?;
190 consumed_ns += consuming.elapsed().as_nanos() as u64;
191 done[pos] = true;
192 count += 1;
193 }
194 }
195 }
196 while count < experts.len() {
197 let mut progress = false;
198 if !fetch.is_empty() {
199 progress |= self.pipeline_submit(&mut ctrl, &mut reads, layer, experts)?;
200 for &(pos, _, id) in &fetch {
201 if let Some(read) = &reads[pos] {
202 match read.try_wait() {
203 Ok(Some(value)) => {
204 ctrl.exact(4, tickets[pos], 0, 0, 1)?;
205 reads[pos] = None;
206 ready[pos] = Some(value);
207 progress = true;
208 }
209 Ok(None) => {}
210 Err(err) => {
211 let _ = ctrl.call(4, tickets[pos], 0, 0, 0);
212 return Err(PagerError::Read { id, err });
213 }
214 }
215 }
216 }
217 loop {
218 let (code, action) = ctrl.call(5, 0, 0, 0, 0)?;
219 if code == 1 {
220 break;
221 }
222 if code != 0 {
223 return Err(PagerError::Layout(format!("ribbon copy refused {code}")));
224 }
225 let pos = action[1] as usize;
226 let (_, slot, id) =
227 fetch.iter().find(|x| x.0 == pos).copied().ok_or_else(|| {
228 PagerError::Layout("ribbon unknown copy position".into())
229 })?;
230 let value = ready[pos].take().ok_or_else(|| {
231 PagerError::Layout("ribbon copy without verified bytes".into())
232 })?;
233 let t = Instant::now();
234 let payload = value.payload();
235 let parts = self.layouts[value.index]
236 .parts(&payload)
237 .map_err(|e| PagerError::Layout(e.to_string()))?;
238 let ver = self
239 .backend
240 .load(slot, id, &parts)
241 .map_err(|err| PagerError::Backend { id, err })?;
242 ctrl.exact(6, tickets[pos], 0, 0, 1)?;
243 drop(parts);
244 drop(payload);
245 drop(value);
246 // Only the two-buffer mode looks ahead while the GPU consumes
247 // this expert. One buffer is the synchronous control: refill
248 // on the next loop, after consumption has retired.
249 if buffers == 2 {
250 self.pipeline_submit(&mut ctrl, &mut reads, layer, experts)?;
251 }
252 // Completion can acknowledge an expired copy without granting
253 // publication. Obtain the ready-state pin before exposing it.
254 ctrl.exact(7, tickets[pos], 0, 0, 0)?;
255 self.res.lock().unwrap().fetched(slot, ver);
256 out[pos] = Some((slot, ver));
257 self.fetch_done.notify_all();
258 {
259 let mut stats = self.stats.lock().unwrap();
260 stats.slot_load_ns += t.elapsed().as_nanos() as u64;
261 stats.bytes_loaded += self.manifest.experts[self.index_of[&id]].len;
262 }
263 let consuming = Instant::now();
264 consume(pos, slot, ver).map_err(PagerError::Layout)?;
265 consumed_ns += consuming.elapsed().as_nanos() as u64;
266 ctrl.exact(8, tickets[pos], 0, 0, 0)?;
267 ctrl.exact(9, tickets[pos], 0, 0, 0)?;
268 done[pos] = true;
269 count += 1;
270 progress = true;
271 }
272 }
273 // Cache hits need no staging operation. Preserve their pre-acquired pins.
274 for pos in 0..experts.len() {
275 if !done[pos] && tickets[pos] == 0 {
276 let (slot, ver) = out[pos].unwrap();
277 let consuming = Instant::now();
278 consume(pos, slot, ver).map_err(PagerError::Layout)?;
279 consumed_ns += consuming.elapsed().as_nanos() as u64;
280 done[pos] = true;
281 count += 1;
282 progress = true;
283 }
284 }
285 if !progress {
286 if start.elapsed() >= self.read_deadline {
287 return Err(PagerError::Read {
288 id: (layer, experts[0]),
289 err: ReadError::Deadline,
290 });
291 }
292 std::thread::sleep(Duration::from_micros(50));
293 }
294 }
295 Ok(())
296 }));
297 // A worker owns its buffer until it actually finishes. Cancelling a ticket
298 // only requests cancellation; dropping the receiver never frees its buffer.
299 for read in reads.iter().flatten() {
300 read.cancel();
301 }
302 let _ = ctrl.call(11, 0, 0, 0, 0);
303 {
304 let mut r = self.res.lock().unwrap();
305 for entry in out.iter().flatten() {
306 r.release(entry.0);
307 }
308 for &(pos, slot, _) in &fetch {
309 if out[pos].is_none() {
310 r.fetch_failed(slot);
311 }
312 }
313 }
314 self.fetch_done.notify_all();
315 let mut stats = self.stats.lock().unwrap();
316 stats.requests += 1;
317 stats.experts_hit += (experts.len() - fetch.len()) as u64;
318 stats.experts_missed += fetch.len() as u64;
319 stats.miss_wall_ns += (start.elapsed().as_nanos() as u64).saturating_sub(consumed_ns);
320 match result {
321 Ok(value) => value,
322 Err(payload) => {
323 drop(stats);
324 std::panic::resume_unwind(payload)
325 }
326 }
327 }
328}