Repository: pytorch
Issue: torch.profiler.profile has an empty python replay stack under certain circumstances
Labels: triaged,oncall: profiler

### 🐛 Describe the bug

Under certain circumstances, the `torch.profiler.profile` will crash with the following error message:

```
RuntimeError: stack.size() INTERNAL ASSERT FAILED at
"/opt/conda/conda-bld/pytorch_1682343967769/work/torch/csrc/autograd/profiler_python.cpp":963,
please report a bug to PyTorch. Python replay stack is empty
```

It seems related to the usage of the `profile` object when wrapped in a function decorated by `@contextlib.contextmanager`. _However_, substituting such a function with a custom class that implements `__enter__` and `__exit__` does _**NOT**_ lead to errors. Similarly, foregoing this function entirely, and manually calling `profile.step()`, does not lead to errors.

It also does not fail for all parameterizations of `wait`, `warmup`, `active`, `repeat`, and `skip_first`.

## Minimal repro example

```python
import contextlib

import torch


def main(
    wait: int = 0,
    warmup: int = 0,
    active: int = 1,
    repeat: int = 2,
    skip_first: int = 0,
):
    """Main."""
    steps_per_cycle = wait + warmup + active
    # times 2 for testing extra steps.
    inner_steps = skip_first + steps_per_cycle * repeat * 2

    with _get_torch_profiler(
        wait=wait, warmup=warmup, active=active, repeat=repeat, skip_first=skip_first
    ) as p:
        for _ in range(inner_steps):
            # with _OnStep(p):
            with on_step(p):
                dummy_func()
                # p.step()


@contextlib.contextmanager
def on_step(profile):
    """On step context manager."""
    yield
    profile.step()


class _OnStep:
    def __init__(self, profile):
        self._profile = profile

    def __enter__(self):
        return None

    def __exit__(self, *args, **kwargs):
        self._profile.step()


def dummy_func():
    """A dummy function to be profiled."""
    model = torch.nn.Linear(1, 1)
    model.forward(torch.zeros(1))


def _get_schedule(wait, warmup, active, repeat, skip_first):
    return torch.profiler.schedule(
        wait=wait, warmup=warmup, active=active, repeat=repeat, skip_first=skip_first
    )


def _get_torch_profiler(wait, warmup, active, repeat, skip_first):
    activities = [
        torch.profiler.ProfilerActivity.CPU,
    ]

    return torch.profiler.profile(
        activities=activities,
        schedule=_get_schedule(
            wait=wait,
            warmup=warmup,
            active=active,
            repeat=repeat,
            skip_first=skip_first,
        ),
        record_shapes=True,
        with_stack=True,
        with_flops=True,
        profile_memory=False,
    )


if __name__ == "__main__":
    main()
```

In the above example, both of these changes will make the script pass:

* uncommenting line 22's `with _OnStep(p)`, and commenting out the line below it.
* commenting out line 23's `on_step(p)`, and uncommenting line 25's `p.step()`.

## Other notes

The above is a stripped version of a unit test suite where many more parameterizations of the arguments passed to `schedule` are tested. About a quarter of them fail; however, while some fail with same error as above, others that follow it will fail with:

```
    def __exit__(self, exc_type, exc_val, exc_tb):
        if not self.enabled:
            return
        if self.use_cuda:
            torch.cuda.synchronize()
>       self.kineto_results = _disable_profiler()
E       RuntimeError: Can't disable Kineto profiler when it's not running

3rdparty/bazel/pip/torch_cuda11/lib/torch/autograd/profiler.py:231: RuntimeError
```

Running the parameterizations that fail with the above in isolation will **PASS**, implying some global state not being cleaned up when exceptions are raised.

### Versions

Note that I tested this script in both of the following docker containers (both found [here](https://hub.docker.com/r/pytorch/pytorch)):

* `docker.io/pytorch/pytorch:2.0.0-cuda11.7-cudnn8-runtime`
* `docker.io/pytorch/pytorch:2.0.1-cuda11.7-cudnn8-runtime`

Output of the `collect_env.py` script in the latter:

```
PyTorch version: 2.0.1
Is debug build: False
CUDA used to build PyTorch: 11.7
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.6 LTS (x86_64)
GCC version: Could not collect
Clang version: Could not collect
CMake version: version 3.22.1
Libc version: glibc-2.31

Python version: 3.10.11 (main, Apr 20 2023, 19:02:41) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.4.0-66-generic-x86_64-with-glibc2.31
Is CUDA available: False
CUDA runtime version: No CUDA
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: No CUDA
Nvidia driver version: No CUDA
cuDNN version: No CUDA
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:                   46 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:                           85
Model name:                      Intel(R) Core(TM) i7-9800X CPU @ 3.80GHz
Stepping:                        4
CPU MHz:                         1200.350
CPU max MHz:                     4500.0000
CPU min MHz:                     1200.0000
BogoMIPS:                        7599.80
Virtualization:                  VT-x
L1d cache:                       256 KiB
L1i cache:                       256 KiB
L2 cache:                        8 MiB
L3 cache:                        16.5 MiB
NUMA node0 CPU(s):               0-15
Vulnerability Itlb multihit:     KVM: Mitigation: Split huge pages
Vulnerability L1tf:              Mitigation; PTE Inversion; VMX conditional cache flushes, SMT vulnerable
Vulnerability Mds:               Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Meltdown:          Mitigation; PTI
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; Full generic retpoline, IBPB conditional, IBRS_FW, STIBP conditional, RSB filling
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Mitigation; Clear CPU buffers; SMT vulnerable
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 pti ssbd mba ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm 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 md_clear flush_l1d

Versions of relevant libraries:
[pip3] numpy==1.24.3
[pip3] torch==2.0.1
[pip3] torchaudio==2.0.2
[pip3] torchdata==0.6.1
[pip3] torchelastic==0.2.2
[pip3] torchtext==0.15.2
[pip3] torchvision==0.15.2
[pip3] triton==2.0.0
[conda] blas                      1.0                         mkl  
[conda] ffmpeg                    4.3                  hf484d3e_0    pytorch
[conda] mkl                       2023.1.0         h6d00ec8_46342  
[conda] mkl-service               2.4.0           py310h5eee18b_1  
[conda] mkl_fft                   1.3.6           py310h1128e8f_1  
[conda] mkl_random                1.2.2           py310h1128e8f_1  
[conda] numpy                     1.24.3          py310h5f9d8c6_1  
[conda] numpy-base                1.24.3          py310hb5e798b_1  
[conda] pytorch                   2.0.1           py3.10_cuda11.7_cudnn8.5.0_0    pytorch
[conda] pytorch-cuda              11.7                 h778d358_5    pytorch
[conda] pytorch-mutex             1.0                        cuda    pytorch
[conda] torchaudio                2.0.2               py310_cu117    pytorch
[conda] torchdata                 0.6.1                     py310    pytorch
[conda] torchelastic              0.2.2                    pypi_0    pypi
[conda] torchtext                 0.15.2                    py310    pytorch
[conda] torchtriton               2.0.0                     py310    pytorch
[conda] torchvision               0.15.2              py310_cu117    pytorch
```

cc @robieta @chaekit @aaronenyeshi @ngimel @nbcsm @guotuofeng @guyang3532 @gaoteng-git @tiffzhaofb @dzhulgakov @davidberard98