use super::*;
#[must_use]
fn evaluate_router_lane(workload: ExecutionWorkloadFeatures) -> ExecutionLane {
let mut router: AdaptiveExecutionRouter = AdaptiveExecutionRouter::default();
let mut active_lane: ExecutionLane = router.get_active_lane();
for step_idx in 0..AB_ROUTER_WARMUP_STEPS {
let now_ms: u64 = ((step_idx as u64).saturating_add(1)).saturating_mul(AB_ROUTER_STEP_MS);
let decision: ExecutionRouterDecision = router.evaluate(workload, now_ms);
active_lane = decision.get_active_lane();
}
active_lane
}
#[must_use]
fn build_parallel_ab_compute_scene(
mode: GpuLayoutMode,
child_count: usize,
grid_cols: f32,
viewport_width: f32,
viewport_height: f32,
) -> GpuComputeSceneInput {
let total_nodes: usize = child_count.saturating_add(1);
let mut nodes: Vec<GpuLayoutNodeInput> = Vec::with_capacity(total_nodes);
let mut visuals: Vec<GpuVisualStyleInput> = Vec::with_capacity(total_nodes);
let root_flags: u32 = pack_gpu_layout_flags(
mode,
GpuJustifyMode::Start,
GpuAlignMode::Start,
true,
true,
true,
);
let mut root_node: GpuLayoutNodeInput = GpuLayoutNodeInput::default();
root_node
.set_parent_bfs(GPU_LAYOUT_NO_PARENT)
.set_first_child(1)
.set_child_count(child_count as u32)
.set_flags_kind(root_flags)
.set_pref_min_size([viewport_width, viewport_height, 0.0, 0.0])
.set_pad_gap_flex([8.0, 8.0, 4.0, 4.0])
.set_extra_or_intrinsic([grid_cols, 0.0, 0.0, 0.0]);
nodes.push(root_node);
let mut root_vis: GpuVisualStyleInput = GpuVisualStyleInput::default();
root_vis
.set_color_rgba(GpuPrimitiveInstance::pack_color_rgba8(Color::rgb(
18, 24, 38,
)))
.set_uv_rect([0, 0, u16::MAX, u16::MAX])
.set_radii_border([GpuPrimitiveInstance::pack_u16_q4(6.0); 4])
.set_kind_flags(GpuPrimitiveInstance::pack_kind_flags(
PrimKind::RoundedRect,
0,
0,
0,
))
.set_clip_ancestor_bfs(GPU_LAYOUT_NO_PARENT)
.set_opacity_q16(u16::MAX as u32);
visuals.push(root_vis);
let child_mode: GpuLayoutMode = match mode {
GpuLayoutMode::DataViz => GpuLayoutMode::DataViz,
GpuLayoutMode::Spring => GpuLayoutMode::Spring,
_ => GpuLayoutMode::Block,
};
let child_flags: u32 = pack_gpu_layout_flags(
child_mode,
GpuJustifyMode::Start,
GpuAlignMode::Start,
true,
true,
true,
);
let cell_kind_flags: u32 =
GpuPrimitiveInstance::pack_kind_flags(PrimKind::RoundedRect, 0, 0, 0);
let cell_radii: [u16; 4] = [GpuPrimitiveInstance::pack_u16_q4(4.0); 4];
for child_idx in 0..child_count {
let mut node: GpuLayoutNodeInput = GpuLayoutNodeInput::default();
node.set_parent_bfs(0)
.set_first_child(0)
.set_child_count(0)
.set_flags_kind(child_flags);
match mode {
GpuLayoutMode::Spring => {
let col: f32 = (child_idx % 200) as f32;
let row: f32 = (child_idx / 200) as f32;
let cur_x: f32 = (col * 6.0) % 1260.0;
let cur_y: f32 = (row * 4.0) % 780.0;
node.set_pref_min_size([cur_x + 12.0, cur_y + 8.0, 5.0, 3.0])
.set_pad_gap_flex([160.0, 16.0, 0.0, 0.0])
.set_extra_or_intrinsic([cur_x, cur_y, 1.0, 0.0]);
}
GpuLayoutMode::DataViz => {
node.set_pref_min_size([8.0, 16.0, 0.0, 0.0])
.set_pad_gap_flex([0.0, 0.0, 0.0, 0.0])
.set_extra_or_intrinsic([
((child_idx + 1) as f32) / (child_count.max(1) as f32),
0.0,
0.0,
0.0,
]);
}
_ => {
if grid_cols >= 64.0 {
node.set_pref_min_size([6.0, 5.0, 4.0, 4.0])
.set_pad_gap_flex([1.0, 1.0, 0.0, 1.0])
.set_extra_or_intrinsic([0.0, 0.0, 6.0, 5.0]);
} else {
node.set_pref_min_size([48.0, 24.0, 16.0, 16.0])
.set_pad_gap_flex([2.0, 2.0, 0.0, 1.0])
.set_extra_or_intrinsic([0.0, 0.0, 48.0, 24.0]);
}
}
}
nodes.push(node);
let mut vis: GpuVisualStyleInput = GpuVisualStyleInput::default();
vis.set_color_rgba(GpuPrimitiveInstance::pack_color_rgba8(Color::rgb(
36 + ((child_idx * 13) % 180) as u8,
116,
224,
)))
.set_uv_rect([0, 0, u16::MAX, u16::MAX])
.set_radii_border(cell_radii)
.set_kind_flags(cell_kind_flags)
.set_clip_ancestor_bfs(GPU_LAYOUT_NO_PARENT)
.set_opacity_q16(u16::MAX as u32);
visuals.push(vis);
}
let mut scene: GpuComputeSceneInput = GpuComputeSceneInput::default();
scene
.set_nodes(nodes)
.set_visuals(visuals)
.set_level_offsets(vec![0, 1, total_nodes as u32])
.set_viewport_size([viewport_width, viewport_height])
.set_root_boundary_rect([0.0, 0.0, viewport_width, viewport_height])
.set_dt_secs(1.0 / 120.0)
.set_clear_color(Color::rgb(10, 14, 24));
scene
}
#[must_use]
fn build_parallel_ab_card_tree(card_count: usize, heavy_text: bool) -> (SceneTree, NodeId) {
let mut tree: SceneTree = SceneTree::default();
let root: NodeId = tree.get_root();
let mut root_style: Style = Style::default().column();
root_style
.get_mut_layout()
.set_width(Length::Percent(100.0));
root_style.get_mut_layout().set_row_gap(4.0);
tree.set_style(root, root_style);
let mut card_style: Style = Style::default().column();
card_style
.get_mut_layout()
.set_width(Length::Percent(100.0));
card_style.get_mut_layout().set_padding(Edges::all(8.0));
card_style
.get_mut_paint()
.set_background(Some(Color::rgb(24, 30, 44)));
let mut body_style: Style = Style::default();
body_style
.get_mut_layout()
.set_width(Length::Percent(100.0));
body_style.get_mut_text().set_font_size(13.0);
body_style.get_mut_text().set_overflow(TextOverflow::Wrap);
let mut last_leaf: NodeId = root;
for card_idx in 0..card_count {
let card: NodeId = tree.create_view(card_style);
tree.append_child(root, card);
let content: String = if heavy_text {
format!("{AB_CARD_PREFIX_LABEL} #{card_idx}: {AB_MIXED_TEXT_COPY}")
} else {
format!("{AB_CARD_PREFIX_LABEL} #{card_idx}")
};
let leaf: NodeId = tree.create_text(content, body_style);
tree.append_child(card, leaf);
last_leaf = leaf;
}
(tree, last_leaf)
}
#[must_use]
fn max_layout_box_slice_error(first: &[LayoutBox], second: &[LayoutBox]) -> f32 {
let mut max_err: f32 = 0.0;
for (left, right) in first.iter().zip(second.iter()) {
let lb: Rect = left.get_bounds();
let rb: Rect = right.get_bounds();
max_err = max_err
.max((lb.get_x() - rb.get_x()).abs())
.max((lb.get_y() - rb.get_y()).abs())
.max((lb.get_width() - rb.get_width()).abs())
.max((lb.get_height() - rb.get_height()).abs());
}
max_err
}
#[must_use]
pub fn run_parallel_ab1_sparse_reactive(
gpu_engine: &mut GpuComputeLayoutEngine,
worker_threads: usize,
iterations: usize,
) -> ParallelAbCaseResult {
let iters: usize = iterations.max(4);
let (mut tree, leaf_node): (SceneTree, NodeId) =
build_parallel_ab_card_tree(AB_SPARSE_NODE_COUNT / 2, false);
let viewport: Size = Size::new(1280.0, 800.0);
let mut layout_engine: LayoutEngine = LayoutEngine::default();
let _: LayoutStats = layout_engine.compute_serial(&mut tree, viewport);
let mut steady_allocs: usize = usize::MAX;
let start_serial: Instant = Instant::now();
for iter_idx in 0..iters {
let next_text: &str = if iter_idx % 2 == 0 {
AB_SPARSE_LEAF_A
} else {
AB_SPARSE_LEAF_B
};
let (_, snap): (LayoutStats, AllocationSnapshot) = measure_allocations(|| {
tree.set_text_str(leaf_node, next_text);
layout_engine.compute_serial(&mut tree, viewport)
});
if iter_idx > 0 {
steady_allocs = steady_allocs.min(snap.get_alloc_count() as usize);
}
}
if steady_allocs == usize::MAX {
steady_allocs = 0;
}
let serial_us: f64 = (start_serial.elapsed().as_secs_f64() * 1_000_000.0) / (iters as f64);
let gpu_scene: GpuComputeSceneInput = build_parallel_ab_compute_scene(
GpuLayoutMode::Grid,
AB_SPARSE_NODE_COUNT,
8.0,
1280.0,
800.0,
);
let _: GpuComputeDispatchResult = gpu_engine.dispatch(&gpu_scene, true);
let mut gpu_exec_ns: u64 = 0;
let mut draw_calls: usize = 0;
let start_gpu: Instant = Instant::now();
for _ in 0..iters {
let res: GpuComputeDispatchResult =
gpu_engine.dispatch_steady_indirect(&gpu_scene, true, false);
gpu_exec_ns = res
.get_gpu_compute_ns()
.saturating_add(res.get_gpu_render_ns());
draw_calls = res.get_draw_calls();
}
let gpu_us: f64 = (start_gpu.elapsed().as_secs_f64() * 1_000_000.0) / (iters as f64);
let mut workload: ExecutionWorkloadFeatures = ExecutionWorkloadFeatures::default();
workload
.set_dirty_nodes(1)
.set_visible_nodes(AB_SPARSE_NODE_COUNT)
.set_tree_depth(3)
.set_gpu_eligible_nodes(0)
.set_cpu_chrome_nodes(1)
.set_dirty_upload_bytes(64)
.set_wrapping_text_ratio(0.5)
.set_worker_threads(worker_threads)
.set_gpu_compute_available(gpu_engine.is_hardware_compute_ready())
.set_thermal_throttled(false);
let router_lane: ExecutionLane = evaluate_router_lane(workload);
let speedup_ratio: f64 = if serial_us > 0.0 {
gpu_us / serial_us
} else {
0.0
};
let hw_ready: bool = gpu_engine.is_hardware_compute_ready();
let gpu_verified: bool = !hw_ready || (gpu_exec_ns > 0 && draw_calls > 0 && serial_us < gpu_us);
let passed: bool =
router_lane == ExecutionLane::CpuSerial && steady_allocs == 0 && gpu_verified;
ParallelAbCaseResult {
name: PARALLEL_AB1_NAME.to_string(),
arm_a_label: AB_ARM_CPU_SERIAL.to_string(),
arm_b_label: AB_ARM_GPU_COMPUTE.to_string(),
arm_a_us: serial_us,
arm_b_us: gpu_us,
speedup_ratio,
gpu_exec_ns,
draw_calls,
max_error_px: 0.0,
upload_savings_ratio: 0.0,
steady_state_allocs: steady_allocs,
router_selected_lane: format!("{router_lane:?}"),
passed,
}
}
#[must_use]
pub fn run_parallel_ab2_heavy_text_reflow(
gpu_ready: bool,
worker_threads: usize,
iterations: usize,
) -> ParallelAbCaseResult {
let iters: usize = iterations.max(4);
let (mut serial_tree, _): (SceneTree, NodeId) =
build_parallel_ab_card_tree(AB_TEXT_CARD_COUNT, true);
let (mut parallel_tree, _): (SceneTree, NodeId) =
build_parallel_ab_card_tree(AB_TEXT_CARD_COUNT, true);
let mut serial_engine: LayoutEngine = LayoutEngine::default();
let mut parallel_engine: LayoutEngine = LayoutEngine::default();
let _: LayoutStats = serial_engine.compute_serial(&mut serial_tree, Size::new(1280.0, 800.0));
let _: LayoutStats =
parallel_engine.compute_parallel(&mut parallel_tree, Size::new(1280.0, 800.0));
let start_serial: Instant = Instant::now();
for iter_idx in 0..iters {
let width: f32 = if iter_idx % 2 == 0 { 960.0 } else { 1280.0 };
let _: LayoutStats =
serial_engine.compute_serial(&mut serial_tree, Size::new(width, 800.0));
}
let serial_us: f64 = (start_serial.elapsed().as_secs_f64() * 1_000_000.0) / (iters as f64);
let start_parallel: Instant = Instant::now();
for iter_idx in 0..iters {
let width: f32 = if iter_idx % 2 == 0 { 960.0 } else { 1280.0 };
let _: LayoutStats =
parallel_engine.compute_parallel(&mut parallel_tree, Size::new(width, 800.0));
}
let parallel_us: f64 = (start_parallel.elapsed().as_secs_f64() * 1_000_000.0) / (iters as f64);
let serial_boxes: Vec<LayoutBox> = serial_tree
.get_nodes()
.iter()
.map(SceneNode::get_layout_box)
.collect();
let parallel_boxes: Vec<LayoutBox> = parallel_tree
.get_nodes()
.iter()
.map(SceneNode::get_layout_box)
.collect();
let max_err: f32 = max_layout_box_slice_error(&serial_boxes, ¶llel_boxes);
let mut workload: ExecutionWorkloadFeatures = ExecutionWorkloadFeatures::default();
workload
.set_dirty_nodes(AB_TEXT_CARD_COUNT * 2)
.set_visible_nodes(AB_TEXT_CARD_COUNT * 2)
.set_tree_depth(3)
.set_gpu_eligible_nodes(0)
.set_cpu_chrome_nodes(AB_TEXT_CARD_COUNT * 2)
.set_dirty_upload_bytes(
(AB_TEXT_CARD_COUNT * 2).saturating_mul(GPU_LAYOUT_NODE_INPUT_BYTES),
)
.set_wrapping_text_ratio(0.5)
.set_worker_threads(worker_threads)
.set_gpu_compute_available(gpu_ready)
.set_thermal_throttled(false);
let router_lane: ExecutionLane = evaluate_router_lane(workload);
let speedup_ratio: f64 = if parallel_us > 0.0 {
serial_us / parallel_us
} else {
0.0
};
let expected_lane: ExecutionLane = if worker_threads > 1 {
ExecutionLane::CpuParallel
} else {
ExecutionLane::CpuSerial
};
let passed: bool = router_lane == expected_lane
&& max_err <= AB_PARITY_MAX_ERR_PX
&& (worker_threads <= 1 || speedup_ratio > 1.0);
ParallelAbCaseResult {
name: PARALLEL_AB2_NAME.to_string(),
arm_a_label: AB_ARM_CPU_SERIAL.to_string(),
arm_b_label: AB_ARM_CPU_PARALLEL.to_string(),
arm_a_us: serial_us,
arm_b_us: parallel_us,
speedup_ratio,
gpu_exec_ns: 0,
draw_calls: 0,
max_error_px: max_err,
upload_savings_ratio: 0.0,
steady_state_allocs: 0,
router_selected_lane: format!("{router_lane:?}"),
passed,
}
}
fn rasterize_primitives_into_framebuffer(
fb: &mut Framebuffer,
primitives: &[GpuPrimitiveInstance],
) {
let fb_w: i32 = fb.get_width() as i32;
let fb_h: i32 = fb.get_height() as i32;
let pixels: &mut [u8] = fb.get_mut_pixels().as_mut_slice();
pixels.fill(16);
for prim in primitives.iter() {
let rect: [f32; 4] = prim.get_rect();
let x0: i32 = (rect[0].floor() as i32).clamp(0, fb_w);
let y0: i32 = (rect[1].floor() as i32).clamp(0, fb_h);
let x1: i32 = ((rect[0] + rect[2]).ceil() as i32).clamp(x0, fb_w);
let y1: i32 = ((rect[1] + rect[3]).ceil() as i32).clamp(y0, fb_h);
if x1 <= x0 || y1 <= y0 {
continue;
}
let rgba: [u8; 4] = prim.get_color_rgba().to_le_bytes();
let half_w: f32 = (rect[2] * 0.5).max(0.5);
let half_h: f32 = (rect[3] * 0.5).max(0.5);
let center_x: f32 = rect[0] + half_w;
let center_y: f32 = rect[1] + half_h;
let radius: f32 = ((prim.get_radii_border()[0] as f32) * 0.0625)
.min(half_w)
.min(half_h);
let sr: f32 = rgba[0] as f32;
let sg: f32 = rgba[1] as f32;
let sb: f32 = rgba[2] as f32;
let sa: f32 = (rgba[3] as f32) / 255.0;
for row in y0..y1 {
let py: f32 = (row as f32) + 0.5;
let qy: f32 = (py - center_y).abs() - (half_h - radius);
let row_base: usize = (row as usize) * (fb_w as usize) * 4;
for col in x0..x1 {
let px: f32 = (col as f32) + 0.5;
let qx: f32 = (px - center_x).abs() - (half_w - radius);
let dist: f32 = (qx.max(0.0).hypot(qy.max(0.0)) + qx.max(qy).min(0.0)) - radius;
let cov: f32 = (0.5 - dist).clamp(0.0, 1.0) * sa;
if cov <= 0.0 {
continue;
}
let inv_cov: f32 = 1.0 - cov;
let off: usize = row_base + (col as usize) * 4;
if off + 3 < pixels.len() {
pixels[off] = (sr * cov + (pixels[off] as f32) * inv_cov) as u8;
pixels[off + 1] = (sg * cov + (pixels[off + 1] as f32) * inv_cov) as u8;
pixels[off + 2] = (sb * cov + (pixels[off + 2] as f32) * inv_cov) as u8;
pixels[off + 3] = 255;
}
}
}
}
}
#[must_use]
pub fn run_parallel_ab3_massive_grid_20k(
gpu_engine: &mut GpuComputeLayoutEngine,
worker_threads: usize,
iterations: usize,
) -> ParallelAbCaseResult {
let iters: usize = iterations.max(4);
let scene_a: GpuComputeSceneInput = build_parallel_ab_compute_scene(
GpuLayoutMode::Grid,
AB_GRID_20K_CELLS,
160.0,
1280.0,
800.0,
);
let scene_b: GpuComputeSceneInput = build_parallel_ab_compute_scene(
GpuLayoutMode::Grid,
AB_GRID_20K_CELLS,
160.0,
1600.0,
900.0,
);
let cpu_ref: GpuComputeDispatchResult = execute_cpu_reference_compute(&scene_a);
let mut cpu_fb: Framebuffer = Framebuffer::allocate(1280, 800);
let start_cpu: Instant = Instant::now();
for iter_idx in 0..iters {
let cur: &GpuComputeSceneInput = if iter_idx % 2 == 0 {
&scene_a
} else {
&scene_b
};
let cpu_step: GpuComputeDispatchResult = execute_cpu_reference_compute(cur);
rasterize_primitives_into_framebuffer(&mut cpu_fb, cpu_step.get_primitives().as_slice());
}
let cpu_us: f64 = (start_cpu.elapsed().as_secs_f64() * 1_000_000.0) / (iters as f64);
let warmup_gpu: GpuComputeDispatchResult = gpu_engine.dispatch(&scene_a, true);
let max_err: f32 = max_layout_output_error_px(
warmup_gpu.get_outputs().as_slice(),
cpu_ref.get_outputs().as_slice(),
);
let mut gpu_exec_ns: u64 = warmup_gpu
.get_gpu_compute_ns()
.saturating_add(warmup_gpu.get_gpu_render_ns());
let mut draw_calls: usize = warmup_gpu.get_draw_calls();
let start_gpu: Instant = Instant::now();
for iter_idx in 0..iters {
let cur: &GpuComputeSceneInput = if iter_idx % 2 == 0 {
&scene_a
} else {
&scene_b
};
let res: GpuComputeDispatchResult = gpu_engine.dispatch_steady_indirect(cur, true, false);
gpu_exec_ns = res
.get_gpu_compute_ns()
.saturating_add(res.get_gpu_render_ns());
draw_calls = res.get_draw_calls();
}
let gpu_us: f64 = (start_gpu.elapsed().as_secs_f64() * 1_000_000.0) / (iters as f64);
let mut workload: ExecutionWorkloadFeatures = ExecutionWorkloadFeatures::default();
workload
.set_dirty_nodes(AB_GRID_20K_CELLS)
.set_visible_nodes(AB_GRID_20K_CELLS)
.set_tree_depth(2)
.set_gpu_eligible_nodes(AB_GRID_20K_CELLS)
.set_cpu_chrome_nodes(0)
.set_dirty_upload_bytes(AB_GRID_20K_CELLS.saturating_mul(GPU_LAYOUT_NODE_INPUT_BYTES))
.set_wrapping_text_ratio(0.0)
.set_worker_threads(worker_threads)
.set_gpu_compute_available(gpu_engine.is_hardware_compute_ready())
.set_thermal_throttled(false);
let router_lane: ExecutionLane = evaluate_router_lane(workload);
let speedup_ratio: f64 = if gpu_us > 0.0 { cpu_us / gpu_us } else { 0.0 };
let expected_lane: ExecutionLane = if gpu_engine.is_hardware_compute_ready() {
ExecutionLane::GpuCompute
} else if worker_threads > 1 {
ExecutionLane::CpuParallel
} else {
ExecutionLane::CpuSerial
};
let gpu_verified: bool = !gpu_engine.is_hardware_compute_ready()
|| (gpu_exec_ns > 0 && draw_calls > 0 && warmup_gpu.get_offscreen_non_zero_pixels() > 0);
let passed: bool =
router_lane == expected_lane && max_err <= AB_PARITY_MAX_ERR_PX && gpu_verified;
ParallelAbCaseResult {
name: PARALLEL_AB3_NAME.to_string(),
arm_a_label: AB_ARM_CPU_SERIAL.to_string(),
arm_b_label: AB_ARM_GPU_COMPUTE.to_string(),
arm_a_us: cpu_us,
arm_b_us: gpu_us,
speedup_ratio,
gpu_exec_ns,
draw_calls,
max_error_px: max_err,
upload_savings_ratio: 0.0,
steady_state_allocs: 0,
router_selected_lane: format!("{router_lane:?}"),
passed,
}
}
#[must_use]
pub fn run_parallel_ab4_50k_spring_indirect(
gpu_engine: &mut GpuComputeLayoutEngine,
worker_threads: usize,
iterations: usize,
) -> ParallelAbCaseResult {
let iters: usize = iterations.max(4);
let scene: GpuComputeSceneInput = build_parallel_ab_compute_scene(
GpuLayoutMode::Spring,
AB_SPRING_50K_NODES,
1.0,
1280.0,
800.0,
);
let cpu_ref: GpuComputeDispatchResult = execute_cpu_reference_compute(&scene);
let mut cpu_fb: Framebuffer = Framebuffer::allocate(1280, 800);
let start_cpu: Instant = Instant::now();
for _ in 0..iters {
let cpu_step: GpuComputeDispatchResult = execute_cpu_reference_compute(&scene);
rasterize_primitives_into_framebuffer(&mut cpu_fb, cpu_step.get_primitives().as_slice());
}
let cpu_us: f64 = (start_cpu.elapsed().as_secs_f64() * 1_000_000.0) / (iters as f64);
let warmup_gpu: GpuComputeDispatchResult = gpu_engine.dispatch(&scene, true);
let max_err: f32 = max_layout_output_error_px(
warmup_gpu.get_outputs().as_slice(),
cpu_ref.get_outputs().as_slice(),
);
let mut gpu_exec_ns: u64 = warmup_gpu
.get_gpu_compute_ns()
.saturating_add(warmup_gpu.get_gpu_render_ns());
let mut draw_calls: usize = warmup_gpu.get_draw_calls();
let start_gpu: Instant = Instant::now();
for _ in 0..iters {
let res: GpuComputeDispatchResult =
gpu_engine.dispatch_steady_indirect(&scene, true, false);
gpu_exec_ns = res
.get_gpu_compute_ns()
.saturating_add(res.get_gpu_render_ns());
draw_calls = res.get_draw_calls();
}
let gpu_us: f64 = (start_gpu.elapsed().as_secs_f64() * 1_000_000.0) / (iters as f64);
let mut coalescer: DirtySpanCoalescer = DirtySpanCoalescer::default();
let mut prim_stream: Vec<GpuPrimitiveInstance> = warmup_gpu.get_primitives().clone();
let _: &[DirtyBufferSpan] = coalescer.diff_and_coalesce(prim_stream.as_slice());
if !prim_stream.is_empty() {
let mutated_color: u32 = prim_stream[0].get_color_rgba().wrapping_add(1);
prim_stream[0].set_color_rgba(mutated_color);
}
let _: &[DirtyBufferSpan] = coalescer.diff_and_coalesce(prim_stream.as_slice());
let upload_savings: f32 = coalescer.last_savings_ratio();
let mut workload: ExecutionWorkloadFeatures = ExecutionWorkloadFeatures::default();
workload
.set_dirty_nodes(AB_SPRING_50K_NODES)
.set_visible_nodes(AB_SPRING_50K_NODES)
.set_tree_depth(2)
.set_gpu_eligible_nodes(AB_SPRING_50K_NODES)
.set_cpu_chrome_nodes(0)
.set_dirty_upload_bytes(coalescer.get_last_dirty_bytes())
.set_wrapping_text_ratio(0.0)
.set_worker_threads(worker_threads)
.set_gpu_compute_available(gpu_engine.is_hardware_compute_ready())
.set_thermal_throttled(false);
let router_lane: ExecutionLane = evaluate_router_lane(workload);
let speedup_ratio: f64 = if gpu_us > 0.0 { cpu_us / gpu_us } else { 0.0 };
let gpu_verified: bool = !gpu_engine.is_hardware_compute_ready()
|| (gpu_exec_ns > 0 && draw_calls > 0 && warmup_gpu.get_offscreen_non_zero_pixels() > 0);
let passed: bool = max_err <= AB_PARITY_MAX_ERR_PX && upload_savings >= 0.90 && gpu_verified;
ParallelAbCaseResult {
name: PARALLEL_AB4_NAME.to_string(),
arm_a_label: AB_ARM_CPU_SERIAL.to_string(),
arm_b_label: AB_ARM_GPU_COMPUTE.to_string(),
arm_a_us: cpu_us,
arm_b_us: gpu_us,
speedup_ratio,
gpu_exec_ns,
draw_calls,
max_error_px: max_err,
upload_savings_ratio: upload_savings,
steady_state_allocs: 0,
router_selected_lane: format!("{router_lane:?}"),
passed,
}
}
#[must_use]
pub fn run_parallel_ab5_mixed_dashboard(
gpu_engine: &mut GpuComputeLayoutEngine,
worker_threads: usize,
iterations: usize,
) -> ParallelAbCaseResult {
let iters: usize = iterations.max(4);
let (mut chrome_tree_seq, _): (SceneTree, NodeId) =
build_parallel_ab_card_tree(AB_DASHBOARD_CHROME_CARDS, true);
let (mut chrome_tree_co, _): (SceneTree, NodeId) =
build_parallel_ab_card_tree(AB_DASHBOARD_CHROME_CARDS, true);
let mut seq_layout: LayoutEngine = LayoutEngine::default();
let mut co_layout: LayoutEngine = LayoutEngine::default();
let body_scene: GpuComputeSceneInput = build_parallel_ab_compute_scene(
GpuLayoutMode::Grid,
AB_GRID_20K_CELLS,
160.0,
1280.0,
800.0,
);
let cpu_body_ref: GpuComputeDispatchResult = execute_cpu_reference_compute(&body_scene);
let mut cpu_fb: Framebuffer = Framebuffer::allocate(1280, 800);
let start_seq: Instant = Instant::now();
for iter_idx in 0..iters {
let width: f32 = if iter_idx % 2 == 0 { 960.0 } else { 1280.0 };
let _: LayoutStats =
seq_layout.compute_parallel(&mut chrome_tree_seq, Size::new(width, 800.0));
let body_step: GpuComputeDispatchResult = execute_cpu_reference_compute(&body_scene);
rasterize_primitives_into_framebuffer(&mut cpu_fb, body_step.get_primitives().as_slice());
}
let pure_cpu_us: f64 = (start_seq.elapsed().as_secs_f64() * 1_000_000.0) / (iters as f64);
let warmup_gpu: GpuComputeDispatchResult = gpu_engine.dispatch(&body_scene, true);
let max_err: f32 = max_layout_output_error_px(
warmup_gpu.get_outputs().as_slice(),
cpu_body_ref.get_outputs().as_slice(),
);
let mut gpu_exec_ns: u64 = warmup_gpu
.get_gpu_compute_ns()
.saturating_add(warmup_gpu.get_gpu_render_ns());
let mut draw_calls: usize = warmup_gpu.get_draw_calls();
let start_co: Instant = Instant::now();
for iter_idx in 0..iters {
let width: f32 = if iter_idx % 2 == 0 { 960.0 } else { 1280.0 };
let in_flight: Option<(usize, usize, usize)> =
gpu_engine.begin_steady_indirect_async(&body_scene, true, false);
let _: LayoutStats =
co_layout.compute_parallel(&mut chrome_tree_co, Size::new(width, 800.0));
let res: GpuComputeDispatchResult = match in_flight {
Some(token) => gpu_engine.finish_steady_indirect_async(token),
None => gpu_engine.dispatch_steady_indirect(&body_scene, true, false),
};
gpu_exec_ns = res
.get_gpu_compute_ns()
.saturating_add(res.get_gpu_render_ns());
draw_calls = res.get_draw_calls();
}
let mixed_us: f64 = (start_co.elapsed().as_secs_f64() * 1_000_000.0) / (iters as f64);
let mut workload: ExecutionWorkloadFeatures = ExecutionWorkloadFeatures::default();
workload
.set_dirty_nodes(AB_DASHBOARD_CHROME_CARDS * 2 + AB_GRID_20K_CELLS)
.set_visible_nodes(AB_DASHBOARD_CHROME_CARDS * 2 + AB_GRID_20K_CELLS)
.set_tree_depth(3)
.set_gpu_eligible_nodes(AB_GRID_20K_CELLS)
.set_cpu_chrome_nodes(AB_DASHBOARD_CHROME_CARDS * 2)
.set_dirty_upload_bytes(AB_GRID_20K_CELLS.saturating_mul(GPU_LAYOUT_NODE_INPUT_BYTES))
.set_wrapping_text_ratio(0.05)
.set_worker_threads(worker_threads)
.set_gpu_compute_available(gpu_engine.is_hardware_compute_ready())
.set_thermal_throttled(false);
let router_lane: ExecutionLane = evaluate_router_lane(workload);
let speedup_ratio: f64 = if mixed_us > 0.0 {
pure_cpu_us / mixed_us
} else {
0.0
};
let expected_lane: ExecutionLane = if gpu_engine.is_hardware_compute_ready() {
ExecutionLane::MixedCoExec
} else if worker_threads > 1 {
ExecutionLane::CpuParallel
} else {
ExecutionLane::CpuSerial
};
let gpu_verified: bool =
!gpu_engine.is_hardware_compute_ready() || (gpu_exec_ns > 0 && draw_calls > 0);
let passed: bool =
router_lane == expected_lane && max_err <= AB_PARITY_MAX_ERR_PX && gpu_verified;
ParallelAbCaseResult {
name: PARALLEL_AB5_NAME.to_string(),
arm_a_label: AB_ARM_CPU_PARALLEL.to_string(),
arm_b_label: AB_ARM_MIXED_COEXEC.to_string(),
arm_a_us: pure_cpu_us,
arm_b_us: mixed_us,
speedup_ratio,
gpu_exec_ns,
draw_calls,
max_error_px: max_err,
upload_savings_ratio: 0.0,
steady_state_allocs: 0,
router_selected_lane: format!("{router_lane:?}"),
passed,
}
}
#[must_use]
pub fn run_parallel_ab6_pipelined_dirty_span(
gpu_engine: &mut GpuComputeLayoutEngine,
iterations: usize,
) -> ParallelAbCaseResult {
let iters: usize = iterations.max(8);
let mut primitives: Vec<GpuPrimitiveInstance> = Vec::with_capacity(AB_PIPELINED_PRIMITIVES);
for idx in 0..AB_PIPELINED_PRIMITIVES {
let mut quad: GpuQuadInstance = GpuQuadInstance::default();
let col: f32 = (idx % 100) as f32;
let row: f32 = (idx / 100) as f32;
quad.set_rect([col * 12.0, row * 8.0, 10.0, 6.0])
.set_clip([0.0, 0.0, 1280.0, 800.0])
.set_color([0.2, 0.55, 0.9, 1.0])
.set_radii([2.0; 4])
.set_kind(GpuPrimitiveKind::RoundedRect as u32);
primitives.push(GpuPrimitiveInstance::from_quad_instance(&quad, 0, 0));
}
let mut driver: NativeGpuDriver = NativeGpuDriver::probe(GraphicsBackend::Metal);
let mut graph_full: RenderGraph = RenderGraph::default();
graph_full.set_max_frames_in_flight(1);
let mut graph_dirty: RenderGraph = RenderGraph::default();
graph_dirty.set_max_frames_in_flight(RENDER_GRAPH_DEFAULT_MAX_IN_FLIGHT);
let target: RenderGraphFrameTarget =
RenderGraphFrameTarget::new(1280, 800, Color::rgb(12, 16, 24));
let mut batch_full: [GpuBatch; 1] = [GpuBatch::default()];
batch_full[0].set_scissor(Rect::new(0.0, 0.0, 1280.0, 800.0));
batch_full[0].set_primitives(primitives.clone());
let mut batch_dirty: [GpuBatch; 1] = [GpuBatch::default()];
batch_dirty[0].set_scissor(Rect::new(0.0, 0.0, 1280.0, 800.0));
batch_dirty[0].set_primitives(primitives);
let _: Result<RenderGraphExecutionReceipt, PlatformError> =
graph_full.execute_frame(&mut driver, target, &batch_full, &[], None);
let _: Result<RenderGraphExecutionReceipt, PlatformError> =
graph_dirty.execute_frame(&mut driver, target, &batch_dirty, &[], None);
let mut full_staging: Vec<u8> =
vec![0u8; AB_PIPELINED_PRIMITIVES.saturating_mul(size_of::<GpuPrimitiveInstance>())];
let warmup_span: [DirtyBufferSpan; 1] = [DirtyBufferSpan::new(0, full_staging.len())];
let _: Option<(usize, u64)> = gpu_engine.upload_primitive_spans_metal(
batch_full[0].get_primitives().as_slice(),
&warmup_span,
0,
true,
);
let mut gpu_exec_ns: u64 = 0;
let start_full: Instant = Instant::now();
for iter_idx in 0..iters {
for dirty_idx in 0..AB_PIPELINED_DIRTY_PRIMITIVES {
let slot: usize = dirty_idx;
let next_rgba: u32 = batch_full[0].get_primitives()[slot]
.get_color_rgba()
.wrapping_add((iter_idx as u32).saturating_add(1));
batch_full[0].get_mut_primitives()[slot].set_color_rgba(next_rgba);
}
graph_full.get_mut_dirty_coalescer().reset();
let _: Result<RenderGraphExecutionReceipt, PlatformError> =
graph_full.execute_frame(&mut driver, target, &batch_full, &[], None);
let prim_slice: &[GpuPrimitiveInstance] = batch_full[0].get_primitives().as_slice();
let spans: &[DirtyBufferSpan] = graph_full.get_dirty_coalescer().get_coalesced();
if let Some((_, ns)) = gpu_engine.upload_primitive_spans_metal(prim_slice, spans, 0, true) {
gpu_exec_ns = gpu_exec_ns.max(ns);
} else {
let src_bytes: &[u8] = unsafe {
from_raw_parts(prim_slice.as_ptr().cast::<u8>(), size_of_val(prim_slice))
};
for span in spans {
let start: usize = span.get_byte_offset();
let end: usize = start
.saturating_add(span.get_byte_len())
.min(full_staging.len())
.min(src_bytes.len());
if end > start {
full_staging[start..end].copy_from_slice(&src_bytes[start..end]);
}
}
}
}
let full_us: f64 = (start_full.elapsed().as_secs_f64() * 1_000_000.0) / (iters as f64);
let mut upload_savings: f32 = 0.0;
let mut draw_calls: usize = 0;
let mut pending_cmd: usize = 0;
let start_dirty: Instant = Instant::now();
for iter_idx in 0..iters {
for dirty_idx in 0..AB_PIPELINED_DIRTY_PRIMITIVES {
let slot: usize = dirty_idx;
let next_rgba: u32 = batch_dirty[0].get_primitives()[slot]
.get_color_rgba()
.wrapping_add((iter_idx as u32).saturating_add(1));
batch_dirty[0].get_mut_primitives()[slot].set_color_rgba(next_rgba);
}
let _: Result<RenderGraphExecutionReceipt, PlatformError> =
graph_dirty.execute_frame(&mut driver, target, &batch_dirty, &[], None);
let prim_slice: &[GpuPrimitiveInstance] = batch_dirty[0].get_primitives().as_slice();
let spans: &[DirtyBufferSpan] = graph_dirty.get_dirty_coalescer().get_coalesced();
if let Some((next_cmd, _)) =
gpu_engine.upload_primitive_spans_metal(prim_slice, spans, iter_idx & 1, false)
{
if pending_cmd != 0 {
let done_ns: u64 = gpu_engine.finish_upload_metal(pending_cmd);
gpu_exec_ns = gpu_exec_ns.max(done_ns);
}
pending_cmd = next_cmd;
} else {
let src_bytes: &[u8] = unsafe {
from_raw_parts(prim_slice.as_ptr().cast::<u8>(), size_of_val(prim_slice))
};
for span in spans {
let start: usize = span.get_byte_offset();
let end: usize = start
.saturating_add(span.get_byte_len())
.min(full_staging.len())
.min(src_bytes.len());
if end > start {
full_staging[start..end].copy_from_slice(&src_bytes[start..end]);
}
}
}
if iter_idx == iters - 1 {
upload_savings = graph_dirty.get_dirty_coalescer().last_savings_ratio();
}
}
if pending_cmd != 0 {
let done_ns: u64 = gpu_engine.finish_upload_metal(pending_cmd);
gpu_exec_ns = gpu_exec_ns.max(done_ns);
}
let dirty_us: f64 = (start_dirty.elapsed().as_secs_f64() * 1_000_000.0) / (iters as f64);
for dirty_idx in 0..AB_PIPELINED_DIRTY_PRIMITIVES {
let next_rgba: u32 = batch_dirty[0].get_primitives()[dirty_idx]
.get_color_rgba()
.wrapping_add(1);
batch_dirty[0].get_mut_primitives()[dirty_idx].set_color_rgba(next_rgba);
}
let (_, alloc_snap): (usize, AllocationSnapshot) = measure_allocations(|| {
let spans: &[DirtyBufferSpan] = graph_dirty
.get_mut_dirty_coalescer()
.diff_and_coalesce(batch_dirty[0].get_primitives().as_slice());
spans.len()
});
let steady_allocs: usize = alloc_snap.get_alloc_count() as usize;
let verify_scene: GpuComputeSceneInput =
build_parallel_ab_compute_scene(GpuLayoutMode::Grid, 64, 8.0, 1280.0, 800.0);
let gpu_receipt: Result<RenderGraphExecutionReceipt, PlatformError> = graph_dirty
.execute_frame(
&mut driver,
target,
&batch_dirty,
&[],
Some((gpu_engine, &verify_scene)),
);
if let Ok(receipt) = gpu_receipt {
gpu_exec_ns = gpu_exec_ns.max(receipt.get_gpu_compute_ns());
draw_calls = receipt.get_draw_calls();
}
let speedup_ratio: f64 = if dirty_us > 0.0 {
full_us / dirty_us
} else {
0.0
};
let hw_ready: bool = gpu_engine.is_hardware_compute_ready();
let gpu_verified: bool =
!hw_ready || (gpu_exec_ns > 0 && draw_calls > 0 && speedup_ratio > 1.0);
let passed: bool = upload_savings >= 0.90 && steady_allocs == 0 && gpu_verified;
ParallelAbCaseResult {
name: PARALLEL_AB6_NAME.to_string(),
arm_a_label: AB_ARM_INFLIGHT1_FULL.to_string(),
arm_b_label: AB_ARM_INFLIGHT2_DIRTY.to_string(),
arm_a_us: full_us,
arm_b_us: dirty_us,
speedup_ratio,
gpu_exec_ns,
draw_calls,
max_error_px: 0.0,
upload_savings_ratio: upload_savings,
steady_state_allocs: steady_allocs,
router_selected_lane: AB_ARM_INFLIGHT2_DIRTY.to_string(),
passed,
}
}
#[must_use]
fn matches_parallel_ab_filter(case_name: &str, filter: Option<&str>) -> bool {
match filter {
Some(pattern) if !pattern.is_empty() => case_name.contains(pattern),
_ => true,
}
}
#[must_use]
pub fn run_filtered_parallel_ab_suite(filter: Option<&str>) -> ParallelAbReport {
let mut gpu_engine: GpuComputeLayoutEngine = GpuComputeLayoutEngine::probe();
let gpu_ready: bool = gpu_engine.is_hardware_compute_ready();
let gpu_backend: String = if gpu_ready {
AB_BACKEND_METAL.to_string()
} else {
AB_BACKEND_CPU_REF.to_string()
};
let worker_threads: usize = global_engine_worker_pool().total_threads();
let mut cases: Vec<ParallelAbCaseResult> = Vec::with_capacity(6);
if matches_parallel_ab_filter(PARALLEL_AB1_NAME, filter) {
cases.push(run_parallel_ab1_sparse_reactive(
&mut gpu_engine,
worker_threads,
16,
));
}
if matches_parallel_ab_filter(PARALLEL_AB2_NAME, filter) {
cases.push(run_parallel_ab2_heavy_text_reflow(
gpu_ready,
worker_threads,
6,
));
}
if matches_parallel_ab_filter(PARALLEL_AB3_NAME, filter) {
cases.push(run_parallel_ab3_massive_grid_20k(
&mut gpu_engine,
worker_threads,
8,
));
}
if matches_parallel_ab_filter(PARALLEL_AB4_NAME, filter) {
cases.push(run_parallel_ab4_50k_spring_indirect(
&mut gpu_engine,
worker_threads,
8,
));
}
if matches_parallel_ab_filter(PARALLEL_AB5_NAME, filter) {
cases.push(run_parallel_ab5_mixed_dashboard(
&mut gpu_engine,
worker_threads,
6,
));
}
if matches_parallel_ab_filter(PARALLEL_AB6_NAME, filter) {
cases.push(run_parallel_ab6_pipelined_dirty_span(&mut gpu_engine, 16));
}
let all_passed: bool = cases
.iter()
.all(|case: &ParallelAbCaseResult| case.get_passed());
ParallelAbReport::new(
gpu_backend,
gpu_ready,
allocation_tracking_active(),
worker_threads,
cases,
all_passed,
)
}
#[must_use]
pub fn format_parallel_ab_report(report: &ParallelAbReport) -> String {
let mut out: String = String::from(AB_REPORT_HEADER);
let _: fmt::Result = writeln!(
out,
"Backend: {} | HardwareGPU: {} | Workers: {} | AllocTracking: {}",
report.get_gpu_backend(),
report.get_hardware_gpu_verified(),
report.get_worker_threads(),
report.get_allocation_tracking()
);
for case in report.get_cases() {
let status: &str = if case.get_passed() {
AB_STATUS_PASS
} else {
AB_STATUS_FAIL
};
let _: fmt::Result = writeln!(
out,
"[{status}] {:<32} | {}: {:>8.1}us vs {}: {:>8.1}us | x{:.2} | gpu_ns={} draws={} err={:.4}px save={:.1}% allocs={} lane={}",
case.get_name(),
case.get_arm_a_label(),
case.get_arm_a_us(),
case.get_arm_b_label(),
case.get_arm_b_us(),
case.get_speedup_ratio(),
case.get_gpu_exec_ns(),
case.get_draw_calls(),
case.get_max_error_px(),
case.get_upload_savings_ratio() * 100.0,
case.get_steady_state_allocs(),
case.get_router_selected_lane(),
);
}
let _: fmt::Result = writeln!(
out,
"Summary: {}/{} passed (all_passed={})",
report.passed_count(),
report.get_cases().len(),
report.get_all_passed()
);
out
}
#[must_use]
pub fn parallel_ab_report_to_json(report: &ParallelAbReport) -> String {
to_string_pretty(report).unwrap_or_default()
}