or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

array-creation.mdcuda-management.mdfft.mdindex.mdkernels.mdlinear-algebra.mdmath-functions.mdrandom.mdscipy-extensions.mdsparse.mdstatistics.md

array-creation.mddocs/

0

# Array Creation and Manipulation

1

2

Core functionality for creating, reshaping, and manipulating GPU arrays with the same interface as NumPy. All operations create arrays on the GPU and support the same broadcasting and indexing semantics as NumPy.

3

4

## Capabilities

5

6

### Basic Array Creation

7

8

Create new arrays with specified shapes, data types, and initialization values.

9

10

```python { .api }

11

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

12

"""

13

Create a GPU array from existing data.

14

15

Parameters:

16

- object: array-like, data to convert to CuPy array

17

- dtype: data type, if None infer from data

18

- copy: bool, whether to copy data

19

- order: {'K', 'A', 'C', 'F'}, memory layout

20

- subok: bool, whether to allow subclasses

21

- ndmin: int, minimum number of dimensions

22

23

Returns:

24

cupy.ndarray: GPU array

25

"""

26

27

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

28

"""

29

Create array filled with zeros.

30

31

Parameters:

32

- shape: int or tuple of ints, shape of new array

33

- dtype: data type, default float64

34

- order: {'C', 'F'}, memory layout

35

36

Returns:

37

cupy.ndarray: Array of zeros

38

"""

39

40

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

41

"""

42

Create array filled with ones.

43

44

Parameters:

45

- shape: int or tuple of ints, shape of new array

46

- dtype: data type, default float64

47

- order: {'C', 'F'}, memory layout

48

49

Returns:

50

cupy.ndarray: Array of ones

51

"""

52

53

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

54

"""

55

Create uninitialized array.

56

57

Parameters:

58

- shape: int or tuple of ints, shape of new array

59

- dtype: data type, default float32

60

- order: {'C', 'F'}, memory layout

61

62

Returns:

63

cupy.ndarray: Uninitialized array

64

"""

65

66

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

67

"""

68

Create array filled with specified value.

69

70

Parameters:

71

- shape: int or tuple of ints, shape of new array

72

- fill_value: scalar, value to fill array with

73

- dtype: data type, if None infer from fill_value

74

- order: {'C', 'F'}, memory layout

75

76

Returns:

77

cupy.ndarray: Array filled with fill_value

78

"""

79

80

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

81

"""

82

Create identity matrix or matrix with ones on diagonal.

83

84

Parameters:

85

- N: int, number of rows

86

- M: int, number of columns (default N)

87

- k: int, diagonal offset

88

- dtype: data type

89

- order: {'C', 'F'}, memory layout

90

91

Returns:

92

cupy.ndarray: Identity or diagonal matrix

93

"""

94

95

def identity(n, dtype=None):

96

"""

97

Create identity matrix of given size.

98

99

Parameters:

100

- n: int, size of identity matrix

101

- dtype: data type, default float64

102

103

Returns:

104

cupy.ndarray: n x n identity matrix

105

"""

106

107

def diag(v, k=0):

108

"""

109

Extract diagonal or construct diagonal matrix.

110

111

Parameters:

112

- v: array-like, if 1-D creates diagonal matrix, if 2-D extracts diagonal

113

- k: int, diagonal offset

114

115

Returns:

116

cupy.ndarray: Diagonal array or matrix

117

"""

118

119

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

120

"""

121

Create array with ones at and below diagonal, zeros elsewhere.

122

123

Parameters:

124

- N: int, number of rows

125

- M: int, number of columns (default N)

126

- k: int, diagonal offset

127

- dtype: data type

128

129

Returns:

130

cupy.ndarray: Triangular matrix

131

"""

132

```

133

134

### Array-like Creation

135

136

Create arrays with same shape or properties as existing arrays.

137

138

```python { .api }

139

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

140

"""

141

Create array of zeros with same shape as existing array.

142

143

Parameters:

144

- a: array-like, reference array

145

- dtype: data type, if None use same as a

146

- order: {'K', 'A', 'C', 'F'}, memory layout

147

- subok: bool, whether to allow subclasses

148

- shape: int or tuple of ints, override shape

149

150

Returns:

151

cupy.ndarray: Array of zeros

152

"""

153

154

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

155

"""Create array of ones with same shape as existing array."""

156

157

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

158

"""Create uninitialized array with same shape as existing array."""

159

160

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

161

"""Create array filled with value, same shape as existing array."""

162

```

163

164

### Numerical Ranges

165

166

Create arrays with evenly or logarithmically spaced values.

167

168

```python { .api }

169

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

170

"""

171

Create array with evenly spaced values within range.

172

173

Parameters:

174

- start: number, start value or stop if stop not given

175

- stop: number, end value (exclusive)

176

- step: number, spacing between values

177

- dtype: data type, if None infer from inputs

178

179

Returns:

180

cupy.ndarray: Array of evenly spaced values

181

"""

182

183

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

184

"""

185

Create array with evenly spaced values over interval.

186

187

Parameters:

188

- start: scalar, start value

189

- stop: scalar, end value

190

- num: int, number of samples

191

- endpoint: bool, whether to include stop value

192

- retstep: bool, whether to return step size

193

- dtype: data type

194

- axis: int, axis along which to store samples

195

196

Returns:

197

cupy.ndarray: Array of evenly spaced values

198

tuple: (array, step) if retstep=True

199

"""

200

201

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

202

"""

203

Create array with logarithmically spaced values.

204

205

Parameters:

206

- start: scalar, base**start is first value

207

- stop: scalar, base**stop is last value

208

- num: int, number of samples

209

- endpoint: bool, whether to include base**stop

210

- base: scalar, logarithm base

211

- dtype: data type

212

- axis: int, axis along which to store samples

213

214

Returns:

215

cupy.ndarray: Array of logarithmically spaced values

216

"""

217

218

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

219

"""

220

Create coordinate arrays from coordinate vectors.

221

222

Parameters:

223

- xi: array-like, coordinate vectors

224

- copy: bool, whether to copy input arrays

225

- sparse: bool, whether to return sparse grid

226

- indexing: {'xy', 'ij'}, indexing convention

227

228

Returns:

229

list of cupy.ndarray: Coordinate arrays

230

"""

231

```

232

233

### Matrix Creation

234

235

Create matrices with specific structures like diagonal, triangular, or Vandermonde matrices.

236

237

```python { .api }

238

def diag(v, k=0):

239

"""

240

Extract or construct diagonal matrix.

241

242

Parameters:

243

- v: array-like, diagonal values or matrix to extract diagonal from

244

- k: int, diagonal offset

245

246

Returns:

247

cupy.ndarray: Diagonal matrix or diagonal values

248

"""

249

250

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

251

"""

252

Create array with ones on and below diagonal.

253

254

Parameters:

255

- N: int, number of rows

256

- M: int, number of columns (default N)

257

- k: int, diagonal offset

258

- dtype: data type

259

260

Returns:

261

cupy.ndarray: Triangular matrix

262

"""

263

264

def tril(m, k=0):

265

"""

266

Return lower triangle of array.

267

268

Parameters:

269

- m: array-like, input array

270

- k: int, diagonal offset

271

272

Returns:

273

cupy.ndarray: Lower triangular matrix

274

"""

275

276

def triu(m, k=0):

277

"""Return upper triangle of array."""

278

279

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

280

"""

281

Generate Vandermonde matrix.

282

283

Parameters:

284

- x: array-like, input vector

285

- N: int, number of columns (default len(x))

286

- increasing: bool, order of powers

287

288

Returns:

289

cupy.ndarray: Vandermonde matrix

290

"""

291

```

292

293

### Data Conversion

294

295

Convert between different data sources and CuPy arrays.

296

297

```python { .api }

298

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

299

"""

300

Convert input to CuPy array.

301

302

Parameters:

303

- a: array-like, input data

304

- dtype: data type, if None preserve existing

305

- order: {'C', 'F'}, memory layout

306

307

Returns:

308

cupy.ndarray: CuPy array view or copy

309

"""

310

311

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

312

"""Convert input to CuPy array, preserving subclasses."""

313

314

def ascontiguousarray(a, dtype=None):

315

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

316

317

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

318

"""

319

Return copy of array.

320

321

Parameters:

322

- a: array-like, input array

323

- order: {'K', 'A', 'C', 'F'}, memory layout

324

- subok: bool, whether to allow subclasses

325

326

Returns:

327

cupy.ndarray: Copy of array

328

"""

329

330

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

331

"""

332

Convert CuPy array to NumPy array on CPU.

333

334

Parameters:

335

- a: cupy.ndarray, input GPU array

336

- stream: cupy.cuda.Stream, CUDA stream for transfer

337

- order: {'C', 'F', 'A'}, memory layout

338

- out: numpy.ndarray, output array to write to

339

- blocking: bool, whether to block until transfer complete

340

341

Returns:

342

numpy.ndarray: CPU array

343

"""

344

```

345

346

### Shape Manipulation

347

348

Modify array shapes and dimensions without changing data.

349

350

```python { .api }

351

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

352

"""

353

Give new shape to array without changing data.

354

355

Parameters:

356

- a: array-like, input array

357

- newshape: int or tuple of ints, new shape

358

- order: {'C', 'F', 'A'}, read/write order

359

360

Returns:

361

cupy.ndarray: Reshaped array

362

"""

363

364

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

365

"""

366

Return contiguous flattened array.

367

368

Parameters:

369

- a: array-like, input array

370

- order: {'C', 'F', 'A', 'K'}, flattening order

371

372

Returns:

373

cupy.ndarray: Flattened array

374

"""

375

376

def squeeze(a, axis=None):

377

"""

378

Remove single-dimensional entries from shape.

379

380

Parameters:

381

- a: array-like, input array

382

- axis: None or int or tuple of ints, axes to squeeze

383

384

Returns:

385

cupy.ndarray: Squeezed array

386

"""

387

388

def expand_dims(a, axis):

389

"""

390

Expand dimensions of array.

391

392

Parameters:

393

- a: array-like, input array

394

- axis: int or tuple of ints, position of new axes

395

396

Returns:

397

cupy.ndarray: Array with expanded dimensions

398

"""

399

```

400

401

### Array Joining

402

403

Combine multiple arrays along various axes.

404

405

```python { .api }

406

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

407

"""

408

Join arrays along existing axis.

409

410

Parameters:

411

- arrays: sequence of arrays, arrays to concatenate

412

- axis: int, axis along which to concatenate

413

- out: cupy.ndarray, output array

414

- dtype: data type, type of output array

415

- casting: {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, casting rule

416

417

Returns:

418

cupy.ndarray: Concatenated array

419

"""

420

421

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

422

"""

423

Join arrays along new axis.

424

425

Parameters:

426

- arrays: sequence of arrays, arrays to stack

427

- axis: int, axis along which to stack

428

- out: cupy.ndarray, output array

429

430

Returns:

431

cupy.ndarray: Stacked array

432

"""

433

434

def vstack(tup):

435

"""Stack arrays vertically (row-wise)."""

436

437

def hstack(tup):

438

"""Stack arrays horizontally (column-wise)."""

439

440

def dstack(tup):

441

"""Stack arrays depth-wise (along third axis)."""

442

443

def column_stack(tup):

444

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

445

```

446

447

### Array Splitting

448

449

Split arrays into multiple sub-arrays.

450

451

```python { .api }

452

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

453

"""

454

Split array into multiple sub-arrays.

455

456

Parameters:

457

- ary: cupy.ndarray, array to split

458

- indices_or_sections: int or 1-D array, split points

459

- axis: int, axis along which to split

460

461

Returns:

462

list of cupy.ndarray: Sub-arrays

463

"""

464

465

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

466

"""Split array into multiple sub-arrays of approximately equal size."""

467

468

def hsplit(ary, indices_or_sections):

469

"""Split array horizontally (column-wise)."""

470

471

def vsplit(ary, indices_or_sections):

472

"""Split array vertically (row-wise)."""

473

474

def dsplit(ary, indices_or_sections):

475

"""Split array depth-wise (along third axis)."""

476

```

477

478

## Usage Examples

479

480

### Creating Arrays from Different Sources

481

482

```python

483

import cupy as cp

484

import numpy as np

485

486

# From Python lists

487

arr = cp.array([1, 2, 3, 4, 5])

488

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

489

490

# From NumPy arrays (transfers to GPU)

491

np_arr = np.random.random((100, 100))

492

gpu_arr = cp.asarray(np_arr)

493

494

# Uninitialized for performance

495

big_array = cp.empty((10000, 10000), dtype=cp.float32)

496

497

# Ranges for computation

498

x = cp.linspace(0, 2*cp.pi, 1000)

499

indices = cp.arange(0, 1000, 2)

500

```

501

502

### Memory-Efficient Array Operations

503

504

```python

505

# Reuse existing arrays when possible

506

result = cp.zeros_like(input_array)

507

cp.add(arr1, arr2, out=result) # Write directly to result

508

509

# Create views instead of copies

510

reshaped = arr.reshape((100, -1)) # View, not copy

511

flattened = arr.ravel() # View when possible

512

```