tidu/rules/
primitive_builder.rs1use computegraph::{GraphOperation, LocalValueId, OperationRole, ValueKey, ValueRef};
2
3#[derive(Clone, Debug, PartialEq, Eq, Hash)]
5pub enum PrimitiveValue<Op: GraphOperation> {
6 Local(LocalValueId),
8 External(computegraph::ValueKey<Op>),
10}
11
12#[derive(Clone, Debug, PartialEq, Eq, Hash)]
21pub enum PrimitiveTransposeInput<Op: GraphOperation> {
22 Residual(ValueKey<Op>),
24 Linear {
26 key: ValueKey<Op>,
28 primal: Option<ValueKey<Op>>,
30 },
31}
32
33impl<Op: GraphOperation> PrimitiveTransposeInput<Op> {
34 pub fn key(&self) -> &ValueKey<Op> {
36 match self {
37 Self::Residual(key) | Self::Linear { key, .. } => key,
38 }
39 }
40
41 pub fn primal(&self) -> Option<&ValueKey<Op>> {
43 match self {
44 Self::Residual(_) => None,
45 Self::Linear { primal, .. } => primal.as_ref(),
46 }
47 }
48
49 pub fn as_residual_value(&self) -> Option<PrimitiveValue<Op>> {
51 match self {
52 Self::Residual(key) => Some(PrimitiveValue::External(key.clone())),
53 Self::Linear { .. } => None,
54 }
55 }
56}
57
58impl<Op: GraphOperation> From<PrimitiveValue<Op>> for ValueRef<Op> {
59 fn from(value: PrimitiveValue<Op>) -> Self {
60 match value {
61 PrimitiveValue::Local(id) => ValueRef::Local(id),
62 PrimitiveValue::External(key) => ValueRef::External(key),
63 }
64 }
65}
66
67impl<Op: GraphOperation> From<ValueRef<Op>> for PrimitiveValue<Op> {
68 fn from(value: ValueRef<Op>) -> Self {
69 match value {
70 ValueRef::Local(id) => PrimitiveValue::Local(id),
71 ValueRef::External(key) => PrimitiveValue::External(key),
72 }
73 }
74}
75
76pub trait PrimitiveBuilder<Op: GraphOperation> {
78 fn add_primitive(
80 &mut self,
81 op: Op,
82 inputs: Vec<PrimitiveValue<Op>>,
83 role: OperationRole,
84 ) -> Vec<LocalValueId>;
85}
86
87#[cfg(test)]
88mod tests;