pytorch - 💡(How to fix) Fix [torch.compile] Integer overflow when comparing tensor with 9223372036854775809 (2^63+1) in masked_fill [1 comments, 2 participants]

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…
GitHub stats
pytorch/pytorch#178392Fetched 2026-04-08 01:30:38
View on GitHub
Comments
1
Participants
2
Timeline
150
Reactions
0
Timeline (top)
mentioned ×70subscribed ×70labeled ×8closed ×1

Error Message

torch._dynamo.exc.TorchRuntimeError: Failed running call_function <built-in function eq>(*(FakeTensor(..., size=(2, 1, 1, 10)), 9223372036854775809), **{}): value cannot be converted to type int64_t without overflow

from user code: File "test.py", line 29, in forward energy = energy.masked_fill(mask == 9223372036854775809, float('-1e20'))

Root Cause

When using torch.compile with a model that performs masked_fill using a comparison with the integer 9223372036854775809 (which is 2^63 + 1), compilation fails with an integer overflow error. The error manifests with slightly different wording across PyTorch versions but has the same root cause: the value exceeds the maximum range of int64_t. code:

import torch
import torch.nn as nn
import torch.nn.functional as F

Fix Action

Fix / Workaround

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 39 bits physical, 48 bits virtual Byte Order: Little Endian CPU(s): 32 On-line CPU(s) list: 0-31 Vendor ID: GenuineIntel Model name: Intel(R) Core(TM) i9-14900HX CPU family: 6 Model: 183 Thread(s) per core: 2 Core(s) per socket: 24 Socket(s): 1 Stepping: 1 CPU(s) scaling MHz: 31% CPU max MHz: 5800.0000 CPU min MHz: 800.0000 BogoMIPS: 4838.40 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 est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect user_shstk avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req hfi vnmi umip pku ospke waitpkg gfni vaes vpclmulqdq rdpid movdiri movdir64b fsrm md_clear serialize arch_lbr ibt flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 896 KiB (24 instances) L1i cache: 1.3 MiB (24 instances) L2 cache: 32 MiB (12 instances) L3 cache: 36 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-31 Vulnerability Gather data sampling: Not affected Vulnerability Ghostwrite: 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: Mitigation; Clear Register File 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 Tsx async abort: Not affected

Code Example

import torch
import torch.nn as nn
import torch.nn.functional as F

class DotProductAttention(nn.Module):

    def __init__(self, embed_size, heads):
        super(DotProductAttention, self).__init__()
        self.embed_size = embed_size
        self.heads = heads
        self.head_dim = embed_size // heads
        assert self.head_dim * heads == embed_size
        self.values = nn.Linear(embed_size, embed_size)
        self.keys = nn.Linear(embed_size, embed_size)
        self.queries = nn.Linear(embed_size, embed_size)
        self.fc_out = nn.Linear(embed_size, embed_size)

    def forward(self, values, keys, queries, mask=None):
        N = queries.shape[0]
        (value_len, key_len, query_len) = (values.shape[1], keys.shape[1], queries.shape[1])
        values = self.values(values)
        keys = self.keys(keys)
        queries = self.queries(queries)
        values = values.reshape(N, value_len, self.heads, self.head_dim)
        keys = keys.reshape(N, key_len, self.heads, self.head_dim)
        queries = queries.reshape(N, query_len, self.heads, self.head_dim)
        energy = torch.einsum('nqhd,nkhd->nhqk', [queries, keys])
        if mask is not None:
            energy = energy.masked_fill(mask == 9223372036854775809, float('-1e20'))
        attention = torch.softmax(energy / self.embed_size ** (1 / 2), dim=3)
        out = torch.einsum('nhql,nlhd->nqhd', [attention, values])
        out = out.reshape(N, query_len, self.heads * self.head_dim)
        out = self.fc_out(out)
        return out

class DotProductAttentionBlock(nn.Module):

    def __init__(self, embed_size, heads, forward_expansion, dropout):
        super(DotProductAttentionBlock, self).__init__()
        self.attention = DotProductAttention(embed_size, heads)
        self.norm1 = nn.LayerNorm(embed_size)
        self.norm2 = nn.LayerNorm(embed_size)
        self.feed_forward = nn.Sequential(nn.Linear(embed_size, forward_expansion * embed_size), nn.ReLU(), nn.Linear(forward_expansion * embed_size, embed_size))
        self.dropout = nn.Dropout(dropout)

    def forward(self, value, key, query, mask=None):
        attention = self.attention(value, key, query, mask)
        x = self.dropout(self.norm1(attention + query))
        forward = self.feed_forward(x)
        out = self.dropout(self.norm2(forward + x))
        return out

class DotProductAttentionDNN(nn.Module):

    def __init__(self, input_size, embed_size, num_layers, heads, forward_expansion, output_size, dropout, max_length):
        super(DotProductAttentionDNN, self).__init__()
        self.embed_size = embed_size
        self.word_embedding = nn.Embedding(input_size, embed_size)
        self.position_embedding = nn.Embedding(max_length, embed_size)
        self.layers = nn.ModuleList([DotProductAttentionBlock(embed_size, heads, forward_expansion, dropout) for _ in range(num_layers)])
        self.fc = nn.Linear(embed_size, output_size)
        self.dropout = nn.Dropout(dropout)

    def forward(self, x, mask=None):
        (N, seq_length) = x.shape
        positions = torch.arange(0, seq_length).expand(N, seq_length).to(x.device)
        out = self.dropout(self.word_embedding(x) + self.position_embedding(positions))
        for layer in self.layers:
            out = layer(out, out, out, mask)
        out = self.fc(out)
        return out

def get_default_model():
    return DotProductAttentionDNN(input_size=1000, embed_size=128, num_layers=2, heads=4, forward_expansion=2, output_size=10, dropout=0.1, max_length=20)

def get_sample_inputs(batch_size=2, seq_length=10):
    x = torch.randint(0, 1000, (batch_size, seq_length))
    mask = torch.ones(batch_size, 1, 1, seq_length)
    return (x, mask)

def run_inference(model, x, mask):
    with torch.no_grad():
        output = model(x, mask)
    return output

def main():
    model = get_default_model()
    model.eval()
    inputs = get_sample_inputs()
    (x, mask) = get_sample_inputs()
    output = run_inference(model, x, mask)
    print('DotProductAttentionDNN executed successfully!')
    print(f'Input shape: {x.shape}')
    print(f'Output shape: {output.shape}')
    print(f'Model parameters: {sum((p.numel() for p in model.parameters()))}')
    compiled_model = torch.compile(model)
    with torch.no_grad():
        output_compile = compiled_model(*inputs)
    print(f'Compile  shape: {output_compile.shape}')
if __name__ == '__main__':
    main()

---

torch._dynamo.exc.TorchRuntimeError: Failed running call_function <built-in function eq>(*(FakeTensor(..., size=(2, 1, 1, 10)), 9223372036854775809), **{}):
value cannot be converted to type int64_t without overflow

from user code:
   File "test.py", line 29, in forward
    energy = energy.masked_fill(mask == 9223372036854775809, float('-1e20'))

---

torch._dynamo.exc.TorchRuntimeError: Dynamo failed to run FX node with fake tensors: call_function <built-in function eq>(*(FakeTensor(..., size=(2, 1, 1, 10)), 9223372036854775809), **{}): got RuntimeError('value cannot be converted to type int64_t without overflow')

from user code:
   File "test.py", line 29, in forward
    energy = energy.masked_fill(mask == 9223372036854775809, float('-1e20'))
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

When using torch.compile with a model that performs masked_fill using a comparison with the integer 9223372036854775809 (which is 2^63 + 1), compilation fails with an integer overflow error. The error manifests with slightly different wording across PyTorch versions but has the same root cause: the value exceeds the maximum range of int64_t. code:

import torch
import torch.nn as nn
import torch.nn.functional as F

class DotProductAttention(nn.Module):

    def __init__(self, embed_size, heads):
        super(DotProductAttention, self).__init__()
        self.embed_size = embed_size
        self.heads = heads
        self.head_dim = embed_size // heads
        assert self.head_dim * heads == embed_size
        self.values = nn.Linear(embed_size, embed_size)
        self.keys = nn.Linear(embed_size, embed_size)
        self.queries = nn.Linear(embed_size, embed_size)
        self.fc_out = nn.Linear(embed_size, embed_size)

    def forward(self, values, keys, queries, mask=None):
        N = queries.shape[0]
        (value_len, key_len, query_len) = (values.shape[1], keys.shape[1], queries.shape[1])
        values = self.values(values)
        keys = self.keys(keys)
        queries = self.queries(queries)
        values = values.reshape(N, value_len, self.heads, self.head_dim)
        keys = keys.reshape(N, key_len, self.heads, self.head_dim)
        queries = queries.reshape(N, query_len, self.heads, self.head_dim)
        energy = torch.einsum('nqhd,nkhd->nhqk', [queries, keys])
        if mask is not None:
            energy = energy.masked_fill(mask == 9223372036854775809, float('-1e20'))
        attention = torch.softmax(energy / self.embed_size ** (1 / 2), dim=3)
        out = torch.einsum('nhql,nlhd->nqhd', [attention, values])
        out = out.reshape(N, query_len, self.heads * self.head_dim)
        out = self.fc_out(out)
        return out

class DotProductAttentionBlock(nn.Module):

    def __init__(self, embed_size, heads, forward_expansion, dropout):
        super(DotProductAttentionBlock, self).__init__()
        self.attention = DotProductAttention(embed_size, heads)
        self.norm1 = nn.LayerNorm(embed_size)
        self.norm2 = nn.LayerNorm(embed_size)
        self.feed_forward = nn.Sequential(nn.Linear(embed_size, forward_expansion * embed_size), nn.ReLU(), nn.Linear(forward_expansion * embed_size, embed_size))
        self.dropout = nn.Dropout(dropout)

    def forward(self, value, key, query, mask=None):
        attention = self.attention(value, key, query, mask)
        x = self.dropout(self.norm1(attention + query))
        forward = self.feed_forward(x)
        out = self.dropout(self.norm2(forward + x))
        return out

class DotProductAttentionDNN(nn.Module):

    def __init__(self, input_size, embed_size, num_layers, heads, forward_expansion, output_size, dropout, max_length):
        super(DotProductAttentionDNN, self).__init__()
        self.embed_size = embed_size
        self.word_embedding = nn.Embedding(input_size, embed_size)
        self.position_embedding = nn.Embedding(max_length, embed_size)
        self.layers = nn.ModuleList([DotProductAttentionBlock(embed_size, heads, forward_expansion, dropout) for _ in range(num_layers)])
        self.fc = nn.Linear(embed_size, output_size)
        self.dropout = nn.Dropout(dropout)

    def forward(self, x, mask=None):
        (N, seq_length) = x.shape
        positions = torch.arange(0, seq_length).expand(N, seq_length).to(x.device)
        out = self.dropout(self.word_embedding(x) + self.position_embedding(positions))
        for layer in self.layers:
            out = layer(out, out, out, mask)
        out = self.fc(out)
        return out

def get_default_model():
    return DotProductAttentionDNN(input_size=1000, embed_size=128, num_layers=2, heads=4, forward_expansion=2, output_size=10, dropout=0.1, max_length=20)

def get_sample_inputs(batch_size=2, seq_length=10):
    x = torch.randint(0, 1000, (batch_size, seq_length))
    mask = torch.ones(batch_size, 1, 1, seq_length)
    return (x, mask)

def run_inference(model, x, mask):
    with torch.no_grad():
        output = model(x, mask)
    return output

def main():
    model = get_default_model()
    model.eval()
    inputs = get_sample_inputs()
    (x, mask) = get_sample_inputs()
    output = run_inference(model, x, mask)
    print('DotProductAttentionDNN executed successfully!')
    print(f'Input shape: {x.shape}')
    print(f'Output shape: {output.shape}')
    print(f'Model parameters: {sum((p.numel() for p in model.parameters()))}')
    compiled_model = torch.compile(model)
    with torch.no_grad():
        output_compile = compiled_model(*inputs)
    print(f'Compile  shape: {output_compile.shape}')
if __name__ == '__main__':
    main()

PyTorch 2.6.0 output:

torch._dynamo.exc.TorchRuntimeError: Failed running call_function <built-in function eq>(*(FakeTensor(..., size=(2, 1, 1, 10)), 9223372036854775809), **{}):
value cannot be converted to type int64_t without overflow

from user code:
   File "test.py", line 29, in forward
    energy = energy.masked_fill(mask == 9223372036854775809, float('-1e20'))

PyTorch 2.7.0 output:

torch._dynamo.exc.TorchRuntimeError: Dynamo failed to run FX node with fake tensors: call_function <built-in function eq>(*(FakeTensor(..., size=(2, 1, 1, 10)), 9223372036854775809), **{}): got RuntimeError('value cannot be converted to type int64_t without overflow')

from user code:
   File "test.py", line 29, in forward
    energy = energy.masked_fill(mask == 9223372036854775809, float('-1e20'))

Versions

PyTorch version: 2.6.0/2.7.0 Is debug build: False CUDA used to build PyTorch: 12.6 ROCM used to build PyTorch: N/A

OS: Ubuntu 24.04.1 LTS (x86_64) GCC version: (Ubuntu 9.5.0-6ubuntu2) 9.5.0 Clang version: Could not collect CMake version: version 4.0.3 Libc version: glibc-2.39

Python version: 3.9.7 (default, Jul 16 2025, 16:34:47) [GCC 13.3.0] (64-bit runtime) Python platform: Linux-6.14.0-29-generic-x86_64-with-glibc2.39 Is CUDA available: False CUDA runtime version: Could not collect CUDA_MODULE_LOADING set to: N/A GPU models and configuration: GPU 0: NVIDIA GeForce RTX 4060 Laptop GPU Nvidia driver version: 580.65.06 cuDNN version: Could not collect 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: 39 bits physical, 48 bits virtual Byte Order: Little Endian CPU(s): 32 On-line CPU(s) list: 0-31 Vendor ID: GenuineIntel Model name: Intel(R) Core(TM) i9-14900HX CPU family: 6 Model: 183 Thread(s) per core: 2 Core(s) per socket: 24 Socket(s): 1 Stepping: 1 CPU(s) scaling MHz: 31% CPU max MHz: 5800.0000 CPU min MHz: 800.0000 BogoMIPS: 4838.40 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 est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect user_shstk avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req hfi vnmi umip pku ospke waitpkg gfni vaes vpclmulqdq rdpid movdiri movdir64b fsrm md_clear serialize arch_lbr ibt flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 896 KiB (24 instances) L1i cache: 1.3 MiB (24 instances) L2 cache: 32 MiB (12 instances) L3 cache: 36 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-31 Vulnerability Gather data sampling: Not affected Vulnerability Ghostwrite: 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: Mitigation; Clear Register File 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 Tsx async abort: Not affected

cc @chauhang @penguinwu @eellison @aorenste @voznesenskym @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @amjames @Lucaskabela @jataylo @bdhirsh @bobrenjc93

extent analysis

Fix Plan

The issue arises from the comparison with the integer 9223372036854775809, which exceeds the maximum range of int64_t. To fix this, we can use a smaller value for masking.

Step-by-Step Solution

  • Replace the line energy = energy.masked_fill(mask == 9223372036854775809, float('-1e20')) with energy = energy.masked_fill(mask == -1, float('-1e20')) to use a smaller value for masking.
  • Update the get_sample_inputs function to return a mask with values of -1 instead of 9223372036854775809.
def get_sample_inputs(batch_size=2, seq_length=10):
    x = torch.randint(0, 1000, (batch_size, seq_length))
    mask = torch.ones(batch_size, 1, 1, seq_length) * -1
    return (x, mask)

Verification

To verify that the fix worked, run the main function and check that the model compiles and runs without errors.

Extra Tips

  • Be cautious when using large integer values in comparisons, as they can exceed the maximum range of the data type.
  • Use smaller values for masking to avoid integer overflow errors.
  • Test the model with different input values to ensure that it works correctly in all scenarios.

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

pytorch - 💡(How to fix) Fix [torch.compile] Integer overflow when comparing tensor with 9223372036854775809 (2^63+1) in masked_fill [1 comments, 2 participants]