/
Tensor.fs
3462 lines (3129 loc) · 210 KB
/
Tensor.fs
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
// Copyright (c) 2016- University of Oxford (Atilim Gunes Baydin <gunes@robots.ox.ac.uk>)
// and other contributors, see LICENSE in root of repository.
//
// BSD 2-Clause License. See LICENSE in root of repository.
namespace DiffSharp
open DiffSharp.Backends
open DiffSharp.Util
open System
#nowarn "1182" // turn off compiler-generated unused variable warnings in this file only
/// <summary>
/// Represents a multi-dimensional data type containing elements of a single data type.
/// </summary>
///
/// <example>
/// A tensor can be constructed from a list or sequence using <see cref="M:DiffSharp.dsharp.tensor(System.Object)" />
///
/// <code>
/// let t = dsharp.tensor([[1.; -1.]; [1.; -1.]])
/// </code>
/// </example>
[<CustomEquality; CustomComparison>]
type Tensor =
internal
| TensorC of primalRaw:RawTensor
| TensorF of primal:Tensor * derivative:Tensor * nestingTag:uint32
| TensorR of primal:Tensor * derivative:(Tensor ref) * parentOp:TensorOp * fanout:(uint32 ref) * nestingTag:uint32
/// Gets the value of the tensor ignoring its first derivative
member t.primal =
match t with
| TensorC(_) -> t
| TensorF(tp,_,_) -> tp
| TensorR(tp,_,_,_,_) -> tp
/// Gets the value of the tensor ignoring all its derivatives
member t.primalDeep =
match t with
| TensorC(_) -> t
| TensorF(tp,_,_) -> tp.primalDeep
| TensorR(tp,_,_,_,_) -> tp.primalDeep
/// Gets the raw value of the tensor ignoring all its derivatives
member t.primalRaw =
match t with
| TensorC(tp) -> tp
| TensorF(tp,_,_) -> tp.primalRaw
| TensorR(tp,_,_,_,_) -> tp.primalRaw
/// Gets the differentiation nesting tag of the tensor
member t.nestingTag =
match t with
| TensorC(_) -> failwithf "Cannot get nesting tag of constant tensor"
| TensorF(_,_,tt) -> tt
| TensorR(_,_,_,_,tt) -> tt
/// Converts the tensor to a new tensor with the given <see cref="T:DiffSharp.Dtype"/>
member t.cast(dtype) =
if t.dtype = dtype then t else
match t with
| TensorC(tp) -> TensorC(tp.Cast(dtype))
| TensorF(_) -> failwith "Cannot cast TensorF - do not cast during differentiation"
| TensorR(_) -> failwith "Cannot cast TensorR - do not cast during differentiation"
/// Converts the tensor to a new tensor with the given system type
member t.cast<'T>() =
match box Unchecked.defaultof<'T> with
| :? float32 -> t.cast(Dtype.Float32)
| :? double -> t.cast(Dtype.Float64)
| :? int32 -> t.cast(Dtype.Int32)
| :? int64 -> t.cast(Dtype.Int64)
| :? int16 -> t.cast(Dtype.Int16)
| :? int8 -> t.cast(Dtype.Int8)
| :? byte -> t.cast(Dtype.Byte)
| :? bool -> t.cast(Dtype.Bool)
| _ -> failwithf "Cannot cast tensor with type %A to given type %A" t.dtype typeof<'T>
/// Returns a new tensor with the same contents moved to the given backend
member t.move(backend: Backend) =
// If a backend move is needed then first move to the CPU
let t =
if t.backend = backend then t
elif t.device = Device.CPU then t
else t.move(Device.CPU)
if t.backend = backend then t else
match t with
| TensorC(tp) ->
let tpflat = tp.ViewT([|tp.Nelement|])
let tpflatValues = tpflat.ToValues()
TensorC(tp.CreateLike(tpflatValues, backend=backend).ViewT(tp.Shape))
| TensorF(_) -> failwith "Cannot move TensorF - do not move during differentiation"
| TensorR(_) -> failwith "Cannot move TensorR - do not move during differentiation"
/// Returns a new tensor with the same contents moved to the given device
member t.move(device: Device) =
if t.device = device then t else
match t with
| TensorC(tp) -> TensorC(tp.MoveTo(device))
| TensorF(_) -> failwith "Cannot move TensorF - do not move during differentiation"
| TensorR(_) -> failwith "Cannot move TensorR - do not move during differentiation"
/// Returns a new tensor with the same contents moved to the given configuration
member t.move(?device:Device, ?dtype:Dtype, ?backend:Backend) =
let t = match backend with None -> t | Some backend -> t.move(backend)
let t = match dtype with None -> t | Some dtype -> t.cast(dtype)
let t = match device with None -> t | Some device -> t.move(device)
t
member internal t.castAfterSummation(?dtype:Dtype) =
match dtype with
| None -> t
| Some dt -> t.cast(dt)
/// Returns a new tensor with the same contents moved to the CPU
member t.cpu() = t.move(Device.CPU)
/// Returns a new tensor with the same contents moved to the primary GPU device
member t.gpu() = t.move(Device.GPU)
/// Returns a new tensor with each element converted to type bool
member t.bool() = t.cast(Dtype.Bool)
/// Returns a new tensor with each element converted to type int8
member t.int8() = t.cast(Dtype.Int8)
/// Returns a new tensor with each element converted to type int16
member t.int16() = t.cast(Dtype.Int16)
/// Returns a new tensor with each element converted to type int32
member t.int32() = t.cast(Dtype.Int32)
/// Returns a new tensor with each element converted to type int32
member t.int() = t.cast(Dtype.Int32)
/// Returns a new tensor with each element converted to type int64
member t.int64() = t.cast(Dtype.Int64)
/// Returns a new tensor with each element converted to type float16
member t.float16() = t.cast(Dtype.Float16)
/// Returns a new tensor with each element converted to type bfloat16
member t.bfloat16() = t.cast(Dtype.BFloat16)
/// Returns a new tensor with each element converted to type float32
member t.float32() = t.cast(Dtype.Float32)
/// Returns a new tensor with each element converted to type float64
member t.float64() = t.cast(Dtype.Float64)
/// Returns a new tensor with each element converted to type float64
member t.float() = t.cast(Dtype.Float64)
/// Returns a new tensor with each element converted to type float64
member t.double() = t.cast(Dtype.Float64)
/// Returns a new tensor with each element converted to type float64
member t.byte() = t.cast(Dtype.Byte)
/// Gets the element type of the tensor
member t.dtype = t.primalRaw.Dtype
/// Gets the device of the tensor
member t.device = t.primalRaw.Device
/// Gets the device type of the tensor
member t.deviceType = t.primalRaw.Device.DeviceType
/// Gets the backend of the tensor
member t.backend = t.primalRaw.Backend
/// Gets the differentiation depth of the tensor
member t.depth =
let rec depth x d =
match x with
| TensorC(_) -> d
| TensorF(tp,_,_) -> depth tp (d + 1)
| TensorR(tp,_,_,_,_) -> depth tp (d + 1)
depth t 0
/// Gets the parent operation of a tensor used in reverse-mode differentiation
member t.parentOp =
match t with
| TensorC(_) -> failwith "Cannot get parent operation of constant Tensor"
| TensorF(_)-> failwith "Cannot get parent operation of TensorF"
| TensorR(_,_,o,_,_) -> o
/// Gets or sets the derivative of a tensor used in differentiation
member t.derivative
with get() =
match t with
| TensorC(_) -> failwith "Cannot get derivative of constant Tensor"
| TensorF(_,td,_) -> td
| TensorR(_,td,_,_,_) -> !td
and set(value) =
match t with
| TensorC(_) -> failwith "Cannot set derivative of constant Tensor"
| TensorF(_) -> failwith "Cannot set derivative of TensorF"
| TensorR(_,td,_,_,_) -> td := value
member t.derivativeDeep =
match t with
| TensorC(_) -> failwith "Cannot get derivative of constant Tensor"
| TensorF(_,td,_) ->
match td with
| TensorC(_) -> td
| _ -> td.derivativeDeep
| TensorR(_,td,_,_,_) ->
match !td with
| TensorC(_) -> !td
| _ -> (!td).derivativeDeep
/// Gets the fanout of a tensor used in reverse-mode differentiation
member t.fanout
with get() =
match t with
| TensorC(_) -> failwith "Cannot get fanout of constant Tensor"
| TensorF(_) -> failwith "Cannot get fanout of TensorF"
| TensorR(_,_,_,f,_) -> !f
and set(value) =
match t with
| TensorC(_) -> failwith "Cannot set fanout of constant Tensor"
| TensorF(_) -> failwith "Cannot set fanout of TensorF"
| TensorR(_,_,_,f,_) -> f := value
/// <summary>
/// Returns the input tensor with added support for forward-mode automatic differentiation.
/// </summary>
/// <remarks>
/// Any tensors produced using this tensor will have attached derivatives for forward mode propagation.
/// The current global nesting level is used for nested differentiation.
/// </remarks>
member t.forwardDiff(derivative:Tensor, ?nestingTag:uint32) =
if not t.dtype.IsFloatingPoint then failwithf "Only tensors with floating dtype can be differentiated. Tensor has dtype %A." t.dtype
let nestingTag = defaultArg nestingTag GlobalNestingLevel.Current
if t.shape <> derivative.shape then
failwithf "Expecting derivative of same shape with primal. primal: %A, derivative: %A" t derivative
TensorF(t, derivative, nestingTag)
/// <summary>
/// Returns the input tensor with added support for reverse-mode automatic differentiation.
/// </summary>
/// <param name="derivative">The derivative (adjoint) to assign to the new reverse-mode tensor. Defaults to an empty placeholder tensor.</param>
/// <param name="nestingTag">The level nestingTag for nested differentiation. Defaults to the current global nesting level</param>
/// <remarks>
/// Any tensors produced using this tensor will also support reverse-mode propagation. After the completion
/// of the corresponding <c>reverse</c> operation on the overall result tensor, the computed derivative
/// will be available.
/// </remarks>
member t.reverseDiff(?derivative:Tensor, ?nestingTag:uint32) =
if not t.dtype.IsFloatingPoint then failwithf "Only tensors with floating dtype can be differentiated. Tensor has dtype %A." t.dtype
let derivative = defaultArg derivative (t.zerosLike([0]))
if derivative.nelement <> 0 && derivative.shape <> t.shape then failwithf "Expecting derivative shape (%A) to match the tensor shape (%A)" derivative.shape t.shape
let nestingTag = defaultArg nestingTag GlobalNestingLevel.Current
TensorR(t, ref derivative, NewT, ref 0u, nestingTag)
/// Returns the input tensor but with any support for automatic differentiation removed.
member t.noDiff() = t.primalDeep
/// Indicates if a tensor is taking part in forward-mode differentiation
member t.isForwardDiff =
match t with
| TensorF(_) -> true
| _ -> false
/// Indicates if a tensor is taking part in reverse-mode differentiation
member t.isReverseDiff =
match t with
| TensorR(_) -> true
| _ -> false
/// Indicates if a tensor is a constant, meaning that it is not taking part in forward or reverse-mode differentiation
member t.isNoDiff =
match t with
| TensorC(_) -> true
| _ -> false
/// Gets the shape of the tensor
member t.shape = t.primalRaw.Shape
member internal t.shapeFullBounds = shapeToFullBounds(t.shape)
/// Gets the number of dimensions of the tensor
member t.dim = t.primalRaw.Dim
/// Gets the number of elements in the tensor
member t.nelement = t.primalRaw.Nelement
/// Returns the value of a scalar tensor as an object
member t.toScalar() = t.primalRaw.ToScalar()
/// Returns the value of a (non-scalar) tensor as an array
member t.toArray() = t.primalRaw.ToArray()
/// Returns the value of a 1D tensor as a 1D array
member t.toArray1D<'T>() =
if t.dim <> 1 then failwithf "Cannot convert tensor with shape %A to 1D array" t.shape
t.cast<'T>().toArray() :?> 'T[]
/// Returns the value of a 2D tensor as a 2D array
member t.toArray2D<'T>() =
if t.dim <> 2 then failwithf "Cannot convert tensor with shape %A to 2D array" t.shape
t.cast<'T>().toArray() :?> 'T[,]
/// Returns the value of a 3D tensor as a 3D array
member t.toArray3D<'T>() =
if t.dim <> 3 then failwithf "Cannot convert tensor with shape %A to 3D array" t.shape
t.cast<'T>().toArray() :?> 'T[,,]
/// Returns the value of a 4D tensor as a 4D array
member t.toArray4D<'T>() =
if t.dim <> 4 then failwithf "Cannot convert tensor with shape %A to 4D array" t.shape
t.cast<'T>().toArray() :?> 'T[,,,]
/// Returns the value of a 5D tensor as a 5D array
member t.toArray5D<'T>() =
if t.dim <> 5 then failwithf "Cannot convert tensor with shape %A to 5D array" t.shape
t.cast<'T>().toArray()
/// Returns the value of a 6D tensor as a 6D array
member t.toArray6D<'T>() =
if t.dim <> 6 then failwithf "Cannot convert tensor with shape %A to 6D array" t.shape
t.cast<'T>().toArray()
/// Indicates if two tensors have the same differentiation type
member t1.isSameDiffType(t2:Tensor) =
match t1, t2 with
| TensorC(_), TensorC(_) -> true
| TensorC(_), TensorF(_) -> false
| TensorC(_), TensorR(_) -> false
| TensorF(_), TensorC(_) -> false
| TensorF(_), TensorF(_) -> true
| TensorF(_), TensorR(_) -> false
| TensorR(_), TensorC(_) -> false
| TensorR(_), TensorF(_) -> false
| TensorR(_), TensorR(_) -> true
/// <summary>Saves the tensor to the given file using a bespoke binary format.</summary>
/// <remarks>
/// The binary format records the elements, backend, element type and shape. It does not record the device.
/// The format used may change from version to version of DiffSharp.
/// </remarks>
member t.save(fileName:string) = saveBinary t fileName
/// <summary>Loads the tensor from the given file using the given element type and configuration.</summary>
///
/// <param name="fileName">The file from which to load the tensor.</param>
/// <param name="device">The device of the resulting tensor. Defaults to the current default device.</param>
/// <param name="dtype">The element type of the resulting tensor. Defaults to the element type of the saved tensor.</param>
/// <param name="backend">The device of the resulting tensor. Defaults to the current default backend.</param>
///
/// <remarks>
/// The backend at the time of saving the tensor must be available when the tensor is reloaded.
/// The tensor is first loaded into that backend and then moved. As a result, intermediate tensors may be created
/// in the process of reloading.
/// </remarks>
static member load(fileName:string, ?device: Device, ?dtype: Dtype, ?backend: Backend):Tensor =
let t : Tensor = loadBinary fileName
let device = defaultArg device Device.Default
let dtype = defaultArg dtype t.dtype
let backend = defaultArg backend Backend.Default
t.move(device=device, dtype=dtype, backend=backend)
/// Returns the tensor after min-max scaling
member t.normalize() =
let min = t.min()
let range = t.max() - min
if range = t.zeroLike() then
t.zerosLike()
else
(t - min) / range
/// Returns the tensor after standardization (z-score normalization)
member t.standardize() =
let stddev:Tensor = t.std()
if stddev = t.zeroLike() || stddev.hasnan() then
t.zerosLike()
else
(t - t.mean()) / stddev
/// Returns a string summarising the tensor
member t.summary() =
match t with
| TensorC(_) -> sprintf "Tensor %A" t.shape
| TensorF(_) -> sprintf "TensorF %A" t.shape
| TensorR(_,_,o,_,_) ->
let c, _ = Reflection.FSharpValue.GetUnionFields(o, typeof<TensorOp>)
let fields = c.GetFields()
sprintf "TensorR %A %s" t.shape c.Name
/// A debugging routine that returns the ancestors of a tensor involved in reverse-mode automatic differentiation
member t.ancestors() =
let mutable p = []
let rec ancestors (t:obj) d =
match t with
| :? Tensor as t ->
p <- p |> List.append [t]
match t with
| TensorC(_) -> sprintf "Tensor %A" t.shape
| TensorF(_) -> sprintf "TensorF %A" t.shape
| TensorR(_,_,o,_,_) ->
let c, _ = Reflection.FSharpValue.GetUnionFields(o, typeof<TensorOp>)
let fields = c.GetFields()
let mutable ret = sprintf "TensorR %A %s" t.shape (o.ToString())
for field in fields do
let fv = field.GetValue(o)
if fv :? Tensor then
ret <- ret + sprintf "\n%s%s" (String.replicate d " ") (ancestors fv (d+1))
ret
| :? (Tensor array) as ts ->
// p <- p |> List.append (ts |> Array.toList)
let mutable ret = ""
let mutable prefix = ""
for t in ts do
ret <- ret + sprintf "%s%s%s" prefix (String.replicate d " ") (ancestors t (d+1))
prefix <- "\n"
ret
// | _ -> indentNewLines (sprintf "%A" t) d
| _ -> ""
let ps = ancestors t 1
p |> List.rev, ps
override t.ToString() =
let rec fmt postfix (t: Tensor) =
match t with
| TensorC(p) -> p.Print(postfix)
| TensorF(tp,_,_) -> fmt (postfix + ":fwd") tp
| TensorR(tp,_,_,_,_) -> fmt (postfix + ":rev") tp
fmt "" t
override t.Equals(other) =
match other with
| :? Tensor as tensor -> t.primalRaw.Equals(tensor.primalRaw)
| _ -> false
override t.GetHashCode() = hash t.primalRaw
interface System.IComparable with
override t.CompareTo(other) =
match other with
| :? Tensor as tensor ->
if t.dim = tensor.dim && t.dim = 0 then
(t.primalRaw :> System.IComparable).CompareTo(tensor.primalRaw)
else
failwith "Cannot compare non-scalar Tensors"
| _ -> failwith "Cannot compare Tensor with another type"
/// Get the scalar zero tensor for the current configuration
static member Zero = TensorC(RawTensor.Zero())
/// Get the scalar one tensor for the current configuration
static member One = TensorC(RawTensor.One())
/// Convert a scalar tensor to a float32 value
static member op_Explicit(tensor:Tensor):single = tensor.toScalar().toSingle()
/// Convert a scalar tensor to a float64 value
static member op_Explicit(tensor:Tensor):double = tensor.toScalar().toDouble()
/// Convert a scalar tensor to a byte value
static member op_Explicit(tensor:Tensor):byte = tensor.toScalar().toByte()
/// Convert a scalar tensor to a signed byte value
static member op_Explicit(tensor:Tensor):int8 = tensor.toScalar().toSByte()
/// Convert a scalar tensor to an int16 value
static member op_Explicit(tensor:Tensor):int16 = tensor.toScalar().toInt16()
/// Convert a scalar tensor to an int32 value
static member op_Explicit(tensor:Tensor):int32 = tensor.toScalar().toInt32()
/// Convert a scalar tensor to an int64 value
static member op_Explicit(tensor:Tensor):int64 = tensor.toScalar().toInt64()
/// Convert a scalar tensor to a boolean value
static member op_Explicit(tensor:Tensor):bool = tensor.toScalar().toBool()
interface System.IConvertible with
override t.GetTypeCode() =
match t.dtype with
| Dtype.Byte -> TypeCode.Byte
| Dtype.Int8 -> TypeCode.SByte
| Dtype.Int16 -> TypeCode.Int16
| Dtype.Int32 -> TypeCode.Int32
| Dtype.Int64 -> TypeCode.Int64
| Dtype.Float32 -> TypeCode.Single
| Dtype.Float64 -> TypeCode.Double
| Dtype.Bool -> TypeCode.Boolean
| Dtype.BFloat16 -> TypeCode.Single
| Dtype.Float16 -> TypeCode.Single
override t.ToSingle(fmt) = t.toScalar().ToSingle(fmt)
override t.ToDouble(fmt) = t.toScalar().ToDouble(fmt)
override t.ToByte(fmt) = t.toScalar().ToByte(fmt)
override t.ToSByte(fmt) = t.toScalar().ToSByte(fmt)
override t.ToInt16(fmt) = t.toScalar().ToInt16(fmt)
override t.ToInt32(fmt) = t.toScalar().ToInt32(fmt)
override t.ToInt64(fmt) = t.toScalar().ToInt64(fmt)
override t.ToBoolean(fmt) = t.toScalar().ToBoolean(fmt)
override t.ToChar(fmt) = t.toScalar().ToChar(fmt)
override t.ToDateTime(fmt) = t.toScalar().ToDateTime(fmt)
override t.ToDecimal(fmt) = t.toScalar().ToDecimal(fmt)
override t.ToString(fmt) = t.toScalar().ToString(fmt)
override t.ToType(ty, fmt) = t.toScalar().ToType(ty, fmt)
override t.ToUInt16(fmt) = t.toScalar().ToUInt16(fmt)
override t.ToUInt32(fmt) = t.toScalar().ToUInt32(fmt)
override t.ToUInt64(fmt) = t.toScalar().ToUInt64(fmt)
/// Convert a scalar tensor to a float32 value
member t.toSingle() = t.toScalar().toSingle()
/// Convert a scalar tensor to a float64 value
member t.toDouble() = t.toScalar().toDouble()
/// Convert a scalar tensor to a byte value
member t.toByte() = t.toScalar().toByte()
/// Convert a scalar tensor to a signed byte value
member t.toSByte() = t.toScalar().toSByte()
/// Convert a scalar tensor to an int16 value
member t.toInt16() = t.toScalar().toInt16()
/// Convert a scalar tensor to an int32 value
member t.toInt32() = t.toScalar().toInt32()
/// Convert a scalar tensor to an int64 value
member t.toInt64() = t.toScalar().toInt64()
/// Convert a scalar tensor to a boolean value
member t.toBool() = t.toScalar().toBool()
/// Returns the size in bytes of an individual element in this tensor. Depending on dtype, backend configuration, this is not guaranteed to be correct and can behave differently in different runtime environments.
member t.elementSize =
let bitsPerElement =
match t.backend, t.dtype with
| Backend.Reference, Dtype.BFloat16 -> 32 // Backed by float32
| Backend.Reference, Dtype.Float16 -> 32 // Backed by float32
| Backend.Reference, Dtype.Float32 -> 32
| Backend.Reference, Dtype.Float64 -> 64
| Backend.Reference, Dtype.Int8 -> 8
| Backend.Reference, Dtype.Byte -> 8
| Backend.Reference, Dtype.Int16 -> 16
| Backend.Reference, Dtype.Int32 -> 32
| Backend.Reference, Dtype.Int64 -> 64
| Backend.Reference, Dtype.Bool -> 8 // Not reliable https://stackoverflow.com/a/28515361
| Backend.Torch, Dtype.BFloat16 -> 16
| Backend.Torch, Dtype.Float16 -> 16
| Backend.Torch, Dtype.Float32 -> 32
| Backend.Torch, Dtype.Float64 -> 64
| Backend.Torch, Dtype.Int8 -> 8
| Backend.Torch, Dtype.Byte -> 8
| Backend.Torch, Dtype.Int16 -> 16
| Backend.Torch, Dtype.Int32 -> 32
| Backend.Torch, Dtype.Int64 -> 64
| Backend.Torch, Dtype.Bool -> 8 // https://github.com/pytorch/pytorch/issues/41571
| _ -> failwithf "Unknown backend, dtype configuration to compute memory size"
bitsPerElement / 8
/// Returns the size in bytes of the total memory used by this tensor. Depending on dtype, backend configuration, this is not guaranteed to be correct and can behave differently in different runtime environments.
member t.memorySize = (int64 t.nelement) * (int64 t.elementSize)
/// Indicates if two tensors have the same shape and all corresponding elements are equal within the
/// given tolerances.
member t.allclose(tensor:Tensor, ?relativeTolerance, ?absoluteTolerance) =
let relativeTolerance = defaultArg relativeTolerance 1e-5
let absoluteTolerance = defaultArg absoluteTolerance 1e-8
t.primalRaw.AllClose(tensor.primalRaw, relativeTolerance, absoluteTolerance)
/// Returns a new tensor filled with '0' values for the given shape, element type and configuration, defaulting to the
/// shape and configuration of the input tensor.
member a.zerosLike(?shape:seq<int>, ?device, ?dtype, ?backend) =
let shape = defaultArg shape (a.shape |> Array.toSeq)
TensorC(a.primalRaw.ZerosLike(shape |> Array.ofSeq, ?device=device, ?dtype=dtype, ?backend=backend))
/// Returns a new tensor filled with '1' values for the given shape, element type and configuration, defaulting to the
/// shape and configuration of the input tensor.
member a.onesLike(?shape:seq<int>, ?device, ?dtype, ?backend) =
let shape = defaultArg shape (a.shape |> Array.toSeq)
TensorC(a.primalRaw.OnesLike(shape |> Array.ofSeq, ?device=device, ?dtype=dtype, ?backend=backend))
/// Returns a new tensor filled with the given scalar value for the given shape, element type and configuration, defaulting to the
/// shape and configuration of the input tensor.
member a.fullLike(value:scalar, ?shape:seq<int>, ?device, ?dtype, ?backend) =
let shape = defaultArg shape (a.shape |> Array.toSeq)
TensorC(a.primalRaw.FullLike(shape |> Array.ofSeq, value, ?device=device, ?dtype=dtype, ?backend=backend))
/// Returns a new scalar tensor for the given shape, element type and configuration, defaulting to the
/// shape and configuration of the input tensor.
member a.scalarLike(scalar:scalar, ?device, ?dtype, ?backend) =
a.fullLike(scalar, [], ?device=device, ?dtype=dtype, ?backend=backend)
/// Returns a new tensor with random values drawn from the uniform distribution [0,1) for the
/// given shape, element type and configuration, defaulting to the shape and configuration of the input tensor.
member a.randLike(?shape:seq<int>, ?device, ?dtype, ?backend) =
let shape = defaultArg shape (a.shape |> Array.toSeq)
TensorC(a.primalRaw.RandomLike((shape |> Array.ofSeq), ?device=device, ?dtype=dtype, ?backend=backend))
/// Returns a new tensor with random values drawn from the standard normal distribution, for the
/// given shape, element type and configuration, defaulting to the shape and configuration of the input tensor.
member a.randnLike(?shape:seq<int>, ?device, ?dtype, ?backend) =
let shape = defaultArg shape (a.shape |> Array.toSeq)
TensorC(a.primalRaw.RandomNormalLike(shape |> Array.ofSeq, ?device=device, ?dtype=dtype, ?backend=backend))
/// Returns a new tensor with random integer values drawn from the given range, for the
/// given shape, element type and configuration, defaulting to the shape and configuration of the input tensor.
member a.randintLike(low:int, high:int, ?shape:seq<int>, ?device, ?dtype, ?backend) =
let shape = defaultArg shape (a.shape |> Array.toSeq)
TensorC(a.primalRaw.RandomIntLike(shape |> Array.ofSeq, low, high, ?device=device, ?dtype=dtype, ?backend=backend))
/// Returns a scalar '0' tensor for the given element type and configuration, defaulting to
/// the element type and configuration of the input tensor.
member a.zeroLike(?device, ?dtype, ?backend) = TensorC(a.primalRaw.ZeroLike(?device=device, ?dtype=dtype, ?backend=backend))
/// Returns a scalar '1' tensor for the given element type and configuration, defaulting to
/// the element type and configuration of the input tensor.
member a.oneLike(?device, ?dtype, ?backend) = TensorC(a.primalRaw.OneLike(?device=device, ?dtype=dtype, ?backend=backend))
/// Returns a tensor in the manner of <see cref="M:DiffSharp.dsharp.arange"/> for the given element type and configuration, defaulting to
/// the element type and configuration of the input tensor.
member a.arangeLike(endVal:float, ?startVal:float, ?step:float, ?device, ?dtype, ?backend) =
let startVal = defaultArg startVal 0.
let step = defaultArg step 1.
let length = (endVal - startVal) / step |> ceil |> int
let v = Array.init length (fun i -> startVal + float(i) * step)
a.like(box v, ?device=device, ?dtype=dtype, ?backend=backend)
/// Returns a tensor in the manner of <see cref="M:DiffSharp.dsharp.arange"/> for the given element type and configuration, defaulting to
/// the element type and configuration of the input tensor.
member a.arangeLike(endVal:int, ?startVal:int, ?step:int, ?device, ?dtype, ?backend) =
let endVal = endVal |> float
let startVal = defaultArg startVal 0 |> float
let step = defaultArg step 1 |> float
let dtype = defaultArg dtype Dtype.Int32
a.arangeLike(endVal=endVal, startVal=startVal, step=step, ?device=device, dtype=dtype, ?backend=backend)
/// Returns a tensor in the manner of <see cref="M:DiffSharp.dsharp.linspace"/> for the given element type and configuration, defaulting to
/// the element type and configuration of the input tensor.
member a.linspaceLike(startVal:float, endVal:float, steps:int, ?device, ?dtype, ?backend) =
let stepVal = (endVal - startVal) / (float (steps - 1))
let v = Array.init steps (fun i -> startVal + (float i) * stepVal)
a.like(box v, ?device=device, ?dtype=dtype, ?backend=backend)
/// Returns a tensor in the manner of <see cref="M:DiffSharp.dsharp.linspace"/> for the given element type and configuration, defaulting to
/// the element type and configuration of the input tensor.
member a.linspaceLike(startVal:int, endVal:int, steps:int, ?device, ?dtype, ?backend) =
a.linspaceLike(startVal |> float, endVal |> float, steps, ?device=device, ?dtype=dtype, ?backend=backend)
/// Returns a tensor in the manner of <see cref="M:DiffSharp.dsharp.logspace"/> for the given element type and configuration, defaulting to
/// the element type and configuration of the input tensor.
member a.logspaceLike(startVal:float, endVal:float, steps:int, ?baseVal:float, ?device, ?dtype, ?backend) =
let baseVal = defaultArg baseVal 10.
a.scalarLike(baseVal, ?device=device, ?dtype=dtype, ?backend=backend).pow(a.linspaceLike(startVal, endVal, steps, ?device=device, ?dtype=dtype, ?backend=backend))
/// Returns a tensor in the manner of <see cref="M:DiffSharp.dsharp.logspace"/> for the given element type and configuration, defaulting to
/// the element type and configuration of the input tensor.
member a.logspaceLike(startVal:int, endVal:int, steps:int, ?baseVal:int, ?device, ?dtype, ?backend) =
let baseVal = defaultArg baseVal 10
a.logspaceLike(startVal |> float, endVal |> float, steps, baseVal |> float, ?device=device, ?dtype=dtype, ?backend=backend)
/// <summary>
/// Returns a tensor from the .NET data in <c>value</c> for the given element type and configuration, defaulting to
/// the element type and configuration of the input tensor.
/// </summary>
member a.like(value, ?device, ?dtype, ?backend) = TensorC(a.primalRaw.CreateLike(value, ?device=device, ?dtype=dtype, ?backend=backend))
/// <summary>Returns a new tensor with underlying storage copied.</summary>
/// <remarks>
/// This method discards differentiability and returns a constant tensor.
/// </remarks>
member a.clone() = TensorC(a.primalRaw.Clone())
/// Returns a tensor in the manner of <see cref="M:DiffSharp.dsharp.onehot"/> for the given element type and configuration, defaulting to
/// the element type and configuration of the input tensor.
member a.onehotLike(length:int, hot:int, ?device, ?dtype, ?backend) =
if hot < 0 || hot >= length then failwithf "Expecting 0 <= hot < length"
a.zerosLike([|length|], ?device=device, ?dtype=dtype, ?backend=backend).addSlice([|hot|], a.onesLike([|1|], ?device=device, ?dtype=dtype, ?backend=backend))
/// <summary>Computes element-wise \(a < b\), returning a boolean tensor containing a <c>true</c> at each location where the comparison is true</summary>
member a.lt(b:Tensor) = TensorC(a.primalRaw.LtTT(b.primalRaw))
/// <summary>Computes element-wise \(a > b\), returning a boolean tensor containing a <c>true</c> at each location where the comparison is true</summary>
member a.gt(b:Tensor) = TensorC(a.primalRaw.GtTT(b.primalRaw))
/// <summary>Computes element-wise \(a \leq b\), returning a boolean tensor containing a <c>true</c> at each location where the comparison is true</summary>
member a.le(b:Tensor) =TensorC(a.primalRaw.LeTT(b.primalRaw))
/// <summary>Computes element-wise \(a \geq b\), returning a boolean tensor containing a <c>true</c> at each location where the comparison is true</summary>
member a.ge(b:Tensor) = TensorC(a.primalRaw.GeTT(b.primalRaw))
/// <summary>Computes element-wise \(a = b\), returning a boolean tensor containing a <c>true</c> at each location where the comparison is true</summary>
member a.eq(b:Tensor) = TensorC(a.primalRaw.EqTT(b.primalRaw))
/// <summary>Computes element-wise \(a \neq b\), returning a boolean tensor containing a <c>true</c> at each location where the comparison is true</summary>
member a.ne(b:Tensor) = let e = a.eq(b) in e.lt(e.onesLike()) // Implement "not equal" relying on "equal"
/// <summary>Returns a new tensor with boolean elements representing if each element is +/-INF or not.</summary>
member a.isinf() = TensorC(a.primalRaw.IsInfT())
/// <summary>Returns a new tensor with boolean elements representing if each element is NaN or not. Complex values are considered NaN when either their real and/or imaginary part is NaN.</summary>
member a.isnan() = TensorC(a.primalRaw.IsNaNT())
/// Gets if any value in the tensor is +/- INF.
member a.hasinf() = a.isinf().sum() > a.zeroLike(dtype=Dtype.Int64)
/// Gets if any value in the tensor is NaN.
member a.hasnan() = a.isnan().sum() > a.zeroLike(dtype=Dtype.Int64)
/// Gets if any value in the tensor is NaN or +/- INF.
member a.hasinfnan() = a.hasinf() || a.hasnan()
/// Gets the index of a maximum value in the tensor.
member a.argmax() =
a.primalRaw.MaxIndexT()
/// <summary>Returns the indexes of maximum values of the primal of the tensor, reducing the given dimension.</summary>
/// <remarks>The resulting tensor does not participate in reverse or forward differentiation. It can be used as input to another operation such as <c>dsharp.gather</c>.</remarks>
member a.argmax(dim:int, ?keepDim: bool) =
let keepDim = defaultArg keepDim false
Shape.checkCanMinMaxReduce dim keepDim a.shape |> ignore
a.primalRaw.MaxReduceT(dim, keepdim=keepDim) |> snd |> TensorC
/// Gets the index of a minimum value in the tensor.
member a.argmin() =
a.primalRaw.MinIndexT()
/// <summary>Returns the indexes of minimum values of the primal of the tensor, reducing the given dimension.</summary>
/// <remarks>The resulting tensor does not participate in reverse or forward differentiation. It can be used as input to another operation such as <c>dsharp.gather</c>.</remarks>
member a.argmin(dim: int, ?keepDim: bool) =
let keepDim = defaultArg keepDim false
Shape.checkCanMinMaxReduce dim keepDim a.shape |> ignore
a.primalRaw.MinReduceT(dim, keepdim=keepDim) |> snd |> TensorC
/// Returns the maximum value along the given dimension of all elements in the input tensor.
member a.max(dim:int, ?keepDim:bool) =
let keepdim = defaultArg keepDim false
let indices = a.argmax(dim=dim, keepDim=true)
let ret:Tensor = a.gather(dim, indices)
if keepdim then ret else ret.squeeze(dim)
/// Returns the minimum value along the given dimension of all elements in the input tensor.
member a.min(dim:int, ?keepDim:bool) =
let keepdim = defaultArg keepDim false
let indices = a.argmin(dim=dim, keepDim=true)
let ret:Tensor = a.gather(dim, indices)
if keepdim then ret else ret.squeeze(dim)
/// Returns the maximum value of all elements in the input tensor.
member a.max() = if a.dim = 0 then a else a[a.argmax()]
/// Returns the minimum value of all elements in the input tensor.
member a.min() = if a.dim = 0 then a else a[a.argmin()]
/// Returns the element-wise maximum of the elements in the two tensors.
member a.max(b:Tensor) =
if a.dtype <> b.dtype then
match Dtype.widen a.dtype b.dtype with
| None -> opNotSupported "max" a.dtype b.dtype
| Some tnew ->
let aCast = a.cast(tnew)
let bCast = b.cast(tnew)
aCast.max(bCast)
elif a.dtype = Dtype.Byte || a.dtype = Dtype.Bool then
let result:Tensor = a.cast(Dtype.Int16).max(b.cast(Dtype.Int16))
result.cast(a.dtype)
else
let result:Tensor = ((a + b) + Tensor.Abs(b - a)) / 2
if result.dtype <> a.dtype then result.cast(a.dtype) else result
/// Returns the element-wise minimum of the elements in the two tensors.
member a.min(b:Tensor) =
if a.dtype <> b.dtype then
match Dtype.widen a.dtype b.dtype with
| None -> opNotSupported "min" a.dtype b.dtype
| Some tnew ->
let aCast = a.cast(tnew)
let bCast = b.cast(tnew)
aCast.min(bCast)
elif a.dtype = Dtype.Byte || a.dtype = Dtype.Bool then
let result:Tensor = a.cast(Dtype.Int16).min(b.cast(Dtype.Int16))
result.cast(a.dtype)
else
let result:Tensor = ((a + b) - Tensor.Abs(a - b)) / 2
if result.dtype <> a.dtype then result.cast(a.dtype) else result
/// <summary>
/// Returns a tensor with the diagonal elements with respect to <c>dim1</c> and <c>dim2</c>.
/// The argument offset controls which diagonal to consider.
/// </summary>
member a.diagonal(?offset:int, ?dim1:int, ?dim2:int) =
// TODO: The following can be slow, especially for reverse mode differentiation of the diagonal of a large tensor. Consider a faster implementation.
if a.dim < 2 then failwithf "Tensor must be at least 2-dimensional"
let offset = defaultArg offset 0
let dim1 = defaultArg dim1 0
let dim2 = defaultArg dim2 1
let mutable finished = false
let mutable d = []
let mutable i = 0
let mutable j = offset
while not finished do
if i >= a.shape[dim1] || j >= a.shape[dim2] then
finished <- true
elif j >= 0 then
// let bounds = array2D [[i0min; i0max; i0given]; [i1min; i1max; i1given]; [i2min; i2max; i2given]; [i3min; i3max; i3given]]
let bounds = Array2D.init (a.dim) 3 (fun ii jj ->
if ii = dim1 then
if jj < 2 then i else 1
elif ii = dim2 then
if jj < 2 then j else 1
else
if jj = 0 then 0
elif jj = 1 then a.shape[ii]-1
else 0
)
d <- [a.GetSlice(bounds)] |> List.append d
i <- i + 1
j <- j + 1
if d |> List.isEmpty then failwithf "Empty diagonal"
Tensor.stack(d)
/// <summary>Returns the sum of the elements of the diagonal of the input 2-D matrix.</summary>
member a.trace() = let d:Tensor = a.diagonal() in d.sum()
/// <summary>Returns a new view of the object tensor with singleton dimensions expanded to a larger size.</summary>
/// <remarks>
/// <para>Passing -1 as the size for a dimension means not changing the size of that dimension.</para>
/// <para>The tensor can be also expanded to a larger number of dimensions, and the new ones will be appended
/// at the front. For the new dimensions, the size cannot be set to -1.
/// </para>
/// <para>
/// Expanding a tensor does not allocate new memory, but only creates a new view on the existing tensor
/// where a dimension of size one is expanded to a larger size by setting the stride to 0. Any dimension
/// of size 1 can be expanded to an arbitrary value without allocating new memory.
/// </para>
/// </remarks>
member a.expand(newShape:seq<int>) =
let newShape = newShape|>Shape.create
if a.shape = newShape then a
else
let newShape = Shape.completeExpand a.shape newShape // Handles -1 semantics
Shape.checkCanExpand a.shape newShape
match a with
| TensorC(ap) -> TensorC(ap.Expand(newShape))
| TensorF(ap,ad,at) ->
let fp = ap.expand(newShape)
let fd = ad.expand(newShape)
TensorF(fp,fd,at)
| TensorR(ap,_,_,_,at) ->
let fp = ap.expand(newShape)
TensorR(fp, ref (a.zerosLike([0])), ExpandT(a), ref 0u, at)
/// <summary>Expand this tensor to the same size as the other.</summary>
member a.expandAs(b:Tensor) = a.expand(b.shape)
/// <summary>Convert tensor to an image tensor with shape Channels x Height x Width</summary>
member t.toImage(?pixelMin:double, ?pixelMax:double, ?normalize:bool, ?gridCols:int) =
let pixelMin = defaultArg pixelMin 0.
let pixelMax = defaultArg pixelMax 1.
let normalize = defaultArg normalize false
if t.dim < 1 || t.dim > 4 then failwithf "Expecting the tensor 1 <= dim (%A) <= 4, received shape %A" t.dim t.shape
if t.dim = 4 then // we make an image grid
let mutable numItems = t.shape[0]
let cols = defaultArg gridCols (int(ceil(sqrt(float(numItems)))))
if cols < 1 || cols > numItems then failwithf "Expecting 1 <= gridCols (%A) <= %A" cols numItems
let mutable rows = 0
let mutable items = numItems
while items > 0 do
rows <- rows + 1
items <- items - cols
let c, h, w = t.shape[1], t.shape[2], t.shape[3]
let mutable tgrid = t.zerosLike([h*rows; w*cols; c])
// transform [n, c, h, w] to [n, h, w, c]
let t:Tensor = t.transpose(1, 3)
let t = t.transpose(2, 1)
let mutable i = 0
for row=0 to rows-1 do
for col=0 to cols-1 do
if i < numItems then
tgrid <- tgrid.addSlice([row*h; col*w; 0], t[i])
i <- i + 1
// transform [h, w, c] to [c, h, w]
tgrid <- tgrid.transpose(0, 2)
tgrid <- tgrid.transpose(1, 2)
tgrid.toImage(pixelMin=pixelMin, pixelMax=pixelMax, normalize=normalize)
else
let mutable pixels = t
if t.dim = 1 then
pixels <- pixels.view([1; 1; t.nelement])
pixels <- pixels.expand([3; -1; -1])
elif t.dim = 2 then
pixels <- pixels.view([1; t.shape[0]; t.shape[1]])
pixels <- pixels.expand([3; -1; -1])
else
if t.shape[0] = 1 then
pixels <- pixels.expand([3; -1; -1])
elif t.shape[0] <> 3 then
failwithf "Expecting the number of channels (%A) to be 1 or 3" t.shape[0]
if pixelMin < 0. || pixelMin > 1. then failwithf "Expecting 0 <= pixelMin (%A) <= 1" pixelMin
if pixelMax < 0. || pixelMax > 1. then failwithf "Expecting 0 <= pixelMax (%A) <= 1" pixelMax
let pixelRange = pixelMax - pixelMin
if pixelRange <= 0. then failwithf "Expecting pixelMin (%A) < pixelMax (%A)" pixelMin pixelMax
if normalize then
pixels <- pixels.normalize()
pixels <- pixelMin + pixels.mul(pixelRange)
pixels
/// <summary>Convert tensor to a grayscale image tensor and return a string representation approximating grayscale values</summary>
member t.toImageString(?pixelMin:double, ?pixelMax:double, ?normalize:bool, ?gridCols:int, ?asciiPalette:string) =
let asciiPalette = defaultArg asciiPalette """ .'`,^:";~-_+<>i!lI?/\|()1{}[]rcvunxzjftLCJUYXZO0Qoahkbdpqwm*WMB8&%$#@"""
let pixels:Tensor = t.toImage(?pixelMin=pixelMin, ?pixelMax=pixelMax, ?normalize=normalize, ?gridCols=gridCols).mean(0) // make it grayscale
let numToAscii (numZeroToOne:float) =
let c = int (numZeroToOne * float(asciiPalette.Length)) - 1
let c = min (asciiPalette.Length - 1) (max 0 c)
asciiPalette[c]
let h, w = pixels.shape[0], pixels.shape[1]
let sb = System.Text.StringBuilder()
for y=0 to h-1 do
for x=0 to w-1 do
sb.Append(numToAscii (float(pixels[y, x]))) |> ignore
sb.AppendLine() |> ignore
sb.ToString()
member t.GetSlice(bounds:int[,]) =
if t.dim = 0 then failwith "Cannot slice a scalar Tensor"
let fullBounds = t.shapeFullBounds |> Array2D.copy
bounds |> Array2D.iteri (fun i j v ->
if j=1 && v >= t.shape[i] then failwithf "Index outside the bounds of Tensor shape %A" t.shape
fullBounds[i, j] <- v)
if fullBounds = t.shapeFullBounds then t // We don't need to slice as the result of the slicing would be the same with this existing tensor
else
match t with
| TensorC(ap) -> TensorC(ap.GetSlice(fullBounds))
| TensorF(ap,ad,at) -> TensorF(ap.GetSlice(fullBounds), ad.GetSlice(fullBounds), at)
| TensorR(ap,_,_,_,at) -> TensorR(ap.GetSlice(fullBounds), ref (ap.zerosLike([0])), SliceT(t, fullBounds), ref 0u, at)
/// <summary>Get the item at the given index as a scalar tensor.</summary>
member t.Item
with get([<System.ParamArray>] index:int[]) =
if t.dim = 0 then failwith "Cannot index a scalar Tensor"
if index.Length > t.dim then failwithf "Expecting an index with <=%i dimensions" t.dim
let bounds = Array2D.init index.Length 3 (fun i j -> if j=2 then 1 else index[i])
t.GetSlice(bounds)
/// <summary>
/// Creates a new tensor from the raw tensor.
/// </summary>
/// <param name="rawTensor">The given raw tensor.</param>
static member ofRawTensor(rawTensor: RawTensor) = TensorC rawTensor
/// <summary>
/// Creates a new tensor from the given data, using the given element type and configuration.
/// </summary>
/// <param name="value">The .NET object used to form the initial values for the tensor.</param>
/// <param name="device">The desired device of returned tensor. Default: if None, uses Device.Default.</param>
/// <param name="dtype">The desired element type of returned tensor. Default: if None, uses Dtype.Default.</param>
/// <param name="backend">The desired backend of returned tensor. Default: if None, uses Backend.Default.</param>
/// <remarks>The fastest creation technique is a one dimensional array matching the desired dtype. Then use 'view' to reshape.</remarks>
static member create(value:obj, ?device:Device, ?dtype:Dtype, ?backend:Backend) =
// Fast paths to create directly from 1D array matching the dtype
match value, defaultArg dtype Dtype.Default with
| (:? (int32[]) as arr), Dtype.Int32 -> TensorC(RawTensor.CreateFromFlatArray(arr, shape=[| arr.Length |], ?device=device, ?dtype=dtype, ?backend=backend))
| (:? (single[]) as arr), Dtype.Float32 -> TensorC(RawTensor.CreateFromFlatArray(arr, shape=[| arr.Length |], ?device=device, ?dtype=dtype, ?backend=backend))
| (:? (double[]) as arr), Dtype.Float64 -> TensorC(RawTensor.CreateFromFlatArray(arr, shape=[| arr.Length |], ?device=device, ?dtype=dtype, ?backend=backend))
| (:? (int16[]) as arr), Dtype.Int16 -> TensorC(RawTensor.CreateFromFlatArray(arr, shape=[| arr.Length |], ?device=device, ?dtype=dtype, ?backend=backend))
| (:? (int64[]) as arr), Dtype.Int64 -> TensorC(RawTensor.CreateFromFlatArray(arr, shape=[| arr.Length |], ?device=device, ?dtype=dtype, ?backend=backend))
// Extra type match check is needed to distinguish between arrays holding byte and int8, see https://github.com/dotnet/fsharp/issues/10202
| (:? (byte[]) as arr), Dtype.Byte when DataConverter.typesMatch<byte> arr -> TensorC(RawTensor.CreateFromFlatArray(arr, shape=[| arr.Length |], ?device=device, ?dtype=dtype, ?backend=backend))
| (:? (int8[]) as arr), Dtype.Int8 when DataConverter.typesMatch<int8> arr -> TensorC(RawTensor.CreateFromFlatArray(arr, shape=[| arr.Length |], ?device=device, ?dtype=dtype, ?backend=backend))
| _ ->
// Empty tensor (no data, shape: [0])
match value with
| :? (seq<obj>) as v when Seq.isEmpty v ->
let result = TensorC(RawTensor.CreateFromFlatArray(Array.zeroCreate<float32> 0, shape=[|0|], ?device=device, dtype=Dtype.Float32, ?backend=backend))
let dtype2 = defaultArg dtype Dtype.Default
result.cast(dtype=dtype2)
| _ ->
// Create a new Tensor from a structure holding scalar Tensors. Maintains differentiability.
let res = value |> DataConverter.tryFlatArrayAndShape<Tensor>
match res with
| Some (tensors, shape) ->
let allScalar = tensors |> Array.forall (fun t -> t.dim = 0)
if not allScalar then failwithf "Combining tensors in an array is only supported where all tensors in the array are scalar (zero-dimensional). Check other operations like stack, cat to combine tensors."
Tensor.stack(tensors).view(shape)
| None ->
// General constant tensor
TensorC(RawTensor.Create(value, ?device=device, ?dtype=dtype, ?backend=backend))
/// <summary>Returns a 2-D tensor with ones on the diagonal and zeros elsewhere.</summary>
static member eye(rows:int, ?cols:int, ?device:Device, ?dtype:Dtype, ?backend:Backend) =
let cols = defaultArg cols rows
if rows <= 0 || cols <= 0 then Tensor.create([], ?device=device, ?dtype=dtype, ?backend=backend)
else
let vals = Array2D.init rows cols (fun i j -> if i = j then 1 else 0)
Tensor.create(vals, ?device=device, ?dtype=dtype, ?backend=backend)