1use crate::fkc::error::FkcError;
44use crate::fkc::lower;
45use crate::fkc::schema::{
46 AcceptBlock, CapsBlock, CostBlock, CostMemory, FdxSpec, FkcFile, FkcFrontMatter, FkcKernel,
47 FkcProvider, GatherSpec, LayoutSpec, OpParamFieldSpec, OpParamsSchema, OutputDesc,
48 PrecisionBlock, QuantSpec, ReturnBlock, TensorDesc,
49};
50use crate::kernel::OpParams;
53use fuel_graph::registry::FusedOpParams;
54
55pub const FKC_SUPPORTED_VERSIONS: &[u32] = &[1];
87
88pub(crate) fn fkc_version_is_supported(version: u32) -> bool {
93 FKC_SUPPORTED_VERSIONS.contains(&version)
94}
95
96fn _fkc_pin_front_matter(front_matter: FkcFrontMatter, provider: FkcProvider) {
126 let FkcFrontMatter {
127 fkc_version: _,
128 provider: _,
129 } = front_matter;
130 let FkcProvider {
131 name: _,
132 backend: _,
133 kernel_source: _,
134 link_registry: _,
135 revision_base: _,
136 } = provider;
137}
138
139fn _fkc_pin_kernel(kernel: FkcKernel) {
140 let FkcKernel {
141 kernel: _,
142 registrable: _,
143 op_kind: _,
144 fused_op: _,
145 blurb: _,
146 backend: _,
147 kernel_source: _,
148 entry_point: _,
149 kernel_revision_hash: _,
150 variant: _,
151 accept: _,
152 return_: _,
153 caps: _,
154 cost: _,
155 precision: _,
156 determinism: _,
157 } = kernel;
158}
159
160fn _fkc_pin_accept(
161 accept: AcceptBlock,
162 op_params: OpParamsSchema,
163 op_param_field: OpParamFieldSpec,
164) {
165 let AcceptBlock {
166 inputs: _,
167 op_params: _,
168 } = accept;
169 let OpParamsSchema {
170 variant: _,
171 fields: _,
172 } = op_params;
173 let OpParamFieldSpec {
174 kind: _,
175 constraint: _,
176 note: _,
177 } = op_param_field;
178}
179
180fn _fkc_pin_return(ret: ReturnBlock, output: OutputDesc) {
181 let ReturnBlock {
182 outputs: _,
183 bundle: _,
184 } = ret;
185 let OutputDesc {
186 name: _,
187 dtype_rule: _,
188 shape_rule: _,
189 layout_guarantee: _,
190 aliasing: _,
191 } = output;
192}
193
194fn _fkc_pin_tensor(
195 tensor: TensorDesc,
196 layout: LayoutSpec,
197 fdx: FdxSpec,
198 quant: QuantSpec,
199 gather: GatherSpec,
200) {
201 let TensorDesc {
202 name: _,
203 optional: _,
204 dtypes: _,
205 dtype_class: _,
206 layout: _,
207 rank: _,
208 shape_constraint: _,
209 fdx: _,
210 device: _,
211 substrate: _,
212 } = tensor;
213 let LayoutSpec {
214 contiguous: _,
215 strided: _,
216 broadcast_stride0: _,
217 broadcast_axes: _,
218 start_offset: _,
219 reverse_strides: _,
220 awkward_layout_strategy: _,
221 } = layout;
222 let FdxSpec {
223 requires_ext: _,
224 quant: _,
225 sub_byte: _,
226 symbolic_extent: _,
227 extent_kind: _,
228 gather: _,
229 } = fdx;
230 let QuantSpec {
231 family: _,
232 ggml_dtype: _,
233 granularity: _,
234 block_shape: _,
235 role: _,
236 scale_operand: _,
237 } = quant;
238 let GatherSpec {
239 kind: _,
240 block_table: _,
241 context_lens: _,
242 } = gather;
243}
244
245fn _fkc_pin_caps_cost_precision(
246 caps: CapsBlock,
247 cost: CostBlock,
248 cost_memory: CostMemory,
249 precision: PrecisionBlock,
250) {
251 let CapsBlock {
252 awkward_layout_strategy: _,
253 fast_paths: _,
254 in_place: _,
255 alignment_bytes: _,
256 access_granularity_bits: _,
257 } = caps;
258 let CostBlock {
259 provenance: _,
260 class: _,
261 cost_fn: _,
262 flops: _,
263 bytes_moved: _,
264 overhead_ns: _,
265 memory: _,
266 } = cost;
267 let CostMemory {
268 device_bytes: _,
269 host_bytes: _,
270 disk_bytes: _,
271 } = cost_memory;
272 let PrecisionBlock {
273 bit_stable_on_same_hardware: _,
274 max_ulp: _,
275 max_relative: _,
276 max_absolute: _,
277 audited: _,
278 notes: _,
279 } = precision;
280}
281
282fn is_fdx_quant_family(tok: &str) -> bool {
297 matches!(
298 tok,
299 "none" | "NONE" | "GGML_BLOCK" | "MX" | "AFFINE_INT" | "AFFINE_FLOAT" | "AFFINE_BLOCK"
300 )
301}
302
303fn is_fdx_granularity(tok: &str) -> bool {
306 matches!(tok, "PerTensor" | "PerToken" | "PerChannel" | "PerBlock")
307}
308
309fn ggml_dtype_code(tok: &str) -> Option<u32> {
314 let code = match tok {
315 "F32" => 0,
316 "F16" => 1,
317 "Q4_0" => 2,
318 "Q4_1" => 3,
319 "Q5_0" => 6,
320 "Q5_1" => 7,
321 "Q8_0" => 8,
322 "Q8_1" => 9,
323 "Q2K" => 10,
324 "Q3K" => 11,
325 "Q4K" => 12,
326 "Q5K" => 13,
327 "Q6K" => 14,
328 "Q8K" => 15,
329 "BF16" => 30,
330 _ => return None,
331 };
332 Some(code)
333}
334
335fn is_registrable_granularity(tok: &str) -> bool {
339 matches!(tok, "PerTensor" | "PerToken" | "PerChannel")
340}
341
342pub fn validate_file(file: &FkcFile) -> Result<(), FkcError> {
350 if !fkc_version_is_supported(file.front_matter.fkc_version) {
352 return Err(FkcError::UnsupportedVersion {
353 found: file.front_matter.fkc_version,
354 supported: FKC_SUPPORTED_VERSIONS,
355 });
356 }
357 for kernel in &file.kernels {
358 match validate_kernel(kernel) {
359 Ok(()) => {}
360 Err(FkcError::GatherNotYetSupported { .. } | FkcError::MxNotYetRegistrable { .. })
374 if !kernel.registrable => {}
375 Err(e) => return Err(e),
376 }
377 }
378 Ok(())
379}
380
381pub fn validate_kernel(kernel: &FkcKernel) -> Result<(), FkcError> {
385 let section = kernel.kernel.as_str();
386
387 let describe_only = !kernel.registrable;
391
392 required_fields(kernel, section, describe_only)?;
394
395 let is_fused = if describe_only {
399 false
402 } else {
403 match (kernel.op_kind.as_deref(), kernel.fused_op.as_deref()) {
404 (Some(op), None) => {
405 lower::lower_op_kind(op, section)?;
407 false
408 }
409 (None, Some(fused)) => {
410 lower::lower_fused_op(fused, section)?;
412 true
413 }
414 (op, fused) => {
415 return Err(FkcError::OpTargetAmbiguous {
416 section: section.to_string(),
417 op_kind: op.map(String::from),
418 fused_op: fused.map(String::from),
419 });
420 }
421 }
422 };
423
424 if let Some(accept) = &kernel.accept {
427 for d in &accept.inputs {
428 let operand = d.name.as_deref().unwrap_or("<input>").to_string();
429 validate_operand(section, &operand, d, accept)?;
430 }
431 if !describe_only
434 && let Some(op_params) = &accept.op_params
435 && let Some(variant) = op_params.variant.as_deref()
436 {
437 validate_op_params_namespace(section, variant, is_fused)?;
438 }
439 }
440
441 if let Some(ret) = &kernel.return_ {
444 for out in &ret.outputs {
445 if let Some(rule) = out.dtype_rule.as_deref() {
448 check_output_dtype_rule(section, out.name.as_deref().unwrap_or("<output>"), rule)?;
449 }
450 }
451 if let Some(bundle) = &ret.bundle {
453 check_bundle_ranks(section, bundle)?;
454 }
455 }
456
457 validate_cost(kernel, section)?;
459
460 validate_precision_coherence(kernel, section)?;
462
463 Ok(())
464}
465
466fn required_fields(kernel: &FkcKernel, section: &str, describe_only: bool) -> Result<(), FkcError> {
471 match kernel.blurb.as_deref() {
476 Some(b) if !b.trim().is_empty() => {}
477 _ => {
478 return Err(FkcError::MissingBlurb {
479 section: section.to_string(),
480 });
481 }
482 }
483
484 require(kernel.entry_point.as_deref(), section, "entry_point")?;
486
487 if !describe_only {
494 let has_inputs = kernel
495 .accept
496 .as_ref()
497 .map(|a| !a.inputs.is_empty())
498 .unwrap_or(false);
499 if !has_inputs {
500 return Err(FkcError::MissingRequiredField {
501 section: section.to_string(),
502 field: "accept.inputs (≥1)".to_string(),
503 });
504 }
505 }
506
507 let has_outputs = kernel
509 .return_
510 .as_ref()
511 .map(|r| !r.outputs.is_empty() || r.bundle.is_some())
512 .unwrap_or(false);
513 if !has_outputs {
514 return Err(FkcError::MissingRequiredField {
515 section: section.to_string(),
516 field: "return.outputs (≥1) or return.bundle".to_string(),
517 });
518 }
519
520 if kernel.cost.is_none() {
522 return Err(FkcError::MissingRequiredField {
523 section: section.to_string(),
524 field: "cost".to_string(),
525 });
526 }
527 if kernel.precision.is_none() {
529 return Err(FkcError::MissingRequiredField {
530 section: section.to_string(),
531 field: "precision".to_string(),
532 });
533 }
534 require(kernel.determinism.as_deref(), section, "determinism")?;
536
537 Ok(())
538}
539
540fn require(v: Option<&str>, section: &str, field: &str) -> Result<(), FkcError> {
541 match v {
542 Some(s) if !s.trim().is_empty() => Ok(()),
543 _ => Err(FkcError::MissingRequiredField {
544 section: section.to_string(),
545 field: field.to_string(),
546 }),
547 }
548}
549
550fn validate_operand(
555 section: &str,
556 operand: &str,
557 d: &TensorDesc,
558 accept: &crate::fkc::schema::AcceptBlock,
559) -> Result<(), FkcError> {
560 for tok in &d.dtypes {
562 lower::lower_dtype(tok, section, operand).map_err(|_| FkcError::FdxTokenNotInTable {
563 section: section.to_string(),
564 field: format!("{operand}.dtypes"),
565 token: tok.clone(),
566 })?;
567 }
568
569 if let Some(layout) = &d.layout {
571 layout_coherence(section, operand, layout)?;
572 }
573
574 awkward_strategy_coherence(section, operand, d, accept)?;
576
577 if let Some(fdx) = &d.fdx {
580 let is_sub_byte = d
582 .dtypes
583 .iter()
584 .any(|t| matches!(t.as_str(), "F4" | "F6E2M3" | "F6E3M2"));
585 if is_sub_byte && fdx.quant.is_none() && fdx.sub_byte.is_none() {
586 return Err(FkcError::QuantIncoherent {
587 section: section.to_string(),
588 operand: operand.to_string(),
589 reason: "sub-byte dtype requires an fdx.sub_byte + fdx.quant block (no reliance \
590 on size_in_bytes()==0)"
591 .to_string(),
592 });
593 }
594
595 if let Some(quant) = &fdx.quant {
596 quant_coherence(section, operand, quant, accept)?;
597 }
598
599 if let Some(gather) = &fdx.gather {
601 gather_coherence(section, operand, gather, fdx, accept)?;
602 }
603
604 extent_coherence(section, operand, fdx)?;
606 }
607
608 Ok(())
609}
610
611fn layout_coherence(
614 section: &str,
615 operand: &str,
616 layout: &crate::fkc::schema::LayoutSpec,
617) -> Result<(), FkcError> {
618 use crate::fkc::caps_map::{Tri, resolve_layout};
619 let r = resolve_layout(Some(layout), section, operand)?;
622
623 let contiguous_ok = matches!(r.contiguous, Tri::Required | Tri::Accepted);
624 let strided_ok = matches!(r.strided, Tri::Accepted);
625
626 if !contiguous_ok && !strided_ok {
628 return Err(FkcError::LayoutIncoherent {
629 section: section.to_string(),
630 operand: operand.to_string(),
631 reason: "neither `contiguous` (required|accepted) nor `strided: accepted` is set — \
632 the kernel accepts no layout"
633 .to_string(),
634 });
635 }
636
637 if matches!(r.broadcast_stride0, Tri::Accepted) && !strided_ok {
639 return Err(FkcError::LayoutIncoherent {
640 section: section.to_string(),
641 operand: operand.to_string(),
642 reason: "`broadcast_stride0: accepted` requires `strided: accepted` (broadcast is a \
643 stride-0 special case)"
644 .to_string(),
645 });
646 }
647 if matches!(r.reverse_strides, Tri::Accepted) && !strided_ok {
649 return Err(FkcError::LayoutIncoherent {
650 section: section.to_string(),
651 operand: operand.to_string(),
652 reason: "`reverse_strides: accepted` requires `strided: accepted` (a negative stride \
653 is still a strided walk)"
654 .to_string(),
655 });
656 }
657
658 match (
665 &layout.broadcast_axes,
666 matches!(r.broadcast_stride0, Tri::Required),
667 ) {
668 (Some(axes), true) if axes.is_empty() => {
669 return Err(FkcError::LayoutIncoherent {
670 section: section.to_string(),
671 operand: operand.to_string(),
672 reason: "`broadcast_stride0: required` with an EMPTY `broadcast_axes` — name the \
673 iteration axes the operand must be stride-0 on"
674 .to_string(),
675 });
676 }
677 (Some(_), false) => {
678 return Err(FkcError::LayoutIncoherent {
679 section: section.to_string(),
680 operand: operand.to_string(),
681 reason: "`broadcast_axes` set without `broadcast_stride0: required` — the mask is \
682 meaningful only for a required (baked) broadcast"
683 .to_string(),
684 });
685 }
686 (None, true) => {
687 return Err(FkcError::LayoutIncoherent {
688 section: section.to_string(),
689 operand: operand.to_string(),
690 reason: "`broadcast_stride0: required` needs `broadcast_axes` — the shape-blind \
691 binder can't verify the broadcast without the axis mask"
692 .to_string(),
693 });
694 }
695 _ => {}
696 }
697 Ok(())
698}
699
700fn awkward_strategy_coherence(
703 section: &str,
704 operand: &str,
705 d: &TensorDesc,
706 _accept: &crate::fkc::schema::AcceptBlock,
707) -> Result<(), FkcError> {
708 use crate::fkc::caps_map::{Tri, resolve_layout};
709
710 let per_operand = d
715 .layout
716 .as_ref()
717 .and_then(|l| l.awkward_layout_strategy.as_deref());
718
719 let Some(strategy) = per_operand else {
720 return Ok(());
723 };
724
725 let r = resolve_layout(d.layout.as_ref(), section, operand)?;
726 match strategy {
727 "handles_strided" => {
728 if !matches!(r.strided, Tri::Accepted) {
729 return Err(FkcError::AwkwardStrategyIncoherent {
730 section: section.to_string(),
731 operand: operand.to_string(),
732 strategy: strategy.to_string(),
733 reason: "`handles_strided` requires `strided: accepted` on this operand"
734 .to_string(),
735 });
736 }
737 }
738 "requires_contiguous" => {
739 if !matches!(r.contiguous, Tri::Required) {
740 return Err(FkcError::AwkwardStrategyIncoherent {
741 section: section.to_string(),
742 operand: operand.to_string(),
743 strategy: strategy.to_string(),
744 reason: "`requires_contiguous` requires `contiguous: required` on this operand"
745 .to_string(),
746 });
747 }
748 }
749 "contiguize_internally" => {
750 if !matches!(r.strided, Tri::Accepted) {
754 return Err(FkcError::AwkwardStrategyIncoherent {
755 section: section.to_string(),
756 operand: operand.to_string(),
757 strategy: strategy.to_string(),
758 reason: "`contiguize_internally` requires `strided: accepted` on this operand \
759 (it accepts strided then copies internally)"
760 .to_string(),
761 });
762 }
763 }
764 other => {
765 return Err(FkcError::AwkwardStrategyIncoherent {
766 section: section.to_string(),
767 operand: operand.to_string(),
768 strategy: other.to_string(),
769 reason: "unknown awkward_layout_strategy (meaning-bearing — §11.1)".to_string(),
770 });
771 }
772 }
773 Ok(())
774}
775
776fn quant_coherence(
779 section: &str,
780 operand: &str,
781 quant: &QuantSpec,
782 accept: &crate::fkc::schema::AcceptBlock,
783) -> Result<(), FkcError> {
784 let family = quant.family.as_deref().unwrap_or("none");
785
786 if !is_fdx_quant_family(family) {
788 return Err(FkcError::FdxTokenNotInTable {
789 section: section.to_string(),
790 field: format!("{operand}.fdx.quant.family"),
791 token: family.to_string(),
792 });
793 }
794 if let Some(g) = quant.granularity.as_deref()
796 && !is_fdx_granularity(g)
797 {
798 return Err(FkcError::FdxTokenNotInTable {
799 section: section.to_string(),
800 field: format!("{operand}.fdx.quant.granularity"),
801 token: g.to_string(),
802 });
803 }
804 if let Some(g) = quant.ggml_dtype.as_deref()
806 && ggml_dtype_code(g).is_none()
807 {
808 return Err(FkcError::QuantIncoherent {
810 section: section.to_string(),
811 operand: operand.to_string(),
812 reason: format!(
813 "ggml_dtype `{g}` is not a real GgmlDType variant (matched by code; \
814 `Q4_K_M` is a GGUF file-format name → use `Q4K`)"
815 ),
816 });
817 }
818
819 if let Some(scale_role) = quant.scale_operand.as_deref() {
826 let names_real = accept
829 .inputs
830 .iter()
831 .any(|i| i.name.as_deref() == Some(scale_role));
832 if !names_real {
833 return Err(FkcError::ScaleDoubleDeclared {
834 section: section.to_string(),
835 operand: operand.to_string(),
836 reason: format!(
837 "scale_operand `{scale_role}` does not name a real accept.inputs role"
838 ),
839 });
840 }
841 if family == "GGML_BLOCK" {
844 return Err(FkcError::ScaleDoubleDeclared {
845 section: section.to_string(),
846 operand: operand.to_string(),
847 reason: "GGML_BLOCK bakes its scale INLINE (per ggml_dtype) — it must NOT also \
848 declare a separate scale_operand"
849 .to_string(),
850 });
851 }
852 }
853
854 match family {
856 "none" | "NONE" => {
857 }
859 "GGML_BLOCK" => {
860 if quant.ggml_dtype.is_none() {
862 return Err(FkcError::QuantIncoherent {
863 section: section.to_string(),
864 operand: operand.to_string(),
865 reason: "GGML_BLOCK requires a `ggml_dtype` (the block format)".to_string(),
866 });
867 }
868 if quant.granularity.is_some() {
869 return Err(FkcError::QuantIncoherent {
870 section: section.to_string(),
871 operand: operand.to_string(),
872 reason: "GGML_BLOCK carries NO granularity (the scale is baked INLINE per \
873 ggml_dtype; no ScalePair, no PerBlock)"
874 .to_string(),
875 });
876 }
877 }
878 "AFFINE_INT" | "AFFINE_FLOAT" => {
879 match quant.granularity.as_deref() {
881 Some(g) if is_registrable_granularity(g) => {}
882 Some("PerBlock") => {
883 return Err(FkcError::QuantIncoherent {
884 section: section.to_string(),
885 operand: operand.to_string(),
886 reason: format!(
887 "{family} granularity must be PerTensor|PerToken|PerChannel \
888 (PerBlock is MX-only)"
889 ),
890 });
891 }
892 _ => {
893 return Err(FkcError::QuantIncoherent {
894 section: section.to_string(),
895 operand: operand.to_string(),
896 reason: format!(
897 "{family} requires granularity ∈ PerTensor|PerToken|PerChannel"
898 ),
899 });
900 }
901 }
902 }
903 "MX" => {
904 if quant.granularity.as_deref() != Some("PerBlock") {
906 return Err(FkcError::QuantIncoherent {
907 section: section.to_string(),
908 operand: operand.to_string(),
909 reason: "MX requires granularity: PerBlock (F8E8M0 per-block scale)"
910 .to_string(),
911 });
912 }
913 return Err(FkcError::MxNotYetRegistrable {
914 section: section.to_string(),
915 family: "MX".to_string(),
916 reason: "no ScaleGranularity::PerBlock target type yet (§6)".to_string(),
917 });
918 }
919 "AFFINE_BLOCK" => {
920 let has_block_shape = quant.block_shape.is_some();
930 let has_separate_scale = quant.scale_operand.is_some();
931 if !has_block_shape && !has_separate_scale {
932 return Err(FkcError::QuantIncoherent {
933 section: section.to_string(),
934 operand: operand.to_string(),
935 reason: "AFFINE_BLOCK requires block geometry — either `block_shape` or a \
936 block-shaped separate `scale_operand` (§10.6)"
937 .to_string(),
938 });
939 }
940 if quant.granularity.as_deref() == Some("PerBlock") {
941 return Err(FkcError::QuantIncoherent {
942 section: section.to_string(),
943 operand: operand.to_string(),
944 reason: "AFFINE_BLOCK must NOT use granularity: PerBlock (PerBlock stays \
945 MX-only; its grain rides block_shape)"
946 .to_string(),
947 });
948 }
949 return Err(FkcError::MxNotYetRegistrable {
950 section: section.to_string(),
951 family: "AFFINE_BLOCK".to_string(),
952 reason: "no block-quant descriptor target type yet (§6)".to_string(),
953 });
954 }
955 _ => unreachable!("family membership already checked against the FDX table"),
956 }
957
958 Ok(())
959}
960
961fn gather_coherence(
964 section: &str,
965 operand: &str,
966 gather: &crate::fkc::schema::GatherSpec,
967 fdx: &crate::fkc::schema::FdxSpec,
968 accept: &crate::fkc::schema::AcceptBlock,
969) -> Result<(), FkcError> {
970 let Some(kind) = gather.kind.as_deref() else {
971 return Ok(());
973 };
974 match kind {
975 "paged_blocks" => {
976 if fdx.requires_ext != Some(true) {
978 return Err(FkcError::GatherIncoherent {
979 section: section.to_string(),
980 operand: operand.to_string(),
981 reason: "paged_blocks requires `fdx.requires_ext: true`".to_string(),
982 });
983 }
984 if fdx.symbolic_extent.as_deref() != Some("required") {
986 return Err(FkcError::GatherIncoherent {
987 section: section.to_string(),
988 operand: operand.to_string(),
989 reason: "paged_blocks requires `fdx.symbolic_extent: required`".to_string(),
990 });
991 }
992 for (label, role) in [
994 ("block_table", gather.block_table.as_deref()),
995 ("context_lens", gather.context_lens.as_deref()),
996 ] {
997 if let Some(role) = role {
998 let exists = accept
999 .inputs
1000 .iter()
1001 .any(|i| i.name.as_deref() == Some(role));
1002 if !exists {
1003 return Err(FkcError::GatherIncoherent {
1004 section: section.to_string(),
1005 operand: operand.to_string(),
1006 reason: format!(
1007 "gather.{label} `{role}` does not name a real accept.inputs role"
1008 ),
1009 });
1010 }
1011 }
1012 }
1013 Ok(())
1033 }
1034 other => Err(FkcError::UnknownAdmissibilityEnum {
1035 section: section.to_string(),
1036 field: format!("{operand}.fdx.gather.kind"),
1037 value: other.to_string(),
1038 }),
1039 }
1040}
1041
1042fn extent_coherence(
1045 section: &str,
1046 operand: &str,
1047 fdx: &crate::fkc::schema::FdxSpec,
1048) -> Result<(), FkcError> {
1049 if let Some(se) = fdx.symbolic_extent.as_deref()
1051 && !matches!(se, "rejected" | "tolerated" | "required")
1052 {
1053 return Err(FkcError::UnknownAdmissibilityEnum {
1054 section: section.to_string(),
1055 field: format!("{operand}.fdx.symbolic_extent"),
1056 value: se.to_string(),
1057 });
1058 }
1059 if let Some(ek) = fdx.extent_kind.as_deref() {
1061 if !matches!(ek, "rejected" | "scalar" | "range" | "affine") {
1062 return Err(FkcError::UnknownAdmissibilityEnum {
1063 section: section.to_string(),
1064 field: format!("{operand}.fdx.extent_kind"),
1065 value: ek.to_string(),
1066 });
1067 }
1068 if matches!(ek, "range" | "affine") && fdx.symbolic_extent.as_deref() != Some("required") {
1070 return Err(FkcError::UnknownAdmissibilityEnum {
1071 section: section.to_string(),
1072 field: format!("{operand}.fdx.extent_kind"),
1073 value: format!(
1074 "{ek} requires symbolic_extent: required (got {:?})",
1075 fdx.symbolic_extent
1076 ),
1077 });
1078 }
1079 }
1080 Ok(())
1081}
1082
1083fn validate_op_params_namespace(
1091 section: &str,
1092 variant: &str,
1093 is_fused: bool,
1094) -> Result<(), FkcError> {
1095 let ok = if is_fused {
1096 is_fused_op_params_variant(variant)
1097 } else {
1098 is_op_params_variant(variant)
1099 };
1100 if ok {
1101 Ok(())
1102 } else {
1103 Err(FkcError::BadOpParamsVariant {
1104 section: section.to_string(),
1105 variant: variant.to_string(),
1106 namespace: if is_fused {
1107 "FusedOpParams"
1108 } else {
1109 "OpParams"
1110 }
1111 .to_string(),
1112 })
1113 }
1114}
1115
1116macro_rules! variant_table {
1140 ($enum:ident, $guard:ident, $table:ident, $($v:ident => $excluded:expr),+ $(,)?) => {
1141 fn $guard(p: &$enum) {
1145 match p { $( $enum::$v { .. } => (), )+ }
1146 }
1147
1148 const $table: &[(&str, Option<&str>)] = &[ $( (stringify!($v), $excluded) ),+ ];
1150 };
1151}
1152
1153variant_table!(
1154 OpParams,
1155 _op_params_is_exhaustive,
1156 OP_PARAMS_VARIANTS,
1157 None => None,
1158 Reduce => None,
1159 Matmul => None,
1160 Conv1D => None,
1161 Conv2D => None,
1162 ConvTranspose1D => None,
1163 ConvTranspose2D => None,
1164 ReduceSumTo => None,
1165 ReduceMaxTo => None,
1166 ReduceMaxToBackward => None,
1167 FlashAttn => None,
1168 PagedAttn => None,
1169 Slice => None,
1170 Cast => None,
1171 Affine => None,
1172 Clamp => None,
1173 PowI => None,
1174 Concat => None,
1175 SoftmaxLastDim => None,
1176 NormLastDim => None,
1177 IndexSelect => None,
1178 Gather => None,
1179 Rope => None,
1180 QMatMul => None,
1181 IndexAdd => None,
1182 ScatterAdd => None,
1183 Flip => None,
1184 Roll => None,
1185 CumSum => None,
1186 Triangular => None,
1187 LogSoftmaxLastDim => None,
1188 MaskedFill => None,
1189 PadBackward => None,
1190 Pad => None,
1191 WriteSlice => None,
1192 WriteSliceRotating => None,
1193 WriteSliceDoff => None,
1194 FusedSoftmaxCrossEntropy => None,
1195 CausalConv1d => None,
1196 SelectiveScan => None,
1197 SsdChunkScan => None,
1198 Nf4Matmul => None,
1199 AwqMatmul => None,
1200 TopKLastDim => None,
1201 MatMulTopK => None,
1202 JitScalars => Some("runtime-JIT-only: no checked-in kernel to contract"),
1207 NonZeroIndices => None,
1208);
1209
1210variant_table!(
1211 FusedOpParams,
1212 _fused_op_params_is_exhaustive,
1213 FUSED_OP_PARAMS_VARIANTS,
1214 SoftmaxLastDim => None,
1215 FusedLinear => None,
1216 RmsNormLastDim => None,
1217 LayerNormLastDim => None,
1218 Rope => None,
1219 Conv2D => None,
1220 SoftmaxLastDimBackward => None,
1221 LayerNormLastDimBackward => None,
1222 RmsNormLastDimBackward => None,
1223 ReduceMaxToBackward => None,
1224 PowIBackward => None,
1225 ConvTranspose2D => None,
1226 FlashAttn => None,
1227 PagedAttn => None,
1228 QMatMul => None,
1229 InplaceAffine => None,
1230 SsdChunkScan => None,
1231 Nf4Matmul => None,
1232 AwqMatmul => None,
1233 RowScaledMatMul => None,
1234 TopKLastDim => None,
1235 MatMulTopK => None,
1236 FlashAttnBackward => None,
1237 SelectiveScan => None,
1238 CausalConv1d => None,
1239 FusedSoftmaxCrossEntropy => None,
1240 Runtime => Some("runtime-registered: identity is a runtime FusedOpId"),
1245);
1246
1247fn is_op_params_variant(v: &str) -> bool {
1251 contract_authorable(OP_PARAMS_VARIANTS, v)
1252}
1253
1254fn is_fused_op_params_variant(v: &str) -> bool {
1258 contract_authorable(FUSED_OP_PARAMS_VARIANTS, v)
1259}
1260
1261fn contract_authorable(table: &[(&str, Option<&str>)], v: &str) -> bool {
1266 table
1267 .iter()
1268 .any(|(name, excluded)| *name == v && excluded.is_none())
1269}
1270
1271fn check_output_dtype_rule(section: &str, operand: &str, rule: &str) -> Result<(), FkcError> {
1278 let rule = rule.trim();
1279 if let Some(inner) = rule
1280 .strip_prefix("fixed(")
1281 .and_then(|s| s.strip_suffix(")"))
1282 {
1283 let tok = inner.trim();
1284 lower::lower_dtype(tok, section, operand).map_err(|_| FkcError::FdxTokenNotInTable {
1285 section: section.to_string(),
1286 field: format!("{operand}.dtype_rule fixed(...)"),
1287 token: tok.to_string(),
1288 })?;
1289 }
1290 Ok(())
1291}
1292
1293fn check_bundle_ranks(section: &str, bundle: &serde_yaml_ng::Value) -> Result<(), FkcError> {
1301 let serde_yaml_ng::Value::Sequence(slots) = bundle else {
1302 return Ok(());
1303 };
1304 for (i, slot) in slots.iter().enumerate() {
1305 let serde_yaml_ng::Value::Mapping(map) = slot else {
1306 continue;
1307 };
1308 let slot_name = map
1309 .get(serde_yaml_ng::Value::String("name".into()))
1310 .and_then(|v| v.as_str())
1311 .map(str::to_string)
1312 .unwrap_or_else(|| format!("slot{i}"));
1313 if let Some(serde_yaml_ng::Value::Sequence(dims)) =
1315 map.get(serde_yaml_ng::Value::String("shape".into()))
1316 && dims.len() > 6
1317 {
1318 return Err(FkcError::BundleSlotRankExceeded {
1319 section: section.to_string(),
1320 slot: slot_name,
1321 rank: dims.len(),
1322 });
1323 }
1324 }
1325 Ok(())
1326}
1327
1328fn validate_cost(kernel: &FkcKernel, section: &str) -> Result<(), FkcError> {
1333 let Some(cost) = &kernel.cost else {
1334 return Ok(());
1336 };
1337
1338 match cost.provenance.as_deref() {
1340 Some("declared") | Some("judge_measured") => {}
1341 other => {
1342 return Err(FkcError::CostProvenanceMissing {
1343 section: section.to_string(),
1344 found: other.map(String::from),
1345 });
1346 }
1347 }
1348
1349 use crate::fkc::cost_expr;
1352 let parse = |field: &str, src: Option<&str>| -> Result<(), FkcError> {
1353 cost_expr::compile_field(src)
1354 .map(|_| ())
1355 .map_err(|e| FkcError::CostExprParse {
1356 section: section.to_string(),
1357 field: field.to_string(),
1358 expr: src.unwrap_or("").to_string(),
1359 reason: e.to_string(),
1360 })
1361 };
1362 parse("flops", cost.flops.as_deref())?;
1363 parse("bytes_moved", cost.bytes_moved.as_deref())?;
1364 if let Some(serde_yaml_ng::Value::String(s)) = &cost.overhead_ns {
1365 parse("overhead_ns", Some(s))?;
1366 }
1367 if let Some(mem) = &cost.memory {
1368 for (field, v) in [
1369 ("memory.device_bytes", &mem.device_bytes),
1370 ("memory.host_bytes", &mem.host_bytes),
1371 ("memory.disk_bytes", &mem.disk_bytes),
1372 ] {
1373 if let Some(serde_yaml_ng::Value::String(s)) = v {
1374 parse(field, Some(s))?;
1375 }
1376 }
1377 }
1378
1379 let class = cost.class.as_deref().unwrap_or("");
1391 let has_any_expr = cost.flops.as_deref().is_some_and(|s| !s.trim().is_empty())
1392 || cost
1393 .bytes_moved
1394 .as_deref()
1395 .is_some_and(|s| !s.trim().is_empty());
1396 let has_cost_fn = cost
1397 .cost_fn
1398 .as_deref()
1399 .is_some_and(|s| !s.trim().is_empty());
1400 if cost.provenance.as_deref() == Some("declared")
1401 && crate::fkc::cost_compile::classify_cost("declared", class, has_any_expr, has_cost_fn)
1402 .is_none()
1403 {
1404 return Err(FkcError::PlaceholderCost {
1405 section: section.to_string(),
1406 reason: "provenance: declared with no usable cost path (no flops/bytes_moved \
1407 expression, no pinned cost.cost_fn) and class is not `free`"
1408 .to_string(),
1409 });
1410 }
1411
1412 Ok(())
1413}
1414
1415fn validate_precision_coherence(kernel: &FkcKernel, section: &str) -> Result<(), FkcError> {
1420 let det = kernel.determinism.as_deref().unwrap_or("");
1421 if det == "nondeterministic" {
1422 if let Some(p) = &kernel.precision {
1425 if p.bit_stable_on_same_hardware == Some(true) {
1426 return Err(FkcError::QuantIncoherent {
1427 section: section.to_string(),
1428 operand: "<precision>".to_string(),
1429 reason: "determinism: nondeterministic requires bit_stable_on_same_hardware = \
1430 false"
1431 .to_string(),
1432 });
1433 }
1434 if p.audited != Some(true) {
1435 return Err(FkcError::QuantIncoherent {
1436 section: section.to_string(),
1437 operand: "<precision>".to_string(),
1438 reason: "determinism: nondeterministic requires audited: true with a \
1439 none(reason) precision (no silent unaudited nondeterminism)"
1440 .to_string(),
1441 });
1442 }
1443 }
1444 }
1445 Ok(())
1446}
1447
1448#[cfg(test)]
1449mod tests {
1450 use super::*;
1451 use crate::fkc::parse_file;
1452
1453 fn valid_bundle() -> String {
1458 r#"---
1459fkc_version: 1
1460provider:
1461 name: test-provider
1462 backend: Cpu
1463 kernel_source: "test-cpu"
1464---
1465
1466# test bundle
1467
1468## demo
1469
1470A blurb.
1471
1472```fkc
1473kernel: demo
1474op_kind: AddElementwise
1475blurb: "demo blurb"
1476entry_point: "x::y"
1477accept:
1478 inputs:
1479 - name: lhs
1480 dtypes: [F32]
1481 layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }
1482 - name: rhs
1483 dtypes: [F32]
1484 layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }
1485 op_params: { variant: None }
1486return:
1487 outputs:
1488 - name: out
1489 dtype_rule: passthrough(lhs)
1490caps:
1491 awkward_layout_strategy: requires_contiguous
1492cost:
1493 provenance: declared
1494 class: cheap_elementwise
1495 flops: "n"
1496 bytes_moved: "3 * n * 4"
1497precision:
1498 bit_stable_on_same_hardware: true
1499 audited: true
1500determinism: same_hardware_bitwise
1501```
1502"#
1503 .to_string()
1504 }
1505
1506 fn validate_str(src: &str) -> Result<(), FkcError> {
1507 let file = parse_file(src).expect("fixture parses");
1508 validate_file(&file)
1509 }
1510
1511 #[test]
1512 fn valid_contract_passes() {
1513 validate_str(&valid_bundle()).expect("the valid fixture validates");
1514 }
1515
1516 #[test]
1518 fn version_too_new_is_unsupported() {
1519 let src = valid_bundle().replace("fkc_version: 1", "fkc_version: 99");
1520 let err = validate_str(&src).expect_err("version 99 unsupported");
1521 assert!(
1522 matches!(err, FkcError::UnsupportedVersion { found: 99, .. }),
1523 "got {err:?}"
1524 );
1525 }
1526
1527 #[test]
1536 fn fkc_version_zero_is_rejected() {
1537 let src = valid_bundle().replace("fkc_version: 1", "fkc_version: 0");
1538 let err = validate_str(&src).expect_err("fkc_version 0 must be rejected");
1539 assert!(
1540 matches!(err, FkcError::UnsupportedVersion { found: 0, .. }),
1541 "expected UnsupportedVersion for fkc_version 0, got {err:?}"
1542 );
1543 }
1544
1545 #[test]
1550 fn fkc_version_one_is_still_accepted() {
1551 let result = validate_str(&valid_bundle());
1552 assert!(
1553 !matches!(result, Err(FkcError::UnsupportedVersion { .. })),
1554 "fkc_version 1 (sole supported) must pass the version gate, got {result:?}"
1555 );
1556 }
1557
1558 #[test]
1566 fn fkc_version_is_decoupled_from_crate_semver() {
1567 assert_eq!(FKC_SUPPORTED_VERSIONS, &[1]);
1570 }
1571
1572 #[test]
1579 fn fkc_front_matter_schema_is_pinned_to_the_version() {
1580 const PINNED_FKC_SCHEMA_VERSION: u32 = 1;
1581 assert_eq!(
1582 FKC_SUPPORTED_VERSIONS.iter().copied().max(),
1583 Some(PINNED_FKC_SCHEMA_VERSION),
1584 "the latest supported fkc_version moved without updating the pinned \
1585 front-matter schema (or vice-versa) — a §8-0002 schema change bumps both"
1586 );
1587 }
1588
1589 #[test]
1591 fn missing_blurb_errors() {
1592 let src = valid_bundle().replace("blurb: \"demo blurb\"\n", "");
1593 let err = validate_str(&src).expect_err("no blurb");
1594 assert!(matches!(err, FkcError::MissingBlurb { .. }), "got {err:?}");
1595 }
1596
1597 #[test]
1598 fn missing_cost_block_errors() {
1599 let src = valid_bundle();
1601 let cut = src.replace(
1602 "cost:\n provenance: declared\n class: cheap_elementwise\n flops: \"n\"\n bytes_moved: \"3 * n * 4\"\n",
1603 "",
1604 );
1605 let err = validate_str(&cut).expect_err("no cost block");
1606 assert!(
1607 matches!(err, FkcError::MissingRequiredField { ref field, .. } if field == "cost"),
1608 "got {err:?}"
1609 );
1610 }
1611
1612 #[test]
1613 fn missing_determinism_errors() {
1614 let src = valid_bundle().replace("determinism: same_hardware_bitwise\n", "");
1615 let err = validate_str(&src).expect_err("no determinism");
1616 assert!(
1617 matches!(err, FkcError::MissingRequiredField { ref field, .. } if field == "determinism"),
1618 "got {err:?}"
1619 );
1620 }
1621
1622 #[test]
1623 fn both_op_kind_and_fused_op_is_ambiguous() {
1624 let src = valid_bundle().replace(
1625 "op_kind: AddElementwise",
1626 "op_kind: AddElementwise\nfused_op: SOFTMAX_LAST_DIM",
1627 );
1628 let err = validate_str(&src).expect_err("both targets");
1629 assert!(
1630 matches!(err, FkcError::OpTargetAmbiguous { .. }),
1631 "got {err:?}"
1632 );
1633 }
1634
1635 #[test]
1637 fn bad_dtype_token_is_fdx_token_not_in_table() {
1638 let src = valid_bundle().replace("dtypes: [F32]", "dtypes: [F99]");
1639 let err = validate_str(&src).expect_err("F99 not a dtype");
1640 assert!(
1641 matches!(err, FkcError::FdxTokenNotInTable { .. }),
1642 "got {err:?}"
1643 );
1644 }
1645
1646 #[test]
1648 fn layout_no_acceptable_form_is_incoherent() {
1649 let src = valid_bundle().replace(
1651 "layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }",
1652 "layout: { contiguous: \"n/a\", strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }",
1653 );
1654 let err = validate_str(&src).expect_err("no acceptable layout");
1655 assert!(
1656 matches!(err, FkcError::LayoutIncoherent { .. }),
1657 "got {err:?}"
1658 );
1659 }
1660
1661 #[test]
1662 fn broadcast_without_strided_is_incoherent() {
1663 let src = valid_bundle().replace(
1664 "layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }",
1665 "layout: { contiguous: required, strided: rejected, broadcast_stride0: accepted, start_offset: rejected, reverse_strides: rejected }",
1666 );
1667 let err = validate_str(&src).expect_err("broadcast w/o strided");
1668 assert!(
1669 matches!(err, FkcError::LayoutIncoherent { .. }),
1670 "got {err:?}"
1671 );
1672 }
1673
1674 #[test]
1675 fn reverse_without_strided_is_incoherent() {
1676 let src = valid_bundle().replace(
1677 "layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }",
1678 "layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: accepted }",
1679 );
1680 let err = validate_str(&src).expect_err("reverse w/o strided");
1681 assert!(
1682 matches!(err, FkcError::LayoutIncoherent { .. }),
1683 "got {err:?}"
1684 );
1685 }
1686
1687 #[test]
1689 fn required_broadcast_with_axes_is_valid() {
1690 let src = valid_bundle()
1692 .replace(
1693 "layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }",
1694 "layout: { contiguous: accepted, strided: accepted, broadcast_stride0: required, broadcast_axes: [0], start_offset: rejected, reverse_strides: rejected }",
1695 )
1696 .replace(
1697 "awkward_layout_strategy: requires_contiguous",
1698 "awkward_layout_strategy: handles_strided",
1699 );
1700 validate_str(&src)
1701 .expect("required broadcast with a non-empty broadcast_axes mask validates");
1702 }
1703
1704 #[test]
1705 fn required_broadcast_without_axes_is_incoherent() {
1706 let src = valid_bundle().replace(
1707 "layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }",
1708 "layout: { contiguous: accepted, strided: accepted, broadcast_stride0: required, start_offset: rejected, reverse_strides: rejected }",
1709 );
1710 let err = validate_str(&src).expect_err("required broadcast needs a broadcast_axes mask");
1711 assert!(
1712 matches!(err, FkcError::LayoutIncoherent { .. }),
1713 "got {err:?}"
1714 );
1715 }
1716
1717 #[test]
1718 fn broadcast_axes_without_required_is_incoherent() {
1719 let src = valid_bundle().replace(
1720 "layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }",
1721 "layout: { contiguous: accepted, strided: accepted, broadcast_stride0: accepted, broadcast_axes: [0], start_offset: rejected, reverse_strides: rejected }",
1722 );
1723 let err = validate_str(&src).expect_err("broadcast_axes is meaningful only with required");
1724 assert!(
1725 matches!(err, FkcError::LayoutIncoherent { .. }),
1726 "got {err:?}"
1727 );
1728 }
1729
1730 #[test]
1731 fn required_broadcast_with_empty_axes_is_incoherent() {
1732 let src = valid_bundle().replace(
1733 "layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }",
1734 "layout: { contiguous: accepted, strided: accepted, broadcast_stride0: required, broadcast_axes: [], start_offset: rejected, reverse_strides: rejected }",
1735 );
1736 let err = validate_str(&src).expect_err("empty broadcast_axes on a required broadcast");
1737 assert!(
1738 matches!(err, FkcError::LayoutIncoherent { .. }),
1739 "got {err:?}"
1740 );
1741 }
1742
1743 #[test]
1745 fn handles_strided_without_strided_accepted_is_incoherent() {
1746 let src = valid_bundle().replace(
1747 "layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }",
1748 "layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected, awkward_layout_strategy: handles_strided }",
1749 );
1750 let err = validate_str(&src).expect_err("handles_strided but strided rejected");
1751 assert!(
1752 matches!(err, FkcError::AwkwardStrategyIncoherent { .. }),
1753 "got {err:?}"
1754 );
1755 }
1756
1757 #[test]
1758 fn unknown_awkward_strategy_is_typed_error() {
1759 let src = valid_bundle().replace(
1760 "layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }",
1761 "layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected, awkward_layout_strategy: teleports }",
1762 );
1763 let err = validate_str(&src).expect_err("unknown strategy");
1764 assert!(
1765 matches!(err, FkcError::AwkwardStrategyIncoherent { .. }),
1766 "got {err:?}"
1767 );
1768 }
1769
1770 fn quant_bundle(family: &str, extra: &str) -> String {
1772 format!(
1774 r#"---
1775fkc_version: 1
1776provider:
1777 name: test-provider
1778 backend: Cpu
1779 kernel_source: "test-cpu"
1780---
1781
1782# q
1783
1784## q
1785
1786blurb.
1787
1788```fkc
1789kernel: q
1790op_kind: QMatMul
1791blurb: "q"
1792entry_point: "x::q"
1793accept:
1794 inputs:
1795 - name: act
1796 dtypes: [F32]
1797 layout: {{ contiguous: required, strided: rejected }}
1798 - name: weight
1799 dtypes: [U8]
1800 layout: {{ contiguous: required, strided: rejected }}
1801 fdx:
1802 requires_ext: true
1803 quant:
1804 family: {family}
1805{extra}
1806 op_params: {{ variant: QMatMul }}
1807return:
1808 outputs:
1809 - name: out
1810 dtype_rule: fixed(F32)
1811cost:
1812 provenance: judge_measured
1813 class: gemm_like
1814precision:
1815 bit_stable_on_same_hardware: true
1816 audited: true
1817determinism: same_hardware_bitwise
1818```
1819"#
1820 )
1821 }
1822
1823 #[test]
1824 fn ggml_block_with_real_dtype_ok() {
1825 let src = quant_bundle(
1826 "GGML_BLOCK",
1827 " ggml_dtype: Q4_0\n role: weight",
1828 );
1829 validate_str(&src).expect("GGML_BLOCK Q4_0 weight validates");
1830 }
1831
1832 #[test]
1833 fn ggml_dtype_q4_k_m_is_quant_incoherent() {
1834 let src = quant_bundle(
1836 "GGML_BLOCK",
1837 " ggml_dtype: Q4_K_M\n role: weight",
1838 );
1839 let err = validate_str(&src).expect_err("Q4_K_M bad");
1840 assert!(
1841 matches!(err, FkcError::QuantIncoherent { .. }),
1842 "got {err:?}"
1843 );
1844 }
1845
1846 #[test]
1847 fn ggml_block_with_granularity_is_incoherent() {
1848 let src = quant_bundle(
1849 "GGML_BLOCK",
1850 " ggml_dtype: Q4_0\n granularity: PerChannel\n role: weight",
1851 );
1852 let err = validate_str(&src).expect_err("GGML carries no granularity");
1853 assert!(
1854 matches!(err, FkcError::QuantIncoherent { .. }),
1855 "got {err:?}"
1856 );
1857 }
1858
1859 #[test]
1860 fn mx_family_is_not_yet_registrable() {
1861 let src = quant_bundle(
1862 "MX",
1863 " granularity: PerBlock\n role: weight",
1864 );
1865 let err = validate_str(&src).expect_err("MX not registrable");
1866 assert!(
1867 matches!(err, FkcError::MxNotYetRegistrable { ref family, .. } if family == "MX"),
1868 "got {err:?}"
1869 );
1870 }
1871
1872 #[test]
1873 fn affine_block_without_block_shape_is_incoherent() {
1874 let src = quant_bundle(
1875 "AFFINE_BLOCK",
1876 " role: weight\n scale_operand: scl",
1877 );
1878 let err = validate_str(&src).expect_err("AFFINE_BLOCK needs block_shape / real scale");
1881 assert!(
1882 matches!(
1883 err,
1884 FkcError::QuantIncoherent { .. } | FkcError::ScaleDoubleDeclared { .. }
1885 ),
1886 "got {err:?}"
1887 );
1888 }
1889
1890 #[test]
1891 fn affine_int_bad_granularity_is_incoherent() {
1892 let src = quant_bundle(
1893 "AFFINE_INT",
1894 " granularity: PerBlock\n role: weight",
1895 );
1896 let err = validate_str(&src).expect_err("AFFINE_INT PerBlock bad");
1897 assert!(
1898 matches!(err, FkcError::QuantIncoherent { .. }),
1899 "got {err:?}"
1900 );
1901 }
1902
1903 #[test]
1904 fn unknown_family_is_fdx_token_not_in_table() {
1905 let src = quant_bundle("MADE_UP", " role: weight");
1906 let err = validate_str(&src).expect_err("MADE_UP not an FDX family");
1907 assert!(
1908 matches!(err, FkcError::FdxTokenNotInTable { .. }),
1909 "got {err:?}"
1910 );
1911 }
1912
1913 #[test]
1914 fn ggml_with_separate_scale_operand_is_double_declared() {
1915 let src = quant_bundle(
1918 "GGML_BLOCK",
1919 " ggml_dtype: Q4_0\n role: weight\n scale_operand: act",
1920 );
1921 let err = validate_str(&src).expect_err("GGML + separate scale");
1922 assert!(
1923 matches!(err, FkcError::ScaleDoubleDeclared { .. }),
1924 "got {err:?}"
1925 );
1926 }
1927
1928 #[test]
1930 fn op_kind_with_fused_only_variant_is_bad_namespace() {
1931 let src = valid_bundle().replace(
1934 "op_params: { variant: None }",
1935 "op_params: { variant: FusedLinear }",
1936 );
1937 let err = validate_str(&src).expect_err("FusedLinear not in OpParams");
1938 assert!(
1939 matches!(err, FkcError::BadOpParamsVariant { ref namespace, .. } if namespace == "OpParams"),
1940 "got {err:?}"
1941 );
1942 }
1943
1944 #[test]
1953 fn op_params_namespace_accepts_the_real_nonzeroindices_variant() {
1954 let src = valid_bundle().replace(
1955 "op_params: { variant: None }",
1956 "op_params: { variant: NonZeroIndices }",
1957 );
1958 validate_str(&src)
1959 .expect("NonZeroIndices is a real OpParams variant — a contract may name it");
1960 }
1961
1962 #[test]
1967 fn op_param_predicates_agree_with_the_generated_variant_tables() {
1968 assert!(
1973 OP_PARAMS_VARIANTS.len() >= 40,
1974 "OP_PARAMS_VARIANTS looks truncated ({} entries) — the rest of this \
1975 test would pass vacuously",
1976 OP_PARAMS_VARIANTS.len()
1977 );
1978 assert!(
1979 FUSED_OP_PARAMS_VARIANTS.len() >= 20,
1980 "FUSED_OP_PARAMS_VARIANTS looks truncated ({} entries)",
1981 FUSED_OP_PARAMS_VARIANTS.len()
1982 );
1983
1984 for (name, excluded) in OP_PARAMS_VARIANTS {
1985 assert_eq!(
1986 is_op_params_variant(name),
1987 excluded.is_none(),
1988 "OpParams::{name} — excluded={excluded:?} but the predicate says \
1989 {}",
1990 is_op_params_variant(name)
1991 );
1992 }
1993 for (name, excluded) in FUSED_OP_PARAMS_VARIANTS {
1994 assert_eq!(
1995 is_fused_op_params_variant(name),
1996 excluded.is_none(),
1997 "FusedOpParams::{name} — excluded={excluded:?} but the predicate \
1998 says {}",
1999 is_fused_op_params_variant(name)
2000 );
2001 }
2002
2003 for (name, excluded) in OP_PARAMS_VARIANTS.iter().chain(FUSED_OP_PARAMS_VARIANTS) {
2006 if let Some(reason) = excluded {
2007 assert!(
2008 !reason.trim().is_empty(),
2009 "{name} is excluded with an empty reason"
2010 );
2011 }
2012 }
2013 }
2014
2015 #[test]
2022 fn runtime_only_op_param_variants_stay_out_of_contract_reach() {
2023 assert!(!is_op_params_variant("JitScalars"));
2024 assert!(!is_fused_op_params_variant("Runtime"));
2025
2026 let src = valid_bundle().replace(
2027 "op_params: { variant: None }",
2028 "op_params: { variant: JitScalars }",
2029 );
2030 let err = validate_str(&src).expect_err("JitScalars is runtime-JIT-only");
2031 assert!(
2032 matches!(err, FkcError::BadOpParamsVariant { ref namespace, .. } if namespace == "OpParams"),
2033 "got {err:?}"
2034 );
2035 }
2036
2037 fn fdx_codes_src() -> String {
2059 let path =
2060 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../fuel-ir/src/dlpack/codes.rs");
2061 std::fs::read_to_string(&path).unwrap_or_else(|e| {
2062 panic!(
2063 "the FDX code table must be readable from the workspace (this test checks \
2064 fuel-dispatch against fuel-ir's source text); read {path:?}: {e}"
2065 )
2066 })
2067 }
2068
2069 const FDX_FAMILY_TOKENS: &[(&str, &str)] = &[
2073 ("FDX_QUANT_NONE", "NONE"),
2074 ("FDX_QUANT_GGML_BLOCK", "GGML_BLOCK"),
2075 ("FDX_QUANT_MX", "MX"),
2076 ("FDX_QUANT_AFFINE_INT", "AFFINE_INT"),
2077 ("FDX_QUANT_AFFINE_FLOAT", "AFFINE_FLOAT"),
2078 ("FDX_QUANT_AFFINE_BLOCK", "AFFINE_BLOCK"),
2079 ];
2080
2081 const FDX_GRAN_TOKENS: &[(&str, &str)] = &[
2083 ("FDX_SCALE_GRAN_PER_TENSOR", "PerTensor"),
2084 ("FDX_SCALE_GRAN_PER_TOKEN", "PerToken"),
2085 ("FDX_SCALE_GRAN_PER_CHANNEL", "PerChannel"),
2086 ("FDX_SCALE_GRAN_PER_BLOCK", "PerBlock"),
2087 ];
2088
2089 fn fdx_consts_with_prefix(prefix: &str) -> std::collections::BTreeSet<String> {
2091 fdx_codes_src()
2092 .lines()
2093 .filter_map(|l| l.trim().strip_prefix("pub const ")?.split(':').next())
2094 .map(|n| n.trim().to_string())
2095 .filter(|n| n.starts_with(prefix))
2096 .collect()
2097 }
2098
2099 #[test]
2100 fn fkc_quant_tokens_are_a_faithful_subset_of_the_fdx_code_table() {
2101 let families = fdx_consts_with_prefix("FDX_QUANT_");
2102 let grans = fdx_consts_with_prefix("FDX_SCALE_GRAN_");
2103
2104 assert!(
2110 families.contains("FDX_QUANT_GGML_BLOCK") && grans.contains("FDX_SCALE_GRAN_PER_BLOCK"),
2111 "parsed {} family / {} granularity consts out of {} lines of codes.rs — \
2112 the parse found neither known anchor, so it is broken, not the table",
2113 families.len(),
2114 grans.len(),
2115 fdx_codes_src().lines().count()
2116 );
2117
2118 let declared_families: std::collections::BTreeSet<String> = FDX_FAMILY_TOKENS
2119 .iter()
2120 .map(|(c, _)| c.to_string())
2121 .collect();
2122 assert_eq!(
2123 families, declared_families,
2124 "FDX's FDX_QUANT_* table and FKC's mirror of it have diverged — update \
2125 FDX_FAMILY_TOKENS *and* is_fdx_quant_family together"
2126 );
2127
2128 let declared_grans: std::collections::BTreeSet<String> =
2129 FDX_GRAN_TOKENS.iter().map(|(c, _)| c.to_string()).collect();
2130 assert_eq!(
2131 grans, declared_grans,
2132 "FDX's FDX_SCALE_GRAN_* table and FKC's mirror of it have diverged"
2133 );
2134
2135 for (konst, token) in FDX_FAMILY_TOKENS {
2137 assert!(
2138 is_fdx_quant_family(token),
2139 "FKC rejects `{token}`, the token for the live FDX const {konst}"
2140 );
2141 }
2142 for (konst, token) in FDX_GRAN_TOKENS {
2143 assert!(
2144 is_fdx_granularity(token),
2145 "FKC rejects `{token}`, the token for the live FDX const {konst}"
2146 );
2147 }
2148
2149 assert!(is_fdx_quant_family("none"));
2151
2152 for bogus in ["PerGroup", "AWQ", "GPTQ", "affine_int", "PERTENSOR", ""] {
2155 assert!(!is_fdx_quant_family(bogus), "family accepted `{bogus}`");
2156 assert!(!is_fdx_granularity(bogus), "granularity accepted `{bogus}`");
2157 }
2158 }
2159
2160 #[test]
2162 fn missing_provenance_errors() {
2163 let src = valid_bundle().replace(" provenance: declared\n", "");
2164 let err = validate_str(&src).expect_err("no provenance");
2165 assert!(
2166 matches!(err, FkcError::CostProvenanceMissing { .. }),
2167 "got {err:?}"
2168 );
2169 }
2170
2171 #[test]
2172 fn bad_cost_expr_is_cost_expr_parse() {
2173 let src = valid_bundle().replace("flops: \"n\"", "flops: \"2 * * n\"");
2174 let err = validate_str(&src).expect_err("malformed flops");
2175 assert!(matches!(err, FkcError::CostExprParse { .. }), "got {err:?}");
2176 }
2177
2178 #[test]
2179 fn declared_with_no_coeffs_and_no_class_is_placeholder() {
2180 let src = valid_bundle()
2181 .replace(" class: cheap_elementwise\n", "")
2182 .replace(" flops: \"n\"\n", "")
2183 .replace(" bytes_moved: \"3 * n * 4\"\n", "");
2184 let err = validate_str(&src).expect_err("bare declared cost");
2185 assert!(
2186 matches!(err, FkcError::PlaceholderCost { .. }),
2187 "got {err:?}"
2188 );
2189 }
2190
2191 #[test]
2192 fn judge_measured_all_tilde_is_not_placeholder() {
2193 let src = valid_bundle()
2196 .replace("provenance: declared", "provenance: judge_measured")
2197 .replace(" flops: \"n\"\n", " flops: ~\n")
2198 .replace(" bytes_moved: \"3 * n * 4\"\n", " bytes_moved: ~\n");
2199 validate_str(&src).expect("judge_measured + ~ is fine");
2200 }
2201
2202 #[test]
2203 fn placeholder_cost_class_field() {
2204 use crate::fkc::cost_compile::{CostClassKind, classify_cost};
2205 assert!(classify_cost("declared", "cheap_elementwise", false, false).is_none());
2206 assert!(matches!(
2207 classify_cost("declared", "free", false, false),
2208 Some(CostClassKind::Free)
2209 ));
2210 assert!(matches!(
2211 classify_cost("declared", "gemm_like", true, false),
2212 Some(CostClassKind::DeclaredFormula)
2213 ));
2214 assert!(matches!(
2215 classify_cost("declared", "gemm_like", false, true),
2216 Some(CostClassKind::VendorSpec)
2217 ));
2218 assert!(matches!(
2219 classify_cost("judge_measured", "gemm_like", false, false),
2220 Some(CostClassKind::JudgeMeasured)
2221 ));
2222 use crate::fkc::register::import_bundle_str;
2224 let src = "---\nfkc_version: 1\nprovider:\n name: ph-provider\n backend: Cpu\n kernel_source: \"ph-cpu\"\n---\n\n# ph\n\n## add_f32\n\nA.\n\n```fkc\nkernel: add_f32\nop_kind: AddElementwise\nblurb: \"a\"\nentry_point: \"x::add_f32\"\naccept:\n inputs:\n - name: lhs\n dtypes: [F32]\n layout: { contiguous: required, strided: rejected }\n - name: rhs\n dtypes: [F32]\n layout: { contiguous: required, strided: rejected }\n op_params: { variant: None }\nreturn:\n outputs:\n - name: out\n dtype_rule: passthrough(lhs)\ncost:\n provenance: declared\n class: cheap_elementwise\nprecision:\n bit_stable_on_same_hardware: true\n audited: true\ndeterminism: same_hardware_bitwise\n```\n";
2225 let err = import_bundle_str(src, &StubLink::new())
2226 .expect_err("declared + non-free class + no usable cost path must reject");
2227 assert!(
2228 matches!(err, FkcError::PlaceholderCost { .. }),
2229 "got {err:?}"
2230 );
2231 }
2232
2233 #[test]
2235 fn nondeterministic_with_bitstable_true_is_incoherent() {
2236 let src = valid_bundle().replace(
2237 "determinism: same_hardware_bitwise",
2238 "determinism: nondeterministic",
2239 );
2240 let err = validate_str(&src).expect_err("nondeterministic + bit_stable true");
2241 assert!(
2242 matches!(err, FkcError::QuantIncoherent { .. }),
2243 "got {err:?}"
2244 );
2245 }
2246
2247 #[test]
2249 fn unknown_extent_kind_is_typed_error() {
2250 let src = quant_bundle("none", "").replace(
2251 " fdx:\n requires_ext: true\n quant:\n family: none\n",
2252 " fdx:\n extent_kind: wobbly\n symbolic_extent: required\n",
2253 );
2254 let err = validate_str(&src).expect_err("bad extent_kind");
2255 assert!(
2256 matches!(err, FkcError::UnknownAdmissibilityEnum { .. }),
2257 "got {err:?}"
2258 );
2259 }
2260
2261 fn describe_only_bundle() -> String {
2267 r#"---
2268fkc_version: 1
2269provider:
2270 name: test-provider
2271 backend: Cpu
2272 kernel_source: "test-cpu"
2273---
2274
2275# describe-only bundle
2276
2277## binary
2278
2279A chassis umbrella.
2280
2281```fkc
2282kernel: binary
2283registrable: false
2284op_kind: binary
2285blurb: "shared binary chassis (documentation umbrella)"
2286entry_point: "x::chassis"
2287accept:
2288 inputs:
2289 - name: lhs
2290 dtypes: [F32, F64, BF16, F16]
2291 layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }
2292 - name: rhs
2293 dtypes: [F32, F64, BF16, F16]
2294 layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }
2295return:
2296 outputs:
2297 - name: out
2298 dtype_rule: passthrough(lhs)
2299cost:
2300 provenance: judge_measured
2301 class: cheap_elementwise
2302precision:
2303 bit_stable_on_same_hardware: true
2304 audited: true
2305determinism: same_hardware_bitwise
2306```
2307"#
2308 .to_string()
2309 }
2310
2311 #[test]
2312 fn describe_only_with_descriptive_op_kind_validates() {
2313 validate_str(&describe_only_bundle()).expect("describe-only section validates");
2316 }
2317
2318 #[test]
2319 fn describe_only_with_tilde_op_kind_validates() {
2320 let src = describe_only_bundle().replace("op_kind: binary\n", "op_kind: ~\n");
2323 validate_str(&src).expect("describe-only with op_kind: ~ validates");
2324 }
2325
2326 #[test]
2327 fn non_describe_only_still_requires_real_op_kind_regression() {
2328 let src = describe_only_bundle().replace("registrable: false\n", "");
2332 let err = validate_str(&src).expect_err("registrable section needs a real op_kind");
2333 assert!(matches!(err, FkcError::UnknownOpKind { .. }), "got {err:?}");
2334 }
2335
2336 #[test]
2337 fn describe_only_still_validates_descriptive_dtypes() {
2338 let src = describe_only_bundle().replace("dtypes: [F32, F64, BF16, F16]", "dtypes: [F99]");
2342 let err = validate_str(&src).expect_err("bad dtype in describe-only docs");
2343 assert!(
2344 matches!(err, FkcError::FdxTokenNotInTable { .. }),
2345 "got {err:?}"
2346 );
2347 }
2348
2349 #[test]
2350 fn describe_only_still_validates_layout_coherence() {
2351 let src = describe_only_bundle().replace(
2353 "layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }",
2354 "layout: { contiguous: \"n/a\", strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }",
2355 );
2356 let err = validate_str(&src).expect_err("incoherent layout in describe-only docs");
2357 assert!(
2358 matches!(err, FkcError::LayoutIncoherent { .. }),
2359 "got {err:?}"
2360 );
2361 }
2362
2363 fn describe_only_zero_input_bundle() -> String {
2368 r#"---
2369fkc_version: 1
2370provider:
2371 name: test-provider
2372 backend: Cpu
2373 kernel_source: "test-cpu"
2374---
2375
2376# describe-only zero-input bundle
2377
2378## rand_fill
2379
2380A zero-operand random fill.
2381
2382```fkc
2383kernel: rand_fill
2384registrable: false
2385op_kind: RandUniform
2386blurb: "fill a dense buffer with U(min,max); no input tensor (RNG state is backend-private)"
2387entry_point: "x::rand_fill"
2388accept:
2389 inputs: []
2390return:
2391 outputs:
2392 - name: out
2393 dtype_rule: cast(out)
2394cost:
2395 provenance: judge_measured
2396 class: cheap_elementwise
2397precision:
2398 bit_stable_on_same_hardware: false
2399 audited: true
2400determinism: nondeterministic
2401```
2402"#
2403 .to_string()
2404 }
2405
2406 #[test]
2407 fn describe_only_zero_input_fill_validates() {
2408 validate_str(&describe_only_zero_input_bundle())
2412 .expect("describe-only zero-input fill validates");
2413 }
2414
2415 #[test]
2416 fn registrable_zero_input_still_fails_missing_required_field() {
2417 let src = describe_only_zero_input_bundle()
2422 .replace("registrable: false\n", "")
2423 .replace("op_kind: RandUniform\n", "op_kind: ReluElementwise\n");
2427 let err = validate_str(&src).expect_err("registrable zero-input section is rejected");
2428 assert!(
2429 matches!(err, FkcError::MissingRequiredField { ref field, .. } if field == "accept.inputs (≥1)"),
2430 "got {err:?}"
2431 );
2432 }
2433
2434 fn paged_blocks_bundle() -> String {
2445 r#"---
2446fkc_version: 1
2447provider:
2448 name: test-provider
2449 backend: Cpu
2450 kernel_source: "test-cpu"
2451---
2452
2453# paged bundle
2454
2455## paged_demo
2456
2457A paged attention blurb.
2458
2459```fkc
2460kernel: paged_demo
2461op_kind: PagedAttn
2462blurb: "naive paged attention over a blocked KV cache"
2463entry_point: "x::paged_demo"
2464accept:
2465 inputs:
2466 - name: q
2467 dtypes: [F32]
2468 layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }
2469 - name: k_cache
2470 dtypes: [F32]
2471 layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }
2472 fdx:
2473 requires_ext: true
2474 symbolic_extent: required
2475 gather: { kind: paged_blocks, block_table: block_table, context_lens: context_lens }
2476 - name: block_table
2477 dtypes: [U32]
2478 layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }
2479 - name: context_lens
2480 dtypes: [U32]
2481 layout: { contiguous: required, strided: rejected, broadcast_stride0: rejected, start_offset: rejected, reverse_strides: rejected }
2482 op_params: { variant: PagedAttn }
2483return:
2484 outputs:
2485 - name: out
2486 dtype_rule: passthrough(q)
2487cost:
2488 provenance: declared
2489 class: attention
2490 flops: "4 * b * hq * sq * ctx * d"
2491 bytes_moved: "2 * b * hq * sq * d * 4"
2492precision:
2493 bit_stable_on_same_hardware: true
2494 audited: true
2495determinism: same_hardware_bitwise
2496```
2497"#
2498 .to_string()
2499 }
2500
2501 #[test]
2502 fn coherent_registrable_paged_blocks_validates() {
2503 validate_str(&paged_blocks_bundle())
2512 .expect("a coherent registrable paged_blocks section validates + is registrable");
2513 }
2514
2515 #[test]
2516 fn incoherent_gather_missing_requires_ext_still_errors() {
2517 let src = paged_blocks_bundle().replace(" requires_ext: true\n", "");
2521 let err = validate_str(&src).expect_err("gather without requires_ext must error");
2522 assert!(
2523 matches!(err, FkcError::GatherIncoherent { ref reason, .. } if reason.contains("requires_ext")),
2524 "got {err:?}",
2525 );
2526 }
2527
2528 #[test]
2529 fn incoherent_gather_dangling_block_table_role_still_errors() {
2530 let src = paged_blocks_bundle().replace("block_table: block_table,", "block_table: nope,");
2535 let err = validate_str(&src).expect_err("dangling block_table role must error");
2536 assert!(
2537 matches!(err, FkcError::GatherIncoherent { ref reason, .. } if reason.contains("block_table")),
2538 "got {err:?}",
2539 );
2540 }
2541
2542 #[test]
2543 fn unknown_gather_kind_is_unknown_admissibility_enum() {
2544 let src = paged_blocks_bundle().replace("kind: paged_blocks,", "kind: ragged_csr,");
2547 let err = validate_str(&src).expect_err("unknown gather kind must error");
2548 assert!(
2549 matches!(err, FkcError::UnknownAdmissibilityEnum { ref value, .. } if value == "ragged_csr"),
2550 "got {err:?}",
2551 );
2552 }
2553
2554 struct StubLink {
2562 seen: std::sync::Mutex<std::collections::HashMap<String, crate::kernel::KernelRef>>,
2563 }
2564 impl StubLink {
2565 fn new() -> Self {
2566 Self {
2567 seen: std::sync::Mutex::new(std::collections::HashMap::new()),
2568 }
2569 }
2570 fn resolve(&self, symbol: &str) -> Option<crate::kernel::KernelRef> {
2571 use std::sync::Arc;
2572 use std::sync::RwLock;
2573 fn k0(
2577 _i: &[Arc<RwLock<fuel_memory::Storage>>],
2578 _o: &mut [Arc<RwLock<fuel_memory::Storage>>],
2579 _l: &[fuel_ir::Layout],
2580 _p: &crate::kernel::OpParams,
2581 ) -> fuel_ir::Result<()> {
2582 Ok(())
2583 }
2584 fn k1(
2585 _i: &[Arc<RwLock<fuel_memory::Storage>>],
2586 _o: &mut [Arc<RwLock<fuel_memory::Storage>>],
2587 _l: &[fuel_ir::Layout],
2588 _p: &crate::kernel::OpParams,
2589 ) -> fuel_ir::Result<()> {
2590 Ok(())
2591 }
2592 fn k2(
2593 _i: &[Arc<RwLock<fuel_memory::Storage>>],
2594 _o: &mut [Arc<RwLock<fuel_memory::Storage>>],
2595 _l: &[fuel_ir::Layout],
2596 _p: &crate::kernel::OpParams,
2597 ) -> fuel_ir::Result<()> {
2598 Ok(())
2599 }
2600 fn k3(
2601 _i: &[Arc<RwLock<fuel_memory::Storage>>],
2602 _o: &mut [Arc<RwLock<fuel_memory::Storage>>],
2603 _l: &[fuel_ir::Layout],
2604 _p: &crate::kernel::OpParams,
2605 ) -> fuel_ir::Result<()> {
2606 Ok(())
2607 }
2608 let table: [crate::kernel::KernelRef; 4] = [k0, k1, k2, k3];
2609 let mut g = self.seen.lock().unwrap();
2610 if let Some(k) = g.get(symbol) {
2611 return Some(*k);
2612 }
2613 let k = table[g.len() % table.len()];
2614 g.insert(symbol.to_string(), k);
2615 Some(k)
2616 }
2617 }
2618 impl crate::fkc::lower::LinkRegistry for StubLink {
2619 fn resolve_primitive(&self, s: &str) -> Option<crate::kernel::KernelRef> {
2620 self.resolve(s)
2621 }
2622 fn resolve_fused(&self, s: &str) -> Option<crate::kernel::KernelRef> {
2623 self.resolve(s)
2624 }
2625 fn resolve_cost_fn(&self, _name: &str) -> Option<crate::kernel::CostFn> {
2626 fn c(
2632 _s: &[fuel_ir::Shape],
2633 _d: &[fuel_ir::DType],
2634 _p: &crate::kernel::OpParams,
2635 _c: &fuel_ir::backend::BackendCapabilities,
2636 ) -> crate::fused::CostEstimate {
2637 crate::fused::CostEstimate::default()
2638 }
2639 Some(c)
2640 }
2641 }
2642
2643 fn collect_fkc_files(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
2646 let rd = std::fs::read_dir(dir).unwrap_or_else(|e| {
2651 panic!(
2652 "collect_fkc_files: read_dir({}) failed: {e} — the FKC file sweep must FAIL, not silently truncate",
2653 dir.display()
2654 )
2655 });
2656 for entry in rd.flatten() {
2657 let path = entry.path();
2658 if path.is_dir() {
2659 if path.file_name().and_then(|n| n.to_str()) == Some("_inventory") {
2660 continue;
2661 }
2662 collect_fkc_files(&path, out);
2663 } else if path.to_string_lossy().ends_with(".fkc.md") {
2664 out.push(path);
2665 }
2666 }
2667 }
2668
2669 #[test]
2697 fn ci_lint_corpus_parse_lower_validate() {
2698 let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
2701 let corpus = manifest.join("kernel-contracts");
2702 assert!(
2703 corpus.is_dir(),
2704 "corpus dir not found at {}",
2705 corpus.display()
2706 );
2707
2708 let mut files = Vec::new();
2709 collect_fkc_files(&corpus, &mut files);
2710 let vulkan_corpus = manifest.join("../fuel-vulkan-dispatch/kernel-contracts");
2713 assert!(
2714 vulkan_corpus.is_dir(),
2715 "Vulkan corpus dir not found at {}",
2716 vulkan_corpus.display()
2717 );
2718 collect_fkc_files(&vulkan_corpus, &mut files);
2719 files.sort();
2720 assert!(!files.is_empty(), "no .fkc.md files found");
2721
2722 let link = StubLink::new();
2723 let mut file_count = 0usize;
2724 let mut section_count = 0usize;
2725 let mut hard_failures: Vec<String> = Vec::new();
2726 let mut deferred: Vec<String> = Vec::new();
2727
2728 for path in &files {
2729 file_count += 1;
2730 let rel = path
2731 .strip_prefix(manifest)
2732 .unwrap_or(path)
2733 .display()
2734 .to_string();
2735 let src = std::fs::read_to_string(path).expect("read corpus file");
2736
2737 let file = match parse_file(&src) {
2739 Ok(f) => f,
2740 Err(e) => {
2741 hard_failures.push(format!("{rel}: PARSE: {e}"));
2742 continue;
2743 }
2744 };
2745 section_count += file.kernels.len();
2746
2747 if !fkc_version_is_supported(file.front_matter.fkc_version) {
2751 hard_failures.push(format!(
2752 "{rel}: fkc_version {} not in supported set {:?}",
2753 file.front_matter.fkc_version, FKC_SUPPORTED_VERSIONS
2754 ));
2755 continue;
2756 }
2757 for kernel in &file.kernels {
2758 let kname = kernel.kernel.as_str();
2759 match validate_kernel(kernel) {
2760 Ok(()) => {}
2761 Err(
2762 e @ (FkcError::MxNotYetRegistrable { .. }
2763 | FkcError::GatherNotYetSupported { .. }),
2764 ) => {
2765 deferred.push(format!("{rel} :: {kname}: {e}"));
2766 }
2767 Err(e) => {
2768 hard_failures.push(format!("{rel} :: {kname}: {e}"));
2769 continue;
2770 }
2771 }
2772 if let Err(e) = lower_one_kernel(&file, kernel, &link) {
2776 match e {
2780 FkcError::MxNotYetRegistrable { .. }
2781 | FkcError::GatherNotYetSupported { .. } => {}
2782 FkcError::FanoutDtypeMismatch { .. } => {
2793 deferred.push(format!("{rel} :: {kname}: LOWER: {e}"));
2794 }
2795 FkcError::OptionalOperandNotLast { .. } => {
2806 deferred.push(format!("{rel} :: {kname}: LOWER: {e}"));
2807 }
2808 _ => hard_failures.push(format!("{rel} :: {kname}: LOWER: {e}")),
2809 }
2810 }
2811 }
2812 }
2813
2814 eprintln!(
2815 "FKC corpus lint: {file_count} files, {section_count} sections; {} deferred (MX/gather not-yet-registrable + multi-axis dtype / chained-optional not-yet-fannable), {} hard failures",
2816 deferred.len(),
2817 hard_failures.len()
2818 );
2819 if !deferred.is_empty() {
2820 eprintln!(
2821 "--- deferred (describable, not-yet-registrable / not-yet-fannable; spec §6/§3.9.1/§3.4) ---"
2822 );
2823 for d in &deferred {
2824 eprintln!(" {d}");
2825 }
2826 }
2827 if !hard_failures.is_empty() {
2828 eprintln!("--- HARD FAILURES (file :: kernel: rule) ---");
2829 for f in &hard_failures {
2830 eprintln!(" {f}");
2831 }
2832 panic!(
2833 "{} corpus contract(s) failed parse/lower/validate — see the list above \
2834 (REPORT these, do not relax the validators)",
2835 hard_failures.len()
2836 );
2837 }
2838 }
2839
2840 #[test]
2864 fn ci_lint_corpus_has_no_cross_file_entry_point_collisions() {
2865 let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
2866 let corpus = manifest.join("kernel-contracts");
2867 assert!(
2868 corpus.is_dir(),
2869 "corpus dir not found at {}",
2870 corpus.display()
2871 );
2872
2873 let mut files = Vec::new();
2874 collect_fkc_files(&corpus, &mut files);
2875 let vulkan_corpus = manifest.join("../fuel-vulkan-dispatch/kernel-contracts");
2878 assert!(
2879 vulkan_corpus.is_dir(),
2880 "Vulkan corpus dir not found at {}",
2881 vulkan_corpus.display()
2882 );
2883 collect_fkc_files(&vulkan_corpus, &mut files);
2884 files.sort();
2885 assert!(!files.is_empty(), "no .fkc.md files found");
2886
2887 let mut claimed: std::collections::HashMap<(String, String), String> =
2889 std::collections::HashMap::new();
2890 let mut collisions: Vec<(String, String, String)> = Vec::new();
2892 let mut checked = 0usize;
2893
2894 for path in &files {
2895 let rel = path
2896 .strip_prefix(manifest)
2897 .unwrap_or(path)
2898 .display()
2899 .to_string();
2900 let src = std::fs::read_to_string(path).expect("read corpus file");
2901 let Ok(file) = parse_file(&src) else {
2902 continue;
2905 };
2906 let kernel_source = file.front_matter.provider.kernel_source.clone();
2907 for kernel in &file.kernels {
2908 if !kernel.registrable {
2911 continue;
2912 }
2913 let Some(entry) = kernel.entry_point.as_ref() else {
2914 continue;
2915 };
2916 checked += 1;
2917 let key = (kernel_source.clone(), entry.clone());
2918 let who = format!("{rel} :: {}", kernel.kernel);
2919 match claimed.get(&key) {
2920 Some(first) => collisions.push((
2921 key.0.clone(),
2922 key.1.clone(),
2923 format!("claimed by BOTH {first} AND {who}"),
2924 )),
2925 None => {
2926 claimed.insert(key, who);
2927 }
2928 }
2929 }
2930 }
2931
2932 eprintln!(
2935 "FKC corpus entry-point uniqueness: {checked} registrable contracts across {} files, {} distinct (kernel_source, entry_point) keys",
2936 files.len(),
2937 claimed.len()
2938 );
2939 assert!(
2940 checked > 0,
2941 "the lint examined zero registrable contracts — it is not looking where it thinks"
2942 );
2943
2944 const KNOWN: &[(&str, &str)] = &[
2961 (
2963 "portable-cpu",
2964 "fuel_cpu_backend::byte_kernels::sum_reduce_f32",
2965 ),
2966 (
2967 "portable-cpu",
2968 "fuel_cpu_backend::byte_kernels::max_reduce_f32",
2969 ),
2970 (
2971 "portable-cpu",
2972 "fuel_cpu_backend::byte_kernels::min_reduce_f32",
2973 ),
2974 (
2975 "portable-cpu",
2976 "fuel_cpu_backend::byte_kernels::mean_reduce_f32",
2977 ),
2978 (
2979 "portable-cpu",
2980 "fuel_cpu_backend::byte_kernels::reduce_sum_to_f32",
2981 ),
2982 (
2983 "portable-cpu",
2984 "fuel_cpu_backend::byte_kernels::reduce_max_to_f32",
2985 ),
2986 (
2987 "portable-cpu",
2988 "fuel_cpu_backend::byte_kernels::reduce_max_to_backward_f32",
2989 ),
2990 ("vulkan-slang", "fuel_vulkan_backend::fkc::rope_f32"),
2995 ("vulkan-slang", "fuel_vulkan_backend::fkc::flash_attn_f32"),
2997 ("vulkan-slang", "fuel_vulkan_backend::fkc::flash_attn_bf16"),
2998 ("vulkan-slang", "fuel_vulkan_backend::fkc::flash_attn_f16"),
2999 (
3000 "vulkan-slang",
3001 "fuel_vulkan_backend::fkc::flash_attn_backward_q_f32",
3002 ),
3003 (
3004 "vulkan-slang",
3005 "fuel_vulkan_backend::fkc::flash_attn_backward_k_f32",
3006 ),
3007 (
3008 "vulkan-slang",
3009 "fuel_vulkan_backend::fkc::flash_attn_backward_v_f32",
3010 ),
3011 ];
3012 let is_known =
3013 |key: &(String, String)| KNOWN.iter().any(|(ks, ep)| *ks == key.0 && *ep == key.1);
3014
3015 let novel: Vec<&(String, String, String)> = collisions
3016 .iter()
3017 .filter(|c| !is_known(&(c.0.clone(), c.1.clone())))
3018 .collect();
3019
3020 let seen: std::collections::HashSet<(String, String)> = collisions
3024 .iter()
3025 .map(|c| (c.0.clone(), c.1.clone()))
3026 .collect();
3027 let stale: Vec<&(&str, &str)> = KNOWN
3028 .iter()
3029 .filter(|(ks, ep)| !seen.contains(&((*ks).to_string(), (*ep).to_string())))
3030 .collect();
3031
3032 if !stale.is_empty() {
3033 for (ks, ep) in &stale {
3034 eprintln!(" STALE ALLOWLIST ENTRY (no longer collides): {ks} :: {ep}");
3035 }
3036 panic!(
3037 "{} allowlisted collision(s) no longer occur — delete them from KNOWN so the list keeps reflecting the real debt",
3038 stale.len()
3039 );
3040 }
3041
3042 if !novel.is_empty() {
3043 for (ks, ep, who) in &novel {
3044 eprintln!(" NEW COLLISION: kernel_source `{ks}` entry_point `{ep}` — {who}");
3045 }
3046 panic!(
3047 "{} NEW cross-file entry-point collision(s) — each would resolve to one KernelRef and trip the duplicate gate at registration. Give the new contract its own entry point, or mark it `registrable: false` if it is documentation.",
3048 novel.len()
3049 );
3050 }
3051 }
3052
3053 fn lower_one_kernel(
3058 file: &FkcFile,
3059 kernel: &FkcKernel,
3060 link: &dyn crate::fkc::lower::LinkRegistry,
3061 ) -> Result<(), FkcError> {
3062 let mut one = file.clone();
3065 one.kernels = vec![kernel.clone()];
3066 crate::fkc::lower::lower_file(&one, link, &mut Vec::new()).map(|_| ())
3067 }
3068}