Repository: pytorch
Issue: [Dynamo][DeepSpeed] torch._dynamo.exc.InternalTorchDynamoError: NestedUserFunctionVariable() has no type
Labels: needs reproduction,oncall: distributed,triaged,oncall: pt2,module: dynamo,dynamo-triage-june2024,dynamo-variable-tracker

### 🐛 Describe the bug

Hi,

We use `torch.compile` to run GPTJ3.6B model training on our GPU platforms, while we got some dynamo errors and the process aborted. The error is happening when running the below code in Megatron-DeepSpeed:
https://github.com/microsoft/Megatron-DeepSpeed/blob/6a8b2f589d20e2e162a47e3986fef774b42c318b/megatron/core/utils.py#L67
### Error logs

The Dynamo throws a error: **torch._dynamo.exc.InternalTorchDynamoError: name 'torch' is not defined** when the guard is eval the frame. I collect the error frame as below: 
```
[DUPLICATE_INPUT] guard =  Name: "___odict_getitem(L['self'].buffer, ('mpu', torch.bfloat16))"
    Source: local
    Create Function: DUPLICATE_INPUT
    Guard Types: None
    Code List: None
    Object Weakref: None
    Guarded Class Weakref: None

[DUPLICATE_INPUT] code =  ["L['___stack0'] is ___odict_getitem(L['self'].buffer, ('mpu', torch.bfloat16))"]
[get][GuardBuilder] name:  ___odict_getitem(L['self'].buffer, ('mpu', torch.bfloat16))
```

Here is the full back trace:
```
Traceback (most recent call last):
  File "/home/zhuhong/zejun/DS/llm.devkit/frameworks.ai.megatron-deepspeed/pretrain_gpt.py", line 375, in <module>
    pretrain(train_valid_test_datasets_provider,
  File "/home/zhuhong/zejun/DS/llm.devkit/frameworks.ai.megatron-deepspeed/megatron/training.py", line 225, in pretrain
    iteration = train(forward_step_func,
  File "/home/zhuhong/zejun/DS/llm.devkit/frameworks.ai.megatron-deepspeed/megatron/training.py", line 1192, in train
    train_step(forward_step_func,
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/_dynamo/eval_frame.py", line 328, in _fn
    return fn(*args, **kwargs)
  File "/home/zhuhong/zejun/DS/llm.devkit/frameworks.ai.megatron-deepspeed/megatron/training.py", line 682, in train_step
    forward_backward_func = get_forward_backward_func()
  File "/home/zhuhong/zejun/DS/llm.devkit/frameworks.ai.megatron-deepspeed/megatron/training.py", line 693, in <resume in train_step>
    losses_reduced = forward_backward_func(
  File "/home/zhuhong/zejun/DS/llm.devkit/frameworks.ai.megatron-deepspeed/megatron/core/pipeline_parallel/schedules.py", line 343, in forward_backward_no_pipelining
    model_type = get_model_type(model)
  File "/home/zhuhong/zejun/DS/llm.devkit/frameworks.ai.megatron-deepspeed/megatron/core/pipeline_parallel/schedules.py", line 358, in <resume in forward_backward_no_pipelining>
    output_tensor = forward_step(forward_step_func, data_iterator, model, num_microbatches,
  File "/home/zhuhong/zejun/DS/llm.devkit/frameworks.ai.megatron-deepspeed/megatron/core/pipeline_parallel/schedules.py", line 190, in forward_step
    set_input_tensor = get_attr_wrapped_model(model, "set_input_tensor")
  File "/home/zhuhong/zejun/DS/llm.devkit/frameworks.ai.megatron-deepspeed/megatron/core/pipeline_parallel/schedules.py", line 199, in <resume in forward_step>
    output_tensor, loss_func = forward_step_func(data_iterator, model)
  File "/home/zhuhong/zejun/DS/llm.devkit/frameworks.ai.megatron-deepspeed/pretrain_gpt.py", line 259, in forward_step
    tokens, labels, loss_mask, attention_mask, position_ids = get_batch(
  File "/home/zhuhong/zejun/DS/llm.devkit/frameworks.ai.megatron-deepspeed/pretrain_gpt.py", line 277, in <resume in forward_step>
    output_tensor, other_losses = model(tokens, position_ids, attention_mask,
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
    return forward_call(*args, **kwargs)
  File "/home/zhuhong/zejun/DS/llm.devkit/frameworks.ai.deepspeed/deepspeed/utils/nvtx.py", line 15, in wrapped_fn
    ret_val = func(*args, **kwargs)
  File "/home/zhuhong/zejun/DS/llm.devkit/frameworks.ai.deepspeed/deepspeed/runtime/engine.py", line 1777, in forward
    if self.global_steps == 0 and hasattr(self, "compression_scheduler"):
  File "/home/zhuhong/zejun/DS/llm.devkit/frameworks.ai.deepspeed/deepspeed/runtime/engine.py", line 1822, in <resume in forward>
    loss = self.module(*inputs, **kwargs)
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
    return forward_call(*args, **kwargs)
  File "/home/zhuhong/zejun/DS/llm.devkit/frameworks.ai.megatron-deepspeed/megatron/model/gpt_model.py", line 129, in forward
    lm_output, moe_losses = self.language_model(
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
    return forward_call(*args, **kwargs)
  File "/home/zhuhong/zejun/DS/llm.devkit/frameworks.ai.megatron-deepspeed/megatron/model/language_model.py", line 524, in forward
    encoder_input = self.embedding(enc_input_ids, enc_position_ids,
  File "/home/zhuhong/zejun/DS/llm.devkit/frameworks.ai.megatron-deepspeed/megatron/model/language_model.py", line 552, in <resume in forward>
    encoder_output, *encoder_moe_losses = self.encoder(
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
    return forward_call(*args, **kwargs)
  File "/home/zhuhong/zejun/DS/llm.devkit/frameworks.ai.megatron-deepspeed/megatron/model/transformer.py", line 1941, in forward
    hidden_states = layer(
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
    return forward_call(*args, **kwargs)
  File "/home/zhuhong/zejun/DS/llm.devkit/frameworks.ai.megatron-deepspeed/megatron/model/transformer.py", line 1217, in forward
    self.self_attention(
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
    return forward_call(*args, **kwargs)
  File "/home/zhuhong/zejun/DS/llm.devkit/frameworks.ai.megatron-deepspeed/megatron/model/transformer.py", line 678, in forward
    mixed_x_layer, _ = self.query_key_value(hidden_states)
  File "/home/zhuhong/zejun/DS/llm.devkit/frameworks.ai.megatron-deepspeed/megatron/model/transformer.py", line 815, in <resume in forward>
    context_layer = self.core_attention(
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
    return forward_call(*args, **kwargs)
  File "/home/zhuhong/zejun/DS/llm.devkit/frameworks.ai.megatron-deepspeed/megatron/model/transformer.py", line 294, in forward
    matmul_input_buffer = parallel_state.get_global_memory_buffer().get_tensor(
  File "/home/zhuhong/zejun/DS/llm.devkit/frameworks.ai.megatron-deepspeed/megatron/core/utils.py", line 67, in get_tensor
    if self.buffer.get((name, dtype), None) is None or \
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/_dynamo/eval_frame.py", line 493, in catch_errors
    return callback(frame, cache_entry, hooks, frame_state)
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/_dynamo/convert_frame.py", line 641, in _convert_frame
    result = inner_convert(frame, cache_size, hooks, frame_state)
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/_dynamo/convert_frame.py", line 133, in _fn
    return fn(*args, **kwargs)
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/_dynamo/convert_frame.py", line 389, in _convert_frame_assert
    return _compile(
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/_dynamo/convert_frame.py", line 586, in _compile
    raise InternalTorchDynamoError(str(e)).with_traceback(
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/_dynamo/convert_frame.py", line 569, in _compile
    guarded_code = compile_inner(code, one_graph, hooks, transform)
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/_dynamo/utils.py", line 189, in time_wrapper
    r = func(*args, **kwargs)
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/_dynamo/convert_frame.py", line 549, in compile_inner
    check_fn = CheckFunctionManager(
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/_dynamo/guards.py", line 932, in __init__
    guard.create(local_builder, global_builder)
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/_guards.py", line 243, in create
    return self.create_fn(self.source.select(local_builder, global_builder), self)
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/_dynamo/guards.py", line 470, in DUPLICATE_INPUT
    self._produce_guard_code(guard, code)
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/_dynamo/guards.py", line 742, in _produce_guard_code
    guarded_object = self.get(guard.name) if name_valid else None
  File "/home/zhuhong/miniconda3/envs/zejun_ds/lib/python3.9/site-packages/torch/_dynamo/guards.py", line 235, in get
    return eval(name, self.scope, CLOSURE_VARS)
  File "<string>", line 1, in <module>
torch._dynamo.exc.InternalTorchDynamoError: name 'torch' is not defined
```

### Minified repro

For now the small reproducer is not implemented yet.

### Versions

```
PyTorch version: 2.1.0a0+git44d1ed8
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: Could not collect
CMake version: version 3.28.1
Libc version: glibc-2.35

Python version: 3.9.7 | packaged by conda-forge | (default, Sep 29 2021, 19:23:11)  [GCC 9.4.0] (64-bit runtime)
Python platform: Linux-5.15.47+prerelease23.6.33-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:                   52 bits physical, 57 bits virtual
Byte Order:                      Little Endian
CPU(s):                          224
On-line CPU(s) list:             0-223
Vendor ID:                       GenuineIntel
Model name:                      Intel(R) Xeon(R) Platinum 8480+
CPU family:                      6
Model:                           143
Thread(s) per core:              2
Core(s) per socket:              56
Socket(s):                       2
Stepping:                        6
CPU max MHz:                     3800.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 tsc_known_freq 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 cat_l2 cdp_l3 invpcid_single cdp_l2 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 avx_vnni avx512_bf16 wbnoinvd dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b enqcmd fsrm md_clear serialize tsxldtrk pconfig arch_lbr avx512_fp16 flush_l1d arch_capabilities
Virtualization:                  VT-x
L1d cache:                       5.3 MiB (112 instances)
L1i cache:                       3.5 MiB (112 instances)
L2 cache:                        224 MiB (112 instances)
L3 cache:                        210 MiB (2 instances)
NUMA node(s):                    2
NUMA node0 CPU(s):               0-55,112-167
NUMA node1 CPU(s):               56-111,168-223
Vulnerability Itlb multihit:     Not affected
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Not affected
Vulnerability Meltdown:          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
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected

Versions of relevant libraries:
[pip3] flake8==4.0.1
[pip3] intel-extension-for-pytorch==2.1.10+git4929a52
[pip3] numpy==1.26.2
[pip3] torch==2.1.0a0+git44d1ed8
[pip3] torchvision==0.15.2a0+cxx11.abi
[pip3] triton==2.1.0
[conda] intel-extension-for-pytorch 2.1.10+git4929a52          pypi_0    pypi
[conda] numpy                     1.26.2                   pypi_0    pypi
[conda] torch                     2.1.0a0+git44d1ed8          pypi_0    pypi
[conda] torchvision               0.15.2a0+cxx11.abi          pypi_0    pypi
[conda] triton                    2.1.0                    pypi_0    pypi
```

cc @mrshenli @pritamdamania87 @zhaojuanmao @satgera @gqchen @aazzolini @osalpekar @jiayisuse @H-Huang @kwen2501 @awgu @penguinwu @fegin @XilunWu @wanchaol @fduwjj @wz337 @tianyu-l @wconstab @yf225 @chauhang @d4l3k @ezyang @anijain2305 @voznesenskym @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @chenyang78 @kadeng @rohan-varma @msaroufim @bdhirsh @zou3519 @aakhundov