1use bitflags::bitflags;
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub enum BufferAccess {
12 Read,
14 Write,
16 ReadWrite,
18}
19
20#[non_exhaustive]
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub enum OpValueKind {
24 Matrix,
26 Image,
28 Audio,
30 VideoFrame,
32 QuantMatrix,
34 Texture,
36}
37
38impl OpValueKind {
39 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#[non_exhaustive]
54#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
55pub enum OpShapeRule {
56 #[default]
58 MatchInput,
59 Broadcast,
61 MatmulNt,
63 Explicit,
65}
66
67#[non_exhaustive]
69#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
70pub enum OpDTypeRule {
71 #[default]
73 MatchInput,
74 PromoteFloat,
76 Explicit,
78}
79
80#[non_exhaustive]
82#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
83pub enum OpDifferentiation {
84 #[default]
86 None,
87 Reverse,
89}
90
91impl OpDifferentiation {
92 pub const fn token(self) -> &'static str {
94 match self {
95 Self::None => "none",
96 Self::Reverse => "reverse",
97 }
98 }
99}
100
101#[non_exhaustive]
103#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
104pub enum OpLowering {
105 #[default]
107 Dispatch,
108 Gemm,
110}
111
112impl OpLowering {
113 pub const fn token(self) -> &'static str {
115 match self {
116 Self::Dispatch => "dispatch",
117 Self::Gemm => "gemm",
118 }
119 }
120}
121
122#[non_exhaustive]
130#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
131pub enum OpFusionClass {
132 Pointwise,
134 Broadcast,
136 Gather,
138 Reduce,
140 Scan,
142 Gemm,
144 Conv,
146 Attention,
148 #[default]
151 Opaque,
152 Effect,
155}
156
157impl OpFusionClass {
158 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 pub const fn is_region_admitted(self) -> bool {
176 !matches!(self, Self::Opaque | Self::Effect)
177 }
178}
179
180#[non_exhaustive]
182#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
183pub enum OpControlFlow {
184 #[default]
186 StraightLine,
187 Conditional,
189 Loop,
191}
192
193impl OpControlFlow {
194 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 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
207 pub struct OpEffect: u8 {
208 const READ_INPUTS = 1 << 0;
210 const WRITE_OUTPUTS = 1 << 1;
212 }
213}
214
215#[non_exhaustive]
217#[derive(Clone, Copy, Debug, PartialEq, Eq)]
218pub enum OpAttributeKind {
219 Boolean,
221 SignedInteger,
223 UnsignedInteger,
225 Float,
227 String,
229 Shape,
231 Enum,
233}
234
235impl OpAttributeKind {
236 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#[non_exhaustive]
252#[derive(Clone, Debug, PartialEq)]
253pub enum OpAttribute {
254 Boolean { name: String, value: bool },
256 SignedInteger { name: String, value: i64 },
258 UnsignedInteger { name: String, value: u64 },
260 Float { name: String, value: f64 },
262 String { name: String, value: String },
264 Shape { name: String, value: Vec<usize> },
266 Enum { name: String, value: String },
268}
269
270impl OpAttribute {
271 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
304pub struct OpAttributeSpec {
305 name: &'static str,
306 kind: OpAttributeKind,
307}
308
309impl OpAttributeSpec {
310 pub const fn new(name: &'static str, kind: OpAttributeKind) -> Self {
312 Self { name, kind }
313 }
314
315 pub const fn name(self) -> &'static str {
317 self.name
318 }
319
320 pub const fn kind(self) -> OpAttributeKind {
322 self.kind
323 }
324}
325
326#[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 pub const MAX_VALUES: usize = 8;
356 pub const MAX_ATTRIBUTES: usize = 16;
358
359 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 pub const fn variadic_inputs(mut self, kind: OpValueKind, minimum: usize) -> Self {
390 self.variadic_input = Some((kind, minimum));
391 self
392 }
393
394 pub const fn variadic_outputs(mut self, kind: OpValueKind, minimum: usize) -> Self {
396 self.variadic_output = Some((kind, minimum));
397 self
398 }
399
400 pub const fn aligned_variadic_aliases(mut self) -> Self {
403 self.aligned_variadic_aliases = true;
404 self
405 }
406
407 pub const fn attributes(mut self, attributes: &'static [OpAttributeSpec]) -> Self {
409 self.attributes = attributes;
410 self
411 }
412
413 pub const fn with_differentiation(mut self, value: OpDifferentiation) -> Self {
415 self.differentiation = value;
416 self
417 }
418
419 pub const fn with_shape_rule(mut self, value: OpShapeRule) -> Self {
421 self.shape_rule = value;
422 self
423 }
424
425 pub const fn with_dtype_rule(mut self, value: OpDTypeRule) -> Self {
427 self.dtype_rule = value;
428 self
429 }
430
431 pub const fn with_lowering(mut self, value: OpLowering) -> Self {
433 self.lowering = value;
434 self
435 }
436
437 pub const fn with_fusion_class(mut self, value: OpFusionClass) -> Self {
439 self.fusion_class = value;
440 self
441 }
442
443 pub const fn effects(mut self, value: OpEffect) -> Self {
445 self.effects = value;
446 self
447 }
448
449 pub const fn mutated_inputs(mut self, mask: u8) -> Self {
451 self.mutated_input_mask = mask;
452 self
453 }
454
455 pub const fn optional_inputs(mut self, mask: u8) -> Self {
457 self.optional_input_mask = mask;
458 self
459 }
460
461 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 pub const fn with_control_flow(mut self, value: OpControlFlow) -> Self {
477 self.control_flow = value;
478 self
479 }
480
481 pub const fn name(self) -> &'static str {
483 self.name
484 }
485
486 pub const fn hash(self) -> u64 {
488 self.hash
489 }
490
491 pub const fn differentiation(self) -> OpDifferentiation {
493 self.differentiation
494 }
495
496 pub const fn shape_rule(self) -> OpShapeRule {
498 self.shape_rule
499 }
500
501 pub const fn dtype_rule(self) -> OpDTypeRule {
503 self.dtype_rule
504 }
505
506 pub const fn attribute_specs(self) -> &'static [OpAttributeSpec] {
508 self.attributes
509 }
510
511 pub const fn lowering(self) -> OpLowering {
513 self.lowering
514 }
515
516 pub const fn fusion_class(self) -> OpFusionClass {
518 self.fusion_class
519 }
520
521 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}