diff --git a/.ci_support/environment-docs.yml b/.ci_support/environment-docs.yml index a6ab251e..98257ad7 100644 --- a/.ci_support/environment-docs.yml +++ b/.ci_support/environment-docs.yml @@ -1,12 +1,13 @@ channels: - conda-forge dependencies: - - nbsphinx - - sphinx - - myst-parser - - numpy - - mpich - - cloudpickle - - mpi4py - - tqdm - - pyzmq \ No newline at end of file +- nbsphinx +- sphinx +- myst-parser +- numpy +- openmpi +- cloudpickle =3.0.0 +- mpi4py =3.1.5 +- tqdm =4.66.1 +- pyzmq =25.1.2 +- flux-core \ No newline at end of file diff --git a/.ci_support/environment-mpich.yml b/.ci_support/environment-mpich.yml index cba47606..510cd94d 100644 --- a/.ci_support/environment-mpich.yml +++ b/.ci_support/environment-mpich.yml @@ -4,7 +4,7 @@ dependencies: - python - numpy - mpich -- cloudpickle =2.2.1 -- mpi4py =3.1.4 +- cloudpickle =3.0.0 +- mpi4py =3.1.5 - tqdm =4.66.1 -- pyzmq =25.1.1 +- pyzmq =25.1.2 diff --git a/.ci_support/environment-old.yml b/.ci_support/environment-old.yml new file mode 100644 index 00000000..161f7ae1 --- /dev/null +++ b/.ci_support/environment-old.yml @@ -0,0 +1,10 @@ +channels: +- conda-forge +dependencies: +- python +- numpy +- openmpi =4.1.4 +- cloudpickle =2.0.0 +- mpi4py =3.1.4 +- tqdm =4.44.0 +- pyzmq =25.0.0 \ No newline at end of file diff --git a/.ci_support/environment-openmpi.yml b/.ci_support/environment-openmpi.yml index 3dcad16c..4f35bca9 100644 --- a/.ci_support/environment-openmpi.yml +++ b/.ci_support/environment-openmpi.yml @@ -4,7 +4,7 @@ dependencies: - python - numpy - openmpi -- cloudpickle =2.2.1 -- mpi4py =3.1.4 +- cloudpickle =3.0.0 +- mpi4py =3.1.5 - tqdm =4.66.1 -- pyzmq =25.1.1 +- pyzmq =25.1.2 diff --git a/.ci_support/environment-win.yml b/.ci_support/environment-win.yml index d4ac426c..4fb6e616 100644 --- a/.ci_support/environment-win.yml +++ b/.ci_support/environment-win.yml @@ -4,7 +4,7 @@ dependencies: - python - numpy - msmpi -- cloudpickle =2.2.1 -- mpi4py =3.1.4 +- cloudpickle =3.0.0 +- mpi4py =3.1.5 - tqdm =4.66.1 -- pyzmq =25.1.1 +- pyzmq =25.1.2 diff --git a/.ci_support/release.py b/.ci_support/release.py new file mode 100644 index 00000000..a3edb012 --- /dev/null +++ b/.ci_support/release.py @@ -0,0 +1,61 @@ +def get_setup_version_and_pattern(setup_content): + depend_lst, version_lst = [], [] + for l in setup_content: + if '==' in l: + lst = l.split('[')[-1].split(']')[0].replace(' ', '').replace('"', '').replace("'", '').split(',') + for dep in lst: + if dep != '\n': + version_lst.append(dep.split('==')[1]) + depend_lst.append(dep.split('==')[0]) + + version_high_dict = {d: v for d, v in zip(depend_lst, version_lst)} + return version_high_dict + + +def get_env_version(env_content): + read_flag = False + depend_lst, version_lst = [], [] + for l in env_content: + if 'dependencies:' in l: + read_flag = True + elif read_flag: + lst = l.replace('-', '').replace(' ', '').replace('\n', '').split("=") + if len(lst) == 2: + depend_lst.append(lst[0]) + version_lst.append(lst[1]) + return {d:v for d, v in zip(depend_lst, version_lst)} + + +def update_dependencies(setup_content, version_low_dict, version_high_dict): + version_combo_dict = {} + for dep, ver in version_high_dict.items(): + if dep in version_low_dict.keys() and version_low_dict[dep] != ver: + version_combo_dict[dep] = dep + ">=" + version_low_dict[dep] + ",<=" + ver + else: + version_combo_dict[dep] = dep + "==" + ver + + setup_content_new = "" + pattern_dict = {d:d + "==" + v for d, v in version_high_dict.items()} + for l in setup_content: + for k, v in pattern_dict.items(): + if v in l: + l = l.replace(v, version_combo_dict[k]) + setup_content_new +=l + return setup_content_new + + +if __name__ == "__main__": + with open('pyproject.toml', "r") as f: + setup_content = f.readlines() + + with open('environment.yml', "r") as f: + env_content = f.readlines() + + setup_content_new = update_dependencies( + setup_content=setup_content[2:], + version_low_dict=get_env_version(env_content=env_content), + version_high_dict=get_setup_version_and_pattern(setup_content=setup_content[2:]), + ) + + with open('pyproject.toml', "w") as f: + f.writelines("".join(setup_content[:2]) + setup_content_new) diff --git a/.github/delete-merged-branch-config.yml b/.github/delete-merged-branch-config.yml deleted file mode 100644 index da32d1c9..00000000 --- a/.github/delete-merged-branch-config.yml +++ /dev/null @@ -1,3 +0,0 @@ -exclude: - - main -delete_closed_pr: false \ No newline at end of file diff --git a/.github/workflows/black.yml b/.github/workflows/black.yml index 363ba27f..9f5d698e 100644 --- a/.github/workflows/black.yml +++ b/.github/workflows/black.yml @@ -1,5 +1,4 @@ -# This workflow will install Python dependencies, run tests and lint with a variety of Python versions -# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions +# This workflow is used to check the differences and find conflict markers or whitespace errors name: Black @@ -14,19 +13,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - - uses: conda-incubator/setup-miniconda@v2.2.0 + - uses: psf/black@stable with: - python-version: '3.11' - mamba-version: "*" - channels: conda-forge - miniforge-variant: Mambaforge - channel-priority: strict - auto-update-conda: true - environment-file: .ci_support/environment-openmpi.yml - - name: Setup - shell: bash -l {0} - run: | - conda install -c conda-forge black - - name: Test - shell: bash -l {0} - run: black --check pympipool \ No newline at end of file + options: "--check --diff" + src: ./${{ github.event.repository.name }} diff --git a/.github/workflows/check-macos-latest.yml b/.github/workflows/check-macos-latest.yml new file mode 100644 index 00000000..dc28c9d4 --- /dev/null +++ b/.github/workflows/check-macos-latest.yml @@ -0,0 +1,35 @@ +# We are waiting on the macos-latest image to play nicely with MPI + +name: Is-macos-latest-working-yet + +on: + schedule: + - cron: '0 23 * * 2' + workflow_dispatch: + +jobs: + openmpi-on-macos-latest: + runs-on: macos-latest + steps: + - uses: actions/checkout@v2 + - uses: conda-incubator/setup-miniconda@v2.2.0 + with: + python-version: "3.11" + mamba-version: "*" + channels: conda-forge + miniforge-variant: Mambaforge + channel-priority: strict + auto-update-conda: true + environment-file: .ci_support/environment-openmpi.yml + - name: Test + shell: bash -l {0} + timeout-minutes: 10 + run: | + pip install versioneer[toml]==0.29 + pip install . --no-deps --no-build-isolation + cd tests + python -m unittest discover . + env: + OMPI_MCA_plm: 'isolated' + OMPI_MCA_rmaps_base_oversubscribe: 'yes' + OMPI_MCA_btl_vader_single_copy_mechanism: 'none' diff --git a/.github/workflows/dependabot.yml b/.github/workflows/dependabot.yml new file mode 100644 index 00000000..74b47f22 --- /dev/null +++ b/.github/workflows/dependabot.yml @@ -0,0 +1,38 @@ +name: Update Dependabot + +on: + pull_request_target: + branches: [ main ] + +jobs: + build: + runs-on: ubuntu-latest + if: (github.actor == 'dependabot[bot]') + steps: + - uses: actions/checkout@v2 + with: + ref: ${{ github.event.pull_request.head.ref }} # Check out the head of the actual branch, not the PR + fetch-depth: 0 # otherwise, you will fail to push refs to dest repo + token: ${{ secrets.DEPENDABOT_WORKFLOW_TOKEN }} + - name: UpdateEnvironmentFile + env: + PR_TITLE: ${{ github.event.pull_request.title }} + shell: bash -l {0} + run: | + package=$(echo "$PR_TITLE" | awk '{print $2}') + from=$(echo "$PR_TITLE" | awk '{print $4}') + to=$(echo "$PR_TITLE" | awk '{print $6}') + sed -i "/${package}/s/${from}/${to}/g" .ci_support/environment-mpich.yml + sed -i "/${package}/s/${from}/${to}/g" .ci_support/environment-openmpi.yml + sed -i "/${package}/s/${from}/${to}/g" .ci_support/environment-win.yml + sed -i "/${package}/s/${from}/${to}/g" .ci_support/environment-docs.yml + - name: UpdateDependabotPR commit + run: | + git config --local user.email "pyiron@mpie.de" + git config --local user.name "pyironrunner" + git commit -m "[dependabot skip] Update environment" -a + - name: UpdateDependabotPR push + uses: ad-m/github-push-action@master + with: + github_token: ${{ secrets.DEPENDABOT_WORKFLOW_TOKEN }} + branch: ${{ github.event.pull_request.head.ref }} diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index b32f614b..8315c0b5 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -1,32 +1,41 @@ +# This workflow is used to upload and deploy a new release to PyPi +# Based on https://github.com/pypa/gh-action-pypi-publish + name: PyPi Release on: push: pull_request: + workflow_dispatch: -# based on https://github.com/pypa/gh-action-pypi-publish jobs: build: + if: startsWith(github.event.ref, 'refs/tags') || github.event_name == 'release' runs-on: ubuntu-latest - + environment: + name: pypi + url: https://pypi.org/p/${{ github.event.repository.name }} + permissions: + id-token: write steps: - uses: actions/checkout@v2 - - uses: actions/setup-python@v2 + - uses: conda-incubator/setup-miniconda@v2.2.0 with: - python-version: '3.11' - - - name: Install dependencies - run: >- - python -m pip install --user --upgrade setuptools wheel + python-version: 3.11 + mamba-version: "*" + channels: conda-forge + miniforge-variant: Mambaforge + channel-priority: strict + auto-update-conda: true + environment-file: .ci_support/environment-openmpi.yml - name: Convert dependencies - run: >- - sed -i 's/==/>=/g' setup.py; cat setup.py + run: | + cp .ci_support/environment-old.yml environment.yml + python .ci_support/release.py; cat pyproject.toml - name: Build - run: >- + shell: bash -l {0} + run: | + pip install versioneer[toml]==0.29 python setup.py sdist bdist_wheel - name: Publish distribution 📦 to PyPI - if: startsWith(github.event.ref, 'refs/tags') || github.event_name == 'release' - uses: pypa/gh-action-pypi-publish@master - with: - user: __token__ - password: ${{ secrets.pypi_password }} \ No newline at end of file + uses: pypa/gh-action-pypi-publish@release/v1 diff --git a/.github/workflows/format_black.yml b/.github/workflows/format_black.yml new file mode 100644 index 00000000..f7a62e5d --- /dev/null +++ b/.github/workflows/format_black.yml @@ -0,0 +1,33 @@ +# This workflow will checkout the branch of the PR, apply black formatting and commit the result to the PR. Does not work for forks. + +name: Format black + +on: + pull_request: + types: [labeled] + +jobs: + build: + if: contains(github.event.pull_request.labels.*.name, 'format_black' ) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + token: ${{ secrets.DEPENDABOT_WORKFLOW_TOKEN }} + ref: ${{ github.event.pull_request.head.ref }} # Check out the head of the actual branch, not the PR + fetch-depth: 0 # otherwise, you will fail to push refs to dest repo + - name: format black + uses: psf/black@stable + with: + options: "" + src: "./${{ github.event.repository.name }}" + - name: commit + run: | + git config --local user.email "pyiron@mpie.de" + git config --local user.name "pyiron-runner" + git commit -m "Format black" -a + - name: push + uses: ad-m/github-push-action@master + with: + github_token: ${{ secrets.DEPENDABOT_WORKFLOW_TOKEN }} + branch: ${{ github.event.pull_request.head.ref }} diff --git a/.github/workflows/pypicheck.yml b/.github/workflows/pypicheck.yml index 202829a7..5c8dbbf9 100644 --- a/.github/workflows/pypicheck.yml +++ b/.github/workflows/pypicheck.yml @@ -23,5 +23,6 @@ jobs: - name: Setup shell: bash -l {0} run: | - pip install --no-deps . + pip install versioneer[toml]==0.29 + pip install . --no-deps --no-build-isolation pip check diff --git a/.github/workflows/unittest-flux.yml b/.github/workflows/unittest-flux.yml index 7c20a8b2..14d10bcb 100644 --- a/.github/workflows/unittest-flux.yml +++ b/.github/workflows/unittest-flux.yml @@ -38,22 +38,15 @@ jobs: channel-priority: strict auto-update-conda: true environment-file: ${{ matrix.environment-file }} - - name: Install flux - shell: bash -l {0} - run: mamba install -y flux-core coverage - - name: Setup - shell: bash -l {0} - run: pip install --no-deps . - name: Test shell: bash -l {0} timeout-minutes: 5 - run: > - for f in $(ls tests/test_*.py); do - echo $f; - if [ $f != "tests/test_flux.py" ]; then - coverage run --omit pympipool/_version.py -m unittest $f; - fi - done + run: | + mamba install -y flux-core=0.58.0 coverage + pip install versioneer[toml]==0.29 + pip install . --no-deps --no-build-isolation + cd tests + coverage run --omit pympipool/_version.py -m unittest discover . env: OMPI_MCA_plm: 'isolated' OMPI_MCA_rmaps_base_oversubscribe: 'yes' diff --git a/.github/workflows/unittest-mpich.yml b/.github/workflows/unittest-mpich.yml index 6f59c2a1..9e24625f 100644 --- a/.github/workflows/unittest-mpich.yml +++ b/.github/workflows/unittest-mpich.yml @@ -15,7 +15,7 @@ jobs: strategy: matrix: include: - - operating-system: macos-latest + - operating-system: macos-11 python-version: '3.12' label: osx-64-py-3-12-mpich prefix: /Users/runner/miniconda3/envs/my-env @@ -56,10 +56,11 @@ jobs: channel-priority: strict auto-update-conda: true environment-file: .ci_support/environment-mpich.yml - - name: Setup - shell: bash -l {0} - run: pip install --no-deps . - name: Test shell: bash -l {0} timeout-minutes: 5 - run: for f in $(ls tests/test_*.py); do echo $f; python -m unittest $f; done + run: | + pip install versioneer[toml]==0.29 + pip install . --no-deps --no-build-isolation + cd tests + python -m unittest discover . diff --git a/.github/workflows/unittest-openmpi.yml b/.github/workflows/unittest-openmpi.yml index 9de84c3d..ff651757 100644 --- a/.github/workflows/unittest-openmpi.yml +++ b/.github/workflows/unittest-openmpi.yml @@ -15,7 +15,7 @@ jobs: strategy: matrix: include: - - operating-system: macos-latest + - operating-system: macos-11 python-version: '3.12' label: osx-64-py-3-12-openmpi prefix: /Users/runner/miniconda3/envs/my-env @@ -29,17 +29,17 @@ jobs: python-version: '3.11' label: linux-64-py-3-11-openmpi prefix: /usr/share/miniconda3/envs/my-env - + - operating-system: ubuntu-latest python-version: '3.10' label: linux-64-py-3-10-openmpi prefix: /usr/share/miniconda3/envs/my-env - + - operating-system: ubuntu-latest python-version: 3.9 label: linux-64-py-3-9-openmpi prefix: /usr/share/miniconda3/envs/my-env - + - operating-system: ubuntu-latest python-version: 3.8 label: linux-64-py-3-8-openmpi @@ -56,13 +56,14 @@ jobs: channel-priority: strict auto-update-conda: true environment-file: .ci_support/environment-openmpi.yml - - name: Setup - shell: bash -l {0} - run: pip install --no-deps . - name: Test shell: bash -l {0} timeout-minutes: 5 - run: for f in $(ls tests/test_*.py); do echo $f; python -m unittest $f; done + run: | + pip install versioneer[toml]==0.29 + pip install . --no-deps --no-build-isolation + cd tests + python -m unittest discover . env: OMPI_MCA_plm: 'isolated' OMPI_MCA_rmaps_base_oversubscribe: 'yes' diff --git a/.github/workflows/unittest-win.yml b/.github/workflows/unittest-win.yml index d82caba5..bf0710e3 100644 --- a/.github/workflows/unittest-win.yml +++ b/.github/workflows/unittest-win.yml @@ -28,10 +28,11 @@ jobs: channel-priority: strict auto-update-conda: true environment-file: .ci_support/environment-win.yml - - name: Setup - shell: bash -l {0} - run: pip install --no-deps . - name: Test shell: bash -l {0} timeout-minutes: 5 - run: for f in $(ls tests/test_*.py); do echo $f; python -m unittest $f; done + run: | + pip install versioneer[toml]==0.29 + pip install . --no-deps --no-build-isolation + cd tests + python -m unittest discover . diff --git a/.github/workflows/unittests-old.yml b/.github/workflows/unittests-old.yml new file mode 100644 index 00000000..dc49dafd --- /dev/null +++ b/.github/workflows/unittests-old.yml @@ -0,0 +1,37 @@ +# This workflow is used to run the unittest of pyiron + +name: Unittest Lower Bound + +on: + push: + branches: [ main ] + pull_request: + branches: [ main ] + +jobs: + build: + + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: conda-incubator/setup-miniconda@v2.2.0 + with: + python-version: '3.9' + mamba-version: "*" + channels: conda-forge + miniforge-variant: Mambaforge + channel-priority: strict + auto-update-conda: true + environment-file: .ci_support/environment-old.yml + - name: Test + shell: bash -l {0} + timeout-minutes: 5 + run: | + pip install versioneer[toml]==0.29 + pip install . --no-deps --no-build-isolation + cd tests + python -m unittest discover . + env: + OMPI_MCA_plm: 'isolated' + OMPI_MCA_rmaps_base_oversubscribe: 'yes' + OMPI_MCA_btl_vader_single_copy_mechanism: 'none' diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..912537cd --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +*.pyc +.DS_Store +.coverage +.idea/ +.vscode/ diff --git a/.readthedocs.yml b/.readthedocs.yml index b4de3480..38c2541e 100644 --- a/.readthedocs.yml +++ b/.readthedocs.yml @@ -6,9 +6,13 @@ version: 2 build: - os: "ubuntu-20.04" + os: "ubuntu-22.04" tools: - python: "mambaforge-4.10" + python: "mambaforge-22.9" + jobs: + pre_build: + - pip install versioneer[toml]==0.29 + - pip install . --no-deps --no-build-isolation # Build documentation in the docs/ directory with Sphinx sphinx: @@ -19,10 +23,4 @@ formats: [] # Install pyiron from conda conda: - environment: .ci_support/environment-docs.yml - -# Optionally set the version of Python and requirements required to build your docs -python: - install: - - method: pip - path: . \ No newline at end of file + environment: .ci_support/environment-docs.yml \ No newline at end of file diff --git a/MANIFEST.in b/MANIFEST.in index 3078faee..cc0d1164 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,3 +1 @@ -include versioneer.py -include pympipool/_version.py include LICENSE \ No newline at end of file diff --git a/README.md b/README.md index 1206b284..d357e529 100644 --- a/README.md +++ b/README.md @@ -1,110 +1,153 @@ -# pympipool - scale python functions over multiple compute nodes +# pympipool - up-scale python functions for high performance computing [![Unittests](https://github.com/pyiron/pympipool/actions/workflows/unittest-openmpi.yml/badge.svg)](https://github.com/pyiron/pympipool/actions/workflows/unittest-openmpi.yml) [![Coverage Status](https://coveralls.io/repos/github/pyiron/pympipool/badge.svg?branch=main)](https://coveralls.io/github/pyiron/pympipool?branch=main) +[![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/pyiron/pympipool/HEAD?labpath=notebooks%2Fexamples.ipynb) -Up-scaling python functions for high performance computing (HPC) can be challenging. While the python standard library -provides interfaces for multiprocessing and asynchronous task execution, namely [`multiprocessing`](https://docs.python.org/3/library/multiprocessing.html) -and [`concurrent.futures`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures) both are -limited to the execution on a single compute node. So a series of python libraries have been developed to address the -up-scaling of python functions for HPC. Starting in the datascience and machine learning community with solutions like -[dask](https://www.dask.org) over more HPC focused solutions like [parsl](http://parsl-project.org) up to Python bindings -for the message passing interface (MPI) named [mpi4py](https://mpi4py.readthedocs.io). Each of these solutions has their -advantages and disadvantages, in particular the mixing of MPI parallel python functions and serial python functions in -combined workflows remains challenging. - -To address these challenges `pympipool` is developed with three goals in mind: -* Reimplement the standard python library interfaces namely [`multiprocessing.pool.Pool`](https://docs.python.org/3/library/multiprocessing.html) -and [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures) -as closely as possible, to minimize the barrier of up-scaling an existing workflow to be used on HPC resources. -* Integrate MPI parallel python functions based on [mpi4py](https://mpi4py.readthedocs.io) on the same level as serial -python functions, so both can be combined in a single workflow. This allows the users to parallelize their workflows -one function at a time. Internally this is achieved by coupling a serial python process to a MPI parallel python process. -* Embrace [Jupyter](https://jupyter.org) notebooks for the interactive development of HPC workflows, as they allow the -users to document their though process right next to the python code and their results all within one document. - -# Features -As different users and different workflows have different requirements in terms of the level of parallelization, the -`pympipool` implements a series of five different interfaces: -* [`pympipool.Pool`](https://pympipool.readthedocs.io/en/latest/interfaces.html#pool): Following the -[`multiprocessing.pool.Pool`](https://docs.python.org/3/library/multiprocessing.html) the `pympipool.Pool` class -implements the `map()` and `starmap()` functions. Internally these connect to an MPI parallel subprocess running the -[`mpi4py.futures.MPIPoolExecutor`](https://mpi4py.readthedocs.io/en/stable/mpi4py.futures.html#mpipoolexecutor). -So by increasing the number of workers, by setting the `max_workers` parameter the `pympipool.Pool` can scale the -execution of serial python functions beyond a single compute node. For MPI parallel python functions the `pympipool.MPISpawnPool` -is derived from the `pympipool.Pool` and uses `MPI_Spawn()` to execute those. For more details see below. -* [`pympipool.Executor`](https://pympipool.readthedocs.io/en/latest/interfaces.html#executor): The easiest way to -execute MPI parallel python functions right next to serial python functions is the `pympipool.Executor`. It implements -the executor interface defined by the [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures). -So functions are submitted to the `pympipool.Executor` using the `submit()` function, which returns an -[`concurrent.futures.Future`](https://docs.python.org/3/library/concurrent.futures.html#future-objects) object. With -these [`concurrent.futures.Future`](https://docs.python.org/3/library/concurrent.futures.html#future-objects) objects -asynchronous workflows can be constructed which periodically check if the computation is completed `done()` and then -query the results using the `result()` function. The limitation of the `pympipool.Executor` is lack of load balancing, -each `pympipool.Executor` acts as a serial first in first out (FIFO) queue. So it is the task of the user to balance the -load of many different tasks over multiple `pympipool.Executor` instances. -* [`pympipool.HPCExecutor`](https://pympipool.readthedocs.io/en/latest/interfaces.html#hpcexecutor>): To address the -limitation of the `pympipool.Executor` that only a single task is executed at any time, the `pympipool.HPCExecutor` -provides a wrapper around multiple `pympipool.Executor` objects. It balances the queues of the individual -`pympipool.Executor` objects to maximize the throughput for the given resources. This functionality comes with an -additional overhead of another thread, acting as a broker between the task queue of the `pympipool.HPCExecutor` and the -individual `pympipool.Executor` objects. -* [`pympipool.PoolExecutor`](https://pympipool.readthedocs.io/en/latest/interfaces.html#poolexecutor): To combine the -functionality of the `pympipool.Pool` and the `pympipool.Executor` the `pympipool.PoolExecutor` again connects to the -[`mpi4py.futures.MPIPoolExecutor`](https://mpi4py.readthedocs.io/en/stable/mpi4py.futures.html#mpipoolexecutor). -Still in contrast to the `pympipool.Pool` it does not implement the `map()` and `starmap()` functions but rather the -`submit()` function based on the [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures) -interface. In this case the load balancing happens internally and the maximum number of workers `max_workers` defines -the maximum number of parallel tasks. But only serial python tasks can be executed in contrast to the `pympipool.Executor` -which can also execute MPI parallel python tasks. -* [`pympipool.MPISpawnPool`](https://pympipool.readthedocs.io/en/latest/interfaces.html#mpispawnpool): An alternative -way to support MPI parallel functions in addition to the `pympipool.Executor` is the `pympipool.MPISpawnPool`. Just like -the `pympipool.Pool` it supports the `map()` and `starmap()` functions. The additional `ranks_per_task` parameter -defines how many MPI ranks are used per task. All functions are executed with the same number of MPI ranks. The -limitation of this approach is that it uses `MPI_Spawn()` to create new MPI ranks for the execution of the individual -tasks. Consequently, this approach is not as scalable as the `pympipool.Executor` but it offers load balancing for a -large number of similar MPI parallel tasks. -* [`pympipool.SocketInterface`](https://pympipool.readthedocs.io/en/latest/interfaces.html#socketinterface): The key -functionality of the `pympipool` package is the coupling of a serial python process with an MPI parallel python process. -This happens in the background using a combination of the [zero message queue](https://zeromq.org) and -[cloudpickle](https://github.com/cloudpipe/cloudpickle) to communicate binary python objects. The `pympipool.SocketInterface` -is an abstraction of this interface, which is used in the other classes inside `pympipool` and might also be helpful for -other projects. - -In addition to using MPI to start a number of processes on different HPC computing resources, `pympipool` also supports -the [flux-framework](https://flux-framework.org) as additional backend. By setting the optional `enable_flux_backend` -parameter to `True` the flux backend can be enabled for the `pympipool.Pool`, `pympipool.Executor` and `pympipool.PoolExecutor`. -Other optional parameters include the selection of the working directory where the python function should be executed `cwd` -and the option to oversubscribe MPI tasks which is an [OpenMPI](https://www.open-mpi.org) specific feature which can be -enabled by setting `oversubscribe` to `True`. For more details on the `pympipool` classes and their application, the -extended documentation is linked below. +Up-scaling python functions for high performance computing (HPC) can be challenging. While the python standard library +provides interfaces for multiprocessing and asynchronous task execution, namely +[multiprocessing](https://docs.python.org/3/library/multiprocessing.html) and +[concurrent.futures](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures) both are +limited to the execution on a single compute node. So a series of python libraries have been developed to address the +up-scaling of python functions for HPC. Starting in the datascience and machine learning community with solutions +like [dask](https://www.dask.org) over more HPC focused solutions like +[fireworks](https://materialsproject.github.io/fireworks/) and [parsl](http://parsl-project.org) up to Python +bindings for the message passing interface (MPI) named [mpi4py](https://mpi4py.readthedocs.io). Each of these +solutions has their advantages and disadvantages, in particular scaling beyond serial python functions, including thread +based parallelism, MPI parallel python application or assignment of GPUs to individual python function remains +challenging. + +To address these challenges `pympipool` is developed with three goals in mind: + +* Extend the standard python library [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures) + interface, to minimize the barrier of up-scaling an existing workflow to be used on HPC resources. +* Integrate thread based parallelism, MPI parallel python functions based on [mpi4py](https://mpi4py.readthedocs.io) and + GPU assignment. This allows the users to accelerate their workflows one function at a time. +* Embrace [Jupyter](https://jupyter.org) notebooks for the interactive development of HPC workflows, as they allow the + users to document their though process right next to the python code and their results all within one document. + +## HPC Context +In contrast to frameworks like [dask](https://www.dask.org), [fireworks](https://materialsproject.github.io/fireworks/) +and [parsl](http://parsl-project.org) which can be used to submit a number of worker processes directly the the HPC +queuing system and then transfer tasks from either the login node or an interactive allocation to these worker processes +to accelerate the execution, [mpi4py](https://mpi4py.readthedocs.io) and `pympipool` follow a different +approach. Here the user creates their HPC allocation first and then [mpi4py](https://mpi4py.readthedocs.io) or +`pympipool` can be used to distribute the tasks within this allocation. The advantage of this approach is that +no central data storage is required as the workers and the scheduling task can communicate directly. + +## Examples +The following examples illustrates how `pympipool` can be used to distribute a series of MPI parallel function calls +within a queuing system allocation. `example.py`: +``` +from pympipool import Executor + +def calc(i): + from mpi4py import MPI + size = MPI.COMM_WORLD.Get_size() + rank = MPI.COMM_WORLD.Get_rank() + return i, size, rank + +with Executor(max_workers=2, cores_per_worker=2) as exe: + fs_0 = exe.submit(calc, 0) + fs_1 = exe.submit(calc, 1) + print(fs_0.result(), fs_1.result()) +``` +This example can be executed using:: +``` +python example.py +``` +Which returns:: +``` +>>> [(0, 2, 0), (0, 2, 1)], [(1, 2, 0), (1, 2, 1)] +``` +The important part in this example is that [mpi4py](https://mpi4py.readthedocs.io) is only used in the `calc()` +function, not in the python script, consequently it is not necessary to call the script with `mpiexec` but instead +a call with the regular python interpreter is sufficient. This highlights how `pympipool` allows the users to +parallelize one function at a time and not having to convert their whole workflow to use [mpi4py](https://mpi4py.readthedocs.io). +The same code can also be executed inside a jupyter notebook directly which enables an interactive development process. + +The standard [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures) +interface is extended by adding the option `cores_per_worker=2` to assign multiple MPI ranks to each function call. +To create two workers `max_workers=2` each with two cores each requires a total of four CPU cores to be available. +After submitting the function `calc()` with the corresponding parameter to the executor `exe.submit(calc, 0)` +a python [`concurrent.futures.Future`](https://docs.python.org/3/library/concurrent.futures.html#future-objects) is +returned. Consequently, the `pympipool.Executor` can be used as a drop-in replacement for the +[`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures) +which allows the user to add parallelism to their workflow one function at a time. + +## Backends +Depending on the availability of different resource schedulers in your HPC environment the `pympipool.Executor` +uses a different backend, with the `pympipool.flux.PyFluxExecutor` being the preferred backend: + +* `pympipool.mpi.PyMpiExecutor`: The simplest executor of the three uses [mpi4py](https://mpi4py.readthedocs.io) as a + backend. This simplifies the installation on all operating systems including Windows. Still at the same time it limits + the up-scaling to a single compute node and serial or MPI parallel python functions. There is no support for thread + based parallelism or GPU assignment. This interface is primarily used for testing and developing or as a fall-back + solution. It is not recommended to use this interface in production. +* `pympipool.slurm.PySlurmExecutor`: The [SLURM workload manager](https://www.schedmd.com) is commonly used on HPC + systems to schedule and distribute tasks. `pympipool` provides a python interface for scheduling the execution of + python functions as SLURM job steps which are typically created using the `srun` command. This executor supports + serial python functions, thread based parallelism, MPI based parallelism and the assignment of GPUs to individual + python functions. When the [SLURM workload manager](https://www.schedmd.com) is installed on your HPC cluster this + interface can be a reasonable choice, still depending on the [SLURM workload manager](https://www.schedmd.com) + configuration in can be limited in terms of the fine-grained scheduling or the responsiveness when working with + hundreds of compute nodes in an individual allocation. +* `pympipool.flux.PyFluxExecutor`: The [flux framework](https://flux-framework.org) is the preferred backend for + `pympipool`. Just like the `pympipool.slurm.PySlurmExecutor` it supports serial python functions, thread based + parallelism, MPI based parallelism and the assignment of GPUs to individual python functions. Still the advantages of + using the [flux framework](https://flux-framework.org) as a backend are the easy installation, the faster allocation + of resources as the resources are managed within the allocation and no central databases is used and the superior + level of fine-grained resource assignment which is typically not available on HPC resource schedulers. + +Each of these backends consists of two parts a broker and a worker. When a new tasks is submitted from the user it is +received by the broker and the broker identifies the first available worker. The worker then executes a task and returns +it to the broker, who returns it to the user. While there is only one broker per `pympipool.Executor` the number +of workers can be specified with the `max_workers` parameter. + +## Disclaimer +While we try to develop a stable and reliable software library, the development remains a opensource project under the +BSD 3-Clause License without any warranties:: +``` +BSD 3-Clause License + +Copyright (c) 2022, Jan Janssen +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +``` # Documentation -* [Installation](https://pympipool.readthedocs.io/en/latest/installation.html) - * [pypi-based installation](https://pympipool.readthedocs.io/en/latest/installation.html#pypi-based-installation) - * [conda-based installation](https://pympipool.readthedocs.io/en/latest/installation.html#conda-based-installation) -* [Interfaces](https://pympipool.readthedocs.io/en/latest/interfaces.html) - * [Pool](https://pympipool.readthedocs.io/en/latest/interfaces.html#pool) - * [Executor](https://pympipool.readthedocs.io/en/latest/interfaces.html#executor) - * [HPCExecutor](https://pympipool.readthedocs.io/en/latest/interfaces.html#hpcexecutor>) - * [ParallelExecutor](https://pympipool.readthedocs.io/en/latest/interfaces.html#poolexecutor) - * [MPISpawnPool](https://pympipool.readthedocs.io/en/latest/interfaces.html#mpispawnpool) - * [SocketInterface](https://pympipool.readthedocs.io/en/latest/interfaces.html#socketinterface) -* [Development](https://pympipool.readthedocs.io/en/latest/development.html) - -# License -`pympipool` is released under the BSD license https://github.com/pyiron/pympipool/blob/main/LICENSE . It is a spin-off -of the `pyiron` project https://github.com/pyiron/pyiron therefore if you use `pympipool` for calculation which result -in a scientific publication, please cite: - - @article{pyiron-paper, - title = {pyiron: An integrated development environment for computational materials science}, - journal = {Computational Materials Science}, - volume = {163}, - pages = {24 - 36}, - year = {2019}, - issn = {0927-0256}, - doi = {https://doi.org/10.1016/j.commatsci.2018.07.043}, - url = {http://www.sciencedirect.com/science/article/pii/S0927025618304786}, - author = {Jan Janssen and Sudarsan Surendralal and Yury Lysogorskiy and Mira Todorova and Tilmann Hickel and Ralf Drautz and Jörg Neugebauer}, - keywords = {Modelling workflow, Integrated development environment, Complex simulation protocols}, - } +* [Installation](https://pympipool.readthedocs.io/en/latest/installation.html) + * [Basic Installation](https://pympipool.readthedocs.io/en/latest/installation.html#basic-installation) + * [High Performance Computing](https://pympipool.readthedocs.io/en/latest/installation.html#high-performance-computing) +* [Examples](https://pympipool.readthedocs.io/en/latest/examples.html) + * [Compatibility](https://pympipool.readthedocs.io/en/latest/examples.html#compatibility) + * [Data Handling](https://pympipool.readthedocs.io/en/latest/examples.html#data-handling) + * [Up-Scaling](https://pympipool.readthedocs.io/en/latest/examples.html#up-scaling) +* [Development](https://pympipool.readthedocs.io/en/latest/development.html) + * [Contributions](https://pympipool.readthedocs.io/en/latest/development.html#contributions) + * [Integration](https://pympipool.readthedocs.io/en/latest/development.html#integration) + * [Alternative Projects](https://pympipool.readthedocs.io/en/latest/development.html#alternative-projects) +* [Module Index](https://pympipool.readthedocs.io/en/latest/py-modindex.html) diff --git a/binder/environment.yml b/binder/environment.yml new file mode 100644 index 00000000..34f38cda --- /dev/null +++ b/binder/environment.yml @@ -0,0 +1,11 @@ +channels: +- conda-forge +dependencies: +- python +- numpy +- openmpi +- cloudpickle =3.0.0 +- flux-core +- mpi4py =3.1.5 +- tqdm =4.66.1 +- pyzmq =25.1.1 diff --git a/binder/kernel.json b/binder/kernel.json new file mode 100644 index 00000000..16c69cf5 --- /dev/null +++ b/binder/kernel.json @@ -0,0 +1,16 @@ +{ + "argv": [ + "flux", + "start", + "/srv/conda/envs/notebook/bin/python", + "-m", + "ipykernel_launcher", + "-f", + "{connection_file}" + ], + "display_name": "Flux", + "language": "python", + "metadata": { + "debugger": true + } +} \ No newline at end of file diff --git a/binder/postBuild b/binder/postBuild new file mode 100644 index 00000000..f5cee2b7 --- /dev/null +++ b/binder/postBuild @@ -0,0 +1,6 @@ +# jupyter kernel +mkdir -p /home/jovyan/.local/share/jupyter/kernels/flux +cp binder/kernel.json /home/jovyan/.local/share/jupyter/kernels/flux + +# install pympipool +pip install . \ No newline at end of file diff --git a/docs/source/development.md b/docs/source/development.md index 871be717..ae2a38de 100644 --- a/docs/source/development.md +++ b/docs/source/development.md @@ -1,10 +1,27 @@ # Development The `pympipool` package is developed based on the need to simplify the up-scaling of python functions over multiple compute nodes. The project is under active development, so the difference between the individual interfaces might not -always be clearly defined. The `pympipool.Pool` interface is the oldest and consequently currently most stable but at -the same time also most limited interface. The `pympipool.Executor` is the recommended interface for most workflows but -it can be computationally less efficient than the `pympipool.PoolExecutor` interface for large number of serial python -functions. Finally, the `pympipool.MPISpawnPool` is primarily a prototype of an alternative interface, which is available -for testing but typically not recommended, based on the limitations of initiating new communicators. +always be clearly defined. -Any feedback and contributions are welcome. \ No newline at end of file +## Contributions +Any feedback and contributions are welcome. + +## Integration +The key functionality of the `pympipool` package is the up-scaling of python functions with thread based parallelism, +MPI based parallelism or by assigning GPUs to individual python functions. In the background this is realized using a +combination of the [zero message queue](https://zeromq.org) and [cloudpickle](https://github.com/cloudpipe/cloudpickle) +to communicate binary python objects. The `pympipool.communication.SocketInterface` is an abstraction of this interface, +which is used in the other classes inside `pympipool` and might also be helpful for other projects. It comes with a +series of utility functions: + +* `pympipool.communication.interface_bootup()`: To initialize the interface +* `pympipool.communication.interface_connect()`: To connect the interface to another instance +* `pympipool.communication.interface_send()`: To send messages via this interface +* `pympipool.communication.interface_receive()`: To receive messages via this interface +* `pympipool.communication.interface_shutdown()`: To shutdown the interface + +## Alternative Projects +[dask](https://www.dask.org), [fireworks](https://materialsproject.github.io/fireworks/) and [parsl](http://parsl-project.org) +address similar challenges. On the one hand they are more restrictive when it comes to the assignment of resource to +a given worker for execution, on the other hand they provide support beyond the high performance computing (HPC) +environment. \ No newline at end of file diff --git a/docs/source/examples.md b/docs/source/examples.md new file mode 100644 index 00000000..978cd4d8 --- /dev/null +++ b/docs/source/examples.md @@ -0,0 +1,393 @@ +# Examples +The `pympipool.Executor` extends the interface of the [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures) +to simplify the up-scaling of individual functions in a given workflow. + +## Compatibility +Starting with the basic example of `1+1=2`. With the `ThreadPoolExecutor` from the [`concurrent.futures`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures) +standard library this can be written as - `test_thread.py`: +``` +from concurrent.futures import ThreadPoolExecutor + +with ThreadPoolExecutor( + max_workers=1, +) as exe: + future = exe.submit(sum, [1, 1]) + print(future.result()) +``` +In this case `max_workers=1` limits the number of threads used by the `ThreadPoolExecutor` to one. Then the `sum()` +function is submitted to the executor with a list with two ones `[1, 1]` as input. A [`concurrent.futures.Future`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures) +object is returned. The `Future` object allows to check the status of the execution with the `done()` method which +returns `True` or `False` depending on the state of the execution. Or the main process can wait until the execution is +completed by calling `result()`. + +This example stored in a python file named `test_thread.py` can be executed using the python interpreter: +``` +python test_thread.py +>>> 2 +``` +The result of the calculation is `1+1=2`. + +The `pympipool.Executor` class extends the interface of the [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures) +class by providing more parameters to specify the level of parallelism. In addition, to specifying the maximum number +of workers `max_workers` the user can also specify the number of cores per worker `cores_per_worker` for MPI based +parallelism, the number of threads per core `threads_per_core` for thread based parallelism and the number of GPUs per +worker `gpus_per_worker`. Finally, for those backends which support over-subscribing this can also be enabled using the +`oversubscribe` parameter. All these parameters are optional, so the `pympipool.Executor` can be used as a drop-in +replacement for the [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures). + +The previous example is rewritten for the `pympipool.Executor` in - `test_sum.py`: +``` +from pympipool import Executor + +with Executor( + max_workers=1, + cores_per_worker=1, + threads_per_core=1, + gpus_per_worker=0, + oversubscribe=False +) as exe: + future = exe.submit(sum, [1,1]) + print(future.result()) +``` +Again this example can be executed with the python interpreter: +``` +python test_sum.py +>>> 2 +``` +The result of the calculation is again `1+1=2`. + +Beyond pre-defined functions like the `sum()` function, the same functionality can be used to submit user-defined +functions. In the `test_serial.py` example a custom summation function is defined: +``` +from pympipool import Executor + +def calc(*args): + return sum(*args) + +with Executor(max_workers=2) as exe: + fs_1 = exe.submit(calc, [2, 1]) + fs_2 = exe.submit(calc, [2, 2]) + fs_3 = exe.submit(calc, [2, 3]) + fs_4 = exe.submit(calc, [2, 4]) + print([ + fs_1.result(), + fs_2.result(), + fs_3.result(), + fs_4.result(), + ]) +``` +In contrast to the previous example where just a single function was submitted to a single worker, in this case a total +of four functions is submitted to a group of two workers `max_workers=2`. Consequently, the functions are executed as a +set of two pairs. + +The script can be executed with any python interpreter: +``` +python test_serial.py +>>> [3, 4, 5, 6] +``` +It returns the corresponding sums as expected. The same can be achieved with the built-in [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures) +classes. Still one advantage of using the `pympipool.Executor` rather than the built-in ones, is the ability to execute +the same commands in interactive environments like [Jupyter notebooks](https://jupyter.org). This is achieved by using +[cloudpickle](https://github.com/cloudpipe/cloudpickle) to serialize the python function and its parameters rather than +the regular pickle package. + +For backwards compatibility with the [`multiprocessing.Pool`](https://docs.python.org/3/library/multiprocessing.html) +class the [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures) +also implements the `map()` function to map a series of inputs to a function. The same `map()` function is also +available in the `pympipool.Executor` - `test_map.py`: +``` +from pympipool import Executor + +def calc(*args): + return sum(*args) + +with Executor(max_workers=2) as exe: + print(list(exe.map(calc, [[2, 1], [2, 2], [2, 3], [2, 4]]))) +``` +Again the script can be executed with any python interpreter: +``` +python test_map.py +>>> [3, 4, 5, 6] +``` +The results remain the same. + +## Data Handling +A limitation of many parallel approaches is the overhead in communication when working with large datasets. Instead of +reading the same dataset repetitively, the `pympipool.Executor` loads the dataset only once per worker and afterwards +each function submitted to this worker has access to the dataset, as it is already loaded in memory. To achieve this +the user defines an initialization function `init_function` which returns a dictionary with one key per dataset. The +keys of the dictionary can then be used as additional input parameters in each function submitted to the `pympipool.Executor`. +This functionality is illustrated in the `test_data.py` example: +``` +from pympipool import Executor + +def calc(i, j, k): + return i + j + k + +def init_function(): + return {"j": 4, "k": 3, "l": 2} + +with Executor(max_workers=1, init_function=init_function) as exe: + fs = exe.submit(calc, 2, j=5) + print(fs.result()) +``` +The function `calc()` requires three inputs `i`, `j` and `k`. But when the function is submitted to the executor only +two inputs are provided `fs = exe.submit(calc, 2, j=5)`. In this case the first input parameter is mapped to `i=2`, the +second input parameter is specified explicitly `j=5` but the third input parameter `k` is not provided. So the +`pympipool.Executor` automatically checks the keys set in the `init_function()` function. In this case the returned +dictionary `{"j": 4, "k": 3, "l": 2}` defines `j=4`, `k=3` and `l=2`. For this specific call of the `calc()` function, +`i` and `j` are already provided so `j` is not required, but `k=3` is used from the `init_function()` and as the `calc()` +function does not define the `l` parameter this one is also ignored. + +Again the script can be executed with any python interpreter: +``` +python test_data.py +>>> 10 +``` +The result is `2+5+3=10` as `i=2` and `j=5` are provided during the submission and `k=3` is defined in the `init_function()` +function. + +## Up-Scaling +The availability of certain features depends on the backend `pympipool` is installed with. In particular the thread +based parallelism and the GPU assignment is only available with the `pympipool.slurm.PySlurmExecutor` or the +`pympipool.flux.PyFluxExecutor` backend. The latter is recommended based on the easy installation, the faster allocation +of resources as the resources are managed within the allocation and no central databases is used and the superior level +of fine-grained resource assignment which is typically not available on other HPC resource schedulers including the +[SLURM workload manager](https://www.schedmd.com). The `pympipool.flux.PyFluxExecutor` requires +[flux framework](https://flux-framework.org) to be installed in addition to the `pympipool` package. The features are +summarized in the table below: + +| Feature \ Backend | `PyMpiExecutor` | `PySlurmExecutor` | `PyFluxExecutor` | +|:--------------------------:|:---------------:|:-----------------:|:----------------:| +| Thread based parallelism | no | yes | yes | +| MPI based parallelism | yes | yes | yes | +| GPU assignment | no | yes | yes | +| Resource over-subscription | yes | yes | no | +| Scalability | 1 node | ~100 nodes | no limit | + +### Thread-based Parallelism +The number of threads per core can be controlled with the `threads_per_core` parameter during the initialization of the +`pympipool.Executor`. Unfortunately, there is no uniform way to control the number of cores a given underlying library +uses for thread based parallelism, so it might be necessary to set certain environment variables manually: + +* `OMP_NUM_THREADS`: for openmp +* `OPENBLAS_NUM_THREADS`: for openblas +* `MKL_NUM_THREADS`: for mkl +* `VECLIB_MAXIMUM_THREADS`: for accelerate on Mac Os X +* `NUMEXPR_NUM_THREADS`: for numexpr + +At the current stage `pympipool.Executor` does not set these parameters itself, so you have to add them in the function +you submit before importing the corresponding library: + +``` +def calc(i): + import os + os.environ["OMP_NUM_THREADS"] = "2" + os.environ["OPENBLAS_NUM_THREADS"] = "2" + os.environ["MKL_NUM_THREADS"] = "2" + os.environ["VECLIB_MAXIMUM_THREADS"] = "2" + os.environ["NUMEXPR_NUM_THREADS"] = "2" + import numpy as np + return i +``` + +Most modern CPUs use hyper-threading to present the operating system with double the number of virtual cores compared to +the number of physical cores available. So unless this functionality is disabled `threads_per_core=2` is a reasonable +default. Just be careful if the number of threads is not specified it is possible that all workers try to access all +cores at the same time which can lead to poor performance. So it is typically a good idea to monitor the CPU utilization +with increasing number of workers. + +Specific manycore CPU models like the Intel Xeon Phi processors provide a much higher hyper-threading ration and require +a higher number of threads per core for optimal performance. + +### MPI Parallel Python Functions +Beyond thread based parallelism, the message passing interface (MPI) is the de facto standard parallel execution in +scientific computing and the [`mpi4py`](https://mpi4py.readthedocs.io) bindings to the MPI libraries are commonly used +to parallelize existing workflows. The limitation of this approach is that it requires the whole code to adopt the MPI +communication standards to coordinate the way how information is distributed. Just like the `pympipool.Executor` the +[`mpi4py.futures.MPIPoolExecutor`](https://mpi4py.readthedocs.io/en/stable/mpi4py.futures.html#mpipoolexecutor) +implements the [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures) +interface. Still in this case eah python function submitted to the executor is still limited to serial execution. The +novel approach of the `pympipool.Executor` is mixing these two types of parallelism. Individual functions can use +the [`mpi4py`](https://mpi4py.readthedocs.io) library to handle the parallel execution within the context of this +function while these functions can still me submitted to the `pympipool.Executor` just like any other function. The +advantage of this approach is that the users can parallelize their workflows one function at the time. + +The example in `test_mpi.py` illustrates the submission of a simple MPI parallel python function: +``` +from pympipool import Executor + +def calc(i): + from mpi4py import MPI + size = MPI.COMM_WORLD.Get_size() + rank = MPI.COMM_WORLD.Get_rank() + return i, size, rank + +with Executor(cores_per_worker=2) as exe: + fs = exe.submit(calc, 3) + print(fs.result()) +``` +The `calc()` function initializes the [`mpi4py`](https://mpi4py.readthedocs.io) library and gathers the size of the +allocation and the rank of the current process within the MPI allocation. This function is then submitted to an +`pympipool.Executor` which is initialized with a single worker with two cores `cores_per_worker=2`. So each function +call is going to have access to two cores. + +Just like before the script can be called with any python interpreter even though it is using the [`mpi4py`](https://mpi4py.readthedocs.io) +library in the background it is not necessary to execute the script with `mpiexec` or `mpirun`: +``` +python test_mpi.py +>>> [(3, 2, 0), (3, 2, 1)] +``` +The response consists of a list of two tuples, one for each MPI parallel process, with the first entry of the tuple +being the parameter `i=3`, followed by the number of MPI parallel processes assigned to the function call `cores_per_worker=2` +and finally the index of the specific process `0` or `1`. + +### GPU Assignment +With the rise of machine learning applications, the use of GPUs for scientific application becomes more and more popular. +Consequently, it is essential to have full control over the assignment of GPUs to specific python functions. In the +`test_gpu.py` example the `tensorflow` library is used to identify the GPUs and return their configuration: +``` +import socket +from pympipool import Executor +from tensorflow.python.client import device_lib + +def get_available_gpus(): + local_device_protos = device_lib.list_local_devices() + return [ + (x.name, x.physical_device_desc, socket.gethostname()) + for x in local_device_protos if x.device_type == 'GPU' + ] + +with Executor( + max_workers=2, + gpus_per_worker=1, +) as exe: + fs_1 = exe.submit(get_available_gpus) + fs_2 = exe.submit(get_available_gpus) + +print(fs_1.result(), fs_2.result()) +``` +The additional parameter `gpus_per_worker=1` specifies that one GPU is assigned to each worker. This functionality +requires `pympipool` to be connected to a resource manager like the [SLURM workload manager](https://www.schedmd.com) +or preferably the [flux framework](https://flux-framework.org). The rest of the script follows the previous examples, +as two functions are submitted and the results are printed. + +To clarify the execution of such an example on a high performance computing (HPC) cluster using the [SLURM workload manager](https://www.schedmd.com) +the submission script is given below: +``` +#!/bin/bash +#SBATCH --nodes=2 +#SBATCH --gpus-per-node=1 +#SBATCH --get-user-env=L + +python test_gpu.py +``` +The important part is that for using the `pympipool.slurm.PySlurmExecutor` backend the script `test_gpu.py` does not +need to be executed with `srun` but rather it is sufficient to just execute it with the python interpreter. `pympipool` +internally calls `srun` to assign the individual resources to a given worker. + +For the more complex setup of running the [flux framework](https://flux-framework.org) as a secondary resource scheduler +within the [SLURM workload manager](https://www.schedmd.com) it is essential that the resources are passed from the +[SLURM workload manager](https://www.schedmd.com) to the [flux framework](https://flux-framework.org). This is achieved +by calling `srun flux start` in the submission script: +``` +#!/bin/bash +#SBATCH --nodes=2 +#SBATCH --gpus-per-node=1 +#SBATCH --get-user-env=L + +srun flux start python test_gpu.py +``` +As a result the GPUs available on the two compute nodes are reported: +``` +>>> [('/device:GPU:0', 'device: 0, name: Tesla V100S-PCIE-32GB, pci bus id: 0000:84:00.0, compute capability: 7.0', 'cn138'), +>>> ('/device:GPU:0', 'device: 0, name: Tesla V100S-PCIE-32GB, pci bus id: 0000:84:00.0, compute capability: 7.0', 'cn139')] +``` +In this case each compute node `cn138` and `cn139` is equipped with one `Tesla V100S-PCIE-32GB`. + +## External Executables +While `pympipool` was initially designed for up-scaling python functions for HPC, the same functionality can be leveraged +to up-scale any executable independent of the programming language it is developed in. This approach follows the design +of the `flux.job.FluxExecutor` included in the [flux framework](https://flux-framework.org). In `pympipool` this approach +is extended to support any kind of subprocess, so it is no longer limited to the [flux framework](https://flux-framework.org). + +### Subprocess +Following the [`subprocess.check_output()`](https://docs.python.org/3/library/subprocess.html) interface of the standard +python libraries, any kind of command can be submitted to the `pympipool.SubprocessExecutor`. The command can either be +specified as a list `["echo", "test"]` in which the first entry is typically the executable followed by the corresponding +parameters or the command can be specified as a string `"echo test"` with the additional parameter `shell=True`. +``` +from pympipool import SubprocessExecutor + +with SubprocessExecutor(max_workers=2) as exe: + future = exe.submit(["echo", "test"], universal_newlines=True) + print(future.done(), future.result(), future.done()) +>>> (False, "test", True) +``` +In analogy to the previous examples the `SubprocessExecutor` class is directly imported from the `pympipool` module and +the maximum number of workers is set to two `max_workers=2`. In contrast to the `pympipool.Executor` class no other +settings to assign specific hardware to the command via the python interface are available in the `SubprocessExecutor` +class. To specify the hardware requirements for the individual commands, the user has to manually assign the resources +using the commands of the resource schedulers like `srun`, `flux run` or `mpiexec`. + +The `concurrent.futures.Future` object returned after submitting a command to the `pymipool.SubprocessExecutor` behaves +just like any other future object. It provides a `done()` function to check if the execution completed as well as a +`result()` function to return the output of the submitted command. + +In comparison to the `flux.job.FluxExecutor` included in the [flux framework](https://flux-framework.org) the +`pymipool.SubprocessExecutor` differs in two ways. One the `pymipool.SubprocessExecutor` does not provide any option for +resource assignment and two the `pymipool.SubprocessExecutor` returns the output of the command rather than just +returning the exit status when calling `result()`. + +### Interactive Shell +Beyond external executables which are called once with a set of input parameters and or input files and return one set +of outputs, there are some executables which allow the user to interact with the executable during the execution. The +challenge of interfacing a python process with such an interactive executable is to identify when the executable is ready +to receive the next input. A very basis example for an interactive executable is a script which counts to the number +input by the user. This can be written in python as `count.py`: +``` +def count(iterations): + for i in range(int(iterations)): + print(i) + print("done") + + +if __name__ == "__main__": + while True: + user_input = input() + if "shutdown" in user_input: + break + else: + count(iterations=int(user_input)) +``` +This example is challenging in terms of interfacing it with a python process as the length of the output changes depending +on the input. The first option that the `pympipool.ShellExecutor` provides is specifying the number of lines to read for +each call submitted to the executable using the `lines_to_read` parameter. In comparison to the `SubprocessExecutor` +defined above the `ShellExecutor` only supports the execution of a single executable at a time, correspondingly the input +parameters for calling the executable are provided at the time of initialization of the `ShellExecutor` and the inputs +are submitted using the `submit()` function: +``` +from pympipool import ShellExecutor + +with ShellExecutor(["python", "count.py"], universal_newlines=True) as exe: + future_lines = exe.submit(string_input="4", lines_to_read=5) + print(future_lines.done(), future_lines.result(), future_lines.done()) +>>> (False, "0\n1\n2\n3\ndone\n", True) +``` +The response for a given set of input is again returned as `concurrent.futures.Future` object, this allows the user to +execute other steps on the python side while waiting for the completion of the external executable. In this case the +example counts the numbers from `0` to `3` and prints each of them in one line followed by `done` to notify the user its +waiting for new inputs. This results in `n+1` lines of output for the input of `n`. Still predicting the number of lines +for a given input can be challenging, so the `pympipool.ShellExecutor` class also provides the option to wait until a +specific pattern is found in the output using the `stop_read_pattern`: +``` +from pympipool import ShellExecutor + +with ShellExecutor(["python", "count.py"], universal_newlines=True) as exe: + future_pattern = exe.submit(string_input="4", stop_read_pattern="done") + print(future_pattern.done(), future_pattern.result(), future_pattern.done()) +>>> (False, "0\n1\n2\n3\ndone\n", True) +``` +In this example the pattern simply searches for the string `done` in the output of the program and returns all the output +gathered from the executable since the last input as the result of the `concurrent.futures.Future` object returned after +the submission of the interactive command. \ No newline at end of file diff --git a/docs/source/index.rst b/docs/source/index.rst index da66dfac..d166a2f5 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -1,32 +1,127 @@ -.. pympipool documentation master file, created by - sphinx-quickstart on Sat Jun 10 11:15:31 2023. - You can adapt this file completely to your liking, but it should at least - contain the root `toctree` directive. +==================================================================== +pympipool - up-scale python functions for high performance computing +==================================================================== -pympipool - scale python functions over multiple compute nodes -============================================================== +:Author: Jan Janssen +:Contact: janssen@lanl.gov -Up-scaling python functions for high performance computing (HPC) can be challenging. While the python standard library provides interfaces for multiprocessing and asynchronous task execution, namely `multiprocessing `_ and `concurrent.futures `_ both are limited to the execution on a single compute node. So a series of python libraries have been developed to address the up-scaling of python functions for HPC. Starting in the datascience and machine learning community with solutions like `dask `_ over more HPC focused solutions like `parsl `_ up to Python bindings for the message passing interface (MPI) named `mpi4py `_. Each of these solutions has their advantages and disadvantages, in particular the mixing of MPI parallel python functions and serial python functions in combined workflows remains challenging. +Up-scaling python functions for high performance computing (HPC) can be challenging. While the python standard library +provides interfaces for multiprocessing and asynchronous task execution, namely +`multiprocessing `_ and +`concurrent.futures `_, both are +limited to the execution on a single compute node. So a series of python libraries have been developed to address the +up-scaling of python functions for HPC. Starting in the datascience and machine learning community with solutions +like `dask `_, over to more HPC-focused solutions like +`fireworks `_ and `parsl `_, up to Python +bindings for the message passing interface (MPI) named `mpi4py `_. Each of these +solutions has its advantages and disadvantages. However, one disadvantage common to all these libraries is the relative difficulty of scaling from serial functions to functions that make use of thread-based, MPI-based, or GPU-based parallelism. To address these challenges :code:`pympipool` is developed with three goals in mind: -* Reimplement the standard python library interfaces namely `multiprocessing.pool.Pool `_ and `concurrent.futures.Executor `_ as closely as possible, to minimize the barrier of up-scaling an existing workflow to be used on HPC resources. -* Integrate MPI parallel python functions based on `mpi4py `_ on the same level as serial python functions, so both can be combined in a single workflow. This allows the users to parallelize their workflows one function at a time. Internally this is achieved by coupling a serial python process to a MPI parallel python process. +* Extend the standard python library `concurrent.futures.Executor `_ interface, to minimize the barrier of up-scaling an existing workflow to be used on HPC resources. +* Integrate thread-based parallelism, MPI-parallel python functions based on `mpi4py `_, and GPU assignment. This allows users to accelerate their workflows one function at a time. * Embrace `Jupyter `_ notebooks for the interactive development of HPC workflows, as they allow the users to document their though process right next to the python code and their results all within one document. -Features +HPC Context +----------- +Frameworks like `dask `_, `fireworks `_ +and `parsl `_ can be used to submit a number of worker processes directly to the HPC +queuing system and then transfer tasks from either the login node or an interactive allocation to these worker processes +to accelerate the execution. By contrast, `mpi4py `_ and :code:`pympipool` follow a different +approach, in which the user creates their HPC allocation first and then `mpi4py `_ or +:code:`pympipool` can be used to distribute the tasks within this allocation. The advantage of this approach is that +no central data storage is required as the workers and the scheduling task can communicate directly. + +Examples -------- -As different users and different workflows have different requirements in terms of the level of parallelization, the -:code:`pympipool` implements a series of five different interfaces: +The following examples illustrates how :code:`pympipool` can be used to distribute a series of MPI parallel function +calls within a queuing system allocation. :code:`example.py`:: + + from pympipool import Executor + + def calc(i): + from mpi4py import MPI + size = MPI.COMM_WORLD.Get_size() + rank = MPI.COMM_WORLD.Get_rank() + return i, size, rank + + with Executor(max_workers=2, cores_per_worker=2) as exe: + fs_0 = exe.submit(calc, 0) + fs_1 = exe.submit(calc, 1) + print(fs_0.result(), fs_1.result()) + +This example can be executed using:: + + python example.py + +Which returns:: + + [(0, 2, 0), (0, 2, 1)], [(1, 2, 0), (1, 2, 1)] + +The important part in this example is that `mpi4py `_ is only used in the :code:`calc()` +function, not in the python script, consequently it is not necessary to call the script with :code:`mpiexec` but instead +a call with the regular python interpreter is sufficient. This highlights how :code:`pympipool` allows the users to +parallelize one function at a time and not having to convert their whole workflow to use `mpi4py `_. +The same code can also be executed inside a jupyter notebook directly which enables an interactive development process. + +The standard `concurrent.futures.Executor `_ +interface is extended by adding the option :code:`cores_per_worker=2` to assign multiple MPI ranks to each function call. +To create two workers :code:`max_workers=2` each with two cores each requires a total of four CPU cores to be available. + +After submitting the function :code:`calc()` with the corresponding parameter to the executor :code:`exe.submit(calc, 0)` +a python `concurrent.futures.Future `_ is +returned. Consequently, the :code:`pympipool.Executor` can be used as a drop-in replacement for the +`concurrent.futures.Executor `_ +which allows the user to add parallelism to their workflow one function at a time. + +Backends +-------- +Depending on the availability of different resource schedulers in your HPC environment the :code:`pympipool.Executor` +uses a different backend, with the :code:`pympipool.flux.PyFluxExecutor` being the preferred backend: + +* :code:`pympipool.mpi.PyMpiExecutor`: The simplest executor of the three uses `mpi4py `_ as a backend. This simplifies the installation on all operation systems including Windows. Still at the same time it limits the up-scaling to a single compute node and serial or MPI parallel python functions. There is no support for thread based parallelism or GPU assignment. This interface is primarily used for testing and developing or as a fall-back solution. It is not recommended to use this interface in production. +* :code:`pympipool.slurm.PySlurmExecutor`: The `SLURM workload manager `_ is commonly used on HPC systems to schedule and distribute tasks. :code:`pympipool` provides a python interface for scheduling the execution of python functions as SLURM job steps which are typically created using the :code:`srun` command. This executor supports serial python functions, thread based parallelism, MPI based parallelism and the assignment of GPUs to individual python functions. When the `SLURM workload manager `_ is installed on your HPC cluster this interface can be a reasonable choice, still depending on the SLURM configuration in can be limited in terms of the fine-grained scheduling or the responsiveness when working with hundreds of compute nodes in an individual allocation. +* :code:`pympipool.flux.PyFluxExecutor`: The `flux framework `_ is the preferred backend for :code:`pympipool`. Just like the :code:`pympipool.slurm.PySlurmExecutor` it supports serial python functions, thread based parallelism, MPI based parallelism and the assignment of GPUs to individual python functions. Still the advantages of using the `flux framework `_ as a backend are the easy installation, the faster allocation of resources as the resources are managed within the allocation and no central databases is used and the superior level of fine-grained resource assignment which is typically not available on HPC resource schedulers. + +Each of these backends consists of two parts a broker and a worker. When a new tasks is submitted from the user it is +received by the broker and the broker identifies the first available worker. The worker then executes a task and returns +it to the broker, who returns it to the user. While there is only one broker per :code:`pympipool.Executor` the number +of workers can be specified with the :code:`max_workers` parameter. + +Disclaimer +---------- +While we try to develop a stable and reliable software library, the development remains a opensource project under the +BSD 3-Clause License without any warranties:: + + BSD 3-Clause License + + Copyright (c) 2022, Jan Janssen + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. -* `pympipool.Pool `_: Following the `multiprocessing.pool.Pool `_ the :code:`pympipool.Pool` class implements the `map()` and `starmap()` functions. Internally these connect to an MPI parallel subprocess running the `mpi4py.futures.MPIPoolExecutor `_. So by increasing the number of workers, by setting the :code:`max_workers` parameter the :code:`pympipool.Pool` can scale the execution of serial python functions beyond a single compute node. For MPI parallel python functions the :code:`pympipool.MPISpawnPool` is derived from the :code:`pympipool.Pool` and uses :code:`MPI_Spawn()` to execute those. For more details see below. -* `pympipool.Executor `_: The easiest way to execute MPI parallel python functions right next to serial python functions is the :code:`pympipool.Executor`. It implements the executor interface defined by the `concurrent.futures.Executor `_. So functions are submitted to the :code:`pympipool.Executor` using the :code:`submit()` function, which returns an `concurrent.futures.Future `_ object. With these `concurrent.futures.Future `_ objects asynchronous workflows can be constructed which periodically check if the computation is completed `done()` and then query the results using the :code:`result()` function. The limitation of the :code:`pympipool.Executor` is lack of load balancing, each :code:`pympipool.Executor` acts as a serial first in first out (FIFO) queue. So it is the task of the user to balance the load of many different tasks over multiple :code:`pympipool.Executor` instances. -* `pympipool.HPCExecutor `_: To address the limitation of the :code:`pympipool.Executor` that only a single task is executed at any time, the :code:`pympipool.HPCExecutor` provides a wrapper around multiple :code:`pympipool.Executor` objects. It balances the queues of the individual :code:`pympipool.Executor` objects to maximize the throughput for the given resources. This functionality comes with an additional overhead of another thread, acting as a broker between the task queue of the :code:`pympipool.HPCExecutor` and the individual :code:`pympipool.Executor` objects. -* `pympipool.PoolExecutor `_: To combine the functionality of the :code:`pympipool.Pool` and the :code:`pympipool.Executor` the :code:`pympipool.PoolExecutor` again connects to the `mpi4py.futures.MPIPoolExecutor `_. Still in contrast to the :code:`pympipool.Pool` it does not implement the :code:`map()` and :code:`starmap()` functions but rather the :code:`submit()` function based on the `concurrent.futures.Executor `_ interface. In this case the load balancing happens internally and the maximum number of workers :code:`max_workers` defines the maximum number of parallel tasks. But only serial python tasks can be executed in contrast to the :code:`pympipool.Executor` which can also execute MPI parallel python tasks. -* `pympipool.MPISpawnPool `_: An alternative way to support MPI parallel functions in addition to the :code:`pympipool.Executor` is the :code:`pympipool.MPISpawnPool`. Just like the :code:`pympipool.Pool` it supports the :code:`map()` and :code:`starmap()` functions. The additional :code:`ranks_per_task` parameter defines how many MPI ranks are used per task. All functions are executed with the same number of MPI ranks. The limitation of this approach is that it uses :code:`MPI_Spawn()` to create new MPI ranks for the execution of the individual tasks. Consequently, this approach is not as scalable as the :code:`pympipool.Executor` but it offers load balancing for a large number of similar MPI parallel tasks. -* `pympipool.SocketInterface `_: The key functionality of the :code:`pympipool` package is the coupling of a serial python process with an MPI parallel python process. This happens in the background using a combination of the `zero message queue `_ and `cloudpickle `_ to communicate binary python objects. The :code:`pympipool.SocketInterface` is an abstraction of this interface, which is used in the other classes inside :code:`pympipool` and might also be helpful for other projects. + * Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. -In addition to using MPI to start a number of processes on different HPC computing resources, :code:`pympipool` also supports the `flux-framework `_ as additional backend. By setting the optional :code:`enable_flux_backend` parameter to :code:`True` the flux backend can be enabled for the :code:`pympipool.Pool`, :code:`pympipool.Executor` and :code:`pympipool.PoolExecutor`. Other optional parameters include the selection of the working directory where the python function should be executed :code:`cwd` and the option to oversubscribe MPI tasks which is an `OpenMPI `_ specific feature which can be enabled by setting :code:`oversubscribe` to :code:`True`. For more details on the :code:`pympipool` classes and their application, the extended documentation is linked below. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Documentation ------------- @@ -35,7 +130,7 @@ Documentation :maxdepth: 2 installation - interfaces + examples development -* :ref:`modindex` \ No newline at end of file +* :ref:`modindex` diff --git a/docs/source/installation.md b/docs/source/installation.md index e3d3f457..6a4c7680 100644 --- a/docs/source/installation.md +++ b/docs/source/installation.md @@ -1,18 +1,130 @@ # Installation -The `pympipool` package can be installed either via `pip` or `conda`. While most HPC systems use Linux these days, the `pympipool` package can be installed on all major operation systems. +For up-scaling python functions beyond a single compute node `pympipool` requires the integration with a high +performance computing (HPC) resource manager. These HPC resource manager are currently only supported for Linux. Still +for testing and development purposes the `pympipool` package can installed on all major operating systems including +Windows. -## pypi-based installation -`pympipool` can be installed from the python package index (pypi) using the following command: +This basic installation is based on the `pympipool.mpi.PyMPIExecutor` interface and allows up-scaling serial +and parallel python functions which use the message passing interface (MPI) for python [`mpi4py`](https://mpi4py.readthedocs.io) +on a single compute node. In addition, the integration with an HPC resource manager provides scaling beyond one compute +node, thread based parallelism and the assignment of GPUs. Still the user would not call the interface directly, but +rather use it through the `pympipool.Executor`. + +## Basic Installation +For testing and development purposes the `pympipool` package can installed on all major operating systems including +Windows. It is recommended to use the [conda package manager](https://anaconda.org/conda-forge/pympipool) for the +installation of the `pympipool` package. Still for advanced users who aim at maximizing their performance by compiling +their own version of `mpi` and `mpi4py` the `pympipool` package is also provided via the +[python package index (pypi)](https://pypi.org/project/pympipool/). + +### conda-based installation +In the same way `pympipool` can be installed with the [conda package manager](https://anaconda.org/conda-forge/pympipool): +``` +conda install -c conda-forge pympipool +``` +When resolving the dependencies with `conda` gets slow it is recommended to use `mamba` instead of `conda`. So you can +also install `pympipool` using: +``` +mamba install -c conda-forge pympipool +``` + +### pypi-based installation +`pympipool` can be installed from the [python package index (pypi)](https://pypi.org/project/pympipool/) using the +following command: ``` pip install pympipool ``` -## conda-based installation -The `conda` package combines all dependencies in one package: +## High Performance Computing +`pympipool` currently provides interfaces to the [SLURM workload manager](https://www.schedmd.com) and the +[flux framework](https://flux-framework.org). With the [flux framework](https://flux-framework.org) being the +recommended solution as it can be installed without root permissions and it can be integrated in existing resource +managers like the [SLURM workload manager](https://www.schedmd.com). The advantages of using `pympipool` in combination +with these resource schedulers is the fine-grained resource allocation. In addition to scaling beyond a single compute +node, they add the ability to assign GPUs and thread based parallelism. The two resource manager are internally linked to +two interfaces: + +* `pympipool.slurm.PySlurmExecutor`: The interface for the [SLURM workload manager](https://www.schedmd.com). +* `pympipool.flux.PyFluxExecutor`: The interface for the [flux framework](https://flux-framework.org). + +Still the user would not call these interfaces directly, but rather use it through the `pympipool.Executor`. + +### Flux Framework +For Linux users without a pre-installed resource scheduler in their high performance computing (HPC) environment, the +[flux framework](https://flux-framework.org) can be installed with the `conda` package manager: ``` -conda install -c conda-forge pympipool +conda install -c conda-forge flux-core ``` -When resolving the dependencies with `conda` gets slow it is recommended to use `mamba` instead of `conda`. So you can also install `pympipool` using: +For alternative ways to install the [flux framework](https://flux-framework.org) please refer to their official +[documentation](https://flux-framework.readthedocs.io/en/latest/quickstart.html). + +#### Nvidia +For adding GPU support in the [flux framework](https://flux-framework.org) you want to install `flux-sched` in addition +to `flux-core`. For Nvidia GPUs you need: ``` -mamba install -c conda-forge pympipool +conda install -c conda-forge flux-core flux-sched libhwloc=*=cuda* +``` +In case this fails because there is no GPU on the login node and the `cudatoolkit` cannot be installed you can use the +`CONDA_OVERRIDE_CUDA` environment variable to pretend a local cuda version is installed `conda` can link to using: +``` +CONDA_OVERRIDE_CUDA="11.6" conda install -c conda-forge flux-core flux-sched libhwloc=*=cuda* +``` + +#### AMD +For adding GPU support in the [flux framework](https://flux-framework.org) you want to install `flux-sched` in addition +to `flux-core`. For AMD GPUs you need: +``` +conda install -c conda-forge flux-core flux-sched +``` + +#### Test Flux +To test the [flux framework](https://flux-framework.org) and validate the GPUs are correctly recognized you can start +a flux instance using: +``` +flux start +``` +Afterwards, you can list the resources accessible to flux using: +``` +flux resource list +``` +This should contain a column for the GPUs if you installed the required dependencies. Here is an example output for a +workstation with a six core CPU and a single GPU: +``` + STATE NNODES NCORES NGPUS NODELIST + free 1 6 1 ljubi + allocated 0 0 0 + down 0 0 0 ``` +As the [flux framework](https://flux-framework.org) only lists physical cores rather than virtual cores enabled by +hyper-threading the total number of CPU cores might be half the number of cores you expect. + +When the [flux framework](https://flux-framework.org) is used inside an existing queuing system, then you have to +communicate these resources to it. For the [SLURM workload manager](https://www.schedmd.com) this is achieved by calling +`flux start` with `srun`. For an interactive session use: +``` +srun --pty flux start +``` +Alternatively, to execute a python script which uses `pympipool` you can call it with: +``` +srun flux start python +``` +In the same way to start a Jupyter Notebook in an interactive allocation you can use: +``` +srun --pty flux start jupyter notebook +``` +Then each jupyter notebook you execute on this jupyter notebook server has access to the resources of the interactive +allocation. + +### SLURM +The installation of the [SLURM workload manager](https://www.schedmd.com) is explained in the corresponding +[documentation](https://slurm.schedmd.com/quickstart_admin.html) . As it requires root access, it is not explained here. +Rather we assume you have access to an HPC cluster which already has SLURM installed. + +While the [SLURM workload manager](https://www.schedmd.com) and the [flux framework](https://flux-framework.org) are +both resource schedulers, the [flux framework](https://flux-framework.org) can also be installed on an HPC system which +uses the [SLURM workload manager](https://www.schedmd.com) as primary resource scheduler. This enables more fine-grained +scheduling like independent GPU access on HPC systems where [SLURM workload manager](https://www.schedmd.com) is +configured to allow only one job step per node. Furthermore, the [flux framework](https://flux-framework.org) provides +superior performance in large allocation with several hundred compute nodes or in the case when many `pympipool.slurm.PySlurmExecutor` +objects are created frequently, as each creation of an `pympipool.slurm.PySlurmExecutor` results in an `srun` call which is +communicated to the central database of the [SLURM workload manager](https://www.schedmd.com). diff --git a/docs/source/interfaces.md b/docs/source/interfaces.md deleted file mode 100644 index b07cccfe..00000000 --- a/docs/source/interfaces.md +++ /dev/null @@ -1,301 +0,0 @@ -# Interfaces -The `pympipool` class provides five different interfaces to scale python functions over multiple compute nodes. They are -briefly summarized here and explained in more detail below. - -| Feature | Pool | Executor | HPCExecutor | PoolExecutor | MPISpawnPool | -|:----------------------:|:----:|:--------:|:-----------:|:------------:|:------------:| -| `map()` | yes | yes | yes | yes | yes | -| `starmap()` | yes | no | no | no | yes | -| `submit()` | no | yes | yes | yes | no | -| parallel execution | yes | no | yes | yes | yes | -| MPI parallel functions | no | yes | yes | no | yes | -| flux framework support | yes | yes | yes | yes | no | -| internal storage | no | yes | yes | no | no | - -While all four interfaces implement the `map()` function, only two of them implement the `starmap()` function while the -rest implements the asynchronous `sumbit()` function which returns [`concurrent.futures.Future`](https://docs.python.org/3/library/concurrent.futures.html#future-objects). -In terms of the execution it is important to differentiate between parallel execution, meaning multiple individual -functions are executed in parallel and MPI parallel functions, which each require multiple MPI ranks to be executed. -Furthermore, most interfaces are integrated with the [flux-framework](https://flux-framework.org) and the -[SLURM queuing system](https://slurm.schedmd.com) so rather than using MPI ranks to distribute functions over multiple -compute nodes, they can also use the flux-framework or the SLURM queuing system for this purpose. Finally, the -`pympipool.Executor` and `pympipool.HPCExecutor` are currently the only interfaces which implements an internal storage, -so data can remain in the executor process while applying multiple functions which interact with this data. - -The sixth interface is the `SocketInterface`. This interface connects two python processes to transfer python objects -between them. It is used for all the above interfaces to connect the serial python process of the user interacts, with -the MPI parallel python process, which executes the python functions over multiple compute nodes. - -## Pool -Following the [`multiprocessing.pool.Pool`](https://docs.python.org/3/library/multiprocessing.html) -the `pympipool.Pool` class implements the `map()` and `starmap()` functions. Internally these connect to an MPI parallel -subprocess running the [`mpi4py.futures.MPIPoolExecutor`](https://mpi4py.readthedocs.io/en/stable/mpi4py.futures.html#mpipoolexecutor). -So by increasing the number of workers, by setting the `max_workers` parameter the `pympipool.Pool` can scale the -execution of serial python functions beyond a single compute node. For MPI parallel python functions the `pympipool.MPISpawnPool` -is derived from the `pympipool.Pool` and uses `MPI_Spawn()` to execute those. For more details see below. - -Example how to use the `pympipool.Pool` class. This can be executed inside a jupyter notebook, interactive python shell -or as a python script. For the example a python script is used. Write a python test script named `test_pool_map.py`: -```python -import numpy as np -from pympipool import Pool - -def calc(i): - return np.array(i ** 2) - -with Pool(max_workers=2) as p: - print(p.map(func=calc, iterable=[1, 2, 3, 4])) -``` -The function `calc()` is applied on the list of arguments `iterable`. The script is executed as serial python process, -while internally it uses MPI to execute two sets of two parameters at a time. As you see the `numpy` library is -dynamically included when the function is transferred to the MPI parallel subprocess for execution. To execute the -python file `test_pool.py` in a serial python process use: -``` -python test_pool_map.py ->>> [array(1), array(4), array(9), array(16)] -``` -Beyond the number of workers defined by `max_workers`, the additional parameters are `oversubscribe` to enable -[OpenMPI](https://www.open-mpi.org) over-subscription, `enable_flux_backend` and `enable_slurm_backend` to switch from -MPI as backend to flux or SLURM as alternative backend. In addition, the parameters `queue_adapter` and -`queue_adapter_kwargs` provide an interface to [pysqa](https://pysqa.readthedocs.org) the simple queue adapter for -python. The `queue_adapter` can be set as `pysqa.queueadapter.QueueAdapter` object and the `queue_adapter_kwargs` -parameter represents a dictionary of input arguments for the `submit_job()` function of the queue adapter. Finally, the -`cwd` parameter specifies the current working directory where the python functions are executed. - -In addition to the `map()` function, the `pympipool.Pool` interface implements the `starmap()` function. The example is -very similar to the one above. Just this time the `calc()` function accepts two arguments rather than one: -```python -from pympipool import Pool - -def calc(i, j): - return i + j - -with Pool(max_workers=2) as p: - print(p.starmap(func=calc, iterable=[[1, 2], [3, 4], [5, 6], [7, 8]])) -``` -The script named `test_pool_starmap.py` is executed and the sum of the input parameters is returned: -``` -python test_pool_starmap.py ->>> [3, 7, 11, 15] -``` -In summary the `pympipool.Pool` class implements both the `map()` function and the `starmap()` function to scale serial -python functions over multiple compute nodes. It internally handles the load distribution over multiple compute nodes. - -## Executor -The easiest way to execute MPI parallel python functions right next to serial python functions is the `pympipool.Executor`. -It implements the executor interface defined by the [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures). -So functions are submitted to the `pympipool.Executor` using the `submit()` function, which returns an -[`concurrent.futures.Future`](https://docs.python.org/3/library/concurrent.futures.html#future-objects) object. With -these [`concurrent.futures.Future`](https://docs.python.org/3/library/concurrent.futures.html#future-objects) objects -asynchronous workflows can be constructed which periodically check if the computation is completed `done()` and then query -the results using the `result()` function. The limitation of the `pympipool.Executor` is lack of load balancing, each -`pympipool.Executor` acts as a serial first in first out (FIFO) queue. So it is the task of the user to balance the load -of many different tasks over multiple `pympipool.Executor` instances. - -In comparison to the [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures) -in the standard python library the `pympipool.Executor` can execute MPI parallel python functions which internally use -the `mpi4py` library. In this example the `calc()` function returns the total number of MPI ranks and the index of the -individual MPI ranks. By setting the `cores` parameter of the `pympipool.Executor` to `2` the `calc()` function is -executed with two MPI ranks. -```python -from pympipool import Executor - -def calc(i): - from mpi4py import MPI - size = MPI.COMM_WORLD.Get_size() - rank = MPI.COMM_WORLD.Get_rank() - return i, size, rank - -with Executor(cores=2) as p: - fs = p.submit(calc, 3) - print(fs.result()) -``` -The important part is that in contrast to the `mpi4py` library the scripts which use the `pympipool.Executor` class can -be executed as serial python scripts, without the need to invoke external MPI calls. -``` -python test_executor_mpi.py ->>> [(3, 2, 0), (3, 2, 1)] -``` -The responses of the individual MPI ranks are returned as a combined python list. So in this case each MPI rank returns -a triple of the parameter `i=3`, the total number of MPI ranks `2` and the index of the selected MPI rank. - -In addition to the ability to execute MPI parallel functions the `pympipool.Executor` class also implements an internal -data storage, which can be utilized for serial and MPI parallel python functions. By adding an initialization function -`init_function` as additional parameter to the initialization of the `pympipool.Executor` class which returns a dictionary -of python variables, these variables are added to the internal storage. Each function which is submitted to this -`pympipool.Executor` class can use these variables as input parameters, interact with them or modify them. -```python -from pympipool import Executor - -def calc(i, j, k): - return i + j + k - -def init_function(): - return {"j": 4, "k": 3, "l": 2} - -with Executor(cores=1, init_function=init_function) as p: - fs = p.submit(calc, 2, j=5) - print(fs.result()) -``` -In this example the `calc()` function takes three arguments `i`,`j` and `k`. While the arguments `j`, `k` and `l` are -set by the `init_function()` function. When the `calc()` function is submitted only the `i` parameter is required, while -the parameters `j` and `k` can be accessed from the internal storage. At the same time the `l` parameter which is not -used by the `calc()` function, does not interact with it. So not all functions have to use all parameters. Finally, -when the parameter is provided during the submission `submit()`, like in this case the `j` parameter, then the submitted -parameter is used rather than the parameter from internal memory. -``` -python test_executor_init.py ->>> 10 -``` -So the sum of `i`,`j` and `k` results in `10` rather than `9`. Beyond the number of cores defined by `cores`, the number -of GPUs defined by `gpus_per_task` and the initialization function defined by `init_function` the additional parameters -are `oversubscribe` to enable [OpenMPI](https://www.open-mpi.org) over-subscription, `enable_flux_backend` and -`enable_slurm_backend` to switch from MPI as backend to flux or SLURM as alternative backend. In addition, the -parameters `queue_adapter` and `queue_adapter_kwargs` provide an interface to [pysqa](https://pysqa.readthedocs.org) the -simple queue adapter for python. The `queue_adapter` can be set as `pysqa.queueadapter.QueueAdapter` object and the -`queue_adapter_kwargs` parameter represents a dictionary of input arguments for the `submit_job()` function of the queue -adapter. Finally, the `cwd` parameter specifies the current working directory where the python functions are executed. - -When multiple functions are submitted to the `pympipool.Executor` class then they are executed following the first in -first out principle. The `len()` function applied on the `pympipool.Executor` object can be used to list how many items -are still waiting to be executed. - -## HPCExecutor -To address the limitation of the `pympipool.Executor` that only a single task is executed at any time, the -`pympipool.HPCExecutor` provides a wrapper around multiple `pympipool.Executor` objects. It balances the queues of the -individual `pympipool.Executor` objects to maximize the throughput for the given resources. This functionality comes -with an additional overhead of another thread, acting as a broker between the task queue of the `pympipool.HPCExecutor` -and the individual `pympipool.Executor` objects. - -Example how to use the `pympipool.HPCExecutor` class. This can be executed inside a jupyter notebook, interactive python -shell or as a python script. For the example a python script is used. Write a python test script named `test_hpc_gpu.py`: -``` -import socket -from pympipool import HPCExecutor -from tensorflow.python.client import device_lib - -def get_available_gpus(): - local_device_protos = device_lib.list_local_devices() - return [ - (x.name, x.physical_device_desc, socket.gethostname()) - for x in local_device_protos if x.device_type == 'GPU' - ] - -with HPCExecutor( - max_workers=2, - cores_per_worker=1, - gpus_per_worker=1, - enable_flux_backend=True, -) as exe: - fs_1 = exe.submit(get_available_gpus) - fs_2 = exe.submit(get_available_gpus) - -print(fs_1.result()) -print(fs_2.result()) -``` -The example demonstrates how one GPU is assigned to each of the two tasks which are executed in parallel. To access the -GPUs the `tensorflow` package is used in the `get_available_gpus()` function to return a brief summary of the available -GPU. The initialization of the `pympipool.HPCExecutor` then follows the same scheme as the initialization of the -`pympipool.Executor`. The `max_workers` argument defines the number of `pympipool.Executor` objects the -`pympipool.HPCExecutor` is managing internally. Then for each of these `pympipool.Executor` objects the number of cores -is defined by `cores_per_worker` and the number of GPUs is defined by `gpus_per_worker`. By default the number of GPUs -is set to zero, as assigning GPUs to tasks requires an advanced scheduling backend like the flux-framework enabled by -the `enable_flux_backend` option or the SLURM queuing system backend enabled by the `enable_slurm_backend` option. In -addition, the parameters `queue_adapter` and `queue_adapter_kwargs` provide an interface to -[pysqa](https://pysqa.readthedocs.org) the simple queue adapter for python. The `queue_adapter` can be set as -`pysqa.queueadapter.QueueAdapter` object and the `queue_adapter_kwargs` parameter represents a dictionary of input -arguments for the `submit_job()` function of the queue adapter. Finally, the `cwd` parameter specifies the current -working directory where the python functions are executed. - -The submission of the individual tasks follows the definition of the `pympipool.HPCExecutor` in analogy to the example -above for the `pympipool.Executor`. Finally, the results are printed to the standard output: -``` -python test_hpc_gpu.py ->>> [('/device:GPU:0', 'device: 0, name: Tesla V100S-PCIE-32GB, pci bus id: 0000:84:00.0, compute capability: 7.0', 'cn138')] ->>> [('/device:GPU:0', 'device: 0, name: Tesla V100S-PCIE-32GB, pci bus id: 0000:84:00.0, compute capability: 7.0', 'cn139')] -``` -The output highlights that for each of the two workers there is only a single GPU visible. This applies to the example -case where only one GPU is available on each of the two hosts, as well as to hosts with multiple GPUs. Consequently, -the `pympipool.HPCExecutor` drastically simplifies the scheduling of `GPU` and their assignment for python tasks. - -## PoolExecutor -To combine the functionality of the `pympipool.Pool` and the `pympipool.Executor` the `pympipool.PoolExecutor` again -connects to the [`mpi4py.futures.MPIPoolExecutor`](https://mpi4py.readthedocs.io/en/stable/mpi4py.futures.html#mpipoolexecutor). -Still in contrast to the `pympipool.Pool` it does not implement the `map()` and `starmap()` functions but rather the -`submit()` function based on the [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures) -interface. In this case the load balancing happens internally and the maximum number of workers `max_workers` defines -the maximum number of parallel tasks. But only serial python tasks can be executed in contrast to the `pympipool.Executor` -which can also execute MPI parallel python tasks. - -In the example a simple `calc()` function which calculates the sum of two parameters `i` and `j` is submitted with four -different parameter combinations to an `pympipool.PoolExecutor` with a total of two workers specified by the `max_workers` -parameter. -```python -from pympipool import PoolExecutor - -def calc(i, j): - return i + j - -with PoolExecutor(max_workers=2) as p: - fs1 = p.submit(calc, 1, 2) - fs2 = p.submit(calc, 3, 4) - fs3 = p.submit(calc, 5, 6) - fs4 = p.submit(calc, 7, 8) - print(fs1.result(), fs2.result(), fs3.result(), fs4.result()) -``` -The functions are executed in two sets of two function and the result is returned when all functions are executed as the -`result()` call waits until the future object completed. -``` -python test_pool_executor.py ->>> 3 7 11 15 -``` -Beyond the number of workers defined by `max_workers`, the additional parameters are `oversubscribe` to enable -[OpenMPI](https://www.open-mpi.org) over-subscription, `enable_flux_backend` and `enable_slurm_backend` to switch from -MPI as backend to flux or SLURM as alternative backend. In addition, the parameters `queue_adapter` and -`queue_adapter_kwargs` provide an interface to [pysqa](https://pysqa.readthedocs.org) the simple queue adapter for -python. The `queue_adapter` can be set as `pysqa.queueadapter.QueueAdapter` object and the `queue_adapter_kwargs` -parameter represents a dictionary of input arguments for the `submit_job()` function of the queue adapter. Finally, the -`cwd` parameter specifies the current working directory where the python functions are executed. - -## MPISpawnPool -An alternative way to support MPI parallel functions in addition to the `pympipool.Executor` is the `pympipool.MPISpawnPool`. -Just like the `pympipool.Pool` it supports the `map()` and `starmap()` functions. The additional `ranks_per_task` -parameter defines how many MPI ranks are used per task. All functions are executed with the same number of MPI ranks. -The limitation of this approach is that it uses `MPI_Spawn()` to create new MPI ranks for the execution of the -individual tasks. Consequently, this approach is not as scalable as the `pympipool.Executor` but it offers load -balancing for a large number of similar MPI parallel tasks. - -In the example the maximum number of workers is defined by the maximum number of MPI ranks `max_ranks` devided by the -number of ranks per task `ranks_per_tasks`. So in the case of a total of four ranks and two ranks per task only two -workers are created. -```python -from pympipool import MPISpawnPool - -def calc(i, comm): - return i, comm.Get_size(), comm.Get_rank() - -with MPISpawnPool(max_ranks=4, ranks_per_task=2) as p: - print(p.map(func=calc, iterable=[1, 2, 3, 4])) -``` -In contrast to the `pympipool.Executor` which returns the results of each individual MPI rank, the `pympipool.MPISpawnPool` -only returns the results of one MPI rank per function call, so it is the users task to synchronize the response of the -MPI parallel functions. -``` -python test_mpispawnpool.py ->>> [[1, 2, 0], [2, 2, 0], [3, 2, 0], [4, 2, 0]] -``` -Beyond the maximum number of ranks defined by `max_ranks` and the ranks per task defined by `ranks_per_task` the -additional parameters are `oversubscribe` to enable [OpenMPI](https://www.open-mpi.org) over-subscription. In addition, -the parameters `queue_adapter` and `queue_adapter_kwargs` provide an interface to [pysqa](https://pysqa.readthedocs.org) -the simple queue adapter for python. The `queue_adapter` can be set as `pysqa.queueadapter.QueueAdapter` object and the -`queue_adapter_kwargs` parameter represents a dictionary of input arguments for the `submit_job()` function of the queue -adapter. Finally, the `cwd` parameter specifies the current working directory where the MPI parallel python functions -are executed. The flux backend as well as the SLURM backend are not supported for the `pympipool.MPISpawnPool` as the -`MPI_Spawn()` command is incompatible to the internal management of ranks inside flux and SLURM. - -## SocketInterface -`pympipool.SocketInterface`: The key functionality of the `pympipool` package is the coupling of a serial python process -with an MPI parallel python process. This happens in the background using a combination of the [zero message queue](https://zeromq.org) -and [cloudpickle](https://github.com/cloudpipe/cloudpickle) to communicate binary python objects. The `pympipool.SocketInterface` -is an abstraction of this interface, which is used in the other classes inside `pympipool` and might also be helpful for -other projects. \ No newline at end of file diff --git a/notebooks/examples.ipynb b/notebooks/examples.ipynb new file mode 100644 index 00000000..c91b48a2 --- /dev/null +++ b/notebooks/examples.ipynb @@ -0,0 +1,849 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "19bad499-5a97-425c-beec-dcd88d693d4c", + "metadata": {}, + "source": [ + "# Examples\n", + "The `pympipool.Executor` extends the interface of the [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures)\n", + "to simplify the up-scaling of individual functions in a given workflow." + ] + }, + { + "cell_type": "markdown", + "id": "f752ec8d-50b8-46fb-86f2-08a9126f1a39", + "metadata": {}, + "source": [ + "## Compatibility\n", + "Starting with the basic example of `1+1=2`. With the `ThreadPoolExecutor` from the [`concurrent.futures`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures)\n", + "standard library this can be written as: " + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "584cd590-acaf-48d7-a5b5-e4049a9626b7", + "metadata": {}, + "outputs": [], + "source": [ + "from concurrent.futures import ThreadPoolExecutor" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "73673e42-2c68-4b91-b6ff-db1ecb2c0587", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2\n" + ] + } + ], + "source": [ + "with ThreadPoolExecutor(\n", + " max_workers=1,\n", + ") as exe:\n", + " future = exe.submit(sum, [1, 1])\n", + " print(future.result())" + ] + }, + { + "cell_type": "markdown", + "id": "32156314-02a9-4210-8a8c-94afe09b64f6", + "metadata": {}, + "source": [ + "In this case `max_workers=1` limits the number of threads uses by the `ThreadPoolExecutor` to one. Then the `sum()` \n", + "function is submitted to the executor with a list with two ones `[1, 1]` as input. A [`concurrent.futures.Future`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures)\n", + "object is returned. The `Future` object allows to check the status of the execution with the `done()` method which \n", + "returns `True` or `False` depending on the state of the execution. Or the main process can wait until the execution is \n", + "completed by calling `result()`. " + ] + }, + { + "cell_type": "markdown", + "id": "b750d830-bd0d-4474-9f70-913d0b9d6b8a", + "metadata": {}, + "source": [ + "The result of the calculation is `1+1=2`. " + ] + }, + { + "cell_type": "markdown", + "id": "4fbf72a2-0e0e-43ce-be8f-db3489c4eafe", + "metadata": {}, + "source": [ + "The `pympipool.Executor` class extends the interface of the [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures) \n", + "class by providing more parameters to specify the level of parallelism. In addition, to specifying the maximum number \n", + "of workers `max_workers` the user can also specify the number of cores per worker `cores_per_worker` for MPI based \n", + "parallelism, the number of threads per core `threads_per_core` for thread based parallelism and the number of GPUs per\n", + "worker `gpus_per_worker`. Finally, for those backends which support over-subscribing this can also be enabled using the \n", + "`oversubscribe` parameter. All these parameters are optional, so the `pympipool.Executor` can be used as a drop-in \n", + "replacement for the [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures)." + ] + }, + { + "cell_type": "markdown", + "id": "9b5a26e2-3d18-4778-ba10-e3e213b70433", + "metadata": {}, + "source": [ + "The previous example is rewritten for the `pympipool.Executor`:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "60373c38-63f8-48dc-be0f-ddb71ebf88f8", + "metadata": {}, + "outputs": [], + "source": [ + "from pympipool import Executor " + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "fd755b28-ff01-4530-9099-001cac151e31", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2\n" + ] + } + ], + "source": [ + "with Executor(\n", + " max_workers=1, \n", + " cores_per_worker=1, \n", + " threads_per_core=1, \n", + " gpus_per_worker=0, \n", + " oversubscribe=False\n", + ") as exe:\n", + " future = exe.submit(sum, [1,1])\n", + " print(future.result())" + ] + }, + { + "cell_type": "markdown", + "id": "44c4bc4b-cf97-461e-98e7-62bcdb8caff2", + "metadata": {}, + "source": [ + "The result of the calculation is again `1+1=2`." + ] + }, + { + "cell_type": "markdown", + "id": "331aed93-806a-4057-ab9c-19479190f472", + "metadata": {}, + "source": [ + "Beyond pre-defined functions like the `sum()` function, the same functionality can be used to submit user-defined \n", + "functions. In the following example a custom summation function is defined: " + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "cdeb8710-b328-463d-a436-82d6756e76b3", + "metadata": {}, + "outputs": [], + "source": [ + "def calc(*args):\n", + " return sum(*args)" + ] + }, + { + "cell_type": "markdown", + "id": "d5efa995-d4d4-4f9c-a7e6-38dd66143535", + "metadata": {}, + "source": [ + "In contrast to the previous example where just a single function was submitted to a single worker, in this case a total\n", + "of four functions is submitted to a group of two workers `max_workers=2`. Consequently, the functions are executed as a\n", + "set of two pairs. " + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "82033832-7ccd-4c67-a1fb-57f55710b77c", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[3, 4, 5, 6]\n" + ] + } + ], + "source": [ + "with Executor(max_workers=2) as exe:\n", + " fs_1 = exe.submit(calc, [2, 1])\n", + " fs_2 = exe.submit(calc, [2, 2])\n", + " fs_3 = exe.submit(calc, [2, 3])\n", + " fs_4 = exe.submit(calc, [2, 4])\n", + " print([\n", + " fs_1.result(), \n", + " fs_2.result(), \n", + " fs_3.result(), \n", + " fs_4.result(),\n", + " ])" + ] + }, + { + "cell_type": "markdown", + "id": "86838528-312e-46cc-b022-0c946bf95037", + "metadata": {}, + "source": [ + "The snippet can be executed with any python interpreter. It returns the corresponding sums as expected. The same can be achieved with the built-in [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures)\n", + "classes. Still one advantage of using the `pympipool.Executor` rather than the built-in ones, is the ability to execute \n", + "the same commands in interactive environments like [Jupyter notebooks](https://jupyter.org). This is achieved by using \n", + "[cloudpickle](https://github.com/cloudpipe/cloudpickle) to serialize the python function and its parameters rather than\n", + "the regular pickle package. " + ] + }, + { + "cell_type": "markdown", + "id": "4de690ed-661c-4e6e-a97e-c478393d0dc6", + "metadata": {}, + "source": [ + "For backwards compatibility with the [`multiprocessing.Pool`](https://docs.python.org/3/library/multiprocessing.html) \n", + "class the [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures)\n", + "also implements the `map()` function to map a series of inputs to a function. The same `map()` function is also \n", + "available in the `pympipool.Executor`: " + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "3f06b0c1-5ee1-40c5-82ab-31d77cfcdb46", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[3, 4, 5, 6]\n" + ] + } + ], + "source": [ + "with Executor(max_workers=2) as exe:\n", + " print(list(exe.map(calc, [[2, 1], [2, 2], [2, 3], [2, 4]])))" + ] + }, + { + "cell_type": "markdown", + "id": "a5d0f249-23bb-4727-8b09-87320ecb98eb", + "metadata": {}, + "source": [ + "The results remain the same. " + ] + }, + { + "cell_type": "markdown", + "id": "580b00ee-6d5b-4ca9-ba36-ff70128c0b6b", + "metadata": {}, + "source": [ + "## Data Handling\n", + "A limitation of many parallel approaches is the overhead in communication when working with large datasets. Instead of\n", + "reading the same dataset repetitively, the `pympipool.Executor` loads the dataset only once per worker and afterwards \n", + "each function submitted to this worker has access to the dataset, as it is already loaded in memory. To achieve this\n", + "the user defines an initialization function `init_function` which returns a dictionary with one key per dataset. The \n", + "keys of the dictionary can then be used as additional input parameters in each function submitted to the `pympipool.Executor`.\n", + "This functionality is illustrated in the following example: " + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "8fe8c750-4dc5-4b26-ad8d-9f755bff3494", + "metadata": {}, + "outputs": [], + "source": [ + "def calc(i, j, k):\n", + " return i + j + k" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "5f943266-1bee-421e-a1b4-583d222b1c99", + "metadata": {}, + "outputs": [], + "source": [ + "def init_function():\n", + " return {\"j\": 4, \"k\": 3, \"l\": 2}" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "0debe907-b646-4fd5-bae7-46b16645d2f3", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "10\n" + ] + } + ], + "source": [ + "with Executor(max_workers=1, init_function=init_function) as exe:\n", + " fs = exe.submit(calc, 2, j=5)\n", + " print(fs.result())" + ] + }, + { + "cell_type": "markdown", + "id": "72fa803a-ace0-41ea-8090-d64dfd0797cc", + "metadata": {}, + "source": [ + "The function `calc()` requires three inputs `i`, `j` and `k`. But when the function is submitted to the executor only \n", + "two inputs are provided `fs = exe.submit(calc, 2, j=5)`. In this case the first input parameter is mapped to `i=2`, the\n", + "second input parameter is specified explicitly `j=5` but the third input parameter `k` is not provided. So the \n", + "`pympipool.Executor` automatically checks the keys set in the `init_function()` function. In this case the returned \n", + "dictionary `{\"j\": 4, \"k\": 3, \"l\": 2}` defines `j=4`, `k=3` and `l=2`. For this specific call of the `calc()` function,\n", + "`i` and `j` are already provided so `j` is not required, but `k=3` is used from the `init_function()` and as the `calc()`\n", + "function does not define the `l` parameter this one is also ignored. " + ] + }, + { + "cell_type": "markdown", + "id": "1443d216-1add-445a-a662-5b16af6c1443", + "metadata": {}, + "source": [ + "The result is `2+5+3=10` as `i=2` and `j=5` are provided during the submission and `k=3` is defined in the `init_function()`\n", + "function." + ] + }, + { + "cell_type": "markdown", + "id": "8d1e21ec-0b8d-45bf-bfb1-62b3df8e242a", + "metadata": {}, + "source": [ + "## Up-Scaling \n", + "The availability of certain features depends on the backend `pympipool` is installed with. In particular the thread \n", + "based parallelism and the GPU assignment is only available with the `pympipool.slurm.PySlurmExecutor` or the \n", + "`pympipool.flux.PyFluxExecutor` backend. The latter is recommended based on the easy installation, the faster allocation \n", + "of resources as the resources are managed within the allocation and no central databases is used and the superior level \n", + "of fine-grained resource assignment which is typically not available on other HPC resource schedulers including the\n", + "[SLURM workload manager](https://www.schedmd.com). The `pympipool.flux.PyFluxExecutor` requires \n", + "[flux framework](https://flux-framework.org) to be installed in addition to the `pympipool` package. The features are \n", + "summarized in the table below: \n", + "\n", + "| Feature \\ Backend | `PyMpiExecutor` | `PySlurmExecutor` | `PyFluxExecutor` |\n", + "|:--------------------------:|:---------------:|:-----------------:|:----------------:|\n", + "| Thread based parallelism | no | yes | yes | \n", + "| MPI based parallelism | yes | yes | yes |\n", + "| GPU assignment | no | yes | yes |\n", + "| Resource over-subscription | yes | yes | no |\n", + "| Scalability | 1 node | ~100 nodes | no limit |" + ] + }, + { + "cell_type": "markdown", + "id": "f3b9cc80-70ed-4bc8-abf9-62ecbd70b960", + "metadata": {}, + "source": [ + "### Thread-based Parallelism\n", + "The number of threads per core can be controlled with the `threads_per_core` parameter during the initialization of the \n", + "`pympipool.Executor`. Unfortunately, there is no uniform way to control the number of cores a given underlying library \n", + "uses for thread based parallelism, so it might be necessary to set certain environment variables manually: \n", + "\n", + "* `OMP_NUM_THREADS`: for openmp\n", + "* `OPENBLAS_NUM_THREADS`: for openblas\n", + "* `MKL_NUM_THREADS`: for mkl\n", + "* `VECLIB_MAXIMUM_THREADS`: for accelerate on Mac Os X\n", + "* `NUMEXPR_NUM_THREADS`: for numexpr\n", + "\n", + "At the current stage `pympipool.Executor` does not set these parameters itself, so you have to add them in the function\n", + "you submit before importing the corresponding library: " + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "fbf5f7b2-eb3e-4a81-bae8-e429747300a0", + "metadata": {}, + "outputs": [], + "source": [ + "def calc(i):\n", + " import os\n", + " os.environ[\"OMP_NUM_THREADS\"] = \"2\"\n", + " os.environ[\"OPENBLAS_NUM_THREADS\"] = \"2\"\n", + " os.environ[\"MKL_NUM_THREADS\"] = \"2\"\n", + " os.environ[\"VECLIB_MAXIMUM_THREADS\"] = \"2\"\n", + " os.environ[\"NUMEXPR_NUM_THREADS\"] = \"2\"\n", + " import numpy as np\n", + " return i" + ] + }, + { + "cell_type": "markdown", + "id": "334619d0-8d95-419e-885c-e5bc05747584", + "metadata": {}, + "source": [ + "Most modern CPUs use hyper-threading to present the operating system with double the number of virtual cores compared to\n", + "the number of physical cores available. So unless this functionality is disabled `threads_per_core=2` is a reasonable \n", + "default. Just be careful if the number of threads is not specified it is possible that all workers try to access all \n", + "cores at the same time which can lead to poor performance. So it is typically a good idea to monitor the CPU utilization\n", + "with increasing number of workers. " + ] + }, + { + "cell_type": "markdown", + "id": "7c3146c1-8722-4b67-ab21-c250b8e7c9dd", + "metadata": {}, + "source": [ + "Specific manycore CPU models like the Intel Xeon Phi processors provide a much higher hyper-threading ration and require\n", + "a higher number of threads per core for optimal performance. " + ] + }, + { + "cell_type": "markdown", + "id": "b4976d45-0f4e-496c-8173-9631f512135b", + "metadata": {}, + "source": [ + "### MPI Parallel Python Functions\n", + "Beyond thread based parallelism, the message passing interface (MPI) is the de facto standard parallel execution in \n", + "scientific computing and the [`mpi4py`](https://mpi4py.readthedocs.io) bindings to the MPI libraries are commonly used\n", + "to parallelize existing workflows. The limitation of this approach is that it requires the whole code to adopt the MPI\n", + "communication standards to coordinate the way how information is distributed. Just like the `pympipool.Executor` the \n", + "[`mpi4py.futures.MPIPoolExecutor`](https://mpi4py.readthedocs.io/en/stable/mpi4py.futures.html#mpipoolexecutor) \n", + "implements the [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#module-concurrent.futures)\n", + "interface. Still in this case eah python function submitted to the executor is still limited to serial execution. The\n", + "novel approach of the `pympipool.Executor` is mixing these two types of parallelism. Individual functions can use\n", + "the [`mpi4py`](https://mpi4py.readthedocs.io) library to handle the parallel execution within the context of this \n", + "function while these functions can still me submitted to the `pympipool.Executor` just like any other function. The\n", + "advantage of this approach is that the users can parallelize their workflows one function at the time. \n", + "\n", + "The following example illustrates the submission of a simple MPI parallel python function: " + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "cfa072a4-f88f-45b0-be94-a78f0edad513", + "metadata": {}, + "outputs": [], + "source": [ + "def calc(i):\n", + " from mpi4py import MPI\n", + " size = MPI.COMM_WORLD.Get_size()\n", + " rank = MPI.COMM_WORLD.Get_rank()\n", + " return i, size, rank" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "fd036b03-085d-4850-b11e-537c8fd476d5", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[(3, 2, 0), (3, 2, 1)]\n" + ] + } + ], + "source": [ + "with Executor(cores_per_worker=2) as exe:\n", + " fs = exe.submit(calc, 3)\n", + " print(fs.result())" + ] + }, + { + "cell_type": "markdown", + "id": "b4f97426-d8fb-42ef-98ca-135054bd39a7", + "metadata": {}, + "source": [ + "The `calc()` function initializes the [`mpi4py`](https://mpi4py.readthedocs.io) library and gathers the size of the \n", + "allocation and the rank of the current process within the MPI allocation. This function is then submitted to an \n", + "`pympipool.Executor` which is initialized with a single worker with two cores `cores_per_worker=2`. So each function\n", + "call is going to have access to two cores. \n", + "\n", + "Just like before the script can be called with any python interpreter even though it is using the [`mpi4py`](https://mpi4py.readthedocs.io)\n", + "library in the background it is not necessary to execute the script with `mpiexec` or `mpirun`." + ] + }, + { + "cell_type": "markdown", + "id": "69dcfdcb-41db-4c3b-a1c5-07ff3be0c9a0", + "metadata": {}, + "source": [ + "The response consists of a list of two tuples, one for each MPI parallel process, with the first entry of the tuple \n", + "being the parameter `i=3`, followed by the number of MPI parallel processes assigned to the function call `cores_per_worker=2`\n", + "and finally the index of the specific process `0` or `1`. " + ] + }, + { + "cell_type": "markdown", + "id": "dc41f241-663c-474e-ae1e-b2365389bc90", + "metadata": {}, + "source": [ + "### GPU Assignment\n", + "With the rise of machine learning applications, the use of GPUs for scientific application becomes more and more popular.\n", + "Consequently, it is essential to have full control over the assignment of GPUs to specific python functions. In the \n", + "following example the `tensorflow` library is used to identify the GPUs and return their configuration: " + ] + }, + { + "cell_type": "raw", + "id": "6ac9630b-4ab5-4f7f-bf55-812e8189da4f", + "metadata": {}, + "source": [ + "import socket\n", + "from tensorflow.python.client import device_lib" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "998138f5-f0cb-47a7-ba36-7594b8ec41fc", + "metadata": {}, + "outputs": [], + "source": [ + "def get_available_gpus():\n", + " local_device_protos = device_lib.list_local_devices()\n", + " return [\n", + " (x.name, x.physical_device_desc, socket.gethostname()) \n", + " for x in local_device_protos if x.device_type == 'GPU'\n", + " ]" + ] + }, + { + "cell_type": "raw", + "id": "9d33af22-7b90-4ff7-a434-9c4cd9a930d5", + "metadata": {}, + "source": [ + "with Executor(\n", + " max_workers=2, \n", + " gpus_per_worker=1, \n", + ") as exe:\n", + " fs_1 = exe.submit(get_available_gpus)\n", + " fs_2 = exe.submit(get_available_gpus)\n", + " print(fs_1.result(), fs_2.result())" + ] + }, + { + "cell_type": "markdown", + "id": "8dc7a989-908a-48a6-8d06-ac1e24173f5c", + "metadata": {}, + "source": [ + "The additional parameter `gpus_per_worker=1` specifies that one GPU is assigned to each worker. This functionality \n", + "requires `pympipool` to be connected to a resource manager like the [SLURM workload manager](https://www.schedmd.com)\n", + "or preferably the [flux framework](https://flux-framework.org). The rest of the script follows the previous examples, \n", + "as two functions are submitted and the results are printed. " + ] + }, + { + "cell_type": "markdown", + "id": "d1a17c6c-41ee-4595-913e-4af7272010a5", + "metadata": {}, + "source": [ + "To clarify the execution of such an example on a high performance computing (HPC) cluster using the [SLURM workload manager](https://www.schedmd.com)\n", + "the submission script is given below: " + ] + }, + { + "cell_type": "raw", + "id": "11ce332b-d2c1-4434-84c4-1e523e430848", + "metadata": {}, + "source": [ + "#!/bin/bash\n", + "#SBATCH --nodes=2\n", + "#SBATCH --gpus-per-node=1\n", + "#SBATCH --get-user-env=L\n", + "\n", + "python test_gpu.py" + ] + }, + { + "cell_type": "markdown", + "id": "14bf6228-db64-406b-b04f-4d23daaa836d", + "metadata": {}, + "source": [ + "The important part is that for using the `pympipool.slurm.PySlurmExecutor` backend the script `test_gpu.py` does not \n", + "need to be executed with `srun` but rather it is sufficient to just execute it with the python interpreter. `pympipool`\n", + "internally calls `srun` to assign the individual resources to a given worker. " + ] + }, + { + "cell_type": "markdown", + "id": "66e3be02-c11c-4053-9600-6bcfefefb127", + "metadata": {}, + "source": [ + "For the more complex setup of running the [flux framework](https://flux-framework.org) as a secondary resource scheduler\n", + "within the [SLURM workload manager](https://www.schedmd.com) it is essential that the resources are passed from the \n", + "[SLURM workload manager](https://www.schedmd.com) to the [flux framework](https://flux-framework.org). This is achieved\n", + "by calling `srun flux start` in the submission script: " + ] + }, + { + "cell_type": "raw", + "id": "aa0e2abf-7ab2-464f-a341-b93f91fbdd99", + "metadata": {}, + "source": [ + "#!/bin/bash\n", + "#SBATCH --nodes=2\n", + "#SBATCH --gpus-per-node=1\n", + "#SBATCH --get-user-env=L\n", + "\n", + "srun flux start python test_gpu.py" + ] + }, + { + "cell_type": "markdown", + "id": "6c84fb7d-4285-4d73-8f1e-7cb88050eb85", + "metadata": {}, + "source": [ + "As a result the GPUs available on the two compute nodes are reported: " + ] + }, + { + "cell_type": "raw", + "id": "a431e015-a309-49ac-9f10-756bda0177fc", + "metadata": {}, + "source": [ + ">>> [('/device:GPU:0', 'device: 0, name: Tesla V100S-PCIE-32GB, pci bus id: 0000:84:00.0, compute capability: 7.0', 'cn138'),\n", + ">>> ('/device:GPU:0', 'device: 0, name: Tesla V100S-PCIE-32GB, pci bus id: 0000:84:00.0, compute capability: 7.0', 'cn139')]" + ] + }, + { + "cell_type": "markdown", + "id": "70eb9a19-325e-4179-a196-4417e3f30e19", + "metadata": {}, + "source": [ + "In this case each compute node `cn138` and `cn139` is equipped with one `Tesla V100S-PCIE-32GB`." + ] + }, + { + "cell_type": "markdown", + "id": "5b554291-41ba-484d-b3da-a764bb286c4c", + "metadata": {}, + "source": [ + "## External Executables\n", + "While `pympipool` was initially designed for up-scaling python functions for HPC, the same functionality can be leveraged\n", + "to up-scale any executable independent of the programming language it is developed in. This approach follows the design \n", + "of the `flux.job.FluxExecutor` included in the [flux framework](https://flux-framework.org). In `pympipool` this approach\n", + "is extended to support any kind of subprocess, so it is no longer limited to the [flux framework](https://flux-framework.org)." + ] + }, + { + "cell_type": "markdown", + "id": "35e426c3-2e61-42f6-8c85-31dd288b7f51", + "metadata": {}, + "source": [ + "### Subprocess\n", + "Following the [`subprocess.check_output()`](https://docs.python.org/3/library/subprocess.html) interface of the standard\n", + "python libraries, any kind of command can be submitted to the `pympipool.SubprocessExecutor`. The command can either be \n", + "specified as a list `[\"echo\", \"test\"]` in which the first entry is typically the executable followed by the corresponding\n", + "parameters or the command can be specified as a string `\"echo test\"` with the additional parameter `shell=True`." + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "91463388-789a-4749-b02f-71a6d76f9b96", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "False test\n", + " True\n" + ] + } + ], + "source": [ + "from pympipool import SubprocessExecutor\n", + "\n", + "with SubprocessExecutor(max_workers=2) as exe:\n", + " future = exe.submit([\"echo\", \"test\"], universal_newlines=True)\n", + " print(future.done(), future.result(), future.done())" + ] + }, + { + "cell_type": "markdown", + "id": "a8c436db-fc60-45a8-8603-ff9a7e8439ca", + "metadata": {}, + "source": [ + "In analogy to the previous examples the `SubprocessExecutor` class is directly imported from the `pympipool` module and \n", + "the maximum number of workers is set to two `max_workers=2`. In contrast to the `pympipool.Executor` class no other\n", + "settings to assign specific hardware to the command via the python interface are available in the `SubprocessExecutor` \n", + "class. To specify the hardware requirements for the individual commands, the user has to manually assign the resources\n", + "using the commands of the resource schedulers like `srun`, `flux run` or `mpiexec`.\n", + "\n", + "The `concurrent.futures.Future` object returned after submitting a command to the `pymipool.SubprocessExecutor` behaves\n", + "just like any other future object. It provides a `done()` function to check if the execution completed as well as a \n", + "`result()` function to return the output of the submitted command. \n", + "\n", + "In comparison to the `flux.job.FluxExecutor` included in the [flux framework](https://flux-framework.org) the \n", + "`pymipool.SubprocessExecutor` differs in two ways. One the `pymipool.SubprocessExecutor` does not provide any option for\n", + "resource assignment and two the `pymipool.SubprocessExecutor` returns the output of the command rather than just \n", + "returning the exit status when calling `result()`. " + ] + }, + { + "cell_type": "markdown", + "id": "212cc7ed-b8df-447f-98df-e5390c839660", + "metadata": {}, + "source": [ + "### Interactive Shell\n", + "Beyond external executables which are called once with a set of input parameters and or input files and return one set\n", + "of outputs, there are some executables which allow the user to interact with the executable during the execution. The \n", + "challenge of interfacing a python process with such an interactive executable is to identify when the executable is ready\n", + "to receive the next input. A very basis example for an interactive executable is a script which counts to the number \n", + "input by the user. This can be written in python as `count.py`:" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "id": "094f9afc-6fca-43c4-9794-51408ff5fc5f", + "metadata": {}, + "outputs": [], + "source": [ + "with open(\"count.py\", \"w\") as f:\n", + " f.writelines(\"\"\"\\\n", + "def count(iterations):\n", + " for i in range(int(iterations)):\n", + " print(i)\n", + " print(\"done\")\n", + "\n", + "\n", + "if __name__ == \"__main__\":\n", + " while True:\n", + " user_input = input()\n", + " if \"shutdown\" in user_input:\n", + " break\n", + " else:\n", + " count(iterations=int(user_input))\n", + "\"\"\")" + ] + }, + { + "cell_type": "markdown", + "id": "9eb17afc-ada6-4b75-b4e5-aba5a15e2512", + "metadata": {}, + "source": [ + "This example is challenging in terms of interfacing it with a python process as the length of the output changes depending\n", + "on the input. The first option that the `pympipool.ShellExecutor` provides is specifying the number of lines to read for\n", + "each call submitted to the executable using the `lines_to_read` parameter. In comparison to the `SubprocessExecutor` \n", + "defined above the `ShellExecutor` only supports the execution of a single executable at a time, correspondingly the input\n", + "parameters for calling the executable are provided at the time of initialization of the `ShellExecutor` and the inputs \n", + "are submitted using the `submit()` function:" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "8ec6f955-8d40-42b0-a116-c5b538cc8e87", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "False 0\n", + "1\n", + "2\n", + "3\n", + "done\n", + " True\n" + ] + } + ], + "source": [ + "from pympipool import ShellExecutor\n", + "\n", + "with ShellExecutor([\"python\", \"count.py\"], universal_newlines=True) as exe:\n", + " future_lines = exe.submit(string_input=\"4\", lines_to_read=5)\n", + " print(future_lines.done(), future_lines.result(), future_lines.done())" + ] + }, + { + "cell_type": "markdown", + "id": "fcb6fdfc-d5c2-4008-91c1-3f935920cb7e", + "metadata": {}, + "source": [ + "The response for a given set of input is again returned as `concurrent.futures.Future` object, this allows the user to\n", + "execute other steps on the python side while waiting for the completion of the external executable. In this case the \n", + "example counts the numbers from `0` to `3` and prints each of them in one line followed by `done` to notify the user its\n", + "waiting for new inputs. This results in `n+1` lines of output for the input of `n`. Still predicting the number of lines\n", + "for a given input can be challenging, so the `pympipool.ShellExecutor` class also provides the option to wait until a \n", + "specific pattern is found in the output using the `stop_read_pattern`:" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "b048e987-2472-4481-87af-131ade1b1ce1", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "False 0\n", + "1\n", + "2\n", + "3\n", + "done\n", + " True\n" + ] + } + ], + "source": [ + "from pympipool import ShellExecutor\n", + "\n", + "with ShellExecutor([\"python\", \"count.py\"], universal_newlines=True) as exe:\n", + " future_pattern = exe.submit(string_input=\"4\", stop_read_pattern=\"done\")\n", + " print(future_pattern.done(), future_pattern.result(), future_pattern.done())" + ] + }, + { + "cell_type": "markdown", + "id": "7e59baad-fdd1-4895-8eed-efefedc91806", + "metadata": {}, + "source": [ + "In this example the pattern simply searches for the string `done` in the output of the program and returns all the output\n", + "gathered from the executable since the last input as the result of the `concurrent.futures.Future` object returned after\n", + "the submission of the interactive command. " + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.13" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/pympipool/__init__.py b/pympipool/__init__.py index 80edaf05..1567c721 100644 --- a/pympipool/__init__.py +++ b/pympipool/__init__.py @@ -1,4 +1,153 @@ +import os +import shutil from ._version import get_versions +from pympipool.mpi.executor import PyMPIExecutor +from pympipool.shared.interface import SLURM_COMMAND +from pympipool.shell.executor import SubprocessExecutor +from pympipool.shell.interactive import ShellExecutor +from pympipool.slurm.executor import PySlurmExecutor + +try: # The PyFluxExecutor requires flux-core to be installed. + from pympipool.flux.executor import PyFluxExecutor + + flux_installed = "FLUX_URI" in os.environ +except ImportError: + flux_installed = False + pass + +# The PySlurmExecutor requires the srun command to be available. +slurm_installed = shutil.which(SLURM_COMMAND) is not None + __version__ = get_versions()["version"] -del get_versions + + +class Executor: + """ + The pympipool.Executor leverages either the message passing interface (MPI), the SLURM workload manager or preferable + the flux framework for distributing python functions within a given resource allocation. In contrast to the + mpi4py.futures.MPIPoolExecutor the pympipool.Executor can be executed in a serial python process and does not + require the python script to be executed with MPI. It is even possible to execute the pympipool.Executor directly in + an interactive Jupyter notebook. + + Args: + max_workers (int): defines the number workers which can execute functions in parallel + cores_per_worker (int): number of MPI cores to be used for each function call + threads_per_core (int): number of OpenMP threads to be used for each function call + gpus_per_worker (int): number of GPUs per worker - defaults to 0 + oversubscribe (bool): adds the `--oversubscribe` command line flag (OpenMPI only) - default False + init_function (None): optional function to preset arguments for functions which are submitted later + cwd (str/None): current working directory where the parallel python task is executed + sleep_interval (float): synchronization interval - default 0.1 + + Examples: + ``` + >>> import numpy as np + >>> from pympipool import Executor + >>> + >>> def calc(i, j, k): + >>> from mpi4py import MPI + >>> size = MPI.COMM_WORLD.Get_size() + >>> rank = MPI.COMM_WORLD.Get_rank() + >>> return np.array([i, j, k]), size, rank + >>> + >>> def init_k(): + >>> return {"k": 3} + >>> + >>> with Executor(cores=2, init_function=init_k) as p: + >>> fs = p.submit(calc, 2, j=4) + >>> print(fs.result()) + [(array([2, 4, 3]), 2, 0), (array([2, 4, 3]), 2, 1)] + ``` + """ + + def __init__( + self, + max_workers=1, + cores_per_worker=1, + threads_per_core=1, + gpus_per_worker=0, + oversubscribe=False, + init_function=None, + cwd=None, + sleep_interval=0.1, + executor=None, + ): + # Use __new__() instead of __init__(). This function is only implemented to enable auto-completion. + pass + + def __new__( + cls, + max_workers=1, + cores_per_worker=1, + threads_per_core=1, + gpus_per_worker=0, + oversubscribe=False, + init_function=None, + cwd=None, + sleep_interval=0.1, + executor=None, + ): + """ + Instead of returning a pympipool.Executor object this function returns either a pympipool.mpi.PyMPIExecutor, + pympipool.slurm.PySlurmExecutor or pympipool.flux.PyFluxExecutor depending on which backend is available. The + pympipool.flux.PyFluxExecutor is the preferred choice while the pympipool.mpi.PyMPIExecutor is primarily used + for development and testing. The pympipool.flux.PyFluxExecutor requires flux-core from the flux-framework to be + installed and in addition flux-sched to enable GPU scheduling. Finally, the pympipool.slurm.PySlurmExecutor + requires the SLURM workload manager to be installed on the system. + + Args: + max_workers (int): defines the number workers which can execute functions in parallel + cores_per_worker (int): number of MPI cores to be used for each function call + threads_per_core (int): number of OpenMP threads to be used for each function call + gpus_per_worker (int): number of GPUs per worker - defaults to 0 + oversubscribe (bool): adds the `--oversubscribe` command line flag (OpenMPI only) - default False + init_function (None): optional function to preset arguments for functions which are submitted later + cwd (str/None): current working directory where the parallel python task is executed + sleep_interval (float): synchronization interval - default 0.1 + """ + if flux_installed: + if oversubscribe: + raise ValueError( + "Oversubscribing is not supported for the pympipool.flux.PyFLuxExecutor backend." + "Please use oversubscribe=False instead of oversubscribe=True." + ) + return PyFluxExecutor( + max_workers=max_workers, + cores_per_worker=cores_per_worker, + threads_per_core=threads_per_core, + gpus_per_worker=gpus_per_worker, + init_function=init_function, + cwd=cwd, + sleep_interval=sleep_interval, + ) + elif slurm_installed: + return PySlurmExecutor( + max_workers=max_workers, + cores_per_worker=cores_per_worker, + init_function=init_function, + cwd=cwd, + sleep_interval=sleep_interval, + ) + else: + if threads_per_core != 1: + raise ValueError( + "Thread based parallelism is not supported for the pympipool.mpi.PyMPIExecutor backend." + "Please use threads_per_core=1 instead of threads_per_core=" + + str(threads_per_core) + + "." + ) + if gpus_per_worker != 0: + raise ValueError( + "GPU assignment is not supported for the pympipool.mpi.PyMPIExecutor backend." + "Please use gpus_per_worker=0 instead of gpus_per_worker=" + + str(gpus_per_worker) + + "." + ) + return PyMPIExecutor( + max_workers=max_workers, + cores_per_worker=cores_per_worker, + init_function=init_function, + cwd=cwd, + sleep_interval=sleep_interval, + ) diff --git a/pympipool/flux/executor.py b/pympipool/flux/executor.py index 4c8930da..9ab1e52d 100644 --- a/pympipool/flux/executor.py +++ b/pympipool/flux/executor.py @@ -14,6 +14,11 @@ class PyFluxExecutor(ExecutorBase): """ + The pympipool.flux.PyFluxExecutor leverages the flux framework to distribute python tasks within a queuing system + allocation. In analogy to the pympipool.slurm.PySlurmExecutur it provides the option to specify the number of + threads per worker as well as the number of GPUs per worker in addition to specifying the number of cores per + worker. + Args: max_workers (int): defines the number workers which can execute functions in parallel cores_per_worker (int): number of MPI cores to be used for each function call @@ -23,11 +28,31 @@ class PyFluxExecutor(ExecutorBase): cwd (str/None): current working directory where the parallel python task is executed sleep_interval (float): synchronization interval - default 0.1 executor (flux.job.FluxExecutor): Flux Python interface to submit the workers to flux + + Examples: + + >>> import numpy as np + >>> from pympipool.flux import PyFluxExecutor + >>> + >>> def calc(i, j, k): + >>> from mpi4py import MPI + >>> size = MPI.COMM_WORLD.Get_size() + >>> rank = MPI.COMM_WORLD.Get_rank() + >>> return np.array([i, j, k]), size, rank + >>> + >>> def init_k(): + >>> return {"k": 3} + >>> + >>> with PyFluxExecutor(max_workers=2, init_function=init_k) as p: + >>> fs = p.submit(calc, 2, j=4) + >>> print(fs.result()) + [(array([2, 4, 3]), 2, 0), (array([2, 4, 3]), 2, 1)] + """ def __init__( self, - max_workers, + max_workers=1, cores_per_worker=1, threads_per_core=1, gpus_per_worker=0, @@ -59,11 +84,7 @@ def __init__( class PyFluxSingleTaskExecutor(ExecutorBase): """ - The pympipool.Executor behaves like the concurrent.futures.Executor but it uses mpi4py to execute parallel tasks. - In contrast to the mpi4py.futures.MPIPoolExecutor the pympipool.Executor can be executed in a serial python process - and does not require the python script to be executed with MPI. Still internally the pympipool.Executor uses the - mpi4py.futures.MPIPoolExecutor, consequently it is primarily an abstraction of its functionality to improve the - usability in particular when used in combination with Jupyter notebooks. + The pympipool.flux.PyFluxSingleTaskExecutor is the internal worker for the pympipool.flux.PyFluxExecutor. Args: cores (int): defines the number of MPI ranks to use for each function call @@ -71,27 +92,7 @@ class PyFluxSingleTaskExecutor(ExecutorBase): gpus_per_task (int): number of GPUs per MPI rank - defaults to 0 init_function (None): optional function to preset arguments for functions which are submitted later cwd (str/None): current working directory where the parallel python task is executed - - Examples: - ``` - >>> import numpy as np - >>> from pympipool.flux.executor import PyFluxSingleTaskExecutor - >>> - >>> def calc(i, j, k): - >>> from mpi4py import MPI - >>> size = MPI.COMM_WORLD.Get_size() - >>> rank = MPI.COMM_WORLD.Get_rank() - >>> return np.array([i, j, k]), size, rank - >>> - >>> def init_k(): - >>> return {"k": 3} - >>> - >>> with PyFluxSingleTaskExecutor(cores=2, init_function=init_k) as p: - >>> fs = p.submit(calc, 2, j=4) - >>> print(fs.result()) - - [(array([2, 4, 3]), 2, 0), (array([2, 4, 3]), 2, 1)] - ``` + executor (flux.job.FluxExecutor): Flux Python interface to submit the workers to flux """ def __init__( @@ -136,10 +137,10 @@ def __init__( super().__init__( cwd=cwd, cores=cores, - gpus_per_core=gpus_per_core, - threads_per_core=threads_per_core, oversubscribe=oversubscribe, ) + self._threads_per_core = threads_per_core + self._gpus_per_core = gpus_per_core self._executor = executor self._future = None diff --git a/pympipool/mpi/executor.py b/pympipool/mpi/executor.py index 9aac7289..33b53f68 100644 --- a/pympipool/mpi/executor.py +++ b/pympipool/mpi/executor.py @@ -4,48 +4,57 @@ ExecutorBase, executor_broker, ) -from pympipool.shared.interface import MpiExecInterface, SlurmSubprocessInterface +from pympipool.shared.interface import MpiExecInterface from pympipool.shared.thread import RaisingThread class PyMPIExecutor(ExecutorBase): """ + The pympipool.mpi.PyMPIExecutor leverages the message passing interface MPI to distribute python tasks within an + MPI allocation. In contrast to the mpi4py.futures.MPIPoolExecutor the pympipool.mpi.PyMPIExecutor can be executed + in a serial python process and does not require the python script to be executed with MPI. Consequently, it is + primarily an abstraction of its functionality to improve the usability in particular when used in combination with \ + Jupyter notebooks. + Args: max_workers (int): defines the number workers which can execute functions in parallel cores_per_worker (int): number of MPI cores to be used for each function call - threads_per_core (int): number of OpenMP threads to be used for each function call - gpus_per_worker (int): number of GPUs per worker - defaults to 0 oversubscribe (bool): adds the `--oversubscribe` command line flag (OpenMPI only) - default False init_function (None): optional function to preset arguments for functions which are submitted later cwd (str/None): current working directory where the parallel python task is executed sleep_interval (float): synchronization interval - default 0.1 - enable_slurm_backend (bool): enable the SLURM queueing system as backend - defaults to False + + Examples: + + >>> import numpy as np + >>> from pympipool.mpi import PyMPIExecutor + >>> + >>> def calc(i, j, k): + >>> from mpi4py import MPI + >>> size = MPI.COMM_WORLD.Get_size() + >>> rank = MPI.COMM_WORLD.Get_rank() + >>> return np.array([i, j, k]), size, rank + >>> + >>> def init_k(): + >>> return {"k": 3} + >>> + >>> with PyMPIExecutor(max_workers=2, init_function=init_k) as p: + >>> fs = p.submit(calc, 2, j=4) + >>> print(fs.result()) + [(array([2, 4, 3]), 2, 0), (array([2, 4, 3]), 2, 1)] + """ def __init__( self, - max_workers, + max_workers=1, cores_per_worker=1, - threads_per_core=1, - gpus_per_worker=0, oversubscribe=False, init_function=None, cwd=None, sleep_interval=0.1, - enable_slurm_backend=False, ): super().__init__() - if not enable_slurm_backend: - if threads_per_core != 1: - raise ValueError( - "The MPI backend only supports threads_per_core=1, " - + "to manage threads use the SLURM queuing system enable_slurm_backend=True ." - ) - elif gpus_per_worker != 0: - raise ValueError( - "The MPI backend only supports gpus_per_core=0, " - + "to manage GPUs use the SLURM queuing system enable_slurm_backend=True ." - ) self._process = RaisingThread( target=executor_broker, kwargs={ @@ -56,12 +65,9 @@ def __init__( "executor_class": PyMPISingleTaskExecutor, # Executor Arguments "cores": cores_per_worker, - "threads_per_core": threads_per_core, - "gpus_per_task": int(gpus_per_worker / cores_per_worker), "oversubscribe": oversubscribe, "init_function": init_function, "cwd": cwd, - "enable_slurm_backend": enable_slurm_backend, }, ) self._process.start() @@ -69,51 +75,22 @@ def __init__( class PyMPISingleTaskExecutor(ExecutorBase): """ - The pympipool.Executor behaves like the concurrent.futures.Executor but it uses mpi4py to execute parallel tasks. - In contrast to the mpi4py.futures.MPIPoolExecutor the pympipool.Executor can be executed in a serial python process - and does not require the python script to be executed with MPI. Still internally the pympipool.Executor uses the - mpi4py.futures.MPIPoolExecutor, consequently it is primarily an abstraction of its functionality to improve the - usability in particular when used in combination with Jupyter notebooks. + The pympipool.mpi.PyMPISingleTaskExecutor is the internal worker for the pympipool.mpi.PyMPIExecutor. Args: cores (int): defines the number of MPI ranks to use for each function call - threads_per_core (int): number of OpenMP threads to be used for each function call - gpus_per_task (int): number of GPUs per MPI rank - defaults to 0 oversubscribe (bool): adds the `--oversubscribe` command line flag (OpenMPI only) - default False init_function (None): optional function to preset arguments for functions which are submitted later cwd (str/None): current working directory where the parallel python task is executed - enable_slurm_backend (bool): enable the SLURM queueing system as backend - defaults to False - Examples: - ``` - >>> import numpy as np - >>> from pympipool.mpi.executor import PyMPISingleTaskExecutor - >>> - >>> def calc(i, j, k): - >>> from mpi4py import MPI - >>> size = MPI.COMM_WORLD.Get_size() - >>> rank = MPI.COMM_WORLD.Get_rank() - >>> return np.array([i, j, k]), size, rank - >>> - >>> def init_k(): - >>> return {"k": 3} - >>> - >>> with PyMPISingleTaskExecutor(cores=2, init_function=init_k) as p: - >>> fs = p.submit(calc, 2, j=4) - >>> print(fs.result()) - [(array([2, 4, 3]), 2, 0), (array([2, 4, 3]), 2, 1)] - ``` """ def __init__( self, cores=1, - threads_per_core=1, - gpus_per_task=0, oversubscribe=False, init_function=None, cwd=None, - enable_slurm_backend=False, ): super().__init__() self._process = RaisingThread( @@ -122,41 +99,12 @@ def __init__( # Executor Arguments "future_queue": self._future_queue, "cores": cores, - "interface_class": get_interface, + "interface_class": MpiExecInterface, # Interface Arguments - "threads_per_core": threads_per_core, - "gpus_per_core": gpus_per_task, "cwd": cwd, "oversubscribe": oversubscribe, - "enable_slurm_backend": enable_slurm_backend, }, ) self._process.start() self._set_init_function(init_function=init_function) cloudpickle_register(ind=3) - - -def get_interface( - cores=1, - threads_per_core=1, - gpus_per_core=0, - cwd=None, - oversubscribe=False, - enable_slurm_backend=False, -): - if not enable_slurm_backend: - return MpiExecInterface( - cwd=cwd, - cores=cores, - threads_per_core=threads_per_core, - gpus_per_core=gpus_per_core, - oversubscribe=oversubscribe, - ) - else: - return SlurmSubprocessInterface( - cwd=cwd, - cores=cores, - threads_per_core=threads_per_core, - gpus_per_core=gpus_per_core, - oversubscribe=oversubscribe, - ) diff --git a/pympipool/shared/__init__.py b/pympipool/shared/__init__.py index 73fadf43..2daf2f44 100644 --- a/pympipool/shared/__init__.py +++ b/pympipool/shared/__init__.py @@ -8,4 +8,4 @@ ) from pympipool.shared.executorbase import cancel_items_in_queue from pympipool.shared.thread import RaisingThread -from pympipool.shared.interface import MpiExecInterface, SlurmSubprocessInterface +from pympipool.shared.interface import MpiExecInterface, SrunInterface diff --git a/pympipool/shared/executorbase.py b/pympipool/shared/executorbase.py index c950eae1..7c8918cd 100644 --- a/pympipool/shared/executorbase.py +++ b/pympipool/shared/executorbase.py @@ -53,11 +53,21 @@ def shutdown(self, wait=True, *, cancel_futures=False): if cancel_futures: cancel_items_in_queue(que=self._future_queue) self._future_queue.put({"shutdown": True, "wait": wait}) - self._process.join() + if wait: + self._process.join() + self._future_queue.join() + self._process = None + self._future_queue = None def __len__(self): return self._future_queue.qsize() + def __del__(self): + try: + self.shutdown(wait=False) + except (AttributeError, RuntimeError): + pass + def _set_init_function(self, init_function): if init_function is not None: self._future_queue.put( @@ -134,6 +144,7 @@ def execute_parallel_tasks_loop(interface, future_queue): if "shutdown" in task_dict.keys() and task_dict["shutdown"]: interface.shutdown(wait=task_dict["wait"]) future_queue.task_done() + future_queue.join() break elif "fn" in task_dict.keys() and "future" in task_dict.keys(): f = task_dict.pop("future") @@ -174,11 +185,12 @@ def executor_broker( future_queue.task_done() else: future_queue.task_done() + future_queue.join() break def execute_task_dict(task_dict, meta_future_lst): - if "fn" in task_dict.keys(): + if "fn" in task_dict.keys() or "future" in task_dict.keys(): meta_future = next(as_completed(meta_future_lst.keys())) executor = meta_future_lst.pop(meta_future) executor.future_queue.put(task_dict) diff --git a/pympipool/shared/interface.py b/pympipool/shared/interface.py index 8885cb36..0fee6905 100644 --- a/pympipool/shared/interface.py +++ b/pympipool/shared/interface.py @@ -2,14 +2,14 @@ import subprocess +MPI_COMMAND = "mpiexec" +SLURM_COMMAND = "srun" + + class BaseInterface(ABC): - def __init__( - self, cwd, cores=1, threads_per_core=1, gpus_per_core=0, oversubscribe=False - ): + def __init__(self, cwd, cores=1, oversubscribe=False): self._cwd = cwd self._cores = cores - self._threads_per_core = threads_per_core - self._gpus_per_core = gpus_per_core self._oversubscribe = oversubscribe def bootup(self, command_lst): @@ -27,15 +27,11 @@ def __init__( self, cwd=None, cores=1, - threads_per_core=1, - gpus_per_core=0, oversubscribe=False, ): super().__init__( cwd=cwd, cores=cores, - threads_per_core=threads_per_core, - gpus_per_core=gpus_per_core, oversubscribe=oversubscribe, ) self._process = None @@ -50,6 +46,7 @@ def generate_command(self, command_lst): return command_lst def shutdown(self, wait=True): + self._process.communicate() self._process.terminate() if wait: self._process.wait() @@ -63,7 +60,6 @@ class MpiExecInterface(SubprocessInterface): def generate_command(self, command_lst): command_prepend_lst = generate_mpiexec_command( cores=self._cores, - gpus_per_core=self._gpus_per_core, oversubscribe=self._oversubscribe, ) return super().generate_command( @@ -71,7 +67,23 @@ def generate_command(self, command_lst): ) -class SlurmSubprocessInterface(SubprocessInterface): +class SrunInterface(SubprocessInterface): + def __init__( + self, + cwd=None, + cores=1, + threads_per_core=1, + gpus_per_core=0, + oversubscribe=False, + ): + super().__init__( + cwd=cwd, + cores=cores, + oversubscribe=oversubscribe, + ) + self._threads_per_core = threads_per_core + self._gpus_per_core = gpus_per_core + def generate_command(self, command_lst): command_prepend_lst = generate_slurm_command( cores=self._cores, @@ -85,19 +97,19 @@ def generate_command(self, command_lst): ) -def generate_mpiexec_command(cores, gpus_per_core=0, oversubscribe=False): - command_prepend_lst = ["mpiexec", "-n", str(cores)] +def generate_mpiexec_command(cores, oversubscribe=False): + command_prepend_lst = [MPI_COMMAND, "-n", str(cores)] if oversubscribe: command_prepend_lst += ["--oversubscribe"] - if gpus_per_core > 0: - raise ValueError() return command_prepend_lst def generate_slurm_command( cores, cwd, threads_per_core=1, gpus_per_core=0, oversubscribe=False ): - command_prepend_lst = ["srun", "-n", str(cores), "-D", cwd] + command_prepend_lst = [SLURM_COMMAND, "-n", str(cores)] + if cwd is not None: + command_prepend_lst += ["-D", cwd] if threads_per_core > 1: command_prepend_lst += ["--cpus-per-task" + str(threads_per_core)] if gpus_per_core > 0: diff --git a/pympipool/shell/__init__.py b/pympipool/shell/__init__.py new file mode 100644 index 00000000..3086c26f --- /dev/null +++ b/pympipool/shell/__init__.py @@ -0,0 +1,2 @@ +from pympipool.shell.executor import SubprocessExecutor +from pympipool.shell.interactive import ShellExecutor diff --git a/pympipool/shell/executor.py b/pympipool/shell/executor.py new file mode 100644 index 00000000..d9eda6fa --- /dev/null +++ b/pympipool/shell/executor.py @@ -0,0 +1,110 @@ +from concurrent.futures import Future +import subprocess + +from pympipool.shared.executorbase import executor_broker, ExecutorBase +from pympipool.shared.thread import RaisingThread + + +def execute_single_task(future_queue): + """ + Process items received via the queue. + + Args: + future_queue (queue.Queue): + """ + while True: + task_dict = future_queue.get() + if "shutdown" in task_dict.keys() and task_dict["shutdown"]: + future_queue.task_done() + future_queue.join() + break + elif "future" in task_dict.keys(): + f = task_dict.pop("future") + if f.set_running_or_notify_cancel(): + try: + f.set_result( + subprocess.check_output( + *task_dict["args"], **task_dict["kwargs"] + ) + ) + except Exception as thread_exception: + future_queue.task_done() + f.set_exception(exception=thread_exception) + raise thread_exception + else: + future_queue.task_done() + else: + raise KeyError(task_dict) + + +class SubprocessSingleExecutor(ExecutorBase): + """ + The pympipool.shell.SubprocessSingleExecutor is the internal worker for the pympipool.shell.SubprocessExecutor. + """ + + def __init__(self): + super().__init__() + self._process = RaisingThread( + target=execute_single_task, + kwargs={ + "future_queue": self._future_queue, + }, + ) + self._process.start() + + def submit(self, *args, **kwargs): + f = Future() + self._future_queue.put({"future": f, "args": args, "kwargs": kwargs}) + return f + + +class SubprocessExecutor(ExecutorBase): + """ + The pympipool.shell.SubprocessExecutor enables the submission of command line calls via the subprocess.check_output() + interface of the python standard library. It is based on the concurrent.futures.Executor class and returns a + concurrent.futures.Future object for every submitted command line call. Still it does not provide any option to + interact with the external executable during the execution. + + Args: + max_workers (int): defines the number workers which can execute functions in parallel + sleep_interval (float): synchronization interval - default 0.1 + + Examples: + + >>> from pympipool import SubprocessExecutor + >>> with SubprocessExecutor(max_workers=2) as exe: + >>> future = exe.submit(["echo", "test"], universal_newlines=True) + >>> print(future.done(), future.result(), future.done()) + (False, "test", True) + + """ + + def __init__( + self, + max_workers=1, + sleep_interval=0.1, + ): + super().__init__() + self._process = RaisingThread( + target=executor_broker, + kwargs={ + # Broker Arguments + "future_queue": self._future_queue, + "max_workers": max_workers, + "sleep_interval": sleep_interval, + "executor_class": SubprocessSingleExecutor, + }, + ) + self._process.start() + + def submit(self, *args, **kwargs): + """ + Submit a command line call to be executed. The given arguments are provided to subprocess.Popen() as additional + inputs to control the execution. + + Returns: + A Future representing the given call. + """ + f = Future() + self._future_queue.put({"future": f, "args": args, "kwargs": kwargs}) + return f diff --git a/pympipool/shell/interactive.py b/pympipool/shell/interactive.py new file mode 100644 index 00000000..b155577b --- /dev/null +++ b/pympipool/shell/interactive.py @@ -0,0 +1,172 @@ +from concurrent.futures import Future +import subprocess +from time import sleep + +from pympipool.shared.executorbase import cancel_items_in_queue, ExecutorBase +from pympipool.shared.thread import RaisingThread + + +def wait_for_process_to_stop(process, sleep_interval=10e-10): + """ + Wait for the subprocess.Popen() process to stop executing + + Args: + process (subprocess.Popen): process object + sleep_interval (float): interval to sleep during poll() calls + """ + while process.poll() is None: + sleep(sleep_interval) + + +def execute_single_task(future_queue): + """ + Process items received via the queue. + + Args: + future_queue (queue.Queue): + """ + process = None + while True: + task_dict = future_queue.get() + if "shutdown" in task_dict.keys() and task_dict["shutdown"]: + if process is not None and process.poll() is None: + process.stdin.flush() + process.stdin.close() + process.stdout.close() + process.stderr.close() + process.terminate() + wait_for_process_to_stop(process=process) + future_queue.task_done() + # future_queue.join() + break + elif "init" in task_dict.keys() and task_dict["init"]: + process = subprocess.Popen( + *task_dict["args"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + **task_dict["kwargs"], + ) + elif "future" in task_dict.keys(): + if process is None: + raise ValueError("process not initialized") + elif process.poll() is None: + f = task_dict.pop("future") + if f.set_running_or_notify_cancel(): + try: + process.stdin.write(task_dict["input"]) + process.stdin.flush() + lines_count = 0 + output = "" + while True: + output_current = process.stdout.readline() + output += output_current + lines_count += 1 + if ( + task_dict["stop_read_pattern"] is not None + and task_dict["stop_read_pattern"] in output_current + ): + break + elif ( + task_dict["lines_to_read"] is not None + and task_dict["lines_to_read"] == lines_count + ): + break + f.set_result(output) + except Exception as thread_exception: + future_queue.task_done() + f.set_exception(exception=thread_exception) + raise thread_exception + else: + future_queue.task_done() + else: + raise ValueError("process exited") + + +class ShellExecutor(ExecutorBase): + """ + In contrast to the other pympipool.shell.SubprocessExecutor and the pympipool.Executor the pympipool.shell.ShellExecutor + can only execute a single process at a given time. Still it adds the capability to interact with this process during + its execution. The initialization of the pympipool.shell.ShellExecutor takes the same input arguments as the + subprocess.Popen() call for the standard library to start a subprocess. + + Examples + + >>> from pympipool import ShellExecutor + >>> with ShellExecutor(["python", "count.py"], universal_newlines=True) as exe: + >>> future_lines = exe.submit(string_input="4", lines_to_read=5) + >>> print(future_lines.done(), future_lines.result(), future_lines.done()) + (False, "0\n1\n2\n3\ndone\n", True) + + >>> from pympipool import ShellExecutor + >>> with ShellExecutor(["python", "count.py"], universal_newlines=True) as exe: + >>> future_pattern = exe.submit(string_input="4", stop_read_pattern="done") + >>> print(future_pattern.done(), future_pattern.result(), future_pattern.done()) + (False, "0\n1\n2\n3\ndone\n", True) + """ + + def __init__(self, *args, **kwargs): + super().__init__() + self._process = RaisingThread( + target=execute_single_task, + kwargs={ + "future_queue": self._future_queue, + }, + ) + self._process.start() + self._future_queue.put({"init": True, "args": args, "kwargs": kwargs}) + + def submit(self, string_input, lines_to_read=None, stop_read_pattern=None): + """ + Submit the input as a string to the executable. In addition to the input the ShellExecutor also needs a measure + to identify the completion of the execution. This can either be provided based on the number of lines to read + using the `lines_to_read` parameter or by providing a string pattern using the `stop_read_pattern` to stop + reading new lines. One of these two stopping criteria has to be defined. + + Args: + string_input (str): Input to be communicated to the underlying executable + lines_to_read (None/int): integer number of lines to read from the command line (optional) + stop_read_pattern (None/str): string pattern to indicate the command line output is completed (optional) + + Returns: + A Future representing the given call. + """ + if lines_to_read is None and stop_read_pattern is None: + raise ValueError( + "Either the number of lines_to_read (int) or the stop_read_pattern (str) has to be defined." + ) + if string_input[-1:] != "\n": + string_input += "\n" + f = Future() + self._future_queue.put( + { + "future": f, + "input": string_input, + "lines_to_read": lines_to_read, + "stop_read_pattern": stop_read_pattern, + } + ) + return f + + def shutdown(self, wait=True, *, cancel_futures=False): + """Clean-up the resources associated with the Executor. + + It is safe to call this method several times. Otherwise, no other + methods can be called after this one. + + Args: + wait: If True then shutdown will not return until all running + futures have finished executing and the resources used by the + parallel_executors have been reclaimed. + cancel_futures: If True then shutdown will cancel all pending + futures. Futures that are completed or running will not be + cancelled. + """ + if cancel_futures: + cancel_items_in_queue(que=self._future_queue) + self._future_queue.put({"shutdown": True, "wait": wait}) + if wait: + self._process.join() + # self._future_queue.join() + self._process = None + self._future_queue = None diff --git a/pympipool/slurm/__init__.py b/pympipool/slurm/__init__.py new file mode 100644 index 00000000..ed4aeab3 --- /dev/null +++ b/pympipool/slurm/__init__.py @@ -0,0 +1 @@ +from pympipool.slurm.executor import PySlurmExecutor diff --git a/pympipool/slurm/executor.py b/pympipool/slurm/executor.py new file mode 100644 index 00000000..1414493e --- /dev/null +++ b/pympipool/slurm/executor.py @@ -0,0 +1,121 @@ +from pympipool.shared.executorbase import ( + cloudpickle_register, + execute_parallel_tasks, + ExecutorBase, + executor_broker, +) +from pympipool.shared.interface import SrunInterface +from pympipool.shared.thread import RaisingThread + + +class PySlurmExecutor(ExecutorBase): + """ + The pympipool.slurm.PySlurmExecutor leverages the srun command to distribute python tasks within a SLURM queuing + system allocation. In analogy to the pympipool.flux.PyFluxExecutor it provides the option to specify the number of + threads per worker as well as the number of GPUs per worker in addition to specifying the number of cores per + worker. + + Args: + max_workers (int): defines the number workers which can execute functions in parallel + cores_per_worker (int): number of MPI cores to be used for each function call + threads_per_core (int): number of OpenMP threads to be used for each function call + gpus_per_worker (int): number of GPUs per worker - defaults to 0 + oversubscribe (bool): adds the `--oversubscribe` command line flag (OpenMPI only) - default False + init_function (None): optional function to preset arguments for functions which are submitted later + cwd (str/None): current working directory where the parallel python task is executed + sleep_interval (float): synchronization interval - default 0.1 + + Examples: + + >>> import numpy as np + >>> from pympipool.slurm import PySlurmExecutor + >>> + >>> def calc(i, j, k): + >>> from mpi4py import MPI + >>> size = MPI.COMM_WORLD.Get_size() + >>> rank = MPI.COMM_WORLD.Get_rank() + >>> return np.array([i, j, k]), size, rank + >>> + >>> def init_k(): + >>> return {"k": 3} + >>> + >>> with PySlurmExecutor(max_workers=2, init_function=init_k) as p: + >>> fs = p.submit(calc, 2, j=4) + >>> print(fs.result()) + + [(array([2, 4, 3]), 2, 0), (array([2, 4, 3]), 2, 1)] + """ + + def __init__( + self, + max_workers=1, + cores_per_worker=1, + threads_per_core=1, + gpus_per_worker=0, + oversubscribe=False, + init_function=None, + cwd=None, + sleep_interval=0.1, + ): + super().__init__() + self._process = RaisingThread( + target=executor_broker, + kwargs={ + # Broker Arguments + "future_queue": self._future_queue, + "max_workers": max_workers, + "sleep_interval": sleep_interval, + "executor_class": PySlurmSingleTaskExecutor, + # Executor Arguments + "cores": cores_per_worker, + "threads_per_core": threads_per_core, + "gpus_per_task": int(gpus_per_worker / cores_per_worker), + "oversubscribe": oversubscribe, + "init_function": init_function, + "cwd": cwd, + }, + ) + self._process.start() + + +class PySlurmSingleTaskExecutor(ExecutorBase): + """ + The pympipool.slurm.PySlurmSingleTaskExecutor is the internal worker for the pympipool.slurm.PySlurmExecutor. + + Args: + cores (int): defines the number of MPI ranks to use for each function call + threads_per_core (int): number of OpenMP threads to be used for each function call + gpus_per_task (int): number of GPUs per MPI rank - defaults to 0 + oversubscribe (bool): adds the `--oversubscribe` command line flag (OpenMPI only) - default False + init_function (None): optional function to preset arguments for functions which are submitted later + cwd (str/None): current working directory where the parallel python task is executed + + """ + + def __init__( + self, + cores=1, + threads_per_core=1, + gpus_per_task=0, + oversubscribe=False, + init_function=None, + cwd=None, + ): + super().__init__() + self._process = RaisingThread( + target=execute_parallel_tasks, + kwargs={ + # Executor Arguments + "future_queue": self._future_queue, + "cores": cores, + "interface_class": SrunInterface, + # Interface Arguments + "threads_per_core": threads_per_core, + "gpus_per_core": gpus_per_task, + "cwd": cwd, + "oversubscribe": oversubscribe, + }, + ) + self._process.start() + self._set_init_function(init_function=init_function) + cloudpickle_register(ind=3) diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 00000000..98335502 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,50 @@ +[build-system] +requires = ["cloudpickle", "mpi4py", "pyzmq", "setuptools", "tqdm", "versioneer[toml]==0.29"] +build-backend = "setuptools.build_meta" + +[project] +name = "pympipool" +description = "Scale serial and MPI-parallel python functions over hundreds of compute nodes all from within a jupyter notebook or serial python process." +authors = [ + { name = "Jan Janssen", email = "janssen@lanl.gov" }, +] +readme = "README.md" +license = { file = "LICENSE" } +keywords = ["pyiron"] +requires-python = ">=3.8" +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Topic :: Scientific/Engineering :: Physics", + "License :: OSI Approved :: BSD License", + "Intended Audience :: Science/Research", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", +] +dependencies = [ + "cloudpickle==3.0.0", + "mpi4py==3.1.5", + "pyzmq==25.1.2", + "tqdm==4.66.1", +] +dynamic = ["version"] + +[project.urls] +Homepage = "https://github.com/pyiron/pympipool" +Documentation = "https://pympipool.readthedocs.io" +Repository = "https://github.com/pyiron/pympipool" + +[tool.setuptools.packages.find] +include = ["pympipool*"] + +[tool.setuptools.dynamic] +version = {attr = "pympipool.__version__"} + +[tool.versioneer] +VCS = "git" +style = "pep440-pre" +versionfile_source = "pympipool/_version.py" +parentdir_prefix = "pympipool" +tag_prefix = "pympipool-" diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index ea01e101..00000000 --- a/setup.cfg +++ /dev/null @@ -1,12 +0,0 @@ - -# See the docstring in versioneer.py for instructions. Note that you must -# re-run 'versioneer.py setup' after changing this section, and commit the -# resulting files. - -[versioneer] -VCS = git -style = pep440-pre -versionfile_source = pympipool/_version.py -#versionfile_build = -tag_prefix = pympipool- -parentdir_prefix = pympipool diff --git a/setup.py b/setup.py index 9ee0f78d..edb08a34 100644 --- a/setup.py +++ b/setup.py @@ -1,37 +1,8 @@ -""" -Setuptools based setup module -""" -from setuptools import setup, find_packages -from pathlib import Path -import versioneer +from setuptools import setup +import versioneer setup( - name='pympipool', version=versioneer.get_version(), - description='pympipool - scale python functions over multiple compute nodes', - long_description=Path("README.md").read_text(), - long_description_content_type='text/markdown', - url='https://github.com/jan-janssen/pympipool', - author_email='jan.janssen@outlook.com', - license='BSD', - - classifiers=[ - 'Development Status :: 5 - Production/Stable', - 'License :: OSI Approved :: BSD License', - 'Intended Audience :: Science/Research', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Programming Language :: Python :: 3.11' - ], - packages=find_packages(exclude=["*tests*", "*.ci_support*"]), - install_requires=[ - 'cloudpickle==2.2.1', - 'mpi4py==3.1.4', - 'tqdm==4.66.1', - 'pyzmq==25.1.1', - ], cmdclass=versioneer.get_cmdclass(), -) +) \ No newline at end of file diff --git a/tests/executables/count.py b/tests/executables/count.py new file mode 100644 index 00000000..3e65d51e --- /dev/null +++ b/tests/executables/count.py @@ -0,0 +1,13 @@ +def count(iterations): + for i in range(int(iterations)): + print(i) + print("done") + + +if __name__ == "__main__": + while True: + user_input = input() + if "shutdown" in user_input: + break + else: + count(iterations=int(user_input)) \ No newline at end of file diff --git a/tests/test_flux.py b/tests/test_flux.py index 4d84511d..c5313e0e 100644 --- a/tests/test_flux.py +++ b/tests/test_flux.py @@ -1,4 +1,5 @@ from concurrent.futures import Future +import os from queue import Queue import numpy as np @@ -15,7 +16,7 @@ FluxPythonInterface, ) - skip_flux_test = False + skip_flux_test = "FLUX_URI" not in os.environ except ImportError: skip_flux_test = True diff --git a/tests/test_future.py b/tests/test_future.py index 1d59d4ee..426d0156 100644 --- a/tests/test_future.py +++ b/tests/test_future.py @@ -27,3 +27,88 @@ def test_pool_serial_multi_core(self): sleep(1) self.assertTrue(output.done()) self.assertEqual(output.result(), [np.array(4), np.array(4)]) + + def test_independence_from_executor(self): + """ + Ensure that futures are able to live on after the executor gets garbage + collected. + """ + + with self.subTest("From the main process"): + mutable = [] + + def slow_callable(): + from time import sleep + sleep(1) + return True + + def callback(future): + mutable.append("Called back") + + def submit(): + # Executor only exists in this scope and can get garbage collected after + # this function is exits + future = PyMPISingleTaskExecutor().submit(slow_callable) + future.add_done_callback(callback) + return future + + self.assertListEqual( + [], + mutable, + msg="Sanity check that test is starting in the expected condition" + ) + future = submit() + + self.assertFalse( + future.done(), + msg="The submit function is slow, it should be running still" + ) + self.assertListEqual( + [], + mutable, + msg="While running, the mutable should not have been impacted by the " + "callback" + ) + future.result() # Wait for the calculation to finish + self.assertListEqual( + ["Called back"], + mutable, + msg="After completion, the callback should modify the mutable data" + ) + + with self.subTest("From inside a class"): + class Foo: + def __init__(self): + self.running = False + + def run(self): + self.running = True + + future = PyMPISingleTaskExecutor().submit(self.return_42) + future.add_done_callback(self.finished) + + return future + + def return_42(self): + from time import sleep + sleep(1) + return 42 + + def finished(self, future): + self.running = False + + foo = Foo() + self.assertFalse( + foo.running, + msg="Sanity check that the test starts in the expected condition" + ) + fs = foo.run() + self.assertTrue( + foo.running, + msg="We should be able to exit the run method before the task completes" + ) + fs.result() # Wait for completion + self.assertFalse( + foo.running, + msg="After task completion, we expect the callback to modify the class" + ) \ No newline at end of file diff --git a/tests/test_interface.py b/tests/test_interface.py index 149e5f03..b8cac32e 100644 --- a/tests/test_interface.py +++ b/tests/test_interface.py @@ -18,7 +18,7 @@ def test_interface(self): task_dict = {"fn": calc, "args": (), "kwargs": {"i": 2}} interface = SocketInterface( interface=MpiExecInterface( - cwd=None, cores=1, gpus_per_core=0, oversubscribe=False + cwd=None, cores=1, oversubscribe=False ) ) interface.bootup( diff --git a/tests/test_meta.py b/tests/test_meta.py index 643883c8..1bba9a07 100644 --- a/tests/test_meta.py +++ b/tests/test_meta.py @@ -110,7 +110,7 @@ def test_meta_executor_parallel(self): self.assertTrue(fs_1.done()) def test_errors(self): - with self.assertRaises(ValueError): + with self.assertRaises(TypeError): PyMPIExecutor(max_workers=1, cores_per_worker=1, threads_per_core=2) - with self.assertRaises(ValueError): + with self.assertRaises(TypeError): PyMPIExecutor(max_workers=1, cores_per_worker=1, gpus_per_worker=1) diff --git a/tests/test_parse.py b/tests/test_parse.py index 32123162..eaa953d1 100644 --- a/tests/test_parse.py +++ b/tests/test_parse.py @@ -2,7 +2,7 @@ import sys import unittest from pympipool.shared.backend import parse_arguments -from pympipool.shared.interface import SlurmSubprocessInterface, MpiExecInterface +from pympipool.shared.interface import SrunInterface, MpiExecInterface class TestParser(unittest.TestCase): @@ -22,7 +22,7 @@ def test_command_local(self): result_dict["zmqport"], ] interface = MpiExecInterface( - cwd=None, cores=2, gpus_per_core=0, oversubscribe=True + cwd=None, cores=2, oversubscribe=True ) self.assertEqual( command_lst, @@ -32,13 +32,6 @@ def test_command_local(self): ) self.assertEqual(result_dict, parse_arguments(command_lst)) - def test_mpiexec_gpu(self): - interface = MpiExecInterface( - cwd=os.path.abspath("."), cores=2, gpus_per_core=1, oversubscribe=True - ) - with self.assertRaises(ValueError): - interface.bootup(command_lst=[]) - def test_command_slurm(self): result_dict = { "host": "127.0.0.1", @@ -59,7 +52,7 @@ def test_command_slurm(self): "--zmqport", result_dict["zmqport"], ] - interface = SlurmSubprocessInterface( + interface = SrunInterface( cwd=os.path.abspath("."), cores=2, gpus_per_core=1, oversubscribe=True ) self.assertEqual( diff --git a/tests/test_shell_interactive.py b/tests/test_shell_interactive.py new file mode 100644 index 00000000..3c98cd6a --- /dev/null +++ b/tests/test_shell_interactive.py @@ -0,0 +1,39 @@ +from concurrent.futures import Future +import os +import queue + +from unittest import TestCase + +from pympipool.shell.interactive import ShellExecutor, execute_single_task + + +class ShellInteractiveExecutorTest(TestCase): + def setUp(self): + self.executable_path = os.path.join(os.path.dirname(__file__), "executables", "count.py") + + def test_execute_single_task(self): + test_queue = queue.Queue() + future_lines = Future() + future_pattern = Future() + test_queue.put({"init": True, "args": [["python", self.executable_path]], "kwargs": {"universal_newlines": True}}) + test_queue.put({"future": future_lines, "input": "4\n", "lines_to_read": 5, "stop_read_pattern": None}) + test_queue.put({"future": future_pattern, "input": "4\n", "lines_to_read": None, "stop_read_pattern": "done"}) + test_queue.put({"shutdown": True}) + self.assertFalse(future_lines.done()) + self.assertFalse(future_pattern.done()) + execute_single_task(future_queue=test_queue) + self.assertTrue(future_lines.done()) + self.assertTrue(future_pattern.done()) + self.assertEqual("0\n1\n2\n3\ndone\n", future_lines.result()) + self.assertEqual("0\n1\n2\n3\ndone\n", future_pattern.result()) + + def test_shell_interactive_executor(self): + with ShellExecutor(["python", self.executable_path], universal_newlines=True) as exe: + future_lines = exe.submit(string_input="4", lines_to_read=5, stop_read_pattern=None) + future_pattern = exe.submit(string_input="4", lines_to_read=None, stop_read_pattern="done") + self.assertFalse(future_lines.done()) + self.assertFalse(future_pattern.done()) + self.assertEqual("0\n1\n2\n3\ndone\n", future_lines.result()) + self.assertEqual("0\n1\n2\n3\ndone\n", future_pattern.result()) + self.assertTrue(future_lines.done()) + self.assertTrue(future_pattern.done()) diff --git a/tests/test_subprocess_executor.py b/tests/test_subprocess_executor.py new file mode 100644 index 00000000..209dffb2 --- /dev/null +++ b/tests/test_subprocess_executor.py @@ -0,0 +1,62 @@ +from concurrent.futures import Future +import queue + +from unittest import TestCase + +from pympipool.shell.executor import SubprocessSingleExecutor, SubprocessExecutor, execute_single_task + + +class SubprocessExecutorTest(TestCase): + def test_execute_single_task(self): + test_queue = queue.Queue() + f = Future() + test_queue.put({"future": f, "args": [["echo", "test"]], "kwargs": {"universal_newlines": True}}) + test_queue.put({"shutdown": True}) + self.assertFalse(f.done()) + execute_single_task(future_queue=test_queue) + self.assertTrue(f.done()) + self.assertEqual("test\n", f.result()) + + def test_shell_static_executor_args(self): + with SubprocessSingleExecutor() as exe: + future = exe.submit(["echo", "test"], universal_newlines=True, shell=False) + self.assertFalse(future.done()) + self.assertEqual("test\n", future.result()) + self.assertTrue(future.done()) + + def test_shell_static_executor_binary(self): + with SubprocessSingleExecutor() as exe: + future = exe.submit(["echo", "test"], universal_newlines=False, shell=False) + self.assertFalse(future.done()) + self.assertEqual(b"test\n", future.result()) + self.assertTrue(future.done()) + + def test_shell_static_executor_shell(self): + with SubprocessSingleExecutor() as exe: + future = exe.submit("echo test", universal_newlines=True, shell=True) + self.assertFalse(future.done()) + self.assertEqual("test\n", future.result()) + self.assertTrue(future.done()) + + def test_shell_executor(self): + with SubprocessExecutor(max_workers=2) as exe: + f_1 = exe.submit(["echo", "test_1"], universal_newlines=True) + f_2 = exe.submit(["echo", "test_2"], universal_newlines=True) + f_3 = exe.submit(["echo", "test_3"], universal_newlines=True) + f_4 = exe.submit(["echo", "test_4"], universal_newlines=True) + self.assertFalse(f_1.done()) + self.assertFalse(f_2.done()) + self.assertFalse(f_3.done()) + self.assertFalse(f_4.done()) + self.assertEqual("test_1\n", f_1.result()) + self.assertEqual("test_2\n", f_2.result()) + self.assertTrue(f_1.done()) + self.assertTrue(f_2.done()) + self.assertFalse(f_3.done()) + self.assertFalse(f_4.done()) + self.assertEqual("test_3\n", f_3.result()) + self.assertEqual("test_4\n", f_4.result()) + self.assertTrue(f_1.done()) + self.assertTrue(f_2.done()) + self.assertTrue(f_3.done()) + self.assertTrue(f_4.done()) diff --git a/tests/test_with_dynamic_objects.py b/tests/test_with_dynamic_objects.py new file mode 100644 index 00000000..29494857 --- /dev/null +++ b/tests/test_with_dynamic_objects.py @@ -0,0 +1,236 @@ +""" +The purpose of these tests is the check executor behaviour when the python objects +are dynamically generated. +This is a special (and rather difficult) case for serializing objects which cannot +be pickled using the standard pickle module, and thus poses a relatively thorough test +for the general un-pickle-able case. +""" +from concurrent.futures._base import TimeoutError as cfbTimeoutError +from functools import partialmethod +from time import sleep +import unittest + +from pympipool import Executor + + +class Foo: + """ + A base class to be dynamically modified for putting an executor/serializer through + its paces. + """ + def __init__(self, fnc: callable): + self.fnc = fnc + self.result = None + self.running = False + + @property + def run(self): + self.running = True + return self.fnc + + def process_result(self, future): + self.result = future.result() + self.running = False + + +def dynamic_foo(): + """ + A decorator for dynamically modifying the Foo class to test + CloudpickleProcessPoolExecutor. + + Overrides the `fnc` input of `Foo` with the decorated function. + """ + def as_dynamic_foo(fnc: callable): + return type( + "DynamicFoo", + (Foo,), # Define parentage + { + "__init__": partialmethod( + Foo.__init__, + fnc + ) + }, + ) + + return as_dynamic_foo + + +class TestDynamicallyDefinedObjects(unittest.TestCase): + def test_args(self): + """ + We should be able to use a dynamically defined return value. + """ + + @dynamic_foo() + def does_nothing(): + return + + @dynamic_foo() + def slowly_returns_dynamic(dynamic_arg): + """ + Returns a complex, dynamically defined variable + """ + sleep(0.1) + dynamic_arg.attribute_on_dynamic = "attribute updated" + return dynamic_arg + + dynamic_dynamic = slowly_returns_dynamic() + executor = Executor() + dynamic_object = does_nothing() + fs = executor.submit(dynamic_dynamic.run, dynamic_object) + self.assertEqual( + fs.result().attribute_on_dynamic, + "attribute updated", + msg="The submit callable should have modified the mutable, dynamically " + "defined object with a new attribute." + ) + + def test_callable(self): + """ + We should be able to use a dynamic callable -- in this case, a method of + a dynamically defined class. + """ + fortytwo = 42 # No magic numbers; we use it in a couple places so give it a var + + @dynamic_foo() + def slowly_returns_42(): + sleep(0.1) + return fortytwo + + dynamic_42 = slowly_returns_42() # Instantiate the dynamically defined class + self.assertIsInstance( + dynamic_42, + Foo, + msg="Just a sanity check that the test is set up right" + ) + self.assertIsNone( + dynamic_42.result, + msg="Just a sanity check that the test is set up right" + ) + executor = Executor() + fs = executor.submit(dynamic_42.run) + fs.add_done_callback(dynamic_42.process_result) + self.assertFalse( + fs.done(), + msg="The submit callable sleeps long enough that we expect to still be " + "running here -- did something fail to get submit to an executor??" + ) + self.assertEqual( + fortytwo, + fs.result(), + msg="The future is expected to behave as usual" + ) + self.assertEqual( + fortytwo, + dynamic_42.result, + msg="The callback modifies its object and should run by the time the result" + "is available -- did it fail to get called?" + ) + + def test_callback(self): + """Make sure the callback methods can modify their owners""" + + @dynamic_foo() + def returns_42(): + return 42 + + dynamic_42 = returns_42() + self.assertFalse( + dynamic_42.running, + msg="Sanity check that the test starts in the expected condition" + ) + executor = Executor() + fs = executor.submit(dynamic_42.run) + fs.add_done_callback(dynamic_42.process_result) + self.assertTrue( + dynamic_42.running, + msg="Submit method need to be able to modify their owners" + ) + fs.result() # Wait for the process to finish + self.assertFalse( + dynamic_42.running, + msg="Callback methods need to be able to modify their owners" + ) + + def test_exception(self): + """ + Exceptions from dynamically defined callables should get cleanly raised. + """ + + @dynamic_foo() + def raise_error(): + raise RuntimeError + + re = raise_error() + executor = Executor() + fs = executor.submit(re.run) + with self.assertRaises( + RuntimeError, + msg="The callable just raises an error -- this should get shown to the user" + ): + fs.result() + + def test_return(self): + """ + We should be able to use a dynamic return value -- in this case, a + method of a dynamically defined class. + """ + + @dynamic_foo() + def does_nothing(): + return + + @dynamic_foo() + def slowly_returns_dynamic(): + """ + Returns a complex, dynamically defined variable + """ + sleep(0.1) + inside_variable = does_nothing() + inside_variable.result = "it was an inside job!" + return inside_variable + + dynamic_dynamic = slowly_returns_dynamic() + executor = Executor() + fs = executor.submit(dynamic_dynamic.run) + self.assertIsInstance( + fs.result(), + Foo, + msg="Just a sanity check that we're getting the right type of dynamically " + "defined type of object" + ) + self.assertEqual( + fs.result().result, + "it was an inside job!", + msg="The submit callable modifies the object that owns it, and this should" + "be reflected in the main process after deserialziation" + ) + + def test_timeout(self): + """ + Timeouts for dynamically defined callables should be handled ok. + """ + + fortytwo = 42 + + @dynamic_foo() + def slow(): + sleep(0.1) + return fortytwo + + f = slow() + executor = Executor() + fs = executor.submit(f.run) + self.assertEqual( + fs.result(timeout=30), + fortytwo, + msg="waiting long enough should get the result" + ) + + with self.assertRaises( + (TimeoutError, cfbTimeoutError), + msg="With a timeout time smaller than our submit callable's sleep time, " + "we had better get an exception!" + ): + fs = executor.submit(f.run) + fs.result(timeout=0.0001) diff --git a/tests/test_worker.py b/tests/test_worker.py index 5bc26747..386fb16f 100644 --- a/tests/test_worker.py +++ b/tests/test_worker.py @@ -3,7 +3,7 @@ from queue import Queue from time import sleep from concurrent.futures import CancelledError -from pympipool.mpi.executor import PyMPISingleTaskExecutor, get_interface +from pympipool.mpi.executor import PyMPISingleTaskExecutor, MpiExecInterface from pympipool.shared.executorbase import cloudpickle_register, execute_parallel_tasks from concurrent.futures import Future @@ -107,7 +107,7 @@ def test_execute_task_failed_no_argument(self): future_queue=q, cores=1, oversubscribe=False, - interface_class=get_interface, + interface_class=MpiExecInterface, ) q.join() @@ -121,7 +121,7 @@ def test_execute_task_failed_wrong_argument(self): future_queue=q, cores=1, oversubscribe=False, - interface_class=get_interface, + interface_class=MpiExecInterface, ) q.join() @@ -135,7 +135,7 @@ def test_execute_task(self): future_queue=q, cores=1, oversubscribe=False, - interface_class=get_interface, + interface_class=MpiExecInterface, ) self.assertEqual(f.result(), np.array(4)) q.join() @@ -150,7 +150,7 @@ def test_execute_task_parallel(self): future_queue=q, cores=2, oversubscribe=False, - interface_class=get_interface, + interface_class=MpiExecInterface, ) self.assertEqual(f.result(), [np.array(4), np.array(4)]) q.join() diff --git a/tests/test_worker_memory.py b/tests/test_worker_memory.py index f8aaa7cb..2d4da738 100644 --- a/tests/test_worker_memory.py +++ b/tests/test_worker_memory.py @@ -3,7 +3,7 @@ from queue import Queue from pympipool.shared.backend import call_funct from pympipool.shared.executorbase import cloudpickle_register, execute_parallel_tasks -from pympipool.mpi.executor import PyMPISingleTaskExecutor, get_interface +from pympipool.mpi.executor import PyMPISingleTaskExecutor, MpiExecInterface from concurrent.futures import Future @@ -43,7 +43,7 @@ def test_execute_task(self): future_queue=q, cores=1, oversubscribe=False, - interface_class=get_interface, + interface_class=MpiExecInterface, ) self.assertEqual(f.result(), np.array([5])) q.join() diff --git a/versioneer.py b/versioneer.py deleted file mode 100644 index 1e3753e6..00000000 --- a/versioneer.py +++ /dev/null @@ -1,2277 +0,0 @@ - -# Version: 0.29 - -"""The Versioneer - like a rocketeer, but for versions. - -The Versioneer -============== - -* like a rocketeer, but for versions! -* https://github.com/python-versioneer/python-versioneer -* Brian Warner -* License: Public Domain (Unlicense) -* Compatible with: Python 3.7, 3.8, 3.9, 3.10, 3.11 and pypy3 -* [![Latest Version][pypi-image]][pypi-url] -* [![Build Status][travis-image]][travis-url] - -This is a tool for managing a recorded version number in setuptools-based -python projects. The goal is to remove the tedious and error-prone "update -the embedded version string" step from your release process. Making a new -release should be as easy as recording a new tag in your version-control -system, and maybe making new tarballs. - - -## Quick Install - -Versioneer provides two installation modes. The "classic" vendored mode installs -a copy of versioneer into your repository. The experimental build-time dependency mode -is intended to allow you to skip this step and simplify the process of upgrading. - -### Vendored mode - -* `pip install versioneer` to somewhere in your $PATH - * A [conda-forge recipe](https://github.com/conda-forge/versioneer-feedstock) is - available, so you can also use `conda install -c conda-forge versioneer` -* add a `[tool.versioneer]` section to your `pyproject.toml` or a - `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md)) - * Note that you will need to add `tomli; python_version < "3.11"` to your - build-time dependencies if you use `pyproject.toml` -* run `versioneer install --vendor` in your source tree, commit the results -* verify version information with `python setup.py version` - -### Build-time dependency mode - -* `pip install versioneer` to somewhere in your $PATH - * A [conda-forge recipe](https://github.com/conda-forge/versioneer-feedstock) is - available, so you can also use `conda install -c conda-forge versioneer` -* add a `[tool.versioneer]` section to your `pyproject.toml` or a - `[versioneer]` section to your `setup.cfg` (see [Install](INSTALL.md)) -* add `versioneer` (with `[toml]` extra, if configuring in `pyproject.toml`) - to the `requires` key of the `build-system` table in `pyproject.toml`: - ```toml - [build-system] - requires = ["setuptools", "versioneer[toml]"] - build-backend = "setuptools.build_meta" - ``` -* run `versioneer install --no-vendor` in your source tree, commit the results -* verify version information with `python setup.py version` - -## Version Identifiers - -Source trees come from a variety of places: - -* a version-control system checkout (mostly used by developers) -* a nightly tarball, produced by build automation -* a snapshot tarball, produced by a web-based VCS browser, like github's - "tarball from tag" feature -* a release tarball, produced by "setup.py sdist", distributed through PyPI - -Within each source tree, the version identifier (either a string or a number, -this tool is format-agnostic) can come from a variety of places: - -* ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows - about recent "tags" and an absolute revision-id -* the name of the directory into which the tarball was unpacked -* an expanded VCS keyword ($Id$, etc) -* a `_version.py` created by some earlier build step - -For released software, the version identifier is closely related to a VCS -tag. Some projects use tag names that include more than just the version -string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool -needs to strip the tag prefix to extract the version identifier. For -unreleased software (between tags), the version identifier should provide -enough information to help developers recreate the same tree, while also -giving them an idea of roughly how old the tree is (after version 1.2, before -version 1.3). Many VCS systems can report a description that captures this, -for example `git describe --tags --dirty --always` reports things like -"0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the -0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has -uncommitted changes). - -The version identifier is used for multiple purposes: - -* to allow the module to self-identify its version: `myproject.__version__` -* to choose a name and prefix for a 'setup.py sdist' tarball - -## Theory of Operation - -Versioneer works by adding a special `_version.py` file into your source -tree, where your `__init__.py` can import it. This `_version.py` knows how to -dynamically ask the VCS tool for version information at import time. - -`_version.py` also contains `$Revision$` markers, and the installation -process marks `_version.py` to have this marker rewritten with a tag name -during the `git archive` command. As a result, generated tarballs will -contain enough information to get the proper version. - -To allow `setup.py` to compute a version too, a `versioneer.py` is added to -the top level of your source tree, next to `setup.py` and the `setup.cfg` -that configures it. This overrides several distutils/setuptools commands to -compute the version when invoked, and changes `setup.py build` and `setup.py -sdist` to replace `_version.py` with a small static file that contains just -the generated version data. - -## Installation - -See [INSTALL.md](./INSTALL.md) for detailed installation instructions. - -## Version-String Flavors - -Code which uses Versioneer can learn about its version string at runtime by -importing `_version` from your main `__init__.py` file and running the -`get_versions()` function. From the "outside" (e.g. in `setup.py`), you can -import the top-level `versioneer.py` and run `get_versions()`. - -Both functions return a dictionary with different flavors of version -information: - -* `['version']`: A condensed version string, rendered using the selected - style. This is the most commonly used value for the project's version - string. The default "pep440" style yields strings like `0.11`, - `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section - below for alternative styles. - -* `['full-revisionid']`: detailed revision identifier. For Git, this is the - full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". - -* `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the - commit date in ISO 8601 format. This will be None if the date is not - available. - -* `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that - this is only accurate if run in a VCS checkout, otherwise it is likely to - be False or None - -* `['error']`: if the version string could not be computed, this will be set - to a string describing the problem, otherwise it will be None. It may be - useful to throw an exception in setup.py if this is set, to avoid e.g. - creating tarballs with a version string of "unknown". - -Some variants are more useful than others. Including `full-revisionid` in a -bug report should allow developers to reconstruct the exact code being tested -(or indicate the presence of local changes that should be shared with the -developers). `version` is suitable for display in an "about" box or a CLI -`--version` output: it can be easily compared against release notes and lists -of bugs fixed in various releases. - -The installer adds the following text to your `__init__.py` to place a basic -version in `YOURPROJECT.__version__`: - - from ._version import get_versions - __version__ = get_versions()['version'] - del get_versions - -## Styles - -The setup.cfg `style=` configuration controls how the VCS information is -rendered into a version string. - -The default style, "pep440", produces a PEP440-compliant string, equal to the -un-prefixed tag name for actual releases, and containing an additional "local -version" section with more detail for in-between builds. For Git, this is -TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags ---dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the -tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and -that this commit is two revisions ("+2") beyond the "0.11" tag. For released -software (exactly equal to a known tag), the identifier will only contain the -stripped tag, e.g. "0.11". - -Other styles are available. See [details.md](details.md) in the Versioneer -source tree for descriptions. - -## Debugging - -Versioneer tries to avoid fatal errors: if something goes wrong, it will tend -to return a version of "0+unknown". To investigate the problem, run `setup.py -version`, which will run the version-lookup code in a verbose mode, and will -display the full contents of `get_versions()` (including the `error` string, -which may help identify what went wrong). - -## Known Limitations - -Some situations are known to cause problems for Versioneer. This details the -most significant ones. More can be found on Github -[issues page](https://github.com/python-versioneer/python-versioneer/issues). - -### Subprojects - -Versioneer has limited support for source trees in which `setup.py` is not in -the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are -two common reasons why `setup.py` might not be in the root: - -* Source trees which contain multiple subprojects, such as - [Buildbot](https://github.com/buildbot/buildbot), which contains both - "master" and "slave" subprojects, each with their own `setup.py`, - `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI - distributions (and upload multiple independently-installable tarballs). -* Source trees whose main purpose is to contain a C library, but which also - provide bindings to Python (and perhaps other languages) in subdirectories. - -Versioneer will look for `.git` in parent directories, and most operations -should get the right version string. However `pip` and `setuptools` have bugs -and implementation details which frequently cause `pip install .` from a -subproject directory to fail to find a correct version string (so it usually -defaults to `0+unknown`). - -`pip install --editable .` should work correctly. `setup.py install` might -work too. - -Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in -some later version. - -[Bug #38](https://github.com/python-versioneer/python-versioneer/issues/38) is tracking -this issue. The discussion in -[PR #61](https://github.com/python-versioneer/python-versioneer/pull/61) describes the -issue from the Versioneer side in more detail. -[pip PR#3176](https://github.com/pypa/pip/pull/3176) and -[pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve -pip to let Versioneer work correctly. - -Versioneer-0.16 and earlier only looked for a `.git` directory next to the -`setup.cfg`, so subprojects were completely unsupported with those releases. - -### Editable installs with setuptools <= 18.5 - -`setup.py develop` and `pip install --editable .` allow you to install a -project into a virtualenv once, then continue editing the source code (and -test) without re-installing after every change. - -"Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a -convenient way to specify executable scripts that should be installed along -with the python package. - -These both work as expected when using modern setuptools. When using -setuptools-18.5 or earlier, however, certain operations will cause -`pkg_resources.DistributionNotFound` errors when running the entrypoint -script, which must be resolved by re-installing the package. This happens -when the install happens with one version, then the egg_info data is -regenerated while a different version is checked out. Many setup.py commands -cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into -a different virtualenv), so this can be surprising. - -[Bug #83](https://github.com/python-versioneer/python-versioneer/issues/83) describes -this one, but upgrading to a newer version of setuptools should probably -resolve it. - - -## Updating Versioneer - -To upgrade your project to a new release of Versioneer, do the following: - -* install the new Versioneer (`pip install -U versioneer` or equivalent) -* edit `setup.cfg` and `pyproject.toml`, if necessary, - to include any new configuration settings indicated by the release notes. - See [UPGRADING](./UPGRADING.md) for details. -* re-run `versioneer install --[no-]vendor` in your source tree, to replace - `SRC/_version.py` -* commit any changed files - -## Future Directions - -This tool is designed to make it easily extended to other version-control -systems: all VCS-specific components are in separate directories like -src/git/ . The top-level `versioneer.py` script is assembled from these -components by running make-versioneer.py . In the future, make-versioneer.py -will take a VCS name as an argument, and will construct a version of -`versioneer.py` that is specific to the given VCS. It might also take the -configuration arguments that are currently provided manually during -installation by editing setup.py . Alternatively, it might go the other -direction and include code from all supported VCS systems, reducing the -number of intermediate scripts. - -## Similar projects - -* [setuptools_scm](https://github.com/pypa/setuptools_scm/) - a non-vendored build-time - dependency -* [minver](https://github.com/jbweston/miniver) - a lightweight reimplementation of - versioneer -* [versioningit](https://github.com/jwodder/versioningit) - a PEP 518-based setuptools - plugin - -## License - -To make Versioneer easier to embed, all its code is dedicated to the public -domain. The `_version.py` that it creates is also in the public domain. -Specifically, both are released under the "Unlicense", as described in -https://unlicense.org/. - -[pypi-image]: https://img.shields.io/pypi/v/versioneer.svg -[pypi-url]: https://pypi.python.org/pypi/versioneer/ -[travis-image]: -https://img.shields.io/travis/com/python-versioneer/python-versioneer.svg -[travis-url]: https://travis-ci.com/github/python-versioneer/python-versioneer - -""" -# pylint:disable=invalid-name,import-outside-toplevel,missing-function-docstring -# pylint:disable=missing-class-docstring,too-many-branches,too-many-statements -# pylint:disable=raise-missing-from,too-many-lines,too-many-locals,import-error -# pylint:disable=too-few-public-methods,redefined-outer-name,consider-using-with -# pylint:disable=attribute-defined-outside-init,too-many-arguments - -import configparser -import errno -import json -import os -import re -import subprocess -import sys -from pathlib import Path -from typing import Any, Callable, cast, Dict, List, Optional, Tuple, Union -from typing import NoReturn -import functools - -have_tomllib = True -if sys.version_info >= (3, 11): - import tomllib -else: - try: - import tomli as tomllib - except ImportError: - have_tomllib = False - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - VCS: str - style: str - tag_prefix: str - versionfile_source: str - versionfile_build: Optional[str] - parentdir_prefix: Optional[str] - verbose: Optional[bool] - - -def get_root() -> str: - """Get the project root directory. - - We require that all commands are run from the project root, i.e. the - directory that contains setup.py, setup.cfg, and versioneer.py . - """ - root = os.path.realpath(os.path.abspath(os.getcwd())) - setup_py = os.path.join(root, "setup.py") - pyproject_toml = os.path.join(root, "pyproject.toml") - versioneer_py = os.path.join(root, "versioneer.py") - if not ( - os.path.exists(setup_py) - or os.path.exists(pyproject_toml) - or os.path.exists(versioneer_py) - ): - # allow 'python path/to/setup.py COMMAND' - root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) - setup_py = os.path.join(root, "setup.py") - pyproject_toml = os.path.join(root, "pyproject.toml") - versioneer_py = os.path.join(root, "versioneer.py") - if not ( - os.path.exists(setup_py) - or os.path.exists(pyproject_toml) - or os.path.exists(versioneer_py) - ): - err = ("Versioneer was unable to run the project root directory. " - "Versioneer requires setup.py to be executed from " - "its immediate directory (like 'python setup.py COMMAND'), " - "or in a way that lets it use sys.argv[0] to find the root " - "(like 'python path/to/setup.py COMMAND').") - raise VersioneerBadRootError(err) - try: - # Certain runtime workflows (setup.py install/develop in a setuptools - # tree) execute all dependencies in a single python process, so - # "versioneer" may be imported multiple times, and python's shared - # module-import table will cache the first one. So we can't use - # os.path.dirname(__file__), as that will find whichever - # versioneer.py was first imported, even in later projects. - my_path = os.path.realpath(os.path.abspath(__file__)) - me_dir = os.path.normcase(os.path.splitext(my_path)[0]) - vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) - if me_dir != vsr_dir and "VERSIONEER_PEP518" not in globals(): - print("Warning: build in %s is using versioneer.py from %s" - % (os.path.dirname(my_path), versioneer_py)) - except NameError: - pass - return root - - -def get_config_from_root(root: str) -> VersioneerConfig: - """Read the project setup.cfg file to determine Versioneer config.""" - # This might raise OSError (if setup.cfg is missing), or - # configparser.NoSectionError (if it lacks a [versioneer] section), or - # configparser.NoOptionError (if it lacks "VCS="). See the docstring at - # the top of versioneer.py for instructions on writing your setup.cfg . - root_pth = Path(root) - pyproject_toml = root_pth / "pyproject.toml" - setup_cfg = root_pth / "setup.cfg" - section: Union[Dict[str, Any], configparser.SectionProxy, None] = None - if pyproject_toml.exists() and have_tomllib: - try: - with open(pyproject_toml, 'rb') as fobj: - pp = tomllib.load(fobj) - section = pp['tool']['versioneer'] - except (tomllib.TOMLDecodeError, KeyError) as e: - print(f"Failed to load config from {pyproject_toml}: {e}") - print("Try to load it from setup.cfg") - if not section: - parser = configparser.ConfigParser() - with open(setup_cfg) as cfg_file: - parser.read_file(cfg_file) - parser.get("versioneer", "VCS") # raise error if missing - - section = parser["versioneer"] - - # `cast`` really shouldn't be used, but its simplest for the - # common VersioneerConfig users at the moment. We verify against - # `None` values elsewhere where it matters - - cfg = VersioneerConfig() - cfg.VCS = section['VCS'] - cfg.style = section.get("style", "") - cfg.versionfile_source = cast(str, section.get("versionfile_source")) - cfg.versionfile_build = section.get("versionfile_build") - cfg.tag_prefix = cast(str, section.get("tag_prefix")) - if cfg.tag_prefix in ("''", '""', None): - cfg.tag_prefix = "" - cfg.parentdir_prefix = section.get("parentdir_prefix") - if isinstance(section, configparser.SectionProxy): - # Make sure configparser translates to bool - cfg.verbose = section.getboolean("verbose") - else: - cfg.verbose = section.get("verbose") - - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -# these dictionaries contain VCS-specific tools -LONG_VERSION_PY: Dict[str, str] = {} -HANDLERS: Dict[str, Dict[str, Callable]] = {} - - -def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator - """Create decorator to mark a method as the handler of a VCS.""" - def decorate(f: Callable) -> Callable: - """Store f in HANDLERS[vcs][method].""" - HANDLERS.setdefault(vcs, {})[method] = f - return f - return decorate - - -def run_command( - commands: List[str], - args: List[str], - cwd: Optional[str] = None, - verbose: bool = False, - hide_stderr: bool = False, - env: Optional[Dict[str, str]] = None, -) -> Tuple[Optional[str], Optional[int]]: - """Call the given command(s).""" - assert isinstance(commands, list) - process = None - - popen_kwargs: Dict[str, Any] = {} - if sys.platform == "win32": - # This hides the console window if pythonw.exe is used - startupinfo = subprocess.STARTUPINFO() - startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW - popen_kwargs["startupinfo"] = startupinfo - - for command in commands: - try: - dispcmd = str([command] + args) - # remember shell=False, so use git.cmd on windows, not just git - process = subprocess.Popen([command] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None), **popen_kwargs) - break - except OSError as e: - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %s" % dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %s" % (commands,)) - return None, None - stdout = process.communicate()[0].strip().decode() - if process.returncode != 0: - if verbose: - print("unable to run %s (error)" % dispcmd) - print("stdout was %s" % stdout) - return None, process.returncode - return stdout, process.returncode - - -LONG_VERSION_PY['git'] = r''' -# This file helps to compute a version number in source trees obtained from -# git-archive tarball (such as those provided by githubs download-from-tag -# feature). Distribution tarballs (built by setup.py sdist) and build -# directories (produced by setup.py build) will contain a much shorter file -# that just contains the computed version number. - -# This file is released into the public domain. -# Generated by versioneer-0.29 -# https://github.com/python-versioneer/python-versioneer - -"""Git implementation of _version.py.""" - -import errno -import os -import re -import subprocess -import sys -from typing import Any, Callable, Dict, List, Optional, Tuple -import functools - - -def get_keywords() -> Dict[str, str]: - """Get the keywords needed to look up the version information.""" - # these strings will be replaced by git during git-archive. - # setup.py/versioneer.py will grep for the variable names, so they must - # each be defined on a line of their own. _version.py will just call - # get_keywords(). - git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" - git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" - git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" - keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} - return keywords - - -class VersioneerConfig: - """Container for Versioneer configuration parameters.""" - - VCS: str - style: str - tag_prefix: str - parentdir_prefix: str - versionfile_source: str - verbose: bool - - -def get_config() -> VersioneerConfig: - """Create, populate and return the VersioneerConfig() object.""" - # these strings are filled in when 'setup.py versioneer' creates - # _version.py - cfg = VersioneerConfig() - cfg.VCS = "git" - cfg.style = "%(STYLE)s" - cfg.tag_prefix = "%(TAG_PREFIX)s" - cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" - cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" - cfg.verbose = False - return cfg - - -class NotThisMethod(Exception): - """Exception raised if a method is not valid for the current scenario.""" - - -LONG_VERSION_PY: Dict[str, str] = {} -HANDLERS: Dict[str, Dict[str, Callable]] = {} - - -def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator - """Create decorator to mark a method as the handler of a VCS.""" - def decorate(f: Callable) -> Callable: - """Store f in HANDLERS[vcs][method].""" - if vcs not in HANDLERS: - HANDLERS[vcs] = {} - HANDLERS[vcs][method] = f - return f - return decorate - - -def run_command( - commands: List[str], - args: List[str], - cwd: Optional[str] = None, - verbose: bool = False, - hide_stderr: bool = False, - env: Optional[Dict[str, str]] = None, -) -> Tuple[Optional[str], Optional[int]]: - """Call the given command(s).""" - assert isinstance(commands, list) - process = None - - popen_kwargs: Dict[str, Any] = {} - if sys.platform == "win32": - # This hides the console window if pythonw.exe is used - startupinfo = subprocess.STARTUPINFO() - startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW - popen_kwargs["startupinfo"] = startupinfo - - for command in commands: - try: - dispcmd = str([command] + args) - # remember shell=False, so use git.cmd on windows, not just git - process = subprocess.Popen([command] + args, cwd=cwd, env=env, - stdout=subprocess.PIPE, - stderr=(subprocess.PIPE if hide_stderr - else None), **popen_kwargs) - break - except OSError as e: - if e.errno == errno.ENOENT: - continue - if verbose: - print("unable to run %%s" %% dispcmd) - print(e) - return None, None - else: - if verbose: - print("unable to find command, tried %%s" %% (commands,)) - return None, None - stdout = process.communicate()[0].strip().decode() - if process.returncode != 0: - if verbose: - print("unable to run %%s (error)" %% dispcmd) - print("stdout was %%s" %% stdout) - return None, process.returncode - return stdout, process.returncode - - -def versions_from_parentdir( - parentdir_prefix: str, - root: str, - verbose: bool, -) -> Dict[str, Any]: - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for _ in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %%s but none started with prefix %%s" %% - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs: str) -> Dict[str, str]: - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords: Dict[str, str] = {} - try: - with open(versionfile_abs, "r") as fobj: - for line in fobj: - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - except OSError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords( - keywords: Dict[str, str], - tag_prefix: str, - verbose: bool, -) -> Dict[str, Any]: - """Get version information from git keywords.""" - if "refnames" not in keywords: - raise NotThisMethod("Short version file found") - date = keywords.get("date") - if date is not None: - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - - # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = {r.strip() for r in refnames.strip("()").split(",")} - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %%d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = {r for r in refs if re.search(r'\d', r)} - if verbose: - print("discarding '%%s', no digits" %% ",".join(refs - tags)) - if verbose: - print("likely tags: %%s" %% ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - # Filter out refs that exactly match prefix or that don't start - # with a number once the prefix is stripped (mostly a concern - # when prefix is '') - if not re.match(r'\d', r): - continue - if verbose: - print("picking %%s" %% r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs( - tag_prefix: str, - root: str, - verbose: bool, - runner: Callable = run_command -) -> Dict[str, Any]: - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - # GIT_DIR can interfere with correct operation of Versioneer. - # It may be intended to be passed to the Versioneer-versioned project, - # but that should not change where we get our version from. - env = os.environ.copy() - env.pop("GIT_DIR", None) - runner = functools.partial(runner, env=env) - - _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=not verbose) - if rc != 0: - if verbose: - print("Directory %%s not under git control" %% root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = runner(GITS, [ - "describe", "--tags", "--dirty", "--always", "--long", - "--match", f"{tag_prefix}[[:digit:]]*" - ], cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces: Dict[str, Any] = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], - cwd=root) - # --abbrev-ref was added in git-1.6.3 - if rc != 0 or branch_name is None: - raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") - branch_name = branch_name.strip() - - if branch_name == "HEAD": - # If we aren't exactly on a branch, pick a branch which represents - # the current commit. If all else fails, we are on a branchless - # commit. - branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) - # --contains was added in git-1.5.4 - if rc != 0 or branches is None: - raise NotThisMethod("'git branch --contains' returned error") - branches = branches.split("\n") - - # Remove the first line if we're running detached - if "(" in branches[0]: - branches.pop(0) - - # Strip off the leading "* " from the list of branches. - branches = [branch[2:] for branch in branches] - if "master" in branches: - branch_name = "master" - elif not branches: - branch_name = None - else: - # Pick the first branch that is returned. Good or bad. - branch_name = branches[0] - - pieces["branch"] = branch_name - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparsable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%%s'" - %% describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%%s' doesn't start with prefix '%%s'" - print(fmt %% (full_tag, tag_prefix)) - pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" - %% (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) - pieces["distance"] = len(out.split()) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = runner(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip() - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def plus_or_dot(pieces: Dict[str, Any]) -> str: - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces: Dict[str, Any]) -> str: - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_branch(pieces: Dict[str, Any]) -> str: - """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . - - The ".dev0" means not master branch. Note that .dev0 sorts backwards - (a feature branch will appear "older" than the master branch). - - Exceptions: - 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0" - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+untagged.%%d.g%%s" %% (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def pep440_split_post(ver: str) -> Tuple[str, Optional[int]]: - """Split pep440 version string at the post-release segment. - - Returns the release segments before the post-release and the - post-release version number (or -1 if no post-release segment is present). - """ - vc = str.split(ver, ".post") - return vc[0], int(vc[1] or 0) if len(vc) == 2 else None - - -def render_pep440_pre(pieces: Dict[str, Any]) -> str: - """TAG[.postN.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post0.devDISTANCE - """ - if pieces["closest-tag"]: - if pieces["distance"]: - # update the post release segment - tag_version, post_version = pep440_split_post(pieces["closest-tag"]) - rendered = tag_version - if post_version is not None: - rendered += ".post%%d.dev%%d" %% (post_version + 1, pieces["distance"]) - else: - rendered += ".post0.dev%%d" %% (pieces["distance"]) - else: - # no commits, use the tag as the version - rendered = pieces["closest-tag"] - else: - # exception #1 - rendered = "0.post0.dev%%d" %% pieces["distance"] - return rendered - - -def render_pep440_post(pieces: Dict[str, Any]) -> str: - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%%s" %% pieces["short"] - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%%s" %% pieces["short"] - return rendered - - -def render_pep440_post_branch(pieces: Dict[str, Any]) -> str: - """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . - - The ".dev0" means not master branch. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%%s" %% pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+g%%s" %% pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_old(pieces: Dict[str, Any]) -> str: - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%%d" %% pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces: Dict[str, Any]) -> str: - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces: Dict[str, Any]) -> str: - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-branch": - rendered = render_pep440_branch(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-post-branch": - rendered = render_pep440_post_branch(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%%s'" %% style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -def get_versions() -> Dict[str, Any]: - """Get version information or return default if unable to do so.""" - # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have - # __file__, we can work backwards from there to the root. Some - # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which - # case we can only use expanded keywords. - - cfg = get_config() - verbose = cfg.verbose - - try: - return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, - verbose) - except NotThisMethod: - pass - - try: - root = os.path.realpath(__file__) - # versionfile_source is the relative path from the top of the source - # tree (where the .git directory might live) to this file. Invert - # this to find the root from __file__. - for _ in cfg.versionfile_source.split('/'): - root = os.path.dirname(root) - except NameError: - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to find root of source tree", - "date": None} - - try: - pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) - return render(pieces, cfg.style) - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - except NotThisMethod: - pass - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, - "error": "unable to compute version", "date": None} -''' - - -@register_vcs_handler("git", "get_keywords") -def git_get_keywords(versionfile_abs: str) -> Dict[str, str]: - """Extract version information from the given file.""" - # the code embedded in _version.py can just fetch the value of these - # keywords. When used from setup.py, we don't want to import _version.py, - # so we do it with a regexp instead. This function is not used from - # _version.py. - keywords: Dict[str, str] = {} - try: - with open(versionfile_abs, "r") as fobj: - for line in fobj: - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - if line.strip().startswith("git_date ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["date"] = mo.group(1) - except OSError: - pass - return keywords - - -@register_vcs_handler("git", "keywords") -def git_versions_from_keywords( - keywords: Dict[str, str], - tag_prefix: str, - verbose: bool, -) -> Dict[str, Any]: - """Get version information from git keywords.""" - if "refnames" not in keywords: - raise NotThisMethod("Short version file found") - date = keywords.get("date") - if date is not None: - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - - # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant - # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 - # -like" string, which we must then edit to make compliant), because - # it's been around since git-1.5.3, and it's too difficult to - # discover which version we're using, or to work around using an - # older one. - date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - refnames = keywords["refnames"].strip() - if refnames.startswith("$Format"): - if verbose: - print("keywords are unexpanded, not using") - raise NotThisMethod("unexpanded keywords, not a git-archive tarball") - refs = {r.strip() for r in refnames.strip("()").split(",")} - # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of - # just "foo-1.0". If we see a "tag: " prefix, prefer those. - TAG = "tag: " - tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} - if not tags: - # Either we're using git < 1.8.3, or there really are no tags. We use - # a heuristic: assume all version tags have a digit. The old git %d - # expansion behaves like git log --decorate=short and strips out the - # refs/heads/ and refs/tags/ prefixes that would let us distinguish - # between branches and tags. By ignoring refnames without digits, we - # filter out many common branch names like "release" and - # "stabilization", as well as "HEAD" and "master". - tags = {r for r in refs if re.search(r'\d', r)} - if verbose: - print("discarding '%s', no digits" % ",".join(refs - tags)) - if verbose: - print("likely tags: %s" % ",".join(sorted(tags))) - for ref in sorted(tags): - # sorting will prefer e.g. "2.0" over "2.0rc1" - if ref.startswith(tag_prefix): - r = ref[len(tag_prefix):] - # Filter out refs that exactly match prefix or that don't start - # with a number once the prefix is stripped (mostly a concern - # when prefix is '') - if not re.match(r'\d', r): - continue - if verbose: - print("picking %s" % r) - return {"version": r, - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": None, - "date": date} - # no suitable tags, so version is "0+unknown", but full hex is still there - if verbose: - print("no suitable tags, using unknown + full revision id") - return {"version": "0+unknown", - "full-revisionid": keywords["full"].strip(), - "dirty": False, "error": "no suitable tags", "date": None} - - -@register_vcs_handler("git", "pieces_from_vcs") -def git_pieces_from_vcs( - tag_prefix: str, - root: str, - verbose: bool, - runner: Callable = run_command -) -> Dict[str, Any]: - """Get version from 'git describe' in the root of the source tree. - - This only gets called if the git-archive 'subst' keywords were *not* - expanded, and _version.py hasn't already been rewritten with a short - version string, meaning we're inside a checked out source tree. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - - # GIT_DIR can interfere with correct operation of Versioneer. - # It may be intended to be passed to the Versioneer-versioned project, - # but that should not change where we get our version from. - env = os.environ.copy() - env.pop("GIT_DIR", None) - runner = functools.partial(runner, env=env) - - _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, - hide_stderr=not verbose) - if rc != 0: - if verbose: - print("Directory %s not under git control" % root) - raise NotThisMethod("'git rev-parse --git-dir' returned error") - - # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] - # if there isn't one, this yields HEX[-dirty] (no NUM) - describe_out, rc = runner(GITS, [ - "describe", "--tags", "--dirty", "--always", "--long", - "--match", f"{tag_prefix}[[:digit:]]*" - ], cwd=root) - # --long was added in git-1.5.5 - if describe_out is None: - raise NotThisMethod("'git describe' failed") - describe_out = describe_out.strip() - full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) - if full_out is None: - raise NotThisMethod("'git rev-parse' failed") - full_out = full_out.strip() - - pieces: Dict[str, Any] = {} - pieces["long"] = full_out - pieces["short"] = full_out[:7] # maybe improved later - pieces["error"] = None - - branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], - cwd=root) - # --abbrev-ref was added in git-1.6.3 - if rc != 0 or branch_name is None: - raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") - branch_name = branch_name.strip() - - if branch_name == "HEAD": - # If we aren't exactly on a branch, pick a branch which represents - # the current commit. If all else fails, we are on a branchless - # commit. - branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) - # --contains was added in git-1.5.4 - if rc != 0 or branches is None: - raise NotThisMethod("'git branch --contains' returned error") - branches = branches.split("\n") - - # Remove the first line if we're running detached - if "(" in branches[0]: - branches.pop(0) - - # Strip off the leading "* " from the list of branches. - branches = [branch[2:] for branch in branches] - if "master" in branches: - branch_name = "master" - elif not branches: - branch_name = None - else: - # Pick the first branch that is returned. Good or bad. - branch_name = branches[0] - - pieces["branch"] = branch_name - - # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] - # TAG might have hyphens. - git_describe = describe_out - - # look for -dirty suffix - dirty = git_describe.endswith("-dirty") - pieces["dirty"] = dirty - if dirty: - git_describe = git_describe[:git_describe.rindex("-dirty")] - - # now we have TAG-NUM-gHEX or HEX - - if "-" in git_describe: - # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) - if not mo: - # unparsable. Maybe git-describe is misbehaving? - pieces["error"] = ("unable to parse git-describe output: '%s'" - % describe_out) - return pieces - - # tag - full_tag = mo.group(1) - if not full_tag.startswith(tag_prefix): - if verbose: - fmt = "tag '%s' doesn't start with prefix '%s'" - print(fmt % (full_tag, tag_prefix)) - pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" - % (full_tag, tag_prefix)) - return pieces - pieces["closest-tag"] = full_tag[len(tag_prefix):] - - # distance: number of commits since tag - pieces["distance"] = int(mo.group(2)) - - # commit: short hex revision ID - pieces["short"] = mo.group(3) - - else: - # HEX: no tags - pieces["closest-tag"] = None - out, rc = runner(GITS, ["rev-list", "HEAD", "--left-right"], cwd=root) - pieces["distance"] = len(out.split()) # total number of commits - - # commit date: see ISO-8601 comment in git_versions_from_keywords() - date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() - # Use only the last line. Previous lines may contain GPG signature - # information. - date = date.splitlines()[-1] - pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) - - return pieces - - -def do_vcs_install(versionfile_source: str, ipy: Optional[str]) -> None: - """Git-specific installation logic for Versioneer. - - For Git, this means creating/changing .gitattributes to mark _version.py - for export-subst keyword substitution. - """ - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] - files = [versionfile_source] - if ipy: - files.append(ipy) - if "VERSIONEER_PEP518" not in globals(): - try: - my_path = __file__ - if my_path.endswith((".pyc", ".pyo")): - my_path = os.path.splitext(my_path)[0] + ".py" - versioneer_file = os.path.relpath(my_path) - except NameError: - versioneer_file = "versioneer.py" - files.append(versioneer_file) - present = False - try: - with open(".gitattributes", "r") as fobj: - for line in fobj: - if line.strip().startswith(versionfile_source): - if "export-subst" in line.strip().split()[1:]: - present = True - break - except OSError: - pass - if not present: - with open(".gitattributes", "a+") as fobj: - fobj.write(f"{versionfile_source} export-subst\n") - files.append(".gitattributes") - run_command(GITS, ["add", "--"] + files) - - -def versions_from_parentdir( - parentdir_prefix: str, - root: str, - verbose: bool, -) -> Dict[str, Any]: - """Try to determine the version from the parent directory name. - - Source tarballs conventionally unpack into a directory that includes both - the project name and a version string. We will also support searching up - two directory levels for an appropriately named parent directory - """ - rootdirs = [] - - for _ in range(3): - dirname = os.path.basename(root) - if dirname.startswith(parentdir_prefix): - return {"version": dirname[len(parentdir_prefix):], - "full-revisionid": None, - "dirty": False, "error": None, "date": None} - rootdirs.append(root) - root = os.path.dirname(root) # up a level - - if verbose: - print("Tried directories %s but none started with prefix %s" % - (str(rootdirs), parentdir_prefix)) - raise NotThisMethod("rootdir doesn't start with parentdir_prefix") - - -SHORT_VERSION_PY = """ -# This file was generated by 'versioneer.py' (0.29) from -# revision-control system data, or from the parent directory name of an -# unpacked source archive. Distribution tarballs contain a pre-generated copy -# of this file. - -import json - -version_json = ''' -%s -''' # END VERSION_JSON - - -def get_versions(): - return json.loads(version_json) -""" - - -def versions_from_file(filename: str) -> Dict[str, Any]: - """Try to determine the version from _version.py if present.""" - try: - with open(filename) as f: - contents = f.read() - except OSError: - raise NotThisMethod("unable to read _version.py") - mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", - contents, re.M | re.S) - if not mo: - mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", - contents, re.M | re.S) - if not mo: - raise NotThisMethod("no version_json in _version.py") - return json.loads(mo.group(1)) - - -def write_to_version_file(filename: str, versions: Dict[str, Any]) -> None: - """Write the given version number to the given _version.py file.""" - contents = json.dumps(versions, sort_keys=True, - indent=1, separators=(",", ": ")) - with open(filename, "w") as f: - f.write(SHORT_VERSION_PY % contents) - - print("set %s to '%s'" % (filename, versions["version"])) - - -def plus_or_dot(pieces: Dict[str, Any]) -> str: - """Return a + if we don't already have one, else return a .""" - if "+" in pieces.get("closest-tag", ""): - return "." - return "+" - - -def render_pep440(pieces: Dict[str, Any]) -> str: - """Build up version string, with post-release "local version identifier". - - Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you - get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty - - Exceptions: - 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_branch(pieces: Dict[str, Any]) -> str: - """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . - - The ".dev0" means not master branch. Note that .dev0 sorts backwards - (a feature branch will appear "older" than the master branch). - - Exceptions: - 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0" - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+untagged.%d.g%s" % (pieces["distance"], - pieces["short"]) - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def pep440_split_post(ver: str) -> Tuple[str, Optional[int]]: - """Split pep440 version string at the post-release segment. - - Returns the release segments before the post-release and the - post-release version number (or -1 if no post-release segment is present). - """ - vc = str.split(ver, ".post") - return vc[0], int(vc[1] or 0) if len(vc) == 2 else None - - -def render_pep440_pre(pieces: Dict[str, Any]) -> str: - """TAG[.postN.devDISTANCE] -- No -dirty. - - Exceptions: - 1: no tags. 0.post0.devDISTANCE - """ - if pieces["closest-tag"]: - if pieces["distance"]: - # update the post release segment - tag_version, post_version = pep440_split_post(pieces["closest-tag"]) - rendered = tag_version - if post_version is not None: - rendered += ".post%d.dev%d" % (post_version + 1, pieces["distance"]) - else: - rendered += ".post0.dev%d" % (pieces["distance"]) - else: - # no commits, use the tag as the version - rendered = pieces["closest-tag"] - else: - # exception #1 - rendered = "0.post0.dev%d" % pieces["distance"] - return rendered - - -def render_pep440_post(pieces: Dict[str, Any]) -> str: - """TAG[.postDISTANCE[.dev0]+gHEX] . - - The ".dev0" means dirty. Note that .dev0 sorts backwards - (a dirty tree will appear "older" than the corresponding clean one), - but you shouldn't be releasing software with -dirty anyways. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - return rendered - - -def render_pep440_post_branch(pieces: Dict[str, Any]) -> str: - """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . - - The ".dev0" means not master branch. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += plus_or_dot(pieces) - rendered += "g%s" % pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["branch"] != "master": - rendered += ".dev0" - rendered += "+g%s" % pieces["short"] - if pieces["dirty"]: - rendered += ".dirty" - return rendered - - -def render_pep440_old(pieces: Dict[str, Any]) -> str: - """TAG[.postDISTANCE[.dev0]] . - - The ".dev0" means dirty. - - Exceptions: - 1: no tags. 0.postDISTANCE[.dev0] - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"] or pieces["dirty"]: - rendered += ".post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - else: - # exception #1 - rendered = "0.post%d" % pieces["distance"] - if pieces["dirty"]: - rendered += ".dev0" - return rendered - - -def render_git_describe(pieces: Dict[str, Any]) -> str: - """TAG[-DISTANCE-gHEX][-dirty]. - - Like 'git describe --tags --dirty --always'. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - if pieces["distance"]: - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render_git_describe_long(pieces: Dict[str, Any]) -> str: - """TAG-DISTANCE-gHEX[-dirty]. - - Like 'git describe --tags --dirty --always -long'. - The distance/hash is unconditional. - - Exceptions: - 1: no tags. HEX[-dirty] (note: no 'g' prefix) - """ - if pieces["closest-tag"]: - rendered = pieces["closest-tag"] - rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) - else: - # exception #1 - rendered = pieces["short"] - if pieces["dirty"]: - rendered += "-dirty" - return rendered - - -def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]: - """Render the given version pieces into the requested style.""" - if pieces["error"]: - return {"version": "unknown", - "full-revisionid": pieces.get("long"), - "dirty": None, - "error": pieces["error"], - "date": None} - - if not style or style == "default": - style = "pep440" # the default - - if style == "pep440": - rendered = render_pep440(pieces) - elif style == "pep440-branch": - rendered = render_pep440_branch(pieces) - elif style == "pep440-pre": - rendered = render_pep440_pre(pieces) - elif style == "pep440-post": - rendered = render_pep440_post(pieces) - elif style == "pep440-post-branch": - rendered = render_pep440_post_branch(pieces) - elif style == "pep440-old": - rendered = render_pep440_old(pieces) - elif style == "git-describe": - rendered = render_git_describe(pieces) - elif style == "git-describe-long": - rendered = render_git_describe_long(pieces) - else: - raise ValueError("unknown style '%s'" % style) - - return {"version": rendered, "full-revisionid": pieces["long"], - "dirty": pieces["dirty"], "error": None, - "date": pieces.get("date")} - - -class VersioneerBadRootError(Exception): - """The project root directory is unknown or missing key files.""" - - -def get_versions(verbose: bool = False) -> Dict[str, Any]: - """Get the project version from whatever source is available. - - Returns dict with two keys: 'version' and 'full'. - """ - if "versioneer" in sys.modules: - # see the discussion in cmdclass.py:get_cmdclass() - del sys.modules["versioneer"] - - root = get_root() - cfg = get_config_from_root(root) - - assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" - handlers = HANDLERS.get(cfg.VCS) - assert handlers, "unrecognized VCS '%s'" % cfg.VCS - verbose = verbose or bool(cfg.verbose) # `bool()` used to avoid `None` - assert cfg.versionfile_source is not None, \ - "please set versioneer.versionfile_source" - assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" - - versionfile_abs = os.path.join(root, cfg.versionfile_source) - - # extract version from first of: _version.py, VCS command (e.g. 'git - # describe'), parentdir. This is meant to work for developers using a - # source checkout, for users of a tarball created by 'setup.py sdist', - # and for users of a tarball/zipball created by 'git archive' or github's - # download-from-tag feature or the equivalent in other VCSes. - - get_keywords_f = handlers.get("get_keywords") - from_keywords_f = handlers.get("keywords") - if get_keywords_f and from_keywords_f: - try: - keywords = get_keywords_f(versionfile_abs) - ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) - if verbose: - print("got version from expanded keyword %s" % ver) - return ver - except NotThisMethod: - pass - - try: - ver = versions_from_file(versionfile_abs) - if verbose: - print("got version from file %s %s" % (versionfile_abs, ver)) - return ver - except NotThisMethod: - pass - - from_vcs_f = handlers.get("pieces_from_vcs") - if from_vcs_f: - try: - pieces = from_vcs_f(cfg.tag_prefix, root, verbose) - ver = render(pieces, cfg.style) - if verbose: - print("got version from VCS %s" % ver) - return ver - except NotThisMethod: - pass - - try: - if cfg.parentdir_prefix: - ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) - if verbose: - print("got version from parentdir %s" % ver) - return ver - except NotThisMethod: - pass - - if verbose: - print("unable to compute version") - - return {"version": "0+unknown", "full-revisionid": None, - "dirty": None, "error": "unable to compute version", - "date": None} - - -def get_version() -> str: - """Get the short version string for this project.""" - return get_versions()["version"] - - -def get_cmdclass(cmdclass: Optional[Dict[str, Any]] = None): - """Get the custom setuptools subclasses used by Versioneer. - - If the package uses a different cmdclass (e.g. one from numpy), it - should be provide as an argument. - """ - if "versioneer" in sys.modules: - del sys.modules["versioneer"] - # this fixes the "python setup.py develop" case (also 'install' and - # 'easy_install .'), in which subdependencies of the main project are - # built (using setup.py bdist_egg) in the same python process. Assume - # a main project A and a dependency B, which use different versions - # of Versioneer. A's setup.py imports A's Versioneer, leaving it in - # sys.modules by the time B's setup.py is executed, causing B to run - # with the wrong versioneer. Setuptools wraps the sub-dep builds in a - # sandbox that restores sys.modules to it's pre-build state, so the - # parent is protected against the child's "import versioneer". By - # removing ourselves from sys.modules here, before the child build - # happens, we protect the child from the parent's versioneer too. - # Also see https://github.com/python-versioneer/python-versioneer/issues/52 - - cmds = {} if cmdclass is None else cmdclass.copy() - - # we add "version" to setuptools - from setuptools import Command - - class cmd_version(Command): - description = "report generated version string" - user_options: List[Tuple[str, str, str]] = [] - boolean_options: List[str] = [] - - def initialize_options(self) -> None: - pass - - def finalize_options(self) -> None: - pass - - def run(self) -> None: - vers = get_versions(verbose=True) - print("Version: %s" % vers["version"]) - print(" full-revisionid: %s" % vers.get("full-revisionid")) - print(" dirty: %s" % vers.get("dirty")) - print(" date: %s" % vers.get("date")) - if vers["error"]: - print(" error: %s" % vers["error"]) - cmds["version"] = cmd_version - - # we override "build_py" in setuptools - # - # most invocation pathways end up running build_py: - # distutils/build -> build_py - # distutils/install -> distutils/build ->.. - # setuptools/bdist_wheel -> distutils/install ->.. - # setuptools/bdist_egg -> distutils/install_lib -> build_py - # setuptools/install -> bdist_egg ->.. - # setuptools/develop -> ? - # pip install: - # copies source tree to a tempdir before running egg_info/etc - # if .git isn't copied too, 'git describe' will fail - # then does setup.py bdist_wheel, or sometimes setup.py install - # setup.py egg_info -> ? - - # pip install -e . and setuptool/editable_wheel will invoke build_py - # but the build_py command is not expected to copy any files. - - # we override different "build_py" commands for both environments - if 'build_py' in cmds: - _build_py: Any = cmds['build_py'] - else: - from setuptools.command.build_py import build_py as _build_py - - class cmd_build_py(_build_py): - def run(self) -> None: - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - _build_py.run(self) - if getattr(self, "editable_mode", False): - # During editable installs `.py` and data files are - # not copied to build_lib - return - # now locate _version.py in the new build/ directory and replace - # it with an updated value - if cfg.versionfile_build: - target_versionfile = os.path.join(self.build_lib, - cfg.versionfile_build) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - cmds["build_py"] = cmd_build_py - - if 'build_ext' in cmds: - _build_ext: Any = cmds['build_ext'] - else: - from setuptools.command.build_ext import build_ext as _build_ext - - class cmd_build_ext(_build_ext): - def run(self) -> None: - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - _build_ext.run(self) - if self.inplace: - # build_ext --inplace will only build extensions in - # build/lib<..> dir with no _version.py to write to. - # As in place builds will already have a _version.py - # in the module dir, we do not need to write one. - return - # now locate _version.py in the new build/ directory and replace - # it with an updated value - if not cfg.versionfile_build: - return - target_versionfile = os.path.join(self.build_lib, - cfg.versionfile_build) - if not os.path.exists(target_versionfile): - print(f"Warning: {target_versionfile} does not exist, skipping " - "version update. This can happen if you are running build_ext " - "without first running build_py.") - return - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - cmds["build_ext"] = cmd_build_ext - - if "cx_Freeze" in sys.modules: # cx_freeze enabled? - from cx_Freeze.dist import build_exe as _build_exe # type: ignore - # nczeczulin reports that py2exe won't like the pep440-style string - # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. - # setup(console=[{ - # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION - # "product_version": versioneer.get_version(), - # ... - - class cmd_build_exe(_build_exe): - def run(self) -> None: - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _build_exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - cmds["build_exe"] = cmd_build_exe - del cmds["build_py"] - - if 'py2exe' in sys.modules: # py2exe enabled? - try: - from py2exe.setuptools_buildexe import py2exe as _py2exe # type: ignore - except ImportError: - from py2exe.distutils_buildexe import py2exe as _py2exe # type: ignore - - class cmd_py2exe(_py2exe): - def run(self) -> None: - root = get_root() - cfg = get_config_from_root(root) - versions = get_versions() - target_versionfile = cfg.versionfile_source - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, versions) - - _py2exe.run(self) - os.unlink(target_versionfile) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % - {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - cmds["py2exe"] = cmd_py2exe - - # sdist farms its file list building out to egg_info - if 'egg_info' in cmds: - _egg_info: Any = cmds['egg_info'] - else: - from setuptools.command.egg_info import egg_info as _egg_info - - class cmd_egg_info(_egg_info): - def find_sources(self) -> None: - # egg_info.find_sources builds the manifest list and writes it - # in one shot - super().find_sources() - - # Modify the filelist and normalize it - root = get_root() - cfg = get_config_from_root(root) - self.filelist.append('versioneer.py') - if cfg.versionfile_source: - # There are rare cases where versionfile_source might not be - # included by default, so we must be explicit - self.filelist.append(cfg.versionfile_source) - self.filelist.sort() - self.filelist.remove_duplicates() - - # The write method is hidden in the manifest_maker instance that - # generated the filelist and was thrown away - # We will instead replicate their final normalization (to unicode, - # and POSIX-style paths) - from setuptools import unicode_utils - normalized = [unicode_utils.filesys_decode(f).replace(os.sep, '/') - for f in self.filelist.files] - - manifest_filename = os.path.join(self.egg_info, 'SOURCES.txt') - with open(manifest_filename, 'w') as fobj: - fobj.write('\n'.join(normalized)) - - cmds['egg_info'] = cmd_egg_info - - # we override different "sdist" commands for both environments - if 'sdist' in cmds: - _sdist: Any = cmds['sdist'] - else: - from setuptools.command.sdist import sdist as _sdist - - class cmd_sdist(_sdist): - def run(self) -> None: - versions = get_versions() - self._versioneer_generated_versions = versions - # unless we update this, the command will keep using the old - # version - self.distribution.metadata.version = versions["version"] - return _sdist.run(self) - - def make_release_tree(self, base_dir: str, files: List[str]) -> None: - root = get_root() - cfg = get_config_from_root(root) - _sdist.make_release_tree(self, base_dir, files) - # now locate _version.py in the new base_dir directory - # (remembering that it may be a hardlink) and replace it with an - # updated value - target_versionfile = os.path.join(base_dir, cfg.versionfile_source) - print("UPDATING %s" % target_versionfile) - write_to_version_file(target_versionfile, - self._versioneer_generated_versions) - cmds["sdist"] = cmd_sdist - - return cmds - - -CONFIG_ERROR = """ -setup.cfg is missing the necessary Versioneer configuration. You need -a section like: - - [versioneer] - VCS = git - style = pep440 - versionfile_source = src/myproject/_version.py - versionfile_build = myproject/_version.py - tag_prefix = - parentdir_prefix = myproject- - -You will also need to edit your setup.py to use the results: - - import versioneer - setup(version=versioneer.get_version(), - cmdclass=versioneer.get_cmdclass(), ...) - -Please read the docstring in ./versioneer.py for configuration instructions, -edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. -""" - -SAMPLE_CONFIG = """ -# See the docstring in versioneer.py for instructions. Note that you must -# re-run 'versioneer.py setup' after changing this section, and commit the -# resulting files. - -[versioneer] -#VCS = git -#style = pep440 -#versionfile_source = -#versionfile_build = -#tag_prefix = -#parentdir_prefix = - -""" - -OLD_SNIPPET = """ -from ._version import get_versions -__version__ = get_versions()['version'] -del get_versions -""" - -INIT_PY_SNIPPET = """ -from . import {0} -__version__ = {0}.get_versions()['version'] -""" - - -def do_setup() -> int: - """Do main VCS-independent setup function for installing Versioneer.""" - root = get_root() - try: - cfg = get_config_from_root(root) - except (OSError, configparser.NoSectionError, - configparser.NoOptionError) as e: - if isinstance(e, (OSError, configparser.NoSectionError)): - print("Adding sample versioneer config to setup.cfg", - file=sys.stderr) - with open(os.path.join(root, "setup.cfg"), "a") as f: - f.write(SAMPLE_CONFIG) - print(CONFIG_ERROR, file=sys.stderr) - return 1 - - print(" creating %s" % cfg.versionfile_source) - with open(cfg.versionfile_source, "w") as f: - LONG = LONG_VERSION_PY[cfg.VCS] - f.write(LONG % {"DOLLAR": "$", - "STYLE": cfg.style, - "TAG_PREFIX": cfg.tag_prefix, - "PARENTDIR_PREFIX": cfg.parentdir_prefix, - "VERSIONFILE_SOURCE": cfg.versionfile_source, - }) - - ipy = os.path.join(os.path.dirname(cfg.versionfile_source), - "__init__.py") - maybe_ipy: Optional[str] = ipy - if os.path.exists(ipy): - try: - with open(ipy, "r") as f: - old = f.read() - except OSError: - old = "" - module = os.path.splitext(os.path.basename(cfg.versionfile_source))[0] - snippet = INIT_PY_SNIPPET.format(module) - if OLD_SNIPPET in old: - print(" replacing boilerplate in %s" % ipy) - with open(ipy, "w") as f: - f.write(old.replace(OLD_SNIPPET, snippet)) - elif snippet not in old: - print(" appending to %s" % ipy) - with open(ipy, "a") as f: - f.write(snippet) - else: - print(" %s unmodified" % ipy) - else: - print(" %s doesn't exist, ok" % ipy) - maybe_ipy = None - - # Make VCS-specific changes. For git, this means creating/changing - # .gitattributes to mark _version.py for export-subst keyword - # substitution. - do_vcs_install(cfg.versionfile_source, maybe_ipy) - return 0 - - -def scan_setup_py() -> int: - """Validate the contents of setup.py against Versioneer's expectations.""" - found = set() - setters = False - errors = 0 - with open("setup.py", "r") as f: - for line in f.readlines(): - if "import versioneer" in line: - found.add("import") - if "versioneer.get_cmdclass()" in line: - found.add("cmdclass") - if "versioneer.get_version()" in line: - found.add("get_version") - if "versioneer.VCS" in line: - setters = True - if "versioneer.versionfile_source" in line: - setters = True - if len(found) != 3: - print("") - print("Your setup.py appears to be missing some important items") - print("(but I might be wrong). Please make sure it has something") - print("roughly like the following:") - print("") - print(" import versioneer") - print(" setup( version=versioneer.get_version(),") - print(" cmdclass=versioneer.get_cmdclass(), ...)") - print("") - errors += 1 - if setters: - print("You should remove lines like 'versioneer.VCS = ' and") - print("'versioneer.versionfile_source = ' . This configuration") - print("now lives in setup.cfg, and should be removed from setup.py") - print("") - errors += 1 - return errors - - -def setup_command() -> NoReturn: - """Set up Versioneer and exit with appropriate error code.""" - errors = do_setup() - errors += scan_setup_py() - sys.exit(1 if errors else 0) - - -if __name__ == "__main__": - cmd = sys.argv[1] - if cmd == "setup": - setup_command()