Masked Tensor for specific PyTorch

username: loveis98
cooked: <p>I have version 1.12.1 PyTorch. How can I use the functionality of MaskedTensor?</p>

username: ptrblck
cooked: <p>You would need to update to <code>torch&gt;=1.13</code> as it seems masked tensors were introduced then as seen in the <a href="https://pytorch.org/docs/1.13/masked.html#torch-masked">docs</a>.</p>

username: loveis98
cooked: <p>Are you shure that this feature are available? <a href="https://pytorch.org/docs/stable/masked.html" rel="noopener nofollow ugc">docs</a> say it is prototype</p>

username: ptrblck
cooked: <p>Yes, and you can easily check it by installing <code>1.13+</code>:</p>
<pre><code class="lang-python">&gt;&gt;&gt; import torch
&gt;&gt;&gt; torch.__version__
'1.13.1+cu117'
&gt;&gt;&gt; torch.masked
&lt;module 'torch.masked' from ...
&gt;&gt;&gt; from torch.masked import masked_tensor, as_masked_tensor
&gt;&gt;&gt; data = torch.arange(24).reshape(2, 3, 4)
&gt;&gt;&gt; mask = data % 2 == 0
&gt;&gt;&gt; mt = masked_tensor(data.float(), mask)
&gt;&gt;&gt; print("mt[0]:\n", mt[0])
mt[0]:
 MaskedTensor(
  [
    [  0.0000,       --,   2.0000,       --],
    [  4.0000,       --,   6.0000,       --],
    [  8.0000,       --,  10.0000,       --]
  ]
)
&gt;&gt;&gt; print("mt[:, :, 2:4]:\n", mt[:, :, 2:4])
mt[:, :, 2:4]:
 MaskedTensor(
  [
    [
      [  2.0000,       --],
      [  6.0000,       --],
      [ 10.0000,       --]
    ],
    [
      [ 14.0000,       --],
      [ 18.0000,       --],
      [ 22.0000,       --]
    ]
  ]
)
</code></pre>

username: loveis98
cooked: <p>In torch 1.13.0 I run into strange error with maskedtensor,</p>
<p>TypeError: mask must have dtype bool.</p>
<p>while forward(), but maskedtensor itself is created without errors. It is why my question about version.</p>

username: ptrblck
cooked: <p>Which <code>dtype</code> are you expecting for the mask if not bool?</p>

username: loveis98
cooked: <p>Only bool<br>
If my mask was not bool, maskedtensor would not  be created<br>
But this error occurs when forward() runs</p>

username: ptrblck
cooked: <p>In this case I would recommend checking the <code>forward</code> method and which <code>dtype</code> your <code>mask</code> currently has as it doesn’t seem to be a <code>BoolTensor</code>. Call <code>mask = mask.bool()</code> and it should work assuming it contains valid values which can be transformed to bool without issues.</p>

username: loveis98
cooked: <p>No, it doesn’t work<br>
Mask is bool, but the error remains</p>

username: ptrblck
cooked: <p>Could you post a minimal and executable code snippet reproducing the error, please?</p>

username: loveis98
cooked: <pre><code class="lang-auto">device='cuda'
batchsize=32

 
x = torch.rand((batchsize, 100)).to(device)
x[:, 80:] = -1
batch = {
    'features': [
        torch.randint(0, 5, (batchsize, 100)).to(device),
        masked_tensor(x, (x != -1).bool(), requires_grad=True)
    ],
    'label': torch.randint(0, 2, (batchsize,)).to(device)
}

 
class Rnn(nn.Module):
    def __init__(self, rnn_units=64, top_classifier_units=32):
        super(Rnn, self).__init__()

        self._embeddings = nn.ModuleList(
            [self._create_embedding_projection(*(5, 2))])
        self._spatial_dropout = nn.Dropout2d(0.05)
        self._embeddings_concated_dim = 2 #2 - dim of the embedding
        self._rnn = nn.GRU(input_size=self._embeddings_concated_dim+1,#1 - number of continious features
                            hidden_size=128, batch_first=True, num_layers=1,
                            bidirectional=True)

        self._hidden_size = rnn_units
        n_pooling = 2
        in_features_linear = n_pooling * self._hidden_size * 2
        self._top_classifier = nn.Sequential(nn.Linear(in_features=in_features_linear,
                                                       out_features=top_classifier_units),
                                             nn.ReLU(),
                                             nn.Linear(in_features=top_classifier_units, out_features=1)
                                            )

    def forward(self, features):
        batch_size = features[0].shape[0]
        embeddings = [embedding(features[i]) \
                        for i, embedding in enumerate(self._embeddings)]
        numeric = [features[i][:, :, None] for i in range(
                    len(self._embeddings),
                    len(self._embeddings)+1
                    )]


        concated_embeddings = torch.cat(embeddings, dim=-1)
        concated_embeddings = concated_embeddings.permute(0, 2, 1).unsqueeze(3)
        dropout_embeddings = self._spatial_dropout(concated_embeddings)
        dropout_embeddings = dropout_embeddings.squeeze(3).permute(0, 2, 1)
        concated_embeddings = torch.cat([dropout_embeddings] + numeric, dim=-1)
        states, _ = self._rnn(concated_embeddings)
        poolings = []
        poolings.append(states.max(dim=1)[0])
        poolings.append(states.sum(dim=1) / states.shape[1])    
        combined_input = torch.cat(poolings, dim=-1)
        logit = self._top_classifier(combined_input)  
        return logit

    @classmethod
    def _create_embedding_projection(cls, cardinality, embed_size, add_missing=True, padding_idx=0, init=None):
        add_missing = 1 if add_missing else 0
        v = nn.Embedding(num_embeddings=cardinality+add_missing, embedding_dim=embed_size, padding_idx=padding_idx)
        if init is not None:
            v.weight.data.copy_(init)
        return v



model = Rnn(rnn_units=128, top_classifier_units=128).to(device)
optimizer = torch.optim.Adam(lr=1e-3, params=model.parameters())
 
for epoch in range(10):
    print(f'Starting epoch {epoch+1}')
    loss_function = nn.BCEWithLogitsLoss()
    num_batches = 1
    running_loss = 0.0
    model.train()
    output = torch.flatten(model(batch['features']))
    batch_loss = loss_function(output, batch['label'].float())
    batch_loss.backward()
    optimizer.step()
    optimizer.zero_grad()
    running_loss += batch_loss

Starting epoch 1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[70], line 8
      5 running_loss = 0.0
      6 model.train()
----&gt; 8 output = torch.flatten(model(batch['features']))
      9 batch_loss = loss_function(output, batch['label'].float())
     11 batch_loss.backward()

 
File ~/venv/lib/python3.10/site-packages/torch/nn/modules/module.py:1501, in Module._call_impl(self, *args, **kwargs)
   1496 # If we don't have any hooks, we want to skip the rest of the logic in
   1497 # this function, and just call forward.
   1498 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
   1499         or _global_backward_pre_hooks or _global_backward_hooks
   1500         or _global_forward_hooks or _global_forward_pre_hooks):
-&gt; 1501     return forward_call(*args, **kwargs)
   1502 # Do not call functions when jit is used
   1503 full_backward_hooks, non_full_backward_hooks = [], []

Cell In[66], line 41, in Rnn.forward(self, features)
     39 dropout_embeddings = self._spatial_dropout(concated_embeddings)
     40 dropout_embeddings = dropout_embeddings.squeeze(3).permute(0, 2, 1)
---&gt; 41 concated_embeddings = torch.cat([dropout_embeddings] + numeric, dim=-1)
     43 states, _ = self._rnn(concated_embeddings)
     44 poolings = []
...
    208     or data.dtype == torch.int64
    209 ):
    210     raise TypeError(f"{data.dtype} is not supported in MaskedTensor.")

TypeError: mask must have dtype bool.
</code></pre>
<p><em>The problem occurs when I concat embedding and masked tensor.</em></p>
<p>PyTorch version: 2.0.1+cu118<br>
Is debug build: False<br>
CUDA used to build PyTorch: 11.8<br>
ROCM used to build PyTorch: N/A<br>
OS: CentOS Linux release 7.9.2009 (Core) (x86_64)<br>
GCC version: (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44)<br>
Clang version: Could not collect<br>
CMake version: version 3.27.2<br>
Libc version: glibc-2.17<br>
Python version: 3.10.8 (main, Oct 28 2022, 08:43:57) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] (64-bit runtime)<br>
Python platform: Linux-3.10.0-1160.76.1.el7.x86_64-x86_64-with-glibc2.17<br>
Is CUDA available: True<br>
CUDA runtime version: Could not collect<br>
CUDA_MODULE_LOADING set to: LAZY<br>
GPU models and configuration: GPU 0: Tesla V100-PCIE-32GB<br>
Nvidia driver version: 460.106.00<br>
cuDNN version: Could not collect<br>
HIP runtime version: N/A<br>
MIOpen runtime version: N/A<br>
Is XNNPACK available: True</p>
<p>CPU:<br>
Architecture:          x86_64<br>
CPU op-mode(s):        32-bit, 64-bit<br>
Byte Order:            Little Endian<br>
CPU(s):                40<br>
On-line CPU(s) list:   0-39<br>
Thread(s) per core:    2<br>
Core(s) per socket:    10<br>
Socket(s):             2<br>
NUMA node(s):          2<br>
Vendor ID:             GenuineIntel<br>
CPU family:            6<br>
Model:                 85<br>
Model name:            Intel(R) Xeon(R) Silver 4114 CPU @ 2.20GHz<br>
Stepping:              4<br>
CPU MHz:               2499.975<br>
CPU max MHz:           3000.0000<br>
CPU min MHz:           800.0000<br>
BogoMIPS:              4400.00<br>
Virtualization:        VT-x<br>
L1d cache:             32K<br>
L1i cache:             32K<br>
L2 cache:              1024K<br>
L3 cache:              14080K<br>
NUMA node0 CPU(s):     0-9,20-29<br>
NUMA node1 CPU(s):     10-19,30-39</p>
<p>Flags:                 fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 invpcid_single intel_ppin intel_pt ssbd mba ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_pkg_req pku ospke md_clear spec_ctrl intel_stibp flush_l1d</p>
<p>Versions of relevant libraries:<br>
[pip3] numpy==1.23.1<br>
[pip3] torch==2.0.1+cu118<br>
[pip3] torchaudio==2.0.2<br>
[pip3] torchvision==0.15.2<br>
[pip3] triton==2.0.0<br>
[conda] Could not collect</p>
<p>output of <code>nvidia-smi</code>:<br>
<div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/7/1/7182c7ae69a8b5ca6d503847c6cc2cbfb80b3847.jpeg" data-download-href="https://discuss.pytorch.org/uploads/default/7182c7ae69a8b5ca6d503847c6cc2cbfb80b3847" title="Без имени"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/7/1/7182c7ae69a8b5ca6d503847c6cc2cbfb80b3847_2_690x204.jpeg" alt="Без имени" data-base62-sha1="gca9eRS81PdobNWlXW78KZG3VFd" width="690" height="204" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/7/1/7182c7ae69a8b5ca6d503847c6cc2cbfb80b3847_2_690x204.jpeg, https://discuss.pytorch.org/uploads/default/original/3X/7/1/7182c7ae69a8b5ca6d503847c6cc2cbfb80b3847.jpeg 1.5x, https://discuss.pytorch.org/uploads/default/original/3X/7/1/7182c7ae69a8b5ca6d503847c6cc2cbfb80b3847.jpeg 2x" data-dominant-color="ECECEC"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">Без имени</span><span class="informations">893×265 69.4 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>

username: loveis98
cooked: <p>Hi! were you able to reproduce the error?</p>

username: ptrblck
cooked: <p>Yes, thanks for the code snippet.<br>
You cannot concatenate a standard tensor with a masked one as seen here:</p>
<pre><code class="lang-python">import torch
from torch.masked import masked_tensor, as_masked_tensor
data = torch.arange(24).reshape(2, 3, 4)
mask = data % 2 == 0
mt = masked_tensor(data.float(), mask)

print(mt)
print(torch.cat([mt, mt]))
# fails
#print(torch.cat([torch.zeros(2, 3, 4), mt]))
print(torch.cat([masked_tensor(torch.zeros(2, 3, 4), torch.ones_like(data).bool()), mt]))
</code></pre>
<p>and would need to create another masked tensor.</p>

username: loveis98
cooked: <p>thank you very much, this thought never even occurred to me:)<br>
I have a doubt that if I turn the embeddings into a masked_tensor (with a mask True, like <code>torch.cat([masked_tensor(dropout_embeddings, torch.full_like(dropout_embeddings, True).bool())] + numeric, dim=-1)</code>), then the embeddings themselves will learn worse, is that so?</p>