Skip to main content

oa/core/operation/
contract.rs

1//! Backend-independent operation contracts.
2
3use bitflags::bitflags;
4
5// ─── BufferAccess ────────────────────────────────────────────────────────────
6
7/// Read/write access qualifier for a buffer binding.
8///
9/// Port provenance: `oa::BufferAccess` in `oa/core/bufferAccess.h`.
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub enum BufferAccess {
12	/// Buffer is read-only at this binding site.
13	Read,
14	/// Buffer is write-only at this binding site.
15	Write,
16	/// Buffer is both read and written at this binding site.
17	ReadWrite,
18}
19
20/// Semantic kind of one operation value.
21#[non_exhaustive]
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub enum OpValueKind {
24	/// Dense numeric matrix.
25	Matrix,
26	/// Image value.
27	Image,
28	/// Audio value.
29	Audio,
30	/// Video-frame value.
31	VideoFrame,
32	/// Quantized matrix value.
33	QuantMatrix,
34	/// Packed RGBA8 texture value.
35	Texture,
36}
37
38impl OpValueKind {
39	/// Return the stable semantic-report token.
40	pub const fn token(self) -> &'static str {
41		match self {
42			Self::Matrix => "matrix",
43			Self::Image => "image",
44			Self::Audio => "audio",
45			Self::VideoFrame => "video_frame",
46			Self::QuantMatrix => "quant_matrix",
47			Self::Texture => "texture",
48		}
49	}
50}
51
52/// Uniform shape relationship declared by an operation schema.
53#[non_exhaustive]
54#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
55pub enum OpShapeRule {
56	/// Output shape matches the admitted input shape.
57	#[default]
58	MatchInput,
59	/// Inputs use multidirectional broadcasting.
60	Broadcast,
61	/// Right input uses OA's `[N, K]` transposed-weight convention.
62	MatMulNt,
63	/// Operation-specific validation and inference is required.
64	Explicit,
65}
66
67/// Uniform dtype relationship declared by an operation schema.
68#[non_exhaustive]
69#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
70pub enum OpDTypeRule {
71	/// Inputs and outputs retain one dtype.
72	#[default]
73	MatchInput,
74	/// Inputs are promoted to a floating-point result.
75	PromoteFloat,
76	/// Operation-specific validation and inference is required.
77	Explicit,
78}
79
80/// Reverse-differentiation behavior declared by an operation schema.
81#[non_exhaustive]
82#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
83pub enum OpDifferentiation {
84	/// The operation has no reverse derivative.
85	#[default]
86	None,
87	/// The operation participates in reverse-mode differentiation.
88	Reverse,
89}
90
91impl OpDifferentiation {
92	/// Return the stable semantic-report token.
93	pub const fn token(self) -> &'static str {
94		match self {
95			Self::None => "none",
96			Self::Reverse => "reverse",
97		}
98	}
99}
100
101/// Backend-neutral lowering family requested by an operation schema.
102#[non_exhaustive]
103#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
104pub enum OpLowering {
105	/// Lower through the generic compute-dispatch path.
106	#[default]
107	Dispatch,
108	/// Lower through the engine's GEMM service.
109	Gemm,
110}
111
112impl OpLowering {
113	/// Return the stable semantic-report token.
114	pub const fn token(self) -> &'static str {
115		match self {
116			Self::Dispatch => "dispatch",
117			Self::Gemm => "gemm",
118		}
119	}
120}
121
122/// Fusion taxonomy class declared by an operation schema.
123///
124/// Region formation uses the class to admit or reject an operation:
125/// `Opaque` and `Effect` operations never enter a fusion region, while the
126/// structural classes name the read/write pattern the region compiler
127/// reasons about. `Opaque` is the default so an undeclared operation fails
128/// closed rather than silently joining a region.
129#[non_exhaustive]
130#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
131pub enum OpFusionClass {
132	/// Element-local arithmetic with no cross-lane reads.
133	Pointwise,
134	/// Element-local arithmetic with broadcast input expansion.
135	Broadcast,
136	/// Indexed or layout reads (gather, index, reshape, transpose).
137	Gather,
138	/// Cross-element reduction (sum, mean, norm, softmax, argmax).
139	Reduce,
140	/// Ordered prefix accumulation.
141	Scan,
142	/// Dense matrix multiplication family.
143	Gemm,
144	/// Convolution or pooling stencil.
145	Conv,
146	/// Attention-family kernel (SDPA, flash, causal variants).
147	Attention,
148	/// Internally fused composite that must not be decomposed or joined
149	/// into a region (SSM cells, recurrent cells, cryptographic kernels).
150	#[default]
151	Opaque,
152	/// Stateful or side-effecting operation (RNG cursors, environment
153	/// steps, parameter update kernels) excluded from region formation.
154	Effect,
155}
156
157impl OpFusionClass {
158	/// Return the stable schema/report token.
159	pub const fn token(self) -> &'static str {
160		match self {
161			Self::Pointwise => "pointwise",
162			Self::Broadcast => "broadcast",
163			Self::Gather => "gather",
164			Self::Reduce => "reduce",
165			Self::Scan => "scan",
166			Self::Gemm => "gemm",
167			Self::Conv => "conv",
168			Self::Attention => "attention",
169			Self::Opaque => "opaque",
170			Self::Effect => "effect",
171		}
172	}
173
174	/// Whether the class admits the operation to fusion-region formation.
175	pub const fn is_region_admitted(self) -> bool {
176		!matches!(self, Self::Opaque | Self::Effect)
177	}
178}
179
180/// Semantic control-flow class of an operation.
181#[non_exhaustive]
182#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
183pub enum OpControlFlow {
184	/// Ordinary acyclic dataflow.
185	#[default]
186	StraightLine,
187	/// Conditional execution.
188	Conditional,
189	/// Loop or recurrence.
190	Loop,
191}
192
193impl OpControlFlow {
194	/// Return the stable semantic-report token.
195	pub const fn token(self) -> &'static str {
196		match self {
197			Self::StraightLine => "straight_line",
198			Self::Conditional => "conditional",
199			Self::Loop => "loop",
200		}
201	}
202}
203
204bitflags! {
205	/// Logical value effects of an operation.
206	#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
207	pub struct OpEffect: u8 {
208		/// Read logical inputs.
209		const READ_INPUTS = 1 << 0;
210		/// Write logical outputs.
211		const WRITE_OUTPUTS = 1 << 1;
212	}
213}
214
215/// Stable type tag for a non-value operation attribute.
216#[non_exhaustive]
217#[derive(Clone, Copy, Debug, PartialEq, Eq)]
218pub enum OpAttributeKind {
219	/// Boolean value.
220	Boolean,
221	/// Signed integer value.
222	SignedInteger,
223	/// Unsigned integer value.
224	UnsignedInteger,
225	/// Floating-point value.
226	Float,
227	/// Free-form UTF-8 string.
228	String,
229	/// Matrix shape.
230	Shape,
231	/// Symbolic enum value.
232	Enum,
233}
234
235impl OpAttributeKind {
236	/// Return the stable semantic-report token.
237	pub const fn token(self) -> &'static str {
238		match self {
239			Self::Boolean => "boolean",
240			Self::SignedInteger => "signed_integer",
241			Self::UnsignedInteger => "unsigned_integer",
242			Self::Float => "float",
243			Self::String => "string",
244			Self::Shape => "shape",
245			Self::Enum => "enum",
246		}
247	}
248}
249
250/// One ordered non-value input that affects operation meaning.
251#[non_exhaustive]
252#[derive(Clone, Debug, PartialEq)]
253pub enum OpAttribute {
254	/// Boolean attribute.
255	Boolean { name: String, value: bool },
256	/// Signed integer attribute.
257	SignedInteger { name: String, value: i64 },
258	/// Unsigned integer attribute.
259	UnsignedInteger { name: String, value: u64 },
260	/// Floating-point attribute.
261	Float { name: String, value: f64 },
262	/// String attribute.
263	String { name: String, value: String },
264	/// Shape attribute.
265	Shape { name: String, value: Vec<usize> },
266	/// Symbolic enum attribute.
267	Enum { name: String, value: String },
268}
269
270impl OpAttribute {
271	/// Return this attribute's schema name.
272	pub fn name(&self) -> &str {
273		match self {
274			Self::Boolean { name, .. }
275			| Self::SignedInteger { name, .. }
276			| Self::UnsignedInteger { name, .. }
277			| Self::Float { name, .. }
278			| Self::String { name, .. }
279			| Self::Shape { name, .. }
280			| Self::Enum { name, .. } => name,
281		}
282	}
283
284	/// Return this attribute's stable kind.
285	pub const fn kind(&self) -> OpAttributeKind {
286		match self {
287			Self::Boolean { .. } => OpAttributeKind::Boolean,
288			Self::SignedInteger { .. } => OpAttributeKind::SignedInteger,
289			Self::UnsignedInteger { .. } => OpAttributeKind::UnsignedInteger,
290			Self::Float { .. } => OpAttributeKind::Float,
291			Self::String { .. } => OpAttributeKind::String,
292			Self::Shape { .. } => OpAttributeKind::Shape,
293			Self::Enum { .. } => OpAttributeKind::Enum,
294		}
295	}
296
297	pub(crate) fn validate(&self) -> bool {
298		!self.name().is_empty() && !matches!(self, Self::Enum { value, .. } if value.is_empty())
299	}
300}
301
302/// Ordered schema declaration for one operation attribute.
303#[derive(Clone, Copy, Debug, PartialEq, Eq)]
304pub struct OpAttributeSpec {
305	name: &'static str,
306	kind: OpAttributeKind,
307}
308
309impl OpAttributeSpec {
310	/// Construct one generated attribute declaration.
311	pub const fn new(name: &'static str, kind: OpAttributeKind) -> Self {
312		Self { name, kind }
313	}
314
315	/// Return the declared attribute name.
316	pub const fn name(self) -> &'static str {
317		self.name
318	}
319
320	/// Return the declared attribute kind.
321	pub const fn kind(self) -> OpAttributeKind {
322		self.kind
323	}
324}
325
326/// Stable semantic contract for one operation before backend lowering.
327///
328/// Generated operation registries own these descriptors. The builder-style
329/// `const` methods are public so generated code remains ordinary inspectable
330/// Rust rather than a private binary table.
331#[derive(Clone, Copy, Debug)]
332pub struct OperationContract {
333	name: &'static str,
334	hash: u64,
335	input_kinds: &'static [OpValueKind],
336	output_kinds: &'static [OpValueKind],
337	variadic_input: Option<(OpValueKind, usize)>,
338	variadic_output: Option<(OpValueKind, usize)>,
339	aligned_variadic_aliases: bool,
340	attributes: &'static [OpAttributeSpec],
341	shape_rule: OpShapeRule,
342	dtype_rule: OpDTypeRule,
343	differentiation: OpDifferentiation,
344	lowering: OpLowering,
345	effects: OpEffect,
346	fusion_class: OpFusionClass,
347	mutated_input_mask: u8,
348	optional_input_mask: u8,
349	output_alias_inputs: [Option<u8>; Self::MAX_VALUES],
350	control_flow: OpControlFlow,
351}
352
353impl OperationContract {
354	/// Maximum number of fixed logical inputs or outputs.
355	pub const MAX_VALUES: usize = 8;
356	/// Maximum number of semantic attributes.
357	pub const MAX_ATTRIBUTES: usize = 8;
358
359	/// Construct the fixed-arity portion of an operation contract.
360	pub const fn new(
361		name: &'static str,
362		hash: u64,
363		input_kinds: &'static [OpValueKind],
364		output_kinds: &'static [OpValueKind],
365	) -> Self {
366		Self {
367			name,
368			hash,
369			input_kinds,
370			output_kinds,
371			variadic_input: None,
372			variadic_output: None,
373			aligned_variadic_aliases: false,
374			attributes: &[],
375			shape_rule: OpShapeRule::MatchInput,
376			dtype_rule: OpDTypeRule::MatchInput,
377			differentiation: OpDifferentiation::None,
378			lowering: OpLowering::Dispatch,
379			effects: OpEffect::empty(),
380			fusion_class: OpFusionClass::Opaque,
381			mutated_input_mask: 0,
382			optional_input_mask: 0,
383			output_alias_inputs: [None; Self::MAX_VALUES],
384			control_flow: OpControlFlow::StraightLine,
385		}
386	}
387
388	/// Declare a homogeneous variadic input tail and its minimum length.
389	pub const fn variadic_inputs(mut self, kind: OpValueKind, minimum: usize) -> Self {
390		self.variadic_input = Some((kind, minimum));
391		self
392	}
393
394	/// Declare a homogeneous variadic output tail and its minimum length.
395	pub const fn variadic_outputs(mut self, kind: OpValueKind, minimum: usize) -> Self {
396		self.variadic_output = Some((kind, minimum));
397		self
398	}
399
400	/// Declare that each variadic output aliases and mutates the variadic input
401	/// at the same tail position.
402	pub const fn aligned_variadic_aliases(mut self) -> Self {
403		self.aligned_variadic_aliases = true;
404		self
405	}
406
407	/// Declare the ordered non-value input signature.
408	pub const fn attributes(mut self, attributes: &'static [OpAttributeSpec]) -> Self {
409		self.attributes = attributes;
410		self
411	}
412
413	/// Declare reverse-differentiation behavior.
414	pub const fn with_differentiation(mut self, value: OpDifferentiation) -> Self {
415		self.differentiation = value;
416		self
417	}
418
419	/// Declare the schema's uniform shape rule.
420	pub const fn with_shape_rule(mut self, value: OpShapeRule) -> Self {
421		self.shape_rule = value;
422		self
423	}
424
425	/// Declare the schema's uniform dtype rule.
426	pub const fn with_dtype_rule(mut self, value: OpDTypeRule) -> Self {
427		self.dtype_rule = value;
428		self
429	}
430
431	/// Declare the backend-neutral lowering family.
432	pub const fn with_lowering(mut self, value: OpLowering) -> Self {
433		self.lowering = value;
434		self
435	}
436
437	/// Declare the schema's fusion taxonomy class.
438	pub const fn with_fusion_class(mut self, value: OpFusionClass) -> Self {
439		self.fusion_class = value;
440		self
441	}
442
443	/// Declare logical read and write effects.
444	pub const fn effects(mut self, value: OpEffect) -> Self {
445		self.effects = value;
446		self
447	}
448
449	/// Declare the fixed-input mutation bit mask.
450	pub const fn mutated_inputs(mut self, mask: u8) -> Self {
451		self.mutated_input_mask = mask;
452		self
453	}
454
455	/// Declare the fixed-input optionality bit mask.
456	pub const fn optional_inputs(mut self, mask: u8) -> Self {
457		self.optional_input_mask = mask;
458		self
459	}
460
461	/// Declare that one output aliases a fixed input's storage.
462	///
463	/// Aliasing does not imply mutation. A pass-through output is a fresh SSA
464	/// value over the same bytes; an in-place write additionally declares the
465	/// input in [`Self::mutated_inputs`].
466	pub const fn alias(mut self, output: usize, input: u8) -> Self {
467		assert!(
468			output < Self::MAX_VALUES,
469			"operation alias output exceeds fixed capacity"
470		);
471		self.output_alias_inputs[output] = Some(input);
472		self
473	}
474
475	/// Declare semantic control flow.
476	pub const fn with_control_flow(mut self, value: OpControlFlow) -> Self {
477		self.control_flow = value;
478		self
479	}
480
481	/// Return the stable qualified operation name.
482	pub const fn name(self) -> &'static str {
483		self.name
484	}
485
486	/// Return the schema-derived semantic contract hash.
487	pub const fn hash(self) -> u64 {
488		self.hash
489	}
490
491	/// Return the declared differentiation behavior.
492	pub const fn differentiation(self) -> OpDifferentiation {
493		self.differentiation
494	}
495
496	/// Return the uniform shape rule.
497	pub const fn shape_rule(self) -> OpShapeRule {
498		self.shape_rule
499	}
500
501	/// Return the uniform dtype rule.
502	pub const fn dtype_rule(self) -> OpDTypeRule {
503		self.dtype_rule
504	}
505
506	/// Return the ordered non-value attribute signature.
507	pub const fn attribute_specs(self) -> &'static [OpAttributeSpec] {
508		self.attributes
509	}
510
511	/// Return the declared lowering family.
512	pub const fn lowering(self) -> OpLowering {
513		self.lowering
514	}
515
516	/// Return the schema-declared fusion taxonomy class.
517	pub const fn fusion_class(self) -> OpFusionClass {
518		self.fusion_class
519	}
520
521	/// Return the declared control-flow class.
522	pub const fn control_flow(self) -> OpControlFlow {
523		self.control_flow
524	}
525
526	pub(crate) fn accepts_input_count(self, count: usize) -> bool {
527		self
528			.variadic_input
529			.map_or(count == self.input_kinds.len(), |(_, minimum)| {
530				count >= self.input_kinds.len().saturating_add(minimum)
531			})
532	}
533
534	pub(crate) fn accepts_output_count(self, count: usize) -> bool {
535		self
536			.variadic_output
537			.map_or(count == self.output_kinds.len(), |(_, minimum)| {
538				count >= self.output_kinds.len().saturating_add(minimum)
539			})
540	}
541
542	pub(crate) fn input_kind(self, index: usize) -> Option<OpValueKind> {
543		self
544			.input_kinds
545			.get(index)
546			.copied()
547			.or_else(|| self.variadic_input.map(|(kind, _)| kind))
548	}
549
550	pub(crate) fn output_kind(self, index: usize) -> Option<OpValueKind> {
551		self
552			.output_kinds
553			.get(index)
554			.copied()
555			.or_else(|| self.variadic_output.map(|(kind, _)| kind))
556	}
557
558	pub(crate) const fn mutates_input(self, index: usize) -> bool {
559		(index < Self::MAX_VALUES && self.mutated_input_mask & (1 << index) != 0)
560			|| (self.aligned_variadic_aliases && index >= self.input_kinds.len())
561	}
562
563	pub(crate) const fn input_is_optional(self, index: usize) -> bool {
564		index < Self::MAX_VALUES && self.optional_input_mask & (1 << index) != 0
565	}
566
567	pub(crate) fn alias_input(self, output: usize) -> Option<usize> {
568		let fixed = self
569			.output_alias_inputs
570			.get(output)
571			.copied()
572			.flatten()
573			.map(usize::from);
574		fixed.or_else(|| {
575			(self.aligned_variadic_aliases && output >= self.output_kinds.len())
576				.then(|| self.input_kinds.len() + (output - self.output_kinds.len()))
577		})
578	}
579
580	pub(crate) fn variadic_alias_counts_match(self, input_count: usize, output_count: usize) -> bool {
581		!self.aligned_variadic_aliases
582			|| input_count.saturating_sub(self.input_kinds.len())
583				== output_count.saturating_sub(self.output_kinds.len())
584	}
585
586	pub(crate) fn validate(self, attributes: &[OpAttribute]) -> bool {
587		if self.name.is_empty()
588			|| self.hash == 0
589			|| self.input_kinds.len() > Self::MAX_VALUES
590			|| self.output_kinds.len() > Self::MAX_VALUES
591			|| self.attributes.len() > Self::MAX_ATTRIBUTES
592			|| attributes.len() != self.attributes.len()
593		{
594			return false;
595		}
596		let input_mask = if self.input_kinds.is_empty() {
597			0
598		} else {
599			((1_u16 << self.input_kinds.len()) - 1) as u8
600		};
601		if self.variadic_input.is_some_and(|(_, minimum)| minimum == 0)
602			|| self
603				.variadic_output
604				.is_some_and(|(_, minimum)| minimum == 0)
605			|| self.optional_input_mask & !input_mask != 0
606			|| self.mutated_input_mask & !input_mask != 0
607			|| self.optional_input_mask & self.mutated_input_mask != 0
608		{
609			return false;
610		}
611		if self.aligned_variadic_aliases
612			&& (!matches!(
613				(self.variadic_input, self.variadic_output),
614				(Some((input, input_minimum)), Some((output, output_minimum)))
615					if input == output && input_minimum == output_minimum
616			) || !self.effects.contains(OpEffect::WRITE_OUTPUTS))
617		{
618			return false;
619		}
620		for (output, alias) in self.output_alias_inputs.iter().copied().enumerate() {
621			let Some(input) = alias else { continue };
622			let input = usize::from(input);
623			if output >= self.output_kinds.len() || input >= self.input_kinds.len() {
624				return false;
625			}
626		}
627		for input in 0..self.input_kinds.len() {
628			if self.mutates_input(input)
629				&& self
630					.output_alias_inputs
631					.iter()
632					.take(self.output_kinds.len())
633					.filter(|alias| alias.is_some_and(|alias| usize::from(alias) == input))
634					.count()
635					!= 1
636			{
637				return false;
638			}
639		}
640		attributes.iter().zip(self.attributes).all(|(value, spec)| {
641			value.validate() && value.name() == spec.name && value.kind() == spec.kind
642		})
643	}
644
645	pub(crate) const fn effects_value(self) -> OpEffect {
646		self.effects
647	}
648
649	pub(crate) const fn optional_input_mask(self) -> u8 {
650		self.optional_input_mask
651	}
652}