Repository: pytorch
Issue: RuntimeError: function CompiledFunctionBackward returned an incorrect number of gradients (expected 3, got 2)
Labels: needs reproduction,triaged,oncall: pt2,module: aotdispatch

### 🐛 Describe the bug

I have integrate our new accelerator to torch by utilizing torch.compile feature. And it works good for inference. Now am working on giving support for training  but it gives me error while calling backward call.  It says 

`File "/home/tiru/work/vsim/lib/python3.10/site-packages/torch/autograd/graph.py", line 744, in _engine_run_backward
    return Variable._execution_engine.run_backward(  # Calls into the C++ engine to run the backward pass
RuntimeError: function CompiledFunctionBackward returned an incorrect number of gradients (expected 3, got 2)`

As per the documeantation AutoGrade Function will check the number of outputs from backward graph should match with number of inputs in forward graph which required gradient.  I am pasting both forward and backward graphs produced by torch dynamo Here.  
Forward graph
`class GraphModule(torch.nn.Module):
    def forward(self, primals_1: "f32[64, 100]", primals_2: "f32[64]", primals_3: "f32[32, 100]"):
        # File: /home/tiru/work/tvm/python/torch_pac/utests/test_MLP_train.py:19 in forward, code: x = self.fc1(x)
        permute: "f32[100, 64]" = torch.ops.aten.permute.default(primals_1, [1, 0]);  primals_1 = None
        mm: "f32[32, 64]" = torch.ops.aten.mm.default(primals_3, permute);  permute = None
        add: "f32[32, 64]" = torch.ops.aten.add.Tensor(mm, primals_2);  mm = primals_2 = None
        return [add, primals_3]`

backward graph
`class GraphModule(torch.nn.Module):
    def forward(self, primals_3: "f32[32, 100]", tangents_1: "f32[32, 64]"):
        # File: /home/tiru/work/tvm/python/torch_pac/utests/test_MLP_train.py:19 in forward, code: x = self.fc1(x)
        permute_1: "f32[64, 32]" = torch.ops.aten.permute.default(tangents_1, [1, 0])
        mm_1: "f32[64, 100]" = torch.ops.aten.mm.default(permute_1, primals_3);  permute_1 = primals_3 = None
        permute_2: "f32[100, 64]" = torch.ops.aten.permute.default(mm_1, [1, 0]);  mm_1 = None
        permute_3: "f32[64, 100]" = torch.ops.aten.permute.default(permute_2, [1, 0]);  permute_2 = None
        sum_1: "f32[1, 64]" = torch.ops.aten.sum.dim_IntList(tangents_1, [0], True);  tangents_1 = None
        view: "f32[64]" = torch.ops.aten.reshape.default(sum_1, [64]);  sum_1 = None
        return [permute_3, view, None]`

here the one of the input in forward graph which is primals_3 does have requires_grad is False which means it does not have gradient.

so why does auto grade engine considering this as input and giving me this error.

`  File "/home/tiru/work/tvm/python/torch_pac/utests/test_MLP_train.py", line 74, in <module>
    test_MLP_training()
  File "/home/tiru/work/tvm/python/torch_pac/utests/test_MLP_train.py", line 70, in test_MLP_training
    loss.backward()
  File "/home/tiru/work/vsim/lib/python3.10/site-packages/torch/_tensor.py", line 525, in backward
    torch.autograd.backward(
  File "/home/tiru/work/vsim/lib/python3.10/site-packages/torch/autograd/__init__.py", line 267, in backward
    _engine_run_backward(
  File "/home/tiru/work/vsim/lib/python3.10/site-packages/torch/autograd/graph.py", line 744, in _engine_run_backward
    return Variable._execution_engine.run_backward(  # Calls into the C++ engine to run the backward pass
RuntimeError: function CompiledFunctionBackward returned an incorrect number of gradients (expected 3, got 2)`


here is thest case i am using for my backend.
`
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset

from torch_pac.graph.config import config_
import logging
logging.basicConfig()
logging.getLogger().setLevel(logging.INFO)

class MLP(nn.Module):
    def __init__(self, input_dim, hidden_dim, output_dim):
        super(MLP, self).__init__()
        self.fc1 = nn.Linear(input_dim, hidden_dim)
        # self.relu = nn.ReLU()
        # self.fc2 = nn.Linear(hidden_dim, output_dim)

    def forward(self, x):
        x = self.fc1(x)
        # x = self.relu(x)
        # x = self.fc2(x)
        return x



def test_MLP_training():

    input_dim = 100
    hidden_dim = 64
    output_dim = 10
    batch_size = 32
    learning_rate = 0.001
    epochs = 5

    X = torch.randn(100, input_dim)
    y = torch.randint(0, output_dim, (100,))

    dataset = TensorDataset(X, y)
    dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)


    model = MLP(input_dim, hidden_dim, output_dim)
    criterion = nn.CrossEntropyLoss()
    optimizer = optim.Adam(model.parameters(), lr=learning_rate)

    # model = torch.compile(model)
    # for epoch in range(epochs):
    #     for data, targets in dataloader:
    #         outputs = model(data)
    #         loss = criterion(outputs, targets)
    #         optimizer.zero_grad()
    #         loss.backward()
    #         optimizer.step()
    #     print(f"cpu : Epoch [{epoch+1}/{epochs}], Loss: {loss.item():.4f}")

    torch._dynamo.reset()

    dbg_config={'relay.ext.cpac.dbg_export_IR': True,
                    'relay.ext.cpac.dbg_export_graphviz': True,
                    'relay.ext.cpac.dbg_fname_prefix': 'dbg/test_mlp_train/',
                    'relay.ext.cpac.input_layout_hint' : 'matrix',
                    'relay.ext.cpac.dbg_export_templates' : False}
    config_.set_config(dbg_config)
    model = torch.compile(model,backend="cpac")
    for epoch in range(epochs):
        for data, targets in dataloader:
            outputs = model(data)
            loss = criterion(outputs, targets)
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
        print(f"cpac : Epoch [{epoch+1}/{epochs}], Loss: {loss.item():.4f}")
if __name__ == '__main__':
    test_MLP_training()
`

### Error logs

_No response_

### Minified repro

_No response_

### Versions

Collecting environment information...
PyTorch version: 2.3.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.29.0
Libc version: glibc-2.35

Python version: 3.10.12 (main, Sep 11 2024, 15:47:36) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-5.15.0-105-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 A100 80GB PCIe
GPU 1: NVIDIA A100 80GB PCIe

Nvidia driver version: 550.54.14
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.7
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, 57 bits virtual
Byte Order:                         Little Endian
CPU(s):                             128
On-line CPU(s) list:                0-127
Vendor ID:                          GenuineIntel
Model name:                         Intel(R) Xeon(R) Gold 6338 CPU @ 2.00GHz
CPU family:                         6
Model:                              106
Thread(s) per core:                 2
Core(s) per socket:                 32
Socket(s):                          2
Stepping:                           6
CPU max MHz:                        3200.0000
CPU min MHz:                        800.0000
BogoMIPS:                           4000.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 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 invpcid_single intel_ppin ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect wbnoinvd dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid fsrm md_clear pconfig flush_l1d arch_capabilities
Virtualization:                     VT-x
L1d cache:                          3 MiB (64 instances)
L1i cache:                          2 MiB (64 instances)
L2 cache:                           80 MiB (64 instances)
L3 cache:                           96 MiB (2 instances)
NUMA node(s):                       2
NUMA node0 CPU(s):                  0-31,64-95
NUMA node1 CPU(s):                  32-63,96-127
Vulnerability Gather data sampling: Mitigation; Microcode
Vulnerability Itlb multihit:        Not affected
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Retbleed:             Not affected
Vulnerability Spec rstack overflow: Not affected
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:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] numpy==1.24.4
[pip3] onnx==1.14.0
[pip3] onnx-graphsurgeon==0.3.27
[pip3] onnx2pytorch==0.4.1
[pip3] onnxruntime==1.15.1
[pip3] pytorch-triton==3.0.0+45fff310c8
[pip3] torch==2.3.0
[pip3] torch_pac==0.0.1.dev0
[pip3] torchaudio==2.2.0.dev20240502+cu118
[pip3] torchvision==0.19.0.dev20240502+cu118
[pip3] triton==2.3.0
[conda] Could not collect

cc @ezyang @chauhang @penguinwu @zou3519 @bdhirsh @yf225