Compare commits

...
5 changed files with 391 additions and 143 deletions

No files matched your search

@@ -26,8 +26,8 @@ env:
CARGO_TERM_COLOR: always
# The four benchmarks, built and run by one `cargo bench` call so their slow thin-LTO links happen in parallel
BENCHMARKS: --bench compile_demo_art_gungraun --bench update_executor_gungraun --bench run_once_gungraun --bench run_cached_gungraun
# The brush benchmark, which needs the GPU nodes and so gets its own call rather than changing what the others build
BRUSH_BENCHMARK: -p interpreted-executor --features gpu --bench brush_stroke_gungraun
# The benchmarks in `node-graph/interpreted-executor/benches` that render on the GPU, built with its `gpu` feature in a call of their own so the others build as before
GPU_BENCHMARKS: brush_stroke_gungraun artwork_gungraun
jobs:
profile:
@@ -57,7 +57,7 @@ jobs:
- name: Install lavapipe
run: |
# The runners have no GPU, so the brush benchmark renders on Mesa's software Vulkan device
# The runners have no GPU, so the GPU benchmarks render on Mesa's software Vulkan device
sudo apt-get update
sudo apt-get install -y mesa-vulkan-drivers
# Mesa releases name the ICD with or without the architecture (`lvp_icd.x86_64.json` or `lvp_icd.json`), so ask the package where it put it
@@ -87,10 +87,9 @@ jobs:
run: |
cargo bench $BENCHMARKS -- --save-baseline=master
# Until the brush benchmark reaches master, a baseline commit may predate it
if [ -f node-graph/interpreted-executor/benches/brush_stroke_gungraun.rs ]; then
cargo bench $BRUSH_BENCHMARK -- --save-baseline=master
fi
# A PR adding a GPU benchmark is measured against a baseline commit that predates it
gpu_benchmarks=$(for benchmark in $GPU_BENCHMARKS; do if [ -f "node-graph/interpreted-executor/benches/$benchmark.rs" ]; then echo "--bench $benchmark"; fi; done)
if [ -n "$gpu_benchmarks" ]; then cargo bench -p interpreted-executor --features gpu $gpu_benchmarks -- --save-baseline=master; fi
# Saved before the PR benchmarks run, since they write their own results into the same folder
- name: Save benchmark baseline
@@ -109,23 +108,31 @@ jobs:
# Unlike the default, this sets `pipefail`, so a failed benchmark fails the step rather than leaving its results empty
shell: bash
run: |
# The brush benchmark has nothing to compare against until the baseline commit has it
git cat-file -e HEAD^1:node-graph/interpreted-executor/benches/brush_stroke_gungraun.rs 2>/dev/null && brush=true || brush=false
# A GPU benchmark has nothing to compare against until the baseline commit has it
baselined=$(for benchmark in $GPU_BENCHMARKS; do if git cat-file -e "HEAD^1:node-graph/interpreted-executor/benches/$benchmark.rs" 2>/dev/null; then echo "$benchmark"; fi; done)
gpu_benchmarks=$(for benchmark in $baselined; do echo "--bench $benchmark"; done)
{
cargo bench $BENCHMARKS -- --baseline=master --output-format=json
if $brush; then cargo bench $BRUSH_BENCHMARK -- --baseline=master --output-format=json; fi
if [ -n "$gpu_benchmarks" ]; then cargo bench -p interpreted-executor --features gpu $gpu_benchmarks -- --baseline=master --output-format=json; fi
} | jq -sc | sed 's/\\"//g' > /tmp/all_output.json
# Split the results into one file per benchmark for the analysis below
split_results() { jq -c --arg prefix "$1::" '[.[] | select(.module_path | startswith($prefix))]' /tmp/all_output.json > "/tmp/$2_output.json"; }
# Split the results into one file per benchmark, or per function of one, for the analysis below
split_results() { jq -c --arg path "$1" '[.[] | select(.module_path == $path or (.module_path | startswith($path + "::")))]' /tmp/all_output.json > "/tmp/$2_output.json"; }
split_results compile_demo_art_gungraun compile
split_results update_executor_gungraun update
split_results run_once_gungraun run_once
split_results run_cached_gungraun run_cached
if $brush; then
split_results brush_stroke_gungraun brush_stroke
fi
for benchmark in $baselined; do
case $benchmark in
# Its edits and zooms take different render paths, so each gets a section of its own
artwork_gungraun)
split_results artwork_gungraun::artwork_group::add_rectangle artwork_edit
split_results artwork_gungraun::artwork_group::zoom artwork_zoom
;;
*) split_results "$benchmark" "$benchmark" ;;
esac
done
- name: Make old comments collapsed by default
# Only run if we have write permissions (not a fork)
@@ -178,18 +185,22 @@ jobs:
return benchmark.profiles?.find((profile) => profile.tool === 'Callgrind')?.data?.total?.metrics;
}
// The brush benchmark only has results once the baseline commit has it too
const brush = fs.existsSync('/tmp/brush_stroke_output.json');
// A GPU benchmark only has results once the baseline commit has it too
const gpuBenchmarks = [
['brush_stroke_gungraun', 'Brush Strokes'],
['artwork_edit', 'Artwork Edit'],
['artwork_zoom', 'Zoom'],
].filter(([name]) => fs.existsSync(`/tmp/${name}_output.json`));
const allOutputs = [
JSON.parse(fs.readFileSync('/tmp/compile_output.json', 'utf8')),
JSON.parse(fs.readFileSync('/tmp/update_output.json', 'utf8')),
JSON.parse(fs.readFileSync('/tmp/run_once_output.json', 'utf8')),
JSON.parse(fs.readFileSync('/tmp/run_cached_output.json', 'utf8')),
...(brush ? [JSON.parse(fs.readFileSync('/tmp/brush_stroke_output.json', 'utf8'))] : [])
...gpuBenchmarks.map(([name]) => JSON.parse(fs.readFileSync(`/tmp/${name}_output.json`, 'utf8')))
];
const outputNames = ['compile', 'update', 'run_once', 'run_cached', ...(brush ? ['brush_stroke'] : [])];
const sectionTitles = ['Compilation', 'Update', 'Run Once', 'Cached Execution', ...(brush ? ['Brush Stroke'] : [])];
const outputNames = ['compile', 'update', 'run_once', 'run_cached', ...gpuBenchmarks.map(([name]) => name)];
const sectionTitles = ['Compilation', 'Update', 'Run Once', 'Cached Execution', ...gpuBenchmarks.map(([, title]) => title)];
// Fail instead of reporting no changes when a benchmark has no baseline comparison, such as after gungraun changes its output format
const missingComparisons = [];
@@ -252,9 +263,11 @@ jobs:
const updateOutput = JSON.parse(fs.readFileSync('/tmp/update_output.json', 'utf8'));
const runOnceOutput = JSON.parse(fs.readFileSync('/tmp/run_once_output.json', 'utf8'));
const runCachedOutput = JSON.parse(fs.readFileSync('/tmp/run_cached_output.json', 'utf8'));
// The brush benchmark only has results once the baseline commit has it too, and a section without results is left out
// A GPU benchmark only has results once the baseline commit has it too, and a section without results is left out
const readOptional = (path) => (fs.existsSync(path) ? JSON.parse(fs.readFileSync(path, 'utf8')) : []);
const brushStrokeOutput = readOptional('/tmp/brush_stroke_output.json');
const brushStrokeOutput = readOptional('/tmp/brush_stroke_gungraun_output.json');
const artworkEditOutput = readOptional('/tmp/artwork_edit_output.json');
const artworkZoomOutput = readOptional('/tmp/artwork_zoom_output.json');
const hasSignificantChanges = '${{ steps.analyze.outputs.has-significant-changes }}' === 'true';
let commentBody = "";
@@ -344,7 +357,9 @@ jobs:
{ output: updateOutput, title: "🔄 Executor Update" },
{ output: runOnceOutput, title: "🚀 Render: Cold Execution" },
{ output: runCachedOutput, title: "⚡ Render: Cached Execution" },
{ output: brushStrokeOutput, title: "🖌️ Render: Brush Strokes" }
{ output: brushStrokeOutput, title: "🖌️ Render: Brush Strokes" },
{ output: artworkEditOutput, title: "✏️ Render: Artwork Edit" },
{ output: artworkZoomOutput, title: "🔍 Render: Zoom" }
];
// Generate sections and determine which ones have results
@@ -73,3 +73,8 @@ harness = false
name = "brush_stroke_gungraun"
harness = false
required-features = ["gpu"]
[[bench]]
name = "artwork_gungraun"
harness = false
required-features = ["gpu"]
@@ -0,0 +1,190 @@
//! Counts the instructions for editing and viewing the demo artwork once it has been rendered, as the editor renders it after each change:
//! drawing a rectangle on top of it, which recompiles the graph and renders the viewport,
//! and zooming in, which renders the viewport anew since none of the cached tiles match the new zoom.
mod gpu_util;
use glam::{DAffine2, DVec2};
use gpu_util::{GpuDocument, VIEWPORT, callgrind};
use graph_craft::concrete;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
use graphene_std::transform_nodes::transform;
use graphene_std::vector::generator_nodes::rectangle;
use graphene_std::vector::{GradientForm, GradientRamp};
use graphene_std::vector_nodes::fill;
use graphene_std::{Color, Context};
use gungraun::prelude::*;
use std::path::Path;
/// The zoom step the measured render takes, about the viewport center.
const ZOOM: f64 = 1.5;
/// The new rectangle's nodes, numbered clear of the document's own so every run builds the same graph.
const RECTANGLE: NodeId = NodeId(u64::MAX - 3);
const TRANSFORM: NodeId = NodeId(u64::MAX - 2);
const FILL: NodeId = NodeId(u64::MAX - 1);
const LAYER: NodeId = NodeId(u64::MAX);
pub struct Session {
gpu: GpuDocument,
/// Where the viewport shows the artwork.
view: DAffine2,
/// The document graph for the measured update.
document: NodeNetwork,
}
/// Opens lavapipe and renders the demo artwork `name` fitted into the viewport, so the measured step meets the caches the editor would have.
fn open(name: &str) -> (Session, NodeNetwork) {
let network = futures::executor::block_on(document_loader::open_document(Path::new(&format!("../../demo-artwork/{name}.graphite"))))
.expect("Failed to open the demo artwork")
.network;
let view = fit(&network);
let mut gpu = GpuDocument::new();
gpu.compile(network.clone());
gpu.render(view);
let session = Session {
gpu,
view,
document: NodeNetwork::default(),
};
(session, network)
}
fn setup_add_rectangle(name: &str) -> Session {
let (mut session, network) = open(name);
session.document = with_rectangle(network);
session
}
/// The artwork viewed after zooming out and back, so the device has the shaders for a zoom change while no tiles at the measured zoom are cached.
fn setup_zoom(name: &str) -> Session {
let (session, _) = open(name);
session.gpu.render(zoomed(session.view, 1. / ZOOM));
session.gpu.render(session.view);
session
}
/// The view zoomed by `factor` about the viewport center.
fn zoomed(view: DAffine2, factor: f64) -> DAffine2 {
let center = VIEWPORT.as_dvec2() / 2.;
DAffine2::from_translation(center) * DAffine2::from_scale(DVec2::splat(factor)) * DAffine2::from_translation(-center) * view
}
/// The view that fits the document's root artboard into the viewport with a margin, as zooming to fit does.
fn fit(network: &NodeNetwork) -> DAffine2 {
let artboard = root(network);
let location = vec_input(artboard, 2);
let size = vec_input(artboard, 3);
let scale = (VIEWPORT.as_dvec2() / size).min_element() * 0.9;
let offset = (VIEWPORT.as_dvec2() - size * scale) / 2. - location * scale;
DAffine2::from_translation(offset) * DAffine2::from_scale(DVec2::splat(scale))
}
/// The document with a rectangle layer on top of its artboard's other layers, with the nodes the Rectangle tool creates.
fn with_rectangle(mut network: NodeNetwork) -> NodeNetwork {
let artboard = root(&network);
let location = vec_input(artboard, 2);
let size = vec_input(artboard, 3);
let NodeInput::Node { node_id: top, .. } = artboard.inputs[1] else {
panic!("The artboard has no layers");
};
// The top layer serves as the template for the new one, sharing the document's layer definition
let mut layer = network.nodes[&top].clone();
assert!(matches!(layer.implementation, DocumentNodeImplementation::Definition(_)), "The artboard's top layer is no layer node");
layer.inputs[0] = NodeInput::node(top, 0);
layer.inputs[1] = NodeInput::node(FILL, 0);
let node = |implementation, inputs| DocumentNode {
inputs,
call_argument: concrete!(Context),
implementation: DocumentNodeImplementation::ProtoNode(implementation),
..Default::default()
};
let value = |value| NodeInput::value(value, false);
let rectangle = node(
rectangle::IDENTIFIER,
vec![
value(TaggedValue::None),
value(TaggedValue::Number(size.x / 3.)),
value(TaggedValue::Number(size.y / 3.)),
value(TaggedValue::BoxCorners(vec![0.])),
value(TaggedValue::Bool(true)),
value(TaggedValue::Bool(false)),
],
);
let transform = node(
transform::IDENTIFIER,
vec![
NodeInput::node(RECTANGLE, 0),
value(TaggedValue::DVec2(location + size / 2.)),
value(TaggedValue::Number(0.)),
value(TaggedValue::DVec2(DVec2::ONE)),
value(TaggedValue::DVec2(DVec2::ZERO)),
],
);
let color = Color::from_rgbaf32_unchecked(0.9, 0.3, 0.2, 1.);
let fill = node(
fill::IDENTIFIER,
vec![
NodeInput::node(TRANSFORM, 0),
value(TaggedValue::Color(color)),
value(TaggedValue::Color(color)),
value(TaggedValue::GradientRamp(GradientRamp::default())),
value(TaggedValue::GradientForm(GradientForm::Linear)),
value(TaggedValue::Bool(false)),
value(TaggedValue::DAffine2(DAffine2::IDENTITY)),
],
);
let NodeInput::Node { node_id: root_id, .. } = network.exports[0] else { unreachable!() };
network.nodes.extend([(RECTANGLE, rectangle), (TRANSFORM, transform), (FILL, fill), (LAYER, layer)]);
network.nodes.get_mut(&root_id).expect("The document has no root node").inputs[1] = NodeInput::node(LAYER, 0);
network
}
/// The artboard the document exports, which every demo artwork has.
fn root(network: &NodeNetwork) -> &DocumentNode {
let NodeInput::Node { node_id, .. } = network.exports[0] else {
panic!("The document exports no node");
};
&network.nodes[&node_id]
}
fn vec_input(node: &DocumentNode, index: usize) -> DVec2 {
match node.inputs[index].as_value() {
Some(TaggedValue::DVec2(value)) => *value,
other => panic!("The artboard's input {index} is {other:?} rather than a vector"),
}
}
#[library_benchmark]
#[benches::artwork(args = ["isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_add_rectangle)]
pub fn add_rectangle(mut session: Session) -> Session {
let document = std::mem::take(&mut session.document);
callgrind::start();
session.gpu.compile(document);
session.gpu.render(session.view);
callgrind::stop();
// Return the session so its teardown happens outside the measured section
session
}
#[library_benchmark]
#[benches::artwork(args = ["isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_zoom)]
pub fn zoom(session: Session) -> Session {
let view = zoomed(session.view, ZOOM);
callgrind::start();
session.gpu.render(view);
callgrind::stop();
session
}
library_benchmark_group!(name = artwork_group; benchmarks = add_rectangle, zoom);
main!(
config = gpu_util::config();
library_benchmark_groups = artwork_group
);
@@ -1,33 +1,21 @@
//! Counts the instructions a document update costs when one stroke is added to its brush layer, the way the Brush tool appends strokes:
//! wrapping and compiling the changed graph, updating the executor and rendering the viewport, as the editor's runtime does for each change.
//! Rendering the same document with an empty brush cache is measured alongside, showing how much of the earlier render the cache saves.
//!
//! The graph renders on a software Vulkan device (lavapipe), so CI runners without a GPU can measure it and the counts include the "GPU" work.
use core_types::transform::{Footprint, RenderQuality};
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
mod gpu_util;
use glam::{DAffine2, DVec2};
use gpu_util::{GpuDocument, VIEWPORT, callgrind};
use graph_craft::concrete;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
use graph_craft::graphene_compiler::Compiler;
use graphene_std::application_io::RenderConfig;
use graphene_std::brush::basic_brush::{basic_brush, basic_brush_pipeline};
use graphene_std::brush::{BrushCache, Channel, Stroke, brush_strokes};
use graphene_std::graphic;
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
use graphene_std::uuid::NodeId;
use graphene_std::{Color, Context};
use gungraun::prelude::*;
use gungraun::{Callgrind, EntryPoint};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::util::wrap_network_in_scope;
use std::hint::black_box;
use std::sync::Arc;
use wgpu_executor::{WgpuContextBuilder, WgpuExecutor};
/// Small enough to keep Valgrind runs short, since the full-frame passes scale with it.
const VIEWPORT: UVec2 = UVec2::new(960, 540);
/// Samples in the added stroke.
const STROKE_SAMPLES: usize = 128;
/// Samples in each stroke already in the document.
@@ -38,11 +26,7 @@ const SAMPLE_SPACING: f64 = 4.;
const STROKES_PER_GROUP: usize = 8;
pub struct Session {
gpu: WgpuExecutor,
editor_api: Arc<PlatformEditorApi>,
runtime: AsyncRuntime,
preprocessor: preprocessor::Preprocessor,
executor: DynamicExecutor,
gpu: GpuDocument,
/// The document graph for the measured update.
document: NodeNetwork,
}
@@ -51,42 +35,18 @@ impl Session {
/// Opens lavapipe and renders the finished document once through a brush cache that is then discarded,
/// so that the device's shaders are compiled and its textures allocated before anything is measured.
fn open(after: &[Group]) -> Self {
let gpu = lavapipe();
let mut session = Self {
editor_api: Arc::new(PlatformEditorApi {
application_io: Some(Arc::new(PlatformApplicationIo::new_with_executor(gpu.clone()))),
}),
gpu,
runtime: AsyncRuntime::new(Arc::new(BlockingSpawner)),
preprocessor: preprocessor::Preprocessor::new(),
executor: DynamicExecutor::default(),
gpu: GpuDocument::new(),
document: NodeNetwork::default(),
};
session.update(brush_layer(&BrushCache::default(), after));
session
}
/// Recompiles the document graph into the executor and renders the viewport, as the runtime does after an edit.
/// Recompiles the document graph and renders the viewport, as the runtime does after an edit.
fn update(&mut self, document: NodeNetwork) {
let mut network = wrap_network_in_scope(document, self.editor_api.clone(), self.runtime.handle());
self.preprocessor.preprocess(&mut network, &|_| None).expect("Failed to preprocess the document");
let proto_network = Compiler {}.compile_single(network).expect("Failed to compile the document").network;
self.executor.update(proto_network).expect("Failed to update the executor");
let render_config = RenderConfig {
viewport: Footprint {
transform: DAffine2::IDENTITY,
resolution: VIEWPORT,
quality: RenderQuality::Full,
},
scale: 1.,
..Default::default()
};
let output = self.executor.tree().eval_tagged_value(self.executor.output(), &render_config.into_context());
assert!(matches!(output, Ok(graphene_std::Poll::Final(_))), "Failed to render the document: {output:?}");
// Waiting for the device puts its rasterization inside the measurement, rather than only the encoding of its commands
let _ = self.gpu.context().device.poll(wgpu::PollType::wait_indefinitely());
let _ = black_box(output);
self.gpu.compile(document);
self.gpu.render(DAffine2::IDENTITY);
}
}
@@ -110,29 +70,6 @@ fn setup_render_layer(existing: usize) -> Session {
session
}
/// Opens lavapipe, refusing a hardware device, whose work Callgrind can't see.
fn lavapipe() -> WgpuExecutor {
let context = futures::executor::block_on(WgpuContextBuilder::new().with_backends(wgpu::Backends::VULKAN).build())
.expect("No Vulkan device; install lavapipe (mesa-vulkan-drivers) and point VK_DRIVER_FILES at its ICD");
let info = context.adapter.get_info();
assert_eq!(
info.device_type,
wgpu::DeviceType::Cpu,
"Picked {} instead of a software device, which would make the counts meaningless; point VK_DRIVER_FILES at lavapipe's ICD",
info.name
);
WgpuExecutor::with_context(context).expect("Failed to create the GPU executor")
}
/// Runs spawned work to completion on the spot, so everything the graph starts happens in the measured section.
struct BlockingSpawner;
impl Spawn for BlockingSpawner {
fn spawn(&self, task: Task) {
futures::executor::block_on(task);
}
}
/// The `Brush Strokes` settings of a group, as the Brush tool starts a new group whenever its settings change.
#[derive(Clone, Copy)]
struct Style {
@@ -279,47 +216,6 @@ impl Random {
}
}
/// Callgrind's client requests for switching instrumentation, which unlike collection applies to every thread.
/// Outside Valgrind these are a few no-op rotations.
mod callgrind {
/// `VG_USERREQ_TOOL_BASE('C', 'T')` in `callgrind.h`, followed by `DUMP_STATS`, `ZERO_STATS`, `TOGGLE_COLLECT` and `DUMP_STATS_AT`
const START_INSTRUMENTATION: u64 = ((b'C' as u64) << 24 | (b'T' as u64) << 16) + 4;
const STOP_INSTRUMENTATION: u64 = START_INSTRUMENTATION + 1;
pub fn start() {
request(START_INSTRUMENTATION);
}
pub fn stop() {
request(STOP_INSTRUMENTATION);
}
/// The x86-64 form of `VALGRIND_DO_CLIENT_REQUEST_EXPR` in `valgrind.h`, which Valgrind recognizes by the preamble's rotations of `rdi` (adding up to a full turn).
#[cfg(target_arch = "x86_64")]
fn request(code: u64) {
let args = [code, 0, 0, 0, 0, 0];
// SAFETY: The rotations leave `rdi` as it was and `xchg rbx, rbx` changes nothing, so natively this only reads `args`; under Valgrind, the request writes `rdx`
unsafe {
std::arch::asm!(
"rol rdi, 3",
"rol rdi, 13",
"rol rdi, 61",
"rol rdi, 51",
"xchg rbx, rbx",
in("rax") args.as_ptr(),
inout("rdx") 0_u64 => _,
out("rdi") _,
options(nostack),
);
}
}
#[cfg(not(target_arch = "x86_64"))]
fn request(_code: u64) {
panic!("This benchmark only knows how to reach Valgrind on x86-64");
}
}
#[library_benchmark]
#[benches::existing_strokes(args = [0, 16, 256], setup = setup_add_stroke)]
pub fn add_stroke(session: Session) -> Session {
@@ -345,12 +241,6 @@ fn measure(mut session: Session) -> Session {
library_benchmark_group!(name = brush_stroke_group; benchmarks = add_stroke, render_layer);
main!(
// Only what runs between `callgrind::start` and `callgrind::stop` is measured, on every thread,
// since the device works on its own queue thread, which the default entry point (collecting on the benchmark's thread alone) would leave out
config = LibraryBenchmarkConfig::default()
.pass_through_env("VK_DRIVER_FILES")
// Rasterizing on the queue thread alone keeps the counts independent of the runner's core count
.env("LP_NUM_THREADS", "0")
.tool(Callgrind::with_args(["--instr-atstart=no"]).entry_point(EntryPoint::None));
config = gpu_util::config();
library_benchmark_groups = brush_stroke_group
);
@@ -0,0 +1,148 @@
//! Shared by the benchmarks that render documents the way the editor does, through Vello on a software Vulkan device (lavapipe),
//! so CI runners without a GPU can measure them and the counts include the "GPU" work.
use core_types::transform::{Footprint, RenderQuality};
use glam::{DAffine2, UVec2};
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::document::NodeNetwork;
use graph_craft::graphene_compiler::Compiler;
use graphene_std::application_io::{ExportFormat, RenderConfig};
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
use gungraun::{Callgrind, EntryPoint, LibraryBenchmarkConfig};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::util::wrap_network_in_scope;
use std::hint::black_box;
use std::sync::Arc;
use wgpu_executor::{WgpuContextBuilder, WgpuExecutor};
/// Small enough to keep Valgrind runs short, since the full-frame passes scale with it.
pub const VIEWPORT: UVec2 = UVec2::new(960, 540);
/// Measures only what runs between [`callgrind::start`] and [`callgrind::stop`], on every thread,
/// since the device works on its own queue thread, which the default entry point (collecting on the benchmark's thread alone) would leave out.
pub fn config() -> LibraryBenchmarkConfig {
let mut config = LibraryBenchmarkConfig::default();
config
.pass_through_env("VK_DRIVER_FILES")
// Rasterizing on the queue thread alone keeps the counts independent of the runner's core count
.env("LP_NUM_THREADS", "0")
// Shaders compiled by an earlier run, such as the baseline's, would otherwise load from disk and lower the counts
.env("MESA_SHADER_CACHE_DISABLE", "true")
.tool(Callgrind::with_args(["--instr-atstart=no"]).entry_point(EntryPoint::None));
config
}
/// A document compiled into an executor that renders it through the editor's render chain, as the editor's runtime does.
pub struct GpuDocument {
gpu: WgpuExecutor,
editor_api: Arc<PlatformEditorApi>,
runtime: AsyncRuntime,
preprocessor: preprocessor::Preprocessor,
executor: DynamicExecutor,
}
impl GpuDocument {
pub fn new() -> Self {
let gpu = lavapipe();
Self {
editor_api: Arc::new(PlatformEditorApi {
application_io: Some(Arc::new(PlatformApplicationIo::new_with_executor(gpu.clone()))),
}),
gpu,
runtime: AsyncRuntime::new(Arc::new(BlockingSpawner)),
preprocessor: preprocessor::Preprocessor::new(),
executor: DynamicExecutor::default(),
}
}
/// Wraps and compiles the document graph into the executor, as the runtime does after an edit.
pub fn compile(&mut self, document: NodeNetwork) {
let mut network = wrap_network_in_scope(document, self.editor_api.clone(), self.runtime.handle());
self.preprocessor.preprocess(&mut network, &|_| None).expect("Failed to preprocess the document");
let proto_network = Compiler {}.compile_single(network).expect("Failed to compile the document").network;
self.executor.update(proto_network).expect("Failed to update the executor");
}
/// Renders the viewport with the document placed by `transform`, waiting for the device to finish.
pub fn render(&self, transform: DAffine2) {
let render_config = RenderConfig {
viewport: Footprint {
transform,
resolution: VIEWPORT,
quality: RenderQuality::Full,
},
scale: 1.,
export_format: ExportFormat::Raster,
..Default::default()
};
let output = self.executor.tree().eval_tagged_value(self.executor.output(), &render_config.into_context());
assert!(matches!(output, Ok(graphene_std::Poll::Final(_))), "Failed to render the document: {output:?}");
// Waiting for the device puts its rasterization inside the measurement, rather than only the encoding of its commands
let _ = self.gpu.context().device.poll(wgpu::PollType::wait_indefinitely());
let _ = black_box(output);
}
}
/// Opens lavapipe, refusing a hardware device, whose work Callgrind can't see.
fn lavapipe() -> WgpuExecutor {
let context = futures::executor::block_on(WgpuContextBuilder::new().with_backends(wgpu::Backends::VULKAN).build())
.expect("No Vulkan device; install lavapipe (mesa-vulkan-drivers) and point VK_DRIVER_FILES at its ICD");
let info = context.adapter.get_info();
assert_eq!(
info.device_type,
wgpu::DeviceType::Cpu,
"Picked {} instead of a software device, which would make the counts meaningless; point VK_DRIVER_FILES at lavapipe's ICD",
info.name
);
WgpuExecutor::with_context(context).expect("Failed to create the GPU executor")
}
/// Runs spawned work to completion on the spot, so everything the graph starts happens in the measured section.
struct BlockingSpawner;
impl Spawn for BlockingSpawner {
fn spawn(&self, task: Task) {
futures::executor::block_on(task);
}
}
/// Callgrind's client requests for switching instrumentation, which unlike collection applies to every thread.
/// Outside Valgrind these are a few no-op rotations.
pub mod callgrind {
/// `VG_USERREQ_TOOL_BASE('C', 'T')` in `callgrind.h`, followed by `DUMP_STATS`, `ZERO_STATS`, `TOGGLE_COLLECT` and `DUMP_STATS_AT`
const START_INSTRUMENTATION: u64 = ((b'C' as u64) << 24 | (b'T' as u64) << 16) + 4;
const STOP_INSTRUMENTATION: u64 = START_INSTRUMENTATION + 1;
pub fn start() {
request(START_INSTRUMENTATION);
}
pub fn stop() {
request(STOP_INSTRUMENTATION);
}
/// The x86-64 form of `VALGRIND_DO_CLIENT_REQUEST_EXPR` in `valgrind.h`, which Valgrind recognizes by the preamble's rotations of `rdi` (adding up to a full turn).
#[cfg(target_arch = "x86_64")]
fn request(code: u64) {
let args = [code, 0, 0, 0, 0, 0];
// SAFETY: The rotations leave `rdi` as it was and `xchg rbx, rbx` changes nothing, so natively this only reads `args`; under Valgrind, the request writes `rdx`
unsafe {
std::arch::asm!(
"rol rdi, 3",
"rol rdi, 13",
"rol rdi, 61",
"rol rdi, 51",
"xchg rbx, rbx",
in("rax") args.as_ptr(),
inout("rdx") 0_u64 => _,
out("rdi") _,
options(nostack),
);
}
}
#[cfg(not(target_arch = "x86_64"))]
fn request(_code: u64) {
panic!("The GPU benchmarks only know how to reach Valgrind on x86-64");
}
}