astropy: `test_fitting_with_initial_values[DogBoxLSQFitter]` fails to converge with mamba/miniforge openblas on macOS/arm64

Description

Seeing test_fitting_with_initial_values[DogBoxLSQFitter] fail with numpy 1.26.0 installed from MambaForge/Miniforge3 on an M1 Mac.

Expected behavior

Fit should converge for the given values in the test.

How to Reproduce

  1. Get Astropy including test deps from mamba as
mamba install --update-all astropy asdf-astropy graphviz h5py matplotlib ndcube pytest-astropy pytest-cov scipy spectral-cube

1a. For testing with the release candidates update Astropy via pip install --upgrade 'astropy==6.0.0rc2' 2. Then run import astropy; astropy.test(package='modeling') 3. An error occurs.

______________________________________________________ test_fitting_with_initial_values[DogBoxLSQFitter] _______________________________________________________

fitter = <astropy.modeling.fitting.DogBoxLSQFitter object at 0x14efc3d00>

    @pytest.mark.skipif(not HAS_SCIPY, reason="requires scipy")
    @pytest.mark.parametrize("fitter", fitters)
    def test_fitting_with_initial_values(fitter):
        fitter = fitter()
    
        x, y = _fake_gaussian_data()
    
        # Fit the data using a Gaussian with units
        g_init = models.Gaussian1D(amplitude=1.0 * u.mJy, mean=3 * u.cm, stddev=2 * u.mm)
>       g = fitter(g_init, x, y)

../../../opt/miniforge/envs/pip312/lib/python3.12/site-packages/astropy/modeling/tests/test_quantities_fitting.py:113: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
../../../opt/miniforge/envs/pip312/lib/python3.12/site-packages/astropy/modeling/fitting.py:285: in wrapper
    model_new = func(self, model, xdata, ydata, **kwargs)
../../../opt/miniforge/envs/pip312/lib/python3.12/site-packages/astropy/modeling/fitting.py:1365: in __call__
    init_values, fitparams, cov_x = self._run_fitter(
../../../opt/miniforge/envs/pip312/lib/python3.12/site-packages/astropy/modeling/fitting.py:1524: in _run_fitter
    self.fit_info = optimize.least_squares(
../../../opt/miniforge/envs/pip312/lib/python3.12/site-packages/scipy/optimize/_lsq/least_squares.py:949: in least_squares
    result = dogbox(fun_wrapped, jac_wrapped, x0, f0, J0, lb, ub, ftol,
../../../opt/miniforge/envs/pip312/lib/python3.12/site-packages/scipy/optimize/_lsq/dogbox.py:266: in dogbox
    f_new = fun(x_new)
../../../opt/miniforge/envs/pip312/lib/python3.12/site-packages/scipy/optimize/_lsq/least_squares.py:828: in fun_wrapped
    return np.atleast_1d(fun(x, *args, **kwargs))
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <astropy.modeling.fitting.DogBoxLSQFitter object at 0x14efc3d00>, fps = array([nan, nan, nan])
args = (<Gaussian1D(amplitude=nan, mean=nan, stddev=nan)>, None, array([-500.        , -499.49974987, -498.99949975, ...,  49...87,  500.        ]), array([-0.04094153,  0.09578867, -0.10388774, ..., -0.04841979,
       -0.611328  ,  0.38374856]))
model = <Gaussian1D(amplitude=nan, mean=nan, stddev=nan)>, weights = None
meas = array([-0.04094153,  0.09578867, -0.10388774, ..., -0.04841979,
       -0.611328  ,  0.38374856])

    def objective_function(self, fps, *args):
        """
        Function to minimize.
    
        Parameters
        ----------
        fps : list
            parameters returned by the fitter
        args : list
            [model, [weights], [input coordinates]]
    
        """
        model = args[0]
        weights = args[1]
        fitter_to_model_params(model, fps, self._use_min_max_bounds)
        meas = args[-1]
    
        if weights is None:
            value = np.ravel(model(*args[2:-1]) - meas)
        else:
            value = np.ravel(weights * (model(*args[2:-1]) - meas))
    
        if not np.all(np.isfinite(value)):
>           raise NonFiniteValueError(
                "Objective function has encountered a non-finite value, "
                "this will cause the fit to fail!\n"
                "Please remove non-finite values from your input data before "
                "fitting to avoid this error."
            )
E           astropy.modeling.fitting.NonFiniteValueError: Objective function has encountered a non-finite value, this will cause the fit to fail!
E           Please remove non-finite values from your input data before fitting to avoid this error.

../../../opt/miniforge/envs/pip312/lib/python3.12/site-packages/astropy/modeling/fitting.py:1141: NonFiniteValueError
--------------------------------------------------------------------- Captured stdout call ---------------------------------------------------------------------
 ** On entry to DLASCL parameter number  4 had an illegal value
 ** On entry to DLASCL parameter number  4 had an illegal value
 ** On entry to DLASCL parameter number  4 had an illegal value

Happens on Python 3.10-3.12 with Astropy 5.3.4, 6.0.0rc1 and 6.0.0rc2 whenever numpy is installed via mamba/conda/miniforge, which installs this openblas:

~/opt/miniforge/envs/pip312/lib/libopenblas.0.dylib: @rpath/libopenblas.0.dylib (compatibility version 0.0.0, current version 0.0.0) @rpath/libgfortran.5.dylib (compatibility version 6.0.0, current version 6.0.0) @rpath/libomp.dylib (compatibility version 5.0.0, current version 5.0.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1292.0.0)

The fit converges when using pip-installed numpy 1.26.0 or 1.26.2 (pip install --force-reinstall numpy), which is linking against

~/opt/miniforge/envs/pip31/lib/python3.12/site-packages/numpy/.dylibs/libopenblas64_.0.dylib

as well when linking against my own build of OpenBLAS 0.3.25. Tests also pass with all versions on Intel Mac. So likely this is a precision limit in the arm64 OpenBLAS 0.3.24 packaged with miniforge, though the test may be pushing the limits as well.

Versions

macOS-12.7-arm64-arm-64bit
Python 3.12.0 | packaged by conda-forge | (main, Oct 26 2023, 18:09:17) [Clang 16.0.6 ]
astropy 6.0.0rc2
Numpy 1.26.0
pyerfa 2.0.1.1
Scipy 1.11.3
Matplotlib 3.8.1

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Comments: 17 (14 by maintainers)

Commits related to this issue

Most upvoted comments

Yes, sorry I was not clear about that and updated the How to Reproduce accordingly – everything is installed via mamba (except in case of astropy-6.0.0rc, which is updated on top of the mamba packages with pip, but with the same results). Updating to the pip-numpy package is fixing this with or without changing scipy, as it is numpy’s _umath_linalg.cpythonX.so that is linked against libblas and using the failing DLASCL.

Sorry for going silent for a long time on this - I had a very busy time the past few weeks. I did test it a month ago with this patch, and it worked just fine - Astropy now passed it’s unit test suite on all architectures we support in EESSI: zen2, zen3, zen4, skylake, haswell, sapphire_rapids, x86_64/generic, aarch64/generic, neoverse_v1, neoverse_n1 (https://github.com/EESSI/software-layer/pull/916#issuecomment-2701742420). I am still planning to upstream the fix…!

@neutrinoceros : Contrary to the original reporter, my software stack doesn’t use conda / mamba at all. We use EasyBuild (an HPC software installation framework) to build a full software stack from sources with architecture-specific optimization (typically: -march=native). Regarding your specific question: no, we do not build with -fast-math. The build command for our OpenBLAS build is

make -j 16 shared  BINARY='64'  CC='gcc'  FC='gfortran'  MAKE_NB_JOBS='-1'  USE_OPENMP='1'  USE_THREAD='1'  CFLAGS='-O2 -ftree-vectorize -march=native -fno-math-errno' "

technical difficulties set aside, this seems reasonable to me. Others might be in a better position to advise on how best to define/find a stable region, but in any case, thank you for offering !

Since we’re building on such a wide range of architectures, I am as confident as I can be that my change in initial conditions shouldn’t be an issue for anyone - although we all know there are no guarantees 😄 But, I’m assuming the astropy devs will also run the unit test suite before releasing new versions, so that at least provides one more datapoint to see if the newly chosen init conditions would result in a passing test for them as well.

I also ran into this when trying to install Astropy in EESSI, see https://github.com/EESSI/software-layer/pull/916#issuecomment-2669244149 and was happy to find this ticket as a reference.

A little context: EESSI is a software environment jointly created by several HPC sites in Europe. It aims to deliver optimized CPU installations, meaning we typically build software from sources and optimize for a wide range of CPU architectures, including ARM architectures. I see the test passing on all of our X86 architectures (zen2, 3, 4, haswell, skylake, sapphire rapids), but failing on ARM (neoverse_V1, neoverse_N1, and a generic ARM build).

Since we build from sources and optimize for the particular architecture, this also means that the OpenBLAS installations will be optimized for the specific ARM architectures on which this is failing. My bet is that the same was done for the binaries that mamba provides and with which this thread started. Please note that for EESSI, we try to run unit tests as much as possible to validate the sanity of our software installations. For OpenBLAS, we ran the Lapack test suite. While there are some failures in complex number arithmetic (which were discussed and understood with the OpenBLAS devs), all of the tests on real numbers pass.

Currently, this issue is marked as an “Upstream Fix Required”. I personally don’t believe that is quite right (although it wouldn’t hurt to inform the mamba-folks, they might want to double-check that their OpenBLAS build passes the Lapack test - if they haven’t already done so). Yes, optimization may cause numerical results to be ever-so-slightly different. To me, the question is: what kind of variation can be expected from the underlying BLAS library. Personally, I’d consider anything that doesn’t break that Lapack tests to be acceptable variation.

As @WilliamJamieson mentions, the purpose of this particular test is “to test the convergence of the various fitters when dealing with units on the input”. I’d say that is just as well done if they start from a more stable initial condition, that is less sensitive to underlying numerical behavior. If you’re still open to it, I’m happy to make a PR to adjust the numbers, but… I’m maybe not the best person to decide on what initial condition could be expected to be stable. I did a small grid search to see what succeeded and what failed, but… it seems a bit hard to define a clear, stable region:

Amplitude Mean Stddev Result
1 3 2 Fail
1 2.5 2 Fail
1 3.5 2 Fail
1 4 2 Pass
1 5 2 Pass
2 3 2 Fail
0.5 3 2 Fail
10 3 2 Fail
100 3 2 Fail
0.1 3 2 Fail
1 3 1 Fail
1 3 3 Fail
1 3 10 Pass
1 3 100 Fail
1 3 20 Fail
1 10 2 Fail
1 7 2 Fail
1 7 10 Pass
1 7 4 Pass
1 10 10 Fail
1 5 3 Fail
1 5 4 Fail
1 4 3 Pass
1 4 4 Pass

Based on this, my best guess that Amplitude = 1, Mean = 4 and Stddev = 3 is probably a pretty stable starting point, but if anyone has a better, more rationalized set of parameters, I’m happy to go for those. I’ll create a patch for myself and see if I can build with it on all the architectures EESSI supports. At least that would give confirmation that it’ll pass with a wide range of optimized OpenBLAS installations…

Does this mean we can close this as “won’t fix”?

This looks like a numpy/scipy problem not an astropy problem.

Rather of mamba/miniforge then, since it is their OpenBLAS build that apparently has lower accuracy (perhaps over-optimised?). But you can cause most of the optimisation tests to fail by pushing the initial values too hard – had those problems with some modeling tests before, so that does play a role here. But since all tests seem to pass on all other architectures and BLAS builds, I’d agree here it is really a mamba issue; just wanted to have it recorded if something like this pops up again.