-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayMetadata.php
More file actions
95 lines (80 loc) · 2.73 KB
/
Copy pathArrayMetadata.php
File metadata and controls
95 lines (80 loc) · 2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
declare(strict_types=1);
namespace PhpMlKit\NDArray;
use FFI\CData;
use PhpMlKit\NDArray\FFI\Lib;
/**
* Holds shape, strides, offset and ndim for an array.
*
* NDArray uses this instead of storing those fields directly. When FFI needs
* a C ArrayMetadata struct, call toCData() to build and fill it; use
* Lib::addr($metadata->toCData()) when passing to FFI.
*
* @internal this is an internal implementation detail, not part of the public API
*/
final class ArrayMetadata
{
public readonly int $ndim;
/** @var array<int> */
public readonly array $strides;
public readonly int $size;
/** Cached C struct and backing arrays so pointers stay valid. */
private ?CData $cachedStruct = null;
private ?CData $cachedShapeC = null;
private ?CData $cachedStridesC = null;
/**
* @param array<int> $shape Shape dimensions
* @param array<int> $strides Element strides per dimension (row-major if empty)
* @param int $offset Flat offset into root data
*/
public function __construct(
public readonly array $shape,
array $strides = [],
public readonly int $offset = 0,
) {
$this->ndim = \count($shape);
$this->strides = [] !== $strides ? $strides : self::computeStrides($shape);
$this->size = (int) array_product($shape);
}
/**
* Build and return the C ArrayMetadata struct. Caches the struct and
* shape/strides arrays so the returned struct remains valid. Pass
* Lib::addr($this->toCData()) when an FFI function expects a pointer.
*
* @internal
*/
public function toCData(): CData
{
if (null !== $this->cachedStruct) {
return $this->cachedStruct;
}
$lib = Lib::get();
$this->cachedShapeC = $lib->createCArray('size_t', $this->shape);
$this->cachedStridesC = $lib->createCArray('size_t', $this->strides);
$this->cachedStruct = $lib->new('struct ArrayMetadata', false);
$this->cachedStruct->offset = $this->offset;
$this->cachedStruct->shape = \FFI::addr($this->cachedShapeC[0]);
$this->cachedStruct->strides = \FFI::addr($this->cachedStridesC[0]);
$this->cachedStruct->ndim = $this->ndim;
return $this->cachedStruct;
}
/**
* Compute row-major strides from shape.
*
* @param array<int> $shape
*
* @return array<int>
*/
public static function computeStrides(array $shape): array
{
$ndim = \count($shape);
if (0 === $ndim) {
return [];
}
$strides = array_fill(0, $ndim, 1);
for ($i = $ndim - 2; $i >= 0; --$i) {
$strides[$i] = $strides[$i + 1] * $shape[$i + 1];
}
return $strides;
}
}