forked from CodeWithKyrian/transformers-php
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTensor.php
More file actions
1701 lines (1371 loc) · 49.7 KB
/
Tensor.php
File metadata and controls
1701 lines (1371 loc) · 49.7 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
namespace Codewithkyrian\Transformers\Tensor;
use ArrayObject;
use Countable;
use EmptyIterator;
use Interop\Polite\Math\Matrix\Buffer;
use Interop\Polite\Math\Matrix\NDArray;
use InvalidArgumentException;
use IteratorAggregate;
use LogicException;
use OutOfRangeException;
use Rindow\Math\Matrix\Complex;
use Rindow\Math\Matrix\ComplexUtils;
use Rindow\Math\Matrix\Drivers\Service;
use Rindow\Math\Matrix\Range;
use RuntimeException;
use Serializable;
use Traversable;
class Tensor implements NDArray, Countable, Serializable, IteratorAggregate
{
use ComplexUtils;
const RANGE_STYLE_DEFAULT = 0;
const RANGE_STYLE_1 = 1;
static public int $rangeStyle = self::RANGE_STYLE_DEFAULT;
const SERIALIZE_NDARRAY_KEYWORD = 'Tensor:';
protected static MatrixOperator $mo;
protected static Service $service;
protected array $shape;
protected int $offset;
protected int $dtype;
protected Buffer $buffer;
protected static array $pack = [
NDArray::bool => 'C',
NDArray::int8 => 'c',
NDArray::int16 => 's',
NDArray::int32 => 'l',
NDArray::int64 => 'q',
NDArray::uint8 => 'C',
NDArray::uint16 => 'S',
NDArray::uint32 => 'L',
NDArray::uint64 => 'Q',
//NDArray::float8 => 'N/A',
//NDArray::float16 => 'N/A',
NDArray::float32 => 'g',
NDArray::float64 => 'e',
NDArray::complex64 => 'g',
NDArray::complex128 => 'e',
];
protected bool $portableSerializeMode = false;
public function __construct(
mixed $array = null,
?int $dtype = null,
?array $shape = null,
?int $offset = null,
) {
if ($array === null && $dtype === null && $shape === null && $offset === null) {
// Empty definition for Unserialize
return;
}
$orgDtype = $dtype;
if ($dtype === null) {
$dtype = NDArray::float32;
}
if ($array === null && $shape !== null) {
$this->assertShape($shape);
$size = (int)array_product($shape);
$this->buffer = self::newBuffer($size, $dtype);
$this->offset = 0;
} elseif ($this->isBuffer($array)) {
if (!is_int($offset))
throw new InvalidArgumentException("Must specify offset with the buffer");
if ($shape === null)
throw new InvalidArgumentException("Invalid dimension size");
$this->buffer = $array;
$this->offset = $offset;
$size = (int)array_product($shape);
} elseif (is_array($array) || $array instanceof ArrayObject) {
$size = $this->countRecursive($array);
$this->buffer = self::newBuffer($size, $dtype);
$this->flattenArray($array, $this->buffer);
$this->offset = 0;
$shape ??= $this->generateShape($array);
} elseif (is_numeric($array) || is_bool($array) || $this->isComplexObject($array)) {
if (is_numeric($array)) {
if ($orgDtype == null) {
$dtype = NDArray::float32;
}
} elseif (is_bool($array)) {
if ($orgDtype == null) {
$dtype = NDArray::bool;
} else {
if ($dtype != NDArray::bool) {
throw new InvalidArgumentException("unmatch dtype with bool value");
}
}
} elseif ($this->isComplexObject($array)) {
if ($orgDtype == null) {
$dtype = NDArray::complex64;
} else {
if (!$this->isComplex($dtype)) {
throw new InvalidArgumentException("unmatch dtype with complex value");
}
}
}
$this->buffer = self::newBuffer(1, $dtype);
$this->buffer[0] = $array;
$this->offset = 0;
$shape ??= [];
$this->assertShape($shape);
$size = (int)array_product($shape);
if ($size != 1)
throw new InvalidArgumentException("Invalid dimension size");
} else {
throw new InvalidArgumentException("Invalid type of array");
}
$this->assertShape($shape);
$this->shape = $shape;
if (count($this->buffer) - $this->offset < $size)
throw new InvalidArgumentException("Invalid dimension size");
$this->dtype = $dtype;
}
function countRecursive($array): int
{
$count = 0;
foreach ($array as $child) {
if (is_array($child) || $child instanceof ArrayObject) {
$count += $this->countRecursive($child);
} else {
$count++;
}
}
return $count;
}
/**
* Create a new buffer for the tensor.
*
* @param int $size The size of the buffer.
* @param int|null $dtype The data type of the buffer.
*/
public static function newBuffer(int $size, ?int $dtype = null): Buffer
{
return self::service()->buffer()->Buffer($size, $dtype);
}
/**
* Check if the given value is a buffer.
*/
protected function isBuffer(mixed $buffer): bool
{
return $buffer instanceof Buffer;
}
protected function isComplex(?int $dtype = null): bool
{
$dtype = $dtype ?? $this->dtype;
return $this->cistype($dtype);
}
public function isComplexObject(mixed $value): bool
{
return $this->cisObject($value);
}
/**
* Assert that the given shape is valid.
*/
protected function assertShape(array $shape): void
{
foreach ($shape as $num) {
if (!is_int($num)) {
throw new InvalidArgumentException(
"Invalid shape numbers. It gives " . gettype($num)
);
}
if ($num < 0) {
throw new InvalidArgumentException(
"Invalid shape numbers. It gives " . $num
);
}
}
}
/**
* Flatten the given nested array into a flat array.
*/
protected function flattenArray(array|ArrayObject $nestedArray, $flatArray, int &$currentIndex = 0): int
{
$numElements = 0;
if ($nestedArray instanceof ArrayObject) {
$nestedArray = $nestedArray->getArrayCopy();
}
// Iterate through the nested array
foreach ($nestedArray as $value) {
// If the value is an array or ArrayObject, flatten it recursively
if (is_array($value) || $value instanceof ArrayObject) {
$numInNested = $this->flattenArray($value, $flatArray, $currentIndex);
if ($numElements === 0) {
$numElements = $numInNested;
} elseif ($numElements !== $numInNested) {
throw new InvalidArgumentException("The shape of the dimension is broken");
}
} else {
// If the value is not an array, append it to the flat array
$flatArray[$currentIndex++] = $value;
$numElements++;
}
}
return $numElements;
}
/**
* Unflatten the given flat array into a nested array according to the given shape.
*/
protected function unflattenArray($flatArray, &$currentIndex, array $shape): array
{
$size = array_shift($shape);
$nestedArray = [];
if (count($shape)) {
for ($i = 0; $i < $size; $i++) {
$nestedArray[$i] = $this->unflattenArray($flatArray, $currentIndex, $shape);
}
} else {
for ($i = 0; $i < $size; $i++) {
$nestedArray[$i] = $flatArray[$currentIndex];
$currentIndex++;
}
}
return $nestedArray;
}
/**
* Generate the shape of the given array.
*/
protected function generateShape($array): array
{
$shape = [];
while (is_array($array) || $array instanceof ArrayObject) {
$shape[] = count($array);
$array = current($array);
}
return $shape;
}
public static function mo(): MatrixOperator
{
if (!isset(self::$mo)) {
self::$mo = new MatrixOperator(self::service());
}
return self::$mo;
}
public static function service(): Service
{
if (!isset(self::$service)) {
self::$service = new TensorService();
// self::$service = new MatlibPhp();
}
return self::$service;
}
public static function setService(Service $service): void
{
self::$service = $service;
self::$mo = new MatrixOperator(self::service());
}
/**
* Return the internal flat buffer of the tensor.
*/
public function buffer(): Buffer
{
return $this->buffer;
}
/**
* Returns the data type of the tensor.
*/
public function dtype(): int
{
return $this->dtype;
}
/**
* Get the shape of the tensor.
*/
public function shape(): array
{
return $this->shape;
}
/**
* The offset of the tensor. This is used when the tensor is a view of another tensor.
*/
public function offset(): int
{
return $this->offset;
}
/**
* Returns how many dimensions the tensor has.
*
* @return int
*/
public function ndim(): int
{
return count($this->shape);
}
public function count(): int
{
if (count($this->shape) == 0)
return 0;
return $this->shape[0];
}
/**
* Returns the total number of elements in the tensor.
*/
public function size(): int
{
return (int)array_product($this->shape);
}
/**
* Reshape the tensor into the given shape.
*/
public function reshape(array $shape): static
{
$this->assertShape($shape);
if ($this->size() != array_product($shape)) {
throw new InvalidArgumentException("Unmatched size to reshape: " .
"[" . implode(',', $this->shape()) . "]=>[" . implode(',', $shape) . "]");
}
return new self($this->buffer(), $this->dtype(), $shape, $this->offset());
}
public static function fromArray(array|NDArray $array, ?int $dtype = null, $shape = null): ?static
{
if (empty($array)) return null;
if ($array instanceof NDArray) {
return new static($array->buffer(), $array->dtype(), $shape ?? $array->shape(), $array->offset());
}
return new static($array, $dtype, $shape);
}
public static function fromString(string $string, int $dtype, array $shape): static
{
$buffer = Tensor::newBuffer(array_product($shape), $dtype);
$buffer->load($string);
return new static($buffer, $dtype, $shape, 0);
}
public static function random(array $shape, ?int $dtype = null): static
{
$dtype ??= NDArray::float32;
$size = array_product($shape);
$buffer = Tensor::newBuffer($size, $dtype);
$buffer->load(random_bytes($size * TensorBuffer::$valueSize[$dtype]));
return new static($buffer, shape: $shape, offset: 0);
}
/**
* Convert the tensor into an array.
*/
public function toArray()
{
if (count($this->shape) == 0) {
return $this->buffer[$this->offset];
}
$idx = $this->offset;
return $this->unflattenArray($this->buffer, $idx, $this->shape);
}
public function toString(): string
{
return $this->buffer->dump();
}
/**
* Convert the tensor into a flat array of the buffer contents.
*/
public function toBufferArray(): array
{
$fmt = self::$pack[$this->dtype] . '*';
return array_values(unpack($fmt, $this->buffer->dump()));
}
public static function fill(array $shape, float|int $value, ?int $dtype = null): static
{
$mo = self::mo();
$ndArray = $mo->full($shape, $value, $dtype);
return new static($ndArray->buffer(), $ndArray->dtype(), $ndArray->shape(), $ndArray->offset());
}
public static function repeat(Tensor|array $tensor, int $repeats, ?int $axis = null): static
{
$mo = self::mo();
if (is_array($tensor)) {
$tensor = $mo->array($tensor);
}
$ndArray = $mo->la()->repeat($tensor, $repeats, $axis);
return new static($ndArray->buffer(), $ndArray->dtype(), $ndArray->shape(), $ndArray->offset());
}
/**
* Return a one matrix with the given shape.
*
* @param array $shape The shape of the one matrix to return.
* @param ?int $dtype The data type of the one matrix to return. Eg: float32, int32, etc. If null, defaults to float32.
*
* @return static
*/
public static function ones(array $shape, ?int $dtype = null): static
{
$mo = self::mo();
$ndArray = $mo->ones($shape, $dtype);
return new static($ndArray->buffer(), $ndArray->dtype(), $ndArray->shape(), $ndArray->offset());
}
/**
* Return a one matrix like the given one.
*
* @param Tensor $other The tensor to copy the shape and dtype from.
*/
public static function onesLike(Tensor $other): static
{
$mo = self::mo();
$ndArray = $mo->ones($other->shape, $other->dtype);
return new static($ndArray->buffer(), $ndArray->dtype(), $ndArray->shape(), $ndArray->offset());
}
/**
* Return a zero matrix with the given shape.
*
* @param array $shape The shape of the zero matrix to return.
* @param int|null $dtype The data type of the zero matrix to return. Eg: float32, int32, etc. If null, defaults to float32.
*
* @return static
*/
public static function zeros(array $shape, ?int $dtype = null): static
{
$mo = self::mo();
$ndArray = $mo->zeros($shape, $dtype);
return new static($ndArray->buffer(), $ndArray->dtype(), $ndArray->shape(), $ndArray->offset());
}
/**
* Return a zero matrix like the given one.
*
* @param Tensor $other The tensor to copy the shape and dtype from.
*/
public static function zerosLike(Tensor $other): static
{
$mo = self::mo();
$ndArray = $mo->zerosLike($other);
return new static($ndArray->buffer(), $ndArray->dtype(), $ndArray->shape(), $ndArray->offset());
}
public function copyTo(Tensor $other): void
{
self::mo()->la()->copy($this, $other);
}
/**
* Stack an array of tensors along a specified axis.
*
* @param Tensor[] $tensors The array of tensors to stack.
* @param int $axis The axis to stack along.
*
* @return Tensor The stacked tensor.
*/
public static function stack(array $tensors, int $axis = 0): Tensor
{
$mo = self::mo();
$stacked = $mo->la()->stack($tensors, $axis);
return new Tensor($stacked->buffer(), $stacked->dtype(), $stacked->shape(), $stacked->offset());
}
/**
* Concatenates an array of tensors along a specified dimension.
*
* @param Tensor[] $tensors The array of tensors to concatenate.
* @param int $axis The dimension to concatenate along.
*
* @return Tensor The concatenated tensor.
*/
public static function concat(array $tensors, int $axis = 0): Tensor
{
$mo = self::mo();
$ndArray = $mo->la()->concat($tensors, $axis);
return new static($ndArray->buffer(), $ndArray->dtype(), $ndArray->shape(), $ndArray->offset());
}
/**
* Safely calculates the positive index within the specified size and axis.
*
* @param int $index The input index.
* @param int $size The size of the dimension.
* @param int|null $axis The axis (optional).
*
* @return int The positive index within bounds.
* @throws InvalidArgumentException If the index is out of bounds.
*/
public static function safeIndex(int $index, int $size, ?int $axis = null): int
{
if ($index < -$size || $index >= $size) {
throw new InvalidArgumentException(
"IndexError: index $index is out of bounds for axis"
. ($axis === null ? '' : ' ' . $axis) . " with size $size"
);
}
if ($index < 0) {
// Negative indexing, ensuring positive index
$index = (($index % $size) + $size) % $size;
}
return $index;
}
/**
* Returns a tensor with all specified axis of input of size 1 removed.
*
* @param ?int $axis If given, the input will be squeezed only in the specified axis.
*
* @return static The squeezed tensor.
*/
public function squeeze(?int $axis = null): static
{
$mo = self::mo();
$ndArray = $mo->la()->squeeze($this, $axis);
return new static($ndArray->buffer(), $ndArray->dtype(), $ndArray->shape(), $ndArray->offset());
}
/**
* Returns a tensor with all specified axis of input of size 1 removed.
*
* @param ?int $axis If given, the input will be squeezed only in the specified axis.
*
* @return static The squeezed tensor.
*/
public function unsqueeze(?int $axis = null): static
{
$mo = self::mo();
$ndArray = $mo->la()->expandDims($this, $axis);
return new static($ndArray->buffer(), $ndArray->dtype(), $ndArray->shape(), $ndArray->offset());
}
/**
* Add a tensor or scalar to this tensor. If it's a tensor, it must be the same shape, and it performs
* an element-wise addition. If it's a scalar, it adds the scalar to every element in the tensor.
*
* @param Tensor|float|int $other The NDArray to add to this NDArray.
*
* @return static
*/
public function add(Tensor|float|int $other): static
{
$mo = self::mo();
if ($other instanceof Tensor) {
$ndArray = $mo->la()->add($this, $other);
} else {
$ndArray = $mo->la()->increment($this, $other);
}
return new static($ndArray->buffer(), $ndArray->dtype(), $ndArray->shape(), $ndArray->offset());
}
/**
* Return a new Tensor with the sigmoid function applied to each element.
*
* @return self
*/
public function sigmoid(): self
{
$mo = self::mo();
$ndArray = $mo->f(fn($x) => 1 / (1 + exp(-$x)), $this);
return new static($ndArray->buffer(), $ndArray->dtype(), $ndArray->shape(), $ndArray->offset());
}
/**
* Calculates the magnitude of the tensor
*
* @return float The magnitude of the tensor.
*/
public function magnitude(): float
{
$mo = self::mo();
return $mo->la()->nrm2($this);
}
public function sqrt(): NDArray
{
$mo = self::mo();
return $mo->la()->sqrt($this);
}
/**
* Return a new Tensor with every element multiplied by a constant.
*
* @param Tensor|float|int $value The constant to multiply by.
*
* @return self
*/
public function multiply(Tensor|float|int $value): self
{
$mo = self::mo();
if ($value instanceof Tensor) {
$ndArray = $mo->la()->multiply($this, $value);
} else {
$ndArray = $mo->la()->scal($value, $this);
}
return new static($ndArray->buffer(), $ndArray->dtype(), $ndArray->shape(), $ndArray->offset());
}
public function matmul(Tensor $other, ?bool $transposeA = null, ?bool $transposeB = null): Tensor
{
$mo = self::mo();
$result = $mo->la()->matmul($this, $other, $transposeA, $transposeB);
return new static($result->buffer(), $result->dtype(), $result->shape(), $result->offset());
}
public function log(): self
{
$mo = self::mo();
$ndArray = $mo->la()->log($this);
return new static($ndArray->buffer(), $ndArray->dtype(), $ndArray->shape(), $ndArray->offset());
}
public function exp(): self
{
$mo = self::mo();
$ndArray = $mo->la()->exp($this);
return new static($ndArray->buffer(), $ndArray->dtype(), $ndArray->shape(), $ndArray->offset());
}
/**
* Return a new Tensor raised to the power of a scalar or element-wise power of another tensor.
*/
public function pow(float|Tensor $exponent): self
{
$mo = self::mo();
$ndArray = $mo->la()->pow($this, $exponent);
return new static($ndArray->buffer(), $ndArray->dtype(), $ndArray->shape(), $ndArray->offset());
}
/**
* Calculate the dot product of this tensor and another tensor.
*/
public function dot(Tensor $other): float
{
$mo = self::mo();
return $mo->dot($this, $other);
}
/**
* Calculate the cross product of this tensor and another tensor. The shapes of the tensors must be compatible for
* cross product
*/
public function cross(Tensor $other): Tensor
{
$mo = self::mo();
$crossProduct = $mo->cross($this, $other);
return new static($crossProduct->buffer(), $crossProduct->dtype(), $crossProduct->shape(), $crossProduct->offset());
}
public function sum(?int $axis = null): float|self
{
$mo = self::mo();
$ndArray = $mo->sum($this, $axis);
if (is_scalar($ndArray)) {
return $ndArray;
}
return new static($ndArray->buffer(), $ndArray->dtype(), $ndArray->shape(), $ndArray->offset());
}
/**
* Return a transposed version of this Tensor.
*
* @return $this
*/
public function transpose(): self
{
$mo = self::mo();
$ndArray = $mo->transpose($this);
return new static($ndArray->buffer(), $ndArray->dtype(), $ndArray->shape(), $ndArray->offset());
}
public function reciprocal(): self
{
$mo = self::mo();
$ndArray = $mo->la()->reciprocal($this);
return new static($ndArray->buffer(), $ndArray->dtype(), $ndArray->shape(), $ndArray->offset());
}
/**
* Calculates the cosine similarity between this Tensor and another Tensor.
*
* @param Tensor $other The Tensor to calculate the cosine similarity with.
*
* @return float|int The cosine similarity between this Tensor and the other Tensor.
*/
public function cosSimilarity(Tensor $other): float|int
{
$dotProduct = $this->dot($other);
$magnitude = $this->magnitude();
$otherMagnitude = $other->magnitude();
return $dotProduct / ($magnitude * $otherMagnitude);
}
/**
* Performs `L_p` normalization of inputs over specified dimension.
*
* @param int $p Order of the norm. Supported values are 1, 2, Infinity.
* @param int|null $axis The axis or axes along which to perform the reduction. If null (default), reduces all dimensions.
*
* @return static The normalized tensor.
*/
public function normalize(int $p = 2, ?int $axis = null): static
{
$result = clone $this;
$axis = $result->safeIndex($axis, $result->ndim());
$norm = $result->norm($p, $axis, true);
foreach ($norm->buffer as $i => $value) {
$resultIndex = 0;
$num = $i;
$resultMultiplier = 1;
for ($j = $result->ndim() - 1; $j >= 0; --$j) {
$size = $result->shape()[$j];
if ($j !== $axis) {
$index = $num % $size;
$resultIndex += $index * $resultMultiplier;
$resultMultiplier *= $result->shape()[$j];
}
$num = floor($num / $size);
}
// Divide by normalized value
$result->buffer[$i] /= $norm->buffer[$resultIndex];
}
return $result;
}
/**
* Returns the matrix norm or vector norm of a given tensor.
*
* @param int $ord Order of the norm. Supported values are 1, 2, Infinity.
* @param int|null $axis The axis or axes along which to perform the reduction. If null (default), reduces all dimensions.
* @param bool $keepShape If true, retains reduced shape with length 1.
*
* @return static
*/
public function norm(int $ord = 2, ?int $axis = null, bool $keepShape = false): static
{
$mo = self::mo();
if ($axis === null) {
$val = pow(array_reduce($this->toBufferArray(), fn($carry, $item) => $carry + pow($item, $ord), 0), 1 / $ord);
return new Tensor([$val], $this->dtype(), []);
}
// Negative indexing
$axis = $this->safeIndex($axis, $this->ndim());
// Calculate the shape of the resulting array after summation
$resultShape = $this->shape();
$resultShape[$axis] = 1; // Remove the specified axis
// Create a new array to store the accumulated values
$result = $this->zeros([count($this->buffer) / $this->shape()[$axis]]);
// Iterate over the data array
foreach ($this->buffer as $i => $value) {
// Calculate the index in the resulting array
$resultIndex = 0;
$num = $i;
$resultMultiplier = 1;
for ($j = $this->ndim() - 1; $j >= 0; --$j) {
$size = $this->shape()[$j];
if ($j !== $axis) {
$index = $num % $size;
$resultIndex += $index * $resultMultiplier;
$resultMultiplier *= $resultShape[$j];
}
$num = floor($num / $size);
}
// Accumulate the value at the current index
$result[$resultIndex] += pow($this->buffer[$i], $ord);
}
if ($ord === 1) {
$result = $mo->op($result, '**', 1 / $ord);
}
if (!$keepShape) {
array_splice($resultShape, $axis, 1);
}
return new static($result->buffer(), $result->dtype(), $resultShape, $result->offset());
}
/**
* Clamps all elements in input into the range [ min, max ] and returns a resulting tensor.
*
* @param float|int $min The minimum value.
* @param float|int $max The maximum value.
*
* @return static The clamped tensor.
*/
public function clamp(float|int $min, float|int $max): static
{
$mo = self::mo();
$result = $mo->f(fn($x) => max($min, min($max, $x)), $this);
return new static($result->buffer(), $result->dtype(), $result->shape(), $result->offset());
}
/**
* Rounds elements of input to the nearest integer.
*
* @return static The rounded tensor.
*/
public function round(int $precision = 0): static
{
$mo = self::mo();
$result = $mo->f(fn($x) => round($x, $precision), $this);
return new static($result->buffer(), $result->dtype(), $result->shape(), $result->offset());
}
/**
* Cast the tensor to a new dtype.
*
* @param int $dtype The new dtype.
*
* @return static
*/
public function to(int $dtype): static
{
if ($this->dtype() === $dtype) {
return $this;
}
$mo = self::mo();
$ndArray = $mo->astype($this, $dtype);
return new static($ndArray->buffer(), $ndArray->dtype(), $ndArray->shape(), $ndArray->offset());
}
/**
* Returns the mean value of each row of the tensor in the given axis.
*/
public function mean(?int $axis = null, bool $keepShape = false): static|float|int|Tensor
{
$mo = self::mo();
if ($axis !== null) {
$axis = $this->safeIndex($axis, $this->ndim());
}
$mean = $mo->mean($this, $axis);
if ($mean instanceof NDArray) {
$shape = $this->shape();
$shape[$axis] = 1;
if (!$keepShape) {
array_splice($shape, $axis, 1);
}
return new static($mean->buffer(), $mean->dtype(), $shape, $mean->offset());
}
return $mean;
}
/**
* Calculates the standard deviation and mean over the dimensions specified by dim. dim can be a
* single dimension or `null` to reduce over all dimensions.
*
* @param int|null $axis The dimension to reduce. If `null`, reduces over all dimensions.
* @param int $correction The type of normalization. Default is 0.
* @param bool $keepShape Whether to keep the reduced dimension or not.
*
* @return array The standard deviation and mean of the tensor.
*/
public function stdMean(?int $axis = null, int $correction = 1, bool $keepShape = false): array