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

本文详细介绍了如何使用 mpi4py 并行读/写 numpy npy 文件,包括文件格式、并行写入数组的步骤、并行读取数组的步骤,以及相关操作的示例代码。内容涵盖了 numpy npy 文件的结构,以及如何通过 MPI 进程高效地进行并行 I/O 操作。
摘要由CSDN通过智能技术生成

本文从本人简书博客同步过来

上一篇中我们介绍了 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
<https://www.numpy.org/neps/nep-0001-npy-format.html>`_, 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 > 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值