Repository: pytorch/pytorch

Issue:
compile() breaks TransformerEncoder mask dtype check
### 🐛 Describe the bug

Running `compile()` on a function that builds an attention mask and passes a tensor through a `TransformerEncoder` results in the dtype of the mask getting changed, triggering an exception:

```
import torch
import torch.nn as nn


def transformer_encoder(inputs, input_seq_len):
    encoder_layer = nn.TransformerEncoderLayer(
        d_model=16,
        nhead=2,
        dim_feedforward=32,
        dropout=0.1,
        activation='relu',
        batch_first=True,
    )
    encoder_norm = nn.LayerNorm(16)
    encoder = nn.TransformerEncoder(
        encoder_layer, 2, encoder_norm
    )

    src_mask = torch.ones(inputs.shape[1], inputs.shape[1], dtype=torch.bool).triu_(diagonal=1)
    padding_mask = (torch.arange(inputs.shape[1])[None, :].cpu() >= input_seq_len[:, None])
    
    print(src_mask,src_mask.dtype, )
    print(padding_mask,padding_mask.dtype, )
    
    return encoder(inputs, 
        mask=src_mask,
        src_key_padding_mask=padding_mask,
    )
    
    

transformer_encoder_opt = torch.compile(transformer_encoder)

inputs = torch.randn(2,3,16)
input_seq_len = torch.tensor([3,2])

transformer_encoder_opt(inputs, input_seq_len)
```

Output:
```
tensor([[0, 1, 1],
        [0, 0, 1],
        [0, 0, 0]]) torch.bool
tensor([[False, False, False],
        [False, False,  True]]) torch.bool
```

```
File /mnt/ext/phd/research/pt2/lib/python3.9/site-packages/torch/nn/functional.py:5000, in _canonical_mask(mask, mask_name, other_type, other_name, target_type, check_other)
   4998 _mask_is_float = torch.is_floating_point(mask)
   4999 if _mask_dtype != torch.bool and not _mask_is_float:
-> 5000     raise AssertionError(
   5001         f"only bool and floating types of {mask_name} are supported")
   5002 if check_other and other_type is not None:
   5003     if _mask_dtype != other_type:

AssertionError: only bool and floating types of attn_mask are supported
```

Output for non compiled function:
```
tensor([[False,  True,  True],
        [False, False,  True],
        [False, False, False]]) torch.bool
tensor([[False, False, False],
        [False, False,  True]]) torch.bool
```


### Error logs

_No response_

### Minified repro

_No response_

### Versions

Collecting environment information...
PyTorch version: 2.1.0.dev20230302+cu118
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.2 LTS (x86_64)
GCC version: (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0
Clang version: Could not collect
CMake version: version 3.25.0
Libc version: glibc-2.35

Python version: 3.9.13 (main, Oct 13 2022, 21:15:33)  [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-60-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 2080 Ti
Nvidia driver version: 525.78.01
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.7.6.5
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.2.2
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.2.2
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.2.2
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.2.2
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.2.2
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.2.2
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.2.2
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture:                    x86_64
CPU op-mode(s):                  32-bit, 64-bit
Address sizes:                   39 bits physical, 48 bits virtual
Byte Order:                      Little Endian
CPU(s):                          8
On-line CPU(s) list:             0-7
Vendor ID:                       GenuineIntel
Model name:                      Intel(R) Core(TM) i7-9700 CPU @ 3.00GHz
CPU family:                      6
Model:                           158
Thread(s) per core:              1
Core(s) per socket:              8
Socket(s):                       1
Stepping:                        13
CPU max MHz:                     4700.0000
CPU min MHz:                     800.0000
BogoMIPS:                        6000.00
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 cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_
timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault invpcid_single ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2
 erms invpcid mpx rdseed adx smap clflushopt intel_pt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp md_clear flush_l1d arch_capabilities
Virtualisation:                  VT-x
L1d cache:                       256 KiB (8 instances)
L1i cache:                       256 KiB (8 instances)
L2 cache:                        2 MiB (8 instances)
L3 cache:                        12 MiB (1 instance)
NUMA node(s):                    1
NUMA node0 CPU(s):               0-7
Vulnerability Itlb multihit:     KVM: Mitigation: VMX disabled                                                                                                           
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Not affected
Vulnerability Meltdown:          Not affected
Vulnerability Mmio stale data:   Mitigation; Clear CPU buffers; SMT disabled
Vulnerability Retbleed:          Mitigation; Enhanced IBRS                                                                                                                    
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1:        Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:        Mitigation; Enhanced IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
Vulnerability Srbds:             Mitigation; Microcode
Vulnerability Tsx async abort:   Mitigation; TSX disabled

Versions of relevant libraries:
[pip3] numpy==1.24.1
[pip3] pytorch-triton==2.0.0+b8b470bc59
[pip3] torch==2.1.0.dev20230302+cu118
[pip3] torchaudio==2.0.0.dev20230302+cu118
[pip3] torchvision==0.15.0.dev20230302+cu118
[conda] numpy                     1.21.5                   pypi_0    pypi
[conda] torch                     1.7.1                    pypi_0    pypi
[conda] torchseq                  3.0.0a0                   dev_0    <develop>

cc @ezyang @soumith @msaroufim @wconstab @ngimel @bdhirsh


Discussion:

Resolving patch:
diff --git a/torch/_decomp/__init__.py b/torch/_decomp/__init__.py
--- a/torch/_decomp/__init__.py
+++ b/torch/_decomp/__init__.py
@@ -308,6 +308,7 @@ def core_aten_decompositions() -> Dict[OpOverload, Callable]:
             aten.trace,
             aten.transpose.int,
             aten.tril.default,
+            aten.triu.default,
             aten.unfold,
             aten.unfold_backward,
             aten.upsample_bilinear2d,
diff --git a/torch/_inductor/lowering.py b/torch/_inductor/lowering.py
--- a/torch/_inductor/lowering.py
+++ b/torch/_inductor/lowering.py
@@ -1505,30 +1505,6 @@ def fn(index):
     )
 
 
-@register_lowering(aten.triu)
-def triu(x, diagonal=0):
-    x_loader = x.make_loader()
-    dtype = x.get_dtype()
-
-    def inner_fn(index):
-        *_, i, j = index
-        return ops.where(
-            ops.ge(
-                ops.index_expr(j - i - diagonal, torch.int32),
-                ops.constant(0, torch.int32),
-            ),
-            x_loader(index),
-            ops.constant(0, dtype),
-        )
-
-    return Pointwise.create(
-        device=x.get_device(),
-        dtype=dtype,
-        inner_fn=inner_fn,
-        ranges=list(x.get_size()),
-    )
-
-
 @register_lowering(aten.select_scatter, type_promotion_kind=None)
 def select_scatter(x, src, dim: int, index: int):
     assert x.get_dtype() == src.get_dtype()


Test patch:
diff --git a/test/inductor/test_torchinductor_opinfo.py b/test/inductor/test_torchinductor_opinfo.py
--- a/test/inductor/test_torchinductor_opinfo.py
+++ b/test/inductor/test_torchinductor_opinfo.py
@@ -448,6 +448,7 @@ def wrapper_set_seed(op, *args, **kwargs):
     "mT",
     "mH",
     "rsub",
+    "triu",
 }