CuPy: NumPy & SciPy for GPU - CUDA 11.x optimized distribution providing GPU-accelerated computing with Python
—
CuPy provides comprehensive array operations for GPU-accelerated computation, offering NumPy-compatible array creation, manipulation, indexing, reshaping, joining, and splitting operations optimized for CUDA and ROCm platforms.
Core array creation functions for initializing GPU arrays with various patterns and data sources.
def array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0):
"""
Create an array from an array-like object.
Parameters:
object: array_like - Input data in any form convertible to an array
dtype: data-type, optional - Desired data type for the array
copy: bool, optional - If True, create a copy of the object
order: {'K', 'A', 'C', 'F'}, optional - Memory layout
subok: bool, optional - If True, sub-classes will be passed through
ndmin: int, optional - Minimum number of dimensions
"""
def zeros(shape, dtype=float, order='C'):
"""
Return a new array of given shape and type, filled with zeros.
Parameters:
shape: int or tuple of ints - Shape of the new array
dtype: data-type, optional - Desired data type for the array
order: {'C', 'F'}, optional - Row-major (C) or column-major (F) order
"""
def ones(shape, dtype=None, order='C'):
"""
Return a new array of given shape and type, filled with ones.
Parameters:
shape: int or tuple of ints - Shape of the new array
dtype: data-type, optional - Desired data type for the array
order: {'C', 'F'}, optional - Row-major (C) or column-major (F) order
"""
def empty(shape, dtype=float, order='C'):
"""
Return a new array of given shape and type, without initializing entries.
Parameters:
shape: int or tuple of ints - Shape of the new array
dtype: data-type, optional - Desired data type for the array
order: {'C', 'F'}, optional - Row-major (C) or column-major (F) order
"""
def full(shape, fill_value, dtype=None, order='C'):
"""
Return a new array of given shape and type, filled with fill_value.
Parameters:
shape: int or tuple of ints - Shape of the new array
fill_value: scalar - Fill value
dtype: data-type, optional - Desired data type for the array
order: {'C', 'F'}, optional - Row-major (C) or column-major (F) order
"""
def eye(N, M=None, k=0, dtype=float, order='C'):
"""
Return a 2-D array with ones on the diagonal and zeros elsewhere.
Parameters:
N: int - Number of rows in the output
M: int, optional - Number of columns in the output (defaults to N)
k: int, optional - Index of the diagonal
dtype: data-type, optional - Data type of the returned array
order: {'C', 'F'}, optional - Row-major (C) or column-major (F) order
"""
def identity(n, dtype=None):
"""
Return the identity array.
Parameters:
n: int - Number of rows (and columns) in n x n output
dtype: data-type, optional - Data type of the output
"""Functions for creating arrays from existing data sources including arrays, files, and iterables.
def asarray(a, dtype=None, order=None):
"""
Convert the input to an array.
Parameters:
a: array_like - Input data in any form convertible to an array
dtype: data-type, optional - Data type
order: {'C', 'F'}, optional - Memory layout order
"""
def asanyarray(a, dtype=None, order=None):
"""
Convert the input to an array, preserving array subclasses.
Parameters:
a: array_like - Input data
dtype: data-type, optional - Data type
order: {'C', 'F'}, optional - Memory layout order
"""
def ascontiguousarray(a, dtype=None):
"""
Return a contiguous array in memory (C order).
Parameters:
a: array_like - Input array
dtype: data-type, optional - Data type
"""
def copy(a, order='K'):
"""
Return an array copy of the given object.
Parameters:
a: array_like - Input data
order: {'C', 'F', 'A', 'K'}, optional - Memory layout order
"""
def fromfile(file, dtype=float, count=-1, sep=''):
"""
Construct an array from data in a text or binary file.
Parameters:
file: file or str - Open file object or filename
dtype: data-type - Data type of the returned array
count: int - Number of items to read (-1 means all data)
sep: str - Separator between items for text files
"""
def fromfunction(function, shape, **kwargs):
"""
Construct an array by executing a function over each coordinate.
Parameters:
function: callable - Function is called with N parameters
shape: tuple of ints - Shape of the output array
**kwargs: keyword arguments passed to function
"""
def fromiter(iterable, dtype, count=-1):
"""
Create a new 1-dimensional array from an iterable object.
Parameters:
iterable: iterable object - An iterable object providing data for the array
dtype: data-type - The data type of the returned array
count: int, optional - The number of items to read from iterable
"""
def frombuffer(buffer, dtype=float, count=-1, offset=0):
"""
Interpret a buffer as a 1-dimensional array.
Parameters:
buffer: buffer_like - An object that exposes the buffer interface
dtype: data-type, optional - Data type of the returned array
count: int, optional - Number of items to read
offset: int, optional - Start reading buffer from this offset
"""
def fromstring(string, dtype=float, count=-1, sep=''):
"""
A new 1-D array initialized from text data in a string.
Parameters:
string: str - A string containing the data
dtype: data-type, optional - The data type of the array
count: int, optional - Read this number of dtype elements from the data
sep: str, optional - The string separating numbers in the data
"""
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.
Parameters:
fname: file, str, pathlib.Path, list of str, generator - File to read
dtype: data-type, optional - Data type of the resulting array
comments: str or sequence of str, optional - Characters or list of characters used to indicate the start of a comment
delimiter: str, optional - String used to separate values
converters: dict, optional - Dictionary mapping column number to function that converts the column string to the appropriate Python type
skiprows: int, optional - Skip the first skiprows lines, including comments
usecols: int or sequence, optional - Which columns to read
unpack: bool, optional - If True, return data in separate arrays
ndmin: int, optional - Minimum number of dimensions that the returned array should have
encoding: str, optional - Encoding used to decode the inputfile
max_rows: int, optional - Read max_rows lines of content after skiprows lines
"""
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(NameValidator.defaultexcludelist)), 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: file, str, pathlib.Path, list of str, generator - File to read
dtype: dtype, optional - Data type of the resulting array
comments: str, optional - Characters used to indicate the start of a comment
delimiter: str, int, or sequence, optional - String(s) used to separate values
skip_header: int, optional - Number of lines to skip at the beginning of the file
skip_footer: int, optional - Number of lines to skip at the end of the file
converters: variable or None, optional - Set of functions that convert the data of a column to a value
missing_values: variable or None, optional - Set of strings corresponding to missing data
filling_values: variable or None, optional - Set of values to be used as default when the data are missing
usecols: sequence or None, optional - Which columns to read
names: {None, True, str, sequence}, optional - Names for the columns
excludelist: sequence, optional - List of names to exclude
deletechars: str, optional - Characters to remove from the field names
defaultfmt: str, optional - Format used to define the field names
autostrip: bool, optional - Whether to automatically strip whitespaces from the values
replace_space: char, optional - Character(s) used in replacement of white spaces in the field names
case_sensitive: {True, False, 'upper', 'lower'}, optional - If True, field names are case sensitive
unpack: bool, optional - If True, return data in separate variables
invalid_raise: bool, optional - If True, an exception is raised if an inconsistency is detected in the number of columns
max_rows: int, optional - Maximum number of rows to read
encoding: str, optional - Encoding used to decode the inputfile
"""Functions for creating arrays with evenly or logarithmically spaced values.
def arange(start, stop=None, step=1, dtype=None):
"""
Return evenly spaced values within a given interval.
Parameters:
start: number, optional - Start of interval (default is 0)
stop: number - End of interval (not included)
step: number, optional - Spacing between values (default is 1)
dtype: dtype, optional - Type of the output array
"""
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0):
"""
Return evenly spaced numbers over a specified interval.
Parameters:
start: array_like - Starting value of the sequence
stop: array_like - End value of the sequence
num: int, optional - Number of samples to generate (default is 50)
endpoint: bool, optional - If True, stop is the last sample
retstep: bool, optional - If True, return (samples, step)
dtype: dtype, optional - Type of the output array
axis: int, optional - Axis in the result to store the samples
"""
def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0):
"""
Return numbers spaced evenly on a log scale.
Parameters:
start: array_like - Base**start is the starting value of the sequence
stop: array_like - Base**stop is the final value of the sequence
num: int, optional - Number of samples to generate (default is 50)
endpoint: bool, optional - If True, stop is the last sample
base: array_like, optional - Base of the log space (default is 10.0)
dtype: dtype, optional - Type of the output array
axis: int, optional - Axis in the result to store the samples
"""
def meshgrid(*xi, copy=True, sparse=False, indexing='xy'):
"""
Return coordinate matrices from coordinate vectors.
Parameters:
xi: array_like - 1-D arrays representing the coordinates of a grid
copy: bool, optional - If False, a view into the original arrays are returned
sparse: bool, optional - If True, return a sparse grid instead of a dense one
indexing: {'xy', 'ij'}, optional - Cartesian ('xy', default) or matrix ('ij') indexing of output
"""Specialized functions for creating matrices and diagonal arrays.
def diag(v, k=0):
"""
Extract a diagonal or construct a diagonal array.
Parameters:
v: array_like - If v is a 2-D array, return its k-th diagonal. If v is 1-D, return a 2-D array with v on the k-th diagonal
k: int, optional - Diagonal offset
"""
def diagflat(v, k=0):
"""
Create a two-dimensional array with the flattened input as a diagonal.
Parameters:
v: array_like - Input data, which is flattened and set as the k-th diagonal of the output
k: int, optional - Diagonal offset
"""
def tri(N, M=None, k=0, dtype=float):
"""
An array with ones at and below the given diagonal and zeros elsewhere.
Parameters:
N: int - Number of rows in the array
M: int, optional - Number of columns in the array (default equals N)
k: int, optional - Sub-diagonal at and below which the array is filled
dtype: dtype, optional - Data type of the returned array
"""
def tril(m, k=0):
"""
Lower triangle of an array.
Parameters:
m: array_like - Input array
k: int, optional - Diagonal above which to zero elements
"""
def triu(m, k=0):
"""
Upper triangle of an array.
Parameters:
m: array_like - Input array
k: int, optional - Diagonal below which to zero elements
"""
def vander(x, N=None, increasing=False):
"""
Generate a Vandermonde matrix.
Parameters:
x: array_like - 1-D input array
N: int, optional - Number of columns in the output (default is len(x))
increasing: bool, optional - Order of the powers of the columns
"""Functions for examining and manipulating array shapes and dimensions.
def shape(a):
"""
Return the shape of an array.
Parameters:
a: array_like - Input array
"""
def ravel(a, order='C'):
"""
Return a contiguous flattened array.
Parameters:
a: array_like - Input array
order: {'C','F', 'A', 'K'}, optional - Memory layout
"""
def reshape(a, newshape, order='C'):
"""
Gives a new shape to an array without changing its data.
Parameters:
a: array_like - Array to be reshaped
newshape: int or tuple of ints - New shape should be compatible with the original shape
order: {'C', 'F', 'A'}, optional - Read the elements using this index order
"""
def resize(a, new_shape):
"""
Return a new array with the specified shape.
Parameters:
a: array_like - Array to be resized
new_shape: int or tuple of ints - Shape of resized array
"""Functions for rearranging array axes and dimensions.
def moveaxis(a, source, destination):
"""
Move axes of an array to new positions.
Parameters:
a: ndarray - Array whose axes should be reordered
source: int or sequence of int - Original positions of the axes to move
destination: int or sequence of int - Destination positions for each of the original axes
"""
def rollaxis(a, axis, start=0):
"""
Roll the specified axis backwards, until it lies in a given position.
Parameters:
a: ndarray - Input array
axis: int - Axis to be rolled
start: int, optional - Position where the rolled axis starts (default is 0)
"""
def swapaxes(a, axis1, axis2):
"""
Interchange two axes of an array.
Parameters:
a: array_like - Input array
axis1: int - First axis
axis2: int - Second axis
"""
def transpose(a, axes=None):
"""
Reverse or permute the axes of an array.
Parameters:
a: array_like - Input array
axes: tuple or list of ints, optional - If specified, it must be a tuple or list which contains a permutation of [0,1,..,N-1] where N is the number of axes of a
"""Functions for adding, removing, and broadcasting array dimensions.
def atleast_1d(*arys):
"""
Convert inputs to arrays with at least one dimension.
Parameters:
arys: array_like - One or more input arrays
"""
def atleast_2d(*arys):
"""
View inputs as arrays with at least two dimensions.
Parameters:
arys: array_like - One or more input arrays
"""
def atleast_3d(*arys):
"""
View inputs as arrays with at least three dimensions.
Parameters:
arys: array_like - One or more input arrays
"""
def broadcast(*args):
"""
Produce an object which mimics broadcasting.
Parameters:
args: array_likes - Input arrays
"""
def broadcast_arrays(*args):
"""
Broadcast any number of arrays against each other.
Parameters:
args: array_likes - Input arrays to broadcast
"""
def broadcast_to(array, shape, subok=False):
"""
Broadcast an array to a new shape.
Parameters:
array: array_like - Array to broadcast
shape: tuple - Shape of the desired array
subok: bool, optional - If True, then sub-classes will be passed-through
"""
def expand_dims(a, axis):
"""
Expand the shape of an array.
Parameters:
a: array_like - Input array
axis: int or tuple of ints - Position in the expanded axes where the new axis (or axes) is placed
"""
def squeeze(a, axis=None):
"""
Remove single-dimensional entries from the shape of an array.
Parameters:
a: array_like - Input data
axis: None or int or tuple of ints, optional - Selects a subset of the single-dimensional entries in the shape
"""Functions for combining multiple arrays along various axes.
def concatenate(arrays, axis=0, out=None):
"""
Join a sequence of arrays along an existing axis.
Parameters:
arrays: sequence of array_like - Arrays must have the same shape, except in the dimension corresponding to axis
axis: int, optional - Axis along which the arrays will be joined (default is 0)
out: ndarray, optional - If provided, the destination to place the result
"""
def stack(arrays, axis=0, out=None):
"""
Join a sequence of arrays along a new axis.
Parameters:
arrays: sequence of array_like - Each array must have the same shape
axis: int, optional - Axis in the result array along which the input arrays are stacked
out: ndarray, optional - If provided, the destination to place the result
"""
def vstack(tup):
"""
Stack arrays in sequence vertically (row wise).
Parameters:
tup: sequence of ndarrays - Arrays to stack
"""
def hstack(tup):
"""
Stack arrays in sequence horizontally (column wise).
Parameters:
tup: sequence of ndarrays - Arrays to stack
"""
def dstack(tup):
"""
Stack arrays in sequence depth wise (along third axis).
Parameters:
tup: sequence of arrays - Arrays to stack
"""
def column_stack(tup):
"""
Stack 1-D arrays as columns into a 2-D array.
Parameters:
tup: sequence of 1-D or 2-D arrays - Arrays to stack
"""Functions for dividing arrays into sub-arrays along various axes.
def split(ary, indices_or_sections, axis=0):
"""
Split an array into multiple sub-arrays as views into ary.
Parameters:
ary: ndarray - Array to be divided into sub-arrays
indices_or_sections: int or 1-D array - If int, N equal sub-arrays are created. If 1-D array of sorted integers, entries indicate where along axis the array is split
axis: int, optional - Axis along which to split (default is 0)
"""
def array_split(ary, indices_or_sections, axis=0):
"""
Split an array into multiple sub-arrays.
Parameters:
ary: ndarray - Array to be divided into sub-arrays
indices_or_sections: int or 1-D array - If int, N sub-arrays of equal or near-equal size are created. If 1-D array, entries indicate split points
axis: int, optional - Axis along which to split (default is 0)
"""
def hsplit(ary, indices_or_sections):
"""
Split an array into multiple sub-arrays horizontally (column-wise).
Parameters:
ary: ndarray - Array to be divided into sub-arrays
indices_or_sections: int or 1-D array - Split specification
"""
def vsplit(ary, indices_or_sections):
"""
Split an array into multiple sub-arrays vertically (row-wise).
Parameters:
ary: ndarray - Array to be divided into sub-arrays
indices_or_sections: int or 1-D array - Split specification
"""
def dsplit(ary, indices_or_sections):
"""
Split array into multiple sub-arrays along the 3rd axis (depth).
Parameters:
ary: ndarray - Array to be divided into sub-arrays
indices_or_sections: int or 1-D array - Split specification
"""Functions for repeating and tiling array elements and patterns.
def tile(A, reps):
"""
Construct an array by repeating A the number of times given by reps.
Parameters:
A: array_like - Input array
reps: array_like - Number of repetitions of A along each axis
"""
def repeat(a, repeats, axis=None):
"""
Repeat elements of an array.
Parameters:
a: array_like - Input array
repeats: int or array of ints - Number of repetitions for each element
axis: int, optional - Axis along which to repeat values
"""Functions for modifying arrays by adding or removing elements.
def append(arr, values, axis=None):
"""
Append values to the end of an array.
Parameters:
arr: array_like - Values are appended to a copy of this array
values: array_like - Values to append to arr
axis: int, optional - Axis along which values are appended
"""
def delete(arr, obj, axis=None):
"""
Return a new array with sub-arrays along an axis deleted.
Parameters:
arr: array_like - Input array
obj: int, slice or array of ints - Indicate indices of sub-arrays to remove along the specified axis
axis: int, optional - Axis along which to delete the subarray defined by obj
"""
def unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None):
"""
Find the unique elements of an array.
Parameters:
ar: array_like - Input array
return_index: bool, optional - If True, also return the indices of ar that result in the unique array
return_inverse: bool, optional - If True, also return the indices of the unique array that can be used to reconstruct ar
return_counts: bool, optional - If True, also return the number of times each unique item appears in ar
axis: int, optional - The axis to operate on
"""
def trim_zeros(filt, trim='fb'):
"""
Trim the leading and/or trailing zeros from a 1-D array or sequence.
Parameters:
filt: 1-D array or sequence - Input array
trim: str, optional - A string with 'f' representing trim from front and 'b' to trim from back
"""Functions for rearranging array elements and changing element order.
def flip(m, axis=None):
"""
Reverse the order of elements in an array along the given axis.
Parameters:
m: array_like - Input array
axis: None or int or tuple of ints, optional - Axis or axes along which to flip over
"""
def fliplr(m):
"""
Flip array in the left/right direction.
Parameters:
m: array_like - Input array, must be at least 2-D
"""
def flipud(m):
"""
Flip array in the up/down direction.
Parameters:
m: array_like - Input array
"""
def roll(a, shift, axis=None):
"""
Roll array elements along a given axis.
Parameters:
a: array_like - Input array
shift: int or array_like - Number of places by which elements are shifted
axis: int or array_like, optional - Axis or axes along which elements are shifted
"""
def rot90(m, k=1, axes=(0, 1)):
"""
Rotate an array by 90 degrees in the plane specified by axes.
Parameters:
m: array_like - Array of two or more dimensions
k: int, optional - Number of times the array is rotated by 90 degrees
axes: array_like - Axes that define the plane of rotation (default is first two axes)
"""import cupy as cp
# Array creation
gpu_array = cp.array([1, 2, 3, 4])
zeros_matrix = cp.zeros((1000, 1000))
identity = cp.eye(5)
# Shape manipulation
reshaped = cp.reshape(gpu_array, (2, 2))
flattened = cp.ravel(zeros_matrix)
# Joining arrays
a = cp.array([[1, 2], [3, 4]])
b = cp.array([[5, 6]])
vstacked = cp.vstack([a, b])
hstacked = cp.hstack([a, a])
# Array splitting
parts = cp.split(gpu_array, 2)
hsplit_result = cp.hsplit(vstacked, 2)
# Element operations
repeated = cp.repeat(gpu_array, 2)
tiled = cp.tile(gpu_array, (2, 1))
unique_vals = cp.unique(cp.array([1, 2, 2, 3, 3, 3]))Array operations in CuPy provide the foundation for GPU-accelerated computation, enabling efficient manipulation of large datasets with NumPy-compatible interfaces while leveraging the parallel processing power of modern GPUs.
Install with Tessl CLI
npx tessl i tessl/pypi-cupy-cuda11x