1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
//! Semantic-program automatic-differentiation rules for extension operations.
//!
//! Rules in this module are owned explicitly by [`crate::AdContext`]. They
//! operate on opaque semantic [`ProgramValue`] tokens and never expose
//! computegraph node keys or execution-program slots.
use std::collections::HashMap;
use std::fmt::Debug;
use std::sync::Arc;
pub use tenferro_ops::ad::ResidualSpec;
use tenferro_ops::ext_op::ExtensionOp;
use tenferro_runtime::program::{
ProgramBuildError, ProgramValue, ProgramValueMetadata, SemanticOpRef, SemanticOperationView,
SemanticProgramBuilder, SemanticProvenanceView,
};
/// One optional semantic AD value.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AdValue {
/// This primal, tangent, or cotangent is inactive.
Absent,
/// Active value owned by the destination semantic-program builder.
Value(ProgramValue),
}
impl AdValue {
/// Return the active semantic value, if present.
#[must_use]
pub const fn value(self) -> Option<ProgramValue> {
match self {
Self::Absent => None,
Self::Value(value) => Some(value),
}
}
}
/// Semantic extension AD rule role.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SemanticAdRuleRole {
/// Definitional forward linearization.
Linearize,
/// Transpose of a linearized extension operation.
LinearTranspose,
/// Direct reverse rule expressed against primal values.
PrimalVjp,
}
/// Registration failures for semantic extension AD rules.
#[derive(Debug, thiserror::Error)]
pub enum SemanticExtensionRegistryError {
/// A rule with the same family and role is already present.
#[error("semantic extension AD {role:?} rule for family {family_id:?} is already registered")]
DuplicateRule {
/// Duplicate extension family identifier.
family_id: &'static str,
/// Duplicate semantic AD role.
role: SemanticAdRuleRole,
},
/// A rule family is not a namespaced, versioned identifier.
#[error("semantic extension AD family {family_id:?} is not namespaced and versioned")]
MalformedFamilyId {
/// Invalid extension family identifier.
family_id: &'static str,
},
}
/// Whether a checked semantic AD request refers to a primal input or output.
///
/// # Examples
///
/// ```
/// use tenferro_ad::semantic_extension::PrimalValueKind;
///
/// assert_eq!(format!("{:?}", PrimalValueKind::Input), "Input");
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum PrimalValueKind {
/// An ordered primal input.
Input,
/// An ordered primal output.
Output,
}
/// Failures while dispatching or building semantic extension AD.
#[derive(Debug, thiserror::Error)]
pub enum SemanticAdError {
/// The supplied operation is not an extension operation.
#[error("semantic AD extension dispatch received a core operation")]
CoreOperation,
/// Observable effects make implicit differentiation unsafe.
#[error("semantic extension family {family_id:?} has observable effects")]
EffectfulExtension {
/// Effectful extension family.
family_id: &'static str,
},
/// No rule is registered for the requested family and role.
#[error("semantic extension family {family_id:?} has no {role:?} AD rule")]
MissingRule {
/// Extension family without a rule.
family_id: &'static str,
/// Missing semantic AD role.
role: SemanticAdRuleRole,
},
/// An ordered request or result field has the wrong length.
#[error("semantic AD field {field} expects {expected} values, got {actual}")]
Arity {
/// Name of the invalid ordered field.
field: &'static str,
/// Required field length.
expected: usize,
/// Supplied field length.
actual: usize,
},
/// A checked primal value index is outside the request's ordered values.
#[error(
"semantic extension family {family_id:?} {kind:?} index {index} is out of bounds for length {len}"
)]
PrimalIndexOutOfBounds {
/// Extension family that owns the request.
family_id: &'static str,
/// Ordered primal collection being accessed.
kind: PrimalValueKind,
/// Requested index.
index: usize,
/// Number of values in the collection.
len: usize,
},
/// A checked primal value was not declared as a tensor residual by the rule.
#[error(
"semantic extension family {family_id:?} may not access undeclared {kind:?} residual value {index}"
)]
UndeclaredResidualValue {
/// Extension family that owns the request.
family_id: &'static str,
/// Ordered primal collection being accessed.
kind: PrimalValueKind,
/// Requested index.
index: usize,
},
/// A request or result value belongs to another builder.
#[error("semantic AD field {field}[{index}] does not belong to the destination builder")]
ForeignValue {
/// Name of the invalid ordered field.
field: &'static str,
/// Index of the foreign value.
index: usize,
},
/// A family-specific rule deliberately rejects this payload.
#[error("semantic extension family {family_id:?} does not support {role:?}: {message}")]
Unsupported {
/// Extension family that rejected the transform.
family_id: &'static str,
/// Rejected semantic AD role.
role: SemanticAdRuleRole,
/// Bounded family-specific diagnostic.
message: String,
},
/// A family-specific rule failed with a typed source error.
#[error("semantic extension family {family_id:?} {role:?} rule failed: {source}")]
Rule {
/// Extension family whose rule failed.
family_id: &'static str,
/// Semantic AD role being evaluated.
role: SemanticAdRuleRole,
/// Original typed rule failure.
#[source]
source: Box<dyn std::error::Error + Send + Sync + 'static>,
},
/// A family-specific semantic rule invariant was violated.
#[error("semantic extension family {family_id:?} {role:?} invariant failed: {message}")]
Invariant {
/// Extension family whose invariant failed.
family_id: &'static str,
/// Semantic AD role being evaluated.
role: SemanticAdRuleRole,
/// Bounded invariant diagnostic.
message: String,
},
/// Semantic-program construction failed inside a rule.
#[error("semantic extension AD program construction failed: {0}")]
Build(#[from] ProgramBuildError),
}
/// Ordered inputs for one semantic extension linearization rule.
#[derive(Clone, Copy)]
pub struct SemanticLinearizeRequest<'a> {
op: &'a dyn ExtensionOp,
primal_inputs: &'a [ProgramValue],
primal_outputs: &'a [ProgramValue],
tangent_inputs: &'a [AdValue],
active_outputs: &'a [bool],
provenance: SemanticProvenanceView<'a>,
}
impl<'a> SemanticLinearizeRequest<'a> {
/// Borrow the extension payload.
pub const fn op(self) -> &'a dyn ExtensionOp {
self.op
}
/// Borrow ordered destination-local primal inputs.
pub const fn primal_inputs(self) -> &'a [ProgramValue] {
self.primal_inputs
}
/// Borrow ordered destination-local primal outputs.
pub const fn primal_outputs(self) -> &'a [ProgramValue] {
self.primal_outputs
}
/// Borrow ordered optional tangent inputs.
pub const fn tangent_inputs(self) -> &'a [AdValue] {
self.tangent_inputs
}
/// Borrow the ordered active-output mask.
pub const fn active_outputs(self) -> &'a [bool] {
self.active_outputs
}
/// Return bounded operation provenance.
pub const fn provenance(self) -> SemanticProvenanceView<'a> {
self.provenance
}
}
/// Output of one semantic extension linearization rule.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SemanticLinearizeResult {
tangent_outputs: Box<[AdValue]>,
residuals: Box<[ProgramValue]>,
}
impl SemanticLinearizeResult {
/// Construct ordered tangent outputs and residuals.
#[must_use]
pub fn new(
tangent_outputs: impl IntoIterator<Item = AdValue>,
residuals: impl IntoIterator<Item = ProgramValue>,
) -> Self {
Self {
tangent_outputs: tangent_outputs.into_iter().collect(),
residuals: residuals.into_iter().collect(),
}
}
/// Borrow ordered optional tangent outputs.
pub fn tangent_outputs(&self) -> &[AdValue] {
&self.tangent_outputs
}
/// Borrow ordered residual values saved for transpose.
pub fn residuals(&self) -> &[ProgramValue] {
&self.residuals
}
}
/// Ordered inputs for one semantic linear-transpose rule.
pub struct SemanticLinearTransposeRequest<'a> {
op: &'a dyn ExtensionOp,
primal_inputs: &'a [ProgramValue],
primal_outputs: &'a [ProgramValue],
primal_input_metadata: Box<[ProgramValueMetadata]>,
primal_output_metadata: Box<[ProgramValueMetadata]>,
cotangent_outputs: &'a [AdValue],
active_inputs: &'a [bool],
residuals: &'a [ProgramValue],
residual_mask: ResidualSpec,
provenance: SemanticProvenanceView<'a>,
}
impl<'a> SemanticLinearTransposeRequest<'a> {
/// Borrow the extension payload.
///
/// # Examples
///
/// ```rust
/// # use tenferro_ad::semantic_extension::{SemanticAdError, SemanticLinearTransposeRequest};
/// # fn inspect(request: &SemanticLinearTransposeRequest<'_>) -> Result<(), SemanticAdError> {
/// let _ = request.op().family_id();
/// # Ok(())
/// # }
/// ```
pub fn op(&self) -> &dyn ExtensionOp {
self.op
}
/// Return one declared primal input tensor value.
///
/// # Errors
///
/// Returns [`SemanticAdError::PrimalIndexOutOfBounds`] before checking the
/// residual mask, or [`SemanticAdError::UndeclaredResidualValue`] when the
/// rule did not declare this input as a tensor residual.
///
/// # Examples
///
/// ```rust
/// # use tenferro_ad::semantic_extension::{SemanticAdError, SemanticLinearTransposeRequest};
/// # fn inspect(request: &SemanticLinearTransposeRequest<'_>) -> Result<(), SemanticAdError> {
/// let _ = request.primal_input_value(0)?;
/// # Ok(())
/// # }
/// ```
pub fn primal_input_value(&self, index: usize) -> Result<ProgramValue, SemanticAdError> {
checked_primal_value(
self.op.family_id(),
PrimalValueKind::Input,
index,
self.primal_inputs,
self.residual_mask,
)
}
/// Return one declared primal output tensor value.
///
/// # Errors
///
/// Returns [`SemanticAdError::PrimalIndexOutOfBounds`] before checking the
/// residual mask, or [`SemanticAdError::UndeclaredResidualValue`] when the
/// rule did not declare this output as a tensor residual.
///
/// # Examples
///
/// ```rust
/// # use tenferro_ad::semantic_extension::{SemanticAdError, SemanticLinearTransposeRequest};
/// # fn inspect(request: &SemanticLinearTransposeRequest<'_>) -> Result<(), SemanticAdError> {
/// let _ = request.primal_output_value(0)?;
/// # Ok(())
/// # }
/// ```
pub fn primal_output_value(&self, index: usize) -> Result<ProgramValue, SemanticAdError> {
checked_primal_value(
self.op.family_id(),
PrimalValueKind::Output,
index,
self.primal_outputs,
self.residual_mask,
)
}
/// Borrow metadata for one primal input without exposing its value token.
///
/// # Errors
///
/// Returns [`SemanticAdError::PrimalIndexOutOfBounds`] when `index` is not
/// an ordered primal input.
///
/// # Examples
///
/// ```rust
/// # use tenferro_ad::semantic_extension::{SemanticAdError, SemanticLinearTransposeRequest};
/// # fn inspect(request: &SemanticLinearTransposeRequest<'_>) -> Result<(), SemanticAdError> {
/// let _ = request.primal_input_meta(0)?;
/// # Ok(())
/// # }
/// ```
pub fn primal_input_meta(
&self,
index: usize,
) -> Result<&ProgramValueMetadata, SemanticAdError> {
checked_primal_metadata(
self.op.family_id(),
PrimalValueKind::Input,
index,
&self.primal_input_metadata,
)
}
/// Borrow metadata for one primal output without exposing its value token.
///
/// # Errors
///
/// Returns [`SemanticAdError::PrimalIndexOutOfBounds`] when `index` is not
/// an ordered primal output.
///
/// # Examples
///
/// ```rust
/// # use tenferro_ad::semantic_extension::{SemanticAdError, SemanticLinearTransposeRequest};
/// # fn inspect(request: &SemanticLinearTransposeRequest<'_>) -> Result<(), SemanticAdError> {
/// let _ = request.primal_output_meta(0)?;
/// # Ok(())
/// # }
/// ```
pub fn primal_output_meta(
&self,
index: usize,
) -> Result<&ProgramValueMetadata, SemanticAdError> {
checked_primal_metadata(
self.op.family_id(),
PrimalValueKind::Output,
index,
&self.primal_output_metadata,
)
}
/// Return the number of ordered primal inputs.
#[must_use]
///
/// # Examples
///
/// ```rust
/// # use tenferro_ad::semantic_extension::{SemanticAdError, SemanticLinearTransposeRequest};
/// # fn inspect(request: &SemanticLinearTransposeRequest<'_>) -> Result<(), SemanticAdError> {
/// let _ = request.primal_input_count();
/// # Ok(())
/// # }
/// ```
pub const fn primal_input_count(&self) -> usize {
self.primal_input_metadata.len()
}
/// Return the number of ordered primal outputs.
#[must_use]
///
/// # Examples
///
/// ```rust
/// # use tenferro_ad::semantic_extension::{SemanticAdError, SemanticLinearTransposeRequest};
/// # fn inspect(request: &SemanticLinearTransposeRequest<'_>) -> Result<(), SemanticAdError> {
/// let _ = request.primal_output_count();
/// # Ok(())
/// # }
/// ```
pub const fn primal_output_count(&self) -> usize {
self.primal_output_metadata.len()
}
/// Borrow ordered optional output cotangents.
///
/// # Examples
///
/// ```rust
/// # use tenferro_ad::semantic_extension::{SemanticAdError, SemanticLinearTransposeRequest};
/// # fn inspect(request: &SemanticLinearTransposeRequest<'_>) -> Result<(), SemanticAdError> {
/// let _ = request.cotangent_outputs();
/// # Ok(())
/// # }
/// ```
pub fn cotangent_outputs(&self) -> &[AdValue] {
self.cotangent_outputs
}
/// Borrow the ordered active-input mask.
///
/// # Examples
///
/// ```rust
/// # use tenferro_ad::semantic_extension::{SemanticAdError, SemanticLinearTransposeRequest};
/// # fn inspect(request: &SemanticLinearTransposeRequest<'_>) -> Result<(), SemanticAdError> {
/// let _ = request.active_inputs();
/// # Ok(())
/// # }
/// ```
pub fn active_inputs(&self) -> &[bool] {
self.active_inputs
}
/// Borrow ordered residuals produced by linearization.
///
/// # Examples
///
/// ```rust
/// # use tenferro_ad::semantic_extension::{SemanticAdError, SemanticLinearTransposeRequest};
/// # fn inspect(request: &SemanticLinearTransposeRequest<'_>) -> Result<(), SemanticAdError> {
/// let _ = request.residuals();
/// # Ok(())
/// # }
/// ```
pub fn residuals(&self) -> &[ProgramValue] {
self.residuals
}
/// Return this rule's declared residual mask: which primal input/output
/// indices may be read as tensor values. Accesses outside the mask must
/// only use shape/dtype metadata.
///
/// # Examples
///
/// ```rust
/// # use tenferro_ad::semantic_extension::{SemanticAdError, SemanticLinearTransposeRequest};
/// # fn inspect(request: &SemanticLinearTransposeRequest<'_>) -> Result<(), SemanticAdError> {
/// let _ = request.residual_mask();
/// # Ok(())
/// # }
/// ```
pub const fn residual_mask(&self) -> ResidualSpec {
self.residual_mask
}
/// Return bounded operation provenance.
///
/// # Examples
///
/// ```rust
/// # use tenferro_ad::semantic_extension::{SemanticAdError, SemanticLinearTransposeRequest};
/// # fn inspect(request: &SemanticLinearTransposeRequest<'_>) -> Result<(), SemanticAdError> {
/// let _ = request.provenance();
/// # Ok(())
/// # }
/// ```
pub const fn provenance(&self) -> SemanticProvenanceView<'a> {
self.provenance
}
}
/// Ordered inputs for one direct semantic primal-VJP rule.
pub struct SemanticPrimalVjpRequest<'a> {
op: &'a dyn ExtensionOp,
primal_inputs: &'a [ProgramValue],
primal_outputs: &'a [ProgramValue],
primal_input_metadata: Box<[ProgramValueMetadata]>,
primal_output_metadata: Box<[ProgramValueMetadata]>,
cotangent_outputs: &'a [AdValue],
active_inputs: &'a [bool],
residual_mask: ResidualSpec,
provenance: SemanticProvenanceView<'a>,
}
impl<'a> SemanticPrimalVjpRequest<'a> {
/// Borrow the extension payload.
///
/// # Examples
///
/// ```rust
/// # use tenferro_ad::semantic_extension::{SemanticAdError, SemanticPrimalVjpRequest};
/// # fn inspect(request: &SemanticPrimalVjpRequest<'_>) -> Result<(), SemanticAdError> {
/// let _ = request.op().family_id();
/// # Ok(())
/// # }
/// ```
pub fn op(&self) -> &dyn ExtensionOp {
self.op
}
/// Return one declared primal input tensor value.
///
/// # Errors
///
/// Returns [`SemanticAdError::PrimalIndexOutOfBounds`] before checking the
/// residual mask, or [`SemanticAdError::UndeclaredResidualValue`] when the
/// rule did not declare this input as a tensor residual.
///
/// # Examples
///
/// ```rust
/// # use tenferro_ad::semantic_extension::{SemanticAdError, SemanticPrimalVjpRequest};
/// # fn inspect(request: &SemanticPrimalVjpRequest<'_>) -> Result<(), SemanticAdError> {
/// let _ = request.primal_input_value(0)?;
/// # Ok(())
/// # }
/// ```
pub fn primal_input_value(&self, index: usize) -> Result<ProgramValue, SemanticAdError> {
checked_primal_value(
self.op.family_id(),
PrimalValueKind::Input,
index,
self.primal_inputs,
self.residual_mask,
)
}
/// Return one declared primal output tensor value.
///
/// # Errors
///
/// Returns [`SemanticAdError::PrimalIndexOutOfBounds`] before checking the
/// residual mask, or [`SemanticAdError::UndeclaredResidualValue`] when the
/// rule did not declare this output as a tensor residual.
///
/// # Examples
///
/// ```rust
/// # use tenferro_ad::semantic_extension::{SemanticAdError, SemanticPrimalVjpRequest};
/// # fn inspect(request: &SemanticPrimalVjpRequest<'_>) -> Result<(), SemanticAdError> {
/// let _ = request.primal_output_value(0)?;
/// # Ok(())
/// # }
/// ```
pub fn primal_output_value(&self, index: usize) -> Result<ProgramValue, SemanticAdError> {
checked_primal_value(
self.op.family_id(),
PrimalValueKind::Output,
index,
self.primal_outputs,
self.residual_mask,
)
}
/// Borrow metadata for one primal input without exposing its value token.
///
/// # Errors
///
/// Returns [`SemanticAdError::PrimalIndexOutOfBounds`] when `index` is not
/// an ordered primal input.
///
/// # Examples
///
/// ```rust
/// # use tenferro_ad::semantic_extension::{SemanticAdError, SemanticPrimalVjpRequest};
/// # fn inspect(request: &SemanticPrimalVjpRequest<'_>) -> Result<(), SemanticAdError> {
/// let _ = request.primal_input_meta(0)?;
/// # Ok(())
/// # }
/// ```
pub fn primal_input_meta(
&self,
index: usize,
) -> Result<&ProgramValueMetadata, SemanticAdError> {
checked_primal_metadata(
self.op.family_id(),
PrimalValueKind::Input,
index,
&self.primal_input_metadata,
)
}
/// Borrow metadata for one primal output without exposing its value token.
///
/// # Errors
///
/// Returns [`SemanticAdError::PrimalIndexOutOfBounds`] when `index` is not
/// an ordered primal output.
///
/// # Examples
///
/// ```rust
/// # use tenferro_ad::semantic_extension::{SemanticAdError, SemanticPrimalVjpRequest};
/// # fn inspect(request: &SemanticPrimalVjpRequest<'_>) -> Result<(), SemanticAdError> {
/// let _ = request.primal_output_meta(0)?;
/// # Ok(())
/// # }
/// ```
pub fn primal_output_meta(
&self,
index: usize,
) -> Result<&ProgramValueMetadata, SemanticAdError> {
checked_primal_metadata(
self.op.family_id(),
PrimalValueKind::Output,
index,
&self.primal_output_metadata,
)
}
/// Return the number of ordered primal inputs.
#[must_use]
///
/// # Examples
///
/// ```rust
/// # use tenferro_ad::semantic_extension::{SemanticAdError, SemanticPrimalVjpRequest};
/// # fn inspect(request: &SemanticPrimalVjpRequest<'_>) -> Result<(), SemanticAdError> {
/// let _ = request.primal_input_count();
/// # Ok(())
/// # }
/// ```
pub const fn primal_input_count(&self) -> usize {
self.primal_input_metadata.len()
}
/// Return the number of ordered primal outputs.
#[must_use]
///
/// # Examples
///
/// ```rust
/// # use tenferro_ad::semantic_extension::{SemanticAdError, SemanticPrimalVjpRequest};
/// # fn inspect(request: &SemanticPrimalVjpRequest<'_>) -> Result<(), SemanticAdError> {
/// let _ = request.primal_output_count();
/// # Ok(())
/// # }
/// ```
pub const fn primal_output_count(&self) -> usize {
self.primal_output_metadata.len()
}
/// Borrow ordered optional output cotangents.
///
/// # Examples
///
/// ```rust
/// # use tenferro_ad::semantic_extension::{SemanticAdError, SemanticPrimalVjpRequest};
/// # fn inspect(request: &SemanticPrimalVjpRequest<'_>) -> Result<(), SemanticAdError> {
/// let _ = request.cotangent_outputs();
/// # Ok(())
/// # }
/// ```
pub fn cotangent_outputs(&self) -> &[AdValue] {
self.cotangent_outputs
}
/// Borrow the ordered active-input mask.
///
/// # Examples
///
/// ```rust
/// # use tenferro_ad::semantic_extension::{SemanticAdError, SemanticPrimalVjpRequest};
/// # fn inspect(request: &SemanticPrimalVjpRequest<'_>) -> Result<(), SemanticAdError> {
/// let _ = request.active_inputs();
/// # Ok(())
/// # }
/// ```
pub fn active_inputs(&self) -> &[bool] {
self.active_inputs
}
/// Return this rule's declared residual mask: which primal input/output
/// indices may be read as tensor values. Accesses outside the mask must
/// only use shape/dtype metadata.
///
/// # Examples
///
/// ```rust
/// # use tenferro_ad::semantic_extension::{SemanticAdError, SemanticPrimalVjpRequest};
/// # fn inspect(request: &SemanticPrimalVjpRequest<'_>) -> Result<(), SemanticAdError> {
/// let _ = request.residual_mask();
/// # Ok(())
/// # }
/// ```
pub const fn residual_mask(&self) -> ResidualSpec {
self.residual_mask
}
/// Return bounded operation provenance.
///
/// # Examples
///
/// ```rust
/// # use tenferro_ad::semantic_extension::{SemanticAdError, SemanticPrimalVjpRequest};
/// # fn inspect(request: &SemanticPrimalVjpRequest<'_>) -> Result<(), SemanticAdError> {
/// let _ = request.provenance();
/// # Ok(())
/// # }
/// ```
pub const fn provenance(&self) -> SemanticProvenanceView<'a> {
self.provenance
}
}
/// Definitional JVP rule for one extension family.
pub trait SemanticLinearizeRule: Debug + Send + Sync + 'static {
/// Return the versioned extension family handled by this rule.
fn family_id(&self) -> &'static str;
/// Emit ordered tangent outputs and residuals into `builder`.
///
/// # Errors
///
/// Returns [`SemanticAdError::Unsupported`] when the payload is outside
/// the rule's supported domain, or [`SemanticAdError::Build`] when emitted
/// semantic operations fail validation.
fn linearize(
&self,
request: SemanticLinearizeRequest<'_>,
builder: &mut SemanticProgramBuilder,
) -> Result<SemanticLinearizeResult, SemanticAdError>;
}
/// Transpose rule for an extension viewed as a linear map.
pub trait SemanticLinearTransposeRule: Debug + Send + Sync + 'static {
/// Return the versioned extension family handled by this rule.
fn family_id(&self) -> &'static str;
/// Declare which primal input/output indices this rule reads as tensor
/// residuals. Indices not declared may only be accessed through metadata.
fn residual_mask(&self) -> ResidualSpec;
/// Emit ordered optional input cotangents into `builder`.
///
/// # Errors
///
/// Returns [`SemanticAdError::Unsupported`] when the payload is outside
/// the rule's supported domain, or [`SemanticAdError::Build`] when emitted
/// semantic operations fail validation.
fn linear_transpose(
&self,
request: SemanticLinearTransposeRequest<'_>,
builder: &mut SemanticProgramBuilder,
) -> Result<Box<[AdValue]>, SemanticAdError>;
}
/// Optional direct VJP rule expressed against primal semantic values.
pub trait SemanticPrimalVjpRule: Debug + Send + Sync + 'static {
/// Return the versioned extension family handled by this rule.
fn family_id(&self) -> &'static str;
/// Declare which primal input/output indices this rule reads as tensor
/// residuals. Indices not declared may only be accessed through metadata.
fn residual_mask(&self) -> ResidualSpec;
/// Emit ordered optional input cotangents into `builder`.
///
/// # Errors
///
/// Returns [`SemanticAdError::Unsupported`] when the payload is outside
/// the rule's supported domain, or [`SemanticAdError::Build`] when emitted
/// semantic operations fail validation.
fn primal_vjp(
&self,
request: SemanticPrimalVjpRequest<'_>,
builder: &mut SemanticProgramBuilder,
) -> Result<Box<[AdValue]>, SemanticAdError>;
}
type LinearizeMap = HashMap<&'static str, Arc<dyn SemanticLinearizeRule>>;
type LinearTransposeMap = HashMap<&'static str, Arc<dyn SemanticLinearTransposeRule>>;
type PrimalVjpMap = HashMap<&'static str, Arc<dyn SemanticPrimalVjpRule>>;
/// Explicit clone-on-write set of semantic extension AD rules.
#[derive(Clone, Default)]
pub struct SemanticExtensionRuleSet {
linearize: Arc<LinearizeMap>,
linear_transpose: Arc<LinearTransposeMap>,
primal_vjp: Arc<PrimalVjpMap>,
}
impl Debug for SemanticExtensionRuleSet {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut linearize: Vec<_> = self.linearize.keys().copied().collect();
let mut linear_transpose: Vec<_> = self.linear_transpose.keys().copied().collect();
let mut primal_vjp: Vec<_> = self.primal_vjp.keys().copied().collect();
linearize.sort_unstable();
linear_transpose.sort_unstable();
primal_vjp.sort_unstable();
formatter
.debug_struct("SemanticExtensionRuleSet")
.field("linearize", &linearize)
.field("linear_transpose", &linear_transpose)
.field("primal_vjp", &primal_vjp)
.finish()
}
}
impl SemanticExtensionRuleSet {
/// Construct an empty rule set.
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Register one semantic linearize rule.
///
/// # Errors
///
/// Returns [`SemanticExtensionRegistryError::MalformedFamilyId`] for an
/// invalid family or [`SemanticExtensionRegistryError::DuplicateRule`] for
/// an existing family in this role.
pub fn register_linearize(
&mut self,
rule: Arc<dyn SemanticLinearizeRule>,
) -> Result<(), SemanticExtensionRegistryError> {
validate_insert(
&self.linearize,
rule.family_id(),
SemanticAdRuleRole::Linearize,
)?;
Arc::make_mut(&mut self.linearize).insert(rule.family_id(), rule);
Ok(())
}
/// Register one semantic linear-transpose rule.
///
/// # Errors
///
/// Returns [`SemanticExtensionRegistryError::MalformedFamilyId`] for an
/// invalid family or [`SemanticExtensionRegistryError::DuplicateRule`] for
/// an existing family in this role.
pub fn register_linear_transpose(
&mut self,
rule: Arc<dyn SemanticLinearTransposeRule>,
) -> Result<(), SemanticExtensionRegistryError> {
validate_insert(
&self.linear_transpose,
rule.family_id(),
SemanticAdRuleRole::LinearTranspose,
)?;
Arc::make_mut(&mut self.linear_transpose).insert(rule.family_id(), rule);
Ok(())
}
/// Register one direct semantic primal-VJP rule.
///
/// # Errors
///
/// Returns [`SemanticExtensionRegistryError::MalformedFamilyId`] for an
/// invalid family or [`SemanticExtensionRegistryError::DuplicateRule`] for
/// an existing family in this role.
pub fn register_primal_vjp(
&mut self,
rule: Arc<dyn SemanticPrimalVjpRule>,
) -> Result<(), SemanticExtensionRegistryError> {
validate_insert(
&self.primal_vjp,
rule.family_id(),
SemanticAdRuleRole::PrimalVjp,
)?;
Arc::make_mut(&mut self.primal_vjp).insert(rule.family_id(), rule);
Ok(())
}
/// Return a rule set containing one semantic linearize rule.
///
/// # Errors
///
/// Returns [`SemanticExtensionRegistryError::MalformedFamilyId`] for an
/// invalid family or [`SemanticExtensionRegistryError::DuplicateRule`] for
/// an existing linearize rule.
pub fn with_linearize(
mut self,
rule: Arc<dyn SemanticLinearizeRule>,
) -> Result<Self, SemanticExtensionRegistryError> {
self.register_linearize(rule)?;
Ok(self)
}
/// Return a rule set containing one semantic linear-transpose rule.
///
/// # Errors
///
/// Returns [`SemanticExtensionRegistryError::MalformedFamilyId`] for an
/// invalid family or [`SemanticExtensionRegistryError::DuplicateRule`] for
/// an existing linear-transpose rule.
pub fn with_linear_transpose(
mut self,
rule: Arc<dyn SemanticLinearTransposeRule>,
) -> Result<Self, SemanticExtensionRegistryError> {
self.register_linear_transpose(rule)?;
Ok(self)
}
/// Return a rule set containing one direct semantic primal-VJP rule.
///
/// # Errors
///
/// Returns [`SemanticExtensionRegistryError::MalformedFamilyId`] for an
/// invalid family or [`SemanticExtensionRegistryError::DuplicateRule`] for
/// an existing primal-VJP rule.
pub fn with_primal_vjp(
mut self,
rule: Arc<dyn SemanticPrimalVjpRule>,
) -> Result<Self, SemanticExtensionRegistryError> {
self.register_primal_vjp(rule)?;
Ok(self)
}
/// Merge another rule set atomically.
///
/// # Errors
///
/// Returns [`SemanticExtensionRegistryError::MalformedFamilyId`] for an
/// invalid family or [`SemanticExtensionRegistryError::DuplicateRule`] for
/// a role-equivalent duplicate. The receiver is unchanged on failure.
pub fn merge(&mut self, other: Self) -> Result<(), SemanticExtensionRegistryError> {
let mut candidate = self.clone();
for rule in other.linearize.values() {
candidate.register_linearize(Arc::clone(rule))?;
}
for rule in other.linear_transpose.values() {
candidate.register_linear_transpose(Arc::clone(rule))?;
}
for rule in other.primal_vjp.values() {
candidate.register_primal_vjp(Arc::clone(rule))?;
}
*self = candidate;
Ok(())
}
/// Look up a semantic linearize rule by extension family.
#[must_use]
pub fn lookup_linearize(&self, family_id: &str) -> Option<Arc<dyn SemanticLinearizeRule>> {
self.linearize.get(family_id).cloned()
}
/// Look up a semantic linear-transpose rule by extension family.
#[must_use]
pub fn lookup_linear_transpose(
&self,
family_id: &str,
) -> Option<Arc<dyn SemanticLinearTransposeRule>> {
self.linear_transpose.get(family_id).cloned()
}
/// Look up a direct semantic primal-VJP rule by extension family.
#[must_use]
pub fn lookup_primal_vjp(&self, family_id: &str) -> Option<Arc<dyn SemanticPrimalVjpRule>> {
self.primal_vjp.get(family_id).cloned()
}
/// Validate and dispatch one semantic extension linearization.
///
/// # Errors
///
/// Returns [`SemanticAdError::CoreOperation`] for a core operation,
/// [`SemanticAdError::EffectfulExtension`] before rule dispatch for an
/// effectful extension, or typed rule/arity/ownership/build failures.
#[allow(clippy::too_many_arguments)]
pub fn linearize_operation(
&self,
operation: SemanticOperationView<'_>,
primal_inputs: &[ProgramValue],
primal_outputs: &[ProgramValue],
tangent_inputs: &[AdValue],
active_outputs: &[bool],
builder: &mut SemanticProgramBuilder,
) -> Result<SemanticLinearizeResult, SemanticAdError> {
let op = extension_for_dispatch(operation)?;
validate_operation_inputs(operation, primal_inputs, primal_outputs, builder)?;
validate_len("tangent_inputs", op.input_count(), tangent_inputs.len())?;
validate_len("active_outputs", op.output_count(), active_outputs.len())?;
validate_ad_values("tangent_inputs", tangent_inputs, builder)?;
let rule = self
.lookup_linearize(op.family_id())
.ok_or(SemanticAdError::MissingRule {
family_id: op.family_id(),
role: SemanticAdRuleRole::Linearize,
})?;
let result = rule.linearize(
SemanticLinearizeRequest {
op,
primal_inputs,
primal_outputs,
tangent_inputs,
active_outputs,
provenance: operation.provenance(),
},
builder,
)?;
validate_len(
"tangent_outputs",
op.output_count(),
result.tangent_outputs.len(),
)?;
validate_ad_values("tangent_outputs", &result.tangent_outputs, builder)?;
validate_values("residuals", &result.residuals, builder)?;
Ok(result)
}
/// Validate and dispatch one semantic extension linear transpose.
///
/// # Errors
///
/// Returns [`SemanticAdError::EffectfulExtension`] before rule dispatch,
/// [`SemanticAdError::MissingRule`] when no transpose rule exists,
/// [`SemanticAdError::Arity`] / [`SemanticAdError::ForeignValue`] for an
/// invalid request or result, or a typed family-rule failure.
#[allow(clippy::too_many_arguments)]
pub fn linear_transpose_operation(
&self,
operation: SemanticOperationView<'_>,
primal_inputs: &[ProgramValue],
primal_outputs: &[ProgramValue],
cotangent_outputs: &[AdValue],
active_inputs: &[bool],
residuals: &[ProgramValue],
builder: &mut SemanticProgramBuilder,
) -> Result<Box<[AdValue]>, SemanticAdError> {
let op = extension_for_dispatch(operation)?;
validate_operation_inputs(operation, primal_inputs, primal_outputs, builder)?;
validate_len(
"cotangent_outputs",
op.output_count(),
cotangent_outputs.len(),
)?;
validate_len("active_inputs", op.input_count(), active_inputs.len())?;
validate_ad_values("cotangent_outputs", cotangent_outputs, builder)?;
validate_values("residuals", residuals, builder)?;
let primal_input_metadata = snapshot_metadata(primal_inputs, builder)?;
let primal_output_metadata = snapshot_metadata(primal_outputs, builder)?;
let rule =
self.lookup_linear_transpose(op.family_id())
.ok_or(SemanticAdError::MissingRule {
family_id: op.family_id(),
role: SemanticAdRuleRole::LinearTranspose,
})?;
let result = rule.linear_transpose(
SemanticLinearTransposeRequest {
op,
primal_inputs,
primal_outputs,
primal_input_metadata,
primal_output_metadata,
cotangent_outputs,
active_inputs,
residuals,
residual_mask: rule.residual_mask(),
provenance: operation.provenance(),
},
builder,
)?;
validate_len("cotangent_inputs", op.input_count(), result.len())?;
validate_ad_values("cotangent_inputs", &result, builder)?;
Ok(result)
}
/// Validate and dispatch one direct semantic primal VJP.
///
/// # Errors
///
/// Returns [`SemanticAdError::EffectfulExtension`] before rule dispatch,
/// [`SemanticAdError::MissingRule`] when no primal-VJP rule exists,
/// [`SemanticAdError::Arity`] / [`SemanticAdError::ForeignValue`] for an
/// invalid request or result, or a typed family-rule failure.
#[allow(clippy::too_many_arguments)]
pub fn primal_vjp_operation(
&self,
operation: SemanticOperationView<'_>,
primal_inputs: &[ProgramValue],
primal_outputs: &[ProgramValue],
cotangent_outputs: &[AdValue],
active_inputs: &[bool],
builder: &mut SemanticProgramBuilder,
) -> Result<Box<[AdValue]>, SemanticAdError> {
let op = extension_for_dispatch(operation)?;
validate_operation_inputs(operation, primal_inputs, primal_outputs, builder)?;
validate_len(
"cotangent_outputs",
op.output_count(),
cotangent_outputs.len(),
)?;
validate_len("active_inputs", op.input_count(), active_inputs.len())?;
validate_ad_values("cotangent_outputs", cotangent_outputs, builder)?;
let primal_input_metadata = snapshot_metadata(primal_inputs, builder)?;
let primal_output_metadata = snapshot_metadata(primal_outputs, builder)?;
let rule = self
.lookup_primal_vjp(op.family_id())
.ok_or(SemanticAdError::MissingRule {
family_id: op.family_id(),
role: SemanticAdRuleRole::PrimalVjp,
})?;
let result = rule.primal_vjp(
SemanticPrimalVjpRequest {
op,
primal_inputs,
primal_outputs,
primal_input_metadata,
primal_output_metadata,
cotangent_outputs,
active_inputs,
residual_mask: rule.residual_mask(),
provenance: operation.provenance(),
},
builder,
)?;
validate_len("cotangent_inputs", op.input_count(), result.len())?;
validate_ad_values("cotangent_inputs", &result, builder)?;
Ok(result)
}
}
fn extension_for_dispatch(
operation: SemanticOperationView<'_>,
) -> Result<&dyn ExtensionOp, SemanticAdError> {
let SemanticOpRef::Extension(op) = operation.op() else {
return Err(SemanticAdError::CoreOperation);
};
if !operation.effects().is_empty() {
return Err(SemanticAdError::EffectfulExtension {
family_id: op.family_id(),
});
}
Ok(op)
}
fn validate_operation_inputs(
operation: SemanticOperationView<'_>,
primal_inputs: &[ProgramValue],
primal_outputs: &[ProgramValue],
builder: &SemanticProgramBuilder,
) -> Result<(), SemanticAdError> {
validate_len(
"primal_inputs",
operation.inputs().len(),
primal_inputs.len(),
)?;
validate_len(
"primal_outputs",
operation.outputs().len(),
primal_outputs.len(),
)?;
validate_values("primal_inputs", primal_inputs, builder)?;
validate_values("primal_outputs", primal_outputs, builder)
}
fn checked_primal_value(
family_id: &'static str,
kind: PrimalValueKind,
index: usize,
values: &[ProgramValue],
residual_mask: ResidualSpec,
) -> Result<ProgramValue, SemanticAdError> {
if index >= values.len() {
return Err(SemanticAdError::PrimalIndexOutOfBounds {
family_id,
kind,
index,
len: values.len(),
});
}
let declared = match kind {
PrimalValueKind::Input => residual_mask.declares_input(index),
PrimalValueKind::Output => residual_mask.declares_output(index),
};
if !declared {
return Err(SemanticAdError::UndeclaredResidualValue {
family_id,
kind,
index,
});
}
Ok(values[index])
}
fn checked_primal_metadata<'a>(
family_id: &'static str,
kind: PrimalValueKind,
index: usize,
metadata: &'a [ProgramValueMetadata],
) -> Result<&'a ProgramValueMetadata, SemanticAdError> {
metadata
.get(index)
.ok_or(SemanticAdError::PrimalIndexOutOfBounds {
family_id,
kind,
index,
len: metadata.len(),
})
}
fn snapshot_metadata(
values: &[ProgramValue],
builder: &SemanticProgramBuilder,
) -> Result<Box<[ProgramValueMetadata]>, SemanticAdError> {
values
.iter()
.copied()
.map(|value| Ok(builder.value_metadata(value)?.clone()))
.collect()
}
fn validate_values(
field: &'static str,
values: &[ProgramValue],
builder: &SemanticProgramBuilder,
) -> Result<(), SemanticAdError> {
for (index, value) in values.iter().copied().enumerate() {
if builder.validate_value(value).is_err() {
return Err(SemanticAdError::ForeignValue { field, index });
}
}
Ok(())
}
fn validate_ad_values(
field: &'static str,
values: &[AdValue],
builder: &SemanticProgramBuilder,
) -> Result<(), SemanticAdError> {
for (index, value) in values.iter().copied().enumerate() {
if let AdValue::Value(value) = value {
if builder.validate_value(value).is_err() {
return Err(SemanticAdError::ForeignValue { field, index });
}
}
}
Ok(())
}
fn validate_len(
field: &'static str,
expected: usize,
actual: usize,
) -> Result<(), SemanticAdError> {
if expected != actual {
return Err(SemanticAdError::Arity {
field,
expected,
actual,
});
}
Ok(())
}
fn validate_insert<T>(
map: &HashMap<&'static str, T>,
family_id: &'static str,
role: SemanticAdRuleRole,
) -> Result<(), SemanticExtensionRegistryError> {
if !is_valid_family_id(family_id) {
return Err(SemanticExtensionRegistryError::MalformedFamilyId { family_id });
}
if map.contains_key(family_id) {
return Err(SemanticExtensionRegistryError::DuplicateRule { family_id, role });
}
Ok(())
}
fn is_valid_family_id(family_id: &str) -> bool {
let Some((prefix, version)) = family_id.rsplit_once('.') else {
return false;
};
let Some(version) = version.strip_prefix('v') else {
return false;
};
let Some((crate_name, op_name)) = prefix.split_once('.') else {
return false;
};
!crate_name.is_empty()
&& !op_name.is_empty()
&& !version.is_empty()
&& version.bytes().all(|byte| byte.is_ascii_digit())
&& crate_name.is_ascii()
&& op_name.is_ascii()
&& !crate_name.chars().any(char::is_whitespace)
&& !op_name.chars().any(char::is_whitespace)
}
#[cfg(test)]
mod tests;