CuPy: NumPy & SciPy for GPU - A NumPy/SciPy-compatible array library for GPU-accelerated computing with Python, specifically built for AMD ROCm 4.3 platform
—
File input/output operations for saving and loading CuPy arrays and data. These functions provide compatibility with NumPy's I/O format while handling GPU-CPU data transfers automatically.
Save and load arrays in NumPy's binary formats with automatic GPU-CPU data transfers.
def save(file, arr, allow_pickle=True, fix_imports=True):
"""
Save an array to a binary file in NumPy .npy format.
Parameters:
- file: str or file-like, filename or file object
- arr: cupy.ndarray, array to save
- allow_pickle: bool, allow saving object arrays using Python pickles
- fix_imports: bool, only useful for loading Python 2 generated pickled files
"""
def savez(file, *args, **kwds):
"""
Save several arrays into a single file in uncompressed .npz format.
Parameters:
- file: str or file-like, filename or file object
- args: cupy.ndarray, arrays to save as positional arguments
- kwds: cupy.ndarray, arrays to save as keyword arguments
"""
def savez_compressed(file, *args, **kwds):
"""
Save several arrays into a single file in compressed .npz format.
Parameters:
- file: str or file-like, filename or file object
- args: cupy.ndarray, arrays to save as positional arguments
- kwds: cupy.ndarray, arrays to save as keyword arguments
"""
def load(file, mmap_mode=None, allow_pickle=False, fix_imports=True, encoding='ASCII'):
"""
Load arrays or pickled objects from .npy, .npz or pickled files.
Parameters:
- file: str or file-like, filename or file object
- mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, memory-mapping mode
- allow_pickle: bool, allow loading pickled object arrays
- fix_imports: bool, only useful for loading Python 2 generated pickled files
- encoding: str, encoding used to decode py2 strings
Returns:
cupy.ndarray, dict, or object: loaded array(s) or object
"""Load and save arrays in text formats with automatic data type conversion.
def loadtxt(fname, dtype=float, comments='#', delimiter=None, converters=None,
skiprows=0, usecols=None, unpack=False, ndmin=0, encoding='bytes',
max_rows=None):
"""
Load data from a text file into a GPU array.
Parameters:
- fname: str or file-like, filename or file object
- dtype: data-type, data type of the resulting array
- comments: str or sequence, characters marking comments
- delimiter: str, string used to separate values
- converters: dict, mapping column to function for conversion
- skiprows: int, number of lines to skip at beginning
- usecols: int or sequence, columns to read
- unpack: bool, if True, return arrays for each column
- ndmin: int, minimum number of dimensions
- encoding: str, encoding to decode input
- max_rows: int, maximum number of rows to read
Returns:
cupy.ndarray: array from text file
"""
def savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='',
footer='', comments='# ', encoding=None):
"""
Save a GPU array to a text file.
Parameters:
- fname: str or file-like, filename or file object
- X: cupy.ndarray, 1-D or 2-D array to save
- fmt: str or sequence, format string for array elements
- delimiter: str, string separating columns
- newline: str, string separating lines
- header: str, text written at beginning of file
- footer: str, text written at end of file
- comments: str, string to prepend to header and footer
- encoding: str, encoding used to encode file
"""
def genfromtxt(fname, dtype=float, comments='#', delimiter=None, skip_header=0,
skip_footer=0, converters=None, missing_values=None,
filling_values=None, usecols=None, names=None, excludelist=None,
deletechars=''.join(sorted(set(string.punctuation) - set('_'))),
defaultfmt="f%i", autostrip=False, replace_space='_',
case_sensitive=True, unpack=None, invalid_raise=True,
max_rows=None, encoding='bytes'):
"""
Load data from a text file with missing values handled as specified.
Parameters:
- fname: str or file-like, filename or file object
- dtype: data-type, data type of the resulting array
- comments: str or sequence, characters marking comments
- delimiter: str, string used to separate values
- skip_header: int, number of lines to skip at beginning
- skip_footer: int, number of lines to skip at end
- converters: dict, mapping column to conversion function
- missing_values: set, strings corresponding to missing values
- filling_values: set, values to use for missing data
- usecols: sequence, columns to read
- names: {None, True, str, sequence}, field names for structured array
- excludelist: sequence, names of fields to exclude
- deletechars: str, characters to remove from field names
- defaultfmt: str, format of field names
- autostrip: bool, whether to strip whitespace from values
- replace_space: str, character to replace spaces in field names
- case_sensitive: bool, whether field names are case sensitive
- unpack: bool, if True, return separate variables for each column
- invalid_raise: bool, whether to raise exception for inconsistent data
- max_rows: int, maximum number of rows to read
- encoding: str, encoding to decode input
Returns:
cupy.ndarray: array from text file with missing values handled
"""Format arrays as strings for display and output purposes.
def array_str(a, max_line_width=None, precision=None, suppress_small=None):
"""
Return a string representation of an array.
Parameters:
- a: cupy.ndarray, input array
- max_line_width: int, maximum line width for printing
- precision: int, floating point precision
- suppress_small: bool, whether to suppress small values
Returns:
str: string representation of array
"""
def array_repr(arr, max_line_width=None, precision=None, suppress_small=None):
"""
Return string representation of array that recreates the array.
Parameters:
- arr: cupy.ndarray, input array
- max_line_width: int, maximum line width for printing
- precision: int, floating point precision
- suppress_small: bool, whether to suppress small values
Returns:
str: string representation of array
"""
def array2string(a, max_line_width=None, precision=None, suppress_small=None,
separator=' ', prefix="", style=float, formatter=None,
threshold=None, edgeitems=None, sign=None, floatmode=None,
suffix="", legacy=None):
"""
Return a string representation of an array with full control over formatting.
Parameters:
- a: cupy.ndarray, input array
- max_line_width: int, maximum line width
- precision: int, floating point precision
- suppress_small: bool, suppress small values in scientific notation
- separator: str, separator between array elements
- prefix: str, string prepended to each line
- style: function, formatting function for array elements
- formatter: dict, custom formatting functions for different data types
- threshold: int, total number of elements triggering summarization
- edgeitems: int, number of edge items to show in summary
- sign: str, controls printing of the sign of floats
- floatmode: str, controls precision of floating point output
- suffix: str, string appended to each line
- legacy: str, legacy printing mode compatibility
Returns:
str: formatted string representation of array
"""import cupy as cp
# Save and load single array
x = cp.array([1, 2, 3, 4, 5])
cp.save('array.npy', x)
loaded_x = cp.load('array.npy')
# Save multiple arrays
y = cp.array([[1, 2], [3, 4]])
z = cp.array([5, 6, 7])
cp.savez('arrays.npz', x=x, y=y, z=z)
# Load multiple arrays
data = cp.load('arrays.npz')
print(data['x'], data['y'], data['z'])
# Text file I/O
data_2d = cp.random.rand(10, 3)
cp.savetxt('data.txt', data_2d, fmt='%.6f', delimiter=',')
loaded_data = cp.loadtxt('data.txt', delimiter=',')
# Array string formatting
arr = cp.array([[1.23456789, 2.34567890], [3.45678901, 4.56789012]])
print(cp.array_str(arr, precision=3))
print(cp.array_repr(arr, precision=2))Install with Tessl CLI
npx tessl i tessl/pypi-cupy-rocm-4-3