Single tensors · .npy

NumPy .npy array file

A single N-d array: a 6-byte magic, 2 version bytes, a little-endian header length, and an ASCII/latin1/UTF-8 Python-dict-literal header {'descr','fortran_order','shape'} padded so the data starts at a multiple of 64, then the raw array bytes in C or Fortran order. Byte order is declared per array in descr, so big-endian is possible. Object arrays are stored as a pickle (unsafe). It is the simplest cross-language interchange format for one tensor, with readers for C/C++ (cnpy, xtensor), Rust (ndarray-npy, npyz), Julia, JS and Go.

What it is
one tensor
Byte order
per array declared
Dimension order
per array flag
Compression
none
Metadata
none
Loading
may execute code on load

How to read it

magic(6) | major(1) | minor(1) | HEADER_LEN (u16 v1 / u32 v2,v3 LE) | header text | data

magicbytes[6]
majoru8
minoru8
header_lenu16le
header_lenu32le
headerlatin1[header_len] | utf8[header_len]
databytes[prod(shape)*itemsize]for 'O' arrays: a pickle stream instead
0      6  7  8        10/12                                      64*k
+------+--+--+--------+-----------------------------------------+-------------+
|\x93NUMPY|ma|mi| HLEN | {'descr': '<f4', 'fortran_order': ...}   \n| array bytes |
+------+--+--+--------+-----------------------------------------+-------------+

One tensor

namenone (derive from the file name)
dtypeheader.descr (simple) -> canonical, ignoring the byte-order char
shapeheader.shape (logical, outermost first, for both orders)
data_offsetlen(magic)+2+len(header_len field)+header_len
nbytesprod(shape) * itemsize
order'F' if fortran_order else 'C'
byte_orderdescr[0]: '<' little, '>' big, '|' n/a
alignment64. start of array data. numpy >= 1.14.0 pads so (magic+version+length field+header) % 64 == 0 (ARRAY_ALIGN, PR 9025). numpy < 1.14 used 16, and v2 was sometimes aligned to less than 16.

Header

Exactly the keys descr, fortran_order, shape (any other set is rejected). The numpy writer emits them sorted, as "{'descr': '<f4', 'fortran_order': False, 'shape': (3, 4), }", followed by GROWTH_AXIS spare spaces, then alignment spaces and '\n'.

header  := "{" entry ("," entry)* ","? "}" " "* "\n"     # a Python dict literal, parsed with ast.literal_eval
entry   := "'descr': " descr | "'fortran_order': " ("True"|"False") | "'shape': " tuple
tuple   := "()" | "(" int ",)" | "(" int ("," " "? int)+ ")"
descr   := "'" byteorder kind size "'"                    # simple dtype, e.g. '<f4' '|u1' '>i8' '<U10'
         | "[" field ("," field)* "]"                     # structured dtype, list of tuples
byteorder := "<" | ">" | "|" | "="                        # writers emit < > | only
kind    := "b" bool | "i" int | "u" uint | "f" float | "c" complex | "V" void | "S" bytes | "U" UCS4 str
         | "O" object | "M8[unit]" datetime64 | "m8[unit]" timedelta64
field   := "(" name "," descr ("," shape)? ")"

Reader

The procedure that finds each tensor's bytes.

read

pseudo-python
def read_npy(f, allow_pickle=False):
    if f.read(6) != b"\x93NUMPY": raise Invalid("magic")
    major, minor = f.read(1)[0], f.read(1)[0]
    if (major, minor) == (1, 0): hl = unpack("<H", f.read(2)); enc = "latin1"
    elif (major, minor) in ((2, 0), (3, 0)): hl = unpack("<I", f.read(4)); enc = "latin1" if major == 2 else "utf8"
    else: raise Unsupported((major, minor))
    text = f.read(hl).decode(enc)
    d = literal_eval(text)                           # safe parser; grammar in types.Header
    if set(d) != {"descr", "fortran_order", "shape"}: raise Invalid("keys")
    dt = parse_descr(d["descr"])                     # -> (canonical, itemsize, byte_order) or structured/object
    if dt.is_object:
        if not allow_pickle: raise Invalid("object array needs pickle")
        return unpickle(f)                           # UNSAFE
    shape = list(d["shape"]); n = prod(shape) * dt.itemsize
    offset = f.tell()                                # normally a multiple of 64
    data = f.read(n)
    if len(data) != n: raise Invalid("truncated")
    if dt.byte_order == ">": data = byteswap(data, CANON[dt.canonical])   # canonical is little-endian; '>c8' swaps each f32 part
    if d["fortran_order"]: data = fortran_to_c(data, shape, dt.itemsize)   # transpose copy
    return Tensor(name=None, dtype=dt.canonical, shape=shape, data=data)

Number formats

The name in the file, and the canonical dtype it maps to.

In the fileCodeCanonicalBits
bool|b1bool8
int8|i1int88
uint8|u1uint88
int16<i2int1616
uint16<u2uint1616
int32<i4int3232
uint32<u4uint3232
int64<i8int6464
uint64<u8uint6464
float16<f2float1616
float32<f4float3232
float64<f8float6464
longdouble<f16none128
complex64<c8complex6464
complex128<c16complex128128
datetime64<M8[unit]none64
timedelta64<m8[unit]none64
bytes|S<n>none—
str<U<n>none—
void|V<n> / <V<n>none—
object|Onone—
structured[(...)]none—

Reject the file when

Listed in the spec's order. Only rules marked MUST that reject the file are shown. The other IDs are warnings or implementation limits. A rule marked suggestion is the spec project's own decision where no official document decides. It is not the format's official behaviour.

RuleMust holdError
NPY-001

bytes 0..5 == \x93NUMPY

NPY-002

(major, minor) in {(1,0),(2,0),(3,0)}

NPY-003

header is a dict literal with exactly the keys descr, fortran_order, shape

EXPECTED_KEYS == d.keys()
NPY-004

shape is a tuple of non-negative ints; fortran_order is a bool; descr parses as a dtype

NPY-006Suggestion SUG-013

file holds at least prod(shape)*itemsize data bytes; numpy ignores trailing bytes for np.load, but np.memmap/fromfile take exactly that count

NPY-008

descr with 'O' (anywhere, including inside structured dtypes) is refused unless pickle is explicitly allowed

Example

Example file. numpy 2.5.4 wrote this file. The file has no array name inside it; the name is the stem, w_f32.

w_f32.npy1,152 bytes

NameDtypeShapeBytes
w_f32<f4float324 × 641,024

Header

{'descr': '<f4', 'fortran_order': False, 'shape': (4, 64), }

Sources

Tensref rev 3.1