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
//! # Trilu
//!
//! Returns the upper or lower triangular part of a 2-D matrix or batches of 2-D matrices.
//!
//! **ONNX Spec**: <https://onnx.ai/onnx/operators/onnx__Trilu.html>
//!
//! ## Opset Versions
//! - **Opset 14**: Initial version introducing triangular matrix extraction with optional diagonal offset.
//!
//! **FIXME**: The implementation does not validate that the input tensor has rank >= 2, which is
//! required by the ONNX spec. This should be validated in infer_types.
//!
//! ## Implementation Notes
//! - If `upper=1` (true):
//! - Positive k: Retains upper triangle excluding main diagonal and (k-1) diagonals above it
//! - Negative k: Retains upper triangle including main diagonal and |k| diagonals below it
//! - If `upper=0` (false):
//! - Positive k: Retains lower triangle including main diagonal and k diagonals above it
//! - Negative k: Retains lower triangle excluding main diagonal and (|k|-1) diagonals below it
use derive_new::new;
use onnx_ir_derive::NodeBuilder;
use crate::ir::{ArgType, Argument, Node, RawNode, TensorDataExt};
use crate::processor::{
InputSpec, NodeProcessor, NodeSpec, OutputPreferences, OutputSpec, ProcessError,
};
/// Configuration for the Trilu operation.
#[derive(Debug, Clone, PartialEq, new)]
pub struct TriluConfig {
/// Whether to return the upper triangular matrix.
pub upper: bool,
/// The diagonal offset.
pub diagonal: i64,
}
/// Node representation for Trilu operation
#[derive(Debug, Clone, NodeBuilder)]
pub struct TriluNode {
pub name: String,
pub inputs: Vec<Argument>,
pub outputs: Vec<Argument>,
pub config: TriluConfig,
}
pub(crate) struct TriluProcessor;
impl NodeProcessor for TriluProcessor {
type Config = TriluConfig;
fn spec(&self) -> NodeSpec {
NodeSpec {
min_opset: 14,
max_opset: None,
inputs: InputSpec::Range(1, 2),
outputs: OutputSpec::Exact(1),
}
}
fn lift_constants(&self, node: &mut RawNode, _opset: usize) -> Result<(), ProcessError> {
// Lift diagonal input (input[1]) if present
// FIXME: This should check if the input is constant before attempting to lift,
// similar to other processors. Currently it lifts unconditionally if present.
// Should use: if node.inputs[1].is_constant() { node.inputs[1].to_static()?; }
if node.inputs.len() > 1 {
node.inputs[1].to_static()?;
}
Ok(())
}
fn infer_types(
&self,
node: &mut RawNode,
_opset: usize,
_output_preferences: &OutputPreferences,
) -> Result<(), ProcessError> {
// TODO: Missing validation that input tensor is at least rank 2.
// ONNX spec requires last two dimensions to form a matrix, so rank must be >= 2.
let input_rank = match &node.inputs[0].ty {
ArgType::Tensor(t) => t.rank,
_ => 0,
};
if input_rank < 2 {
return Err(ProcessError::Custom(format!(
"Trilu: input must have rank >= 2, got rank {}",
input_rank
)));
}
// Infer output type
crate::processor::same_as_input(node);
Ok(())
}
fn extract_config(&self, node: &RawNode, _opset: usize) -> Result<Self::Config, ProcessError> {
let mut upper = true;
let mut diagonal = 0;
for (key, value) in node.attrs.iter() {
if key.as_str() == "upper" {
upper = value.clone().into_i64() != 0
}
}
// The second input of the Trilu node is the diagonal value, coming from a constant node
// FIXME: The spec states that `k` should be a 0-D tensor (scalar tensor), but the
// implementation assumes Data::Int64 (scalar value). This should handle the proper
// tensor extraction with shape validation to ensure it's 0-D.
// Should validate: k tensor has shape [] or [1] and contains single int64 value.
if let Some(diagonal_arg) = node.inputs.get(1) {
if let Some(tensor_data) = diagonal_arg.value() {
// Extract scalar value, converting from any numeric type to i64
diagonal = match tensor_data.scalar_i64() {
Ok(val) => val,
Err(e) => {
log::warn!(
"Trilu node {}: Failed to extract diagonal value: {:?}",
node.name,
e
);
0
}
};
} else {
log::warn!(
"Trilu node {}: diagonal input has no value (not constant)",
node.name
);
}
}
let config = TriluConfig::new(upper, diagonal);
Ok(config)
}
fn build_node(&self, builder: RawNode, opset: usize) -> Node {
let config = self
.extract_config(&builder, opset)
.expect("Config extraction failed");
Node::Trilu(TriluNode {
name: builder.name,
inputs: builder.inputs,
outputs: builder.outputs,
config,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ir::NodeType;
use crate::node::test_utils::TestNodeBuilder;
/// Helper function to create test nodes for Trilu tests
fn create_test_node(upper_attr: Option<i64>, diagonal_input: Option<i64>) -> TestNodeBuilder {
let mut builder = TestNodeBuilder::new(NodeType::Trilu, "test_trilu")
.input_tensor_f32("X", 2, None) // Typically a matrix
.output_tensor_f32("Y", 2, None);
// Add diagonal input if provided
if let Some(diag) = diagonal_input {
builder = builder.input_scalar_tensor_i64("k", Some(diag));
}
// Add upper attribute if provided
if let Some(upper) = upper_attr {
builder = builder.attr_int("upper", upper);
}
builder
}
#[test]
fn test_trilu_config_default() {
// Test with no attributes or inputs - should use defaults (upper=true, diagonal=0)
let node = create_test_node(None, None).build();
let mut node = node;
let processor = TriluProcessor;
let prefs = OutputPreferences::new();
let config = processor.extract_config(&node, 16).unwrap();
processor.infer_types(&mut node, 16, &prefs).unwrap();
assert_eq!(
config,
TriluConfig {
upper: true,
diagonal: 0
}
);
}
#[test]
fn test_trilu_config_upper_true() {
// Test with upper=1 attribute
let node = create_test_node(Some(1), None).build();
let mut node = node;
let processor = TriluProcessor;
let prefs = OutputPreferences::new();
let config = processor.extract_config(&node, 16).unwrap();
processor.infer_types(&mut node, 16, &prefs).unwrap();
assert_eq!(
config,
TriluConfig {
upper: true,
diagonal: 0
}
);
}
#[test]
fn test_trilu_config_upper_false() {
// Test with upper=0 attribute (lower triangular)
let node = create_test_node(Some(0), None).build();
let mut node = node;
let processor = TriluProcessor;
let prefs = OutputPreferences::new();
let config = processor.extract_config(&node, 16).unwrap();
processor.infer_types(&mut node, 16, &prefs).unwrap();
assert_eq!(
config,
TriluConfig {
upper: false,
diagonal: 0
}
);
}
#[test]
fn test_trilu_config_with_diagonal() {
// Test with diagonal=2 input (offset 2 above main diagonal)
let node = create_test_node(None, Some(2)).build_with_graph_data(16);
let mut node = node;
let processor = TriluProcessor;
let prefs = OutputPreferences::new();
let config = processor.extract_config(&node, 16).unwrap();
processor.infer_types(&mut node, 16, &prefs).unwrap();
assert_eq!(
config,
TriluConfig {
upper: true,
diagonal: 2
}
);
}
#[test]
fn test_trilu_config_with_negative_diagonal() {
// Test with diagonal=-3 input (offset 3 below main diagonal)
let node = create_test_node(None, Some(-3)).build_with_graph_data(16);
let mut node = node;
let processor = TriluProcessor;
let prefs = OutputPreferences::new();
let config = processor.extract_config(&node, 16).unwrap();
processor.infer_types(&mut node, 16, &prefs).unwrap();
assert_eq!(
config,
TriluConfig {
upper: true,
diagonal: -3
}
);
}
#[test]
fn test_trilu_config_both_params() {
// Test with both upper attribute and diagonal input
let node = create_test_node(Some(0), Some(1)).build_with_graph_data(16);
let mut node = node;
let processor = TriluProcessor;
let prefs = OutputPreferences::new();
let config = processor.extract_config(&node, 16).unwrap();
processor.infer_types(&mut node, 16, &prefs).unwrap();
assert_eq!(
config,
TriluConfig {
upper: false,
diagonal: 1
}
);
}
#[test]
fn test_trilu_config_non_binary_upper() {
// Test with non-binary values for the upper attribute
// Any non-zero value should be treated as true
let node = create_test_node(Some(42), None).build();
let mut node = node;
let processor = TriluProcessor;
let prefs = OutputPreferences::new();
let config = processor.extract_config(&node, 16).unwrap();
processor.infer_types(&mut node, 16, &prefs).unwrap();
assert_eq!(
config,
TriluConfig {
upper: true,
diagonal: 0
}
);
}
#[test]
fn test_trilu_config_negative_non_binary_upper() {
// Test with negative values for the upper attribute
// Any non-zero value should be treated as true
let node = create_test_node(Some(-5), None).build();
let mut node = node;
let processor = TriluProcessor;
let prefs = OutputPreferences::new();
let config = processor.extract_config(&node, 16).unwrap();
processor.infer_types(&mut node, 16, &prefs).unwrap();
assert_eq!(
config,
TriluConfig {
upper: true,
diagonal: 0
}
);
}
// TODO: Missing test for rank-1 (1D) input - should be rejected as rank must be >= 2.
// TODO: Missing test for non-square matrices - e.g., shape [3, 5] should work.
// Trilu works on rectangular matrices, not just square ones.
// TODO: Missing test for batched inputs - e.g., shape [2, 3, 4, 5].
// ONNX spec supports batched triangular operations on last two dimensions.
// TODO: Missing test for very large diagonal offset.
// E.g., diagonal=100 for 5x5 matrix - should result in all zeros (upper) or all values (lower).
// TODO: Missing test for diagonal offset equal to matrix dimensions.
// Edge cases where k = H or k = -W.
// TODO: Missing test for k input type validation.
// k must be int64 tensor per spec, should reject other types.
// TODO: Missing test for k input shape validation.
// k should be 0-D tensor (scalar), test with 1D tensor [k] to verify handling.
}