Skip to content
Open
5 changes: 5 additions & 0 deletions helios/src/cuda.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1125,6 +1125,11 @@ impl Stream {
})
}

pub(crate) fn with_context<T>(&self, operation: impl FnOnce() -> Result<T>) -> Result<T> {
// SAFETY: `self.context` is the CUDA context bound when this stream was opened and outlives it.
unsafe { self.driver.with_context(self.context, operation) }
}

pub(crate) fn synchronize(&self) -> Result<()> {
self.driver.check("cuStreamSynchronize", unsafe {
(self.driver.stream_synchronize)(self.handle as Handle)
Expand Down
121 changes: 100 additions & 21 deletions helios/src/execution/parallel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,56 @@ fn read_identity(bytes: &[u8]) -> Result<(Fence, usize)> {
Ok(value)
}

fn apply_peer_message(
pending: &mut VecDeque<Pending>,
manifest: &ExecutionManifest,
index: usize,
tag: u8,
bytes: Vec<u8>,
) -> Result<()> {
if tag == READY {
let (fence, graph) = read_identity(&bytes)?;
ready_frame(pending, index, fence, graph)?;
} else if tag == COMPLETE {
let mut reader = Reader(&bytes);
let fence = Fence(reader.number()? as u64);
let graph = reader.number()?;
let timing = wire::timing(&mut reader)?;
let proposal_confidence = wire::proposal_confidence(
&mut reader,
manifest.request_capacity(),
manifest.completion_token_capacity,
)?;
let speculative_survival = wire::speculative_survival(
&mut reader,
manifest.request_capacity(),
manifest.completion_token_capacity,
)?;
if reader.0.len() != manifest.completion_bytes() {
return Err(invalid("rank completion size differs from its ABI"));
}
let completion = FrameCompletion {
logprobs: None,
prompt_logprobs: None,
proposal_confidence,
speculative_survival,
fence,
graph_index: graph,
timing,
records: super::transport::decode_records(
reader.0,
fence,
manifest.request_capacity(),
manifest.completion_fields(),
)?,
};
protocol::record_peer_completion(pending, index, completion)?;
} else {
return Err(invalid("unexpected rank message"));
}
Ok(())
}

/// Rank zero owns request scheduling; peer processes execute identical graph steps.
/// Two frame slots include preparation and unconsumed all-rank completions.
pub struct TensorParallelExecutor {
Expand Down Expand Up @@ -234,6 +284,49 @@ impl TensorParallelExecutor {
&& self.local.can_submit(grammar)
}

#[cfg(feature = "server")]
pub(crate) fn zero_kv_pages(&mut self, pages: &[u32]) -> Result<()> {
if pages.is_empty() {
return Ok(());
}
if let Some(error) = &self.poison {
return Err(error.clone());
}
if self.shutdown.is_some() {
return Err(invalid("tensor-parallel executor is closed"));
}
let result = (|| -> Result<()> {
let payload = wire::encode_page_ids(pages)?;
for peer in &mut self.peers {
peer.channel.nonblocking(false)?;
peer.channel.send(ZERO_KV_PAGES, &payload)?;
}
self.local.zero_kv_pages(pages)?;
let manifest = self.local.manifest();
for (index, peer) in self.peers.iter_mut().enumerate() {
let deadline = std::time::Instant::now() + TIMEOUT;
loop {
let (tag, bytes) = peer.channel.wait(false)?;
if tag == ZEROED_KV_PAGES {
if !bytes.is_empty() {
return Err(invalid("unexpected zero_kv_pages reply payload"));
}
break;
}
apply_peer_message(&mut self.pending, manifest, index, tag, bytes)?;
if std::time::Instant::now() >= deadline {
return Err(invalid("rank zero_kv_pages deadline expired"));
}
}
}
Ok(())
})();
if let Err(error) = &result {
self.poison = Some(error.clone());
}
result
}

pub fn next_fence(&self) -> Result<Fence> {
if let Some(error) = &self.poison {
return Err(error.clone());
Expand Down Expand Up @@ -322,31 +415,12 @@ impl TensorParallelExecutor {
if let Some(completion) = self.local.poll()? {
protocol::record_local_completion(&mut self.pending, completion)?;
}
let manifest = self.local.manifest();
for (index, peer) in self.peers.iter_mut().enumerate() {
peer.channel.nonblocking(true)?;
let result = (|| -> Result<()> {
while let Some((tag, bytes)) = peer.channel.poll()? {
if tag == READY {
let (fence, graph) = read_identity(&bytes)?;
ready_frame(&mut self.pending, index, fence, graph)?;
} else if tag == COMPLETE {
let mut reader = Reader(&bytes);
let fence = Fence(reader.number()? as u64);
let graph = reader.number()?;
let timing = wire::timing(&mut reader)?;
let proposal_confidence = wire::proposal_confidence(&mut reader, self.local.manifest().request_capacity(), self.local.manifest().completion_token_capacity)?;
let speculative_survival = wire::speculative_survival(&mut reader, self.local.manifest().request_capacity(), self.local.manifest().completion_token_capacity)?;
if reader.0.len() != self.local.manifest().completion_bytes() {
return Err(invalid("rank completion size differs from its ABI"));
}
let completion = FrameCompletion {
logprobs: None, prompt_logprobs: None, proposal_confidence, speculative_survival,
fence, graph_index: graph, timing,
records: super::transport::decode_records(reader.0, fence,
self.local.manifest().request_capacity(), self.local.manifest().completion_fields())?,
};
protocol::record_peer_completion(&mut self.pending, index, completion)?;
} else { return Err(invalid("unexpected rank message")); }
apply_peer_message(&mut self.pending, manifest, index, tag, bytes)?;
}
Ok(())
})();
Expand Down Expand Up @@ -670,6 +744,11 @@ pub unsafe fn serve_rank(
leases.track(Some(fence), guard);
started.push_back(Instant::now());
}
ZERO_KV_PAGES => {
let pages = wire::decode_page_ids(&bytes)?;
executor.zero_kv_pages(&pages)?;
channel.send(ZEROED_KV_PAGES, &[])?;
}
_ => return Err(invalid("unexpected rank command")),
}
}
Expand Down
70 changes: 69 additions & 1 deletion helios/src/execution/parallel/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ fn prepare_packets_preserve_large_and_partial_uploads_on_both_transports() {
manifest.graphs[0].input_bindings[2].nbytes = buffer.nbytes;
manifest.input_frame_bytes = 16 + buffer.nbytes;
manifest.validate().unwrap();
assert_eq!(u64::from_le_bytes(layout(&manifest)[..8].try_into().unwrap()), 6);
assert_eq!(u64::from_le_bytes(layout(&manifest)[..8].try_into().unwrap()), 7);
for (sender, receiver) in [crate::execution::rank_stream::test_pair().unwrap(),
(client.into(), server.into())] {
let mut sender = Channel::new(sender).unwrap();
Expand Down Expand Up @@ -833,3 +833,71 @@ fn speculative_agreement_applies_to_speculative_and_speculative_mixed_graphs() {
manifest.graphs[0].token_capacity = 1;
assert!(uses_speculative_agreement(&manifest.graphs[0]));
}

#[test]
fn zero_kv_pages_wire_roundtrip_and_truncation() {
let pages = [7u32, 0, 42, 1024, u32::MAX];
let encoded = wire::encode_page_ids(&pages).unwrap();
assert_eq!(wire::decode_page_ids(&encoded).unwrap(), pages);
assert_eq!(wire::decode_page_ids(&[]).unwrap(), Vec::<u32>::new());
assert!(wire::decode_page_ids(&[1, 2, 3]).is_err());

let (client, server) = crate::execution::rank_stream::test_pair().unwrap();
let mut tx = Channel::new(client).unwrap();
let mut rx = Channel::new(server).unwrap();
tx.send(ZERO_KV_PAGES, &encoded).unwrap();
let (tag, body) = rx.wait(false).unwrap();
assert_eq!(tag, ZERO_KV_PAGES);
assert_eq!(wire::decode_page_ids(&body).unwrap(), pages);
rx.send(ZEROED_KV_PAGES, &[]).unwrap();
assert!(tx.receive(ZEROED_KV_PAGES).unwrap().is_empty());
}

#[test]
fn zero_reply_interleaved_with_control_frames_keeps_control_frames() {
// Mirrors TensorParallelExecutor::zero_kv_pages: the wait for ZEROED_KV_PAGES
// must consume interleaved READY/COMPLETE control frames into the pending
// queue rather than dropping them or mistaking them for the reply.
let manifest = super::super::tests::manifest();
let (sender, receiver) = crate::execution::rank_stream::test_pair().unwrap();
let mut sender = Channel::new(sender).unwrap();
let mut receiver = Channel::new(receiver).unwrap();

// Rank 0 submitted frame 1 (awaiting READY) and committed frame 3 (awaiting
// the peer's COMPLETE); both must survive the zeroing wait.
let mut pending = std::collections::VecDeque::new();
for (fence, graph, committed) in [(Fence(3), 2usize, true), (Fence(1), 0usize, false)] {
pending.push_back(Pending {
fence,
graph,
grammar: false,
uploads: Vec::new(),
dispatched: std::time::Instant::now(),
committed,
queued: false,
ready: vec![false; 1],
completions: (0..=1).map(|_| None).collect(),
});
}

sender.send(READY, &identity(Fence(1), 0)).unwrap();
sender.send(COMPLETE, &completion(&completed(1))).unwrap();
sender.send(ZEROED_KV_PAGES, &[]).unwrap();

loop {
let (tag, bytes) = receiver.wait(false).unwrap();
if tag == ZEROED_KV_PAGES {
assert!(bytes.is_empty(), "the zero reply carries no payload");
break;
}
apply_peer_message(&mut pending, &manifest, 0, tag, bytes).unwrap();
}
assert!(pending[0].completions[1].is_some(), "COMPLETE recorded on the committed frame");
assert!(pending[1].ready[0], "READY recorded on the draining frame");

// A payload on the reply tag is rejected, and an unknown tag is not swallowed.
sender.send(ZEROED_KV_PAGES, &[1]).unwrap();
let (tag, bytes) = receiver.wait(false).unwrap();
assert_eq!((tag, bytes), (ZEROED_KV_PAGES, vec![1]));
assert!(apply_peer_message(&mut std::collections::VecDeque::new(), &manifest, 0, 0xFE, Vec::new()).is_err());
}
31 changes: 30 additions & 1 deletion helios/src/execution/parallel/wire.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ pub(super) const PREPARE_MORE: u8 = 10;
pub(super) const TUNE: u8 = 11;
pub(super) const TUNED: u8 = 12;
pub(super) const STARTED: u8 = 13;
pub(super) const ZERO_KV_PAGES: u8 = 14;
pub(super) const ZEROED_KV_PAGES: u8 = 15;
const MAX_PACKET: usize = 64 * 1024 * 1024;
pub(super) const TIMEOUT: Duration = Duration::from_secs(120);

Expand Down Expand Up @@ -183,7 +185,9 @@ pub(super) fn validate_completion_packet(manifest: &ExecutionManifest) -> Result
pub(super) fn layout(manifest: &ExecutionManifest) -> Vec<u8> {
let mut bytes = Vec::new();
for value in [
6,
// 7: adds ZERO_KV_PAGES/ZEROED_KV_PAGES, so a patched rank cannot
// pass HELLO against an unpatched peer and fail on the first eviction.
7,
manifest.completion_token_capacity,
manifest.max_active,
manifest.input_frame_bytes,
Expand Down Expand Up @@ -495,3 +499,28 @@ pub(super) fn timing(reader: &mut Reader<'_>) -> Result<super::super::ExecutionT
queued: queued == 1,
})
}

#[cfg(any(feature = "server", test))]
pub(super) fn encode_page_ids(pages: &[u32]) -> Result<Vec<u8>> {
let byte_len = pages
.len()
.checked_mul(size_of::<u32>())
.filter(|&n| n <= MAX_PACKET)
.ok_or_else(|| invalid("zero_kv_pages packet exceeds its size limit"))?;
let mut bytes = Vec::with_capacity(byte_len);
for &page in pages {
bytes.extend_from_slice(&page.to_le_bytes());
}
Ok(bytes)
}

pub(super) fn decode_page_ids(bytes: &[u8]) -> Result<Vec<u32>> {
if !bytes.len().is_multiple_of(size_of::<u32>()) {
return Err(invalid("truncated zero_kv_pages control packet"));
}
let mut pages = Vec::with_capacity(bytes.len() / size_of::<u32>());
for chunk in bytes.chunks_exact(size_of::<u32>()) {
pages.push(u32::from_le_bytes(chunk.try_into().unwrap()));
}
Ok(pages)
}
14 changes: 14 additions & 0 deletions helios/src/execution/ranks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,15 @@ impl RankExecutorInner {
}
}

#[cfg(feature = "server")]
fn zero_kv_pages(&mut self, pages: &[u32]) -> Result<()> {
match self {
Self::Local(executor) => executor.zero_kv_pages(pages),
Self::Parallel(executor) => executor.zero_kv_pages(pages),
Self::Threaded(executor) => executor.zero_kv_pages(pages),
}
}

fn close(&mut self) -> Shutdown {
match self {
Self::Local(executor) => executor.close(),
Expand Down Expand Up @@ -188,6 +197,11 @@ impl RankExecutor {
self.inner.next_fence()
}

#[cfg(feature = "server")]
pub(crate) fn zero_kv_pages(&mut self, pages: &[u32]) -> Result<()> {
self.inner.zero_kv_pages(pages)
}

pub(crate) fn close(&mut self) -> Shutdown {
let shutdown = self.inner.close();
self.leases.clear();
Expand Down
Loading