pytorch - 💡(How to fix) Fix Replacing a submodule's `__call__` with `fx.Interpreter` on its exported `gm` causes the parent's output to contain `FakeTensor`

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…

Error Message

import torch from torch._subclasses.fake_tensor import FakeTensor from torch.fx._pytree import tree_flatten_spec from transformers import CLIPTextModel, CLIPTextConfig

def install_hook(): original_call = torch.nn.Module.call captures = {} guard = {"active": False} target_classes = {"CLIPTextEmbeddings", "CLIPEncoder"}

def hook_call(self, *args, **kwargs):
    if guard["active"]:
        return original_call(self, *args, **kwargs)
    cls_name = type(self).__qualname__
    if cls_name not in target_classes:
        return original_call(self, *args, **kwargs)
    if cls_name not in captures:
        try:
            ep = torch.export.export(self, args, kwargs=kwargs, strict=False)
            captures[cls_name] = ep.module()
        except Exception:
            captures[cls_name] = None
            return original_call(self, *args, **kwargs)
    gm = captures[cls_name]
    if gm is None:
        return original_call(self, *args, **kwargs)
    guard["active"] = True
    try:
        flat = tree_flatten_spec((list(args), kwargs), gm._in_spec)
        return torch.fx.Interpreter(gm).run(*flat)
    finally:
        guard["active"] = False

torch.nn.Module.__call__ = hook_call
return original_call

cfg = CLIPTextConfig(hidden_size=64, intermediate_size=128, num_hidden_layers=2, num_attention_heads=2, max_position_embeddings=77, vocab_size=100) m = CLIPTextModel(cfg).eval() input_ids = torch.zeros(1, 77, dtype=torch.long)

WITHOUT the hook — sanity baseline: every output is real

with torch.no_grad(): baseline = m(input_ids, output_hidden_states=True) assert not isinstance(baseline.last_hidden_state, FakeTensor) assert all(not isinstance(h, FakeTensor) for h in baseline.hidden_states)

WITH the hook — last_hidden_state stays real, hidden_states all turn fake

orig = install_hook() try: with torch.no_grad(): out = m(input_ids, output_hidden_states=True) finally: torch.nn.Module.call = orig

print(f"last_hidden_state fake: {isinstance(out.last_hidden_state, FakeTensor)}") for i, h in enumerate(out.hidden_states): print(f"hidden_states[{i}]: fake={isinstance(h, FakeTensor)}")

Fix Action

Fix / Workaround

What we get: the parent returns a BaseModelOutputWithPooling where last_hidden_state is real but every entry in hidden_states is a FakeTensor — even though both fields come from the same internal computation. No FakeTensorMode is active on the dispatcher stack. The captured gm's parameters, buffers, and graph attributes are all real. The submodule's exported gm returns clean outputs when called in isolation.

So nothing on the dispatcher stack, on the model, or on the captured graph is fake. The fake values appear only in the parent's reconstructed output when the parent runs eager and reads from the substituted submodule's return.

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 46 bits physical, 57 bits virtual Byte Order: Little Endian CPU(s): 48 On-line CPU(s) list: 0-47 Vendor ID: GenuineIntel Model name: Intel(R) Xeon(R) Silver 4410Y CPU family: 6 Model: 143 Thread(s) per core: 2 Core(s) per socket: 12 Socket(s): 2 Stepping: 8 CPU max MHz: 3900.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 intel_ppin cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow 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 user_shstk avx_vnni avx512_bf16 wbnoinvd dtherm ida arat pln pts hfi vnmi 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 ibt amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities ibpb_exit_to_user Virtualization: VT-x L1d cache: 1.1 MiB (24 instances) L1i cache: 768 KiB (24 instances) L2 cache: 48 MiB (24 instances) L3 cache: 60 MiB (2 instances) NUMA node(s): 2 NUMA node0 CPU(s): 0-11,24-35 NUMA node1 CPU(s): 12-23,36-47 Vulnerability Gather data sampling: Not affected Vulnerability Indirect target selection: Not affected Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Not affected Vulnerability Reg file data sampling: Not affected Vulnerability Retbleed: Not affected Vulnerability Spec rstack overflow: Not affected Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; Enhanced / Automatic IBRS; IBPB conditional; PBRSB-eIBRS SW sequence; BHI BHI_DIS_S Vulnerability Srbds: Not affected Vulnerability Tsa: Not affected Vulnerability Tsx async abort: Not affected Vulnerability Vmscape: Mitigation; IBPB before exit to userspace

Code Example

import torch
from torch._subclasses.fake_tensor import FakeTensor
from torch.fx._pytree import tree_flatten_spec
from transformers import CLIPTextModel, CLIPTextConfig


def install_hook():
    original_call = torch.nn.Module.__call__
    captures = {}
    guard = {"active": False}
    target_classes = {"CLIPTextEmbeddings", "CLIPEncoder"}

    def hook_call(self, *args, **kwargs):
        if guard["active"]:
            return original_call(self, *args, **kwargs)
        cls_name = type(self).__qualname__
        if cls_name not in target_classes:
            return original_call(self, *args, **kwargs)
        if cls_name not in captures:
            try:
                ep = torch.export.export(self, args, kwargs=kwargs, strict=False)
                captures[cls_name] = ep.module()
            except Exception:
                captures[cls_name] = None
                return original_call(self, *args, **kwargs)
        gm = captures[cls_name]
        if gm is None:
            return original_call(self, *args, **kwargs)
        guard["active"] = True
        try:
            flat = tree_flatten_spec((list(args), kwargs), gm._in_spec)
            return torch.fx.Interpreter(gm).run(*flat)
        finally:
            guard["active"] = False

    torch.nn.Module.__call__ = hook_call
    return original_call


cfg = CLIPTextConfig(hidden_size=64, intermediate_size=128, num_hidden_layers=2,
    num_attention_heads=2, max_position_embeddings=77, vocab_size=100)
m = CLIPTextModel(cfg).eval()
input_ids = torch.zeros(1, 77, dtype=torch.long)

# WITHOUT the hook — sanity baseline: every output is real
with torch.no_grad():
    baseline = m(input_ids, output_hidden_states=True)
assert not isinstance(baseline.last_hidden_state, FakeTensor)
assert all(not isinstance(h, FakeTensor) for h in baseline.hidden_states)

# WITH the hook — last_hidden_state stays real, hidden_states all turn fake
orig = install_hook()
try:
    with torch.no_grad():
        out = m(input_ids, output_hidden_states=True)
finally:
    torch.nn.Module.__call__ = orig

print(f"last_hidden_state fake: {isinstance(out.last_hidden_state, FakeTensor)}")
for i, h in enumerate(out.hidden_states):
    print(f"hidden_states[{i}]: fake={isinstance(h, FakeTensor)}")

---

last_hidden_state fake: False
hidden_states[0]: fake=True
hidden_states[1]: fake=True
hidden_states[2]: fake=True
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

Goal: do per-aten-node observation on each captured submodule while the rest of the application runs eager. For every ATen op inside the exported gm, we want to inspect its tensor inputs and accumulate per-node statistics. fx.Interpreter.run_node is the obvious hook for that, since it's called once per graph node with the runtime-resolved inputs.

The setup:

  1. Take a real model m.
  2. For each submodule we want to observe, capture it once: ep = torch.export.export(submodule, args, kwargs=kwargs, strict=False) and keep gm = ep.module().
  3. Replace that submodule's __call__ so that the next time it's invoked, we run the captured graph instead of the original forward: out = torch.fx.Interpreter(gm).run(*flat) where flat = tree_flatten_spec((args, kwargs), gm._in_spec).
  4. Then we call the parent model eagerly. The parent's forward calls the substituted submodules through our wrapper, gets back outputs, and assembles its own return value.

We expect: the parent should produce the same kind of output as without our hook — all real tensors.

What we get: the parent returns a BaseModelOutputWithPooling where last_hidden_state is real but every entry in hidden_states is a FakeTensor — even though both fields come from the same internal computation. No FakeTensorMode is active on the dispatcher stack. The captured gm's parameters, buffers, and graph attributes are all real. The submodule's exported gm returns clean outputs when called in isolation.

Minimal repro

torch 2.8.0+cu128 (also 2.7.1). Requires transformers for CLIPTextModel.

import torch
from torch._subclasses.fake_tensor import FakeTensor
from torch.fx._pytree import tree_flatten_spec
from transformers import CLIPTextModel, CLIPTextConfig


def install_hook():
    original_call = torch.nn.Module.__call__
    captures = {}
    guard = {"active": False}
    target_classes = {"CLIPTextEmbeddings", "CLIPEncoder"}

    def hook_call(self, *args, **kwargs):
        if guard["active"]:
            return original_call(self, *args, **kwargs)
        cls_name = type(self).__qualname__
        if cls_name not in target_classes:
            return original_call(self, *args, **kwargs)
        if cls_name not in captures:
            try:
                ep = torch.export.export(self, args, kwargs=kwargs, strict=False)
                captures[cls_name] = ep.module()
            except Exception:
                captures[cls_name] = None
                return original_call(self, *args, **kwargs)
        gm = captures[cls_name]
        if gm is None:
            return original_call(self, *args, **kwargs)
        guard["active"] = True
        try:
            flat = tree_flatten_spec((list(args), kwargs), gm._in_spec)
            return torch.fx.Interpreter(gm).run(*flat)
        finally:
            guard["active"] = False

    torch.nn.Module.__call__ = hook_call
    return original_call


cfg = CLIPTextConfig(hidden_size=64, intermediate_size=128, num_hidden_layers=2,
    num_attention_heads=2, max_position_embeddings=77, vocab_size=100)
m = CLIPTextModel(cfg).eval()
input_ids = torch.zeros(1, 77, dtype=torch.long)

# WITHOUT the hook — sanity baseline: every output is real
with torch.no_grad():
    baseline = m(input_ids, output_hidden_states=True)
assert not isinstance(baseline.last_hidden_state, FakeTensor)
assert all(not isinstance(h, FakeTensor) for h in baseline.hidden_states)

# WITH the hook — last_hidden_state stays real, hidden_states all turn fake
orig = install_hook()
try:
    with torch.no_grad():
        out = m(input_ids, output_hidden_states=True)
finally:
    torch.nn.Module.__call__ = orig

print(f"last_hidden_state fake: {isinstance(out.last_hidden_state, FakeTensor)}")
for i, h in enumerate(out.hidden_states):
    print(f"hidden_states[{i}]: fake={isinstance(h, FakeTensor)}")

Output:

last_hidden_state fake: False
hidden_states[0]: fake=True
hidden_states[1]: fake=True
hidden_states[2]: fake=True

What we already ruled out

  • The live model has no fake parameters, no fake buffers, no fake __dict__ attributes (recursive walk).
  • The captured gm has no fake parameters, buffers, or __dict__ attributes either, and no FakeTensor literals in any node args/kwargs.
  • torch._guards.detect_fake_mode() is None before and after every Interpreter.run call.
  • Calling gm(...) directly or Interpreter(gm).run(...) in isolation produces real outputs.

So nothing on the dispatcher stack, on the model, or on the captured graph is fake. The fake values appear only in the parent's reconstructed output when the parent runs eager and reads from the substituted submodule's return.

What we'd like to know

  1. What's the supported way to do per-aten-node observation on an exported gm while the rest of the application runs eager? Is fx.Interpreter(gm).run(*flat_args) the intended tool for this? If not, what is?

  2. If fx.Interpreter(gm).run(*flat_args) IS the intended tool, then this repro shows it producing FakeTensor outputs in the parent's reconstructed BaseModelOutputWithPooling.hidden_states despite nothing visible to us being fake. Is the symptom a bug in the Interpreter / _out_spec reconstruction path, or did we misuse the API?

cc @chauhang @penguinwu @avikchaudhuri @gmagogsfm @zhxchen17 @tugsbayasgalan @angelayi @suo @ydwu4

Versions

Collecting environment information... PyTorch version: 2.7.1+cu126 Is debug build: False CUDA used to build PyTorch: 12.6 ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.4 LTS (x86_64) GCC version: (Ubuntu 10.5.0-1ubuntu1~22.04.3) 10.5.0 Clang version: Could not collect CMake version: version 3.22.1 Libc version: glibc-2.35

Python version: 3.11.9 (main, Apr 19 2024, 16:48:06) [GCC 11.2.0] (64-bit runtime) Python platform: Linux-6.8.0-106-generic-x86_64-with-glibc2.35 Is CUDA available: True CUDA runtime version: 12.8.61 CUDA_MODULE_LOADING set to: LAZY GPU models and configuration: GPU 0: NVIDIA GeForce RTX 4090 Nvidia driver version: 570.86.10 cuDNN version: Probably one of the following: /usr/lib/x86_64-linux-gnu/libcudnn.so.9.11.0 /usr/lib/x86_64-linux-gnu/libcudnn_adv.so.9.11.0 /usr/lib/x86_64-linux-gnu/libcudnn_cnn.so.9.11.0 /usr/lib/x86_64-linux-gnu/libcudnn_engines_precompiled.so.9.11.0 /usr/lib/x86_64-linux-gnu/libcudnn_engines_runtime_compiled.so.9.11.0 /usr/lib/x86_64-linux-gnu/libcudnn_graph.so.9.11.0 /usr/lib/x86_64-linux-gnu/libcudnn_heuristic.so.9.11.0 /usr/lib/x86_64-linux-gnu/libcudnn_ops.so.9.11.0 /usr/local/cuda-12.8/targets/x86_64-linux/lib/libcudnn.so.9 /usr/local/cuda-12.8/targets/x86_64-linux/lib/libcudnn_adv.so.9 /usr/local/cuda-12.8/targets/x86_64-linux/lib/libcudnn_cnn.so.9 /usr/local/cuda-12.8/targets/x86_64-linux/lib/libcudnn_engines_precompiled.so.9 /usr/local/cuda-12.8/targets/x86_64-linux/lib/libcudnn_engines_runtime_compiled.so.9 /usr/local/cuda-12.8/targets/x86_64-linux/lib/libcudnn_graph.so.9 /usr/local/cuda-12.8/targets/x86_64-linux/lib/libcudnn_heuristic.so.9 /usr/local/cuda-12.8/targets/x86_64-linux/lib/libcudnn_ops.so.9 Is XPU available: False HIP runtime version: N/A MIOpen runtime version: N/A Is XNNPACK available: True Caching allocator config: N/A

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 46 bits physical, 57 bits virtual Byte Order: Little Endian CPU(s): 48 On-line CPU(s) list: 0-47 Vendor ID: GenuineIntel Model name: Intel(R) Xeon(R) Silver 4410Y CPU family: 6 Model: 143 Thread(s) per core: 2 Core(s) per socket: 12 Socket(s): 2 Stepping: 8 CPU max MHz: 3900.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 intel_ppin cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow 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 user_shstk avx_vnni avx512_bf16 wbnoinvd dtherm ida arat pln pts hfi vnmi 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 ibt amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities ibpb_exit_to_user Virtualization: VT-x L1d cache: 1.1 MiB (24 instances) L1i cache: 768 KiB (24 instances) L2 cache: 48 MiB (24 instances) L3 cache: 60 MiB (2 instances) NUMA node(s): 2 NUMA node0 CPU(s): 0-11,24-35 NUMA node1 CPU(s): 12-23,36-47 Vulnerability Gather data sampling: Not affected Vulnerability Indirect target selection: Not affected Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Not affected Vulnerability Reg file data sampling: Not affected Vulnerability Retbleed: Not affected Vulnerability Spec rstack overflow: Not affected Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; Enhanced / Automatic IBRS; IBPB conditional; PBRSB-eIBRS SW sequence; BHI BHI_DIS_S Vulnerability Srbds: Not affected Vulnerability Tsa: Not affected Vulnerability Tsx async abort: Not affected Vulnerability Vmscape: Mitigation; IBPB before exit to userspace

Versions of relevant libraries: [pip3] bert_pytorch==0.0.1a4 [pip3] functorch==1.14.0a0+b71aa0b [pip3] mypy==1.17.0 [pip3] mypy_extensions==1.1.0 [pip3] numpy==2.1.2 [pip3] nvidia-cublas-cu12==12.6.4.1 [pip3] nvidia-cuda-cupti-cu12==12.6.80 [pip3] nvidia-cuda-nvrtc-cu12==12.6.77 [pip3] nvidia-cuda-runtime-cu12==12.6.77 [pip3] nvidia-cudnn-cu12==9.5.1.17 [pip3] nvidia-cufft-cu12==11.3.0.4 [pip3] nvidia-curand-cu12==10.3.7.77 [pip3] nvidia-cusolver-cu12==11.7.1.2 [pip3] nvidia-cusparse-cu12==12.5.4.2 [pip3] nvidia-cusparselt-cu12==0.6.3 [pip3] nvidia-nccl-cu12==2.26.2 [pip3] nvidia-nvjitlink-cu12==12.6.85 [pip3] nvidia-nvtx-cu12==12.6.77 [pip3] onnx==1.18.0 [pip3] pytorch-labs-segment-anything-fast==0.2 [pip3] torch==2.7.1+cu126 [pip3] torch_geometric==2.4.0 [pip3] torchao==0.11.0 [pip3] torchaudio==2.7.1+cu126 [pip3] torchbench==0.1 [pip3] torchmultimodal==0.1.0b0 [pip3] torchvision==0.22.1+cu126 [pip3] triton==3.3.1 [conda] bert-pytorch 0.0.1a4 dev_0 <develop> [conda] functorch 1.14.0a0+b71aa0b pypi_0 pypi [conda] numpy 2.1.2 pypi_0 pypi [conda] nvidia-cublas-cu12 12.6.4.1 pypi_0 pypi [conda] nvidia-cuda-cupti-cu12 12.6.80 pypi_0 pypi [conda] nvidia-cuda-nvrtc-cu12 12.6.77 pypi_0 pypi [conda] nvidia-cuda-runtime-cu12 12.6.77 pypi_0 pypi [conda] nvidia-cudnn-cu12 9.5.1.17 pypi_0 pypi [conda] nvidia-cufft-cu12 11.3.0.4 pypi_0 pypi [conda] nvidia-curand-cu12 10.3.7.77 pypi_0 pypi [conda] nvidia-cusolver-cu12 11.7.1.2 pypi_0 pypi [conda] nvidia-cusparse-cu12 12.5.4.2 pypi_0 pypi [conda] nvidia-cusparselt-cu12 0.6.3 pypi_0 pypi [conda] nvidia-nccl-cu12 2.26.2 pypi_0 pypi [conda] nvidia-nvjitlink-cu12 12.6.85 pypi_0 pypi [conda] nvidia-nvtx-cu12 12.6.77 pypi_0 pypi [conda] pytorch-labs-segment-anything-fast 0.2 pypi_0 pypi [conda] torch 2.7.1+cu126 pypi_0 pypi [conda] torch-geometric 2.4.0 pypi_0 pypi [conda] torchao 0.11.0 pypi_0 pypi [conda] torchaudio 2.7.1+cu126 pypi_0 pypi [conda] torchbench 0.1 pypi_0 pypi [conda] torchmultimodal 0.1.0b0 pypi_0 pypi [conda] torchvision 0.22.1+cu126 pypi_0 pypi [conda] triton 3.3.1 pypi_0 pypi

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING