1use fuel_graph::registry::{FusedOpId, FusedOps};
20use fuel_ir::DType;
21use fuel_ir::dispatch::OpKind;
22use fuel_ir::probe::BackendId;
23use smallvec::SmallVec;
24
25use crate::fkc::caps_map::{self, ResolvedLayout};
26use crate::fkc::cost_expr::{self, CompiledCostExpr};
27use crate::fkc::error::FkcError;
28use crate::fkc::precision;
29use crate::fkc::revhash;
30use crate::fkc::schema::{CostBlock, FkcKernel};
31use crate::fused::{KernelRevisionHash, PrecisionGuarantee};
32use crate::kernel::{CostFn, KernelCaps, KernelDTypes, KernelRef};
33
34pub trait LinkRegistry {
47 fn resolve_primitive(&self, symbol: &str) -> Option<KernelRef>;
49 fn resolve_fused(&self, symbol: &str) -> Option<KernelRef>;
51
52 fn resolve_cost_fn(&self, _name: &str) -> Option<CostFn> {
64 None
65 }
66}
67
68#[derive(Debug, Clone)]
77pub struct ResolvedPrimitive {
78 pub op: OpKind,
80 pub dtypes: KernelDTypes,
82 pub backend: BackendId,
84 pub caps: KernelCaps,
87 pub layouts: Vec<ResolvedLayout>,
90 pub precision: PrecisionGuarantee,
92 pub cost: CompiledCostExpr,
94 pub cost_fn: Option<CostFn>,
102 pub kernel: KernelRef,
104 pub kernel_source: String,
106 pub revision: KernelRevisionHash,
108 pub variant: Option<String>,
114}
115
116#[derive(Debug, Clone)]
120pub struct ResolvedFused {
121 pub id: FusedOpId,
123 pub dtypes: KernelDTypes,
125 pub backend: BackendId,
127 pub caps: KernelCaps,
129 pub layouts: Vec<ResolvedLayout>,
131 pub precision: PrecisionGuarantee,
133 pub cost: CompiledCostExpr,
135 pub kernel: KernelRef,
137 pub kernel_source: String,
139 pub revision: KernelRevisionHash,
141 pub variant: Option<String>,
145 pub bundle_slot_names: Vec<String>,
151}
152
153#[derive(Debug, Clone)]
156pub enum Resolved {
157 Primitive(ResolvedPrimitive),
159 Fused(ResolvedFused),
161}
162
163pub(crate) fn lower_op_kind(s: &str, section: &str) -> Result<OpKind, FkcError> {
171 let mapped = match s {
174 "MatMul" => Some(OpKind::MatMul),
175 "AddElementwise" => Some(OpKind::AddElementwise),
176 "SubElementwise" => Some(OpKind::SubElementwise),
177 "MulElementwise" => Some(OpKind::MulElementwise),
178 "DivElementwise" => Some(OpKind::DivElementwise),
179 "ReluElementwise" => Some(OpKind::ReluElementwise),
180 "NegElementwise" => Some(OpKind::NegElementwise),
181 "SqrElementwise" => Some(OpKind::SqrElementwise),
182 "SqrtElementwise" => Some(OpKind::SqrtElementwise),
183 "RecipElementwise" => Some(OpKind::RecipElementwise),
184 "AbsElementwise" => Some(OpKind::AbsElementwise),
185 "TanhElementwise" => Some(OpKind::TanhElementwise),
186 "ExpElementwise" => Some(OpKind::ExpElementwise),
187 "LogElementwise" => Some(OpKind::LogElementwise),
188 "SinElementwise" => Some(OpKind::SinElementwise),
189 "CosElementwise" => Some(OpKind::CosElementwise),
190 "SigmoidElementwise" => Some(OpKind::SigmoidElementwise),
191 "SiluElementwise" => Some(OpKind::SiluElementwise),
192 "GeluElementwise" => Some(OpKind::GeluTanhElementwise),
193 "StepElementwise" => Some(OpKind::StepElementwise),
194 "SumReduce" => Some(OpKind::SumReduce),
195 "MaxReduce" => Some(OpKind::MaxReduce),
196 "MinReduce" => Some(OpKind::MinReduce),
197 "MeanReduce" => Some(OpKind::MeanReduce),
198 "Cast" => Some(OpKind::Cast),
199 "Conv2D" => Some(OpKind::Conv2D),
200 "ConvTranspose2D" => Some(OpKind::ConvTranspose2D),
201 "ReduceSumTo" => Some(OpKind::ReduceSumTo),
202 "ReduceMaxTo" => Some(OpKind::ReduceMaxTo),
203 "FusedLinear" => Some(OpKind::FusedLinear),
204 "RowScaledMatMul" => Some(OpKind::RowScaledMatMul),
205 "TopKLastDim" => Some(OpKind::TopKLastDim),
206 "MatMulTopK" => Some(OpKind::MatMulTopK),
207 "FlashAttn" => Some(OpKind::FlashAttn),
208 "FlashAttnBackwardQ" => Some(OpKind::FlashAttnBackwardQ),
209 "FlashAttnBackwardK" => Some(OpKind::FlashAttnBackwardK),
210 "FlashAttnBackwardV" => Some(OpKind::FlashAttnBackwardV),
211 "PagedAttn" => Some(OpKind::PagedAttn),
212 "Affine" => Some(OpKind::Affine),
213 "ClampElementwise" => Some(OpKind::ClampElementwise),
214 "PowIElementwise" => Some(OpKind::PowIElementwise),
215 "PowIElementwiseBackward" => Some(OpKind::PowIElementwiseBackward),
216 "MaximumElementwise" => Some(OpKind::MaximumElementwise),
217 "MinimumElementwise" => Some(OpKind::MinimumElementwise),
218 "EqualElementwise" => Some(OpKind::EqualElementwise),
219 "NotEqualElementwise" => Some(OpKind::NotEqualElementwise),
220 "LessElementwise" => Some(OpKind::LessElementwise),
221 "LessEqualElementwise" => Some(OpKind::LessEqualElementwise),
222 "GreaterElementwise" => Some(OpKind::GreaterElementwise),
223 "GreaterEqualElementwise" => Some(OpKind::GreaterEqualElementwise),
224 "Where" => Some(OpKind::Where),
225 "FloorElementwise" => Some(OpKind::FloorElementwise),
226 "CeilElementwise" => Some(OpKind::CeilElementwise),
227 "RoundElementwise" => Some(OpKind::RoundElementwise),
228 "SignElementwise" => Some(OpKind::SignElementwise),
229 "ErfElementwise" => Some(OpKind::ErfElementwise),
230 "GeluErfElementwise" => Some(OpKind::GeluElementwise),
231 "PowElementwise" => Some(OpKind::PowElementwise),
232 "RsqrtElementwise" => Some(OpKind::RsqrtElementwise),
233 "RemElementwise" => Some(OpKind::RemElementwise),
234 "Flip" => Some(OpKind::Flip),
235 "Roll" => Some(OpKind::Roll),
236 "CumSum" => Some(OpKind::CumSum),
237 "Pad" => Some(OpKind::Pad),
238 "Triu" => Some(OpKind::Triu),
239 "Tril" => Some(OpKind::Tril),
240 "LogSoftmaxLastDim" => Some(OpKind::LogSoftmaxLastDim),
241 "LogSoftmaxLastDimBackward" => Some(OpKind::LogSoftmaxLastDimBackward),
242 "MaskedFill" => Some(OpKind::MaskedFill),
243 "PadBackward" => Some(OpKind::PadBackward),
244 "Concat" => Some(OpKind::Concat),
245 "SoftmaxLastDim" => Some(OpKind::SoftmaxLastDim),
246 "SoftmaxLastDimBackward" => Some(OpKind::SoftmaxLastDimBackward),
247 "RmsNormLastDim" => Some(OpKind::RmsNormLastDim),
248 "RmsNormLastDimBackward" => Some(OpKind::RmsNormLastDimBackward),
249 "LayerNormLastDim" => Some(OpKind::LayerNormLastDim),
250 "LayerNormLastDimBackward" => Some(OpKind::LayerNormLastDimBackward),
251 "ReduceMaxToBackward" => Some(OpKind::ReduceMaxToBackward),
252 "IndexSelect" => Some(OpKind::IndexSelect),
253 "Gather" => Some(OpKind::Gather),
254 "Rope" => Some(OpKind::Rope),
255 "IndexAdd" => Some(OpKind::IndexAdd),
256 "ScatterAdd" => Some(OpKind::ScatterAdd),
257 "ArgMaxDim" => Some(OpKind::ArgMaxDim),
258 "ArgMinDim" => Some(OpKind::ArgMinDim),
259 "QMatMul" => Some(OpKind::QMatMul),
260 "WriteSlice" => Some(OpKind::WriteSlice),
261 "WriteSliceRotating" => Some(OpKind::WriteSliceRotating),
262 "WriteSliceDoff" => Some(OpKind::WriteSliceDoff),
263 "Copy" => Some(OpKind::Copy),
264 "ReluInplace" => Some(OpKind::ReluInplace),
265 "SiluInplace" => Some(OpKind::SiluInplace),
266 "GeluInplace" => Some(OpKind::GeluTanhInplace),
267 "TanhInplace" => Some(OpKind::TanhInplace),
268 "SigmoidInplace" => Some(OpKind::SigmoidInplace),
269 "NegInplace" => Some(OpKind::NegInplace),
270 "AbsInplace" => Some(OpKind::AbsInplace),
271 "SqrInplace" => Some(OpKind::SqrInplace),
272 "SqrtInplace" => Some(OpKind::SqrtInplace),
273 "RsqrtInplace" => Some(OpKind::RsqrtInplace),
274 "RecipInplace" => Some(OpKind::RecipInplace),
275 "ExpInplace" => Some(OpKind::ExpInplace),
276 "LogInplace" => Some(OpKind::LogInplace),
277 "SinInplace" => Some(OpKind::SinInplace),
278 "CosInplace" => Some(OpKind::CosInplace),
279 "SignInplace" => Some(OpKind::SignInplace),
280 "FloorInplace" => Some(OpKind::FloorInplace),
281 "CeilInplace" => Some(OpKind::CeilInplace),
282 "RoundInplace" => Some(OpKind::RoundInplace),
283 "ErfInplace" => Some(OpKind::ErfInplace),
284 "GeluErfInplace" => Some(OpKind::GeluInplace),
285 "ClampInplace" => Some(OpKind::ClampInplace),
286 "PowIInplace" => Some(OpKind::PowIInplace),
287 "InplaceAffine" => Some(OpKind::InplaceAffine),
288 "FusedSoftmaxCrossEntropy" => Some(OpKind::FusedSoftmaxCrossEntropy),
289 "CausalConv1d" => Some(OpKind::CausalConv1d),
290 "SelectiveScan" => Some(OpKind::SelectiveScan),
291 "SsdChunkScan" => Some(OpKind::SsdChunkScan),
292 "Nf4Matmul" => Some(OpKind::Nf4Matmul),
293 "AwqMatmul" => Some(OpKind::AwqMatmul),
294 _ => None,
295 };
296 match mapped {
303 Some(op) => Ok(op),
304 None => Err(FkcError::UnknownOpKind {
305 section: section.to_string(),
306 op_kind: s.to_string(),
307 }),
308 }
309}
310
311pub(crate) fn lower_fused_op(s: &str, section: &str) -> Result<FusedOpId, FkcError> {
331 fused_op_id_for_const_name(s).ok_or_else(|| FkcError::UnknownFusedOp {
332 section: section.to_string(),
333 fused_op: s.to_string(),
334 })
335}
336
337pub(crate) fn fused_op_id_for_const_name(s: &str) -> Option<FusedOpId> {
342 let id = match s {
343 "SOFTMAX_LAST_DIM" => FusedOps::SOFTMAX_LAST_DIM,
344 "FUSED_LINEAR" => FusedOps::FUSED_LINEAR,
345 "RMS_NORM_LAST_DIM" => FusedOps::RMS_NORM_LAST_DIM,
346 "LAYER_NORM_LAST_DIM" => FusedOps::LAYER_NORM_LAST_DIM,
347 "ROPE" => FusedOps::ROPE,
348 "CONV2D" => FusedOps::CONV2D,
349 "SOFTMAX_LAST_DIM_BACKWARD" => FusedOps::SOFTMAX_LAST_DIM_BACKWARD,
350 "LAYER_NORM_LAST_DIM_BACKWARD" => FusedOps::LAYER_NORM_LAST_DIM_BACKWARD,
351 "RMS_NORM_LAST_DIM_BACKWARD" => FusedOps::RMS_NORM_LAST_DIM_BACKWARD,
352 "REDUCE_MAX_TO_BACKWARD" => FusedOps::REDUCE_MAX_TO_BACKWARD,
353 "CONV_TRANSPOSE2D" => FusedOps::CONV_TRANSPOSE2D,
354 "FLASH_ATTN" => FusedOps::FLASH_ATTN,
355 "PAGED_ATTN" => FusedOps::PAGED_ATTN,
356 "QMATMUL" => FusedOps::QMATMUL,
357 "POWI_BACKWARD" => FusedOps::POWI_BACKWARD,
358 "INPLACE_AFFINE" => FusedOps::INPLACE_AFFINE,
359 "FUSED_SOFTMAX_CROSS_ENTROPY" => FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY,
360 "CAUSAL_CONV1D" => FusedOps::CAUSAL_CONV1D,
361 "SELECTIVE_SCAN" => FusedOps::SELECTIVE_SCAN,
362 "SSD_CHUNK_SCAN" => FusedOps::SSD_CHUNK_SCAN,
363 "NF4_MATMUL" => FusedOps::NF4_MATMUL,
364 "FLASH_ATTN_BACKWARD_Q" => FusedOps::FLASH_ATTN_BACKWARD_Q,
365 "FLASH_ATTN_BACKWARD_K" => FusedOps::FLASH_ATTN_BACKWARD_K,
366 "FLASH_ATTN_BACKWARD_V" => FusedOps::FLASH_ATTN_BACKWARD_V,
367 "AWQ_MATMUL" => FusedOps::AWQ_MATMUL,
368 "ROW_SCALED_MATMUL" => FusedOps::ROW_SCALED_MATMUL,
369 "TOP_K_LAST_DIM" => FusedOps::TOP_K_LAST_DIM,
370 "MATMUL_TOP_K" => FusedOps::MATMUL_TOP_K,
371 _ => return None,
372 };
373 Some(id)
374}
375
376pub(crate) fn lower_dtype(token: &str, section: &str, operand: &str) -> Result<DType, FkcError> {
388 let mapped = match token {
389 "U8" => Some(DType::U8),
390 "I8" => Some(DType::I8),
391 "U32" => Some(DType::U32),
392 "I16" => Some(DType::I16),
393 "I32" => Some(DType::I32),
394 "I64" => Some(DType::I64),
395 "BF16" => Some(DType::BF16),
396 "F16" => Some(DType::F16),
397 "F32" => Some(DType::F32),
398 "F64" => Some(DType::F64),
399 "F8E4M3" => Some(DType::F8E4M3),
400 "F6E2M3" => Some(DType::F6E2M3),
401 "F6E3M2" => Some(DType::F6E3M2),
402 "F4" => Some(DType::F4),
403 "F8E8M0" => Some(DType::F8E8M0),
404 "F8E5M2" => Some(DType::F8E5M2),
405 "F8E6M2" => Some(DType::F8E6M2),
406 "BOOL" => Some(DType::Bool),
407 _ => None,
408 };
409 if let Some(dt) = mapped {
410 match dt {
413 DType::U8
414 | DType::I8
415 | DType::U32
416 | DType::I16
417 | DType::I32
418 | DType::I64
419 | DType::BF16
420 | DType::F16
421 | DType::F32
422 | DType::F64
423 | DType::F8E4M3
424 | DType::F8E5M2
425 | DType::F6E2M3
426 | DType::F6E3M2
427 | DType::F4
428 | DType::F8E8M0
429 | DType::F8E6M2
430 | DType::Bool => (),
431 };
432 Ok(dt)
433 } else if fuel_ir::is_reserved_dtype_token(token) {
434 Err(FkcError::ReservedScalarType {
464 section: section.to_string(),
465 operand: operand.to_string(),
466 token: token.to_string(),
467 })
468 } else {
469 Err(FkcError::BadScalarType {
470 section: section.to_string(),
471 operand: operand.to_string(),
472 token: token.to_string(),
473 })
474 }
475}
476
477pub(crate) fn expand_dtype_class(
484 class: &str,
485 enumerated: &[DType],
486 section: &str,
487 operand: &str,
488) -> Result<Vec<DType>, FkcError> {
489 match class {
490 "float" => Ok(vec![DType::BF16, DType::F16, DType::F32, DType::F64]),
491 "int" => Ok(vec![DType::I8, DType::I16, DType::I32, DType::I64]),
492 "uint" => Ok(vec![DType::U8, DType::U32]),
493 "any" => Ok(enumerated.to_vec()),
494 other => Err(FkcError::BadScalarType {
495 section: section.to_string(),
496 operand: operand.to_string(),
497 token: format!("dtype_class={other}"),
498 }),
499 }
500}
501
502fn lower_backend(s: &str, section: &str) -> Result<BackendId, FkcError> {
508 let mapped = match s {
509 "Cpu" => Some(BackendId::Cpu),
510 "Cuda" => Some(BackendId::Cuda),
511 "Vulkan" => Some(BackendId::Vulkan),
512 "Metal" => Some(BackendId::Metal),
513 _ => None,
514 };
515 match mapped {
518 Some(b) => Ok(b),
519 None => Err(FkcError::UnknownBackend {
520 section: section.to_string(),
521 backend: s.to_string(),
522 }),
523 }
524}
525
526#[derive(Debug, Clone)]
533pub(crate) struct DtypeVariant {
534 pub(crate) dtypes: KernelDTypes,
536 pub(crate) fan_dtype: Option<DType>,
540}
541
542fn dtype_suffix(dt: DType) -> &'static str {
552 dt.as_str()
553}
554
555struct InputOperand {
558 name: String,
559 dtypes: Vec<DType>,
560 optional: bool,
563}
564
565fn resolve_operand_dtypes(
569 d: &crate::fkc::schema::TensorDesc,
570 section: &str,
571 operand: &str,
572) -> Result<Vec<DType>, FkcError> {
573 let mut enumerated: Vec<DType> = Vec::new();
574 for tok in &d.dtypes {
575 enumerated.push(lower_dtype(tok, section, operand)?);
576 }
577 let resolved = if enumerated.is_empty() {
578 if let Some(class) = &d.dtype_class {
579 expand_dtype_class(class, &enumerated, section, operand)?
580 } else {
581 enumerated
582 }
583 } else {
584 enumerated
587 };
588 if resolved.is_empty() {
589 return Err(FkcError::BadScalarType {
590 section: section.to_string(),
591 operand: operand.to_string(),
592 token: "<no dtypes and no dtype_class>".to_string(),
593 });
594 }
595 Ok(resolved)
596}
597
598fn assemble_dtype_variants(
640 kernel: &FkcKernel,
641 section: &str,
642) -> Result<(Vec<DtypeVariant>, Vec<ResolvedLayout>), FkcError> {
643 let mut inputs: Vec<InputOperand> = Vec::new();
644 let mut layouts: Vec<ResolvedLayout> = Vec::new();
645
646 if let Some(accept) = &kernel.accept {
647 for d in &accept.inputs {
648 let operand = d.name.as_deref().unwrap_or("<input>");
649 let resolved = resolve_operand_dtypes(d, section, operand)?;
650 inputs.push(InputOperand {
651 name: operand.to_string(),
652 dtypes: resolved,
653 optional: d.optional,
654 });
655 layouts.push(caps_map::resolve_layout(
656 d.layout.as_ref(),
657 section,
658 operand,
659 )?);
660 }
661 }
662
663 let optional_last = inputs.last().map(|op| op.optional).unwrap_or(false);
668 for (i, op) in inputs.iter().enumerate() {
669 if op.optional && i != inputs.len() - 1 {
670 return Err(FkcError::OptionalOperandNotLast {
671 section: section.to_string(),
672 operand: op.name.clone(),
673 });
674 }
675 }
676
677 let mut fan_set: Option<&[DType]> = None;
680 for operand in &inputs {
681 if operand.dtypes.len() > 1 {
682 match fan_set {
683 None => fan_set = Some(&operand.dtypes),
684 Some(existing) => {
685 if existing != operand.dtypes.as_slice() {
686 return Err(FkcError::FanoutDtypeMismatch {
687 section: section.to_string(),
688 operand: operand.name.clone(),
689 expected: format!("{existing:?}"),
690 found: format!("{:?}", operand.dtypes),
691 });
692 }
693 }
694 }
695 }
696 }
697
698 let fan_dtypes: Vec<Option<DType>> = match fan_set {
701 None => vec![None],
702 Some(set) => set.iter().map(|dt| Some(*dt)).collect(),
703 };
704
705 let per_variant = if optional_last { 2 } else { 1 };
708 let mut variants: Vec<DtypeVariant> = Vec::with_capacity(fan_dtypes.len() * per_variant);
709 for fan in fan_dtypes {
710 let mut input_dtypes: KernelDTypes = SmallVec::new();
714 for operand in &inputs {
715 let dt = if operand.dtypes.len() > 1 {
716 fan.expect("a varying operand implies a fanned dtype")
718 } else {
719 operand.dtypes[0]
720 };
721 input_dtypes.push(dt);
722 }
723
724 let mut output_dtypes: KernelDTypes = SmallVec::new();
732 if let Some(ret) = &kernel.return_ {
733 for out in &ret.outputs {
734 let operand = out.name.as_deref().unwrap_or("<output>");
735 if let Some(rule) = out.dtype_rule.as_deref()
736 && let Some(dt) = resolve_output_slot_dtype(
737 rule,
738 operand,
739 &inputs,
740 fan,
741 optional_last,
742 section,
743 )?
744 {
745 output_dtypes.push(dt);
746 }
747 }
748 if let Some(bundle) = &ret.bundle
759 && let Some((slot, rule)) = bundle_primary_dtype_rule(bundle)
760 && let Some(dt) =
761 resolve_output_slot_dtype(&rule, &slot, &inputs, fan, optional_last, section)?
762 {
763 output_dtypes.push(dt);
764 }
765 }
766
767 if optional_last {
768 let mut present: KernelDTypes = input_dtypes.clone();
771 present.extend_from_slice(&output_dtypes);
772 variants.push(DtypeVariant {
773 dtypes: present,
774 fan_dtype: fan,
775 });
776 let mut absent: KernelDTypes = SmallVec::new();
779 absent.extend_from_slice(&input_dtypes[..input_dtypes.len() - 1]);
780 absent.extend_from_slice(&output_dtypes);
781 variants.push(DtypeVariant {
782 dtypes: absent,
783 fan_dtype: fan,
784 });
785 } else {
786 let mut dtypes: KernelDTypes = input_dtypes;
787 dtypes.extend_from_slice(&output_dtypes);
788 variants.push(DtypeVariant {
789 dtypes,
790 fan_dtype: fan,
791 });
792 }
793 }
794
795 Ok((variants, layouts))
796}
797
798fn passthrough_dtype(inputs: &[InputOperand], role: &str, fan: Option<DType>) -> Option<DType> {
804 let operand_dtype = |op: &InputOperand| -> DType {
805 if op.dtypes.len() > 1 {
806 fan.expect("a varying operand implies a fanned dtype")
807 } else {
808 op.dtypes[0]
809 }
810 };
811 if let Some(op) = inputs.iter().find(|op| op.name == role) {
812 Some(operand_dtype(op))
813 } else {
814 inputs.first().map(operand_dtype)
815 }
816}
817
818fn resolve_output_slot_dtype(
828 rule: &str,
829 operand: &str,
830 inputs: &[InputOperand],
831 fan: Option<DType>,
832 optional_last: bool,
833 section: &str,
834) -> Result<Option<DType>, FkcError> {
835 match parse_dtype_rule(rule, section, operand)? {
836 DtypeRule::Fixed(dt) => Ok(Some(dt)),
837 DtypeRule::Passthrough(role) => {
838 if optional_last && inputs.last().map(|o| o.name == role).unwrap_or(false) {
839 return Err(FkcError::PassthroughNamesOptionalOperand {
840 section: section.to_string(),
841 role,
842 });
843 }
844 Ok(passthrough_dtype(inputs, &role, fan))
845 }
846 DtypeRule::Other => Ok(None),
847 }
848}
849
850fn bundle_primary_dtype_rule(bundle: &serde_yaml_ng::Value) -> Option<(String, String)> {
861 let serde_yaml_ng::Value::Sequence(slots) = bundle else {
862 return None;
863 };
864 let serde_yaml_ng::Value::Mapping(first) = slots.first()? else {
865 return None;
866 };
867 let rule = first
868 .get(serde_yaml_ng::Value::String("dtype_rule".into()))
869 .and_then(|v| v.as_str())?
870 .to_string();
871 let name = first
872 .get(serde_yaml_ng::Value::String("name".into()))
873 .and_then(|v| v.as_str())
874 .unwrap_or("<bundle>")
875 .to_string();
876 Some((name, rule))
877}
878
879enum DtypeRule {
882 Fixed(DType),
883 Passthrough(String),
884 Other,
885}
886
887fn parse_dtype_rule(rule: &str, section: &str, operand: &str) -> Result<DtypeRule, FkcError> {
890 let rule = rule.trim();
891 if let Some(inner) = rule
892 .strip_prefix("fixed(")
893 .and_then(|s| s.strip_suffix(")"))
894 {
895 Ok(DtypeRule::Fixed(lower_dtype(
896 inner.trim(),
897 section,
898 operand,
899 )?))
900 } else if let Some(inner) = rule
901 .strip_prefix("passthrough(")
902 .and_then(|s| s.strip_suffix(")"))
903 {
904 Ok(DtypeRule::Passthrough(inner.trim().to_string()))
905 } else {
906 Ok(DtypeRule::Other)
907 }
908}
909
910fn compile_cost(block: Option<&CostBlock>, section: &str) -> Result<CompiledCostExpr, FkcError> {
928 let Some(cost) = block else {
929 return Ok(CompiledCostExpr::Unknown);
930 };
931
932 let parse = |field: &str, src: Option<&str>| -> Result<CompiledCostExpr, FkcError> {
935 cost_expr::compile_field(src).map_err(|e| FkcError::CostExprParse {
936 section: section.to_string(),
937 field: field.to_string(),
938 expr: src.unwrap_or("").to_string(),
939 reason: e.to_string(),
940 })
941 };
942
943 let flops = parse("flops", cost.flops.as_deref())?;
944 let bytes_moved = parse("bytes_moved", cost.bytes_moved.as_deref())?;
945 if let Some(mem) = &cost.memory
948 && let Some(serde_yaml_ng::Value::String(s)) = &mem.device_bytes
949 {
950 let _ = parse("memory.device_bytes", Some(s))?;
951 }
952 let overhead_ns = match &cost.overhead_ns {
957 None | Some(serde_yaml_ng::Value::Null) => None,
958 Some(serde_yaml_ng::Value::Number(n)) => n.as_f64().map(cost_expr::CostNode::Lit),
959 Some(serde_yaml_ng::Value::String(s)) => match parse("overhead_ns", Some(s))? {
960 CompiledCostExpr::Expr(n) => Some(n),
961 _ => None,
962 },
963 Some(other) => {
964 return Err(FkcError::CostExprParse {
965 section: section.to_string(),
966 field: "overhead_ns".to_string(),
967 expr: format!("{other:?}"),
968 reason: "expected a number, an expression string or `~`".to_string(),
969 });
970 }
971 };
972
973 let node = |e: CompiledCostExpr| match e {
978 CompiledCostExpr::Expr(n) => Some(n),
979 _ => None,
980 };
981 match (node(flops), node(bytes_moved), overhead_ns) {
982 (None, None, None) => Ok(CompiledCostExpr::Unknown),
983 (Some(f), None, None) => Ok(CompiledCostExpr::Expr(f)),
984 (flops, bytes_moved, overhead_ns) => Ok(CompiledCostExpr::Declared {
985 flops,
986 bytes_moved,
987 overhead_ns,
988 }),
989 }
990}
991
992struct Defaults<'a> {
999 backend: &'a str,
1000 kernel_source: &'a str,
1001 revision_base: &'a str,
1002}
1003
1004fn lower_kernel(
1016 kernel: &FkcKernel,
1017 defaults: &Defaults<'_>,
1018 link: &dyn LinkRegistry,
1019 warnings: &mut Vec<crate::fkc::ImportWarning>,
1020) -> Result<Vec<Resolved>, FkcError> {
1021 let section = kernel.kernel.as_str();
1022
1023 match (kernel.op_kind.as_deref(), kernel.fused_op.as_deref()) {
1025 (Some(op_str), None) => {
1026 let op = lower_op_kind(op_str, section)?;
1027 Ok(lower_primitive(kernel, op, defaults, link)?
1029 .into_iter()
1030 .map(Resolved::Primitive)
1031 .collect())
1032 }
1033 (None, Some(fused_str)) => {
1034 let id = lower_fused_op(fused_str, section)?;
1035 Ok(lower_fused(kernel, id, defaults, link, warnings)?
1036 .into_iter()
1037 .map(Resolved::Fused)
1038 .collect())
1039 }
1040 (op, fused) => Err(FkcError::OpTargetAmbiguous {
1041 section: section.to_string(),
1042 op_kind: op.map(String::from),
1043 fused_op: fused.map(String::from),
1044 }),
1045 }
1046}
1047
1048fn lower_primitive(
1063 kernel: &FkcKernel,
1064 op: OpKind,
1065 defaults: &Defaults<'_>,
1066 link: &dyn LinkRegistry,
1067) -> Result<Vec<ResolvedPrimitive>, FkcError> {
1068 let section = kernel.kernel.as_str();
1069 let backend_str = kernel.backend.as_deref().unwrap_or(defaults.backend);
1070 let backend = lower_backend(backend_str, section)?;
1071 let (variants, layouts) = assemble_dtype_variants(kernel, section)?;
1072 let caps = caps_map::project_kernel_caps(&layouts);
1073 let precision = precision::lower_precision(kernel.precision.as_ref(), section)?;
1074 let cost = compile_cost(kernel.cost.as_ref(), section)?;
1075 let cost_fn = match kernel.cost.as_ref().and_then(|c| c.cost_fn.as_deref()) {
1081 Some(name) => Some(
1082 link.resolve_cost_fn(name)
1083 .ok_or_else(|| FkcError::UnknownCostFn {
1084 section: section.to_string(),
1085 cost_fn: name.to_string(),
1086 })?,
1087 ),
1088 None => None,
1089 };
1090
1091 let base_entry_point =
1092 kernel
1093 .entry_point
1094 .as_deref()
1095 .ok_or_else(|| FkcError::MissingRequiredField {
1096 section: section.to_string(),
1097 field: "entry_point".to_string(),
1098 })?;
1099
1100 let kernel_source = kernel
1101 .kernel_source
1102 .as_deref()
1103 .unwrap_or(defaults.kernel_source)
1104 .to_string();
1105 let revision = revhash::compute_revision(kernel, base_entry_point, defaults.revision_base)?;
1108
1109 let mut out = Vec::with_capacity(variants.len());
1110 for variant in variants {
1111 let symbol: std::borrow::Cow<'_, str> = match variant.fan_dtype {
1115 Some(dt) => std::borrow::Cow::Owned(format!("{base_entry_point}_{}", dtype_suffix(dt))),
1116 None => std::borrow::Cow::Borrowed(base_entry_point),
1117 };
1118 let kernel_ref =
1119 link.resolve_primitive(&symbol)
1120 .ok_or_else(|| FkcError::UnknownEntryPoint {
1121 section: section.to_string(),
1122 entry_point: symbol.into_owned(),
1123 })?;
1124
1125 out.push(ResolvedPrimitive {
1126 op,
1127 dtypes: variant.dtypes,
1128 backend,
1129 caps,
1130 layouts: layouts.clone(),
1131 precision,
1132 cost: cost.clone(),
1133 cost_fn,
1134 kernel: kernel_ref,
1135 kernel_source: kernel_source.clone(),
1136 revision,
1137 variant: kernel.variant.clone(),
1140 });
1141 }
1142 Ok(out)
1143}
1144
1145fn lower_fused(
1166 kernel: &FkcKernel,
1167 id: FusedOpId,
1168 defaults: &Defaults<'_>,
1169 link: &dyn LinkRegistry,
1170 warnings: &mut Vec<crate::fkc::ImportWarning>,
1171) -> Result<Vec<ResolvedFused>, FkcError> {
1172 crate::fkc::return_check::cross_check_fused_section(kernel, id, warnings)?;
1178 let section = kernel.kernel.as_str();
1179 let backend_str = kernel.backend.as_deref().unwrap_or(defaults.backend);
1180 let backend = lower_backend(backend_str, section)?;
1181 let (variants, layouts) = assemble_dtype_variants(kernel, section)?;
1182 let caps = caps_map::project_kernel_caps(&layouts);
1183 let precision = precision::lower_precision(kernel.precision.as_ref(), section)?;
1184 let cost = compile_cost(kernel.cost.as_ref(), section)?;
1185
1186 let base_entry_point =
1187 kernel
1188 .entry_point
1189 .as_deref()
1190 .ok_or_else(|| FkcError::MissingRequiredField {
1191 section: section.to_string(),
1192 field: "entry_point".to_string(),
1193 })?;
1194
1195 let kernel_source = kernel
1196 .kernel_source
1197 .as_deref()
1198 .unwrap_or(defaults.kernel_source)
1199 .to_string();
1200 let revision = revhash::compute_revision(kernel, base_entry_point, defaults.revision_base)?;
1203
1204 let mut out = Vec::with_capacity(variants.len());
1205 for variant in variants {
1206 let symbol: std::borrow::Cow<'_, str> = match variant.fan_dtype {
1210 Some(dt) => std::borrow::Cow::Owned(format!("{base_entry_point}_{}", dtype_suffix(dt))),
1211 None => std::borrow::Cow::Borrowed(base_entry_point),
1212 };
1213 let kernel_ref =
1214 link.resolve_fused(&symbol)
1215 .ok_or_else(|| FkcError::UnknownEntryPoint {
1216 section: section.to_string(),
1217 entry_point: symbol.into_owned(),
1218 })?;
1219
1220 out.push(ResolvedFused {
1221 id,
1222 dtypes: variant.dtypes,
1223 backend,
1224 caps,
1225 layouts: layouts.clone(),
1226 precision,
1227 cost: cost.clone(),
1228 kernel: kernel_ref,
1229 kernel_source: kernel_source.clone(),
1230 revision,
1231 variant: kernel.variant.clone(),
1234 bundle_slot_names: crate::fkc::return_check::bundle_slot_names(&kernel.return_),
1240 });
1241 }
1242 Ok(out)
1243}
1244
1245pub fn lower_file(
1255 file: &crate::fkc::schema::FkcFile,
1256 link: &dyn LinkRegistry,
1257 warnings: &mut Vec<crate::fkc::ImportWarning>,
1258) -> Result<Vec<Resolved>, FkcError> {
1259 let provider = &file.front_matter.provider;
1260 let defaults = Defaults {
1261 backend: provider.backend.as_str(),
1262 kernel_source: provider.kernel_source.as_str(),
1263 revision_base: provider.revision_base.as_deref().unwrap_or(""),
1264 };
1265 let mut out = Vec::new();
1269 for kernel in file.kernels.iter().filter(|k| k.registrable) {
1270 out.extend(lower_kernel(kernel, &defaults, link, warnings)?);
1272 }
1273 Ok(out)
1274}
1275
1276#[cfg(test)]
1277mod tests {
1278 use super::*;
1279 use crate::fkc::parse_file;
1280 use std::sync::{Arc, RwLock};
1281
1282 const ELEMENTWISE_BINARY: &str =
1283 include_str!("../../kernel-contracts/cpu/elementwise-binary.fkc.md");
1284 const QUANT_MATMUL: &str = include_str!("../../kernel-contracts/cpu/quant-matmul.fkc.md");
1285 const FUSED_NORM_SOFTMAX: &str =
1288 include_str!("../../kernel-contracts/fused/norm-softmax.fkc.md");
1289
1290 #[test]
1298 fn a_reserved_dtype_token_declines_distinctly_from_an_unknown_one() {
1299 let reserved = lower_dtype("F8E4M3FNUZ", "sec", "lhs").expect_err("must not lower");
1300 assert!(
1301 matches!(reserved, FkcError::ReservedScalarType { .. }),
1302 "a §6.1-reserved token must decline AS reserved, not as a bad token \
1303 — a contract author told 'bad dtype token' goes hunting for a typo \
1304 that does not exist; got {reserved:?}",
1305 );
1306
1307 let unknown = lower_dtype("NOT_A_DTYPE", "sec", "lhs").expect_err("must not lower");
1310 assert!(
1311 matches!(unknown, FkcError::BadScalarType { .. }),
1312 "an unknown token must stay BadScalarType; got {unknown:?}",
1313 );
1314 }
1315
1316 #[test]
1321 fn every_shared_reserved_token_declines_as_reserved_at_this_site() {
1322 for tok in fuel_ir::RESERVED_DTYPE_TOKENS {
1323 let upper = tok.to_ascii_uppercase();
1327 let err = lower_dtype(&upper, "sec", "lhs")
1328 .expect_err("a reserved token must never lower to a DType");
1329 assert!(
1330 matches!(err, FkcError::ReservedScalarType { .. }),
1331 "{upper} is in RESERVED_DTYPE_TOKENS but declined as {err:?} — this \
1332 site has drifted from the shared list",
1333 );
1334 }
1335 assert!(!fuel_ir::RESERVED_DTYPE_TOKENS.is_empty());
1337 }
1338
1339 #[test]
1346 fn a_reserved_token_is_not_accepted_as_the_token_it_extends() {
1347 assert!(
1348 !matches!(lower_dtype("F8E5M2FNUZ", "sec", "lhs"), Ok(DType::F8E5M2)),
1349 "F8E5M2FNUZ must not lower to its OCP prefix F8E5M2",
1350 );
1351 assert!(
1352 !matches!(lower_dtype("F8E4M3FNUZ", "sec", "lhs"), Ok(DType::F8E4M3)),
1353 "F8E4M3FNUZ must not lower to its OCP prefix F8E4M3",
1354 );
1355 assert_eq!(lower_dtype("F8E5M2", "sec", "lhs").unwrap(), DType::F8E5M2);
1359 assert_eq!(lower_dtype("F8E4M3", "sec", "lhs").unwrap(), DType::F8E4M3);
1360 assert!(
1361 fuel_ir::RESERVED_DTYPE_TOKENS
1362 .iter()
1363 .any(|t| t.eq_ignore_ascii_case("F8E5M2FNUZ")),
1364 );
1365 }
1366
1367 fn dummy_kernel(
1370 _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
1371 _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
1372 _layouts: &[fuel_ir::Layout],
1373 _params: &crate::kernel::OpParams,
1374 ) -> fuel_ir::Result<()> {
1375 Ok(())
1376 }
1377
1378 struct StubLink;
1379 impl LinkRegistry for StubLink {
1380 fn resolve_primitive(&self, _symbol: &str) -> Option<KernelRef> {
1381 Some(dummy_kernel)
1382 }
1383 fn resolve_fused(&self, _symbol: &str) -> Option<KernelRef> {
1384 Some(dummy_kernel)
1385 }
1386 }
1387
1388 struct EmptyLink;
1390 impl LinkRegistry for EmptyLink {
1391 fn resolve_primitive(&self, _symbol: &str) -> Option<KernelRef> {
1392 None
1393 }
1394 fn resolve_fused(&self, _symbol: &str) -> Option<KernelRef> {
1395 None
1396 }
1397 }
1398
1399 fn lower_all(src: &str, kernel_name: &str) -> Result<Vec<Resolved>, FkcError> {
1402 let file = parse_file(src).expect("parses");
1403 let provider = &file.front_matter.provider;
1404 let defaults = Defaults {
1405 backend: provider.backend.as_str(),
1406 kernel_source: provider.kernel_source.as_str(),
1407 revision_base: provider.revision_base.as_deref().unwrap_or(""),
1408 };
1409 let kernel = file
1410 .kernels
1411 .iter()
1412 .find(|k| k.kernel == kernel_name)
1413 .unwrap_or_else(|| panic!("kernel {kernel_name} present"));
1414 lower_kernel(kernel, &defaults, &StubLink, &mut Vec::new())
1415 }
1416
1417 fn lower_one(src: &str, kernel_name: &str) -> Result<Resolved, FkcError> {
1420 Ok(lower_all(src, kernel_name)?
1421 .into_iter()
1422 .next()
1423 .expect("a section lowers to ≥1 variant"))
1424 }
1425
1426 #[test]
1431 fn lowers_real_add_f32() {
1432 let r = lower_one(ELEMENTWISE_BINARY, "add_f32").expect("add_f32 lowers");
1433 let Resolved::Primitive(p) = r else {
1434 panic!("add_f32 is a primitive");
1435 };
1436 assert_eq!(p.op, OpKind::AddElementwise);
1437 assert_eq!(p.dtypes.as_slice(), &[DType::F32, DType::F32, DType::F32]);
1439 assert_eq!(p.backend, BackendId::Cpu);
1440 assert!(!p.caps.strided_input);
1442 assert!(p.precision.bit_stable_on_same_hardware);
1444 assert_eq!(p.precision.max_ulp, Some(0));
1445 assert_eq!(
1447 p.kernel as *const () as usize,
1448 dummy_kernel as *const () as usize
1449 );
1450 assert!(matches!(
1453 p.cost,
1454 CompiledCostExpr::Declared {
1455 flops: Some(_),
1456 bytes_moved: Some(_),
1457 ..
1458 }
1459 ));
1460 assert_eq!(p.kernel_source, "portable-cpu");
1461 }
1462
1463 #[test]
1464 fn lowers_binary_chassis_section_fans_out_over_all_dtypes() {
1465 let all = lower_all(ELEMENTWISE_BINARY, "binary").expect("binary lowers");
1470 assert_eq!(all.len(), 4, "4 dtypes ⇒ 4 fanned variants");
1471 let keys: Vec<Vec<DType>> = all
1472 .iter()
1473 .map(|r| {
1474 let Resolved::Primitive(p) = r else {
1475 panic!("binary is a primitive")
1476 };
1477 assert_eq!(p.op, OpKind::AddElementwise);
1478 p.dtypes.to_vec()
1479 })
1480 .collect();
1481 assert_eq!(
1482 keys,
1483 vec![
1484 vec![DType::F32, DType::F32, DType::F32],
1485 vec![DType::F64, DType::F64, DType::F64],
1486 vec![DType::BF16, DType::BF16, DType::BF16],
1487 vec![DType::F16, DType::F16, DType::F16],
1488 ],
1489 "each variant keys on [lhs, rhs, out(passthrough lhs)] at that dtype"
1490 );
1491 }
1492
1493 #[test]
1494 fn lowers_real_qmatmul_q4_0() {
1495 let r = lower_one(QUANT_MATMUL, "qmatmul_q4_0_f32").expect("q4_0 lowers");
1496 let Resolved::Primitive(p) = r else {
1497 panic!("QMatMul is a primitive")
1498 };
1499 assert_eq!(p.op, OpKind::QMatMul);
1500 assert_eq!(p.dtypes.as_slice(), &[DType::F32, DType::U8, DType::F32]);
1502 assert_eq!(p.backend, BackendId::Cpu);
1503 assert_eq!(p.cost, CompiledCostExpr::Unknown);
1505 assert!(p.precision.bit_stable_on_same_hardware);
1506 }
1507
1508 #[test]
1509 fn lowers_real_nf4_matmul_f32() {
1510 let r = lower_one(QUANT_MATMUL, "nf4_matmul_f32").expect("nf4 lowers");
1514 let Resolved::Primitive(p) = r else { panic!() };
1515 assert_eq!(p.op, OpKind::Nf4Matmul);
1516 assert_eq!(
1518 p.dtypes.as_slice(),
1519 &[DType::F32, DType::U8, DType::F32, DType::F32]
1520 );
1521 }
1522
1523 #[test]
1524 fn lower_file_lowers_every_kernel() {
1525 let file = parse_file(ELEMENTWISE_BINARY).expect("parses");
1526 let resolved = lower_file(&file, &StubLink, &mut Vec::new()).expect("all lower");
1527 let registrable = file.kernels.iter().filter(|k| k.registrable).count();
1530 assert_eq!(resolved.len(), registrable);
1531 }
1532
1533 #[test]
1534 fn cost_trampoline_evaluates_matmul_declared_flops() {
1535 const MATMUL: &str = include_str!("../../kernel-contracts/cpu/matmul.fkc.md");
1541 let file = parse_file(MATMUL).expect("matmul contract parses");
1542 let resolved =
1543 lower_file(&file, &StubLink, &mut Vec::new()).expect("matmul contract lowers");
1544 let prim = resolved
1545 .iter()
1546 .find_map(|r| match r {
1547 Resolved::Primitive(p) if p.op == OpKind::MatMul => Some(p),
1548 _ => None,
1549 })
1550 .expect("a MatMul primitive in the matmul contract");
1551 let params = crate::kernel::OpParams::Matmul {
1552 lhs_batch_dims: vec![2],
1553 rhs_batch_dims: vec![2],
1554 m: 3,
1555 n: 4,
1556 k: 5,
1557 m_compute: crate::kernel::MatmulM::All,
1558 };
1559 let est = crate::fkc::cost_estimate(
1560 &prim.cost,
1561 OpKind::MatMul,
1562 &[],
1563 &[DType::F32, DType::F32, DType::F32],
1564 ¶ms,
1565 )
1566 .expect("declared matmul cost evaluates");
1567 assert_eq!(est.flops, 240, "2 * batch(2) * m(3) * n(4) * k(5) = 240");
1568 }
1569
1570 #[test]
1574 fn lowers_real_fused_softmax_last_dim() {
1575 let r = lower_one(FUSED_NORM_SOFTMAX, "softmax_last_dim")
1576 .expect("softmax_last_dim (fused) lowers");
1577 let Resolved::Fused(f) = r else {
1578 panic!("softmax_last_dim is a fused op");
1579 };
1580 assert_eq!(f.id, FusedOps::SOFTMAX_LAST_DIM);
1581 assert_eq!(f.backend, BackendId::Cpu);
1582 assert_eq!(f.kernel_source, "portable-cpu");
1583
1584 let file = parse_file(FUSED_NORM_SOFTMAX).expect("parses");
1590 let resolved =
1591 lower_file(&file, &StubLink, &mut Vec::new()).expect("all fused kernels lower");
1592 assert_eq!(
1593 resolved.len(),
1594 file.kernels.len() * 4,
1595 "each fused section fans over its 4 dtypes (8 sections × 4 = 32)",
1596 );
1597 assert!(resolved.iter().all(|r| matches!(r, Resolved::Fused(_))));
1598 }
1599
1600 const FUSED_FANOUT_SYNTH: &str = r#"---
1613fkc_version: 1
1614provider:
1615 name: test-provider
1616 backend: Cpu
1617 kernel_source: "test-cpu"
1618---
1619
1620# fused dtype-fan synthetic
1621
1622## fanned_softmax
1623
1624A blurb.
1625
1626```fkc
1627kernel: fanned_softmax
1628fused_op: SOFTMAX_LAST_DIM
1629blurb: "synthetic multi-dtype fused softmax"
1630entry_point: "x::softmax_cpu"
1631accept:
1632 inputs:
1633 - name: x
1634 dtypes: [F32, F64, BF16, F16]
1635return:
1636 outputs:
1637 - name: out
1638 dtype_rule: passthrough(x)
1639```
1640
1641## single_norm
1642
1643A blurb.
1644
1645```fkc
1646kernel: single_norm
1647fused_op: RMS_NORM_LAST_DIM
1648blurb: "synthetic single-dtype fused rms-norm"
1649entry_point: "x::rms_norm_f32_cpu"
1650accept:
1651 inputs:
1652 - name: x
1653 dtypes: [F32]
1654return:
1655 outputs:
1656 - name: out
1657 dtype_rule: passthrough(x)
1658```
1659"#;
1660
1661 #[test]
1662 fn fused_multi_dtype_section_fans_into_per_dtype_resolved_fused() {
1663 let all = lower_all(FUSED_FANOUT_SYNTH, "fanned_softmax").expect("fanned_softmax lowers");
1668 assert_eq!(
1669 all.len(),
1670 4,
1671 "4 dtypes ⇒ 4 fanned ResolvedFused (pre-change: 1 representative only)",
1672 );
1673 let keys: Vec<Vec<DType>> = all
1674 .iter()
1675 .map(|r| {
1676 let Resolved::Fused(f) = r else {
1677 panic!("fanned_softmax is a fused op")
1678 };
1679 assert_eq!(f.id, FusedOps::SOFTMAX_LAST_DIM);
1680 assert_eq!(f.backend, BackendId::Cpu);
1681 f.dtypes.to_vec()
1682 })
1683 .collect();
1684 assert_eq!(
1685 keys,
1686 vec![
1687 vec![DType::F32, DType::F32],
1688 vec![DType::F64, DType::F64],
1689 vec![DType::BF16, DType::BF16],
1690 vec![DType::F16, DType::F16],
1691 ],
1692 "each variant keys on [x, out(passthrough x)] at that dtype",
1693 );
1694 }
1695
1696 #[test]
1697 fn fused_single_dtype_section_yields_exactly_one_resolved_fused() {
1698 let all = lower_all(FUSED_FANOUT_SYNTH, "single_norm").expect("single_norm lowers");
1702 assert_eq!(
1703 all.len(),
1704 1,
1705 "single-dtype fused section ⇒ exactly one ResolvedFused"
1706 );
1707 let Resolved::Fused(f) = &all[0] else {
1708 panic!("single_norm is a fused op");
1709 };
1710 assert_eq!(f.id, FusedOps::RMS_NORM_LAST_DIM);
1711 assert_eq!(f.dtypes.as_slice(), &[DType::F32, DType::F32]);
1712 }
1713
1714 const PASSTHROUGH_OPTIONAL_SYNTH: &str = r#"---
1733fkc_version: 1
1734provider:
1735 name: test-provider
1736 backend: Cpu
1737 kernel_source: "test-cpu"
1738---
1739
1740# passthrough-names-optional synthetic
1741
1742## bad_passthrough
1743
1744A blurb.
1745
1746```fkc
1747kernel: bad_passthrough
1748op_kind: AddElementwise
1749blurb: "output passthrough names the optional last operand"
1750entry_point: "x::add_cpu"
1751accept:
1752 inputs:
1753 - name: x
1754 dtypes: [F32]
1755 - name: bias
1756 dtypes: [F32]
1757 optional: true
1758return:
1759 outputs:
1760 - name: out
1761 dtype_rule: passthrough(bias)
1762```
1763"#;
1764
1765 #[test]
1779 fn passthrough_naming_the_optional_last_operand_is_rejected() {
1780 let err = lower_all(PASSTHROUGH_OPTIONAL_SYNTH, "bad_passthrough")
1781 .expect_err("passthrough(bias) names the optional last operand");
1782 match err {
1783 FkcError::PassthroughNamesOptionalOperand { ref role, .. } => {
1784 assert_eq!(role, "bias", "the rejected role is the optional operand");
1785 }
1786 other => panic!("expected PassthroughNamesOptionalOperand, got {other:?}"),
1787 }
1788
1789 let ok = PASSTHROUGH_OPTIONAL_SYNTH.replace("passthrough(bias)", "passthrough(x)");
1793 lower_all(&ok, "bad_passthrough")
1794 .expect("passthrough(x) names a REQUIRED operand and must lower cleanly");
1795 }
1796
1797 const BUNDLE_SYNTH: &str = r#"---
1798fkc_version: 1
1799provider:
1800 name: test-provider
1801 backend: Cpu
1802 kernel_source: "test-cpu"
1803---
1804
1805# bundle key-derivation synthetic
1806
1807## bundle_op
1808
1809A blurb.
1810
1811```fkc
1812kernel: bundle_op
1813op_kind: SelectiveScan
1814blurb: "synthetic multi-output bundle op"
1815entry_point: "x::bundle_op"
1816accept:
1817 inputs:
1818 - name: a
1819 dtypes: [F32]
1820 - name: b
1821 dtypes: [F32]
1822return:
1823 bundle:
1824 - { name: y, dtype_rule: passthrough(a), shape_rule: same_as(a), layout_guarantee: contiguous }
1825 - { name: st, dtype_rule: passthrough(a), shape_rule: same_as(a), layout_guarantee: contiguous }
1826```
1827
1828## plain_op
1829
1830A blurb.
1831
1832```fkc
1833kernel: plain_op
1834op_kind: AddElementwise
1835blurb: "synthetic no-bundle op"
1836entry_point: "x::plain_op"
1837accept:
1838 inputs:
1839 - name: a
1840 dtypes: [F32]
1841 - name: b
1842 dtypes: [F32]
1843return:
1844 outputs:
1845 - name: out
1846 dtype_rule: passthrough(a)
1847```
1848"#;
1849
1850 #[test]
1851 fn return_bundle_appends_primary_output_slot_to_key() {
1852 let r = lower_one(BUNDLE_SYNTH, "bundle_op").expect("bundle_op lowers");
1858 let Resolved::Primitive(p) = r else {
1859 panic!("bundle_op is a primitive");
1860 };
1861 assert_eq!(
1862 p.dtypes.as_slice(),
1863 &[DType::F32, DType::F32, DType::F32],
1864 "a `return.bundle` must append its primary output slot to the key \
1865 (2 inputs + 1 bundle out = 3); the importer previously built the \
1866 2-slot short key `[F32, F32]` from `return.outputs` only",
1867 );
1868 }
1869
1870 #[test]
1871 fn no_bundle_section_key_is_unchanged() {
1872 let r = lower_one(BUNDLE_SYNTH, "plain_op").expect("plain_op lowers");
1876 let Resolved::Primitive(p) = r else {
1877 panic!("plain_op is a primitive");
1878 };
1879 assert_eq!(
1880 p.dtypes.as_slice(),
1881 &[DType::F32, DType::F32, DType::F32],
1882 "a no-bundle section keys on inputs + regular outputs only",
1883 );
1884 }
1885
1886 const VARIANT_SYNTH: &str = r#"---
1897fkc_version: 1
1898provider:
1899 name: test-provider
1900 backend: Cpu
1901 kernel_source: "test-cpu"
1902---
1903
1904# variant retention synthetic
1905
1906## tagged_op
1907
1908A blurb.
1909
1910```fkc
1911kernel: tagged_op
1912op_kind: MatMul
1913blurb: "synthetic split-K partial variant"
1914entry_point: "x::tagged_op"
1915variant: "splitk_partial"
1916accept:
1917 inputs:
1918 - name: lhs
1919 dtypes: [F32]
1920 - name: rhs
1921 dtypes: [F32]
1922return:
1923 outputs:
1924 - name: out
1925 dtype_rule: fixed(F32)
1926```
1927
1928## untagged_op
1929
1930A blurb.
1931
1932```fkc
1933kernel: untagged_op
1934op_kind: MatMul
1935blurb: "synthetic no-variant op"
1936entry_point: "x::untagged_op"
1937accept:
1938 inputs:
1939 - name: lhs
1940 dtypes: [F32]
1941 - name: rhs
1942 dtypes: [F32]
1943return:
1944 outputs:
1945 - name: out
1946 dtype_rule: fixed(F32)
1947```
1948"#;
1949
1950 #[test]
1951 fn variant_tag_is_retained_on_resolved_primitive() {
1952 let r = lower_one(VARIANT_SYNTH, "tagged_op").expect("tagged_op lowers");
1957 let Resolved::Primitive(p) = r else {
1958 panic!("tagged_op is a primitive");
1959 };
1960 assert_eq!(
1961 p.variant.as_deref(),
1962 Some("splitk_partial"),
1963 "the opaque `variant:` tag must survive lowering onto \
1964 ResolvedPrimitive.variant (it was dropped)",
1965 );
1966 }
1967
1968 #[test]
1969 fn no_variant_section_retains_none() {
1970 let r = lower_one(VARIANT_SYNTH, "untagged_op").expect("untagged_op lowers");
1973 let Resolved::Primitive(p) = r else {
1974 panic!("untagged_op is a primitive");
1975 };
1976 assert_eq!(p.variant, None, "a section without `variant:` retains None");
1977 }
1978
1979 #[test]
1984 fn bogus_op_kind_is_unknown_op_kind() {
1985 let err = lower_op_kind("NotARealOp", "k").expect_err("bogus op");
1986 assert!(matches!(err, FkcError::UnknownOpKind { .. }), "got {err:?}");
1987 }
1988
1989 #[test]
1990 fn bogus_dtype_is_bad_scalar_type() {
1991 let err = lower_dtype("F99", "k", "lhs").expect_err("bogus dtype");
1992 assert!(matches!(err, FkcError::BadScalarType { .. }), "got {err:?}");
1993 }
1994
1995 #[test]
2002 fn dtype_suffix_is_the_inverse_of_lower_dtype() {
2003 for dt in [
2004 DType::U8,
2005 DType::I8,
2006 DType::U32,
2007 DType::I16,
2008 DType::I32,
2009 DType::I64,
2010 DType::BF16,
2011 DType::F16,
2012 DType::F32,
2013 DType::F64,
2014 DType::F8E4M3,
2015 DType::F6E2M3,
2016 DType::F6E3M2,
2017 DType::F4,
2018 DType::F8E8M0,
2019 DType::F8E6M2,
2020 ] {
2021 let suffix = super::dtype_suffix(dt);
2022 let token = suffix.to_uppercase();
2023 assert_eq!(
2024 super::lower_dtype(&token, "k", "op").expect("round-trips"),
2025 dt,
2026 "suffix {suffix:?} (token {token:?}) must lower back to {dt:?}",
2027 );
2028 }
2029 }
2030
2031 #[test]
2032 fn bogus_fused_op_is_unknown_fused_op() {
2033 let err = lower_fused_op("NotAFusedOp", "k").expect_err("bogus fused");
2034 assert!(
2035 matches!(err, FkcError::UnknownFusedOp { .. }),
2036 "got {err:?}"
2037 );
2038 }
2039
2040 #[test]
2041 fn screaming_snake_const_name_resolves_not_pascalcase() {
2042 assert_eq!(
2044 lower_fused_op("SOFTMAX_LAST_DIM", "k").unwrap(),
2045 FusedOps::SOFTMAX_LAST_DIM
2046 );
2047 assert_eq!(
2048 lower_fused_op("FLASH_ATTN", "k").unwrap(),
2049 FusedOps::FLASH_ATTN
2050 );
2051 assert_eq!(lower_fused_op("QMATMUL", "k").unwrap(), FusedOps::QMATMUL);
2052 assert!(lower_fused_op("SoftmaxLastDim", "k").is_err());
2055 assert!(lower_fused_op("FlashAttn", "k").is_err());
2056 }
2057
2058 #[test]
2063 fn every_registry_id_is_reachable_through_table() {
2064 use std::collections::HashSet;
2065 let reachable: HashSet<FusedOpId> = [
2067 "SOFTMAX_LAST_DIM",
2068 "FUSED_LINEAR",
2069 "RMS_NORM_LAST_DIM",
2070 "LAYER_NORM_LAST_DIM",
2071 "ROPE",
2072 "CONV2D",
2073 "SOFTMAX_LAST_DIM_BACKWARD",
2074 "LAYER_NORM_LAST_DIM_BACKWARD",
2075 "RMS_NORM_LAST_DIM_BACKWARD",
2076 "REDUCE_MAX_TO_BACKWARD",
2077 "CONV_TRANSPOSE2D",
2078 "FLASH_ATTN",
2079 "PAGED_ATTN",
2080 "QMATMUL",
2081 "POWI_BACKWARD",
2082 "INPLACE_AFFINE",
2083 "FUSED_SOFTMAX_CROSS_ENTROPY",
2084 "CAUSAL_CONV1D",
2085 "SELECTIVE_SCAN",
2086 "SSD_CHUNK_SCAN",
2087 "NF4_MATMUL",
2088 "FLASH_ATTN_BACKWARD_Q",
2089 "FLASH_ATTN_BACKWARD_K",
2090 "FLASH_ATTN_BACKWARD_V",
2091 "AWQ_MATMUL",
2092 "ROW_SCALED_MATMUL",
2093 "TOP_K_LAST_DIM",
2094 "MATMUL_TOP_K",
2095 ]
2096 .iter()
2097 .map(|n| super::fused_op_id_for_const_name(n).expect("table arm exists"))
2098 .collect();
2099
2100 for entry in fuel_graph::registry::default_registry().entries_iter() {
2102 assert!(
2103 reachable.contains(&entry.id),
2104 "FusedOpId {:?} (registry name {:?}) is registered but NOT reachable through the \
2105 SCREAMING_SNAKE constant-name table — add a `fused_op_id_for_const_name` arm",
2106 entry.id,
2107 entry.name,
2108 );
2109 }
2110 }
2111
2112 #[test]
2113 fn bogus_backend_is_unknown_backend() {
2114 let err = lower_backend("Tpu", "k").expect_err("bogus backend");
2115 assert!(
2116 matches!(err, FkcError::UnknownBackend { .. }),
2117 "got {err:?}"
2118 );
2119 }
2120
2121 #[test]
2122 fn unknown_entry_point_errors() {
2123 let file = parse_file(ELEMENTWISE_BINARY).expect("parses");
2124 let provider = &file.front_matter.provider;
2125 let defaults = Defaults {
2126 backend: provider.backend.as_str(),
2127 kernel_source: provider.kernel_source.as_str(),
2128 revision_base: provider.revision_base.as_deref().unwrap_or(""),
2129 };
2130 let kernel = file.kernels.iter().find(|k| k.kernel == "add_f32").unwrap();
2131 let err = lower_kernel(kernel, &defaults, &EmptyLink, &mut Vec::new())
2132 .expect_err("no entry point");
2133 assert!(
2134 matches!(err, FkcError::UnknownEntryPoint { .. }),
2135 "got {err:?}"
2136 );
2137 }
2138
2139 #[test]
2140 fn malformed_cost_expr_is_cost_expr_parse() {
2141 let mut block = CostBlock {
2142 provenance: Some("declared".into()),
2143 class: None,
2144 cost_fn: None,
2145 flops: Some("2 * * n".into()), bytes_moved: None,
2147 overhead_ns: None,
2148 memory: None,
2149 };
2150 let err = compile_cost(Some(&block), "k").expect_err("malformed flops");
2151 assert!(matches!(err, FkcError::CostExprParse { .. }), "got {err:?}");
2152
2153 block.flops = Some("n".into());
2155 block.bytes_moved = Some("3 * n *".into());
2156 let err = compile_cost(Some(&block), "k").expect_err("malformed bytes_moved");
2157 assert!(matches!(err, FkcError::CostExprParse { field, .. } if field == "bytes_moved"));
2158 }
2159
2160 fn gap376_estimate(flops: Option<&str>, bytes: Option<&str>) -> crate::fused::CostEstimate {
2162 let block = CostBlock {
2163 provenance: Some("declared".into()),
2164 class: None,
2165 cost_fn: None,
2166 flops: flops.map(Into::into),
2167 bytes_moved: bytes.map(Into::into),
2168 overhead_ns: None,
2169 memory: None,
2170 };
2171 let expr = compile_cost(Some(&block), "k").expect("cost block compiles");
2172 let params = crate::kernel::OpParams::Matmul {
2173 lhs_batch_dims: vec![2],
2174 rhs_batch_dims: vec![2],
2175 m: 3,
2176 n: 4,
2177 k: 5,
2178 m_compute: crate::kernel::MatmulM::All,
2179 };
2180 crate::fkc::cost_estimate(
2181 &expr,
2182 OpKind::MatMul,
2183 &[],
2184 &[DType::F32, DType::F32, DType::F32],
2185 ¶ms,
2186 )
2187 .expect("declared cost evaluates")
2188 }
2189
2190 #[test]
2191 fn declared_bytes_moved_reaches_the_cost_estimate() {
2192 let est = gap376_estimate(Some("2 * n"), Some("3 * n * dtype_bytes"));
2194 assert_eq!(est.flops, 8, "flops expression still evaluates");
2195 assert_eq!(
2196 est.bytes_moved, 48,
2197 "GAP-376: declared bytes_moved was dropped"
2198 );
2199 }
2200
2201 #[test]
2202 fn bytes_only_block_does_not_read_bytes_as_flops() {
2203 let est = gap376_estimate(None, Some("3 * n * dtype_bytes"));
2205 assert_eq!(est.flops, 0, "GAP-376: a bytes formula was read as flops");
2206 assert_eq!(est.bytes_moved, 48);
2207 }
2208
2209 #[test]
2210 fn flops_only_block_keeps_zero_bytes_moved() {
2211 let est = gap376_estimate(Some("2 * n"), None);
2214 assert_eq!(est.flops, 8);
2215 assert_eq!(est.bytes_moved, 0);
2216 }
2217
2218 fn gap382_estimate(
2220 flops: Option<&str>,
2221 bytes: Option<&str>,
2222 overhead: Option<serde_yaml_ng::Value>,
2223 ) -> crate::fused::CostEstimate {
2224 let block = CostBlock {
2225 provenance: Some("declared".into()),
2226 class: None,
2227 cost_fn: None,
2228 flops: flops.map(Into::into),
2229 bytes_moved: bytes.map(Into::into),
2230 overhead_ns: overhead,
2231 memory: None,
2232 };
2233 let expr = compile_cost(Some(&block), "k").expect("cost block compiles");
2234 let params = crate::kernel::OpParams::Matmul {
2235 lhs_batch_dims: vec![2],
2236 rhs_batch_dims: vec![2],
2237 m: 3,
2238 n: 4,
2239 k: 5,
2240 m_compute: crate::kernel::MatmulM::All,
2241 };
2242 crate::fkc::cost_estimate(
2243 &expr,
2244 OpKind::MatMul,
2245 &[],
2246 &[DType::F32, DType::F32, DType::F32],
2247 ¶ms,
2248 )
2249 .expect("declared cost evaluates")
2250 }
2251
2252 fn num(v: u64) -> Option<serde_yaml_ng::Value> {
2253 Some(serde_yaml_ng::Value::Number(v.into()))
2254 }
2255
2256 #[test]
2257 fn declared_overhead_ns_number_reaches_the_cost_estimate() {
2258 let est = gap382_estimate(Some("2 * n"), None, num(40));
2260 assert_eq!(est.flops, 8, "flops expression still evaluates");
2261 assert_eq!(
2262 est.kernel_overhead_ns, 40,
2263 "GAP-382: a declared overhead_ns was dropped"
2264 );
2265 }
2266
2267 #[test]
2268 fn overhead_only_block_reaches_the_cost_estimate() {
2269 let est = gap382_estimate(None, None, num(40));
2271 assert_eq!(
2272 est.kernel_overhead_ns, 40,
2273 "GAP-382: overhead-only block dropped"
2274 );
2275 assert_eq!(est.flops, 0);
2276 assert_eq!(est.bytes_moved, 0);
2277 }
2278
2279 #[test]
2280 fn overhead_ns_expression_string_is_evaluated() {
2281 let est = gap382_estimate(
2283 Some("n"),
2284 Some("3 * n"),
2285 Some(serde_yaml_ng::Value::String("n * 10".into())),
2286 );
2287 assert_eq!(
2288 est.kernel_overhead_ns, 40,
2289 "GAP-382: string overhead_ns dropped"
2290 );
2291 assert_eq!(est.flops, 4);
2292 assert_eq!(est.bytes_moved, 12, "GAP-376 bytes_moved is unaffected");
2293 }
2294
2295 #[test]
2296 fn absent_or_null_overhead_ns_stays_zero() {
2297 let none = gap382_estimate(Some("2 * n"), Some("3 * n"), None);
2300 assert_eq!(none.kernel_overhead_ns, 0);
2301 let null = gap382_estimate(
2302 Some("2 * n"),
2303 Some("3 * n"),
2304 Some(serde_yaml_ng::Value::Null),
2305 );
2306 assert_eq!(null.kernel_overhead_ns, 0, "`~` means no declared overhead");
2307 }
2308
2309 #[test]
2310 fn a_real_contract_overhead_ns_reaches_the_cost_estimate() {
2311 const COMPARE_WHERE: &str = include_str!("../../kernel-contracts/cpu/compare-where.fkc.md");
2314 let file = parse_file(COMPARE_WHERE).expect("compare-where parses");
2315 let declared: Vec<u64> = file
2316 .kernels
2317 .iter()
2318 .filter_map(|k| k.cost.as_ref())
2319 .filter_map(|c| c.overhead_ns.as_ref())
2320 .filter_map(|v| v.as_u64())
2321 .collect();
2322 assert!(
2323 declared.contains(&40),
2324 "PRECONDITION: the contract declares overhead_ns: 40, got {declared:?}"
2325 );
2326 let resolved = lower_file(&file, &StubLink, &mut Vec::new()).expect("lowers");
2327 let prim = resolved
2328 .iter()
2329 .find_map(|r| match r {
2330 Resolved::Primitive(p) if p.op == OpKind::EqualElementwise => Some(p),
2331 _ => None,
2332 })
2333 .expect("an EqualElementwise primitive");
2334 let est = crate::fkc::cost_estimate(
2335 &prim.cost,
2336 prim.op,
2337 &[fuel_ir::Shape::from_dims(&[8])],
2338 &[DType::F32, DType::F32, DType::U8],
2339 &crate::kernel::OpParams::None,
2340 )
2341 .expect("declared compare cost evaluates");
2342 assert_eq!(est.flops, 8, "flops: \"n\" at n = 8");
2343 assert_eq!(
2344 est.kernel_overhead_ns, 40,
2345 "GAP-382: the corpus contract's declared overhead_ns never reached the estimate"
2346 );
2347 }
2348
2349 #[test]
2355 fn corpus_declared_overhead_ns_reaches_every_estimate() {
2356 fn walk(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
2357 let Ok(rd) = std::fs::read_dir(dir) else {
2358 return;
2359 };
2360 for e in rd.flatten() {
2361 let path = e.path();
2362 if path.is_dir() {
2363 walk(&path, out);
2364 } else if path.to_string_lossy().ends_with(".fkc.md") {
2365 out.push(path);
2366 }
2367 }
2368 }
2369 let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
2370 let mut files = Vec::new();
2371 for tree in [
2372 "kernel-contracts",
2373 "../fuel-cuda-dispatch/kernel-contracts",
2374 "../fuel-vulkan-dispatch/kernel-contracts",
2375 ] {
2376 walk(&base.join(tree), &mut files);
2377 }
2378 files.sort();
2379 assert!(
2380 files.len() > 50,
2381 "CONTROL: the walk must find the corpus, found {}",
2382 files.len()
2383 );
2384
2385 let mut sections = 0usize;
2386 let mut with_number = 0usize;
2387 let mut with_expression = 0usize;
2388 let mut full_ok = 0usize;
2389 let mut full_err = 0usize;
2390 let mut unparsed_files = 0usize;
2391 let mut mismatches: Vec<String> = Vec::new();
2392 let mut by_tree: std::collections::BTreeMap<String, usize> = Default::default();
2393 for f in &files {
2394 let Ok(src) = std::fs::read_to_string(f) else {
2395 continue;
2396 };
2397 let Ok(file) = parse_file(&src) else {
2398 unparsed_files += 1;
2399 continue;
2400 };
2401 for k in &file.kernels {
2402 sections += 1;
2403 let Some(cost) = k.cost.as_ref() else {
2404 continue;
2405 };
2406 let declared = match &cost.overhead_ns {
2407 Some(serde_yaml_ng::Value::Number(n)) => n.as_f64(),
2408 Some(serde_yaml_ng::Value::String(_)) => {
2409 with_expression += 1;
2410 continue;
2411 }
2412 _ => continue,
2413 };
2414 let Some(want) = declared else { continue };
2415 with_number += 1;
2416 let tree = f
2417 .strip_prefix(base)
2418 .ok()
2419 .and_then(|p| p.components().next())
2420 .map(|c| c.as_os_str().to_string_lossy().to_string())
2421 .unwrap_or_else(|| "../".to_string());
2422 *by_tree.entry(tree).or_default() += 1;
2423 let expr = match compile_cost(Some(cost), &k.kernel) {
2424 Ok(e) => e,
2425 Err(e) => {
2426 mismatches.push(format!("{}: {}: compile {e:?}", f.display(), k.kernel));
2427 continue;
2428 }
2429 };
2430 let direct = crate::fkc::cost_expr::eval_overhead_ns(&expr, &Default::default());
2435 if direct != Ok(want.max(0.0) as u32) {
2436 mismatches.push(format!(
2437 "{}: {}: declared {want} got {direct:?}",
2438 f.display(),
2439 k.kernel
2440 ));
2441 }
2442 match crate::fkc::cost_estimate(
2443 &expr,
2444 OpKind::AddElementwise,
2445 &[fuel_ir::Shape::from_dims(&[8])],
2446 &[DType::F32],
2447 &crate::kernel::OpParams::None,
2448 ) {
2449 Ok(est) => {
2450 full_ok += 1;
2451 if Ok(est.kernel_overhead_ns) != direct {
2452 mismatches.push(format!(
2453 "{}: {}: estimate {} != direct {direct:?}",
2454 f.display(),
2455 k.kernel,
2456 est.kernel_overhead_ns
2457 ));
2458 }
2459 }
2460 Err(_) => full_err += 1,
2461 }
2462 }
2463 }
2464 println!(
2465 "\nGAP-382 corpus: {} files ({} unparsed), {} sections; sections with a numeric overhead_ns \
2466 (candidate cost changes 0 -> declared): {}; with an expression-string overhead_ns: {}; of the numeric ones the whole estimate evaluates under the generic n = 8 context for {} and needs op-bound symbols (hand-written cost fn answers in production) for {}; by tree: {:?}",
2467 files.len(),
2468 unparsed_files,
2469 sections,
2470 with_number,
2471 with_expression,
2472 full_ok,
2473 full_err,
2474 by_tree
2475 );
2476 assert!(
2477 with_number > 100,
2478 "CONTROL: the corpus declares far more than 100 numeric overhead_ns sections, saw {with_number}"
2479 );
2480 assert!(
2481 mismatches.is_empty(),
2482 "declared overhead_ns not reaching the estimate: {mismatches:#?}"
2483 );
2484 }
2485
2486 #[test]
2502 fn contract_claims_without_a_ledger_pass_by_dtype_signature() {
2503 use std::collections::BTreeMap;
2504 fn walk(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
2505 let Ok(rd) = std::fs::read_dir(dir) else {
2506 return;
2507 };
2508 for e in rd.flatten() {
2509 let path = e.path();
2510 if path.is_dir() {
2511 walk(&path, out);
2512 } else if path.to_string_lossy().ends_with(".fkc.md") {
2513 out.push(path);
2514 }
2515 }
2516 }
2517 let base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
2518 let mut files = Vec::new();
2519 for tree in [
2520 "kernel-contracts",
2521 "../fuel-cuda-dispatch/kernel-contracts",
2522 "../fuel-vulkan-dispatch/kernel-contracts",
2523 ] {
2524 walk(&base.join(tree), &mut files);
2525 }
2526 files.sort();
2527 let ledger = crate::fkc::verify::embedded();
2528 let claims = |g: &crate::fused::PrecisionGuarantee| {
2529 g.bit_stable_on_same_hardware
2530 || g.max_ulp.is_some()
2531 || g.max_relative.is_some()
2532 || g.max_absolute.is_some()
2533 };
2534 let meets = |g: &crate::fused::PrecisionGuarantee| {
2535 g.bit_stable_on_same_hardware || g.max_relative.is_some() || g.max_absolute.is_some()
2536 };
2537 type PairKey = (String, String, String);
2540 type PairStats = (usize, usize, usize, usize);
2541 let mut pairs: BTreeMap<PairKey, PairStats> = BTreeMap::new();
2542 let mut lower_errors = 0usize;
2543 for f in &files {
2544 let Ok(src) = std::fs::read_to_string(f) else {
2545 continue;
2546 };
2547 let Ok(file) = parse_file(&src) else { continue };
2548 let mut warnings = Vec::new();
2549 let Ok(mut resolved) = lower_file(&file, &StubLink, &mut warnings) else {
2550 lower_errors += 1;
2551 continue;
2552 };
2553 for r in &mut resolved {
2554 let (op, backend, sig, declared, gated) = match r {
2555 Resolved::Primitive(p) => {
2556 let q = crate::fkc::verify::LedgerQuery {
2557 kernel_ref: p.kernel_source.as_str(),
2558 backend: p.backend,
2559 dtypes: p.dtypes.as_slice(),
2560 kernel_revision_hash: p.revision.0,
2561 };
2562 let declared = p.precision;
2563 let gated = crate::fkc::verify::gate_precision(
2564 p.precision,
2565 &q,
2566 ledger,
2567 &mut warnings,
2568 );
2569 (
2570 format!("{:?}", p.op),
2571 p.backend,
2572 format!("{:?}", p.dtypes.as_slice()),
2573 declared,
2574 gated,
2575 )
2576 }
2577 Resolved::Fused(fz) => {
2578 let q = crate::fkc::verify::LedgerQuery {
2579 kernel_ref: fz.kernel_source.as_str(),
2580 backend: fz.backend,
2581 dtypes: fz.dtypes.as_slice(),
2582 kernel_revision_hash: fz.revision.0,
2583 };
2584 let declared = fz.precision;
2585 let gated = crate::fkc::verify::gate_precision(
2586 fz.precision,
2587 &q,
2588 ledger,
2589 &mut warnings,
2590 );
2591 (
2592 format!("Fused({:?})", fz.id),
2593 fz.backend,
2594 format!("{:?}", fz.dtypes.as_slice()),
2595 declared,
2596 gated,
2597 )
2598 }
2599 };
2600 let e = pairs.entry((format!("{backend:?}"), op, sig)).or_default();
2601 e.0 += 1;
2602 if claims(&declared) {
2603 e.1 += 1;
2604 }
2605 if meets(&gated) {
2606 e.2 += 1;
2607 }
2608 if meets(&declared) {
2609 e.3 += 1;
2610 }
2611 }
2612 }
2613 let cpu_meets = |op: &String, sig: &String| {
2614 pairs
2615 .get(&("Cpu".to_string(), op.clone(), sig.clone()))
2616 .is_some_and(|v| v.2 > 0)
2617 };
2618 for backend in ["Cuda", "Vulkan"] {
2619 let mine: Vec<(&PairKey, &PairStats)> =
2620 pairs.iter().filter(|((b, _, _), _)| b == backend).collect();
2621 let n_pairs = mine.len();
2622 let records: usize = mine.iter().map(|(_, v)| v.0).sum();
2623 let declared_ok = mine.iter().filter(|(_, v)| v.3 > 0).count();
2624 let cost_placed = mine.iter().filter(|(_, v)| v.2 > 0).count();
2625 let lost_to_gate = mine.iter().filter(|(_, v)| v.3 > 0 && v.2 == 0).count();
2626 let host_pref: Vec<_> = mine
2627 .iter()
2628 .filter(|((_, op, sig), v)| v.2 == 0 && cpu_meets(op, sig))
2629 .collect();
2630 let no_cpu: usize = mine
2631 .iter()
2632 .filter(|((_, op, sig), v)| v.2 == 0 && !cpu_meets(op, sig))
2633 .count();
2634 println!(
2635 "\n=== {backend}: {n_pairs} (op, dtype signature) pairs from {records} contract records ===\n \
2636 {declared_ok} pairs DECLARE a meeting claim; {cost_placed} still meet the bound after the gate (placed by cost);\n \
2637 {lost_to_gate} pairs LOSE their declared claim at the V-FKC-9 gate (no ledger pass) and have no other meeting record;\n \
2638 {} pairs have no meeting record and a CPU record that meets the bound => PLACED ON THE HOST by AccuracyPreferenceFilter;\n \
2639 {no_cpu} pairs have no meeting record and no CPU contract record meeting the bound (filter skipped: the GPU kernel still runs)",
2640 host_pref.len()
2641 );
2642 let mut by_op: BTreeMap<String, usize> = BTreeMap::new();
2643 let mut by_sig: BTreeMap<String, usize> = BTreeMap::new();
2644 for ((_, op, sig), _) in &host_pref {
2645 *by_op.entry(op.clone()).or_default() += 1;
2646 *by_sig.entry(sig.clone()).or_default() += 1;
2647 }
2648 let mut v: Vec<_> = by_sig.into_iter().collect();
2649 v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
2650 println!(
2651 " host-preferred pairs BY DTYPE SIGNATURE ({} signatures):",
2652 v.len()
2653 );
2654 for (sig, n) in &v {
2655 println!(" {sig:<40} {n}");
2656 }
2657 let mut v: Vec<_> = by_op.into_iter().collect();
2658 v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
2659 println!(" host-preferred pairs BY OP ({} ops):", v.len());
2660 for (op, n) in &v {
2661 println!(" {op:<34} {n}");
2662 }
2663 let decode: Vec<_> = host_pref
2665 .iter()
2666 .filter(|((_, _, sig), _)| {
2667 !["F64", "F8", "I8", "I32", "I64", "U8"]
2668 .iter()
2669 .any(|d| sig.contains(d))
2670 })
2671 .collect();
2672 println!(
2673 " host-preferred pairs over F32/F16/BF16/U32/Bool only ({}):",
2674 decode.len()
2675 );
2676 for ((_, op, sig), _) in &decode {
2677 println!(" {op:<30} {sig}");
2678 }
2679 }
2680 println!(
2681 "\ncontract files scanned: {}, files that did not lower with the stub link: {lower_errors}",
2682 files.len()
2683 );
2684 let cuda_pairs = pairs.iter().filter(|((b, _, _), _)| b == "Cuda").count();
2685 let cuda_host: usize = pairs
2686 .iter()
2687 .filter(|((b, op, sig), v)| b == "Cuda" && v.2 == 0 && cpu_meets(op, sig))
2688 .count();
2689 let cuda_met: usize = pairs
2690 .iter()
2691 .filter(|((b, _, _), v)| b == "Cuda" && v.2 > 0)
2692 .count();
2693 assert!(files.len() > 50, "CONTROL: the walk must find the corpus");
2694 assert!(
2695 cuda_pairs > 100,
2696 "CONTROL: the instrument must see the CUDA pairs"
2697 );
2698 assert!(
2699 cuda_host > 0,
2700 "CONTROL: the recipe's Cast(U32->F32), MaskedFill and Ge are measured host-preferred pairs"
2701 );
2702 assert!(
2703 cuda_met > 0,
2704 "CONTROL: backed CUDA pairs exist (the ledger holds 284 CUDA bit_stable records)"
2705 );
2706 }
2707
2708 #[test]
2709 fn both_op_kind_and_fused_op_is_ambiguous() {
2710 let file = parse_file(ELEMENTWISE_BINARY).expect("parses");
2711 let mut kernel = file.kernels[0].clone();
2712 kernel.fused_op = Some("SoftmaxLastDim".into()); let defaults = Defaults {
2714 backend: "Cpu",
2715 kernel_source: "x",
2716 revision_base: "",
2717 };
2718 let err =
2719 lower_kernel(&kernel, &defaults, &StubLink, &mut Vec::new()).expect_err("ambiguous");
2720 assert!(
2721 matches!(err, FkcError::OpTargetAmbiguous { .. }),
2722 "got {err:?}"
2723 );
2724 }
2725}