use super::{gpu_err, CudaLayer, Qwen35BatchBufs, Qwen35CudaModel, Qwen35CudaState, Result};
use crate::cuda::CudaExecutor;
use std::collections::HashMap;
use trueno_gpu::driver::CudaGraphExec;
const MAX_GRAPHS: usize = 32;
type GraphKey = Vec<u64>;
const SCRATCH_AT: usize = 3;
pub(crate) struct Qwen35BatchGraphs {
enabled: bool,
graphs: HashMap<GraphKey, CudaGraphExec>,
replays: u64,
captures: u64,
}
impl Default for Qwen35BatchGraphs {
fn default() -> Self {
Self {
enabled: std::env::var("QWEN35_CUDA_BATCH_GRAPH").map_or(true, |v| v != "0"),
graphs: HashMap::new(),
replays: 0,
captures: 0,
}
}
}
impl Qwen35BatchGraphs {
pub(super) fn clear(&mut self) {
self.graphs.clear();
}
}
impl Qwen35CudaModel<'_> {
pub fn set_batch_graph(&mut self, on: bool) {
self.batch_graphs.enabled = on;
if !on {
self.batch_graphs.graphs.clear();
}
}
pub fn batch_graph_counts(&self) -> (u64, u64) {
(self.batch_graphs.replays, self.batch_graphs.captures)
}
fn batch_graph_key(
&mut self,
b: &Qwen35BatchBufs,
positions: &[usize],
) -> std::result::Result<Option<GraphKey>, trueno_gpu::GpuError> {
let d = self.dims;
if !self.batch_graphs.enabled
|| !CudaExecutor::gdn_decode_attention_has_slots(d.attn_head_dim)
{
return Ok(None);
}
let m = positions.len() as u32;
let (splits, _) = if self
.layers
.iter()
.any(|l| matches!(l, CudaLayer::Attention(_)))
{
let max_pos = positions.iter().copied().max().unwrap_or(0);
self.executor.reserve_attention_slots(
(d.num_heads, d.num_kv_heads, d.attn_head_dim),
u32::try_from(max_pos).unwrap_or(u32::MAX),
m,
)?
} else {
(0, 0)
};
let mut key = vec![u64::from(m), u64::from(splits), b.hidden.as_ptr()];
key.extend(self.executor.graph_scratch_ptrs());
Ok(Some(key))
}
pub(super) fn batched_graphed(
&mut self,
b: &Qwen35BatchBufs,
states: &[Qwen35CudaState],
positions: &[usize],
) -> Result<bool> {
let key = self
.batch_graph_key(b, positions)
.map_err(|e| gpu_err("qwen35_cuda_batch_graph", &e))?;
let Some(key) = key else {
return Ok(false);
};
if let Some(exec) = self.batch_graphs.graphs.get(&key) {
self.executor
.launch_graph_exec(exec)
.map_err(|e| gpu_err("qwen35_cuda_batch_graph_replay", &e))?;
self.batch_graphs.replays += 1;
return Ok(true);
}
if self.batch_graphs.graphs.len() >= MAX_GRAPHS {
self.batch_graphs.graphs.clear();
}
self.executor.forget_q8_activation();
self.executor.begin_graph_recording();
let body = self.batched_body(b, states, positions, true);
let built = self.executor.end_graph_recording();
body.map_err(|e| gpu_err("qwen35_cuda_batch_graph_capture", &e))?;
let kernels = built.map_err(|e| gpu_err("qwen35_cuda_batch_graph_build", &e))?;
let exec = if kernels > 0 {
self.executor.take_decode_graph()
} else {
None
};
let settled = key[SCRATCH_AT..] == self.executor.graph_scratch_ptrs()[..];
if let (Some(exec), true) = (exec, settled) {
self.batch_graphs.graphs.insert(key, exec);
self.batch_graphs.captures += 1;
}
Ok(true)
}
}
#[cfg(test)]
#[path = "forward_qwen35_cuda_batch_graph_tests.rs"]
mod tests;