Repository: pytorch
Issue: `__torch_function__` does not work for functions that called within other overrided functions
Labels: triaged,module: __torch_function__

### 🐛 Describe the bug

Functions [`torch.nn.functional.relu`](https://github.com/pytorch/pytorch/blob/main/torch/nn/functional.py#L1693) and [`torch.nn.functional.multi_head_attention_forward`](https://github.com/pytorch/pytorch/blob/main/torch/nn/functional.py#L5841) calls within functions from `torch` namespace. But `__torch_function__` overrides function only from `torch.nn.functional` and is not called for functions from `torch` name that called inside.

```python
import torch
import torch.nn.functional as F
from torch.overrides import TorchFunctionMode

class MyTorchFunctionMode(TorchFunctionMode):
    def __torch_function__(self, func, types, args=(), kwargs=None):
        if kwargs is None:
            kwargs = {}
        print(func)
        return func(*args, **kwargs)

x = torch.tensor([-1.0, 0.0, 1.0])

print("\ntorch.nn.functional.relu:")
with MyTorchFunctionMode():
    torch.nn.functional.relu(x)

batch_size = 2
seq_len = 5
embed_dim = 8
num_heads = 2

q = torch.rand((seq_len, batch_size, embed_dim))
k = torch.rand((seq_len, batch_size, embed_dim))
v = torch.rand((seq_len, batch_size, embed_dim))

in_proj_weight = torch.rand((3 * embed_dim, embed_dim))
in_proj_bias = torch.rand(3 * embed_dim)
out_proj_weight = torch.rand((embed_dim, embed_dim))
out_proj_bias = torch.rand(embed_dim)
attn_mask = torch.ones((seq_len, seq_len))
key_padding_mask = torch.zeros((batch_size, seq_len), dtype=torch.bool)

print("\nF.multi_head_attention_forward:")
with MyTorchFunctionMode():
    attn_output, attn_output_weights = F.multi_head_attention_forward(
        query=q,
        key=k,
        value=v,
        embed_dim_to_check=embed_dim,
        num_heads=num_heads,
        in_proj_weight=in_proj_weight,
        in_proj_bias=in_proj_bias,
        bias_k=None,
        bias_v=None,
        add_zero_attn=False,
        dropout_p=0.0,
        out_proj_weight=out_proj_weight,
        out_proj_bias=out_proj_bias,
        training=True,
        key_padding_mask=key_padding_mask,
        need_weights=True,
        attn_mask=attn_mask,
    )
```
```
torch.nn.functional.relu:
<function relu at 0x76ccd67d15e0>

F.multi_head_attention_forward:
<function multi_head_attention_forward at 0x76ccd66efc10>
```
Is it expected behavior?
Is there any way to ignore this functions for `handle_torch_function` to call `__torch_function__` for functions that calls inside?

For example, in case remove `handle_torch_function` output of the code looks like:

```
torch.nn.functional.relu:
<built-in method relu of type object at 0x7de2cfe39480>

F.multi_head_attention_forward:
<method 'dim' of 'torch._C.TensorBase' objects>
<method 'dim' of 'torch._C.TensorBase' objects>
<method 'dim' of 'torch._C.TensorBase' objects>
<method 'dim' of 'torch._C.TensorBase' objects>
<method 'dim' of 'torch._C.TensorBase' objects>
<method-wrapper '__get__' of getset_descriptor object at 0x7de2d05dbc80>
<method-wrapper '__get__' of getset_descriptor object at 0x7de2d05dbc80>
<method-wrapper '__get__' of getset_descriptor object at 0x7de2d05dc480>
<method-wrapper '__get__' of getset_descriptor object at 0x7de2d05dc480>
<method-wrapper '__get__' of getset_descriptor object at 0x7de2d05dc480>
<built-in method is_floating_point of type object at 0x7de2cfe39480>
<built-in method zeros_like of type object at 0x7de2cfe39480>
<method 'masked_fill_' of 'torch._C.TensorBase' objects>
<method-wrapper '__get__' of getset_descriptor object at 0x7de2d05dc480>
<method-wrapper '__get__' of getset_descriptor object at 0x7de2d05dc480>
<built-in method is_floating_point of type object at 0x7de2cfe39480>
<method-wrapper '__get__' of getset_descriptor object at 0x7de2d05dbc80>
<method-wrapper '__get__' of getset_descriptor object at 0x7de2d05dbc80>
<method 'size' of 'torch._C.TensorBase' objects>
<method 'chunk' of 'torch._C.TensorBase' objects>
<method 'chunk' of 'torch._C.TensorBase' objects>
<built-in function linear>
<built-in function linear>
<built-in function linear>
<method 'dim' of 'torch._C.TensorBase' objects>
<method-wrapper '__get__' of getset_descriptor object at 0x7de2d05dbc80>
<method 'unsqueeze' of 'torch._C.TensorBase' objects>
<method 'view' of 'torch._C.TensorBase' objects>
<method 'transpose' of 'torch._C.TensorBase' objects>
<method-wrapper '__get__' of getset_descriptor object at 0x7de2d05dbc80>
<method 'view' of 'torch._C.TensorBase' objects>
<method 'transpose' of 'torch._C.TensorBase' objects>
<method-wrapper '__get__' of getset_descriptor object at 0x7de2d05dbc80>
<method 'view' of 'torch._C.TensorBase' objects>
<method 'transpose' of 'torch._C.TensorBase' objects>
<method 'size' of 'torch._C.TensorBase' objects>
<method-wrapper '__get__' of getset_descriptor object at 0x7de2d05dbc80>
<method 'view' of 'torch._C.TensorBase' objects>
<method 'expand' of 'torch._C.TensorBase' objects>
<method 'reshape' of 'torch._C.TensorBase' objects>
<method 'add' of 'torch._C.TensorBase' objects>
<method-wrapper '__get__' of getset_descriptor object at 0x7de2d05dbc80>
<method 'mul' of 'torch._C.TensorBase' objects>
<method 'transpose' of 'torch._C.TensorBase' objects>
<built-in method baddbmm of type object at 0x7de2cfe39480>
<function softmax at 0x7de1c5d13ca0>
<built-in method bmm of type object at 0x7de2cfe39480>
<method 'transpose' of 'torch._C.TensorBase' objects>
<method 'contiguous' of 'torch._C.TensorBase' objects>
<method 'view' of 'torch._C.TensorBase' objects>
<built-in function linear>
<method 'size' of 'torch._C.TensorBase' objects>
<method 'view' of 'torch._C.TensorBase' objects>
<method 'view' of 'torch._C.TensorBase' objects>
<method 'mean' of 'torch._C.TensorBase' objects>
```

  



### Versions

```
Collecting environment information...
PyTorch version: 2.4.0+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.4 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: version 3.22.1
Libc version: glibc-2.35

Python version: 3.8.19 (default, Apr  6 2024, 17:58:10)  [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-6.5.0-35-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 12.5.40
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA GeForce RTX 3090
GPU 1: NVIDIA GeForce RTX 3090
GPU 2: NVIDIA GeForce RTX 3090

Nvidia driver version: 555.42.02
cuDNN version: Could not collect
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:                      46 bits physical, 48 bits virtual
Byte Order:                         Little Endian
CPU(s):                             36
On-line CPU(s) list:                0-35
Vendor ID:                          GenuineIntel
Model name:                         Intel(R) Core(TM) i9-10980XE CPU @ 3.00GHz
CPU family:                         6
Model:                              85
Thread(s) per core:                 2
Core(s) per socket:                 18
Socket(s):                          1
Stepping:                           7
CPU max MHz:                        4800.0000
CPU min MHz:                        1200.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 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 cpuid_fault epb cat_l3 cdp_l3 invpcid_single ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req vnmi avx512_vnni md_clear flush_l1d arch_capabilities
Virtualization:                     VT-x
L1d cache:                          576 KiB (18 instances)
L1i cache:                          576 KiB (18 instances)
L2 cache:                           18 MiB (18 instances)
L3 cache:                           24.8 MiB (1 instance)
NUMA node(s):                       1
NUMA node0 CPU(s):                  0-35
Vulnerability Gather data sampling: Mitigation; Microcode
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 vulnerable
Vulnerability Retbleed:             Mitigation; Enhanced IBRS
Vulnerability Spec rstack overflow: Not affected
Vulnerability Spec store bypass:    Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:           Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:           Mitigation; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI Syscall hardening, KVM SW loop
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Mitigation; TSX disabled

Versions of relevant libraries:
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.24.4
[pip3] onnx==1.16.1
[pip3] torch==2.4.0
[pip3] torchgraphx==0.1.0
[pip3] torchvision==0.18.1
[pip3] triton==3.0.0
[conda] Could not collect
```

cc @hameerabbasi @rgommers @ezyang