mpi4py 并行读/写 numpy npy 文件的方法

在上一篇中我们介绍了 mpi4py 中获得高性能 I/O 的方法和建议,下面我们将介绍 mpi4py 并行读/写 numpy npy 文件的方法。

在使用 mpi4py 写并行计算程序时经常涉及到对 numpy 数组的操作,常用的操作是将一个大的 numpy 数组按照某种特定的方式分布到各个 MPI 进程中进行并行处理。在某些时候可能需要将这个数组存储到文件中,无论只是为了保存中间数据作为 checkpoint 或保存最后结果以做进一步分析用。numpy 中将数组存储到文件所使用的标准文件格式是 npy 文件。它是一种进行 numpy 数组存储的非常方便的文件格式,numpy 提供一些方法方便地将一个数组存储到一个 npy 文件中并且能够从中完全地恢复该 numpy 数组。不过 numpy 本身并不支持将分布在多个 MPI 进程中的 numpy 数组直接地写入一个 npy 文件。一种方式是每个进程将其本地子数组写入一个单独的 npy 文件。但是这在某些情况下并不方便,比如说 MPI 程序想以一种不同的分布方式从这些 npy 文件中重新读入数据时。一种更方便的方式是各个 MPI 进程将其本地子数组并行地写入一个共同的 noy 文件。我们可以有多种方式,比如说可以先将分布在各个进程中的数据收集到一个进程中,然后由这个进程将这个整体的数组存储到文件中。但这是一种非常低效的操作方式,我们完全可以使用前面介绍过的并行 I/O 操作将这个数组并行地写入文件。前面已经介绍过 mpi4py 中读/写文件中数组的方法,不过我们一直使用的是普通的二进制文件,仅仅只包含数组的数据,没有添加其它任何额外的信息,如数组的 shape,排列方式等,而 numpy npy 文件是包含这些恢复数组所需的必要信息的。从 npy 文件中读取数据并恢复成一个分布在各个 MPI 进程上的 numpy 数组是一个逆操作,我们也希望能以一种并行的方式高效地完成这种操作。在下面我们将首先介绍 npy 文件的存储格式,然后介绍使用 mpi4py 并行读写 npy 文件的方法。

注意:将数组并行存入文件或从文件中并行读取数组的另一种常用方式是使用并行的 HDF5。可以在 mpi4py 中使用并行的 h5py 完成并行 HDF5 文件操作,这在前面作过相应的介绍。

npy 文件简介

numpy npy 文件是一种将 numpy 数组存储到硬盘并包含所存储数组的全部信息的一种文件格式,它是一种二进制文件,是 numpy 存储数组的标准格式。在 npy 文件的头部(header)中纪录了包括数组的 shape,dtype 和存储顺序等必要信息,允许在不同的应用甚至不同的主机环境中正确读取并重构存储在文件中的数组。

一个 numpy 数组是以 native 的二进制格式存储在 noy 文件中的,即数组在 npy 文件中与其在内存中有相同的表示方式。因此数组在存储到 npy 文件或是读取到内存的过程中都不需要进行类型转换,避免数据精度损失。

对 npy 文件更详细的介绍可用参见这里。

npy 文件格式

版本 1.0

版本 1.0 的 npy 文件的数据格式如下:

  • 前 6 字节是一个 magic string: "\x93NUMPY"。
  • 接下来的一个字节是主版本号,如 "\x01"。
  • 接下来的一个字节是次版本号,如 "\x00"。
  • 接下来的 2 个字节构成一个小端无符号短整型数表示文件 header 的长度 HEADER_LEN。
  • 接下来 HEADER_LEN 个字节是用来描述数组信息的 header。它是一个 Python 字典的 ASCII 字符串表示,由一个换行符 "\n" 结尾,并在 "\n" 之前有一定数目的空格 padding。

字典中包含以下描述数组信息的键:

"descr": dtype.descr。可以传递给 numpy.dtype() 创建该数组的 dtype 的描述字符串。
"fortran_order": bool。True 或者 False 表明是 Fortran 排列方式或 C 排列方式。
"shape": tuple of int。数组的 shape。

  • 接下来就是数组的 native 二进制数据。如果数组的 dtype 包含 Python 对象(即 dtype.hasobject == True),则存储在 npy 文件中的是数组的 pickle 化表示,否则是数组本身的连续字节序列。

版本 2.0

版本 1.0 只允许在 header 中最多存储 65536 字节的信息,版本 2.0 将这一限制扩展到了 4 GB。如果描述 数组的 header 信息超过版本 1.0 的限制,numpy 会自动将数据存为版本 2.0,否则会使用兼容性更好的版本 1.0。

npy 文件的具体实现见这里的代码。

numpy npy 文件操作方法

numpy 中将数组存储到 noy 文件中及从 npy 文件中恢复数组的最主要两个方法如下:

numpy.save(file, arr, allow_pickle=True, fix_imports=True)

将一个数组存储为一个 numpy npy 格式的二进制文件。

numpy.load(file, mmap_mode=None, allow_pickle=True, fix_imports=True, encoding='ASCII')

从一个 npy,npz 或 pickle 文件中加载 numpy 数组。

这两个函数的参数介绍和使用方法请参考 numpy 相关文档。

mpi4py 并行读/写 npy 文件

从前面的介绍中可以看出,除了文件前面的 magic string 及 header 等内容需要特别地加以注意之外,数组本身在 npy 文件中的存储并无特别之处,完全可以使用我们前面介绍的并行 I/O 方法进行并行读/写操作。

并行写入数组的步骤

  1. 创建并打开一个 npy 文件。
  2. 由某个进程(如 process 0)构造 npy 文件前面的 magic string 及 header 等信息并将其写入文件中。注意 header 中的 shape 应该是整体数组的 shape,而非该进程本地子数组的 shape。
  3. 各个进程移动其独立文件指针至文件当前的末尾位置。
  4. 根据数组的数据类型和在各个进程中的分布方式创建 etype 和 filetype,并设置文件视图。
  5. 各个进程将本地子数组并行写入文件,尽量采用集合写操作以提高 I/O 性能。
  6. 关闭文件。

并行读取数组的步骤

  1. 打开一个 npy 文件。
  2. 各个进程读取位于文件前面的相应数据以确定文件所使用的版本及 header 的长度。
  3. 各个进程读取 header 并解析数组的 shape,dtype 和排列顺序等信息。
  4. 根据数组的 shape,dtype 及数组将要在各个进程上的分布方式预先分配本地子数组数据缓冲区。
  5. 根据数组的数据类型和在各个进程中的分布方式创建 etype 和 filetype,并设置文件视图。
  6. 各个进程并行地从文件中读取数据到本地子数组的数据缓冲区,尽量采用集合读操作以提高 I/O 性能。
  7. 关闭文件。

例程

下面给出例程。下面的 format.py 文件是由 numpy 的 npy 格式实现做了一些小的改动得到。在 npy_io.py 中的函数 parallel_read_array 和 parallel_write_array 实现了并行读/写 npy 文件中一个按照某个轴(行、列等)分布在各个 MPI 进程上的 nympy 数组的功能。注意:此实现只支持按 C 数组顺序存放且 dtype 中不包含 Python 对象的数组。对更一般的情况,根据前面对并行 I/O 及对 noy 文件格式的相关介绍,读者应该不难实现。

# format.py

"""
Binary serialization

NPY format
==========

A simple format for saving numpy arrays to disk with the full
information about them.

The ``.npy`` format is the standard binary file format in NumPy for
persisting a *single* arbitrary NumPy array on disk. The format stores all
of the shape and dtype information necessary to reconstruct the array
correctly even on another machine with a different architecture.
The format is designed to be as simple as possible while achieving
its limited goals.

The ``.npz`` format is the standard format for persisting *multiple* NumPy
arrays on disk. A ``.npz`` file is a zip file containing multiple ``.npy``
files, one for each array.

Capabilities
------------

- Can represent all NumPy arrays including nested record arrays and
  object arrays.

- Represents the data in its native binary form.

- Supports Fortran-contiguous arrays directly.

- Stores all of the necessary information to reconstruct the array
  including shape and dtype on a machine of a different
  architecture.  Both little-endian and big-endian arrays are
  supported, and a file with little-endian numbers will yield
  a little-endian array on any machine reading the file. The
  types are described in terms of their actual sizes. For example,
  if a machine with a 64-bit C "long int" writes out an array with
  "long ints", a reading machine with 32-bit C "long ints" will yield
  an array with 64-bit integers.

- Is straightforward to reverse engineer. Datasets often live longer than
  the programs that created them. A competent developer should be
  able to create a solution in their preferred programming language to
  read most ``.npy`` files that he has been given without much
  documentation.

- Allows memory-mapping of the data. See `open_memmep`.

- Can be read from a filelike stream object instead of an actual file.

- Stores object arrays, i.e. arrays containing elements that are arbitrary
  Python objects. Files with object arrays are not to be mmapable, but
  can be read and written to disk.

Limitations
-----------

- Arbitrary subclasses of numpy.ndarray are not completely preserved.
  Subclasses will be accepted for writing, but only the array data will
  be written out. A regular numpy.ndarray object will be created
  upon reading the file.

.. warning::

  Due to limitations in the interpretation of structured dtypes, dtypes
  with fields with empty names will have the names replaced by 'f0', 'f1',
  etc. Such arrays will not round-trip through the format entirely
  accurately. The data is intact; only the field names will differ. We are
  working on a fix for this. This fix will not require a change in the
  file format. The arrays with such structures can still be saved and
  restored, and the correct dtype may be restored by using the
  ``loadedarray.view(correct_dtype)`` method.

File extensions
---------------

We recommend using the ``.npy`` and ``.npz`` extensions for files saved
in this format. This is by no means a requirement; applications may wish
to use these file formats but use an extension specific to the
application. In the absence of an obvious alternative, however,
we suggest using ``.npy`` and ``.npz``.

Version numbering
-----------------

The version numbering of these formats is independent of NumPy version
numbering. If the format is upgraded, the code in `numpy.io` will still
be able to read and write Version 1.0 files.

Format Version 1.0
------------------

The first 6 bytes are a magic string: exactly ``\\x93NUMPY``.

The next 1 byte is an unsigned byte: the major version number of the file
format, e.g. ``\\x01``.

The next 1 byte is an unsigned byte: the minor version number of the file
format, e.g. ``\\x00``. Note: the version of the file format is not tied
to the version of the numpy package.

The next 2 bytes form a little-endian unsigned short int: the length of
the header data HEADER_LEN.

The next HEADER_LEN bytes form the header data describing the array's
format. It is an ASCII string which contains a Python literal expression
of a dictionary. It is terminated by a newline (``\\n``) and padded with
spaces (``\\x20``) to make the total of
``len(magic string) + 2 + len(length) + HEADER_LEN`` be evenly divisible
by 64 for alignment purposes.

The dictionary contains three keys:

    "descr" : dtype.descr
      An object that can be passed as an argument to the `numpy.dtype`
      constructor to create the array's dtype.
    "fortran_order" : bool
      Whether the array data is Fortran-contiguous or not. Since
      Fortran-contiguous arrays are a common form of non-C-contiguity,
      we allow them to be written directly to disk for efficiency.
    "shape" : tuple of int
      The shape of the array.

For repeatability and readability, the dictionary keys are sorted in
alphabetic order. This is for convenience only. A writer SHOULD implement
this if possible. A reader MUST NOT depend on this.

Following the header comes the array data. If the dtype contains Python
objects (i.e. ``dtype.hasobject is True``), then the data is a Python
pickle of the array. Otherwise the data is the contiguous (either C-
or Fortran-, depending on ``fortran_order``) bytes of the array.
Consumers can figure out the number of bytes by multiplying the number
of elements given by the shape (noting that ``shape=()`` means there is
1 element) by ``dtype.itemsize``.

Format Version 2.0
------------------

The version 1.0 format only allowed the array header to have a total size of
65535 bytes.  This can be exceeded by structured arrays with a large number of
columns.  The version 2.0 format extends the header size to 4 GiB.
`numpy.save` will automatically save in 2.0 format if the data requires it,
else it will always use the more compatible 1.0 format.

The description of the fourth element of the header therefore has become:
"The next 4 bytes form a little-endian unsigned int: the length of the header
data HEADER_LEN."

Notes
-----
The ``.npy`` format, including motivation for creating it and a comparison of
alternatives, is described in the `"npy-format" NEP
`_, however details have
evolved with time and this document is more current.

"""
from __future__ import division, absolute_import, print_function

import numpy
import sys
import io
import warnings
from numpy.lib.utils import safe_eval
from numpy.compat import asbytes, asstr, isfileobj, long, basestring

if sys.version_info[0] >= 3:
    import pickle
else:
    import cPickle as pickle


MAGIC_PREFIX = b'\x93NUMPY'
MAGIC_LEN = len(MAGIC_PREFIX) + 2
ARRAY_ALIGN = 64 # plausible values are powers of 2 between 16 and 4096
BUFFER_SIZE = 2**18  # size of buffer for reading npz files in bytes

# difference between version 1.0 and 2.0 is a 4 byte (I) header length
# instead of 2 bytes (H) allowing storage of large structured arrays

def _check_version(version):
    if version not in [(1, 0), (2, 0), None]:
        msg = "we only support format version (1,0) and (2, 0), not %s"
        raise ValueError(msg % (version,))

def magic(major, minor):
    """ Return the magic string for the given file format version.

    Parameters
    ----------
    major : int in [0, 255]
    minor : int in [0, 255]

    Returns
    -------
    magic : str

    Raises
    ------
    ValueError if the version cannot be formatted.
    """
    if major < 0 or major > 255:
        raise ValueError("major version must be 0 <= major < 256")
    if minor < 0 or minor > 255:
        raise ValueError("minor version must be 0 <= minor < 256")
    if sys.version_info[0] < 3:
        return MAGIC_PREFIX + chr(major) + chr(minor)
    else:
        return MAGIC_PREFIX + bytes([major, minor])

def read_magic(fp):
    """ Read the magic string to get the version of the file format.

    Parameters
    ----------
    fp : filelike object

    Returns
    -------
    major : int
    minor : int
    """
    magic_str = _read_bytes(fp, MAGIC_LEN, "magic string")
    if magic_str[:-2] != MAGIC_PREFIX:
        msg = "the magic string is not correct; expected %r, got %r"
        raise ValueError(msg % (MAGIC_PREFIX, magic_str[:-2]))
    if sys.version_info[0] < 3:
        major, minor = map(ord, magic_str[-2:])
    else:
        major, minor = magic_str[-2:]
    return major, minor

def dtype_to_descr(dtype):
    """
    Get a serializable descriptor from the dtype.

    The .descr attribute of a dtype object cannot be round-tripped through
    the dtype() constructor. Simple types, like dtype('float32'), have
    a descr which looks like a record array with one field with '' as
    a name. The dtype() constructor interprets this as a request to give
    a default name.  Instead, we construct descriptor that can be passed to
    dtype().

    Parameters
    ----------
    dtype : dtype
        The dtype of the array that will be written to disk.

    Returns
    -------
    descr : object
        An object that can be passed to `numpy.dtype()` in order to
        replicate the input dtype.

    """
    if dtype.names is not None:
        # This is a record array. The .descr is fine.  XXX: parts of the
        # record array with an empty name, like padding bytes, still get
        # fiddled with. This needs to be fixed in the C implementation of
        # dtype().
        return dtype.descr
    else:
        return dtype.str

def header_data_from_array_1_0(array):
    """ Get the dictionary of header metadata from a numpy.ndarray.

    Parameters
    ----------
    array : numpy.ndarray

    Returns
    -------
    d : dict
        This has the appropriate entries for writing its string representation
        to the header of the file.
    """
    d = {'shape': array.shape}
    if array.flags.c_contiguous:
        d['fortran_order'] = False
    elif array.flags.f_contiguous:
        d['fortran_order'] = True
    else:
        # Totally non-contiguous data. We will have to make it C-contiguous
        # before writing. Note that we need to test for C_CONTIGUOUS first
        # because a 1-D array is both C_CONTIGUOUS and F_CONTIGUOUS.
        d['fortran_order'] = False

    d['descr'] = dtype_to_descr(array.dtype)
    return d

def _write_array_header(fp, d, version=None):
    """ Write the header for an array and returns the version used

    Parameters
    ----------
    fp : filelike object
    d : dict
        This has the appropriate entries for writing its string representation
        to the header of the file.
    version: tuple or None
        None means use oldest that works
        explicit version will raise a ValueError if the format does not
        allow saving this data.  Default: None
    Returns
    -------
    version : tuple of int
        the file version which needs to be used to store the data
    """
    import struct
    header = ["{"]
    for key, value in sorted(d.items()):
        # Need to use repr here, since we eval these when reading
        header.append("'%s': %s, " % (key, repr(value)))
    header.append("}")
    header = "".join(header)
    header = asbytes(_filter_header(header))

    hlen = len(header) + 1 # 1 for newline
    padlen_v1 = ARRAY_ALIGN - ((MAGIC_LEN + struct.calcsize('= 3:
        from io import StringIO
    else:
        from StringIO import StringIO

    tokens = []
    last_token_was_number = False
    # adding newline as python 2.7.5 workaround
    string = asstr(s) + "\n"
    for token in tokenize.generate_tokens(StringIO(string).readline):
        token_type = token[0]
        token_string = token[1]
        if (last_token_was_number and
                token_type == tokenize.NAME and
                token_string == "L"):
            continue
        else:
            tokens.append(token)
        last_token_was_number = (token_type == tokenize.NUMBER)
    # removing newline (see above) as python 2.7.5 workaround
    return tokenize.untokenize(tokens)[:-1]


def _read_array_header(fp, version):
    """
    see read_array_header_1_0
    """
    # Read an unsigned, little-endian short int which has the length of the
    # header.
    import struct
    if version == (1, 0):
        hlength_type = '
# npy_io.py

"""
Demonstrates how to use mpi4py to write/read numpy array to/from npy file.

Run this with 2 processes like:
$ mpiexec -n 2 python npy_io.py
"""

import warnings
import numpy as np
import format as fm
from mpi4py import MPI


comm = MPI.COMM_WORLD
rank = comm.Get_rank()

def typemap(dtype):
    """Map a numpy dtype into an MPI_Datatype.

    Parameters
    ----------
    dtype : np.dtype
        The numpy datatype.

    Returns
    -------
    mpitype : MPI.Datatype
        The MPI.Datatype.

    """
    # Need to try both as the name of the typedoct changed in mpi4py 2.0
    try:
        return MPI.__TypeDict__[np.dtype(dtype).char]
    except AttributeError:
        return MPI._typedict[np.dtype(dtype).char]


def parallel_write_array(filename, local_array, axis=0, version=None, comm=None):
    """
    Parallelly write an array distributed in all processes to an NPY file, including a header.

    Parameters
    ----------
    filename : str
        Name of the file to write array into.
    local_array : ndarray
        The subarray local to this process that will be writen to disk.
    axis : int
        The axis that the array is distributed on.
    version : (int, int) or None, optional
        The version number of the format. None means use the oldest
        supported version that is able to store the data.  Default: None
    comm : mpi4py communicator or None.
        A valid mpi4py communicator or None if no MPI.

    """

    # if no MPI, or only 1 MPI process, call np.save directly
    if comm is None or comm.size == 1:
        np.save(filename, local_array)
        return

    if local_array.dtype.hasobject:
        # contain Python objects
        raise RuntimeError('Currently not support array that contains Python objects')
    if local_array.flags.f_contiguous and not local_array.flags.c_contiguous:
        raise RuntimeError('Currently not support Fortran ordered array')

    local_shape = local_array.shape # shape of local_array
    local_axis_len = local_shape[axis]
    local_axis_lens = comm.allgather(local_axis_len)
    global_axis_len = sum(local_axis_lens)
    global_shape = list(local_shape)
    global_shape[axis] = global_axis_len
    global_shape = tuple(global_shape) # shape of global array
    local_start = [0] * len(global_shape)
    local_start[axis] = np.cumsum([0] + local_axis_lens)[comm.rank] # start of local_array in global array

    # open the file in write only mode
    fh = MPI.File.Open(comm, filename, amode=MPI.MODE_CREATE | MPI.MODE_WRONLY)

    # check validity of version
    fm._check_version(version)
    # first write the array header to file by process 0
    if comm.rank == 0:
        # get the header, which is a dict
        header = fm.header_data_from_array_1_0(local_array)
        # update the shape value to shape of the global array
        header['shape'] = global_shape
        # write header to file
        used_ver = fm._write_array_header(fh, header, version)
        # this warning can be removed when 1.9 has aged enough
        if version != (2, 0) and used_ver == (2, 0):
            warnings.warn("Stored array in format 2.0. It can only be"
                        "read by NumPy >= 1.9", UserWarning, stacklevel=2)

        # get the position of the individual file pointer,
        # which is now at the end of the file
        pos = fh.Get_position()
    else:
        pos = 0

    # broadcast the end position of the file to all processes
    pos = comm.bcast(pos, root=0)

    # get the etype
    etype = typemap(local_array.dtype)

    # construct the filetype
    filetype = etype.Create_subarray(global_shape, local_shape, local_start, order=MPI.ORDER_C)
    filetype.Commit()

    # set the file view
    fh.Set_view(pos, etype, filetype, datarep='native')

    # collectively write the array to file
    fh.Write_all(local_array)

    # close the file
    fh.Close()


def parallel_read_array(filename, axis=0, comm=None):
    """
    Parallelly read an array from an NPY file, each process reads its own part.

    Parameters
    ----------
    filename : str
        Name of the file constains the array.
    axis : int
        The axis to distribute the array on each process.
    comm : mpi4py communicator or None.
        A valid mpi4py communicator or None if no MPI.

    Returns
    -------
    local_array : ndarray
        The array local to this process from the data on disk.

    """

    # if no MPI, or only 1 MPI process, call np.load directly
    if comm is None or comm.size == 1:
        return np.load(filename)

    # open the file in read only mode
    fh = MPI.File.Open(comm, filename, amode=MPI.MODE_RDONLY)

    # read and check version of the npy file
    version = fm.read_magic(fh)
    fm._check_version(version)
    # get shape, order, dtype info of the array
    global_shape, fortran_order, dtype = fm._read_array_header(fh, version)

    if dtype.hasobject:
        # contain Python objects
        raise RuntimeError('Currently not support array that contains Python objects')
    if fortran_order:
        raise RuntimeError('Currently not support Fortran ordered array')

    local_shape = list(global_shape)
    axis_len = local_shape[axis]
    base = axis_len / comm.size
    rem = axis_len % comm.size
    part = base * np.ones(comm.size, dtype=np.int) + (np.arange(comm.size) < rem).astype(np.int)
    bound = np.cumsum(np.insert(part, 0, 0))
    local_shape[axis] = part[comm.rank] # shape of local array
    local_start = [0] * len(global_shape)
    local_start[axis] = bound[comm.rank] # start of local_array in global array

    # allocate space for local_array to hold data read from file
    local_array = np.empty(local_shape, dtype=dtype, order='C')

    # get the position of the individual file pointer,
    # which is at the end of the header, the start of array data
    pos = fh.Get_position()

    # get the etype
    etype = typemap(dtype)

    # construct the filetype
    filetype = etype.Create_subarray(global_shape, local_shape, local_start, order=MPI.ORDER_C)
    filetype.Commit()

    # set the file view
    fh.Set_view(pos, etype, filetype, datarep='native')

    # collectively read the array from file
    fh.Read_all(local_array)

    # close the file
    fh.Close()

    return local_array


filename = 'test.npy'
local_array = np.arange(12, dtype='i').reshape(3, 4)

# parallelly write local array to file, assume array is distributed on axis 1, i.e., column
parallel_write_array(filename, local_array, axis=1, comm=comm)

# check data in the file
if rank == 0:
    print 'data in file: %s' % np.load(filename)

# now parallelly read data from file, each process read several row of the array
print 'process %d read: %s' % (rank, parallel_read_array(filename, axis=0, comm=comm))

运行结果如下:

$ mpiexec -n 2 python npy_io.py
data in file: [[ 0  1  2  3  0  1  2  3]
[ 4  5  6  7  4  5  6  7]
[ 8  9 10 11  8  9 10 11]]
process 0 read: [[0 1 2 3 0 1 2 3]
[4 5 6 7 4 5 6 7]]
process 1 read: [[ 8  9 10 11  8  9 10 11]]

以上介绍了 mpi4py 中并行读/写 numpy npy 文件的方法,在下一篇中我们将介绍 mpi4py 初始化和运行时设置。

你可能感兴趣的:(mpi4py 并行读/写 numpy npy 文件的方法)