How can I implement a mask tensor in libtorch?

As the title, how can I implement a mask tensor with libtorch written in python such as:

mask_ = (box[:, 3] <= box[:, 1]) | (box[:, 2] <= box[:, 0])

I’ve done with indexing but I’ve struggled with “|” operator.

mask_ = box.select(1, 3) <= box.select(1, 1);

Just using | would seem to work in C++:

csrc = """
torch::Tensor fn(const torch::Tensor& a, const torch::Tensor& b) {
  return a | b;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
  m.def("fn", &fn, "test function");
}
"""

ext = torch.utils.cpp_extension.load_inline("test_ext", csrc)
a = torch.tensor([False, True])
print(ext.fn(a, a[:, None]))

Best regards

Thomas

I’ve checked before I post this question, and I’ve found that at::Tensor | at::Tensor is not allowed…
mask_ = ( box.select(1, 3) <= box.select(1, 1) ) | ( box.select(1, 2) <= box.select(1, 0) );

You probably want to upgrade your PyTorch version, I did check that the snippet above works with recent PyTorch.
Boolean tensors have been introduced in PyTorch 1.2 or so and PyTorch 1.3 and following refined the semantics.

Best regards

Thomas

P.S.: We don’t use at::Tensor but torch::Tensor these days :slight_smile:.

I’ve found that
mask_ = (box[:, 3] <= box[:, 1]) | (box[:, 2] <= box[:, 0])
works but
mask_ = ( box.select(1, 3) <= box.select(1, 1) ) | ( box.select(1, 2) <= box.select(1, 0) );
does not work…which is quite not understandable for me…
In addition, does libtorch depend on pytorch version? I don’t understand clearly whether libtorch matters with pytorch version because I think libtorch is not connected with pytorch directly.

(Oh, I declare most of variables as torch::Tensor, but when I check the code with vscode, it shows that those are at::Tensor, which is unexpected for me. Anyway it seems no problem.)

libtorch is roughly the C++ part of PyTorch plus a C++ API for the bits of PyTorch implemented in Python. In particular, they share the versions. I usually just use the libtorch that comes with PyTorch to build things, but that could be me.
Do you use a recent libtorch?

Yes and I think version of both libtorch and pytorch are satisfied.