#[allow(dead_code)]
pub(crate) mod overrides;
mod boundary;
mod driver;
mod evidence;
pub(crate) mod policy;
mod production {
pub(super) mod lstm;
pub(super) mod resnet;
pub(super) mod sincnet;
use super::{RecordHash, SpeedEvidence, SpeedScope, SpeedStatus, TupleProof};
use crate::inference::cuda::candidate::ConfigPin;
use crate::inference::cuda::implementation::BoundaryId;
use crate::inference::cuda::{ComputeCapability, CudaMath};
pub(super) const FP32: CudaMath = CudaMath::Fp32;
pub(super) const INTEGRATED_DER: RecordHash =
RecordHash::from_hex("8066268031afba058d93e305206d5b8225e40c6ab2ebb1052874d607e055646f");
pub(super) const LEGACY_SCOPE: SpeedScope = SpeedScope::LegacyCapability {
capability: ComputeCapability::new(12, 0),
};
pub(super) const fn legacy_proof(
boundary: BoundaryId,
batch: usize,
math: CudaMath,
pin: ConfigPin,
record: RecordHash,
) -> TupleProof {
TupleProof {
boundary,
batch,
math,
pin,
accuracy: record,
speed: SpeedStatus::Measured(SpeedEvidence {
scope: LEGACY_SCOPE,
record,
integrated: INTEGRATED_DER,
}),
}
}
}
pub(crate) use boundary::{BoundaryId, ProductionBatches};
pub(crate) use evidence::{
ArchitectureSpeed, Binding, BroadEvidence, ModuleBinding, RecordHash, SpeedEvidence,
SpeedScope, SpeedStatus, TupleProof,
};
#[cfg(all(test, feature = "_cuda-libraries"))]
use super::candidate::{Batches, Coverage, CoverageEntry, Maths};
use super::candidate::{
ConfigPin, ConvCandidate, ConvLayerSpec, ConvOxide, DenseCandidate, DenseOxide, DenseSpec,
FbankCandidate, FbankOxide, FbankSpec, Fp16Policy, LstmCandidate, LstmOxide, LstmProjOxide,
LstmSpec, PlanError, SegConvCandidate, SegConvOxide, SegConvSpec, SincCandidate, SincOxide,
SincSpec, WideconvOxide,
};
use super::device::DeviceAttributes;
use super::error::GeometryError;
use super::kernels::{AreaPtx, LoadedArtifact, ModuleRequest};
use super::tuning::ApprovedChoice;
use super::{
ComputeCapability, CudaError, CudaLibrary, CudaMath, CudaRuntime, KernelModule, PtxTier,
};
pub(crate) type TuningConfiguration = (
BoundaryId,
usize,
CudaMath,
ModuleRequest,
ConfigPin,
&'static str,
);
pub(crate) fn tuning_configurations(
device: &DeviceAttributes,
limit: PtxTier,
) -> Result<Vec<TuningConfiguration>, CudaError> {
driver::tuning_configurations(device, limit)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Target {
pub module: ModuleRequest,
pub device: ComputeCapability,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct AreaTarget {
pub tier: PtxTier,
pub device: ComputeCapability,
}
impl AreaTarget {
pub(crate) fn for_area(runtime: &CudaRuntime, area: KernelModule) -> Result<Self, CudaError> {
Ok(Self {
tier: production_tier(area, runtime.device(), runtime.ptx_tier())
.unwrap_or(PtxTier::BASELINE),
device: runtime.compute_capability(),
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Selection {
Production,
Tuning,
#[cfg(test)]
DriverOnly,
#[cfg(all(test, feature = "_cuda-libraries"))]
Explicit,
}
impl Selection {
pub(super) const fn accuracy(self) -> super::tuning::accuracy::RuntimePolicy {
use super::tuning::accuracy::RuntimePolicy;
match self {
Self::Production if super::driver_only() => RuntimePolicy::ExactFp32,
#[cfg(test)]
Self::DriverOnly => RuntimePolicy::ExactFp32,
_ => RuntimePolicy::Strict,
}
}
}
#[cfg(all(test, feature = "_cuda-libraries"))]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Choice {
#[default]
Library,
Oxide(Selection),
}
#[derive(Debug)]
pub(crate) enum Selected {
Library,
Oxide(Box<Qualified>),
}
const PRODUCTION: &[Binding] = &[production::lstm::BINDING, production::sincnet::BINDING];
const MEASURED_MODULES: &[ModuleBinding] = &[production::resnet::BINDING];
const ALWAYS_ON: &[KernelModule] = &[
KernelModule::Fbank,
KernelModule::Embedding,
KernelModule::Segmentation,
];
const ROUTE_PRECEDENCE: &[KernelModule] = &[
KernelModule::Wideconv,
KernelModule::Resnet,
KernelModule::Segdense,
KernelModule::LstmProj,
KernelModule::Lstm,
KernelModule::Sincnet,
KernelModule::FbankDft,
];
const _: () = {
evidence::validate(PRODUCTION, ALWAYS_ON, ROUTE_PRECEDENCE);
evidence::validate_modules(MEASURED_MODULES, PRODUCTION, ALWAYS_ON, ROUTE_PRECEDENCE);
};
pub(crate) const MODEL_BATCHES: [usize; 2] = ProductionBatches::MODEL;
pub(crate) fn production_module(
area: KernelModule,
device: &DeviceAttributes,
limit: PtxTier,
variants: AreaPtx,
) -> Result<Option<ModuleRequest>, CudaError> {
let qualified = qualified_module(area, device, limit, variants)?;
Ok(qualified.or_else(|| variants.driver_request(area, limit, device.capability())))
}
fn qualified_module(
area: KernelModule,
device: &DeviceAttributes,
limit: PtxTier,
variants: AreaPtx,
) -> Result<Option<ModuleRequest>, CudaError> {
if !ALWAYS_ON.contains(&area) {
return Ok(bound_production_module(area, device, limit));
}
let tier = PtxTier::BASELINE;
let ptx = variants
.embedded(tier)
.ok_or(CudaError::AreaTierNotCompiledIn {
area: area.name(),
tier,
device: device.capability(),
feature: tier.feature(),
})?;
Ok(Some(ModuleRequest::new(
area,
tier,
LoadedArtifact::PtxJit {
sha256: ptx.sha256(),
},
)))
}
fn production_tier(
area: KernelModule,
device: &DeviceAttributes,
limit: PtxTier,
) -> Option<PtxTier> {
if ALWAYS_ON.contains(&area) {
return Some(PtxTier::BASELINE);
}
bound_production_module(area, device, limit)
.map(ModuleRequest::tier)
.or_else(|| area.variants().runnable_tier(limit, device.capability()))
}
fn bound_production_module(
area: KernelModule,
device: &DeviceAttributes,
limit: PtxTier,
) -> Option<ModuleRequest> {
bound_module(PRODUCTION, area, device, limit).or_else(|| {
MEASURED_MODULES
.iter()
.find_map(|binding| binding.request(area, device, limit))
})
}
fn bound_module(
bindings: &[Binding],
area: KernelModule,
device: &DeviceAttributes,
limit: PtxTier,
) -> Option<ModuleRequest> {
bindings
.iter()
.find(|binding| binding.area() == area && binding.scope.contains(device))
.map(|binding| binding.module)
.filter(|module| module.tier() <= limit)
}
#[derive(Debug, Clone, Copy)]
struct Route {
module: ModuleRequest,
proof: &'static TupleProof,
speed: SpeedEvidence,
}
fn production_route(
bindings: &'static [Binding],
precedence: &[KernelModule],
boundary: BoundaryId,
batch: usize,
math: CudaMath,
device: &DeviceAttributes,
) -> Option<Route> {
if !boundary.batches().contains(batch) {
return None;
}
for area in precedence {
let Some((binding, proof)) = bindings
.iter()
.filter(|binding| binding.area() == *area && binding.scope.contains(device))
.find_map(|binding| Some((binding, binding.proof(boundary, batch, math)?)))
else {
continue;
};
return match proof.speed {
SpeedStatus::Measured(speed) if speed.scope.contains(device) => Some(Route {
module: binding.module,
proof,
speed,
}),
SpeedStatus::Measured(_) | SpeedStatus::Unmeasured => None,
};
}
None
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PlanPin {
Pinned(ConfigPin),
#[cfg(all(test, feature = "_cuda-libraries"))]
Implemented,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TokenEvidence {
Production {
accuracy: RecordHash,
speed: SpeedEvidence,
},
Implemented,
Recipe(policy::Recipe),
DeviceDefault(policy::DeviceDefault),
Tuned { acceptance: &'static str },
Port {
scope: SpeedScope,
summary: &'static str,
},
#[cfg(all(test, feature = "_cuda-libraries"))]
Qualification,
}
#[derive(Debug)]
pub(crate) struct Qualified {
boundary: BoundaryId,
batch: usize,
math: CudaMath,
target: Target,
pin: PlanPin,
evidence: TokenEvidence,
selection: Selection,
}
impl Qualified {
fn source(&self) -> policy::Source {
match self.evidence {
TokenEvidence::Tuned { .. } => policy::Source::TuneFile,
TokenEvidence::Recipe(_) | TokenEvidence::Production { .. } => policy::Source::Recipe,
TokenEvidence::Port {
scope: SpeedScope::AllDevices(_),
..
}
| TokenEvidence::DeviceDefault(_)
| TokenEvidence::Implemented => policy::Source::Default,
TokenEvidence::Port { .. } => policy::Source::Recipe,
#[cfg(all(test, feature = "_cuda-libraries"))]
TokenEvidence::Qualification => policy::Source::Default,
}
}
pub(crate) fn area(&self) -> KernelModule {
self.target.module.area()
}
fn speed_measured(&self) -> bool {
match self.evidence {
TokenEvidence::Production { speed, .. } => {
speed.scope.measured_on_device(self.target.device)
}
TokenEvidence::Port { scope, .. } => scope.measured_on_device(self.target.device),
TokenEvidence::Recipe(_) => true,
TokenEvidence::Tuned { .. } => true,
_ => false,
}
}
fn production(
boundary: BoundaryId,
batch: usize,
math: CudaMath,
device: &DeviceAttributes,
route: Route,
) -> Self {
Self {
boundary,
batch,
math,
target: Target {
module: route.module,
device: device.capability(),
},
pin: PlanPin::Pinned(route.proof.pin),
evidence: TokenEvidence::Production {
accuracy: route.proof.accuracy,
speed: route.speed,
},
selection: Selection::Production,
}
}
fn plan_module(&self) -> ModuleRequest {
self.target.module
}
fn check(
&self,
runtime: &CudaRuntime,
area: KernelModule,
boundary: &str,
batch: usize,
math: CudaMath,
) -> Result<super::LoadedKernels, CudaError> {
let mismatch = || CudaError::Unsupported {
context: "qualified plan",
reason: "qualification token does not match the requested plan".to_owned(),
};
if self.boundary.name() != boundary
|| self.batch != batch
|| self.math != math
|| self.target.module.area() != area
|| self.target.device != runtime.compute_capability()
{
return Err(mismatch());
}
let loaded = runtime.load_module(self.plan_module())?;
if loaded.request() != self.plan_module() {
return Err(mismatch());
}
match self.evidence {
TokenEvidence::Production { accuracy, speed } => tracing::debug!(
boundary = self.boundary.name(),
batch,
?math,
%accuracy,
speed_record = %speed.record,
integrated = %speed.integrated,
scope = ?speed.scope,
"CUDA production evidence"
),
TokenEvidence::Port { scope, .. } => {
if let SpeedScope::AllDevices(evidence) = scope {
tracing::debug!(
summary = evidence.summary(),
?scope,
"CUDA broad-winner evidence"
);
}
}
TokenEvidence::Implemented => {}
TokenEvidence::Tuned { acceptance } => {
tracing::debug!(acceptance, "CUDA tuned configuration accuracy acceptance")
}
TokenEvidence::Recipe(recipe) => {
tracing::debug!(summary = recipe.summary(), "CUDA measured recipe evidence")
}
TokenEvidence::DeviceDefault(default) => tracing::debug!(
summary = default.summary(),
"CUDA device-class default evidence"
),
#[cfg(all(test, feature = "_cuda-libraries"))]
TokenEvidence::Qualification => {}
}
Ok(loaded)
}
pub(super) fn finish<T>(
&self,
area: KernelModule,
driver_only: bool,
result: Result<T, PlanError>,
) -> Result<Option<T>, CudaError> {
let library_allowed = self.selection == Selection::Production && !driver_only;
match result {
Ok(plan) => {
let measured = self.speed_measured();
tracing::info!(boundary = self.boundary.name(), batch = self.batch,
math = ?self.math, area = area.name(), source = self.source().name(), speed_measured = measured,
evidence = ?self.evidence, "CUDA route implementation=Oxide");
Ok(Some(plan))
}
Err(PlanError::Cuda(error)) => Err(error),
Err(PlanError::Geometry(error @ GeometryError::Invalid { .. })) => {
Err(self.geometry(area, error))
}
Err(refusal) if library_allowed => {
tracing::warn!(
boundary = self.boundary.name(),
batch = self.batch,
source = policy::Source::Library.name(),
"CUDA candidate unavailable reason={refusal}; using Library"
);
Ok(None)
}
Err(PlanError::DeviceUnsupported { reason }) => {
Err(CudaError::CandidateDeviceUnsupported {
area: area.name(),
boundary: self.boundary.name().to_owned(),
batch: self.batch,
math: self.math,
tier: self.target.module.tier(),
device: self.target.device,
reason,
})
}
Err(PlanError::WeightsOutOfContract { layer, fault }) => {
Err(CudaError::CandidateWeightsOutOfContract {
area: area.name(),
boundary: self.boundary.name().to_owned(),
batch: self.batch,
math: self.math,
tier: self.target.module.tier(),
device: self.target.device,
layer,
fault,
})
}
Err(PlanError::Geometry(error)) => Err(self.geometry(area, error)),
}
}
fn geometry(&self, area: KernelModule, error: GeometryError) -> CudaError {
CudaError::CandidateGeometry {
area: area.name(),
boundary: self.boundary.name().to_owned(),
batch: self.batch,
math: self.math,
error,
}
}
fn foreign_pin(&self, pin: ConfigPin) -> CudaError {
CudaError::Unsupported {
context: "qualified plan",
reason: format!("{} pin {pin:?} cannot plan this area", self.boundary),
}
}
pub(crate) fn conv(
self,
runtime: &CudaRuntime,
spec: ConvLayerSpec<'_>,
) -> Result<Option<ConvOxide>, CudaError> {
let area = KernelModule::Resnet;
let kernels = self.check(runtime, area, spec.name, spec.conv.batch, spec.conv.math)?;
let pin = match self.pin {
PlanPin::Pinned(ConfigPin::Conv(pin)) => Ok(pin),
PlanPin::Pinned(other) => return Err(self.foreign_pin(other)),
#[cfg(all(test, feature = "_cuda-libraries"))]
PlanPin::Implemented => ConvOxide::implemented_pin(&spec),
};
let plan = pin.and_then(|pin| {
let plan = ConvOxide::plan(runtime, &kernels, spec, pin)?;
Ok(plan)
});
self.finish(area, super::driver_only(), plan)
}
pub(crate) fn wideconv(
self,
runtime: &CudaRuntime,
spec: ConvLayerSpec<'_>,
) -> Result<Option<WideconvOxide>, CudaError> {
let area = KernelModule::Wideconv;
let kernels = self.check(runtime, area, spec.name, spec.conv.batch, spec.conv.math)?;
let pin = match self.pin {
PlanPin::Pinned(ConfigPin::Wideconv(pin)) => Ok(pin),
PlanPin::Pinned(other) => return Err(self.foreign_pin(other)),
#[cfg(all(test, feature = "_cuda-libraries"))]
PlanPin::Implemented => WideconvOxide::implemented_pin(&spec),
};
let plan = pin.and_then(|pin| {
let plan = WideconvOxide::plan(runtime, &kernels, spec, pin)?;
Ok(plan)
});
self.finish(area, super::driver_only(), plan)
}
pub(crate) fn sinc(
self,
runtime: &CudaRuntime,
spec: SincSpec<'_>,
) -> Result<Option<SincOxide>, CudaError> {
let area = KernelModule::Sincnet;
let kernels = self.check(
runtime,
area,
"sincnet.conv0.abs_pool",
spec.batch,
spec.math,
)?;
let pin = match self.pin {
PlanPin::Pinned(ConfigPin::Sinc(pin)) => Ok(pin),
PlanPin::Pinned(other) => return Err(self.foreign_pin(other)),
#[cfg(all(test, feature = "_cuda-libraries"))]
PlanPin::Implemented => SincOxide::implemented_pin(&spec),
};
let plan = pin.and_then(|pin| {
let plan = SincOxide::plan(runtime, &kernels, spec, pin)?;
Ok(plan)
});
self.finish(area, super::driver_only(), plan)
}
pub(crate) fn lstm(
self,
runtime: &CudaRuntime,
spec: LstmSpec<'_>,
) -> Result<Option<LstmOxide>, CudaError> {
let area = KernelModule::Lstm;
let kernels = self.check(runtime, area, "lstm.stack", spec.batch, spec.math)?;
let pin = match self.pin {
PlanPin::Pinned(ConfigPin::Lstm(pin)) => Ok(pin),
PlanPin::Pinned(other) => return Err(self.foreign_pin(other)),
#[cfg(all(test, feature = "_cuda-libraries"))]
PlanPin::Implemented => LstmOxide::implemented_pin(&spec),
};
let plan = pin.and_then(|pin| {
let plan = LstmOxide::plan(runtime, &kernels, spec, pin)?;
Ok(plan)
});
self.finish(area, super::driver_only(), plan)
}
pub(crate) fn projected_lstm(
self,
runtime: &CudaRuntime,
spec: LstmSpec<'_>,
) -> Result<Option<LstmProjOxide>, CudaError> {
let area = KernelModule::LstmProj;
let kernels = self.check(runtime, area, "lstm.stack", spec.batch, spec.math)?;
let pin = match self.pin {
PlanPin::Pinned(ConfigPin::Lstm(pin)) => Ok(pin),
PlanPin::Pinned(other) => return Err(self.foreign_pin(other)),
#[cfg(all(test, feature = "_cuda-libraries"))]
PlanPin::Implemented => {
LstmProjOxide::device_pin(runtime.device(), kernels.tier(), &spec)
}
};
let plan = pin.and_then(|pin| LstmProjOxide::plan(runtime, &kernels, spec, pin));
self.finish(area, super::driver_only(), plan)
}
pub(crate) fn dense(
self,
runtime: &CudaRuntime,
spec: DenseSpec,
rows: usize,
weight: &cudarc::driver::CudaSlice<f32>,
bias: &cudarc::driver::CudaSlice<f32>,
) -> Result<Option<DenseOxide>, CudaError> {
let area = KernelModule::Segdense;
let kernels = self.check(
runtime,
area,
spec.site().boundary().name(),
spec.batch(),
spec.math(),
)?;
let pin = match self.pin {
PlanPin::Pinned(ConfigPin::Segdense(pin)) => Ok(pin),
PlanPin::Pinned(other) => return Err(self.foreign_pin(other)),
#[cfg(all(test, feature = "_cuda-libraries"))]
PlanPin::Implemented => {
DenseOxide::implemented_pin(spec, kernels.tier(), runtime.device())
}
};
let plan = spec
.check_rows(rows)
.and(pin)
.and_then(|pin| DenseOxide::plan(runtime, &kernels, spec, weight, bias, pin));
self.finish(area, super::driver_only(), plan)
}
pub(crate) fn segconv(
self,
runtime: &CudaRuntime,
spec: SegConvSpec,
conv: super::geometry::Conv2d,
weight: &cudarc::driver::CudaSlice<f32>,
) -> Result<Option<SegConvOxide>, CudaError> {
let area = KernelModule::Segdense;
let kernels = self.check(
runtime,
area,
spec.site().boundary().name(),
spec.batch(),
spec.math(),
)?;
let pin = match self.pin {
PlanPin::Pinned(ConfigPin::Segdense(pin)) => Ok(pin),
PlanPin::Pinned(other) => return Err(self.foreign_pin(other)),
#[cfg(all(test, feature = "_cuda-libraries"))]
PlanPin::Implemented => {
SegConvOxide::implemented_pin(spec, kernels.tier(), runtime.device())
}
};
let plan = spec
.check_conv(conv)
.and(pin)
.and_then(|pin| SegConvOxide::plan(runtime, &kernels, spec, weight, pin));
self.finish(area, super::driver_only(), plan)
}
pub(crate) fn fbank(
self,
runtime: &CudaRuntime,
spec: FbankSpec,
) -> Result<Option<FbankOxide>, CudaError> {
let area = KernelModule::FbankDft;
let kernels = self.check(runtime, area, "fbank.dft", spec.batch(), spec.math())?;
let pin = match self.pin {
PlanPin::Pinned(ConfigPin::Fbank(pin)) => Ok(pin),
PlanPin::Pinned(other) => return Err(self.foreign_pin(other)),
#[cfg(all(test, feature = "_cuda-libraries"))]
PlanPin::Implemented => FbankOxide::implemented_pin(spec),
};
let plan = pin.and_then(|pin| {
let plan = FbankOxide::plan(runtime, &kernels, spec, pin)?;
Ok(plan)
});
self.finish(area, super::driver_only(), plan)
}
}
#[derive(Debug, thiserror::Error)]
#[error("cannot select a CUDA boundary at batch zero")]
pub(crate) struct SelectionError;
#[cfg(all(test, feature = "_cuda-libraries"))]
pub(crate) fn select(
boundary: BoundaryId,
batch: usize,
math: CudaMath,
device: &DeviceAttributes,
loaded: ModuleRequest,
) -> Result<Selected, SelectionError> {
if batch == 0 {
return Err(SelectionError);
}
Ok(
match production_route(PRODUCTION, ROUTE_PRECEDENCE, boundary, batch, math, device) {
Some(route) if route.module == loaded => Selected::Oxide(Box::new(
Qualified::production(boundary, batch, math, device, route),
)),
_ => Selected::Library,
},
)
}
pub(crate) trait Modules {
fn device(&self) -> &DeviceAttributes;
fn tune_choice(
&self,
_boundary: BoundaryId,
_batch: usize,
_math: CudaMath,
) -> Result<Option<ApprovedChoice>, CudaError> {
Ok(None)
}
fn is_tuning(&self) -> bool {
false
}
fn recipe_mode(&self) -> policy::RecipeMode {
policy::RecipeMode::Disabled
}
fn tier_limit(&self) -> PtxTier;
fn force_library(&self) -> bool {
false
}
fn fp16(&self) -> Fp16Policy {
Fp16Policy::Allowed
}
fn effective_request(&self, request: ModuleRequest) -> Result<ModuleRequest, CudaError> {
Ok(request)
}
fn load(&mut self, request: ModuleRequest) -> Result<ModuleRequest, CudaError>;
#[cfg(all(test, feature = "_cuda-libraries"))]
fn embedded_exact(&self, area: KernelModule) -> Result<ModuleRequest, CudaError>;
}
struct RuntimeModules<'a> {
runtime: &'a CudaRuntime,
fp16: Fp16Policy,
}
impl Modules for RuntimeModules<'_> {
fn is_tuning(&self) -> bool {
self.runtime.is_tuning()
}
fn tune_choice(
&self,
boundary: BoundaryId,
batch: usize,
math: CudaMath,
) -> Result<Option<ApprovedChoice>, CudaError> {
let choice = self.runtime.tuned_choice(boundary, batch, math);
if self.is_tuning() && choice.is_none() {
return Err(super::tuning::invalid(
"no accuracy-approved choice for this tuning tuple",
));
}
Ok(choice)
}
fn recipe_mode(&self) -> policy::RecipeMode {
self.runtime.recipe_mode()
}
fn effective_request(&self, request: ModuleRequest) -> Result<ModuleRequest, CudaError> {
self.runtime.effective_request(request)
}
fn force_library(&self) -> bool {
self.runtime.force_library()
}
fn fp16(&self) -> Fp16Policy {
self.fp16
}
fn device(&self) -> &DeviceAttributes {
self.runtime.device()
}
fn tier_limit(&self) -> PtxTier {
self.runtime.ptx_tier()
}
fn load(&mut self, request: ModuleRequest) -> Result<ModuleRequest, CudaError> {
Ok(self.runtime.load_module(request)?.request())
}
#[cfg(all(test, feature = "_cuda-libraries"))]
fn embedded_exact(&self, area: KernelModule) -> Result<ModuleRequest, CudaError> {
self.runtime.embedded_exact_request(area)
}
}
pub(crate) fn plan_selection(
runtime: &CudaRuntime,
boundary: BoundaryId,
batch: usize,
math: CudaMath,
#[cfg(all(test, feature = "_cuda-libraries"))] override_choice: Option<Choice>,
) -> Result<Selected, CudaError> {
plan_selection_with(
runtime,
boundary,
batch,
math,
Fp16Policy::Allowed,
#[cfg(all(test, feature = "_cuda-libraries"))]
override_choice,
)
}
pub(crate) fn plan_selection_with(
runtime: &CudaRuntime,
boundary: BoundaryId,
batch: usize,
math: CudaMath,
fp16: Fp16Policy,
#[cfg(all(test, feature = "_cuda-libraries"))] override_choice: Option<Choice>,
) -> Result<Selected, CudaError> {
let request = PlanRequest::Hybrid;
#[cfg(all(test, feature = "_cuda-libraries"))]
let request = override_choice.map_or(request, PlanRequest::Qualification);
let modules = RuntimeModules { runtime, fp16 };
let selected = request.resolve(boundary, batch, math, modules)?;
match &selected {
Selected::Oxide(token) => {
tracing::info!(boundary = boundary.name(), batch, ?math, area = token.area().name(), source = token.source().name(), speed_measured = token.speed_measured(), evidence = ?token.evidence, "CUDA route selected implementation=Oxide")
}
Selected::Library => tracing::info!(
boundary = boundary.name(),
batch,
?math,
speed_measured = false,
source = if matches!(
runtime.tuned_choice(boundary, batch, math),
Some(ApprovedChoice::Library)
) && !runtime.force_library()
{
policy::Source::TuneFile.name()
} else {
policy::Source::Library.name()
},
"CUDA route selected implementation=Library"
),
}
Ok(selected)
}
#[derive(Debug, Clone, Copy)]
enum PlanRequest {
Hybrid,
#[cfg_attr(not(all(test, feature = "_cuda-libraries")), allow(dead_code))]
Production,
#[cfg(test)]
DriverOnly,
#[cfg(all(test, feature = "_cuda-libraries"))]
Qualification(Choice),
}
impl PlanRequest {
fn resolve(
self,
boundary: BoundaryId,
batch: usize,
math: CudaMath,
modules: impl Modules,
) -> Result<Selected, CudaError> {
self.resolve_with_candidates(boundary, batch, math, modules, &driver::areas())
}
fn resolve_with_candidates(
self,
boundary: BoundaryId,
batch: usize,
math: CudaMath,
mut modules: impl Modules,
candidates: &[driver::Area],
) -> Result<Selected, CudaError> {
if batch == 0 {
return Err(CudaError::Unsupported {
context: "CUDA selection",
reason: SelectionError.to_string(),
});
}
let driver = super::driver_only();
#[cfg(test)]
let driver = driver || matches!(self, Self::DriverOnly);
if modules.force_library() && matches!(self, Self::Production | Self::Hybrid) {
return Ok(Selected::Library);
}
if matches!(self, Self::Hybrid)
&& let Some(choice) = modules.tune_choice(boundary, batch, math)?
{
if !modules.fp16().allows() && choice.is_fp16() {
if modules.is_tuning() {
return Err(super::tuning::invalid(
"FP16 tuning candidate is excluded by the layer weights",
));
}
} else {
return tuned_selection(choice, boundary, batch, math, &mut modules, !driver);
}
}
if driver {
#[cfg(test)]
if matches!(self, Self::DriverOnly) {
return driver::test_support::select(boundary, batch, math, modules);
}
return driver::select_default(boundary, batch, math, modules);
}
if matches!(self, Self::Hybrid)
&& let Some(selected) =
driver::select_ports(boundary, batch, math, candidates, &mut modules)?
{
return Ok(selected);
}
#[cfg(all(test, feature = "_cuda-libraries"))]
if let Self::Qualification(choice) = self {
match choice {
Choice::Library => return Ok(Selected::Library),
Choice::Oxide(Selection::Explicit) => {
let Some(request) = explicit_request(&modules, boundary, batch, math)? else {
return Ok(Selected::Library);
};
let request = modules.effective_request(request)?;
let loaded = modules.load(request)?;
return qualification_selection(
choice,
boundary,
batch,
math,
modules.device(),
loaded,
);
}
_ => {}
}
}
let device = modules.device();
let Some(route) =
production_route(PRODUCTION, ROUTE_PRECEDENCE, boundary, batch, math, device)
.filter(|route| route.module.tier() <= modules.tier_limit())
else {
return Ok(Selected::Library);
};
let request = modules.effective_request(route.module)?;
let loaded = modules.load(request)?;
if loaded != request {
return Ok(Selected::Library);
}
let mut token = Qualified::production(boundary, batch, math, modules.device(), route);
if request != route.module {
token.target.module = request;
token.evidence = TokenEvidence::Implemented;
}
Ok(Selected::Oxide(Box::new(token)))
}
}
fn tuned_selection(
choice: ApprovedChoice,
boundary: BoundaryId,
batch: usize,
math: CudaMath,
modules: &mut impl Modules,
library_allowed: bool,
) -> Result<Selected, CudaError> {
let ApprovedChoice::Kernel(config) = choice else {
return if library_allowed {
Ok(Selected::Library)
} else {
Err(super::tuning::invalid(
"a driver-only build cannot select Library from a tune file",
))
};
};
if !config.matches(boundary, batch, math) || config.module().tier() > modules.tier_limit() {
return Err(super::tuning::invalid(
"tuned configuration does not match this execution tuple",
));
}
let request = modules.effective_request(config.module())?;
let loaded = modules.load(request)?;
if loaded != request {
return Err(CudaError::ArtifactUnavailable {
module: request.area().name(),
artifact: request.artifact(),
});
}
let evidence = if request == config.module() {
TokenEvidence::Tuned {
acceptance: config.acceptance(),
}
} else {
TokenEvidence::Implemented
};
Ok(Selected::Oxide(Box::new(Qualified {
boundary,
batch,
math,
target: Target {
module: loaded,
device: modules.device().capability(),
},
pin: PlanPin::Pinned(config.pin()),
evidence,
selection: if modules.is_tuning() {
Selection::Tuning
} else {
Selection::Production
},
})))
}
#[cfg(all(test, feature = "_cuda-libraries"))]
fn candidate_coverage(area: KernelModule, tier: PtxTier) -> Coverage {
match area {
KernelModule::Resnet => ConvOxide::coverage(tier),
KernelModule::Wideconv => WideconvOxide::coverage(tier),
KernelModule::Lstm => LstmOxide::coverage(tier),
KernelModule::Sincnet => SincOxide::coverage(tier),
KernelModule::FbankDft => FbankOxide::coverage(tier),
_ => Coverage::NONE,
}
}
#[cfg(all(test, feature = "_cuda-libraries"))]
fn explicit_request(
modules: &impl Modules,
boundary: BoundaryId,
batch: usize,
math: CudaMath,
) -> Result<Option<ModuleRequest>, CudaError> {
explicit_route(boundary, batch, math, |area| {
if matches!(area, KernelModule::Segdense | KernelModule::LstmProj) {
return Ok(None);
}
let request = modules.embedded_exact(area)?;
Ok(Some((request, candidate_coverage(area, request.tier()))))
})
}
#[cfg(all(test, feature = "_cuda-libraries"))]
fn explicit_route(
boundary: BoundaryId,
batch: usize,
math: CudaMath,
mut implemented: impl FnMut(KernelModule) -> Result<Option<(ModuleRequest, Coverage)>, CudaError>,
) -> Result<Option<ModuleRequest>, CudaError> {
for area in ROUTE_PRECEDENCE {
let Some((request, coverage)) = implemented(*area)? else {
continue;
};
if coverage.covers(boundary.name(), batch, math) {
return Ok(Some(request));
}
}
Ok(None)
}
#[cfg(all(test, feature = "_cuda-libraries"))]
fn qualification_selection(
choice: Choice,
boundary: BoundaryId,
batch: usize,
math: CudaMath,
device: &DeviceAttributes,
loaded: ModuleRequest,
) -> Result<Selected, CudaError> {
let coverage = candidate_coverage(loaded.area(), loaded.tier());
Ok(match choice {
Choice::Oxide(selection) if coverage.covers(boundary.name(), batch, math) => {
Selected::Oxide(Box::new(Qualified {
boundary,
batch,
math,
target: Target {
module: loaded,
device: device.capability(),
},
pin: PlanPin::Implemented,
evidence: TokenEvidence::Qualification,
selection,
}))
}
Choice::Library | Choice::Oxide(_) => Selected::Library,
})
}
#[cfg(all(test, feature = "_cuda-libraries"))]
pub(crate) fn legacy_fixture_coverage(
area: KernelModule,
device: &DeviceAttributes,
variants: AreaPtx,
) -> Vec<CoverageEntry> {
PRODUCTION
.iter()
.filter(|binding| binding.area() == area && binding.scope.contains(device))
.filter(|binding| {
variants.embedded(binding.module.tier()).is_some_and(|ptx| {
binding.module.artifact()
== LoadedArtifact::PtxJit {
sha256: ptx.sha256(),
}
})
})
.flat_map(|binding| binding.proofs)
.filter(|proof| {
matches!(proof.speed, SpeedStatus::Measured(speed) if speed.scope.contains(device))
})
.map(|proof| CoverageEntry {
layers: proof.boundary.name_slice(),
batches: Batches::Only(std::slice::from_ref(&proof.batch)),
maths: Maths::Only(std::slice::from_ref(&proof.math)),
})
.collect()
}
#[derive(Debug, Clone)]
pub(crate) struct LibraryNeed {
boundary: BoundaryId,
batch: usize,
math: CudaMath,
target: AreaTarget,
library: CudaLibrary,
}
impl LibraryNeed {
pub(crate) fn new(
boundary: BoundaryId,
batch: usize,
math: CudaMath,
target: AreaTarget,
library: CudaLibrary,
) -> Self {
Self {
boundary,
batch,
math,
target,
library,
}
}
pub(crate) fn error(&self) -> CudaError {
if super::driver_only() {
return driver::missing(self.boundary, self.batch, self.math);
}
CudaError::NotDriverOnly {
area: self.boundary.area().name(),
boundary: self.boundary.name().to_owned(),
batch: self.batch,
math: self.math,
tier: self.target.tier,
device: self.target.device,
library: self.library,
}
}
pub(crate) fn prepare(&self, runtime: &CudaRuntime) -> Result<(), CudaError> {
if super::driver_only() {
return Err(self.error());
}
#[cfg(feature = "_cuda-libraries")]
{
runtime.prepare_library(self.library)?;
tracing::info!(boundary = self.boundary.name(), batch = self.batch,
math = ?self.math, speed_measured = false, "CUDA route implementation=Library");
Ok(())
}
#[cfg(not(feature = "_cuda-libraries"))]
{
let _ = runtime;
Err(self.error())
}
}
pub(crate) fn prepare_handle(&self, runtime: &CudaRuntime) -> Result<(), CudaError> {
match self.library {
CudaLibrary::Nvrtc if !super::driver_only() => Ok(()),
_ => self.prepare(runtime),
}
}
}
#[cfg(all(test, feature = "_cuda-libraries"))]
mod golden_tests;
#[cfg(all(test, feature = "_cuda-libraries"))]
mod tests;