A high-performance inference engine for AI models
use std::{
collections::{BTreeMap, HashSet},
fs,
iter::once,
path::{Path, PathBuf},
};
use anyhow::Context;
use itertools::Itertools;
use proc_macro2::TokenStream;
use shader_slang::{
Blob, CompileTarget, CompilerOptions, ComponentType, GlobalSession, Module, ScalarType, TargetDesc,
};
use spirv::{Capability, Op};
use syn::{BinOp, Expr};
use crate::{
common::{codegen::write_tokens, identifiers::KernelName, kernel::Kernel, mangling::static_mangle},
slang::{
BlockingSlangCompiler, SlangArgumentType, SlangCompilerFields, SlangGpuTypes, SlangKernel, SlangParameterType,
SlangTarget, kernel_wrappers, specialization_name,
},
vulkan::{SlangEntryPointAbi, SlangEntryPointVariant, bindgen, spirv_hash::export_spirv_hash},
};
const DEVICE_CAPABILITIES: [Capability; 15] = [
Capability::Shader,
Capability::Float16,
Capability::Int16,
Capability::Int8,
Capability::GroupNonUniform,
Capability::GroupNonUniformArithmetic,
Capability::GroupNonUniformBallot,
Capability::GroupNonUniformShuffle,
Capability::SignedZeroInfNanPreserve,
Capability::RoundingModeRTE,
Capability::VulkanMemoryModel,
Capability::VulkanMemoryModelDeviceScope,
Capability::PhysicalStorageBufferAddresses,
Capability::DotProductInput4x8BitPacked,
Capability::DotProduct,
];
const GATED_CAPABILITIES: [(Capability, &[&str]); 4] = [
(
Capability::CooperativeMatrixKHR,
&["BF16_TENSOR_CORES", "INT8_TENSOR_CORES_K32", "INT8_TENSOR_CORES_K16", "float_tensor_cores"],
),
(Capability::BFloat16TypeKHR, &["BF16_TENSOR_CORES", "float_tensor_cores"]),
(Capability::BFloat16CooperativeMatrixKHR, &["BF16_TENSOR_CORES", "float_tensor_cores"]),
(Capability::CooperativeMatrixPerElementOperationsNV, &["INT8_ELEMENT_FOLD"]),
];
pub const AXIS_FOLD_GROUPS: u32 = 65_535;
#[derive(Clone)]
pub struct VulkanTarget;
impl SlangTarget for VulkanTarget {
const TARGET_NAME: &'static str = "vulkan";
const SOURCE_DIRECTORY: &'static str = "src/backends/vulkan/kernel";
const PRIVATE_GPU_TYPES: Option<&'static str> = Some("vulkan");
const SESSION_DEFINES: &'static [&'static [(&'static str, &'static str)]] = &[&[], &[("NATIVE_BF16", "1")]];
fn compiler_options(
global_session: &GlobalSession,
options: CompilerOptions,
) -> CompilerOptions {
options
.emit_spirv_directly(true)
.vulkan_use_entry_point_name(true)
.capability(global_session.find_capability("spvGroupNonUniform"))
.capability(global_session.find_capability("spvGroupNonUniformArithmetic"))
.capability(global_session.find_capability("spvGroupNonUniformBallot"))
.capability(global_session.find_capability("spvGroupNonUniformShuffle"))
.capability(global_session.find_capability("spvCooperativeMatrixKHR"))
.capability(global_session.find_capability("spvBFloat16KHR"))
.capability(global_session.find_capability("sm_5_0"))
}
fn create_target_desc<'a>(global_session: &'a GlobalSession) -> TargetDesc<'a> {
TargetDesc::default().format(CompileTarget::Spirv).profile(global_session.find_profile("spirv_1_6"))
}
fn specialization_type(slang_type: &str) -> &str {
match slang_type {
"bool" => "bool",
_ => "uint",
}
}
fn axis_guard(axes: &[(String, String)]) -> (String, Vec<String>) {
if let [(total, size)] = axes {
let index = format!("__dsl_axis_idx.x + __dsl_axis_idx.y * ({AXIS_FOLD_GROUPS}u * ({size}))");
let guard = format!(" let __dsl_axis = {index};\n if (__dsl_axis >= ({total})) return;");
return (guard, vec!["__dsl_axis".to_owned()]);
}
let (guards, indices): (Vec<_>, Vec<_>) = axes
.iter()
.zip(["x", "y", "z"])
.map(|((total, _), axis)| {
(format!(" if (__dsl_axis_idx.{axis} >= ({total})) return;"), format!("__dsl_axis_idx.{axis}"))
})
.unzip();
(guards.join("\n"), indices)
}
fn entry_point_prologue(entry_point: &str) -> String {
format!(
" spirv_asm {{\n OpCapability RoundingModeRTE;\n OpCapability SignedZeroInfNanPreserve;\n \
OpExtension \"SPV_KHR_float_controls\";\n \
OpExecutionMode ${entry_point} RoundingModeRTE 16;\n \
OpExecutionMode ${entry_point} RoundingModeRTE 32;\n \
OpExecutionMode ${entry_point} SignedZeroInfNanPreserve 16;\n \
OpExecutionMode ${entry_point} SignedZeroInfNanPreserve 32;\n }};"
)
}
fn wrapper(
fields: &SlangCompilerFields<Self>,
source_path: &Path,
module: &Module,
kernels: &[SlangKernel],
) -> anyhow::Result<String> {
kernels.iter().try_for_each(check_bindable)?;
let wrappers = kernel_wrappers::<Self>(module, kernels)?;
let generated = fields.source_directory.join("generated");
let imports = once("definitions".to_owned())
.chain(module.dependency_file_paths().filter_map(|path| {
let path = Path::new(path);
(path.parent() == Some(&generated))
.then(|| Some(format!("generated.{}", path.file_stem()?.to_str()?)))
.flatten()
}))
.sorted()
.map(|module| format!("import {module};\n"))
.chain(once(format!("import {source_path:?};")))
.collect::<String>();
Ok(once(imports).chain(wrappers).join("\n\n"))
}
fn emit(
compiler: &BlockingSlangCompiler<Self>,
gpu_types: &SlangGpuTypes,
_module: &Module,
kernels: &[SlangKernel],
descriptors: &[Kernel],
linked: &ComponentType,
output_base: &Path,
) -> anyhow::Result<()> {
let mut declared = BTreeMap::new();
for kernel in kernels {
for argument in &kernel.arguments {
if matches!(argument.argument_type, SlangArgumentType::Specialize { .. }) || argument.pipeline_variants
{
let wire = match Self::specialization_type(&argument.slang_type) {
"bool" => ScalarType::Bool,
_ => ScalarType::Uint32,
};
declared.insert(specialization_name(&kernel.name, &argument.name), wire);
}
}
}
let native = compiler.link(1, &output_base.with_extension("slang"))?;
for (kernel, descriptor) in kernels.iter().zip(descriptors) {
let required = kernel
.preconditions
.iter()
.filter(|(phase, _)| phase == "new")
.map(|(_, condition)| {
let condition = syn::parse_str(condition)
.with_context(|| format!("{}: malformed Precondition '{condition}'", kernel.name))?;
anyhow::Ok(required_capabilities(&condition, false))
})
.flatten_ok()
.collect::<anyhow::Result<HashSet<_>>>()?;
let variants = kernel
.variants()
.map(|variant| {
let types = variant.iter().map(|(_, ty)| ty.to_string()).collect::<Vec<_>>();
let name = static_mangle(&kernel.name, &types);
let (abi, spirv) = entry_point(linked, &name, &declared)?;
let spirv = spirv()?;
check_capabilities(&name, &required, spirv.as_slice(), false)?;
let object_file = output_base.with_file_name(&name).with_extension("spv");
fs::write(&object_file, spirv.as_slice())?;
let (native_abi, native_spirv) = entry_point(&native, &name, &declared)?;
let stores_bf16 = types.iter().any(|ty| ty == "bf16")
|| native_abi
.fields
.iter()
.any(|field| field.layout.as_ref().is_some_and(|layout| layout.name == "bf16"));
let native_file = object_file.with_extension("bf16.spv");
let native = match stores_bf16.then(native_spirv).transpose()? {
Some(native) if native.as_slice() != spirv.as_slice() => {
check_capabilities(&name, &required, native.as_slice(), true)?;
fs::write(&native_file, native.as_slice())?;
Some((native_abi, artifact_path(&native_file)?))
},
_ => {
if native_file.exists() {
fs::remove_file(&native_file)?;
}
None
},
};
Ok(SlangEntryPointVariant {
types,
abi,
spirv: artifact_path(&object_file)?,
native_bf16: native,
})
})
.collect::<anyhow::Result<Vec<_>>>()?;
write_tokens(
bindgen::bindgen(kernel, descriptor, &variants, &gpu_types.paths, &gpu_types.definitions)?,
bindgen::binding_file(output_base, &kernel.name),
)
.with_context(|| format!("cannot write {} binding", kernel.name))?;
}
Ok(())
}
fn bindgen_global(
fields: &SlangCompilerFields<Self>,
modules: &[(PathBuf, &[Kernel], &[KernelName])],
) -> anyhow::Result<TokenStream> {
export_spirv_hash(&fields.output_directory)?;
let mut bindings = Vec::new();
for (output_base, public, private) in modules {
let names =
public.iter().map(|kernel| (&kernel.name, true)).chain(private.iter().map(|name| (name, false)));
for (name, is_public) in names {
let file = bindgen::binding_file(output_base, name);
bindings.push((
file.to_str().context("binding path is not UTF-8")?.to_owned(),
name.to_string(),
is_public,
));
}
}
Ok(bindgen::bindgen_umbrella(&bindings))
}
}
fn check_capabilities(
entry_point: &str,
required: &HashSet<String>,
spirv: &[u8],
native_bf16: bool,
) -> anyhow::Result<()> {
let words = spirv.as_chunks::<4>().0.iter().map(|word| u32::from_le_bytes(*word)).collect::<Vec<_>>();
let mut at = 5;
while at < words.len() {
let (count, opcode) = ((words[at] >> 16) as usize, words[at] & 0xffff);
anyhow::ensure!(count > 0 && at + count <= words.len(), "{entry_point}: malformed SPIR-V");
if Op::from_u32(opcode) == Some(Op::Capability) {
let Some(capability) = Capability::from_u32(words[at + 1]) else {
anyhow::bail!("{entry_point}: unknown SPIR-V capability {}", words[at + 1]);
};
let gated = GATED_CAPABILITIES.iter().find(|(value, _)| *value == capability);
let allowed = DEVICE_CAPABILITIES.contains(&capability)
|| (native_bf16 && capability == Capability::BFloat16TypeKHR)
|| gated.is_some_and(|(_, gates)| gates.iter().any(|gate| required.contains(*gate)));
anyhow::ensure!(
allowed,
"{entry_point}: SPIR-V capability {capability:?} is neither enabled on every device nor gated by a precondition"
);
}
at += count;
}
Ok(())
}
fn required_capabilities(
condition: &Expr,
flags: bool,
) -> Vec<String> {
match condition {
Expr::Binary(binary) if matches!((&binary.op, flags), (BinOp::And(_), false) | (BinOp::BitOr(_), true)) => {
[&binary.left, &binary.right].into_iter().flat_map(|term| required_capabilities(term, flags)).collect()
},
Expr::Paren(paren) => required_capabilities(&paren.expr, flags),
Expr::MethodCall(call) if !flags && call.method == "float_tensor_cores" => vec![call.method.to_string()],
Expr::MethodCall(call) if !flags && call.method == "contains" => {
call.args.iter().flat_map(|flag| required_capabilities(flag, true)).collect()
},
Expr::Path(path)
if flags && path.path.segments.len() == 2 && path.path.segments[0].ident == "VkDeviceCapabilities" =>
{
vec![path.path.segments[1].ident.to_string()]
},
_ => Vec::new(),
}
}
fn entry_point<'a>(
compiled: &'a ComponentType,
name: &str,
declared: &BTreeMap<String, ScalarType>,
) -> anyhow::Result<(SlangEntryPointAbi, impl FnOnce() -> anyhow::Result<Blob> + 'a)> {
let program = compiled.layout(0).context("linked Slang program has no layout")?;
let entry_point = program.find_entry_point_by_name(name).context("entry point not linked")?;
let index =
program.entry_points().position(|entry| entry.name() == Some(name)).context("entry point has no index")?;
let spirv = move || compiled.entry_point_code(index as i64, 0).context("cannot emit entry point SPIR-V");
Ok((SlangEntryPointAbi::from_reflection(program, entry_point, declared)?, spirv))
}
fn artifact_path(file: &Path) -> anyhow::Result<String> {
Ok(file.to_str().context("Slang artifact path is not UTF-8")?.to_owned())
}
fn check_bindable(kernel: &SlangKernel) -> anyhow::Result<()> {
if let Some(parameter) =
kernel.parameters.iter().find(|parameter| matches!(parameter.ty, SlangParameterType::GroupShared { .. }))
{
anyhow::bail!("kernel '{}': GroupShared {} has no Vulkan binding", kernel.name, parameter.name);
}
let has =
|kind: fn(&SlangArgumentType) -> bool| kernel.arguments.iter().any(|argument| kind(&argument.argument_type));
anyhow::ensure!(
!has(|kind| matches!(kind, SlangArgumentType::ThreadContext)),
"kernel '{}': ThreadContext has no Vulkan binding",
kernel.name
);
let variants = kernel.arguments.iter().filter(|argument| argument.pipeline_variants).count();
anyhow::ensure!(
variants <= 1,
"kernel '{}' marks {variants} arguments PipelineVariants; at most one may be",
kernel.name
);
let axis = has(|kind| matches!(kind, SlangArgumentType::Axis { .. }));
let groups = has(|kind| matches!(kind, SlangArgumentType::Groups { .. }));
let threads = has(|kind| matches!(kind, SlangArgumentType::Threads { .. }));
anyhow::ensure!(
groups == threads && (axis || groups),
"kernel '{}' needs either Axis or both Groups and Threads",
kernel.name
);
Ok(())
}