[ONNX] Export of `torch.distributions.normal.Normal` fails in functionalization
Labels: module: onnx, triaged, onnx-triaged, module: dynamo

```python
import torch

class Model(torch.nn.Module):
    def __init__(self):
        self.normal = torch.distributions.normal.Normal(0, 1)
        super().__init__()

    def forward(self, x):
        return self.normal.sample(x.shape)


model = Model()
x = torch.randn(2, 3)
print(model(x))
print(torch.onnx.dynamo_export(model, x).model_proto)
```

Fails with 

```
tensor([[-0.4411, -1.2260,  0.9509],
        [-1.6602,  2.4344,  2.1532]])
/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/onnx/_internal/exporter.py:130: UserWarning: torch.onnx.dynamo_export only implements opset version 18 for now. If you need to use a different opset version, please register them with register_custom_op.
  warnings.warn(
Traceback (most recent call last):
  File "/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/onnx/_internal/exporter.py", line 1195, in dynamo_export
    ).export()
  File "/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/onnx/_internal/exporter.py", line 950, in export
    graph_module = pre_export_passes(
  File "<@beartype(torch.onnx._internal.exporter.pre_export_passes) at 0x7f9de3794f70>", line 97, in pre_export_passes
  File "/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/onnx/_internal/exporter.py", line 1235, in pre_export_passes
    module = passes.Functionalize(
  File "/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/decorator.py", line 151, in wrapper
    ctx.log_and_raise_if_error(diag)
  File "/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/context.py", line 366, in log_and_raise_if_error
    raise diagnostic.source_exception
  File "/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/decorator.py", line 135, in wrapper
    return_values = fn(*args, **kwargs)
  File "/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/onnx/_internal/fx/_pass.py", line 267, in run
    module = self._run(*args, **kwargs)
  File "<@beartype(torch.onnx._internal.fx.passes.functionalization.Functionalize._run) at 0x7f9de37fcee0>", line 11, in _run
  File "/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/onnx/_internal/fx/passes/functionalization.py", line 123, in _run
    graph_module = proxy_tensor.make_fx(
  File "/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/fx/experimental/proxy_tensor.py", line 841, in wrapped
    t = dispatch_trace(wrap_key(func, args, fx_tracer, pre_dispatch), tracer=fx_tracer, concrete_args=tuple(phs))
  File "/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/_compile.py", line 24, in inner
    return torch._dynamo.disable(fn, recursive)(*args, **kwargs)
  File "/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py", line 406, in _fn
    return fn(*args, **kwargs)
  File "/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/_dynamo/external_utils.py", line 17, in inner
    return fn(*args, **kwargs)
  File "/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/fx/experimental/proxy_tensor.py", line 461, in dispatch_trace
    graph = tracer.trace(root, concrete_args)
  File "/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py", line 406, in _fn
    return fn(*args, **kwargs)
  File "/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/_dynamo/external_utils.py", line 17, in inner
    return fn(*args, **kwargs)
  File "/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/fx/_symbolic_trace.py", line 817, in trace
    (self.create_arg(fn(*args)),),
  File "/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/fx/experimental/proxy_tensor.py", line 497, in wrapped
    out = f(*tensors)
  File "<string>", line 1, in <lambda>
  File "/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/onnx/_internal/fx/passes/functionalization.py", line 95, in wrapped
    pytree.tree_map(torch._sync, out)
  File "/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/utils/_pytree.py", line 291, in tree_map
    return tree_unflatten([fn(i) for i in flat_args], spec)
  File "/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/utils/_pytree.py", line 291, in <listcomp>
    return tree_unflatten([fn(i) for i in flat_args], spec)
  File "/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/_utils.py", line 881, in _functionalize_sync
    torch._functionalize_sync(t)
RuntimeError: at::functionalization::impl::isFunctionalTensor(self_) INTERNAL ASSERT FAILED at "../torch/csrc/autograd/python_torch_functions_manual.cpp":561, please report a bug to PyTorch. 

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/justinchu/dev/onnx-script/onnxscript/export.py", line 16, in <module>
    print(torch.onnx.dynamo_export(model, x).model_proto)
  File "<@beartype(torch.onnx._internal.exporter.dynamo_export) at 0x7f9de3794e50>", line 53, in dynamo_export
  File "/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/onnx/_internal/exporter.py", line 1206, in dynamo_export
    raise OnnxExporterError(
torch.onnx.OnnxExporterError: Failed to export the model to ONNX. Generating SARIF report at 'report_dynamo_export.sarif'. SARIF is a standard format for the output of static analysis tools. SARIF logs can be loaded in VS Code SARIF viewer extension, or SARIF web viewer (https://microsoft.github.io/sarif-web-component/). Please report a bug on PyTorch Github: https://github.com/pytorch/pytorch/issues
```


### SARIF

```json
{
 "runs":[
  {
   "tool":{
    "driver":{
     "name":"torch.onnx.dynamo_export",
     "contents":[
      "localizedData",
      "nonLocalizedData"
     ],
     "language":"en-US",
     "rules":[
      {
       "id":"FXE0010",
       "fullDescription":{
        "text":"FX graph transformation during ONNX export before converting from FX IR to ONNX IR.",
        "markdown":"This diagnostic tracks the FX passes executed during the ONNX export process prior\nto converting from FX IR (Intermediate Representation) to ONNX IR.\n\nUnder the scope of ONNX export, an FX pass refers to a specific transformation applied to the FX GraphModule.\nThe primary aim of these passes is to streamline the graph into a format that aligns more with the ONNX IR.\nMoreover, these passes work to substitute unsupported FX IR features with those recognized and endorsed by\nONNX IR. Common transformations include, but aren't limited to, decomposition, functionalization and\ntype promotion.\n\nFor those who are interested in a comprehensive log detailing the modifications made during these passes,\nthere are a couple of options:\n\n- Set DiagnosticOptions.verbosity_level to logging.DEBUG.\n- Activate the environment variable TORCH_LOGS='onnx_diagnostics'.\n\nHowever, it's noteworthy that by default, such detailed logging is turned off. The primary reason being\nits considerable impact on performance.\n\nFor an in-depth understanding of each specific pass, please refer to the directory: torch/onnx/_internal/fx/passes.\n"
       },
       "name":"fx-pass",
       "shortDescription":{
        "text":"FX graph transformation during ONNX export before converting from FX IR to ONNX IR."
       }
      }
     ],
     "version":"2.2.0.dev20231011+cpu"
    }
   },
   "language":"en-US",
   "newlineSequences":[
    "\r\n",
    "\n"
   ],
   "results":[
    {
     "message":{
      "markdown":"Running Decompose pass. \n\n## Additional Message:\n\n## Function Signature\n### Function Signature Transform.run\n- self: <class 'torch.onnx._internal.fx.passes.decomp.Decompose'>\n- args: Tuple[length=1](\nTensor(f32[2, 3]),\n)\nFor detailed logging of graph modifications by this pass, either set `DiagnosticOptions.verbosity_level` to `logging.DEBUG` or use the environment variable `TORCH_LOGS='onnx_diagnostics'`.\n## Return values\ntorch.fx.GraphModule(<lambda>)",
      "text":"Running Decompose pass. "
     },
     "codeFlows":[
      {
       "threadFlows":[
        {
         "locations":[]
        }
       ]
      }
     ],
     "graphs":[],
     "kind":"informational",
     "level":"none",
     "locations":[
      {
       "message":{
        "text":"Transform.run"
       },
       "physicalLocation":{
        "artifactLocation":{
         "uri":"/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/onnx/_internal/fx/_pass.py"
        },
        "region":{
         "snippet":{
          "text":"@diagnostics.diagnose_call("
         },
         "startLine":232
        }
       }
      }
     ],
     "properties":{
      "tags":[]
     },
     "ruleId":"FXE0010",
     "stacks":[]
    },
    {
     "message":{
      "markdown":"Running Functionalize pass. \n\n## Additional Message:\n\n## Function Signature\n### Function Signature Transform.run\n- self: <class 'torch.onnx._internal.fx.passes.functionalization.Functionalize'>\n- args: Tuple[length=1](\nTensor(f32[2, 3]),\n)\nFor detailed logging of graph modifications by this pass, either set `DiagnosticOptions.verbosity_level` to `logging.DEBUG` or use the environment variable `TORCH_LOGS='onnx_diagnostics'`.\n## Exception log\n```\nTraceback (most recent call last):\n\n  File \"/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/onnx/_internal/diagnostics/infra/decorator.py\", line 135, in wrapper\n    return_values = fn(*args, **kwargs)\n\n  File \"/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/onnx/_internal/fx/_pass.py\", line 267, in run\n    module = self._run(*args, **kwargs)\n\n  File \"<@beartype(torch.onnx._internal.fx.passes.functionalization.Functionalize._run) at 0x7feb91391b40>\", line 11, in _run\n\n  File \"/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/onnx/_internal/fx/passes/functionalization.py\", line 123, in _run\n    graph_module = proxy_tensor.make_fx(\n\n  File \"/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/fx/experimental/proxy_tensor.py\", line 858, in wrapped\n    t = dispatch_trace(wrap_key(func, args, fx_tracer, pre_dispatch), tracer=fx_tracer, concrete_args=tuple(phs))\n\n  File \"/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/_compile.py\", line 24, in inner\n    return torch._dynamo.disable(fn, recursive)(*args, **kwargs)\n\n  File \"/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py\", line 401, in _fn\n    return fn(*args, **kwargs)\n\n  File \"/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/_dynamo/external_utils.py\", line 17, in inner\n    return fn(*args, **kwargs)\n\n  File \"/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/fx/experimental/proxy_tensor.py\", line 478, in dispatch_trace\n    graph = tracer.trace(root, concrete_args)\n\n  File \"/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py\", line 401, in _fn\n    return fn(*args, **kwargs)\n\n  File \"/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/_dynamo/external_utils.py\", line 17, in inner\n    return fn(*args, **kwargs)\n\n  File \"/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/fx/_symbolic_trace.py\", line 817, in trace\n    (self.create_arg(fn(*args)),),\n\n  File \"/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/fx/experimental/proxy_tensor.py\", line 514, in wrapped\n    out = f(*tensors)\n\n  File \"<string>\", line 1, in <lambda>\n\n  File \"/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/onnx/_internal/fx/passes/functionalization.py\", line 95, in wrapped\n    pytree.tree_map(torch._sync, out)\n\n  File \"/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/utils/_pytree.py\", line 314, in tree_map\n    return tree_unflatten([fn(i) for i in flat_args], spec)\n\n  File \"/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/utils/_pytree.py\", line 314, in <listcomp>\n    return tree_unflatten([fn(i) for i in flat_args], spec)\n\n  File \"/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/_utils.py\", line 881, in _functionalize_sync\n    torch._functionalize_sync(t)  # type: ignore[attr-defined]\n\nRuntimeError: at::functionalization::impl::isFunctionalTensor(self_) INTERNAL ASSERT FAILED at \"../torch/csrc/autograd/python_torch_functions_manual.cpp\":598, please report a bug to PyTorch. \n\n```",
      "text":"Running Functionalize pass. "
     },
     "codeFlows":[
      {
       "threadFlows":[
        {
         "locations":[]
        }
       ]
      }
     ],
     "graphs":[],
     "kind":"fail",
     "level":"error",
     "locations":[
      {
       "message":{
        "text":"Transform.run"
       },
       "physicalLocation":{
        "artifactLocation":{
         "uri":"/home/justinchu/anaconda3/envs/onnx/lib/python3.10/site-packages/torch/onnx/_internal/fx/_pass.py"
        },
        "region":{
         "snippet":{
          "text":"@diagnostics.diagnose_call("
         },
         "startLine":232
        }
       }
      }
     ],
     "properties":{
      "tags":[]
     },
     "ruleId":"FXE0010",
     "stacks":[]
    }
   ]
  }
 ],
 "version":"2.1.0",
 "schemaUri":"https://docs.oasis-open.org/sarif/sarif/v2.1.0/cs01/schemas/sarif-schema-2.1.0.json"
}
```

## Environments

```
Collecting environment information...
PyTorch version: 2.2.0.dev20231011+cpu
Is debug build: False
CUDA used to build PyTorch: None
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.3 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: 14.0.0-1ubuntu1.1
CMake version: version 3.26.3
Libc version: glibc-2.35

Python version: 3.10.9 (main, Jan 11 2023, 15:21:40) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-6.2.0-1011-azure-x86_64-with-glibc2.35
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
Address sizes:                      46 bits physical, 48 bits virtual
Byte Order:                         Little Endian
CPU(s):                             64
On-line CPU(s) list:                0-63
Vendor ID:                          GenuineIntel
Model name:                         Intel(R) Xeon(R) Platinum 8370C CPU @ 2.80GHz
CPU family:                         6
Model:                              106
Thread(s) per core:                 2
Core(s) per socket:                 32
Socket(s):                          1
Stepping:                           6
BogoMIPS:                           5586.87
Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology cpuid pni pclmulqdq vmx ssse3 fma cx16 pcid sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single pti tpr_shadow vnmi ept vpid fsgsbase bmi1 hle avx2 smep bmi2 erms invpcid rtm avx512f avx512dq rdseed adx smap clflushopt avx512cd avx512bw avx512vl xsaveopt xsavec xsaves md_clear
Virtualization:                     VT-x
Hypervisor vendor:                  Microsoft
Virtualization type:                full
L1d cache:                          1.5 MiB (32 instances)
L1i cache:                          1 MiB (32 instances)
L2 cache:                           40 MiB (32 instances)
L3 cache:                           48 MiB (1 instance)
NUMA node(s):                       1
NUMA node0 CPU(s):                  0-63
Vulnerability Gather data sampling: Unknown: Dependent on hypervisor status
Vulnerability Itlb multihit:        KVM: Mitigation: VMX disabled
Vulnerability L1tf:                 Mitigation; PTE Inversion; VMX conditional cache flushes, SMT vulnerable
Vulnerability Mds:                  Mitigation; Clear CPU buffers; SMT Host state unknown
Vulnerability Meltdown:             Mitigation; PTI
Vulnerability Mmio stale data:      Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown
Vulnerability Retbleed:             Not affected
Vulnerability Spec store bypass:    Vulnerable
Vulnerability Spectre v1:           Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:           Mitigation; Retpolines, STIBP disabled, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Mitigation; Clear CPU buffers; SMT Host state unknown

Versions of relevant libraries:
[pip3] flake8==6.1.0
[pip3] mypy==1.5.1
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.25.1
[pip3] onnx-function-experiment==1.13.0.dev20230109
[pip3] onnx-script==0.1.0
[pip3] onnx-weekly==1.15.0.dev20231002
[pip3] onnxconverter-common==1.13.0
[pip3] onnxruntime==1.16.0
[pip3] onnxscript==0.1.0.dev20230913
[pip3] torch==2.2.0.dev20231011+cpu
[pip3] torchaudio==2.2.0.dev20231011+cpu
[pip3] torchvision==0.17.0.dev20231011+cpu
[pip3] triton==2.1.0
[conda] numpy                     1.25.1                   pypi_0    pypi
[conda] torch                     2.2.0.dev20231011+cpu          pypi_0    pypi
[conda] torchaudio                2.2.0.dev20231011+cpu          pypi_0    pypi
[conda] torchvision               0.17.0.dev20231011+cpu          pypi_0    pypi
[conda] triton                    2.1.0                    pypi_0    pypi
```

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @Xia-Weiwen @wenzhe-nrv @jiayisunx @chenyang78 @aakhundov @kadeng