Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions numpower.c
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,75 @@ PHP_METHOD(NDArray, gpu) {
#endif
}

ZEND_BEGIN_ARG_INFO(arginfo_settype, 0)
ZEND_ARG_INFO(0, dtype)
ZEND_END_ARG_INFO();
/**
* @brief Sets the data type of this NDArray in place.
*
* ```
* setType(string $dtype): void
* ```
Comment thread
andrewdalpino marked this conversation as resolved.
*
* Re-casts the array to the requested dtype, releasing the previous
* storage (unless still referenced by a live slice). This method mutates
* `$this` and returns nothing, consistent with the other in-place method
* `fill()`. The device (CPU or GPU) is preserved. If the target dtype
* equals the current dtype, the call is a true no-op with no allocation.
*
* Supported dtypes: float4, float8, float16, float32, float64, float128,
* int8, uint8, int16, uint16, int32, uint32, int64, uint64.
Comment on lines +313 to +317

@andrewdalpino andrewdalpino Sep 1, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@SkibidiProduction thought this would be helpful to you

*
* @param dtype Target dtype alias.
*
* @throws \Error If the dtype is unknown.
*/
PHP_METHOD(NDArray, setType) {
char *dtype;
size_t dtypeLen = 0;
zval *obj_zval = getThis();

ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STRING(dtype, dtypeLen)
ZEND_PARSE_PARAMETERS_END();

NDArray *ndarray = NDArrayFactory_restoreFromZval(obj_zval);
if (ndarray == NULL) {
return;
}

const char *canonical = type_canonicalize(dtype);
if (canonical == NULL) {
zend_throw_error(NULL,
"Invalid data type '%s'. Supported: float4, float8, float16, "
"float32, float64, float128, int8, uint8, int16, uint16, "
"int32, uint32, int64, uint64", dtype);
return;
}

/* Fast path: already this dtype — true no-op, no allocation, no swap. */
if (is_type(NDArray_TYPE(ndarray), canonical)) {
return;
}

/* NDArray_AsType always returns a fresh, caller-owned, unbuffered
NDArray; the source `ndarray` is left intact. We then swap the new
array into the same buffer slot (preserving the object's uuid) and
release the previous occupant. NDArray_FREE is refcount-aware: if a
live slice still references the old array, its data survives until
the last view is freed. */
NDArray *casted = NDArray_AsType(ndarray, canonical);
if (casted == NULL) {
return; /* Original NDArray remains untouched. */
}

int uuid = NDArray_UUID(ndarray);
NDArray *prev = buffer_replace(uuid, casted);
if (prev) {
NDArray_FREE(prev);
}
}

/**
* @brief Fills the NDArray with a specified value.
*
Expand Down Expand Up @@ -7422,6 +7491,7 @@ static const zend_function_entry class_NDArray_methods[] = {
ZEND_ME(NDArray, gpu, arginfo_gpu, ZEND_ACC_PUBLIC)
ZEND_ME(NDArray, cpu, arginfo_cpu, ZEND_ACC_PUBLIC)
ZEND_ME(NDArray, isGPU, arginfo_is_gpu, ZEND_ACC_PUBLIC)
ZEND_ME(NDArray, setType, arginfo_settype, ZEND_ACC_PUBLIC)

ZEND_ME(NDArray, size, arginfo_size, ZEND_ACC_PUBLIC)
ZEND_ME(NDArray, count, arginfo_count, ZEND_ACC_PUBLIC)
Expand Down
81 changes: 81 additions & 0 deletions tests/types/029-settype-dtype-change.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
--TEST--
NDArray::setType() mutates the array's data type in place (void)
--FILE--
<?php
/* setType() must:
- mutate $this in place (same object identity after the call)
- return void (null)
- convert element values and PHP types to the target dtype
- preserve the device (a CPU array stays CPU)
- be a true no-op when the target dtype equals the current one
- throw on an unknown dtype, leaving the array unchanged */

/* 1. float32 -> int32: values truncate, elements become ints, same object */
$a = new NDArray([1.5, 2.5, 3.7], 'float32');
$ret = $a->setType('int32');
$php = $a->toArray();
$ok = ($a instanceof NDArray) && $php === [1, 2, 3]
&& array_map('gettype', $php) === ['integer', 'integer', 'integer']
&& !$a->isGPU();
echo 'float32->int32: ', ($ok ? 'OK' : 'BAD'), ' ', json_encode($php), "\n";
Comment thread
andrewdalpino marked this conversation as resolved.
Outdated

/* 2. int32 -> float64: elements become floats, values preserved */
$b = new NDArray([1, 2, 3], 'int32');
$b->setType('float64');
$php = $b->toArray();
$ok = array_map('gettype', $php) === ['double', 'double', 'double']
&& $php === [1.0, 2.0, 3.0];
echo 'int32->float64: ', ($ok ? 'OK' : 'BAD'), ' ', json_encode($php), "\n";

/* 3. returns void (null), not a new array */
echo 'return-void: ', (($ret === null) ? 'OK' : 'BAD'),
' (', ($ret === null ? 'null' : 'non-null'), ')', "\n";

/* 4. unknown dtype throws and leaves the array unchanged */
$c = new NDArray([1.0, 2.0], 'float64');
$before = $c->toArray();
$ctypes = array_map('gettype', $before);
$threw = false;
$msg = '';
try { $c->setType('badtype'); }
catch (Throwable $t) { $threw = true; $msg = get_class($t) . ' | ' . $t->getMessage(); }
$still = $c->toArray();
$ok = $threw && $still === $before && array_map('gettype', $still) === $ctypes;
echo "badtype-throws-unchanged: ", ($ok ? 'OK' : 'BAD'), " ", $msg, "\n";

/* 5. same-dtype cast is a true no-op: values and types preserved */
$d = new NDArray([4, 5, 6], 'int32');
$d->setType('int32');
$php = $d->toArray();
$ok = $php === [4, 5, 6] && array_map('gettype', $php) === ['integer','integer','integer'] && !$d->isGPU();
echo 'same-dtype-noop: ', ($ok ? 'OK' : 'BAD'), ' ', json_encode($php), "\n";

/* 6. 0-D scalar (shape []) stays an NDArray; __toString is "7\n" */
$e = new NDArray(7.0);
$e->setType('int32');
$ok = ($e instanceof NDArray) && $e->shape() === [] && trim((string)$e) === '7';
echo 'zero-d: ', ($ok ? 'OK' : 'BAD'), ' shape=', json_encode($e->shape()), "\n";

/* 7. device preserved: a CPU array stays CPU after setType */
$f = new NDArray([1.0, 2.0, 3.0], 'float32');
$f->setType('float64');
$ok = ($f instanceof NDArray) && !$f->isGPU() && $f->toArray() === [1.0, 2.0, 3.0];
echo 'device-stays-CPU: ', ($ok ? 'OK' : 'BAD'), ' isGPU=', ($f->isGPU() ? 1 : 0), "\n";

/* 8. wrong argument count rejects */
try {
(new NDArray([1, 2, 3], 'float32'))->setType();
echo "no-arg: NO-THROW\n";
} catch (Throwable $t) {
echo "no-arg threw: ", get_class($t), "\n";
}
?>
--EXPECT--
float32->int32: OK [1,2,3]
int32->float64: OK [1,2,3]
return-void: OK (null)
badtype-throws-unchanged: OK Error | Invalid data type 'badtype'. Supported: float4, float8, float16, float32, float64, float128, int8, uint8, int16, uint16, int32, uint32, int64, uint64
same-dtype-noop: OK [4,5,6]
zero-d: OK shape=[]
device-stays-CPU: OK isGPU=0
no-arg threw: ArgumentCountError
46 changes: 46 additions & 0 deletions tests/types/030-settype-dtype-change-gpu.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
--TEST--
NDArray::setType() on a GPU array stays on GPU and converts values in place
--SKIPIF--
<?php try { (new NDArray([1.0]))->gpu(); } catch (Error $e) { die('skip ' . $e->getMessage()); } ?>
--FILE--
<?php
/* When the array is on the GPU, setType() must keep it on the GPU and
convert the values in place (the same object stays on device).
->cpu() is used only to read back values — it returns a new array and
leaves $g on the GPU, so the isGPU() assertion is still meaningful. */

$cases = [
['float32', 'int32', [1.5, 2.5, 3.5], [1, 2, 3]],
['int32', 'float64', [1, 2, 3], [1.0, 2.0, 3.0]],
['float64', 'float32', [1.5, 2.5, 0.5], [1.5, 2.5, 0.5]],
['int32', 'int16', [1, 2, 3], [1, 2, 3]],
];

foreach ($cases as [$src, $dst, $vals, $expect]) {
$g = (new NDArray($vals, $src))->gpu();
$g->setType($dst);
$on_gpu = $g->isGPU(); /* still after setType() */
$back = $g->cpu()->toArray(); /* cpu() returns a new array; $g stays GPU */
$ok = ($g instanceof NDArray) && $on_gpu && $back === $expect;
Comment thread
andrewdalpino marked this conversation as resolved.
Outdated
echo "$src->$dst: ", ($ok ? 'OK' : 'BAD'),
' isGPU=', ($g->isGPU() ? 1 : 0),
' vals=', json_encode($back), "\n";
}

/* unknown dtype on GPU throws too, leaving the array intact on GPU */
$g2 = (new NDArray([1.0, 2.0], 'float32'))->gpu();
try {
$g2->setType('nope');
echo "badtype: NO-THROW\n";
} catch (Throwable $t) {
echo "badtype threw: ", get_class($t),
" isGPU=", ($g2->isGPU() ? 1 : 0),
" vals=", json_encode($g2->cpu()->toArray()), "\n";
}
?>
--EXPECT--
float32->int32: OK isGPU=1 vals=[1,2,3]
int32->float64: OK isGPU=1 vals=[1,2,3]
float64->float32: OK isGPU=1 vals=[1.5,2.5,0.5]
int32->int16: OK isGPU=1 vals=[1,2,3]
badtype threw: Error isGPU=1 vals=[1.0,2.0]
Loading