README.rst 11.6 KB
Newer Older
Pierre Augier's avatar
Pierre Augier committed
1
2
FluidPythran: easily speedup your Python code with Pythran
==========================================================
Pierre Augier's avatar
Pierre Augier committed
3

Pierre Augier's avatar
Pierre Augier committed
4
|release| |docs| |coverage|
Pierre Augier's avatar
Pierre Augier committed
5
6
7
8
9

.. |release| image:: https://img.shields.io/pypi/v/fluidpythran.svg
   :target: https://pypi.python.org/pypi/fluidpythran/
   :alt: Latest version

Pierre Augier's avatar
Pierre Augier committed
10
11
12
13
.. |docs| image:: https://readthedocs.org/projects/fluidpythran/badge/?version=latest
   :target: http://fluidpythran.readthedocs.org
   :alt: Documentation status

Pierre Augier's avatar
Pierre Augier committed
14
15
16
17
.. |coverage| image:: https://codecov.io/bb/fluiddyn/fluidpythran/branch/default/graph/badge.svg
   :target: https://codecov.io/bb/fluiddyn/fluidpythran/branch/default/
   :alt: Code coverage

Pierre Augier's avatar
Pierre Augier committed
18
**Documentation**: https://fluidpythran.readthedocs.io
Pierre Augier's avatar
Pierre Augier committed
19

Pierre Augier's avatar
Pierre Augier committed
20
21
.. warning ::

Pierre Augier's avatar
Pierre Augier committed
22
   FluidPythran is in an early stage. Remarks and suggestions are very
Pierre Augier's avatar
Pierre Augier committed
23
   welcome.
Pierre Augier's avatar
Pierre Augier committed
24

Pierre Augier's avatar
Pierre Augier committed
25
26
27
28
29
30
31
   FluidPythran is used in `FluidSim
   <https://bitbucket.org/fluiddyn/fluidsim>`_ (see examples for `blocks
   <https://bitbucket.org/fluiddyn/fluidsim/src/default/fluidsim/base/time_stepping/pseudo_spect.py>`_,
   `@pythran_def
   <https://bitbucket.org/fluiddyn/fluidsim/src/default/fluidsim/operators/operators3d.py>`_
   and `@cachedjit
   <https://bitbucket.org/fluiddyn/fluidsim/src/default/fluidsim/solvers/plate2d/output/correlations_freq.py>`_).
Pierre Augier's avatar
Pierre Augier committed
32
33

FluidPythran is a pure Python package (requiring Python >= 3.6 or Pypy3) to
Pierre Augier's avatar
Pierre Augier committed
34
35
help to write Python code that *can* use `Pythran
<https://github.com/serge-sans-paille/pythran>`_ if it is available.
36

Pierre Augier's avatar
Pierre Augier committed
37
38
39
40
Let's recall that "Pythran is an ahead-of-time (AOT) compiler for a subset of
the Python language, with a focus on scientific computing. It takes a Python
module annotated with a few interface description and turns it into a native
Python module with the same interface, but (hopefully) faster."
Pierre Augier's avatar
Pierre Augier committed
41

Pierre Augier's avatar
Pierre Augier committed
42
43
44
45
46
47
48
49
50
Pythran is able to produce **very efficient C++ code and binaries from high
level Numpy code**. If the algorithm is easier to express without loops, don't
write loops!

Pythran always releases the GIL and can use SIMD instructions and OpenMP!

**Pythran is not a hard dependency of FluidPythran:** Python code using
FluidPythran run fine without Pythran and without compilation (and of course
without speedup)!
Pierre Augier's avatar
Pierre Augier committed
51
52
53
54
55
56
57
58
59

Overview
--------

Python + Numpy + Pythran is a great combo to easily write highly efficient
scientific programs and libraries.

To use Pythran, one needs to isolate the numerical kernels functions in modules
that are compiled by Pythran. The C++ code produced by Pythran never uses the
Pierre Augier's avatar
Pierre Augier committed
60
Python interpreter. It means that only a subset of what is doable in Python can
Pierre Augier's avatar
Pierre Augier committed
61
62
63
be done in Pythran files. Some `language features
<https://pythran.readthedocs.io/en/latest/MANUAL.html#disclaimer>`_ are not
supported by Pythran (for example no classes) and most of the extension
Pierre Augier's avatar
Pierre Augier committed
64
65
packages cannot be used in Pythran files (basically `only Numpy and some Scipy
functions <https://pythran.readthedocs.io/en/latest/SUPPORT.html>`_).
Pierre Augier's avatar
Pierre Augier committed
66

67
68
69
70
71
Another cause of frustration for Python developers when using Pythran is
related to manual writting of Pythran function signatures in comments, which
can not be automated. Pythran uses C++ templates but Pythran users can not
think with this concept. We would like to be able to **express the templated
nature of Pythran with modern Python syntax** (in particular **type
Pierre Augier's avatar
Pierre Augier committed
72
annotations**). Finally, another limitation is that it is not possible to use
Pierre Augier's avatar
Pierre Augier committed
73
Pythran for **just-in-time** (JIT) compilation so one needs to manually write
Pierre Augier's avatar
Pierre Augier committed
74
all argument types.
75

Pierre Augier's avatar
Pierre Augier committed
76
With FluidPythran, we try to overcome these limitations. FluidPythran provides
77
few supplementary Pythran commands and a small Python API to define Pythran
Pierre Augier's avatar
Pierre Augier committed
78
79
80
81
82
functions without writing the Pythran modules. The code of the numerical
kernels can stay in the modules and in the classes where they were written. The
Pythran files (i.e. the files compiled by Pythran), which are usually written
by the user, are produced automatically by FluidPythran.

Pierre Augier's avatar
Pierre Augier committed
83
84
Bonus: There are FluidPythran syntaxes for both **ahead-of-time** and
**just-in-time** compilations!
Pierre Augier's avatar
Pierre Augier committed
85

Pierre Augier's avatar
Pierre Augier committed
86
At run time, FluidPythran uses when possible the pythranized functions, but
Pierre Augier's avatar
Pierre Augier committed
87
88
let's stress again that codes using FluidPythran work fine without Pythran (of
course without speedup)!
Pierre Augier's avatar
Pierre Augier committed
89

Pierre Augier's avatar
Pierre Augier committed
90
91
To summarize, a **strategy to quickly develop a very efficient scientific
application/library** with Python could be:
92

Pierre Augier's avatar
Pierre Augier committed
93
94
95
96
97
98
99
100
101
102
103
104
- Use modern Python coding, standard Numpy/Scipy for the computations and all
  the cool libraries you want.

- Profile your applications on real cases, detect the bottlenecks and apply
  standard optimizations with Numpy.

- Add few lines of FluidPythran to compile the hot spots.

**Implementation details:** Under the hood, FluidPythran creates Pythran files
(one per module for AOT compilation and one per function for JIT compilation)
that can be compiled at build, import or run times depending of the cases. Note
that the developers can still read the Pythran files if needed.
105

Pierre Augier's avatar
Pierre Augier committed
106
107
108
109
110
111
112
Installation
------------

.. code ::

   pip install fluidpythran

Pierre Augier's avatar
Pierre Augier committed
113
114
115
The environment variable :code:`FLUIDPYTHRAN_DIR` can be set to control where
the cached files are saved.

Pierre Augier's avatar
Pierre Augier committed
116
117
A short tour of FluidPythran syntaxes
-------------------------------------
Pierre Augier's avatar
Pierre Augier committed
118

Pierre Augier's avatar
Pierre Augier committed
119
120
Command :code:`# pythran def`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Pierre Augier's avatar
Pierre Augier committed
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148

.. code :: python

    import h5py
    import mpi4py

    from fluidpythran import pythran_def

    # pythran def myfunc(int, float)

    @pythran_def
    def myfunc(a, b):
        return a * b

    ...

Most of this code looks familiar to Pythran users. The differences:

- One can use (for example) h5py and mpi4py (of course not in the Pythran
  functions).

- :code:`# pythran def` instead of :code:`# pythran export` (to stress that it
  is not the same command).

- A tiny bit of Python... The decorator :code:`@pythran_def` replaces the
  Python function by the pythranized function if FluidPythran has been used to
  produced the associated Pythran file.

149

Pierre Augier's avatar
Pierre Augier committed
150
151
Pythran using type annotations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
152

Pierre Augier's avatar
Pierre Augier committed
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
The previous example can be rewritten without Pythran commands:

.. code :: python

    import h5py
    import mpi4py

    from fluidpythran import pythran_def

    @pythran_def
    def myfunc(a: int, b: float):
        return a * b

    ...

Pierre Augier's avatar
Pierre Augier committed
168
169
170
171
172
Nice but very limited... So it is possible to mix type hints and :code:`#
pythran def` commands. Moreover, one can also elegantly define many Pythran
signatures with type variables (see `these examples in the documentation
<https://fluidpythran.readthedocs.io/en/latest/examples/type_hints.html>`_).

173

174
175
176
177
178
Cached Just-In-Time compilation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

With FluidPythran, one can use the Ahead-Of-Time compiler Pythran in a
Just-In-Time mode. It is really the **easiest way to speedup a function with
Pierre Augier's avatar
Pierre Augier committed
179
180
Pythran**, just by adding a decorator! And it also works `in notebooks
<https://fluidpythran.readthedocs.io/en/latest/ipynb/executed/demo_cachedjit.html>`_!
181

Pierre Augier's avatar
Pierre Augier committed
182
It is a "work in progress" so (i) it could be buggy and (ii) the API is not
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
great, but it is a good start!

.. code :: python

    import numpy as np

    # pythran import numpy as numpy

    from fluidpythran import cachedjit, used_by_cachedjit

    @used_by_cachedjit("func1")
    def func0(a, b):
        return a + b

    @cachedjit
    def func1(a, b):
        return np.exp(a) * b * func0(a, b)

Note that the :code:`@cachedjit` decorator takes into account type hints (see
`the example in the documentation
<https://fluidpythran.readthedocs.io/en/latest/examples/using_cachedjit.html>`_).

If the environment variable :code:`PYTHRANIZE_AT_IMPORT` is set, fluidpythran
compiles at import time the functions with type hints.

**Implementation details for just-in-time compilation:** A Pythran file is
produced for each "cachedjited" function (function decorated with
:code:`@cachedjit`). The file is compiled at the first call of the function and
the compiled version is used as soon as it is ready. The warmup can be quite
long but the compiled version is saved and can be reused (without warmup!) by
another process.


Pierre Augier's avatar
Pierre Augier committed
216
217
Command :code:`# pythran block`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Pierre Augier's avatar
Pierre Augier committed
218

Pierre Augier's avatar
Pierre Augier committed
219
220
FluidPythran blocks can be used with classes and more generally in functions
with lines that cannot be compiled by Pythran.
Pierre Augier's avatar
Pierre Augier committed
221
222
223
224
225
226
227
228
229
230
231
232
233
234

.. code :: python

    from fluidpythran import FluidPythran

    fp = FluidPythran()

    class MyClass:

        ...

        def func(self, n):
            a, b = self.something_that_cannot_be_pythranized()

Pierre Augier's avatar
Pierre Augier committed
235
            if fp.is_transpiled:
Pierre Augier's avatar
Pierre Augier committed
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
                result = fp.use_pythranized_block("name_block")
            else:
                # pythran block (
                #     float a, b;
                #     int n
                # ) -> result

                # pythran block (
                #     complex a, b;
                #     int n
                # ) -> result

                result = a**n + b**n

            return self.another_func_that_cannot_be_pythranized(result)

Pierre Augier's avatar
Pierre Augier committed
252
For blocks, we need a little bit more of Python.
Pierre Augier's avatar
Pierre Augier committed
253

Pierre Augier's avatar
Pierre Augier committed
254
- At import time, we have :code:`fp = FluidPythran()`, which detects which
Pierre Augier's avatar
Pierre Augier committed
255
  Pythran module should be used and imports it. This is done at import time
Pierre Augier's avatar
Pierre Augier committed
256
  since we want to be very fast at run time.
Pierre Augier's avatar
Pierre Augier committed
257
258
259

- In the function, we define a block with three lines of Python and special
  Pythran annotations (:code:`# pythran block`). The 3 lines of Python are used
Pierre Augier's avatar
Pierre Augier committed
260
  (i) at run time to choose between the two branches (:code:`is_transpiled` or
Pierre Augier's avatar
Pierre Augier committed
261
  not) and (ii) at compile time to detect the blocks.
Pierre Augier's avatar
Pierre Augier committed
262

Pierre Augier's avatar
Pierre Augier committed
263
264
Note that the annotations in the command :code:`# pythran block` are different
(and somehow easier to write) than in the standard command :code:`# pythran
Pierre Augier's avatar
Pierre Augier committed
265
266
export`.

Pierre Augier's avatar
Pierre Augier committed
267
268
`Blocks can now also be defined with type hints!
<https://fluidpythran.readthedocs.io/en/latest/examples/blocks.html>`_
269

270

Pierre Augier's avatar
Pierre Augier committed
271
272
Python classes: :code:`@pythran_def` for methods
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
273

Pierre Augier's avatar
Pierre Augier committed
274
Just a NotImplemented idea! See https://bitbucket.org/fluiddyn/fluidpythran/issues/3
275

276
277
For simple methods only using simple attributes, if could be simple and *very*
useful to support this:
278
279
280

.. code :: python

281
    from fluidpythran import Type, NDim, Array, pythran_def
282
283
284

    import numpy as np

285
286
287
288
289
290
    T = Type(int, np.float64)
    N = NDim(1)

    A1 = Array[T, N]
    A2 = Array[float, N+1]

291
    class MyClass:
292
293
294
295

        arr0: A1
        arr1: A1
        arr2: A2
296
297
298
299
300
301

        def __init__(self, n, dtype=int):
            self.arr0 = np.zeros(n, dtype=dtype)
            self.arr1 = np.zeros(n, dtype=dtype)
            self.arr2 = np.zeros(n)

302
303
        @pythran_def
        def compute(self, alpha: int):
304
305
306
            tmp = (self.arr0 + self.arr1).mean()
            return tmp ** alpha * self.arr2

Pierre Augier's avatar
Pierre Augier committed
307
308
309
Make the Pythran files
----------------------

Pierre Augier's avatar
Pierre Augier committed
310
There is a command-line tool :code:`fluidpythran` which makes the associated
311
312
Pythran files from Python files with annotations and fluidpythran code. By
default and if Pythran is available, the Pythran files are compiled.
Pierre Augier's avatar
Pierre Augier committed
313
314
315
316
317
318
319
320

There is also a function :code:`make_pythran_files` that can be used in a
setup.py like this:

.. code ::

    from pathlib import Path

Pierre Augier's avatar
Pierre Augier committed
321
    from fluidpythran.dist import make_pythran_files
Pierre Augier's avatar
Pierre Augier committed
322
323
324
325

    here = Path(__file__).parent.absolute()

    paths = ["fluidsim/base/time_stepping/pseudo_spect.py"]
Pierre Augier's avatar
Pierre Augier committed
326
    make_pythran_files([here / path for path in paths], mocked_modules=["h5py"])
Pierre Augier's avatar
Pierre Augier committed
327

328
329
330
Note that the function :code:`make_pythran_files` does not use Pythran.
Compiling the associated Pythran file can be done if wanted (see for example
how it is done in the example package `example_package_fluidpythran
Pierre Augier's avatar
Pierre Augier committed
331
332
333
<https://bitbucket.org/fluiddyn/example_package_fluidpythran>`_ or in
`fluidsim's setup.py
<https://bitbucket.org/fluiddyn/fluidsim/src/default/setup.py>`_).
Pierre Augier's avatar
Pierre Augier committed
334

335
336
337
338
If the environment variable :code:`PYTHRANIZE_AT_IMPORT` is set, FluidPythran
compiles at import time (i.e. only when needed) the Pythran file associated
with the imported module.

Pierre Augier's avatar
Pierre Augier committed
339
340
341
342
343
344
345
License
-------

FluidDyn is distributed under the CeCILL-B_ License, a BSD compatible
french license.

.. _CeCILL-B: http://www.cecill.info/index.en.html