Skip to content

Overflow error in torch.linalg uncaught #65815

Closed

Description

@feeds

🐛 Bug

The torch.linalg.norm function silently produces incorrect results.
(It seems that this is specific to the setup used in Google Colab, on my local machine it works).

To Reproduce

import torch

def custom_norm(tensor):
    return torch.sqrt((tensor**2).sum())

def test_norm(N):
    A = torch.ones((N,N))
    print(f"Size: {A.shape} \t:: Custom norm: {custom_norm(A)} \t:: Torch norm {torch.linalg.norm(A)}")

test_norm(10)
test_norm(100)
test_norm(1000)
test_norm(10000)

Output is

Size: torch.Size([10, 10]) 	:: Custom norm: 10.0 	:: Torch norm 10.0
Size: torch.Size([100, 100]) 	:: Custom norm: 100.0 	:: Torch norm 100.0
Size: torch.Size([1000, 1000]) 	:: Custom norm: 1000.0 	:: Torch norm 1000.0
Size: torch.Size([10000, 10000]) 	:: Custom norm: 10000.0 	:: Torch norm 4096.0

Expected behavior

The torch norm is wrong in the last line, probably due to some internal overflow (?).
Expected behavior would be to report that the capacity of the datatype is not high enough, e.g. raise some Error.

Then the user can correct it to the following, which will yield the correct output.

import torch
def custom_norm(tensor):
    return torch.sqrt((tensor**2).sum())
def test_norm(N):
    A = torch.ones((N,N),dtype=torch.float64)
    print(f"Size: {A.shape} \t:: Custom norm: {custom_norm(A)} \t:: Torch norm {torch.linalg.norm(A)}")
test_norm(10)
test_norm(100)
test_norm(1000)
test_norm(10000)

Environment

Collecting environment information...
PyTorch version: 1.9.0+cu102
Is debug build: False
CUDA used to build PyTorch: 10.2
ROCM used to build PyTorch: N/A

OS: Ubuntu 18.04.5 LTS (x86_64)
GCC version: (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
Clang version: 6.0.0-1ubuntu2 (tags/RELEASE_600/final)
CMake version: version 3.12.0
Libc version: glibc-2.26

Python version: 3.7.12 (default, Sep 10 2021, 00:21:48)  [GCC 7.5.0] (64-bit runtime)
Python platform: Linux-5.4.104+-x86_64-with-Ubuntu-18.04-bionic
Is CUDA available: True
CUDA runtime version: 11.1.105
GPU models and configuration: GPU 0: Tesla P100-PCIE-16GB
Nvidia driver version: 460.32.03
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.7.6.5
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.0.5
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.0.5
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.0.5
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.0.5
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.0.5
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.0.5
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.0.5
HIP runtime version: N/A
MIOpen runtime version: N/A

Versions of relevant libraries:
[pip3] numpy==1.19.5
[pip3] torch==1.9.0+cu102
[pip3] torchsummary==1.5.1
[pip3] torchtext==0.10.0
[pip3] torchvision==0.10.0+cu102
[conda] Could not collect

cc @ezyang @gchanan @kadeng @msaroufim @albanD @pragupta @jianyuh @nikitaved @mruberry @walterddr @lezcano @zou3519 @bdhirsh @jbschlosser @pearu @IvanYashchuk @xwang233

Activity

  1. added
    module: linear algebra
    on Sep 30, 2021
  2. lezcano commented on Sep 30, 2021

    @lezcano
    Collaborator

    cc @kurtamohler who worked on torch.norm for quite some time.

    I think that this is just a bug and should be solved asap. The numbers tested are not even that large and you are working with double precision, so I don't think this comes from an overflow.

  3. kurtamohler commented on Sep 30, 2021

    @kurtamohler
    Collaborator

    Interesting, I'll look into it. It doesn't reproduce in my default environment, but I'll try to duplicate yours @feeds. Could you also post the output of https://raw.githubusercontent.com/pytorch/pytorch/master/torch/utils/collect_env.py for the environment where you do not see this error? That might make it easier to figure out what difference is making this error show up

  4. lezcano commented on Sep 30, 2021

    @lezcano
    Collaborator

    Actually, it does not reproduce in my environment either. @feeds could you confirm whether you see this error in master or the nightly version of PyTorch?

  5. kurtamohler commented on Sep 30, 2021

    @kurtamohler
    Collaborator

    @lezcano, it's in whatever Google colab uses by default (at the moment, it's pip torch==1.9.0+cu102). I can reproduce the error there

  6. lezcano commented on Sep 30, 2021

    @lezcano
    Collaborator

    It might be the case that it's fixed in master? If @feeds confirms this we can close the issue.

  7. kurtamohler commented on Sep 30, 2021

    @kurtamohler
    Collaborator

    cc @ngimel and @heitorschueroff, who have been working on norm functions more recently than me

  8. ngimel commented on Sep 30, 2021

    @ngimel
    Collaborator

    Repros on master after setting num_threads to 1:

    In [1]: import torch
    
    In [2]: torch.set_num_threads(1)
    
    In [3]: a=torch.ones(10000,10000)
    
    In [5]: torch.linalg.norm(a)
    Out[5]: tensor(4096.)
    
    In [6]: torch.set_num_threads(24)
    
    In [7]: torch.linalg.norm(a)
    Out[7]: tensor(10000.)
    

    Most likely cause is as regular summation for norm goes, it stops updating values after reaching 2^24 (because fp32 mantissa), and then sqrt(2^24) is 4096.
    We need cascade reductions for norm to fix this (we have cascade reductions for sum, but not for norm)

  9. added
    module: correctness (silent)
    module: numerical-stability
    module: multithreading
    and removed on Sep 30, 2021
  10. peterbell10 commented on Sep 30, 2021

    @peterbell10
    Collaborator

    I wonder if the SumKernel code could be reused here as a generic map-sum, similar to how nansum is implemented. Though it would still need a separate pass to take the final sqrt. To do it truely as one pass, we would need something like #40570.

  11. added
    triaged
    on Oct 1, 2021
  12. ezyang commented on Oct 4, 2021

    @ezyang
    Contributor

    my kingdom for a pointwise-reductions compiler (cc @bertmaher)

  13. ngimel commented on Oct 4, 2021

    @ngimel
    Collaborator

    Compiler sounds nice, but we should have good vectorized implementations for those reductions regardless.

  14. added and removed
    triaged
    on Oct 4, 2021
  15. added
    triaged
    and removed on Oct 4, 2021
  16. egeboy35 commented on Oct 21, 2026

    @egeboy35
    Contributor

    @ngimel @lezcano

    Drafted by Claude (AI) for @egeboy35.

    This still reproduces on current main (CPU, float32): torch.linalg.vector_norm(torch.randn(10**8)) comes out 1.1% low (9890.4 instead of 10000.3) with 1 thread and with 7, and with one thread vector_norm(torch.ones(10**4, 10**4), 1) and ord=0 both return 16777216 (2**24) instead of 1e8.

    egeboy35 has a fix along the lines suggested on #151761. The load policies in SumKernel.cpp take a per-element map (|x|, x * x, x != 0; nansum's NaN masking becomes one more map), and on CPU norm and _powsum send ord 0, 1 and 2 for float, double, half and bfloat16 through cascade_sum, taking the square root afterwards and accumulating half and bfloat16 in float as mean does. With it the cases above match a float64 reference to about 1e-7 at 1 and 7 threads. Complex inputs, ±inf and other ords keep the current kernel for now. Could this issue be labelled actionable so the PR can be opened?

  17. egeboy35 commented on Oct 28, 2026

    @egeboy35
    Contributor

    @ngimel @lezcano

    Drafted by Claude (AI) for @egeboy35.

    Following up on the Oct 21 comment: the fix is ready on a branch. It routes ord 0, 1 and 2 through sum()'s cascade summation, so vector_norm(randn(10**8)) matches a float64 reference to about 1e-7 instead of coming out 1.1% low, and most cases also get faster (float32 randn(10**7) with ord=1 goes from 18.2 ms to 3.6 ms on one thread). Could one of you add the actionable label so the PR can be opened without being auto-closed?

  18. added a commit that references this issue on Nov 3, 2026
    ee82fb6
  19. added a commit that references this issue on Nov 17, 2026
    b2f3444
  20. added a commit that references this issue on Nov 18, 2026
    87f51fb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    actionablehigh prioritymodule: correctness (silent)module: linear algebramodule: multithreadingmodule: numerical-stabilitymodule: reductionstriaged

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions