Repository: pytorch
Issue: RuntimeError "global alloc not supported yet" when using TorchScript optimization.
Labels: high priority,triage review,oncall: jit

### 🐛 Describe the bug

Calling the `forward` method on TorchScript models can, under some specific conditions, raise a `RuntimeError` with message: "Global alloc not supported yet.".

I think this is linked to an old issue: https://github.com/pytorch/pytorch/issues/69078, however, I managed to consistently reproduce this error. 

The code that reproduces the bug is quite long and needs some explanation. It was taken from a very complex 3D pose estimation model with lots of pre and post processing whose code was largely generated by `torch.fx`. In the post-processing part, there is a class `ComputeCentroids` that computes the center of mass of queried instances in a batch of segmentation masks that appears to be causing the error.

The `ComputeCentroids` was tested with both cpu and gpu devices, with and without `torch::jit::script` and it appears to be working as desired, even with empty input queries.

The error is raised only if **all** the three following conditions apply:
- The inference device is set to "cuda". 
- The torch jit optimization is turned on, as suggested by @OlofHarrysson in https://github.com/pytorch/pytorch/issues/69078
- The first inference is performed with an empty query. Maybe something goes wrong in the torchscript profiling executor?

```python
from typing import cast

import torch
import torch.nn as nn
from torch import Tensor


class ComputeCentroids(nn.Module):
    def forward(self, b_idx: Tensor, i_idx: Tensor, segm: Tensor) -> Tensor:
        dev = segm.device
        B, H, W = segm.shape
        N = int(segm.max()) + 1
        hh, ww = torch.arange(H, device=dev), torch.arange(W, device=dev)
        i, j = torch.meshgrid(hh, ww, indexing="ij")
        xy = torch.stack([j, i], dim=-1).float().view(-1, 2).repeat(B, 1)
        segm_f = (segm.view(B, -1) + torch.arange(B, device=dev)[:, None] * N).view(-1)
        eq = segm_f[:, None] == (i_idx + b_idx * N)[None]
        c_xy = (eq[..., None] * xy[:, None]).sum(0) / eq[..., None].sum(0)
        c_xy.nan_to_num_(-1.0)
        return c_xy


def zero_init() -> dict[str, Tensor]:
    b_idx = torch.zeros(0, device=dev)
    x_idx = torch.zeros(0, device=dev)
    segm = torch.zeros(1, 256, 256, device=dev)
    return {"b_idx": b_idx, "i_idx": x_idx, "segm": segm}


def random_init() -> dict[str, Tensor]:
    b_idx = torch.tensor([0, 0, 0, 0], device=dev)
    i_idx = torch.tensor([0, 1, 2, 3], device=dev)
    segm = torch.randint(0, 10, (1, 256, 256), device=dev)
    return {"b_idx": b_idx, "i_idx": i_idx, "segm": segm}


if __name__ == "__main__":
    compute_cxy = cast(ComputeCentroids, torch.jit.script(ComputeCentroids()))

    # Bug can be reproduced if all the following conditions are verified:
    # - Device is set to "cuda".
    # - Optimized execution is activated.
    # - First inference pass is the result of zero_init().

    dev = "cuda:0"  # "cpu"
    optimize = True  # False
    zero_init_first = True  # False

    with torch.jit.optimized_execution(optimize):  # type: ignore
        if zero_init_first:
            compute_cxy(**zero_init())

        for _ in range(5):
            compute_cxy(**random_init())
```

### Versions

Collecting environment information...
PyTorch version: 2.5.1+cu118
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.6 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-2ubuntu1~20.04) 11.4.0
Clang version: Could not collect
CMake version: version 3.16.3
Libc version: glibc-2.31

Python version: 3.10.15 (main, Sep  7 2024, 18:35:33) [GCC 9.4.0] (64-bit runtime)
Python platform: Linux-5.15.0-130-generic-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: 12.3.107
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 2080 Ti
Nvidia driver version: 550.127.08
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
Byte Order:                           Little Endian
Address sizes:                        39 bits physical, 48 bits virtual
CPU(s):                               16
On-line CPU(s) list:                  0-15
Thread(s) per core:                   2
Core(s) per socket:                   8
Socket(s):                            1
NUMA node(s):                         1
Vendor ID:                            GenuineIntel
CPU family:                           6
Model:                                158
Model name:                           Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz
Stepping:                             13
CPU MHz:                              3600.000
CPU max MHz:                          5000,0000
CPU min MHz:                          800,0000
BogoMIPS:                             7200.00
Virtualization:                       VT-x
L1d cache:                            256 KiB
L1i cache:                            256 KiB
L2 cache:                             2 MiB
L3 cache:                             16 MiB
NUMA node0 CPU(s):                    0-15
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 Reg file data sampling: Not affected
Vulnerability Retbleed:               Mitigation; Enhanced IBRS
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 / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI SW loop, KVM SW loop
Vulnerability Srbds:                  Mitigation; Microcode
Vulnerability Tsx async abort:        Mitigation; TSX disabled
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

Versions of relevant libraries:
[pip3] numpy==1.26.3
[pip3] nvidia-cublas-cu11==11.11.3.6
[pip3] nvidia-cuda-cupti-cu11==11.8.87
[pip3] nvidia-cuda-nvrtc-cu11==11.8.89
[pip3] nvidia-cuda-runtime-cu11==11.8.89
[pip3] nvidia-cudnn-cu11==9.1.0.70
[pip3] nvidia-cufft-cu11==10.9.0.58
[pip3] nvidia-curand-cu11==10.3.0.86
[pip3] nvidia-cusolver-cu11==11.4.1.48
[pip3] nvidia-cusparse-cu11==11.7.5.86
[pip3] nvidia-nccl-cu11==2.21.5
[pip3] nvidia-nvtx-cu11==11.8.86
[pip3] torch==2.5.1+cu118
[pip3] torchaudio==2.5.1+cu118
[pip3] torchvision==0.20.1+cu118
[pip3] triton==3.1.0
[conda] Could not collect

cc @ezyang @gchanan @zou3519 @kadeng @msaroufim @EikanWang @jgong5 @wenzhe-nrv @sanchitintel