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
use super::{
argwhere::argwhere_data, cat::cat_with_slice_assign, repeat_dim::repeat_with_slice_assign,
};
use crate::ExecutionError;
use crate::tensor::{Bool, BoolElem, BoolTensor, Device, FloatTensor, IntTensor};
use crate::{Backend, TensorData, TensorMetadata, element::ElementConversion};
use alloc::vec::Vec;
use burn_std::{Shape, Slice};
use core::future::Future;
/// Bool Tensor API for basic operations, see
#[cfg_attr(doc, doc = crate::doc_tensor!())]
#[cfg_attr(not(doc), doc = "`Tensor`")]
/// for documentation on each function.
pub trait BoolTensorOps<B: Backend> {
/// Creates a new bool tensor.
///
/// # Arguments
///
/// * `shape` - The shape of the tensor.
/// * `device` - The device to create the tensor on.
///
/// # Returns
///
/// The boolean tensor with the given shape.
fn bool_empty(shape: Shape, device: &Device<B>) -> BoolTensor<B>;
/// Creates a new bool tensor filled false.
///
/// # Arguments
///
/// * `shape` - The shape of the tensor.
/// * `device` - The device to create the tensor on.
///
/// # Returns
///
/// The boolean tensor filled with false.
fn bool_zeros(shape: Shape, device: &Device<B>) -> BoolTensor<B>;
/// Creates a new bool tensor filled true.
///
/// # Arguments
///
/// * `shape` - The shape of the tensor.
/// * `device` - The device to create the tensor on.
///
/// # Returns
///
/// The boolean tensor filled with true.
fn bool_ones(shape: Shape, device: &Device<B>) -> BoolTensor<B>;
/// Converts the tensor to a data structure.
///
/// # Arguments
///
/// * `tensor` - The tensor.
///
/// # Returns
///
/// The data structure with the tensor's data.
fn bool_into_data(
tensor: BoolTensor<B>,
) -> impl Future<Output = Result<TensorData, ExecutionError>> + Send;
/// Creates a tensor from the data structure.
///
/// # Arguments
///
/// * `data` - The data structure.
/// * `device` - The device to create the tensor on.
///
/// # Returns
///
/// The tensor with the data.
fn bool_from_data(data: TensorData, device: &Device<B>) -> BoolTensor<B>;
/// Converts bool tensor to int tensor.
///
/// # Arguments
///
/// * `tensor` - The tensor.
///
/// # Returns
///
/// The int tensor with the same data as the bool tensor.
fn bool_into_int(tensor: BoolTensor<B>) -> IntTensor<B>;
/// Converts bool tensor to float tensor.
///
/// # Arguments
///
/// * `tensor` - The tensor.
///
/// # Returns
///
/// The float tensor with the same data as the bool tensor.
fn bool_into_float(tensor: BoolTensor<B>) -> FloatTensor<B>;
/// Gets the device of the tensor.
///
/// # Arguments
///
/// * `tensor` - The tensor.
///
/// # Returns
///
/// The device of the tensor.
fn bool_device(tensor: &BoolTensor<B>) -> Device<B>;
/// Moves the tensor to the device.
fn bool_to_device(tensor: BoolTensor<B>, device: &Device<B>) -> BoolTensor<B>;
/// Reshapes the tensor.
///
/// # Arguments
///
/// * `tensor` - The tensor.
/// * `shape` - The new shape.
///
/// # Returns
///
/// The tensor with the new shape.
fn bool_reshape(tensor: BoolTensor<B>, shape: Shape) -> BoolTensor<B>;
/// Gets the values from the tensor for the given ranges.
///
/// # Arguments
///
/// * `tensor` - The tensor.
/// * `slices` - The slices specifying ranges and steps for each dimension.
///
/// # Returns
///
/// The tensor with the values for the given slices.
///
/// # Note
///
/// Empty slices (where start >= end) are handled at the high-level tensor API and will not
/// be passed to this method. Backend implementations do not need to handle empty slices.
fn bool_slice(tensor: BoolTensor<B>, slices: &[Slice]) -> BoolTensor<B>;
/// Sets the values in the tensor for the given ranges.
///
/// # Arguments
///
/// * `tensor` - The tensor.
/// * `ranges` - The ranges to set the values for.
/// * `value` - The values to set.
///
/// # Returns
///
/// The tensor with the values set for the given ranges.
///
/// # Note
///
/// Empty slice assignments (where any slice range produces 0 elements) are handled at the
/// high-level tensor API and will not be passed to this method. Backend implementations do
/// not need to handle empty slice assignments.
fn bool_slice_assign(
tensor: BoolTensor<B>,
slices: &[Slice],
value: BoolTensor<B>,
) -> BoolTensor<B>;
/// Fills the tensor with values from the value tensor if the mask is true at the given
/// indices.
///
/// # Arguments
///
/// * `tensor` - The tensor.
/// * `mask` - The mask.
/// * `value` - The value tensor.
///
/// # Returns
///
/// The tensor with the values filled.
fn bool_mask_where(
tensor: BoolTensor<B>,
mask: BoolTensor<B>,
value: BoolTensor<B>,
) -> BoolTensor<B>;
/// Fills the tensor with the given value if the mask is true at the given indices.
///
/// # Arguments
///
/// * `tensor` - The tensor.
/// * `mask` - The mask.
/// * `value` - The value.
///
/// # Returns
///
/// The tensor with the values filled.
fn bool_mask_fill(
tensor: BoolTensor<B>,
mask: BoolTensor<B>,
value: BoolElem<B>,
) -> BoolTensor<B>;
/// Gather elements from the tensor at the given indices.
///
/// # Arguments
///
/// * `dim` - The dimension to gather from.
/// * `tensor` - The tensor.
/// * `indices` - The indices.
fn bool_gather(dim: usize, tensor: BoolTensor<B>, indices: IntTensor<B>) -> BoolTensor<B>;
/// Scatter a given value to the tensor at the given indices using boolean or reduction.
///
/// # Arguments
///
/// * `dim` - The dimension to scatter to.
/// * `tensor` - The tensor.
/// * `indices` - The indices.
/// * `value` - The value.
///
/// # Returns
///
/// The tensor with the values scattered.
fn bool_scatter_or(
dim: usize,
tensor: BoolTensor<B>,
indices: IntTensor<B>,
value: BoolTensor<B>,
) -> BoolTensor<B>;
/// Select tensor elements along the given dimension corresponding to the given indices.
///
/// # Arguments
///
/// * `tensor` - The tensor to select from.
/// * `dim` - The dimension to select from.
/// * `indices` - The indices of the elements to select.
///
/// # Returns
///
/// The tensor with the selected elements.
fn bool_select(tensor: BoolTensor<B>, dim: usize, indices: IntTensor<B>) -> BoolTensor<B> {
// Default implementation: convert to int, select, then convert back to bool
let int_tensor = B::bool_into_int(tensor);
let selected = B::int_select(int_tensor, dim, indices);
B::int_equal_elem(selected, 1_i32.elem())
}
/// Assign the selected elements along the given dimension corresponding to the given indices
/// to the given value using sum reduction.
///
/// # Arguments
///
/// * `tensor` - The tensor to assign the values to.
/// * `dim` - The dimension to select from.
/// * `indices` - The indices of the elements to assign.
/// * `value` - The values to assign.
///
/// # Returns
///
/// The tensor with the assigned values.
fn bool_select_or(
tensor: BoolTensor<B>,
dim: usize,
indices: IntTensor<B>,
value: BoolTensor<B>,
) -> BoolTensor<B> {
// Default implementation: convert to int, select_assign, then convert back to bool
let int_tensor = B::bool_into_int(tensor);
let int_values = B::bool_into_int(value);
let assigned = B::int_select_add(int_tensor, dim, indices, int_values);
// After select_assign with sum reduction, any non-zero value should be true
B::int_greater_elem(assigned, 0_i32.elem())
}
/// Repeats one dimension of the tensor a given number of times along that dimension.
///
/// # Arguments
///
/// * `tensor` - The tensor.
/// * `dim` - The dimension to repeat.
/// * `times` - The number of times to repeat the dimension.
///
/// # Returns
///
/// The tensor with the dimension repeated.
fn bool_repeat_dim(tensor: BoolTensor<B>, dim: usize, times: usize) -> BoolTensor<B> {
repeat_with_slice_assign::<B, Bool>(tensor, dim, times)
}
/// Concatenates the tensors along the given dimension.
///
/// # Arguments
///
/// * `tensors` - The tensors to concatenate.
/// * `dim` - The dimension to concatenate along.
///
/// # Returns
///
/// The tensor with the tensors concatenated along the given dimension.
///
/// # Note
///
/// Empty tensors (where the concatenation dimension has size 0) are filtered out at the
/// high-level tensor API and will not be passed to this method. Backend implementations do
/// not need to handle empty tensors.
fn bool_cat(tensors: Vec<BoolTensor<B>>, dim: usize) -> BoolTensor<B> {
cat_with_slice_assign::<B, Bool>(tensors, dim)
}
/// Equates the two tensors.
///
/// # Arguments
///
/// * `lhs` - The left hand side tensor.
/// * `rhs` - The right hand side tensor.
///
/// # Returns
///
/// The tensor with the result of the equate.
fn bool_equal(lhs: BoolTensor<B>, rhs: BoolTensor<B>) -> BoolTensor<B>;
/// Element-wise non-equality comparison.
///
/// # Arguments
///
/// * `lhs` - The left hand side tensor.
/// * `rhs` - The right hand side tensor.
///
/// # Returns
///
/// The tensor with the result of the comparison.
fn bool_not_equal(lhs: BoolTensor<B>, rhs: BoolTensor<B>) -> BoolTensor<B> {
let equal_tensor = B::bool_equal(lhs, rhs);
B::bool_not(equal_tensor)
}
/// Element-wise equality comparison with a scalar.
///
/// # Arguments
///
/// * `lhs` - The left-hand side tensor.
/// * `rhs` - The right-hand side scalar.
///
/// # Returns
///
/// The boolean tensor with the result of the comparison.
fn bool_equal_elem(lhs: BoolTensor<B>, rhs: BoolElem<B>) -> BoolTensor<B>;
/// Element-wise non-equality comparison with a scalar.
///
/// # Arguments
///
/// * `lhs` - The left-hand side tensor.
/// * `rhs` - The right-hand side scalar.
///
/// # Returns
///
/// The boolean tensor with the result of the comparison.
fn bool_not_equal_elem(lhs: BoolTensor<B>, rhs: BoolElem<B>) -> BoolTensor<B> {
let equal_tensor = B::bool_equal_elem(lhs, rhs);
B::bool_not(equal_tensor)
}
/// Inverses boolean values.
///
/// # Arguments
///
/// * `tensor` - The tensor.
///
/// # Returns
///
/// The tensor with the result of the negation.
fn bool_not(tensor: BoolTensor<B>) -> BoolTensor<B>;
/// Executes the logical and (`&&`) operation on two boolean tensors.
///
/// # Arguments
///
/// * `lhs` - The left hand side tensor.
/// * `rhs` - The right hand side tensor.
///
/// # Returns
///
/// The tensor with the result of the logical and.
fn bool_and(tensor: BoolTensor<B>, rhs: BoolTensor<B>) -> BoolTensor<B>;
/// Executes the logical or (`||`) operation on two boolean tensors.
///
/// # Arguments
///
/// * `lhs` - The left hand side tensor.
/// * `rhs` - The right hand side tensor.
///
/// # Returns
///
/// The tensor with the result of the logical or.
fn bool_or(tensor: BoolTensor<B>, rhs: BoolTensor<B>) -> BoolTensor<B>;
/// Element-wise exclusive or.
///
/// # Arguments
///
/// * `lhs` - The left hand side tensor.
/// * `rhs` - The right hand side tensor.
///
/// # Returns
///
/// The tensor with the result of the comparison.
fn bool_xor(lhs: BoolTensor<B>, rhs: BoolTensor<B>) -> BoolTensor<B> {
Self::bool_not_equal(lhs, rhs)
}
/// Transposes a bool tensor.
///
/// # Arguments
///
/// * `tensor` - The tensor to transpose.
///
/// # Returns
///
/// The transposed tensor.
fn bool_transpose(tensor: BoolTensor<B>) -> BoolTensor<B> {
let ndims = tensor.shape().num_dims();
Self::bool_swap_dims(tensor, ndims - 2, ndims - 1)
}
/// Swaps two dimensions of a bool tensor.
///
/// # Arguments
///
/// * `tensor` - The tensor to swap the dimensions of.
/// * `dim1` - The first dimension to swap.
/// * `dim2` - The second dimension to swap.
///
/// # Returns
///
/// The tensor with the dimensions swapped.
fn bool_swap_dims(tensor: BoolTensor<B>, dim1: usize, dim2: usize) -> BoolTensor<B>;
/// Permutes the dimensions of a tensor.
///
/// # Arguments
///
/// * `tensor` - The tensor to permute the dimensions of.
/// * `axes` - The new order of the dimensions.
/// # Returns
///
/// The tensor with the dimensions permuted.
fn bool_permute(tensor: BoolTensor<B>, axes: &[usize]) -> BoolTensor<B>;
/// Reverse the order of elements in a tensor along the given axes.
///
/// # Arguments
///
/// * `tensor` - The tensor to reverse.
/// * `axes` - The axes to reverse.
///
/// The tensor with the elements reversed.
fn bool_flip(tensor: BoolTensor<B>, axes: &[usize]) -> BoolTensor<B>;
/// Tests if any element in the boolean `tensor` evaluates to True.
///
/// # Arguments
///
/// * `tensor` - The tensor to test.
///
/// # Returns
///
/// A boolean tensor with a single element, True if any element in the tensor is True, False otherwise.
fn bool_any(tensor: BoolTensor<B>) -> BoolTensor<B> {
let sum = B::int_sum(B::bool_into_int(tensor));
B::int_greater_elem(sum, 0.elem())
}
/// Tests if any element in the boolean `tensor` evaluates to True along a given dimension `dim`.
///
/// # Arguments
///
/// * `tensor` - The tensor to test.
/// * `dim` - The axis along which to test.
///
/// # Returns
///
/// A boolean tensor `Tensor<B, D, Bool>` with the same size as input `tensor`, except in the `dim` axis
/// where the size is 1. The elem in the `dim` axis is True if any element along this dim in the input
/// evaluates to True, False otherwise.
fn bool_any_dim(tensor: BoolTensor<B>, dim: usize) -> BoolTensor<B> {
let sum = B::int_sum_dim(B::bool_into_int(tensor), dim);
B::int_greater_elem(sum, 0.elem())
}
/// Tests if all elements in the boolean `tensor` evaluate to True.
///
/// # Arguments
///
/// * `tensor` - The tensor to test.
///
/// # Returns
///
/// A boolean tensor `Tensor<B, 1, Bool>` with a single element, True if all elements in the input tensor
/// evaluate to True, False otherwise.
fn bool_all(tensor: BoolTensor<B>) -> BoolTensor<B> {
let num_elems = tensor.shape().num_elements();
let sum = B::int_sum(B::bool_into_int(tensor));
B::int_equal_elem(sum, (num_elems as i32).elem())
}
/// Tests if all elements in the boolean `tensor` evaluate to True along a given dimension `dim`.
///
/// # Arguments
///
/// * `tensor` - The tensor to test.
/// * `dim` - The axis along which to test.
///
/// # Returns
///
/// A boolean tensor `Tensor<B, D, Bool>` with the same size as input `tensor`, except in the `dim` axis
/// where the size is 1. The elem in the `dim` axis is True if all elements along this dim in the input
/// evaluates to True, False otherwise.
fn bool_all_dim(tensor: BoolTensor<B>, dim: usize) -> BoolTensor<B> {
let num_elems = tensor.shape().dims[dim];
let sum = B::int_sum_dim(B::bool_into_int(tensor), dim);
B::int_equal_elem(sum, (num_elems as i32).elem())
}
/// Compute the indices of the elements that are non-zero, grouped by element.
///
/// # Arguments
///
/// * `tensor` - The input tensor.
///
/// # Returns
///
/// A 2D tensor containing the indices of all non-zero elements of the given tensor.
/// Each row contains the indices of a non-zero element.
fn bool_argwhere(tensor: BoolTensor<B>) -> impl Future<Output = IntTensor<B>> + 'static + Send {
async {
// Size of each output tensor is variable (= number of nonzero elements in the tensor).
// Reading the data to count the number of truth values might cause sync but is required.
let device = B::bool_device(&tensor);
let data = B::bool_into_data(tensor)
.await
.expect("Can read the data without error");
argwhere_data::<B>(data, &device)
}
}
/// Broadcasts the bool `tensor` to the given `shape`.
fn bool_expand(tensor: BoolTensor<B>, shape: Shape) -> BoolTensor<B>;
/// Unfold windows along a dimension.
///
/// Returns a view of the tensor with all complete windows of size `size` in dimension `dim`;
/// where windows are advanced by `step` at each index.
///
/// The number of windows is `max(0, (shape[dim] - size).ceil_div(step))`.
///
/// # Arguments
///
/// * `tensor` - The input tensor to unfold; of shape ``[pre=..., dim shape, post=...]``
/// * `dim` - the selected dim.
/// * `size` - the size of each unfolded window.
/// * `step` - the step between each window.
///
/// # Returns
///
/// A tensor view with shape ``[pre=..., windows, size, post=...]``.
fn bool_unfold(tensor: BoolTensor<B>, dim: usize, size: usize, step: usize) -> BoolTensor<B>;
}