Compare commits

...
5 Commits
5 changed files with 2009 additions and 0 deletions

No files matched your search

+1232
View File
File diff suppressed because it is too large. Load diff
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "mac-gpu-probe"
version = "0.0.0"
edition = "2024"
publish = false
# Kept out of the repository's workspace
[workspace]
[dependencies]
wgpu = { version = "30.0", default-features = false, features = ["std", "parking_lot", "dx12", "metal", "vulkan", "wgsl"] }
pollster = "0.4"
env_logger = "0.11"
[target.'cfg(target_os = "macos")'.dependencies]
objc2 = "0.6"
objc2-foundation = "0.3"
objc2-metal = "0.3"
+337
View File
@@ -0,0 +1,337 @@
// Probes whether a CI runner's GPU is real enough to profile on: what adapter it exposes, whether GPU timestamps work,
// how close compute and bandwidth throughput come to the hardware's peak, and how steady repeated measurements are
use std::time::Instant;
#[cfg(target_os = "macos")]
mod metal_direct;
const WARMUP_RUNS: usize = 3;
const TIMED_RUNS: usize = 20;
const SUBMIT_RUNS: usize = 100;
// 4 independent FMA chains on vec4s, 256 iterations: 4 * 4 * 2 * 256 = 8192 FLOPs per invocation.
// Every component starts from the invocation ID, since a constant one lets the compiler precompute its whole chain.
const ALU_SHADER: &str = r#"
@group(0) @binding(0) var<storage, read_write> output: array<vec4<f32>>;
@compute @workgroup_size(256)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
var a0 = f32(id.x) * 1e-7 + vec4<f32>(0.0, 1.0, 2.0, 3.0);
var a1 = a0 + 0.1;
var a2 = a0 + 0.2;
var a3 = a0 + 0.3;
let b0 = vec4<f32>(0.9999, 0.9998, 0.9997, 0.9996);
let b1 = vec4<f32>(0.9995, 0.9994, 0.9993, 0.9992);
let b2 = vec4<f32>(0.9991, 0.9990, 0.9989, 0.9988);
let b3 = vec4<f32>(0.9987, 0.9986, 0.9985, 0.9984);
let c = vec4<f32>(1e-4, 2e-4, 3e-4, 4e-4);
for (var i = 0u; i < 256u; i++) {
a0 = fma(a0, b0, c);
a1 = fma(a1, b1, c);
a2 = fma(a2, b2, c);
a3 = fma(a3, b3, c);
}
output[id.x] = a0 + a1 + a2 + a3;
}
"#;
const ALU_WORKGROUPS: u32 = 4096;
const ALU_FLOPS_PER_INVOCATION: f64 = 8192.;
const BANDWIDTH_SHADER: &str = r#"
@group(0) @binding(0) var<storage, read> source: array<vec4<f32>>;
@group(0) @binding(1) var<storage, read_write> destination: array<vec4<f32>>;
@compute @workgroup_size(256)
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
if (id.x < arrayLength(&source)) {
destination[id.x] = source[id.x] * 1.0001;
}
}
"#;
const BANDWIDTH_BUFFER_BYTES: u64 = 128 * 1024 * 1024;
struct Gpu {
device: wgpu::Device,
queue: wgpu::Queue,
timestamps: Option<Timestamps>,
}
struct Timestamps {
query_set: wgpu::QuerySet,
resolve: wgpu::Buffer,
readback: wgpu::Buffer,
nanoseconds_per_tick: f64,
}
fn main() {
// With `RUST_LOG=wgpu_hal::metal::device=debug`, prints the Metal source wgpu generates for each shader
env_logger::init();
pollster::block_on(run());
}
async fn run() {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends: wgpu::Backends::PRIMARY,
..wgpu::InstanceDescriptor::new_without_display_handle()
});
println!("== Adapters");
for adapter in instance.enumerate_adapters(wgpu::Backends::PRIMARY).await {
let info = adapter.get_info();
println!("{:?} | {} | {:?} | driver {} {}", info.backend, info.name, info.device_type, info.driver, info.driver_info);
}
let Ok(adapter) = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
..Default::default()
})
.await
else {
println!("RESULT: no GPU adapter available");
return;
};
let info = adapter.get_info();
let limits = adapter.limits();
let has_timestamps = adapter.features().contains(wgpu::Features::TIMESTAMP_QUERY);
println!("\n== Chosen adapter\n{:?} | {} | {:?}", info.backend, info.name, info.device_type);
println!("timestamp queries: {has_timestamps}");
println!("max storage buffer binding: {} MiB, max buffer: {} MiB", limits.max_storage_buffer_binding_size / (1 << 20), limits.max_buffer_size / (1 << 20));
let required_features = if has_timestamps { wgpu::Features::TIMESTAMP_QUERY } else { wgpu::Features::empty() };
let Ok((device, queue)) = adapter
.request_device(&wgpu::DeviceDescriptor {
label: None,
required_features,
required_limits: limits,
memory_hints: Default::default(),
trace: wgpu::Trace::Off,
experimental_features: Default::default(),
})
.await
else {
println!("RESULT: the adapter refused to create a device");
return;
};
let timestamps = has_timestamps.then(|| Timestamps {
query_set: device.create_query_set(&wgpu::QuerySetDescriptor {
label: None,
ty: wgpu::QueryType::Timestamp,
count: 2,
}),
resolve: device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: 16,
usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
}),
readback: device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: 16,
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
}),
nanoseconds_per_tick: queue.get_timestamp_period() as f64,
});
let gpu = Gpu { device, queue, timestamps };
submit_latency(&gpu);
alu_throughput(&gpu);
bandwidth(&gpu);
#[cfg(target_os = "macos")]
metal_direct::run();
}
// Round trips of an empty submission, the fixed overhead any per-frame measurement includes
fn submit_latency(gpu: &Gpu) {
let mut microseconds = Vec::new();
for i in 0..(WARMUP_RUNS + SUBMIT_RUNS) {
let start = Instant::now();
let encoder = gpu.device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
gpu.queue.submit(Some(encoder.finish()));
let _ = gpu.device.poll(wgpu::PollType::wait_indefinitely());
if i >= WARMUP_RUNS {
microseconds.push(start.elapsed().as_secs_f64() * 1e6);
}
}
println!("\n== Empty submit round trip (µs)\n{}", summarize(&microseconds));
}
fn alu_throughput(gpu: &Gpu) {
let invocations = ALU_WORKGROUPS as u64 * 256;
let output = gpu.device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: invocations * 16,
usage: wgpu::BufferUsages::STORAGE,
mapped_at_creation: false,
});
let gflops = |milliseconds: f64| invocations as f64 * ALU_FLOPS_PER_INVOCATION / (milliseconds * 1e6);
println!("\n== FP32 compute ({:.1} GFLOP per dispatch)", invocations as f64 * ALU_FLOPS_PER_INVOCATION / 1e9);
for (variant, runtime_checks) in runtime_check_variants() {
let (pipeline, bind_group) = pipeline(gpu, ALU_SHADER, &[&output], runtime_checks);
let (gpu_milliseconds, wall_milliseconds) = time_dispatch(gpu, &pipeline, &bind_group, ALU_WORKGROUPS);
println!("-- Shader {variant}");
report(&gpu_milliseconds, &wall_milliseconds, "GFLOPS", gflops);
}
}
// The safety code wgpu adds to shaders by default, toggled to see which part (if any) slows them down
fn runtime_check_variants() -> [(&'static str, wgpu::ShaderRuntimeChecks); 4] {
let checked = wgpu::ShaderRuntimeChecks::checked();
[
("with wgpu's default checks", checked),
("without bounds checks", wgpu::ShaderRuntimeChecks { bounds_checks: false, ..checked }),
("without forced loop bounding", wgpu::ShaderRuntimeChecks { force_loop_bounding: false, ..checked }),
("without any checks", wgpu::ShaderRuntimeChecks::unchecked()),
]
}
fn bandwidth(gpu: &Gpu) {
let source = gpu.device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: BANDWIDTH_BUFFER_BYTES,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let destination = gpu.device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: BANDWIDTH_BUFFER_BYTES,
usage: wgpu::BufferUsages::STORAGE,
mapped_at_creation: false,
});
// Nonzero contents, in case the hardware compresses zeros
let pattern: Vec<u8> = (0..BANDWIDTH_BUFFER_BYTES).map(|i| (i * 2_654_435_761 >> 24) as u8).collect();
gpu.queue.write_buffer(&source, 0, &pattern);
let workgroups = (BANDWIDTH_BUFFER_BYTES / 16 / 256) as u32;
let bytes_moved = 2. * BANDWIDTH_BUFFER_BYTES as f64;
let gigabytes_per_second = |milliseconds: f64| bytes_moved / (milliseconds * 1e6);
println!("\n== Memory bandwidth ({} MiB read + {} MiB written per dispatch)", BANDWIDTH_BUFFER_BYTES >> 20, BANDWIDTH_BUFFER_BYTES >> 20);
for (variant, runtime_checks) in runtime_check_variants() {
let (pipeline, bind_group) = pipeline(gpu, BANDWIDTH_SHADER, &[&source, &destination], runtime_checks);
let (gpu_milliseconds, wall_milliseconds) = time_dispatch(gpu, &pipeline, &bind_group, workgroups);
println!("-- Shader {variant}");
report(&gpu_milliseconds, &wall_milliseconds, "GB/s", gigabytes_per_second);
}
}
fn pipeline(gpu: &Gpu, shader: &str, buffers: &[&wgpu::Buffer], runtime_checks: wgpu::ShaderRuntimeChecks) -> (wgpu::ComputePipeline, wgpu::BindGroup) {
let descriptor = wgpu::ShaderModuleDescriptor {
label: None,
source: wgpu::ShaderSource::Wgsl(shader.into()),
};
// The shaders here only index within their dispatch, so skipping the checks can't read or write out of bounds
let module = unsafe { gpu.device.create_shader_module_trusted(descriptor, runtime_checks) };
let pipeline = gpu.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: None,
layout: None,
module: &module,
entry_point: Some("main"),
compilation_options: Default::default(),
cache: None,
});
let entries: Vec<_> = buffers
.iter()
.enumerate()
.map(|(binding, buffer)| wgpu::BindGroupEntry {
binding: binding as u32,
resource: buffer.as_entire_binding(),
})
.collect();
let bind_group = gpu.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &pipeline.get_bind_group_layout(0),
entries: &entries,
});
(pipeline, bind_group)
}
// Returns per-run GPU times from timestamp queries (empty if unsupported) and wall-clock times around submit-and-wait
fn time_dispatch(gpu: &Gpu, pipeline: &wgpu::ComputePipeline, bind_group: &wgpu::BindGroup, workgroups: u32) -> (Vec<f64>, Vec<f64>) {
let mut gpu_milliseconds = Vec::new();
let mut wall_milliseconds = Vec::new();
for i in 0..(WARMUP_RUNS + TIMED_RUNS) {
let mut encoder = gpu.device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
{
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: None,
timestamp_writes: gpu.timestamps.as_ref().map(|timestamps| wgpu::ComputePassTimestampWrites {
query_set: &timestamps.query_set,
beginning_of_pass_write_index: Some(0),
end_of_pass_write_index: Some(1),
}),
});
pass.set_pipeline(pipeline);
pass.set_bind_group(0, bind_group, &[]);
pass.dispatch_workgroups(workgroups, 1, 1);
}
if let Some(timestamps) = &gpu.timestamps {
encoder.resolve_query_set(&timestamps.query_set, 0..2, &timestamps.resolve, 0);
encoder.copy_buffer_to_buffer(&timestamps.resolve, 0, &timestamps.readback, 0, 16);
}
let start = Instant::now();
gpu.queue.submit(Some(encoder.finish()));
let _ = gpu.device.poll(wgpu::PollType::wait_indefinitely());
let wall = start.elapsed().as_secs_f64() * 1e3;
let gpu_time = gpu.timestamps.as_ref().and_then(|timestamps| read_timestamps(gpu, timestamps));
if i >= WARMUP_RUNS {
wall_milliseconds.push(wall);
gpu_milliseconds.extend(gpu_time);
}
}
(gpu_milliseconds, wall_milliseconds)
}
fn read_timestamps(gpu: &Gpu, timestamps: &Timestamps) -> Option<f64> {
let slice = timestamps.readback.slice(..);
slice.map_async(wgpu::MapMode::Read, |_| {});
let _ = gpu.device.poll(wgpu::PollType::wait_indefinitely());
let ticks = {
let bytes = slice.get_mapped_range().ok()?;
let start = u64::from_le_bytes(bytes[0..8].try_into().ok()?);
let end = u64::from_le_bytes(bytes[8..16].try_into().ok()?);
end.checked_sub(start)
};
timestamps.readback.unmap();
ticks.filter(|&ticks| ticks > 0).map(|ticks| ticks as f64 * timestamps.nanoseconds_per_tick / 1e6)
}
fn report(gpu_milliseconds: &[f64], wall_milliseconds: &[f64], unit: &str, throughput: impl Fn(f64) -> f64) {
if gpu_milliseconds.is_empty() {
println!("GPU time: unavailable");
} else {
println!("GPU time (ms): {}", summarize(gpu_milliseconds));
println!("Throughput from median GPU time: {:.1} {unit}", throughput(median(gpu_milliseconds)));
}
println!("Wall time (ms): {}", summarize(wall_milliseconds));
println!("Throughput from median wall time: {:.1} {unit}", throughput(median(wall_milliseconds)));
}
fn median(values: &[f64]) -> f64 {
let mut sorted = values.to_vec();
sorted.sort_by(f64::total_cmp);
sorted[sorted.len() / 2]
}
fn summarize(values: &[f64]) -> String {
let mean = values.iter().sum::<f64>() / values.len() as f64;
let deviation = (values.iter().map(|value| (value - mean).powi(2)).sum::<f64>() / values.len() as f64).sqrt();
let min = values.iter().copied().fold(f64::INFINITY, f64::min);
let max = values.iter().copied().fold(f64::NEG_INFINITY, f64::max);
format!("median {:.3}, min {min:.3}, max {max:.3}, spread {:.2}% (n={})", median(values), deviation / mean * 100., values.len())
}
+380
View File
@@ -0,0 +1,380 @@
// Runs the probe's workloads through Metal directly, timed by each command buffer's own GPU start and end times,
// which Metal reports even where counter sampling (and therefore wgpu's timestamp queries) is unavailable
use std::ptr::NonNull;
use std::time::{Duration, Instant};
use objc2::rc::Retained;
use objc2::runtime::ProtocolObject;
use objc2_foundation::NSString;
use objc2_metal::{
MTLBuffer, MTLCommandBuffer, MTLCommandEncoder, MTLCommandQueue, MTLCompileOptions, MTLComputeCommandEncoder, MTLComputePipelineState, MTLCounterSamplingPoint, MTLCounterSet, MTLCreateSystemDefaultDevice, MTLDevice,
MTLLibrary, MTLResourceOptions, MTLSize,
};
use crate::{ALU_FLOPS_PER_INVOCATION, ALU_WORKGROUPS, BANDWIDTH_BUFFER_BYTES, TIMED_RUNS, WARMUP_RUNS, median, summarize};
const SHADERS: &str = r#"
#include <metal_stdlib>
using namespace metal;
kernel void alu(device float4 *output [[buffer(0)]], uint id [[thread_position_in_grid]]) {
float4 a0 = float(id) * 1e-7 + float4(0.0, 1.0, 2.0, 3.0);
float4 a1 = a0 + 0.1;
float4 a2 = a0 + 0.2;
float4 a3 = a0 + 0.3;
const float4 b0 = float4(0.9999, 0.9998, 0.9997, 0.9996);
const float4 b1 = float4(0.9995, 0.9994, 0.9993, 0.9992);
const float4 b2 = float4(0.9991, 0.9990, 0.9989, 0.9988);
const float4 b3 = float4(0.9987, 0.9986, 0.9985, 0.9984);
const float4 c = float4(1e-4, 2e-4, 3e-4, 4e-4);
for (uint i = 0; i < 256; i++) {
a0 = fma(a0, b0, c);
a1 = fma(a1, b1, c);
a2 = fma(a2, b2, c);
a3 = fma(a3, b3, c);
}
output[id] = a0 + a1 + a2 + a3;
}
kernel void bandwidth(device const float4 *source [[buffer(0)]], device float4 *destination [[buffer(1)]], uint id [[thread_position_in_grid]]) {
destination[id] = source[id] * 1.0001;
}
"#;
// What wgpu generated for the probe's WGSL compute shader (copied from its debug log), with its default checks
const NAGA_CHECKED: &str = r#"
#include <metal_stdlib>
#include <simd/simd.h>
using metal::uint;
struct _mslBufferSizes {
uint size0;
};
typedef metal::float4 type_1[1];
[[max_total_threads_per_threadgroup(256)]] kernel void main_(
metal::uint3 id [[thread_position_in_grid]]
, device type_1& output [[buffer(0)]]
, constant _mslBufferSizes& _buffer_sizes [[buffer(1)]]
) {
metal::float4 a0_ = {};
metal::float4 a1_ = {};
metal::float4 a2_ = {};
metal::float4 a3_ = {};
uint i = 0u;
a0_ = metal::float4(static_cast<float>(id.x) * 0.0000001) + metal::float4(0.0, 1.0, 2.0, 3.0);
metal::float4 _e13 = a0_;
a1_ = _e13 + metal::float4(0.1);
metal::float4 _e18 = a0_;
a2_ = _e18 + metal::float4(0.2);
metal::float4 _e23 = a0_;
a3_ = _e23 + metal::float4(0.3);
metal::float4 b0_ = metal::float4(0.9999, 0.9998, 0.9997, 0.9996);
metal::float4 b1_ = metal::float4(0.9995, 0.9994, 0.9993, 0.9992);
metal::float4 b2_ = metal::float4(0.9991, 0.999, 0.9989, 0.9988);
metal::float4 b3_ = metal::float4(0.9987, 0.9986, 0.9985, 0.9984);
metal::float4 c = metal::float4(0.0001, 0.0002, 0.0003, 0.0004);
uint2 loop_bound = uint2(4294967295u);
bool loop_init = true;
while(true) {
if (metal::all(loop_bound == uint2(0u))) { break; }
loop_bound -= uint2(loop_bound.y == 0u, 1u);
if (!loop_init) {
uint _e67 = i;
i = _e67 + 1u;
}
loop_init = false;
uint _e55 = i;
if (_e55 < 256u) {
} else {
break;
}
{
metal::float4 _e58 = a0_;
a0_ = metal::fma(_e58, b0_, c);
metal::float4 _e60 = a1_;
a1_ = metal::fma(_e60, b1_, c);
metal::float4 _e62 = a2_;
a2_ = metal::fma(_e62, b2_, c);
metal::float4 _e64 = a3_;
a3_ = metal::fma(_e64, b3_, c);
}
}
metal::float4 _e72 = a0_;
metal::float4 _e73 = a1_;
metal::float4 _e75 = a2_;
metal::float4 _e77 = a3_;
output[metal::min(unsigned(id.x), (_buffer_sizes.size0 - 0 - 16) / 16)] = ((_e72 + _e73) + _e75) + _e77;
return;
}
"#;
// What wgpu generated with its checks off, which still emits the loop as `while (true)` with a `loop_init` flag
const NAGA_UNCHECKED: &str = r#"
#include <metal_stdlib>
#include <simd/simd.h>
using metal::uint;
struct _mslBufferSizes {
uint size0;
};
typedef metal::float4 type_1[1];
[[max_total_threads_per_threadgroup(256)]] kernel void main_(
metal::uint3 id [[thread_position_in_grid]]
, device type_1& output [[buffer(0)]]
, constant _mslBufferSizes& _buffer_sizes [[buffer(1)]]
) {
metal::float4 a0_ = {};
metal::float4 a1_ = {};
metal::float4 a2_ = {};
metal::float4 a3_ = {};
uint i = 0u;
a0_ = metal::float4(static_cast<float>(id.x) * 0.0000001) + metal::float4(0.0, 1.0, 2.0, 3.0);
metal::float4 _e13 = a0_;
a1_ = _e13 + metal::float4(0.1);
metal::float4 _e18 = a0_;
a2_ = _e18 + metal::float4(0.2);
metal::float4 _e23 = a0_;
a3_ = _e23 + metal::float4(0.3);
metal::float4 b0_ = metal::float4(0.9999, 0.9998, 0.9997, 0.9996);
metal::float4 b1_ = metal::float4(0.9995, 0.9994, 0.9993, 0.9992);
metal::float4 b2_ = metal::float4(0.9991, 0.999, 0.9989, 0.9988);
metal::float4 b3_ = metal::float4(0.9987, 0.9986, 0.9985, 0.9984);
metal::float4 c = metal::float4(0.0001, 0.0002, 0.0003, 0.0004);
bool loop_init = true;
while(true) {
if (!loop_init) {
uint _e67 = i;
i = _e67 + 1u;
}
loop_init = false;
uint _e55 = i;
if (_e55 < 256u) {
} else {
break;
}
{
metal::float4 _e58 = a0_;
a0_ = metal::fma(_e58, b0_, c);
metal::float4 _e60 = a1_;
a1_ = metal::fma(_e60, b1_, c);
metal::float4 _e62 = a2_;
a2_ = metal::fma(_e62, b2_, c);
metal::float4 _e64 = a3_;
a3_ = metal::fma(_e64, b3_, c);
}
}
metal::float4 _e72 = a0_;
metal::float4 _e73 = a1_;
metal::float4 _e75 = a2_;
metal::float4 _e77 = a3_;
output[id.x] = ((_e72 + _e73) + _e75) + _e77;
return;
}
"#;
// The unchecked version with only its loop rewritten as a counted `for` loop
const NAGA_UNCHECKED_FOR_LOOP: &str = r#"
#include <metal_stdlib>
#include <simd/simd.h>
using metal::uint;
struct _mslBufferSizes {
uint size0;
};
typedef metal::float4 type_1[1];
[[max_total_threads_per_threadgroup(256)]] kernel void main_(
metal::uint3 id [[thread_position_in_grid]]
, device type_1& output [[buffer(0)]]
, constant _mslBufferSizes& _buffer_sizes [[buffer(1)]]
) {
metal::float4 a0_ = {};
metal::float4 a1_ = {};
metal::float4 a2_ = {};
metal::float4 a3_ = {};
a0_ = metal::float4(static_cast<float>(id.x) * 0.0000001) + metal::float4(0.0, 1.0, 2.0, 3.0);
metal::float4 _e13 = a0_;
a1_ = _e13 + metal::float4(0.1);
metal::float4 _e18 = a0_;
a2_ = _e18 + metal::float4(0.2);
metal::float4 _e23 = a0_;
a3_ = _e23 + metal::float4(0.3);
metal::float4 b0_ = metal::float4(0.9999, 0.9998, 0.9997, 0.9996);
metal::float4 b1_ = metal::float4(0.9995, 0.9994, 0.9993, 0.9992);
metal::float4 b2_ = metal::float4(0.9991, 0.999, 0.9989, 0.9988);
metal::float4 b3_ = metal::float4(0.9987, 0.9986, 0.9985, 0.9984);
metal::float4 c = metal::float4(0.0001, 0.0002, 0.0003, 0.0004);
for (uint i = 0u; i < 256u; i++) {
metal::float4 _e58 = a0_;
a0_ = metal::fma(_e58, b0_, c);
metal::float4 _e60 = a1_;
a1_ = metal::fma(_e60, b1_, c);
metal::float4 _e62 = a2_;
a2_ = metal::fma(_e62, b2_, c);
metal::float4 _e64 = a3_;
a3_ = metal::fma(_e64, b3_, c);
}
metal::float4 _e72 = a0_;
metal::float4 _e73 = a1_;
metal::float4 _e75 = a2_;
metal::float4 _e77 = a3_;
output[id.x] = ((_e72 + _e73) + _e75) + _e77;
return;
}
"#;
const SUSTAINED_WARMUP: Duration = Duration::from_secs(1);
const INTERLEAVED_ROUNDS: usize = 5;
type Device = ProtocolObject<dyn MTLDevice>;
type Queue = ProtocolObject<dyn MTLCommandQueue>;
type Pipeline = Retained<ProtocolObject<dyn MTLComputePipelineState>>;
type Buffer = Retained<ProtocolObject<dyn MTLBuffer>>;
pub fn run() {
println!("\n######## Direct Metal");
let Some(device) = MTLCreateSystemDefaultDevice() else {
println!("RESULT: no Metal device");
return;
};
describe(&device);
let Some(queue) = device.newCommandQueue() else {
println!("RESULT: no Metal command queue");
return;
};
// Compiled with wgpu's own Metal compile options, so only the source differs between variants
let options = MTLCompileOptions::new();
options.setPreserveInvariance(true);
let pipeline = |source: &str, name: &str| {
let library = match device.newLibraryWithSource_options_error(&NSString::from_str(source), Some(&options)) {
Ok(library) => library,
Err(error) => {
println!("RESULT: Metal shader compilation failed: {error}");
return None;
}
};
let function = library.newFunctionWithName(&NSString::from_str(name))?;
device.newComputePipelineStateWithFunction_error(&function).ok()
};
let variants = [
("hand-written", pipeline(SHADERS, "alu")),
("wgpu's output, default checks", pipeline(NAGA_CHECKED, "main_")),
("wgpu's output, no checks", pipeline(NAGA_UNCHECKED, "main_")),
("wgpu's output, no checks, `for` loop", pipeline(NAGA_UNCHECKED_FOR_LOOP, "main_")),
];
let variants: Vec<_> = variants.into_iter().filter_map(|(name, pipeline)| Some((name, pipeline?))).collect();
let invocations = ALU_WORKGROUPS as u64 * 256;
let output_bytes = invocations as usize * 16;
let Some(output) = device.newBufferWithLength_options(output_bytes, MTLResourceOptions::StorageModePrivate) else { return };
let buffer_sizes = (output_bytes as u32).to_le_bytes();
let Some(pointer) = NonNull::new(buffer_sizes.as_ptr() as *mut std::ffi::c_void) else { return };
let Some(sizes) = (unsafe { device.newBufferWithBytes_length_options(pointer, buffer_sizes.len(), MTLResourceOptions::StorageModeShared) }) else { return };
let buffers = [&output, &sizes];
// Keeps the GPU busy long enough for its clocks to ramp up before anything is timed
let warmup_start = Instant::now();
let mut warmup_dispatches = 0;
while warmup_start.elapsed() < SUSTAINED_WARMUP {
let _ = time_once(&queue, &variants[0].1, &buffers, ALU_WORKGROUPS as usize);
warmup_dispatches += 1;
}
// Each round times every variant in turn, so drift over time (clocks, other VMs on the host) affects them all alike
let mut gpu_milliseconds = vec![Vec::new(); variants.len()];
for _ in 0..INTERLEAVED_ROUNDS {
for (index, (_, pipeline)) in variants.iter().enumerate() {
for _ in 0..(TIMED_RUNS / INTERLEAVED_ROUNDS) {
if let Some((gpu, _)) = time_once(&queue, pipeline, &buffers, ALU_WORKGROUPS as usize) {
gpu_milliseconds[index].push(gpu);
}
}
}
}
let gflops = |milliseconds: f64| invocations as f64 * ALU_FLOPS_PER_INVOCATION / (milliseconds * 1e6);
println!("\n== FP32 compute, direct Metal, after {warmup_dispatches} warmup dispatches over {:?}, interleaved in {INTERLEAVED_ROUNDS} rounds", SUSTAINED_WARMUP);
for ((name, _), times) in variants.iter().zip(&gpu_milliseconds) {
if times.is_empty() {
println!("-- {name}: GPU time unavailable");
} else {
println!("-- {name}: {:.1} GFLOPS from median GPU time; GPU time (ms): {}", gflops(median(times)), summarize(times));
}
}
// Memory bandwidth, with nonzero contents in case the hardware compresses zeros
let Some(bandwidth_pipeline) = pipeline(SHADERS, "bandwidth") else { return };
let pattern: Vec<u8> = (0..BANDWIDTH_BUFFER_BYTES).map(|i| (i * 2_654_435_761 >> 24) as u8).collect();
let Some(pointer) = NonNull::new(pattern.as_ptr() as *mut std::ffi::c_void) else { return };
let source = unsafe { device.newBufferWithBytes_length_options(pointer, pattern.len(), MTLResourceOptions::StorageModeShared) };
let destination = device.newBufferWithLength_options(BANDWIDTH_BUFFER_BYTES as usize, MTLResourceOptions::StorageModePrivate);
let (Some(source), Some(destination)) = (source, destination) else { return };
let workgroups = (BANDWIDTH_BUFFER_BYTES / 16 / 256) as usize;
let mut gpu_milliseconds = Vec::new();
let mut wall_milliseconds = Vec::new();
for i in 0..(WARMUP_RUNS + TIMED_RUNS) {
let Some((gpu, wall)) = time_once(&queue, &bandwidth_pipeline, &[&source, &destination], workgroups) else { continue };
if i >= WARMUP_RUNS {
gpu_milliseconds.push(gpu);
wall_milliseconds.push(wall);
}
}
let gigabytes_per_second = |milliseconds: f64| 2. * BANDWIDTH_BUFFER_BYTES as f64 / (milliseconds * 1e6);
println!("\n== Memory bandwidth, direct Metal");
crate::report(&gpu_milliseconds, &wall_milliseconds, "GB/s", gigabytes_per_second);
let overhead: Vec<f64> = wall_milliseconds.iter().zip(&gpu_milliseconds).map(|(wall, gpu)| (wall - gpu) * 1e3).collect();
if !overhead.is_empty() {
println!("Wall minus GPU time per dispatch (µs): {}", summarize(&overhead));
}
}
fn describe(device: &Device) {
println!("name: {}, unified memory: {}, recommended working set: {} MiB", device.name(), device.hasUnifiedMemory(), device.recommendedMaxWorkingSetSize() >> 20);
let sampling_points = [
("stage boundary", MTLCounterSamplingPoint::AtStageBoundary),
("draw boundary", MTLCounterSamplingPoint::AtDrawBoundary),
("dispatch boundary", MTLCounterSamplingPoint::AtDispatchBoundary),
("tile dispatch boundary", MTLCounterSamplingPoint::AtTileDispatchBoundary),
("blit boundary", MTLCounterSamplingPoint::AtBlitBoundary),
];
let supported: Vec<_> = sampling_points.iter().filter(|(_, point)| device.supportsCounterSampling(*point)).map(|(name, _)| *name).collect();
println!("counter sampling supported at: {}", if supported.is_empty() { "none".to_string() } else { supported.join(", ") });
let sets = device.counterSets().map(|sets| sets.iter().map(|set| set.name().to_string()).collect::<Vec<_>>()).unwrap_or_default();
println!("counter sets: {}", if sets.is_empty() { "none".to_string() } else { sets.join(", ") });
}
// One dispatch, returning its GPU time from the command buffer (if Metal reports one) and the wall-clock time around commit-and-wait
fn time_once(queue: &Queue, pipeline: &Pipeline, buffers: &[&Buffer], workgroups: usize) -> Option<(f64, f64)> {
let command_buffer = queue.commandBuffer()?;
let encoder = command_buffer.computeCommandEncoder()?;
encoder.setComputePipelineState(pipeline);
for (index, buffer) in buffers.iter().enumerate() {
unsafe { encoder.setBuffer_offset_atIndex(Some(buffer), 0, index) };
}
encoder.dispatchThreadgroups_threadsPerThreadgroup(MTLSize { width: workgroups, height: 1, depth: 1 }, MTLSize { width: 256, height: 1, depth: 1 });
encoder.endEncoding();
let start = Instant::now();
command_buffer.commit();
command_buffer.waitUntilCompleted();
let wall = start.elapsed().as_secs_f64() * 1e3;
let gpu = (command_buffer.GPUEndTime() - command_buffer.GPUStartTime()) * 1e3;
(command_buffer.GPUStartTime() > 0. && gpu > 0.).then_some((gpu, wall))
}
+42
View File
@@ -0,0 +1,42 @@
name: "Mac GPU Probe"
# Throwaway feasibility test of macOS runners' GPUs for profiling, run only by pushes to this branch
on:
push:
branches:
- mac-gpu-probe
permissions:
contents: read
jobs:
probe:
strategy:
fail-fast: false
# One at a time, so jobs can't land on one host and share its GPU
max-parallel: 1
matrix:
runner: [blacksmith-6vcpu-macos-latest, macos-latest]
# Repeated to see how much separate jobs (and possibly separate hosts) differ
attempt: [1, 2, 3]
name: probe (${{ matrix.runner }}, ${{ matrix.attempt }})
runs-on: ${{ matrix.runner }}
steps:
- uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
- name: Install Rust
uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
- name: Describe the hardware
run: |
sw_vers
echo "CPU: $(sysctl -n machdep.cpu.brand_string), model: $(sysctl -n hw.model), memory: $(( $(sysctl -n hw.memsize) / 1073741824 )) GiB, running in a VM: $(sysctl -n kern.hv_vmm_present 2>/dev/null || echo unknown)"
system_profiler SPDisplaysDataType SPHardwareDataType
- name: Build the probe
run: cargo build --release --manifest-path .github/mac-gpu-probe/Cargo.toml
- name: Run the probe
env:
RUST_LOG: wgpu_hal::metal::device=debug
run: .github/mac-gpu-probe/target/release/mac-gpu-probe