use crate::error::{CortexError, Result};
use crate::stage::{
AnnCapabilities, AnnExecutor, AnnStage, DType, StageId, StageInput, StageKind, StageKindTag,
StageTensor,
};
use std::collections::BTreeSet;
use std::fmt;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DeviceClass {
Cpu,
Cuda,
Metal,
}
impl DeviceClass {
pub fn as_str(self) -> &'static str {
match self {
DeviceClass::Cpu => "cpu",
DeviceClass::Cuda => "cuda",
DeviceClass::Metal => "metal",
}
}
}
impl fmt::Display for DeviceClass {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BackendLimitations {
pub unsupported_tags: BTreeSet<StageKindTag>,
pub unsupported_dtypes: BTreeSet<DType>,
pub unsupported_devices: BTreeSet<DeviceClass>,
pub notes: Vec<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct HiddenStateBuffer {
pub data: Vec<f32>,
pub shape: Vec<usize>,
pub dtype: DType,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AdapterCapabilities {
pub ann: AnnCapabilities,
pub devices: BTreeSet<DeviceClass>,
pub batch: bool,
pub sequence_cache: bool,
pub hidden_state_io: bool,
pub limitations: BackendLimitations,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NegotiationDocument {
pub backend_name: &'static str,
pub stage_kinds: Vec<String>,
pub dtypes: Vec<String>,
pub devices: Vec<String>,
pub batch: bool,
pub sequence_cache: bool,
pub stateful: bool,
pub hidden_state_io: bool,
pub unsupported: Vec<String>,
pub unsupported_dtypes: Vec<String>,
pub unsupported_devices: Vec<String>,
pub limitations: Vec<String>,
}
impl AdapterCapabilities {
pub fn require_supported(
&self,
stage_id: &StageId,
kind: &StageKind,
dtype: DType,
device: DeviceClass,
) -> Result<()> {
let backend = self.ann.backend_name;
let tag = kind.tag();
if !self.ann.supported_tags.contains(&tag) {
let detail = if self.limitations.unsupported_tags.contains(&tag) {
format!("{tag} is not supported")
} else {
format!("{tag} is not advertised")
};
return Err(unsupported_operation(
backend,
stage_id,
"stage_kind",
detail,
));
}
if !self.ann.supported_dtypes.contains(&dtype) {
let detail = if self.limitations.unsupported_dtypes.contains(&dtype) {
format!("{dtype} is not supported")
} else {
format!("{dtype} is not advertised")
};
return Err(unsupported_operation(backend, stage_id, "dtype", detail));
}
if !self.devices.contains(&device) {
let detail = if self.limitations.unsupported_devices.contains(&device) {
format!("{device} is not supported")
} else {
format!("{device} is not advertised")
};
return Err(unsupported_operation(backend, stage_id, "device", detail));
}
Ok(())
}
pub fn negotiation_document(&self) -> NegotiationDocument {
let mut stage_kinds: Vec<String> = self
.ann
.supported_tags
.iter()
.map(|tag| tag.as_str().to_string())
.collect();
stage_kinds.sort();
let mut dtypes: Vec<String> = self
.ann
.supported_dtypes
.iter()
.map(|dtype| dtype.as_str().to_string())
.collect();
dtypes.sort();
let mut devices: Vec<String> = self
.devices
.iter()
.map(|device| device.as_str().to_string())
.collect();
devices.sort();
let mut unsupported: Vec<String> = self
.limitations
.unsupported_tags
.iter()
.map(|tag| format!("stage_kind:{}", tag.as_str()))
.collect();
unsupported.sort();
let mut unsupported_dtypes: Vec<String> = self
.limitations
.unsupported_dtypes
.iter()
.map(|dtype| format!("dtype:{}", dtype.as_str()))
.collect();
unsupported_dtypes.sort();
let mut unsupported_devices: Vec<String> = self
.limitations
.unsupported_devices
.iter()
.map(|device| format!("device:{}", device.as_str()))
.collect();
unsupported_devices.sort();
let mut limitations = self.limitations.notes.clone();
limitations.push(
"translation target is hybrid-fusion negotiation (hybrid-fusion#41); this document does not place or rank backends".to_string(),
);
NegotiationDocument {
backend_name: self.ann.backend_name,
stage_kinds,
dtypes,
devices,
batch: self.batch,
sequence_cache: self.sequence_cache,
stateful: self.ann.stateful,
hidden_state_io: self.hidden_state_io,
unsupported,
unsupported_dtypes,
unsupported_devices,
limitations,
}
}
}
pub trait ExternalAdapterMarker: AnnExecutor {
fn adapter_capabilities(&self) -> AdapterCapabilities;
fn export_hidden(&self, tensor: &Self::Tensor) -> Result<HiddenStateBuffer>;
fn import_hidden(&self, buffer: &HiddenStateBuffer) -> Result<Self::Tensor>;
}
pub(crate) fn reference_adapter_capabilities(ann: AnnCapabilities) -> AdapterCapabilities {
let unsupported_tags = all_stage_tags()
.into_iter()
.filter(|tag| !ann.supported_tags.contains(tag))
.collect();
AdapterCapabilities {
ann,
devices: BTreeSet::from([DeviceClass::Cpu]),
batch: false,
sequence_cache: false,
hidden_state_io: true,
limitations: BackendLimitations {
unsupported_tags,
unsupported_dtypes: BTreeSet::from([DType::F16, DType::BF16]),
unsupported_devices: BTreeSet::from([DeviceClass::Cuda, DeviceClass::Metal]),
notes: vec![
"reference backend is f32, CPU-only, and dense; no batch axis and no sequence cache".to_string(),
],
},
}
}
fn unsupported_operation(
backend: &'static str,
stage_id: &StageId,
category: &'static str,
detail: String,
) -> CortexError {
CortexError::UnsupportedOperation {
backend,
stage_id: Some(stage_id.to_string()),
category,
detail,
}
}
fn all_stage_tags() -> [StageKindTag; 11] {
[
StageKindTag::Embedding,
StageKindTag::Attention,
StageKindTag::LayerNorm,
StageKindTag::RmsNorm,
StageKindTag::DenseMlp,
StageKindTag::GatedMlp,
StageKindTag::MoeRouter,
StageKindTag::MoeExpert,
StageKindTag::Add,
StageKindTag::Readout,
StageKindTag::Custom,
]
}
#[cfg(feature = "burn")]
fn policy_stub_capabilities(
backend_name: &'static str,
framework_name: &'static str,
) -> AdapterCapabilities {
AdapterCapabilities {
ann: AnnCapabilities {
backend_name,
supported_tags: BTreeSet::new(),
supported_dtypes: BTreeSet::new(),
stateful: false,
},
devices: BTreeSet::new(),
batch: false,
sequence_cache: false,
hidden_state_io: false,
limitations: BackendLimitations {
unsupported_tags: BTreeSet::from(all_stage_tags()),
unsupported_dtypes: BTreeSet::from([DType::F32, DType::F16, DType::BF16]),
unsupported_devices: BTreeSet::from([
DeviceClass::Cpu,
DeviceClass::Cuda,
DeviceClass::Metal,
]),
notes: vec![format!(
"{backend_name} adapter is a structured stub; cortex-hybrid does not depend on the {framework_name} crate"
)],
},
}
}
#[cfg(feature = "burn")]
fn policy_stub_refusal(backend_name: &'static str, framework_name: &'static str) -> CortexError {
CortexError::UnsupportedOperation {
backend: backend_name,
stage_id: None,
category: "policy",
detail: format!(
"{framework_name} is not a dependency of cortex-hybrid; the feature is a structured stub and does not link {framework_name}"
),
}
}
#[cfg(feature = "burn")]
macro_rules! define_policy_stub_adapter {
($adapter:ident, $tensor:ident, $backend:literal, $framework:literal) => {
#[doc = concat!("Tensor stand-in used while ", $framework, " stays outside core.")]
#[derive(Debug, Clone, PartialEq)]
pub struct $tensor {
shape: Vec<usize>,
dtype: $crate::stage::DType,
}
impl $crate::stage::StageTensor for $tensor {
fn meta(&self) -> $crate::stage::TensorMeta {
$crate::stage::TensorMeta {
shape: self.shape.clone(),
dtype: self.dtype,
}
}
}
#[doc = concat!($framework, " participation stub.")]
#[derive(Debug, Clone, Copy)]
pub struct $adapter;
impl $adapter {
pub fn unavailable() -> Self {
Self
}
}
impl $crate::adapter::ExternalAdapterMarker for $adapter {
fn adapter_capabilities(&self) -> $crate::adapter::AdapterCapabilities {
$crate::adapter::policy_stub_capabilities($backend, $framework)
}
fn export_hidden(
&self,
_tensor: &Self::Tensor,
) -> $crate::Result<$crate::adapter::HiddenStateBuffer> {
Err($crate::adapter::policy_stub_refusal($backend, $framework))
}
fn import_hidden(
&self,
_buffer: &$crate::adapter::HiddenStateBuffer,
) -> $crate::Result<Self::Tensor> {
Err($crate::adapter::policy_stub_refusal($backend, $framework))
}
}
impl $crate::stage::AnnExecutor for $adapter {
type Tensor = $tensor;
fn capabilities(&self) -> $crate::stage::AnnCapabilities {
$crate::adapter::ExternalAdapterMarker::adapter_capabilities(self).ann
}
fn execute(
&mut self,
stage: &$crate::stage::AnnStage,
_inputs: &[$crate::stage::StageInput<Self::Tensor>],
) -> $crate::Result<Self::Tensor> {
Err($crate::CortexError::UnsupportedStage {
backend: $backend,
stage_id: stage.id.to_string(),
kind: format!("{:?}", stage.kind),
})
}
}
};
}
#[cfg(feature = "burn")]
pub(crate) use define_policy_stub_adapter;
pub(crate) fn require_f32_buffer(buffer: &HiddenStateBuffer) -> Result<()> {
if buffer.dtype != DType::F32 {
return Err(CortexError::StageDTypeMismatch {
stage_id: "hidden_state".to_string(),
expected: DType::F32.to_string(),
got: buffer.dtype.to_string(),
});
}
let numel =
crate::tensor::checked_numel(&buffer.shape).map_err(|err| CortexError::StageFailed {
stage_id: "hidden_state".to_string(),
source: Box::new(err),
})?;
if buffer.data.len() != numel {
return Err(CortexError::StageFailed {
stage_id: "hidden_state".to_string(),
source: Box::new(CortexError::ShapeMismatch {
expected: buffer.shape.clone(),
got: vec![buffer.data.len()],
}),
});
}
Ok(())
}
pub struct ExternalAdapter;
impl ExternalAdapter {
pub fn capabilities<A: ExternalAdapterMarker + ?Sized>(adapter: &A) -> AdapterCapabilities {
adapter.adapter_capabilities()
}
pub fn execute<A: ExternalAdapterMarker + ?Sized>(
adapter: &mut A,
stage: &AnnStage,
inputs: &[StageInput<A::Tensor>],
) -> Result<A::Tensor> {
adapter.execute(stage, inputs)
}
pub fn export_hidden<A: ExternalAdapterMarker + ?Sized>(
adapter: &A,
tensor: &A::Tensor,
) -> Result<HiddenStateBuffer> {
adapter.export_hidden(tensor)
}
pub fn import_hidden<A: ExternalAdapterMarker + ?Sized>(
adapter: &A,
buffer: &HiddenStateBuffer,
) -> Result<A::Tensor> {
adapter.import_hidden(buffer)
}
}
pub fn require_supported_dtype<T: StageTensor>(
caps: &AnnCapabilities,
stage_id: &StageId,
tensor: &T,
) -> Result<()> {
let dtype = tensor.meta().dtype;
if caps.supported_dtypes.contains(&dtype) {
Ok(())
} else {
Err(CortexError::StageDTypeMismatch {
stage_id: stage_id.to_string(),
expected: caps
.supported_dtypes
.iter()
.map(|dtype| dtype.as_str())
.collect::<Vec<_>>()
.join(", "),
got: dtype.to_string(),
})
}
}
#[cfg(feature = "candle")]
mod candle;
#[cfg(feature = "candle")]
pub use candle::{
AttentionWeights, CandleExecutor, CandleTensor, EmbeddingWeights, GatedMlpWeights, HiddenState,
LayerNormWeights, LinearWeights, MlpWeights, RmsNormWeights, export_hidden_state,
export_reference, import_hidden_state, import_reference,
};
#[cfg(feature = "burn")]
mod burn_adapter;
#[cfg(feature = "burn")]
pub use burn_adapter::BurnAdapter;
#[cfg(test)]
mod tests {
use super::*;
fn buffer(data: Vec<f32>, shape: Vec<usize>) -> HiddenStateBuffer {
HiddenStateBuffer {
data,
shape,
dtype: DType::F32,
}
}
#[test]
fn require_f32_buffer_overflow_is_wrapped_size_overflow() {
let err = require_f32_buffer(&buffer(Vec::new(), vec![usize::MAX, 2])).unwrap_err();
assert!(
matches!(
&err,
CortexError::StageFailed { stage_id, source }
if stage_id == "hidden_state"
&& matches!(
&**source,
CortexError::SizeOverflow { shape } if shape == &[usize::MAX, 2]
)
),
"{err:?}"
);
}
#[test]
fn require_f32_buffer_zero_axis_short_circuits_overflow() {
require_f32_buffer(&buffer(Vec::new(), vec![usize::MAX, usize::MAX, 0])).unwrap();
}
#[test]
fn require_f32_buffer_length_mismatch_is_shape_mismatch() {
require_f32_buffer(&buffer(vec![0.0; 6], vec![2, 3])).unwrap();
let err = require_f32_buffer(&buffer(vec![0.0; 5], vec![2, 3])).unwrap_err();
assert!(
matches!(
&err,
CortexError::StageFailed { source, .. }
if matches!(
&**source,
CortexError::ShapeMismatch { expected, got }
if expected == &[2, 3] && got == &[5]
)
),
"{err:?}"
);
}
}