mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 15:53:26 -10:00
* Update GPU and quantization to new node system Squashed commit of the following: commit 3b69bdafed79f0bb1279609537a8eeead3f06830 Author: Dennis Kobert <[email protected]> Date: Sun Mar 5 11:37:17 2023 +0100 Disable dev tools by default commit dbbbedd68e48d1162442574ad8877c9922d40e4a Merge: b1018eb5 a8f6e11e Author: Dennis Kobert <[email protected]> Date: Sun Mar 5 10:45:00 2023 +0100 Merge branch 'vite' into tauri-restructure-lite commit b1018eb5ee56c2d23f9d5a4f034608ec684bd746 Merge: 3195833e0512cb24Author: Dennis Kobert <[email protected]> Date: Fri Mar 3 17:06:21 2023 +0100 Merge branch 'master' into tauri-restructure-lite commit 3195833e4088a4ed7984955c72617b27b7e39bfc Author: Dennis Kobert <[email protected]> Date: Fri Mar 3 17:06:02 2023 +0100 Bump number of samples commit 3e57e1e3280759cf4f75726635e31d2b8e9387f9 Author: Dennis Kobert <[email protected]> Date: Fri Mar 3 16:55:52 2023 +0100 Move part of quantization code to gcore commit 10c15b0bc6ffb51e2bf2d94cd4eb0e24d761fb6f Merge: 2b3db45a8fe8896cAuthor: Dennis Kobert <[email protected]> Date: Fri Mar 3 14:28:56 2023 +0100 Merge remote-tracking branch 'origin/master' into tauri-restructure-lite commit 2b3db45aee44a20660f0b1204666bb81e5a7e4b6 Author: Dennis Kobert <[email protected]> Date: Fri Mar 3 14:17:11 2023 +0100 Fix types in node registry commit 9122f35c0ba9a86255709680d744a48d3c7dcac4 Merge: 26eefc432cf4ee0fAuthor: Dennis Kobert <[email protected]> Date: Fri Mar 3 01:04:55 2023 +0100 Merge remote-tracking branch 'origin/master' into tauri-restructure-lite commit 26eefc437eaad873f8d38fdb1fae0a1e3ec189e4 Author: Dennis Kobert <[email protected]> Date: Thu Mar 2 23:05:53 2023 +0100 Add Quantize node to document_node_types commit 3f7606a91329200b2c025010d4a0cffee840a11c Author: Dennis Kobert <[email protected]> Date: Thu Mar 2 17:47:51 2023 +0100 Add quantization nodes to node registry commit 22d8e477ef79eef5b57b1dc9805e41bbf81cae43 Author: Dennis Kobert <[email protected]> Date: Thu Mar 2 17:13:28 2023 +0100 Introduce scopes (#1053) * Implement let binding * Add lambda inputs * Fix tests * Fix proto network formatting * Generate a template Scoped network by default * Add comment to explain the lambda parameter * Move binding wrapping out of the template * Fix errors cause by image frames commit 9e0c29d92a164d4a4063e93480e1e289ef5243fe Author: Alexandru Ică <[email protected]> Date: Thu Mar 2 15:55:10 2023 +0200 Make use of ImageFrame in the node system more extensively (#1055) (#1062) Make the node system use ImageFrame more extensively (#1055) commit 5912ef9a1a807917eeb90c1f4835bd8a5de9c821 Author: Dennis Kobert <[email protected]> Date: Wed Mar 1 16:15:21 2023 +0100 Split quantization into multiple nodes commit 285d7b76c176b3e2679ea24eecb38ef867a79f3b Author: Dennis Kobert <[email protected]> Date: Mon Feb 27 12:35:57 2023 +0100 Fix gpu support commit e0b6327eebba8caf7545c4fedc6670abc4c3652e Author: Dennis Kobert <[email protected]> Date: Thu Feb 16 22:08:53 2023 +0100 Don't watch frontend files when using tauri commit 58ae146f6da935cfd37afbd25e1c331b615252da Author: Dennis Kobert <[email protected]> Date: Thu Feb 16 21:48:54 2023 +0100 Migrate vue code base to vite commit f996390cc312618a60f98ccb9cd515f1bae5006d Author: Dennis Kobert <[email protected]> Date: Thu Feb 16 19:34:33 2023 +0100 Start migrating vue to use vite commit 29d752f47cfd1c74ee51fac6f3d75557a378471c Author: Dennis Kobert <[email protected]> Date: Thu Feb 16 19:00:53 2023 +0100 Kill cargo watch process automatically commit 4d1c76b07acadbf609dbab7d57d9a7769b81d4b5 Author: Dennis Kobert <[email protected]> Date: Thu Feb 16 17:37:27 2023 +0100 Start playing around with vite infrastructure commit 8494f5e9227aa433fd5ca75b268a6a96b2706b36 Author: Locria Cyber <[email protected]> Date: Thu Jan 19 18:40:46 2023 +0000 Fix import style and eslint rules commit 92490f7774a7351bb40091bcec78f79c28704768 Author: Locria Cyber <[email protected]> Date: Thu Jan 19 18:25:09 2023 +0000 Fix icons commit dc67821abad87f8ff780b12ae96668af2f7bb355 Author: Locria Cyber <[email protected]> Date: Thu Jan 19 18:20:48 2023 +0000 Add license generator with rollup commit 441e339d31b76dac4f91321d39a39900b5a79bc1 Author: Locria Cyber <[email protected]> Date: Thu Jan 19 18:14:22 2023 +0000 Use eslint --fix to fix TS-in-svelte type imports. Now it compiles. commit 2e847d339e7dcd51ed4c4677ed337c1e20636724 Author: Locria Cyber <[email protected]> Date: Thu Jan 19 17:31:49 2023 +0000 Remove webpack and plugins commit 3adab1b7f40ff17b91163e7ca47a403ef3c02fbc Author: Dennis Kobert <[email protected]> Date: Thu Mar 2 16:10:19 2023 +0100 Fix errors cause by image frames commit 4e5f838995e213b4696225a473b9c56c0084e7a8 Author: Alexandru Ică <[email protected]> Date: Thu Mar 2 15:55:10 2023 +0200 Make use of ImageFrame in the node system more extensively (#1055) (#1062) Make the node system use ImageFrame more extensively (#1055) commit 1d4b0e29c693a53c068f1a30f0e857a9c1a59587 Author: Dennis Kobert <[email protected]> Date: Wed Mar 1 15:13:51 2023 +0100 Update node graph guide readme with new syntax (#1061) commit 6735d8c61f5709e22d2b22abd037bab417e868d6 Author: Rob Nadal <[email protected]> Date: Tue Feb 28 18:59:06 2023 -0500 Bezier-rs: Add function to smoothly join bezier curves (#1037) * Added bezier join * Stylistic changes per review commit cd1d7aa7fbcce39fbbf7762d131ee16ad9cb46dd Author: Dennis Kobert <[email protected]> Date: Wed Feb 22 23:42:32 2023 +0100 Implement let binding Add lambda inputs Fix tests Fix proto network formatting Generate a template Scoped network by default Add comment to explain the lambda parameter Move binding wrapping out of the template * Update package-lock.json * Regenerate package-lock.json and fix lint errors * Readd git keep dir * Revert change to panic.ts * Fix clippy warnings * Apply code review * Clean up node_registry * Fix test / spriv -> spirv typos
251 lines
8.8 KiB
Rust
251 lines
8.8 KiB
Rust
use std::borrow::Cow;
|
|
use std::sync::Arc;
|
|
use wgpu::util::DeviceExt;
|
|
|
|
use super::context::Context;
|
|
use bytemuck::Pod;
|
|
use dyn_any::StaticTypeSized;
|
|
use graph_craft::executor::{Any, Executor};
|
|
|
|
#[derive(Debug)]
|
|
pub struct GpuExecutor<'a, I: StaticTypeSized, O> {
|
|
context: Context,
|
|
entry_point: String,
|
|
shader: Cow<'a, [u32]>,
|
|
_phantom: std::marker::PhantomData<(I, O)>,
|
|
}
|
|
|
|
impl<'a, I: StaticTypeSized, O> GpuExecutor<'a, I, O> {
|
|
pub fn new(context: Context, shader: Cow<'a, [u32]>, entry_point: String) -> anyhow::Result<Self> {
|
|
log::info!("Creating executor");
|
|
Ok(Self {
|
|
context,
|
|
entry_point,
|
|
shader,
|
|
_phantom: std::marker::PhantomData,
|
|
})
|
|
}
|
|
}
|
|
|
|
impl<'a, I: StaticTypeSized + Sync + Pod + Send, O: StaticTypeSized + Send + Sync + Pod> Executor for GpuExecutor<'a, I, O> {
|
|
fn execute<'i, 's: 'i>(&'s self, input: Any<'i>) -> Result<Any<'i>, Box<dyn std::error::Error>> {
|
|
log::info!("Executing shader");
|
|
let input = dyn_any::downcast::<Vec<I>>(input).expect("Wrong input type");
|
|
let context = &self.context;
|
|
let future = execute_shader(context.device.clone(), context.queue.clone(), self.shader.to_vec(), *input, self.entry_point.clone());
|
|
let result = future_executor::block_on(future);
|
|
|
|
let result: Vec<O> = result.ok_or_else(|| String::from("Failed to execute shader"))?;
|
|
Ok(Box::new(result))
|
|
}
|
|
}
|
|
|
|
async fn execute_shader<I: Pod + Send + Sync, O: Pod + Send + Sync>(device: Arc<wgpu::Device>, queue: Arc<wgpu::Queue>, shader: Vec<u32>, data: Vec<I>, entry_point: String) -> Option<Vec<O>> {
|
|
// Loads the shader from WGSL
|
|
dbg!(&shader);
|
|
//write shader to file
|
|
use std::io::Write;
|
|
let mut file = std::fs::File::create("/tmp/shader.spv").unwrap();
|
|
file.write_all(bytemuck::cast_slice(&shader)).unwrap();
|
|
let cs_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
|
label: None,
|
|
source: wgpu::ShaderSource::SpirV(shader.into()),
|
|
});
|
|
|
|
// Gets the size in bytes of the buffer.
|
|
let slice_size = data.len() * std::mem::size_of::<O>();
|
|
let size = slice_size as wgpu::BufferAddress;
|
|
|
|
// Instantiates buffer without data.
|
|
// `usage` of buffer specifies how it can be used:
|
|
// `BufferUsages::MAP_READ` allows it to be read (outside the shader).
|
|
// `BufferUsages::COPY_DST` allows it to be the destination of the copy.
|
|
let staging_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
|
label: None,
|
|
size,
|
|
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
|
|
mapped_at_creation: false,
|
|
});
|
|
|
|
// Instantiates buffer with data (`numbers`).
|
|
// Usage allowing the buffer to be:
|
|
// A storage buffer (can be bound within a bind group and thus available to a shader).
|
|
// The destination of a copy.
|
|
// The source of a copy.
|
|
let storage_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
|
label: Some("Storage Buffer"),
|
|
contents: bytemuck::cast_slice(&data),
|
|
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC,
|
|
});
|
|
|
|
// Instantiates empty buffer for the result.
|
|
// Usage allowing the buffer to be:
|
|
// A storage buffer (can be bound within a bind group and thus available to a shader).
|
|
// The destination of a copy.
|
|
// The source of a copy.
|
|
let dest_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
|
label: Some("Destination Buffer"),
|
|
size,
|
|
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
|
|
mapped_at_creation: false,
|
|
});
|
|
|
|
// A bind group defines how buffers are accessed by shaders.
|
|
// It is to WebGPU what a descriptor set is to Vulkan.
|
|
// `binding` here refers to the `binding` of a buffer in the shader (`layout(set = 0, binding = 0) buffer`).
|
|
|
|
// A pipeline specifies the operation of a shader
|
|
|
|
// Instantiates the pipeline.
|
|
let compute_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
|
label: None,
|
|
layout: None,
|
|
module: &cs_module,
|
|
entry_point: entry_point.as_str(),
|
|
});
|
|
|
|
// Instantiates the bind group, once again specifying the binding of buffers.
|
|
let bind_group_layout = compute_pipeline.get_bind_group_layout(0);
|
|
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
|
label: None,
|
|
layout: &bind_group_layout,
|
|
entries: &[
|
|
wgpu::BindGroupEntry {
|
|
binding: 0,
|
|
resource: storage_buffer.as_entire_binding(),
|
|
},
|
|
wgpu::BindGroupEntry {
|
|
binding: 1,
|
|
resource: dest_buffer.as_entire_binding(),
|
|
},
|
|
],
|
|
});
|
|
|
|
// A command encoder executes one or many pipelines.
|
|
// It is to WebGPU what a command buffer is to Vulkan.
|
|
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
|
|
{
|
|
let mut cpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: None });
|
|
cpass.set_pipeline(&compute_pipeline);
|
|
cpass.set_bind_group(0, &bind_group, &[]);
|
|
cpass.insert_debug_marker("compute node network evaluation");
|
|
cpass.dispatch_workgroups(data.len().min(65535) as u32, 1, 1); // Number of cells to run, the (x,y,z) size of item being processed
|
|
}
|
|
// Sets adds copy operation to command encoder.
|
|
// Will copy data from storage buffer on GPU to staging buffer on CPU.
|
|
encoder.copy_buffer_to_buffer(&dest_buffer, 0, &staging_buffer, 0, size);
|
|
|
|
// Submits command encoder for processing
|
|
queue.submit(Some(encoder.finish()));
|
|
|
|
// Note that we're not calling `.await` here.
|
|
let buffer_slice = staging_buffer.slice(..);
|
|
// Sets the buffer up for mapping, sending over the result of the mapping back to us when it is finished.
|
|
let (sender, receiver) = futures_intrusive::channel::shared::oneshot_channel();
|
|
buffer_slice.map_async(wgpu::MapMode::Read, move |v| sender.send(v).unwrap());
|
|
|
|
// Poll the device in a blocking manner so that our future resolves.
|
|
// In an actual application, `device.poll(...)` should
|
|
// be called in an event loop or on another thread.
|
|
device.poll(wgpu::Maintain::Wait);
|
|
|
|
// Awaits until `buffer_future` can be read from
|
|
#[cfg(feature = "profiling")]
|
|
nvtx::range_push!("compute");
|
|
let result = receiver.receive().await;
|
|
#[cfg(feature = "profiling")]
|
|
nvtx::range_pop!();
|
|
if let Some(Ok(())) = result {
|
|
// Gets contents of buffer
|
|
let data = buffer_slice.get_mapped_range();
|
|
// Since contents are got in bytes, this converts these bytes back to u32
|
|
let result = bytemuck::cast_slice(&data).to_vec();
|
|
|
|
// With the current interface, we have to make sure all mapped views are
|
|
// dropped before we unmap the buffer.
|
|
drop(data);
|
|
staging_buffer.unmap(); // Unmaps buffer from memory
|
|
// If you are familiar with C++ these 2 lines can be thought of similarly to:
|
|
// delete myPointer;
|
|
// myPointer = NULL;
|
|
// It effectively frees the memory
|
|
|
|
// Returns data from buffer
|
|
Some(result)
|
|
} else {
|
|
panic!("failed to run compute on gpu!")
|
|
}
|
|
}
|
|
|
|
// TODO: Fix this test
|
|
// #[cfg(test)]
|
|
// mod test {
|
|
// use super::*;
|
|
// use graph_craft::concrete;
|
|
// use graph_craft::generic;
|
|
// use graph_craft::proto::*;
|
|
|
|
// #[test]
|
|
// fn add_on_gpu() {
|
|
// use crate::executor::Executor;
|
|
// let m = compiler::Metadata::new("project".to_owned(), vec!["[email protected]".to_owned()]);
|
|
// let network = inc_network();
|
|
// let temp_dir = tempfile::tempdir().expect("failed to create tempdir");
|
|
|
|
// let executor: GpuExecutor<u32, u32> = GpuExecutor::new(Context::new(), network, m, temp_dir.path()).unwrap();
|
|
|
|
// let data: Vec<_> = (0..1024).map(|x| x as u32).collect();
|
|
// let result = executor.execute(Box::new(data)).unwrap();
|
|
// let result = dyn_any::downcast::<Vec<u32>>(result).unwrap();
|
|
// for (i, r) in result.iter().enumerate() {
|
|
// assert_eq!(*r, i as u32 + 3);
|
|
// }
|
|
// }
|
|
|
|
// fn inc_network() -> ProtoNetwork {
|
|
// let mut construction_network = ProtoNetwork {
|
|
// inputs: vec![10],
|
|
// output: 1,
|
|
// nodes: [
|
|
// (
|
|
// 1,
|
|
// ProtoNode {
|
|
// identifier: NodeIdentifier::new("graphene_core::ops::IdNode", &[generic!("u32")]),
|
|
// input: ProtoNodeInput::Node(11),
|
|
// construction_args: ConstructionArgs::Nodes(vec![]),
|
|
// },
|
|
// ),
|
|
// (
|
|
// 10,
|
|
// ProtoNode {
|
|
// identifier: NodeIdentifier::new("graphene_core::structural::ConsNode", &[generic!("&ValueNode<u32>"), generic!("()")]),
|
|
// input: ProtoNodeInput::Network,
|
|
// construction_args: ConstructionArgs::Nodes(vec![14]),
|
|
// },
|
|
// ),
|
|
// (
|
|
// 11,
|
|
// ProtoNode {
|
|
// identifier: NodeIdentifier::new("graphene_core::ops::AddNode", &[generic!("u32"), generic!("u32")]),
|
|
// input: ProtoNodeInput::Node(10),
|
|
// construction_args: ConstructionArgs::Nodes(vec![]),
|
|
// },
|
|
// ),
|
|
// (
|
|
// 14,
|
|
// ProtoNode {
|
|
// identifier: NodeIdentifier::new("graphene_core::value::ValueNode", &[concrete!("u32")]),
|
|
// input: ProtoNodeInput::None,
|
|
// construction_args: ConstructionArgs::Value(Box::new(3_u32)),
|
|
// },
|
|
// ),
|
|
// ]
|
|
// .into_iter()
|
|
// .collect(),
|
|
// };
|
|
// construction_network.resolve_inputs();
|
|
// construction_network.reorder_ids();
|
|
// construction_network
|
|
// }
|
|
// }
|