Skip to content

Commit a7c8e34

Browse files
Stela contributorclaude
andcommitted
feat(amd-host): function constants and kernel stage input in the suite runner
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 6b5aacf commit a7c8e34

4 files changed

Lines changed: 227 additions & 11 deletions

File tree

‎crates/stela-amd-host/src/main.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ mod device;
3535
#[cfg(feature = "radv-host")]
3636
mod suite;
3737
#[cfg(feature = "radv-host")]
38+
mod suite_constants;
39+
#[cfg(feature = "radv-host")]
3840
mod suite_render;
3941
#[cfg(feature = "radv-host")]
4042
mod suite_resources;

‎crates/stela-amd-host/src/suite.rs‎

Lines changed: 83 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,18 +19,21 @@ use std::{
1919
time::Instant,
2020
};
2121
use stela_driver_gpu::metal::{
22-
abi::{ArgumentBuffersTier, DispatchType, GpuFamily, ReadWriteTextureTier},
22+
abi::{ArgumentBuffersTier, DispatchType, GpuFamily, IndexType, ReadWriteTextureTier},
2323
capabilities::{Capabilities, Size},
2424
command_buffer::{CommandBuffer, ComputePipelineState},
2525
device::{
2626
BufferId, LibraryId, SamplerId,
2727
pipelines::{ComputePipelineRequest, LinkedFunctions, PipelineArchives},
2828
},
2929
error::{Error, Result},
30+
vertex::{Attribute, StageInLayout, StageInStep, StageInputDescriptor, VertexFormat},
3031
};
3132

32-
const BASIC_CASE: [&str; 15] = [
33+
const BASIC_CASE: [&str; 17] = [
3334
"buffers",
35+
"constants",
36+
"stage_input",
3437
"dispatch",
3538
"function",
3639
"grid",
@@ -94,6 +97,11 @@ fn basic(case: &Value) -> bool {
9497
})
9598
&& all("samplers", &super::suite_resources::SAMPLER)
9699
&& (case["dispatch"].is_null() || case["dispatch"] == "threads")
100+
&& (case["stage_input"].is_null()
101+
|| only(
102+
&case["stage_input"],
103+
&["attributes", "index_buffer", "index_type", "layouts"],
104+
))
97105
}
98106

99107
/// Runs the selected cases of the suite in `dir`; `only` keeps the cases
@@ -180,8 +188,9 @@ pub(crate) struct Runner<'a> {
180188
pub(crate) exporter: &'a Exporter,
181189
pub(crate) plan_dir: PathBuf,
182190
libraries: BTreeMap<String, LibraryId>,
183-
/// By library, function and threadgroup width, height and depth.
184-
pipelines: BTreeMap<(String, String, [u64; 3]), ComputePipelineState>,
191+
/// By library, function, threadgroup size, and the constants and stage
192+
/// input the case gives, as JSON.
193+
pipelines: BTreeMap<(String, String, [u64; 3], String), ComputePipelineState>,
185194
/// The next fake guest range index each import takes.
186195
pub(crate) next_import: u64,
187196
}
@@ -229,6 +238,59 @@ pub(crate) struct Held {
229238
pub(crate) samplers: Vec<SamplerId>,
230239
}
231240

241+
/// A kernel's stage input, as the runner's `stage_input_descriptor`.
242+
fn stage_input(spec: &Value) -> Result<StageInputDescriptor> {
243+
let number = |item: &Value, key: &str, default: u64| item[key].as_u64().unwrap_or(default);
244+
let mut attributes = Vec::new();
245+
for item in spec["attributes"].as_array().into_iter().flatten() {
246+
attributes.push(Attribute {
247+
index: number(item, "index", 0) as u32,
248+
format: named(
249+
VertexFormat::ALL,
250+
item["format"].as_str().unwrap_or_default(),
251+
)
252+
.ok_or(Error::Unsupported("an attribute format"))?,
253+
offset: number(item, "offset", 0),
254+
buffer_index: number(item, "buffer", 0) as u32,
255+
});
256+
}
257+
let mut layouts = Vec::new();
258+
for item in spec["layouts"].as_array().into_iter().flatten() {
259+
let step = item["step"].as_str().unwrap_or("grid_x");
260+
let step_function = match step {
261+
"grid_x" => StageInStep::ThreadPositionInGridX,
262+
"grid_y" => StageInStep::ThreadPositionInGridY,
263+
"grid_x_indexed" => StageInStep::ThreadPositionInGridXIndexed,
264+
"grid_y_indexed" => StageInStep::ThreadPositionInGridYIndexed,
265+
"constant" => StageInStep::Constant,
266+
_ => return Err(Error::Unsupported("a stage-in step function")),
267+
};
268+
if item["stride"].is_string() {
269+
return Err(Error::Unsupported("a dynamic stage-in stride"));
270+
}
271+
layouts.push(StageInLayout {
272+
buffer_index: number(item, "buffer", 0) as u32,
273+
stride: number(item, "stride", 16),
274+
step_function,
275+
step_rate: if step == "constant" {
276+
0
277+
} else {
278+
number(item, "rate", 1)
279+
},
280+
});
281+
}
282+
Ok(StageInputDescriptor {
283+
attributes,
284+
layouts,
285+
index_type: if spec["index_type"] == "uint16" {
286+
IndexType::UInt16
287+
} else {
288+
IndexType::UInt32
289+
},
290+
index_buffer_index: number(spec, "index_buffer", 0) as u32,
291+
})
292+
}
293+
232294
/// Whether the device has what `requires` names, as the runner's `unmet`:
233295
/// the missing one, if any.
234296
pub(crate) fn unmet(capabilities: &Capabilities, requires: &Value) -> Option<String> {
@@ -412,7 +474,7 @@ impl Runner<'_> {
412474
};
413475
let grid = triple("grid", 1);
414476
let group = triple("threadgroup", 64);
415-
let state = self.pipeline(library, function, group)?;
477+
let state = self.pipeline(library, function, group, case)?;
416478

417479
let mut commands = self.device.new_command_buffer();
418480
self.make_buffers(&case["buffers"], held)?;
@@ -449,6 +511,9 @@ impl Runner<'_> {
449511
depth: group[2],
450512
};
451513
if case["dispatch"] == "threads" {
514+
if case["stage_input"].is_object() {
515+
commands.set_stage_in_region([0; 3], grid)?;
516+
}
452517
let grid = grid.map(|size| size as u32);
453518
commands.dispatch_threads(&mut self.device.resolver(), grid, threads)?;
454519
} else {
@@ -485,18 +550,28 @@ impl Runner<'_> {
485550
library: &str,
486551
function: &str,
487552
group: [u64; 3],
553+
case: &Value,
488554
) -> Result<ComputePipelineState> {
489-
let key = (library.to_owned(), function.to_owned(), group);
555+
let shape = format!("{} {}", case["constants"], case["stage_input"]);
556+
let key = (library.to_owned(), function.to_owned(), group, shape);
490557
if let Some(state) = self.pipelines.get(&key) {
491558
return Ok(state.clone());
492559
}
493560
let library = self.library(library)?;
494-
let function = self.device.new_function(library, function, Some(&[]))?;
561+
let constants = super::suite_constants::values(&case["constants"])?;
562+
let function = self
563+
.device
564+
.new_function(library, function, Some(&constants))?;
565+
let stage_input = if case["stage_input"].is_object() {
566+
Some(stage_input(&case["stage_input"])?)
567+
} else {
568+
None
569+
};
495570
let pipeline = self.device.new_compute_pipeline(&ComputePipelineRequest {
496571
compute_function: function,
497572
threadgroup_size_is_multiple_of_thread_execution_width: false,
498573
max_total_threads_per_threadgroup: 0,
499-
stage_input: None,
574+
stage_input,
500575
linked_functions: LinkedFunctions::default(),
501576
support_indirect_command_buffers: false,
502577
archives: PipelineArchives::default(),
Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
//! Function constant values, as the Mac's runner gives them (`constants_of`
2+
//! in `runner.m`): a value converted to the constant's type, or base64
3+
//! bytes, at an index, by name, or over a range of indices.
4+
use super::suite::named;
5+
use serde_json::Value;
6+
use stela_driver_gpu::metal::{
7+
abi::DataType,
8+
device::pipelines::{ConstantKey, ConstantValue},
9+
error::{Error, Result},
10+
};
11+
12+
/// The case's constants, none for a case without.
13+
pub fn values(constants: &Value) -> Result<Vec<ConstantValue>> {
14+
let mut out = Vec::new();
15+
for spec in constants.as_array().into_iter().flatten() {
16+
let data_type = named(DataType::ALL, spec["type"].as_str().unwrap_or_default())
17+
.ok_or(Error::Unsupported("a function constant type"))?;
18+
let bytes = match spec["bytes"].as_str() {
19+
Some(text) => base64(text).ok_or(Error::Invalid("constant bytes"))?,
20+
None => value_bytes(data_type, &spec["value"]),
21+
};
22+
if let Some(range) = spec["range"].as_array() {
23+
let start = range.first().and_then(Value::as_u64).unwrap_or(0) as u32;
24+
let count = range.get(1).and_then(Value::as_u64).unwrap_or(0) as usize;
25+
let size = bytes.len().checked_div(count).unwrap_or(0);
26+
if size == 0 {
27+
return Err(Error::Invalid("a constant range"));
28+
}
29+
for (at, chunk) in bytes.chunks(size).take(count).enumerate() {
30+
out.push(ConstantValue {
31+
key: ConstantKey::Index(start + at as u32),
32+
data_type,
33+
value: chunk.to_vec(),
34+
});
35+
}
36+
continue;
37+
}
38+
let key = match spec["name"].as_str() {
39+
Some(name) => ConstantKey::Name(name.to_owned()),
40+
None => ConstantKey::Index(spec["index"].as_u64().unwrap_or(0) as u32),
41+
};
42+
out.push(ConstantValue {
43+
key,
44+
data_type,
45+
value: bytes,
46+
});
47+
}
48+
Ok(out)
49+
}
50+
51+
/// A value's bytes as the runner's union holds them.
52+
fn value_bytes(data_type: DataType, value: &Value) -> Vec<u8> {
53+
let real = value.as_f64().unwrap_or(0.0);
54+
let integer = value.as_i64().unwrap_or(real as i64);
55+
match data_type {
56+
DataType::Bool | DataType::Char | DataType::UChar => vec![integer as u8],
57+
DataType::Short | DataType::UShort => (integer as u16).to_le_bytes().to_vec(),
58+
DataType::Half => half(real as f32).to_le_bytes().to_vec(),
59+
DataType::Float => (real as f32).to_le_bytes().to_vec(),
60+
DataType::Long | DataType::ULong => (integer as u64).to_le_bytes().to_vec(),
61+
_ => (integer as u32).to_le_bytes().to_vec(),
62+
}
63+
}
64+
65+
/// The nearest half, ties to even.
66+
fn half(value: f32) -> u16 {
67+
let bits = value.to_bits();
68+
let sign = ((bits >> 16) & 0x8000) as u16;
69+
let exponent = ((bits >> 23) & 0xff) as i32;
70+
let mantissa = bits & 0x7f_ffff;
71+
if exponent == 0xff {
72+
return sign | 0x7c00 | if mantissa != 0 { 0x200 } else { 0 };
73+
}
74+
let unbiased = exponent - 127 + 15;
75+
if unbiased >= 0x1f {
76+
return sign | 0x7c00;
77+
}
78+
if unbiased <= 0 {
79+
if unbiased < -10 {
80+
return sign;
81+
}
82+
let full = mantissa | 0x80_0000;
83+
let shift = (14 - unbiased) as u32;
84+
let rounded = (full >> shift)
85+
+ u32::from(
86+
(full >> (shift - 1)) & 1 != 0
87+
&& ((full & ((1 << (shift - 1)) - 1)) != 0 || (full >> shift) & 1 != 0),
88+
);
89+
return sign | rounded as u16;
90+
}
91+
let rounded = (unbiased as u32) << 10 | mantissa >> 13;
92+
let remainder = mantissa & 0x1fff;
93+
let up = remainder > 0x1000 || (remainder == 0x1000 && rounded & 1 != 0);
94+
sign | (rounded + u32::from(up)) as u16
95+
}
96+
97+
fn base64(text: &str) -> Option<Vec<u8>> {
98+
let value = |c: u8| -> Option<u32> {
99+
Some(match c {
100+
b'A'..=b'Z' => c - b'A',
101+
b'a'..=b'z' => c - b'a' + 26,
102+
b'0'..=b'9' => c - b'0' + 52,
103+
b'+' => 62,
104+
b'/' => 63,
105+
_ => return None,
106+
} as u32)
107+
};
108+
let digits: Vec<u8> = text
109+
.bytes()
110+
.filter(|c| *c != b'=' && !c.is_ascii_whitespace())
111+
.collect();
112+
let mut out = Vec::new();
113+
for chunk in digits.chunks(4) {
114+
let mut word = 0;
115+
for (at, &c) in chunk.iter().enumerate() {
116+
word |= value(c)? << (18 - 6 * at);
117+
}
118+
let bytes = word.to_be_bytes();
119+
out.extend_from_slice(&bytes[1..chunk.len()]);
120+
}
121+
Some(out)
122+
}
123+
124+
#[cfg(test)]
125+
mod tests {
126+
use super::*;
127+
128+
#[test]
129+
fn halves_and_base64() {
130+
assert_eq!(half(1.0), 0x3c00);
131+
assert_eq!(half(-2.0), 0xc000);
132+
assert_eq!(half(0.5), 0x3800);
133+
assert_eq!(half(65504.0), 0x7bff);
134+
assert_eq!(base64("AQID").unwrap(), [1, 2, 3]);
135+
assert_eq!(base64("AQI=").unwrap(), [1, 2]);
136+
}
137+
}

‎crates/stela-amd-host/src/suite_render.rs‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,9 @@ use stela_driver_gpu::metal::{
2929
vertex::{Attribute, Layout, StepFunction, VertexDescriptor, VertexFormat},
3030
};
3131

32-
const CASE: [&str; 13] = [
32+
const CASE: [&str; 14] = [
3333
"buffers",
34+
"constants",
3435
"fragment",
3536
"informational",
3637
"kind",
@@ -278,13 +279,14 @@ impl Runner<'_> {
278279

279280
// The pipeline's targets and the pass's attachments.
280281
let library = self.library(case["library"].as_str().unwrap_or_default())?;
282+
let constants = super::suite_constants::values(&case["constants"])?;
281283
let vertex = self.device.new_function(
282284
library,
283285
case["vertex"].as_str().unwrap_or_default(),
284-
Some(&[]),
286+
Some(&constants),
285287
)?;
286288
let fragment = match case["fragment"].as_str() {
287-
Some(name) => Some(self.device.new_function(library, name, Some(&[]))?),
289+
Some(name) => Some(self.device.new_function(library, name, Some(&constants))?),
288290
None => None,
289291
};
290292
let mut targets = RenderTargets::default();

0 commit comments

Comments
 (0)