Skip to content

Fix mliappy libpython extension - #2934

Closed
jan-janssen wants to merge 1 commit into
lammps:developfrom
jan-janssen:mliap
Closed

jan-janssen wants to merge 1 commit into
lammps:developfrom
jan-janssen:mliap

Conversation

@jan-janssen

Copy link
Copy Markdown
Contributor

Summary

Previously mliappy was looking for libpython3.9.a rather than libpython3.9.so

Related Issue(s)

Author(s)

Jan Janssen, Los Alamos National Lab, [email protected]

Licensing

By submitting this pull request, I agree, that my contribution will be included in LAMMPS and redistributed under either the GNU General Public License version 2 (GPL v2) or the GNU Lesser General Public License version 2.1 (LGPL v2.1).

Backward Compatibility

Implementation Notes

Post Submission Checklist

  • The feature or features in this pull request is complete
  • Licensing information is complete
  • Corresponding author information is complete
  • The source code follows the LAMMPS formatting guidelines
  • Suitable new documentation files and/or updates to the existing docs are included
  • The added/updated documentation is integrated and tested with the documentation build system
  • The feature has been verified to work with the conventional build system
  • The feature has been verified to work with the CMake based build system
  • Suitable tests have been added to the unittest tree.
  • A package specific README file has been included or updated
  • One or more example input decks are included

Further Information, Files, and Links

@akohlmey
akohlmey requested a review from athomps September 9, 2021 23:19
@akohlmey akohlmey self-assigned this Sep 9, 2021
@akohlmey akohlmey added this to the Stable Release Summer 2021 milestone Sep 9, 2021
@akohlmey

akohlmey commented Sep 9, 2021

Copy link
Copy Markdown
Member

@lubbersnick any comments on this?

@akohlmey
akohlmey requested a review from rbberger September 9, 2021 23:21
@rbberger

Copy link
Copy Markdown
Member

@jan-janssen can you please elaborate on what Python configuration this happens? Can't reproduce the libpython3.9.a.

@jan-janssen

jan-janssen commented Sep 10, 2021 •

Copy link
Copy Markdown
Contributor Author

I tried it on an anaconda environment, it points to libpython3.9.a but the file is libpython3.9.so .

@rbberger

rbberger commented Sep 10, 2021 •

Copy link
Copy Markdown
Member

@jan-janssen Please be more specific.

Just tried this on a Linux box with Anaconda3 2021.05:

$ python
Python 3.8.8 (default, Apr 13 2021, 19:58:26) 
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import ctypes
>>> import sysconfig 
>>> sysconfig.get_config_vars('INSTSONAME')
['libpython3.8.so.1.0']
>>> sysconfig.get_config_vars('INSTSONAME')[0]
'libpython3.8.so.1.0'
>>> library = sysconfig.get_config_vars('INSTSONAME')[0]
>>> pylib = ctypes.CDLL(library) 
>>> pylib
<CDLL 'libpython3.8.so.1.0', handle 55b77ed83d70 at 0x7f56ebc774c0>

@rbberger

Copy link
Copy Markdown
Member

Could finally reproduce it with conda create -n py39 python=3.9. Note that this patch doesn't help on MacOS, where SHLIB_SUFFIX is reported to be ".so" but is actually ".dylib". This looks more like an Anaconda Python packaging bug to me.

Linux:

(base) [richard@mustang ~]$ python -m sysconfig | grep INSTS
	INSTSONAME = "libpython3.8.so.1.0"
(base) [richard@mustang ~]$ conda activate py39
(py39) [richard@mustang ~]$ python -m sysconfig | grep INSTS
	INSTSONAME = "libpython3.9.a"

MacOS:

(base) richard@wheatley ~ % python -m sysconfig | grep INSTSO
	INSTSONAME = "libpython3.8.dylib"
(base) richard@wheatley ~ % conda activate py39              
(py39) richard@wheatley ~ % python -m sysconfig | grep INSTSO
	INSTSONAME = "libpython3.9.a"

@rbberger rbberger left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Breaks on systems that return INSTSONAME with something like libpython3.9.so.1.0

@jan-janssen

Copy link
Copy Markdown
Contributor Author

@lubbersnick

Copy link
Copy Markdown
Contributor

Heya, I have had some problems using mliappy with anaconda3 on macos and I wonder if Jan has found the problem in a similar way. The issue is not easy to reproduce because it has something to do with how the python build configuration is set up and from what I can tell there is no transparent way to ask for those configurations in anaconda.

I am ok with a solution that doesn't break existing things. Richard pointed out that yes, it will be .dylib sometimes instead of .so.

Maybe we should just mimmick/refactor what goes on here to find the lammps shared library?

https://github.com/lammps/lammps/blob/master/python/lammps/core.py#L115-L132

I guess a question is if we could fit a mliappy test into the LAMMPS test suite? I know that testing the link back to python requires a bit more testing but I guess what's preferable is if we can show the new solution works on any machine/python installation, or, at least, on a superset of what works now.

@akohlmey

Copy link
Copy Markdown
Member

I guess a question is if we could fit a mliappy test into the LAMMPS test suite? I know that testing the link back to python requires a bit more testing but I guess what's preferable is if we can show the new solution works on any machine/python installation, or, at least, on a superset of what works now.

To add a test we would just need a "dummy" or "mock" machine learning potential implementation. One that does nothing but returns some predefined values, e.g. atom ID as x-direction force, type as y-direction force etc.
Then it would be straightforward to add the tests. We do test all kinds of python things already (interfacing in both directions, python to LAMMPS and LAMMPS to python and even "circular", i.e. calling LAMMPS from python that then call python from LAMMPS or calling python from LAMMPS that then loads and uses the LAMMPS python module to get data from LAMMPS.

@lubbersnick

Copy link
Copy Markdown
Contributor

To add a test we would just need a "dummy" or "mock" machine learning potential implementation. One that does nothing but returns some predefined values, e.g. atom ID as x-direction force, type as y-direction force etc.

From the examples we can run this: https://github.com/lammps/lammps/blob/master/examples/mliap/convert_mliap_Ta06A.py to convert the Ta potential into a pytorch format.

Then this tests mliappy from lammps side: https://github.com/lammps/lammps/blob/master/examples/mliap/in.mliap.pytorch.Ta06A

And this tests mliappy from the python side: https://github.com/lammps/lammps/blob/master/examples/mliap/mliap_pytorch_Ta06A.py

@akohlmey

Copy link
Copy Markdown
Member

@lubbersnick you are missing the point. We want to test the interface only. Without being forced to install and load pytorch.

@rbberger

Copy link
Copy Markdown
Member

@lubbersnick FYI, I'm seeing a segfault when trying to run python mliap_pytorch_Ta06A.py. Something messes up the pyx initialization.

__Pyx_PyUnicode_Equals (s1=s1@entry=0x7fffec6894f0, s2=0x0, equals=2) at /home/richard/GitHub/lammps/lammps/build_mliap/cython/mliap_model_python_couple.cpp:20037
p20037	    s2_is_unicode = PyUnicode_CheckExact(s2);
(gdb) print s1
$1 = (PyObject *) 0x7fffec6894f0
(gdb) print s2
$2 = (PyObject *) 0x0
(gdb) list
20032	    int s1_is_unicode, s2_is_unicode;
20033	    if (s1 == s2) {
20034	        goto return_eq;
20035	    }
20036	    s1_is_unicode = PyUnicode_CheckExact(s1);
20037	    s2_is_unicode = PyUnicode_CheckExact(s2);
20038	#if PY_MAJOR_VERSION < 3
20039	    if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) {
20040	        owned_ref = PyUnicode_FromObject(s2);
20041	        if (unlikely(!owned_ref))

The global static variable of the mliap pyx module storing the LATER literal constant becomes a null pointer. I'm seeing the __Pyx_InitGlobals call which sets that literal, PyObject __pyx_n_u_LATER, but something later on sets it to back to null. Currently tracking it down with GDB...

Running mliap without external Python interpreter works.

@rbberger

rbberger commented Sep 13, 2021 •

Copy link
Copy Markdown
Member

@lubbersnick Turns out that what loader.py does isn't good enough.

path = lmp.lib._name
loader = importlib.machinery.ExtensionFileLoader('mliap_model_python_couple', path)

That tries to load liblammps.so. It has to be the absolute path of the library file and it has to match the one the LAMMPS Python module uses. No symlinks or copies. I used a symlink and later a copy, that's why it segfaults above, because a second shared library was loaded in a different memory area but not fully initialized.

If that was the reason for the original Py_IsInitialized check, we could remove that completely.

@lubbersnick

Copy link
Copy Markdown
Contributor

@rbberger The Py_IsInitialized is there because some cases were not able to load the python shared library properly. Much as what you found for liblammps, if a different version of the python library gets loaded then the python interpreter lands in a bad state because the calls to python inside lammps do not cooperate with the global variables of the active interpreter. By checking that the loaded library recognizes that python has been initalized one verifies that indeed the shared library calls compiled into lammps will affect the current python interpreter. My hope is that this PR that @jan-janssen has submitted extends the ability to test that lammps will be able to communicate 'back' to python properly. But in any case if that py_isinitialized check fails then nothing will work (at least, I always get segfault) so I don't suggest we remove it.

So I think what you've found is the flip side of this, but for the extension to python that is compiled into lammps. It seems to mirror the phenomenon -- if the loader adds a new copy of lammps, then global variables (in the pyx module) aren't necessarily initialized right. I thought that grabbing the _name attribute from the active copy of lammps would dynamically work but apparently not. On my machine the _name gives a fully-qualified path but you are finding is that the loader doesn't function right if that name is a link or a copy. If it is a link we should be able to do it with path = pathlib.Path(path).resolve(). I don't know if a copy is an important thing to get right or not. I don't think loaders are designed to work for certain when loading multiple copies of the same library. A different solution might be to store the resolved path on the lammps.lammps objects themselves when they are created? How do we get to links or copies when the current cmake defines exactly what liblammps python should use, will it only happen when someone uses a traditional make build?

@akohlmey

Copy link
Copy Markdown
Member

@lubbersnick I don't think you need any pathname at this moment because the LAMMPS library has already been loaded. Find below a small test case for a simple executable that loads lammps (through the C library interface for simplicity, but C++ would work just as well) and then uses dlopen(NULL,RTLD_NOW) to look up additional symbols and use them. The same would, of course, apply to the Python library. None of that would work with static libraries anyway. But when compiling with Python, the -rdynamic flag is applied which re-exports all symbols from the shared library and the executable when it is loaded.

#include <iostream>
#include <dlfcn.h>

#include "library.h"

void check_reloading()
{
    void *ptr = dlopen(NULL,RTLD_NOW);
    if (!ptr) return;
    int (*has_gzip)() = (int (*)()) dlsym(ptr, "lammps_config_has_gzip_support");
    int (*has_jpeg)() = (int (*)()) dlsym(ptr, "lammps_config_has_jpeg_support");
    if (!has_gzip && !has_jpeg) return;
    
    std::cout << "LAMMPS has gzip: " << (*has_gzip)()
              << "\nLAMMPS has jpeg: " << (*has_jpeg)() << "\n";
    dlclose(ptr);
}

int main(int, char **)
{
    void *lmp = lammps_open_no_mpi(0,nullptr, nullptr);
    std::cout << "LAMMPS version id: " << lammps_version(lmp) << "\n";
    check_reloading();
    lammps_close(lmp);
    return 0;
}

When loading the lammps python module within LAMMPS we use the same approach (i.e. CDLL("")). That way you cannot have a mismatch or load the same symbols multiple times to different addresses.

@rbberger

rbberger commented Sep 14, 2021 •

Copy link
Copy Markdown
Member

@lubbersnick I have to correct myself. The segfault only happens if the importlib machinery in loader.py loads a different file compared to lammps.lammps.__init__(). If the symlink points to the same exact file location the loading works. So only copies or different files are a problem. Sorry for the noise.

Now, the reason why I've ended up having a symlink to liblammps.so in the first place was because the importlib machinery logic in loader.py was insufficient and only was looking at the current working directory for liblammps.so and immediately raises an exception that it can't find the file $PWD/liblammps.so ($PWD was example/mliap). I ended up creating symlink to liblammps.so in my CMake build folder.

So what ended up happening was that loader.py loaded the liblammps.so from my CMake build folder, while lammps.lammps.__init__() with ctypes.CDLL() got $HOME/.local/lib/liblammps.so which I installed with make install after compilation (LD_LIBRARY_PATH points there on my system). Even if those two are binary identical the different file locations cause the messed up/uninitialized internal state.

In the end what is needed is a better way of making sure the same liblammps.so is used by both the importlib machinery and lammps.lammps.

@akohlmey Yes, you need to specify the full path. importlib.machinery.ExtensionFileLoader doesn't care about LD_LIBRARY_PATH or what CDLL does.

@lubbersnick

lubbersnick commented Sep 14, 2021 •

Copy link
Copy Markdown
Contributor

@rbberger I know that "On my machine" isn't an excuse, but on my machine the lib name points into the python installation path for lammps.

>>>lmp.lib._name
'<anaconda-environment-path>/lib/python3.7/site-packages/lammps/liblammps.dylib'

Could this actually depend on how the search for the lammps library is being done in lammps.py?

in other news I did some digging and the fact that a file name is used to load an extension model is built deep into the c part of CPython, so it doesn't look simple to build a custom loader that takes the CDLL. But I won't say that route is completely impossible.

@rbberger

Copy link
Copy Markdown
Member

@lubbersnick I agree. After spending the last days digging into various PEPs and the CPython source code, that's one step too far for this simple extension. Also found this jem:

    if (strchr(pathname, '/') == NULL) {
        /* Prefix bare filename with "./" */
        PyOS_snprintf(pathbuf, sizeof(pathbuf), "./%-.255s", pathname);
        pathname = pathbuf;
    }

    ...

    handle = dlopen(pathname, dlopenflags);

So it actually forces the lib file to be in the working directory if you don't specify the full path.

Anyway, it's probably easier to just re-implement the whole thing in C++, export some extra C symbols, and use ctypes instead.

@lubbersnick

Copy link
Copy Markdown
Contributor

I am planning to extend on the cython, as such, I'd hope not to obliterate it. I think it should be realistic to obtain the full path for the library -- it is a bit crazy if we do not know what file is being loaded. So I look at it like 1) rewrite the code in a way that maintains compatibility and does bi-directional communication between python and C++ or 2) locate an absolute file path for a file we are already using elsewhere. Am I oversimplifying that too much?

@akohlmey

Copy link
Copy Markdown
Member

@lubbersnick from what is currently present, it is difficult to see anything that justifies using cython and from what I understand a significant part of what is causing a problem is the way how cython works as such.

So finding an alternative that allows to drop using cython is desirable, since it was requiring some effort to integrate it without too much complexity into the build procedure in the first place. The "philosophy" of cython seem to imply that the generated source code would otherwise, by preference, be compiled into a standalone shared object. While that would be easy to support this in CMake, it is a serious complexity to be added to the conventional build system. So to stick with cython there has to be a very good argument showing that something needs to be done that cannot be done otherwise (with reasonable effort).

I am opposed to using more band aid to address a problem that is caused by a band aid solution in the first place.

I'd also like to remark that on a unix system you cannot "trust" file names at all to remain the same item when they have the same name, only file descriptors (not even file pointers) and even for that there are exceptions.

What we currently have seems to be somewhat working. That it breaks with coda packaging is something that we currently will have to live with.

@lubbersnick

Copy link
Copy Markdown
Contributor

But the solution to Richard's problem isn't a band-aid. The code is compiled into liblammps, not some random file. And liblammps is not going to be a random file descriptor received over network or something like that -- lammps is compiled as a file on disk. Given the location of liblammps, the code loads it as expected and all the examples work. So fundamentally I don't see that this is a cython issue per se -- I think it's just a matter of tracking what library is dynamically loaded.

In terms of advantages: One advantage of cython not fully exploited right now is to interact with the C++ objects, without having to treat everything as a C function.

Another strong advantage is that code can live where it is used and only interact with the part of lammps it needs to. We aren't having to pass pointers to pairstyles as <void *> through the c library and then hope to reconstruct their types correctly in a completely different part of the code base. We can import and use methods within lammps that aren't exported as part of the external library interface. If at every juncture we decide to export everything we need from C++ as a strict C function, we will end up with non-obvious functions there that require detailed knowledge of lammps internals to use properly. The goal is a tight coupling to python in the MLIAP package so that high-performance ML code in python can be used with lammps easily. This is not the same as 'running lammps from another program', which is (I think) the goal of liblammps & the functions exported there.

Richard's issue is not the exact same as what Jan has raised; we can also address that issue, similarly, by just ensuring we have the correct paths.

There are more potential alternatives -- but give us some time to construct concrete solutions; I think we'll be able to show that nothing more complicated than the existing compilation is needed.

@akohlmey

Copy link
Copy Markdown
Member

@lubbersnick Sorry, but I don't buy several of your arguments and most importantly I don't share your vision of what can become of this piece of code.

Any piece of code that is dependent on accessing the LAMMPS shared library a second time when it is already loaded (e.g. by launching the LAMMPS executable) is in my opinion fundamentally flawed. While it is not a common occurrence, physical files can change and when you are holding the file open its file descriptor will point to the deleted/replaced file while a newly opened file will point to the new. This is built into the OS (except when you are on Windows). Thus when opening the same path a second time, you must not assume that it is the same.

I don't want to start a lengthy argument about details and specifics here and now and just state the thought of turning LAMMPS into the hybrid C++/Python code you describe scares the socks off me when I look at this when I am wearing my maintainer hat.

Since we are gearing up to a stable release, any changes in this area are not going to be taken under consideration for the next month or so, anyway.

@lubbersnick

Copy link
Copy Markdown
Contributor

I found and implemented a simple way to get the embedded python module directly from the CDLL loaded in the lammps.lammps().lib so that there is no need to rely on opening the file more than once. Since you all are gearing up for the current stable release milestone and this PR wasn't meant to solve that problem anyway, I won't make a PR for that just yet.

@akohlmey

Copy link
Copy Markdown
Member

I found and implemented a simple way to get the embedded python module directly from the CDLL loaded in the lammps.lammps().lib so that there is no need to rely on opening the file more than once. Since you all are gearing up for the current stable release milestone and this PR wasn't meant to solve that problem anyway, I won't make a PR for that just yet.

Please submit a draft PR anyway so that @rbberger can have a look and compare it to his attempts now that his memory is fresh. Drafts can't be merged anyway and there are already several PRs labeled to be processed in the next "development cycle"... so there is no harm done.

@akohlmey
akohlmey changed the base branch from master to develop October 12, 2021 18:05
@akohlmey

Copy link
Copy Markdown
Member

@lubbersnick @jan-janssen @rbberger this has been sitting idle for a while, but since we have concluded the previous development cycle with a stable release a month ago, this may be a good time to revisit this topic.
After the long discussion it is clear that the change in this pull request will not be included and that a different solution will need to be found, which can be submitted as a new pull request. Thus I am closing this PR now.

@akohlmey akohlmey closed this Oct 29, 2021
@Boogie3D Boogie3D mentioned this pull request Sep 23, 2022
11 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants