or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

array-operations.mdcuda-interface.mdcustom-kernels.mdfft-operations.mdindex.mdlinear-algebra.mdmath-functions.mdrandom-numbers.mdstatistics-sorting.md

array-operations.mddocs/

0

# Array Operations

1

2

Comprehensive array creation, manipulation, and transformation functions that mirror NumPy's API while operating on GPU memory. These functions form the foundation of CuPy's array computing capabilities.

3

4

## Capabilities

5

6

### Array Creation

7

8

Create arrays directly on GPU memory with various initialization patterns.

9

10

```python { .api }

11

def array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0):

12

"""

13

Create an array on GPU.

14

15

Parameters:

16

- object: array-like input data

17

- dtype: data type, optional

18

- copy: whether to copy data

19

- order: memory layout ('C', 'F', 'A', 'K')

20

- subok: allow subclasses

21

- ndmin: minimum number of dimensions

22

23

Returns:

24

cupy.ndarray: GPU array

25

"""

26

27

def asarray(a, dtype=None, order=None):

28

"""Convert input to GPU array."""

29

30

def ascontiguousarray(a, dtype=None):

31

"""Return contiguous array in C order."""

32

33

def copy(a, order='K', subok=False):

34

"""Return array copy."""

35

```

36

37

### Basic Array Creation

38

39

```python { .api }

40

def zeros(shape, dtype=float, order='C'):

41

"""Return array filled with zeros."""

42

43

def ones(shape, dtype=None, order='C'):

44

"""Return array filled with ones."""

45

46

def empty(shape, dtype=float, order='C'):

47

"""Return uninitialized array."""

48

49

def full(shape, fill_value, dtype=None, order='C'):

50

"""Return array filled with fill_value."""

51

52

def zeros_like(a, dtype=None, order='K', subok=True, shape=None):

53

"""Return zeros array with same shape as a."""

54

55

def ones_like(a, dtype=None, order='K', subok=True, shape=None):

56

"""Return ones array with same shape as a."""

57

58

def empty_like(a, dtype=None, order='K', subok=True, shape=None):

59

"""Return empty array with same shape as a."""

60

61

def full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None):

62

"""Return full array with same shape as a."""

63

```

64

65

### Ranges and Sequences

66

67

```python { .api }

68

def arange(start, stop=None, step=1, dtype=None):

69

"""Return evenly spaced values within interval."""

70

71

def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0):

72

"""Return evenly spaced numbers over interval."""

73

74

def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0):

75

"""Return numbers spaced evenly on log scale."""

76

77

def meshgrid(*xi, copy=True, sparse=False, indexing='xy'):

78

"""Return coordinate matrices from coordinate vectors."""

79

```

80

81

### Matrix Creation

82

83

```python { .api }

84

def eye(N, M=None, k=0, dtype=float, order='C'):

85

"""Return 2-D array with ones on diagonal."""

86

87

def identity(n, dtype=None):

88

"""Return identity array."""

89

90

def diag(v, k=0):

91

"""Extract diagonal or construct diagonal array."""

92

93

def diagflat(v, k=0):

94

"""Create 2-D array with flattened input as diagonal."""

95

96

def tri(N, M=None, k=0, dtype=float):

97

"""Array with ones at and below given diagonal."""

98

99

def tril(m, k=0):

100

"""Lower triangle of array."""

101

102

def triu(m, k=0):

103

"""Upper triangle of array."""

104

105

def vander(x, N=None, increasing=False):

106

"""Generate Vandermonde matrix."""

107

```

108

109

### Shape Manipulation

110

111

```python { .api }

112

def reshape(a, newshape, order='C'):

113

"""Return array with new shape."""

114

115

def ravel(a, order='C'):

116

"""Return contiguous flattened array."""

117

118

def flatten(a, order='C'):

119

"""Return copy of array collapsed into one dimension."""

120

121

def squeeze(a, axis=None):

122

"""Remove single-dimensional entries."""

123

124

def expand_dims(a, axis):

125

"""Expand shape by inserting new axes."""

126

```

127

128

### Transposition

129

130

```python { .api }

131

def transpose(a, axes=None):

132

"""Reverse or permute axes."""

133

134

def swapaxes(a, axis1, axis2):

135

"""Interchange two axes."""

136

137

def moveaxis(a, source, destination):

138

"""Move axes to new positions."""

139

140

def rollaxis(a, axis, start=0):

141

"""Roll specified axis backwards."""

142

```

143

144

### Dimension Changes

145

146

```python { .api }

147

def atleast_1d(*arys):

148

"""Convert inputs to arrays with at least 1 dimension."""

149

150

def atleast_2d(*arys):

151

"""Convert inputs to arrays with at least 2 dimensions."""

152

153

def atleast_3d(*arys):

154

"""Convert inputs to arrays with at least 3 dimensions."""

155

156

def broadcast_to(array, shape, subok=False):

157

"""Broadcast array to shape."""

158

159

def broadcast_arrays(*args, subok=False):

160

"""Broadcast arrays to common shape."""

161

```

162

163

### Joining Arrays

164

165

```python { .api }

166

def concatenate(arrays, axis=0, out=None, dtype=None, casting='same_kind'):

167

"""Join arrays along existing axis."""

168

169

def stack(arrays, axis=0, out=None):

170

"""Join arrays along new axis."""

171

172

def vstack(tup):

173

"""Stack arrays vertically."""

174

175

def hstack(tup):

176

"""Stack arrays horizontally."""

177

178

def dstack(tup):

179

"""Stack arrays depth-wise."""

180

181

def column_stack(tup):

182

"""Stack 1-D arrays as columns into 2-D array."""

183

```

184

185

### Splitting Arrays

186

187

```python { .api }

188

def split(ary, indices_or_sections, axis=0):

189

"""Split array into multiple sub-arrays."""

190

191

def array_split(ary, indices_or_sections, axis=0):

192

"""Split array into multiple sub-arrays."""

193

194

def hsplit(ary, indices_or_sections):

195

"""Split array along 2nd axis."""

196

197

def vsplit(ary, indices_or_sections):

198

"""Split array along 1st axis."""

199

200

def dsplit(ary, indices_or_sections):

201

"""Split array along 3rd axis."""

202

```

203

204

### Tiling and Repeating

205

206

```python { .api }

207

def tile(A, reps):

208

"""Construct array by repeating A."""

209

210

def repeat(a, repeats, axis=None):

211

"""Repeat elements of array."""

212

```

213

214

### Adding/Removing Elements

215

216

```python { .api }

217

def append(arr, values, axis=None):

218

"""Append values to end of array."""

219

220

def resize(a, new_shape):

221

"""Return new array with specified shape."""

222

223

def trim_zeros(filt, trim='fb'):

224

"""Trim leading/trailing zeros."""

225

226

def unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None):

227

"""Find unique elements."""

228

```

229

230

### Rearranging Elements

231

232

```python { .api }

233

def flip(m, axis=None):

234

"""Reverse order of elements along axis."""

235

236

def fliplr(m):

237

"""Flip array left to right."""

238

239

def flipud(m):

240

"""Flip array up to down."""

241

242

def roll(a, shift, axis=None):

243

"""Roll array elements along axis."""

244

245

def rot90(m, k=1, axes=(0, 1)):

246

"""Rotate array by 90 degrees."""

247

```

248

249

### Data Conversion

250

251

```python { .api }

252

def asnumpy(a, stream=None, order='C', out=None):

253

"""

254

Convert CuPy array to NumPy array.

255

256

Parameters:

257

- a: input CuPy array

258

- stream: CUDA stream for async transfer

259

- order: memory layout

260

- out: output NumPy array

261

262

Returns:

263

numpy.ndarray: array on CPU

264

"""

265

266

def asarray_chkfinite(a, dtype=None, order=None):

267

"""Convert to array checking for NaNs or Infs."""

268

269

def asfarray(a, dtype=float):

270

"""Return array converted to float type."""

271

272

def asfortranarray(a, dtype=None):

273

"""Return array laid out in Fortran order."""

274

275

def require(a, dtype=None, requirements=None):

276

"""Return array satisfying requirements."""

277

```

278

279

## Usage Examples

280

281

### Basic Array Creation

282

283

```python

284

import cupy as cp

285

286

# Create arrays with different initialization

287

zeros = cp.zeros((3, 4))

288

ones = cp.ones((2, 2), dtype=cp.float32)

289

identity = cp.eye(5)

290

range_array = cp.arange(10)

291

linear = cp.linspace(0, 1, 100)

292

293

# Create from existing data

294

cpu_data = [1, 2, 3, 4, 5]

295

gpu_array = cp.array(cpu_data)

296

```

297

298

### Shape Manipulation

299

300

```python

301

import cupy as cp

302

303

# Create and reshape arrays

304

arr = cp.arange(12)

305

reshaped = arr.reshape(3, 4)

306

flattened = reshaped.ravel()

307

308

# Transpose operations

309

matrix = cp.random.random((3, 4, 5))

310

transposed = cp.transpose(matrix, (2, 0, 1))

311

swapped = cp.swapaxes(matrix, 0, 2)

312

```

313

314

### Array Joining and Splitting

315

316

```python

317

import cupy as cp

318

319

# Join arrays

320

arr1 = cp.array([1, 2, 3])

321

arr2 = cp.array([4, 5, 6])

322

joined = cp.concatenate([arr1, arr2])

323

stacked = cp.stack([arr1, arr2])

324

325

# Split arrays

326

data = cp.arange(10)

327

split_arrays = cp.split(data, 5) # Split into 5 equal parts

328

first_half, second_half = cp.array_split(data, 2)

329

```