"InternalTorchDynamoError: source code not available" when using `torch.compile` in ipynb or google colab
Labels: high priority, triage review, triaged, oncall: pt2

### 🐛 Describe the bug

Hi!
Following snippet produces errors:
```py3
import torch
print(torch.__version__) # Tried with 2.1.0+cu121 (latest) and 2.0.1 (default in google colab). All fails

class Linear(nn.Linear):
  def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)

  def forward(self, *args, **kwargs):
    return super().forward(*args, **kwargs)

m = Linear(4, 8)
m(torch.randn(3, 4)) # passes

compiled_m = torch.compile(m) # passes
compiled_m(torch.randn(3, 4)) # fails
```

<details>
  <summary> Traceback: </summary>

```pytb
2.1.0+cu121
---------------------------------------------------------------------------
InternalTorchDynamoError                  Traceback (most recent call last)
[<ipython-input-19-61daefda3be3>](https://localhost:8080/#) in <cell line: 15>()
     13 
     14 compiled_m = torch.compile(m) # passes
---> 15 compiled_m(torch.randn(3, 4)) # fails

21 frames
[/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py](https://localhost:8080/#) in _wrapped_call_impl(self, *args, **kwargs)
   1516             return self._compiled_call_impl(*args, **kwargs)  # type: ignore[misc]
   1517         else:
-> 1518             return self._call_impl(*args, **kwargs)
   1519 
   1520     def _call_impl(self, *args, **kwargs):

[/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py](https://localhost:8080/#) in _call_impl(self, *args, **kwargs)
   1525                 or _global_backward_pre_hooks or _global_backward_hooks
   1526                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1527             return forward_call(*args, **kwargs)
   1528 
   1529         try:

[/usr/local/lib/python3.10/dist-packages/torch/_dynamo/eval_frame.py](https://localhost:8080/#) in _fn(*args, **kwargs)
    326             dynamic_ctx.__enter__()
    327             try:
--> 328                 return fn(*args, **kwargs)
    329             finally:
    330                 set_eval_frame(prior)

[/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py](https://localhost:8080/#) in _wrapped_call_impl(self, *args, **kwargs)
   1516             return self._compiled_call_impl(*args, **kwargs)  # type: ignore[misc]
   1517         else:
-> 1518             return self._call_impl(*args, **kwargs)
   1519 
   1520     def _call_impl(self, *args, **kwargs):

[/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py](https://localhost:8080/#) in _call_impl(self, *args, **kwargs)
   1525                 or _global_backward_pre_hooks or _global_backward_hooks
   1526                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1527             return forward_call(*args, **kwargs)
   1528 
   1529         try:

[/usr/local/lib/python3.10/dist-packages/torch/_dynamo/eval_frame.py](https://localhost:8080/#) in catch_errors(frame, cache_entry, frame_state)
    488 
    489         with compile_lock, _disable_current_modes():
--> 490             return callback(frame, cache_entry, hooks, frame_state)
    491 
    492     catch_errors._torchdynamo_orig_callable = callback  # type: ignore[attr-defined]

[/usr/local/lib/python3.10/dist-packages/torch/_dynamo/convert_frame.py](https://localhost:8080/#) in _convert_frame(frame, cache_size, hooks, frame_state)
    639         counters["frames"]["total"] += 1
    640         try:
--> 641             result = inner_convert(frame, cache_size, hooks, frame_state)
    642             counters["frames"]["ok"] += 1
    643             return result

[/usr/local/lib/python3.10/dist-packages/torch/_dynamo/convert_frame.py](https://localhost:8080/#) in _fn(*args, **kwargs)
    131         cleanup = setup_compile_debug()
    132         try:
--> 133             return fn(*args, **kwargs)
    134         finally:
    135             cleanup.close()

[/usr/local/lib/python3.10/dist-packages/torch/_dynamo/convert_frame.py](https://localhost:8080/#) in _convert_frame_assert(frame, cache_entry, hooks, frame_state)
    387         )
    388 
--> 389         return _compile(
    390             frame.f_code,
    391             frame.f_globals,

[/usr/local/lib/python3.10/dist-packages/torch/_dynamo/convert_frame.py](https://localhost:8080/#) in _compile(code, globals, locals, builtins, compiler_fn, one_graph, export, export_constraints, hooks, cache_size, frame, frame_state, compile_id)
    584             fail_reason = str(e)
    585             exception_handler(e, code, frame, export=export)
--> 586             raise InternalTorchDynamoError(str(e)).with_traceback(
    587                 e.__traceback__
    588             ) from None

[/usr/local/lib/python3.10/dist-packages/torch/_dynamo/convert_frame.py](https://localhost:8080/#) in _compile(code, globals, locals, builtins, compiler_fn, one_graph, export, export_constraints, hooks, cache_size, frame, frame_state, compile_id)
    567     with compile_context(CompileContext(compile_id)):
    568         try:
--> 569             guarded_code = compile_inner(code, one_graph, hooks, transform)
    570             return guarded_code
    571         except (

[/usr/local/lib/python3.10/dist-packages/torch/_dynamo/utils.py](https://localhost:8080/#) in time_wrapper(*args, **kwargs)
    187             with torch.profiler.record_function(f"{key} (dynamo_timed)"):
    188                 t0 = time.time()
--> 189                 r = func(*args, **kwargs)
    190                 time_spent = time.time() - t0
    191             compilation_time_metrics[key].append(time_spent)

[/usr/local/lib/python3.10/dist-packages/torch/_dynamo/convert_frame.py](https://localhost:8080/#) in compile_inner(code, one_graph, hooks, transform)
    489         for attempt in itertools.count():
    490             try:
--> 491                 out_code = transform_code_object(code, transform)
    492                 orig_code_map[out_code] = code
    493                 break

[/usr/local/lib/python3.10/dist-packages/torch/_dynamo/bytecode_transformation.py](https://localhost:8080/#) in transform_code_object(code, transformations, safe)
   1026     propagate_line_nums(instructions)
   1027 
-> 1028     transformations(instructions, code_options)
   1029     return clean_and_assemble_instructions(instructions, keys, code_options)[1]
   1030 

[/usr/local/lib/python3.10/dist-packages/torch/_dynamo/convert_frame.py](https://localhost:8080/#) in transform(instructions, code_options)
    439     def transform(instructions, code_options):
    440         nonlocal output
--> 441         tracer = InstructionTranslator(
    442             instructions,
    443             code,

[/usr/local/lib/python3.10/dist-packages/torch/_dynamo/symbolic_convert.py](https://localhost:8080/#) in __init__(self, instructions, f_code, f_locals, f_globals, f_builtins, code_options, compiler_fn, one_graph, export, export_constraints, mutated_closure_cell_contents, frame_state)
   2016             cells_and_freevars_set = set(cells_and_freevars)
   2017 
-> 2018             self.symbolic_locals = collections.OrderedDict(
   2019                 (
   2020                     k,

[/usr/local/lib/python3.10/dist-packages/torch/_dynamo/symbolic_convert.py](https://localhost:8080/#) in <genexpr>(.0)
   2019                 (
   2020                     k,
-> 2021                     VariableBuilder(
   2022                         self,
   2023                         LocalSource(k, cell_or_freevar=k in cells_and_freevars_set),

[/usr/local/lib/python3.10/dist-packages/torch/_dynamo/variables/builder.py](https://localhost:8080/#) in __call__(self, value)
    221                 )
    222             return side_effect_result
--> 223         vt = self._wrap(value).clone(**self.options())
    224         if self._can_lift_attrs_to_inputs(vt):
    225             vt = self.tx.output.side_effects.track_object_existing(

[/usr/local/lib/python3.10/dist-packages/torch/_dynamo/variables/builder.py](https://localhost:8080/#) in _wrap(self, value)
    490         elif (
    491             istype(value, (type, types.FunctionType))
--> 492             and skipfiles.check(getfile(value), allow_torch=True)
    493             and not inspect.getattr_static(value, "_torchdynamo_inline", False)
    494         ):

[/usr/local/lib/python3.10/dist-packages/torch/_dynamo/utils.py](https://localhost:8080/#) in getfile(obj)
    670 def getfile(obj):
    671     try:
--> 672         return inspect.getfile(obj)
    673     except TypeError:
    674         return None

[/usr/local/lib/python3.10/dist-packages/torch/package/package_importer.py](https://localhost:8080/#) in _patched_getfile(object)
    694         if object.__module__ in _package_imported_modules:
    695             return _package_imported_modules[object.__module__].__file__
--> 696     return _orig_getfile(object)
    697 
    698 

[/usr/lib/python3.10/inspect.py](https://localhost:8080/#) in getfile(object)
    783                 return module.__file__
    784             if object.__module__ == '__main__':
--> 785                 raise OSError('source code not available')
    786         raise TypeError('{!r} is a built-in class'.format(object))
    787     if ismethod(object):

InternalTorchDynamoError: source code not available

from user code:
 
Set TORCH_LOGS="+dynamo" and TORCHDYNAMO_VERBOSE=1 for more information


You can suppress this exception and fall back to eager by setting:
    import torch._dynamo
    torch._dynamo.config.suppress_errors = True
```
</details>

I guess Issue happens with all user defined models `forward` inside ipynb.

### Versions

```
Collecting environment information...
PyTorch version: 2.1.0+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.2 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.27.6
Libc version: glibc-2.35

Python version: 3.10.12 (main, Jun 11 2023, 05:26:28) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-5.15.120+-x86_64-with-glibc2.35
Is CUDA available: False
CUDA runtime version: 11.8.89
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: Could not collect
Nvidia driver version: Could not collect
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.0
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):                          2
On-line CPU(s) list:             0,1
Vendor ID:                       GenuineIntel
Model name:                      Intel(R) Xeon(R) CPU @ 2.20GHz
CPU family:                      6
Model:                           79
Thread(s) per core:              2
Core(s) per socket:              1
Socket(s):                       1
Stepping:                        0
BogoMIPS:                        4400.43
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 nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm rdseed adx smap xsaveopt arat md_clear arch_capabilities
Hypervisor vendor:               KVM
Virtualization type:             full
L1d cache:                       32 KiB (1 instance)
L1i cache:                       32 KiB (1 instance)
L2 cache:                        256 KiB (1 instance)
L3 cache:                        55 MiB (1 instance)
NUMA node(s):                    1
NUMA node0 CPU(s):               0,1
Vulnerability Itlb multihit:     Not affected
Vulnerability L1tf:              Mitigation; PTE Inversion
Vulnerability Mds:               Vulnerable; SMT Host state unknown
Vulnerability Meltdown:          Vulnerable
Vulnerability Mmio stale data:   Vulnerable
Vulnerability Retbleed:          Vulnerable
Vulnerability Spec store bypass: Vulnerable
Vulnerability Spectre v1:        Vulnerable: __user pointer sanitization and usercopy barriers only; no swapgs barriers
Vulnerability Spectre v2:        Vulnerable, IBPB: disabled, STIBP: disabled, PBRSB-eIBRS: Not affected
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Vulnerable

Versions of relevant libraries:
[pip3] numpy==1.23.5
[pip3] torch==2.1.0
[pip3] torchaudio==2.0.2+cu118
[pip3] torchdata==0.6.1
[pip3] torchinfo==1.8.0
[pip3] torchsummary==1.5.1
[pip3] torchtext==0.15.2
[pip3] torchvision==0.15.2+cu118
[pip3] triton==2.1.0
[conda] Could not collect
```

cc @ezyang @gchanan @zou3519 @kadeng @msaroufim @wconstab @bdhirsh @anijain2305