NumPy & SciPy compatible GPU-accelerated array library for CUDA computing
—
Comprehensive array creation functions and manipulation operations compatible with NumPy, enabling easy migration of existing code to GPU acceleration. CuPy provides complete GPU implementations of NumPy's array creation and manipulation capabilities.
Create arrays on GPU with various initialization patterns and data sources.
def array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0):
"""Create an array from object on GPU.
Args:
object: Array-like object to convert
dtype: Data type, defaults to object's dtype
copy: Whether to copy data if already an array
order: Memory layout ('C', 'F', 'A', 'K')
subok: Allow subclasses
ndmin: Minimum number of dimensions
Returns:
cupy.ndarray: GPU array
"""
def zeros(shape, dtype=float32, order='C'):
"""Create array filled with zeros.
Args:
shape: Shape of the array
dtype: Data type, defaults to float32
order: Memory layout ('C' or 'F')
Returns:
cupy.ndarray: Zero-filled array
"""
def ones(shape, dtype=None, order='C'):
"""Create array filled with ones.
Args:
shape: Shape of the array
dtype: Data type, defaults to float64
order: Memory layout ('C' or 'F')
Returns:
cupy.ndarray: One-filled array
"""
def empty(shape, dtype=float32, order='C'):
"""Create uninitialized array.
Args:
shape: Shape of the array
dtype: Data type, defaults to float32
order: Memory layout ('C' or 'F')
Returns:
cupy.ndarray: Uninitialized array
"""
def full(shape, fill_value, dtype=None, order='C'):
"""Create array filled with specific value.
Args:
shape: Shape of the array
fill_value: Value to fill array with
dtype: Data type, defaults to fill_value's dtype
order: Memory layout ('C' or 'F')
Returns:
cupy.ndarray: Filled array
"""
def arange(start, stop=None, step=1, dtype=None):
"""Create array with evenly spaced values.
Args:
start: Start value or stop if single argument
stop: Stop value (exclusive)
step: Step size
dtype: Data type
Returns:
cupy.ndarray: Array with evenly spaced values
"""
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0):
"""Create array with linearly spaced values.
Args:
start: Start value
stop: Stop value
num: Number of samples
endpoint: Include stop value
retstep: Return step size
dtype: Data type
axis: Axis along which to store samples
Returns:
cupy.ndarray or tuple: Array and optionally step size
"""
def eye(N, M=None, k=0, dtype=float, order='C'):
"""Create identity matrix or matrix with ones on diagonal.
Args:
N: Number of rows
M: Number of columns, defaults to N
k: Diagonal offset
dtype: Data type
order: Memory layout
Returns:
cupy.ndarray: 2D array with ones on k-th diagonal
"""
def identity(n, dtype=None):
"""Create identity matrix.
Args:
n: Number of rows and columns
dtype: Data type, defaults to float64
Returns:
cupy.ndarray: n x n identity matrix
"""Create arrays similar to existing arrays with different properties.
def zeros_like(a, dtype=None, order='K', subok=True, shape=None):
"""Create zeros array with same shape as input."""
def ones_like(a, dtype=None, order='K', subok=True, shape=None):
"""Create ones array with same shape as input."""
def empty_like(a, dtype=None, order='K', subok=True, shape=None):
"""Create uninitialized array with same shape as input."""
def full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None):
"""Create filled array with same shape as input."""Modify array shapes and dimensions while preserving data.
def reshape(a, newshape, order='C'):
"""Change array shape without changing data.
Args:
a: Input array
newshape: New shape
order: Memory layout
Returns:
cupy.ndarray: Reshaped array view or copy
"""
def transpose(a, axes=None):
"""Reverse or permute array dimensions.
Args:
a: Input array
axes: Permutation of axes
Returns:
cupy.ndarray: Transposed array
"""
def flatten(a, order='C'):
"""Return flattened copy of array.
Args:
a: Input array
order: Memory layout ('C', 'F', 'A', 'K')
Returns:
cupy.ndarray: 1D copy of input
"""
def ravel(a, order='C'):
"""Return flattened array (view if possible).
Args:
a: Input array
order: Memory layout
Returns:
cupy.ndarray: 1D array (view or copy)
"""
def squeeze(a, axis=None):
"""Remove single-dimensional entries.
Args:
a: Input array
axis: Specific axes to squeeze
Returns:
cupy.ndarray: Squeezed array
"""
def expand_dims(a, axis):
"""Expand array dimensions.
Args:
a: Input array
axis: Position of new axis
Returns:
cupy.ndarray: Array with expanded dimensions
"""Combine or split arrays along various axes.
def concatenate(arrays, axis=0, out=None, dtype=None, casting="same_kind"):
"""Join arrays along existing axis.
Args:
arrays: Sequence of arrays
axis: Axis to join along
out: Output array
dtype: Output data type
casting: Type casting rule
Returns:
cupy.ndarray: Concatenated array
"""
def stack(arrays, axis=0, out=None):
"""Join arrays along new axis.
Args:
arrays: Sequence of arrays
axis: Axis to stack along
out: Output array
Returns:
cupy.ndarray: Stacked array
"""
def hstack(tup):
"""Stack arrays horizontally (column-wise)."""
def vstack(tup):
"""Stack arrays vertically (row-wise)."""
def dstack(tup):
"""Stack arrays depth-wise (along third axis)."""
def split(ary, indices_or_sections, axis=0):
"""Split array into sub-arrays.
Args:
ary: Input array
indices_or_sections: Split points or number of sections
axis: Axis to split along
Returns:
list: List of sub-arrays
"""
def hsplit(ary, indices_or_sections):
"""Split array horizontally."""
def vsplit(ary, indices_or_sections):
"""Split array vertically."""
def dsplit(ary, indices_or_sections):
"""Split array depth-wise."""Control memory layout and data sharing between arrays.
def copy(a, order='K', subok=False):
"""Return array copy.
Args:
a: Input array
order: Memory layout
subok: Allow subclasses
Returns:
cupy.ndarray: Copy of input array
"""
def asarray(a, dtype=None, order=None):
"""Convert input to array (copy if needed).
Args:
a: Input data
dtype: Data type
order: Memory layout
Returns:
cupy.ndarray: Array representation
"""
def ascontiguousarray(a, dtype=None):
"""Return C-contiguous array.
Args:
a: Input array
dtype: Data type
Returns:
cupy.ndarray: C-contiguous array
"""
def copyto(dst, src, casting='same_kind', where=True):
"""Copy values from one array to another.
Args:
dst: Destination array
src: Source array or scalar
casting: Type casting rule
where: Boolean mask
"""import cupy as cp
# Create various array types
zeros_arr = cp.zeros((3, 4))
ones_arr = cp.ones((2, 3), dtype=cp.float32)
range_arr = cp.arange(0, 10, 2)
linear_arr = cp.linspace(0, 1, 5)
# Create from Python data
data = [[1, 2, 3], [4, 5, 6]]
gpu_arr = cp.array(data, dtype=cp.float32)# Original array
arr = cp.arange(12) # [0, 1, 2, ..., 11]
# Reshape operations
reshaped = arr.reshape(3, 4)
transposed = reshaped.T
flattened = reshaped.flatten()
# Dimension manipulation
expanded = cp.expand_dims(arr, axis=1) # Add new axis
squeezed = cp.squeeze(expanded) # Remove single dimensionsa = cp.array([[1, 2], [3, 4]])
b = cp.array([[5, 6], [7, 8]])
# Join along different axes
horizontal = cp.hstack([a, b]) # [[1, 2, 5, 6], [3, 4, 7, 8]]
vertical = cp.vstack([a, b]) # [[1, 2], [3, 4], [5, 6], [7, 8]]
stacked = cp.stack([a, b], axis=2) # 3D array
# Split arrays
sub_arrays = cp.split(vertical, 2, axis=0) # Split into 2 parts# Control memory layout and copying
cpu_data = [[1, 2, 3], [4, 5, 6]]
gpu_arr = cp.asarray(cpu_data) # Minimal copying
# Ensure C-contiguous layout for performance
contiguous = cp.ascontiguousarray(gpu_arr)
# Explicit copying
arr_copy = cp.copy(gpu_arr)Install with Tessl CLI
npx tessl i tessl/pypi-cupy-cuda114