-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathml.go
3126 lines (2497 loc) · 72.1 KB
/
ml.go
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
package fast
import (
"fmt"
"math"
"os"
"reflect"
"runtime"
"sync"
"time"
"unsafe"
"github.com/x448/float16"
)
const (
DEBUG = false
MAX_DIMS = 4
MAX_NODES = 4096
MAX_PARAMS = 16
MAX_OPT = 4
QK = 32 // quantization
TOKEN_BOS = 1
TOKEN_EOS = 2
)
// computation graph
type Graph struct {
//MaxThreads int
//UseAVX bool
//UseNEON bool
NodesCount uint32
LeafsCount uint32
Jobs chan *ComputeParams
Nodes [MAX_NODES]*Tensor
Grads [MAX_NODES]*Tensor
Leafs [MAX_NODES]*Tensor
}
type InitParams struct {
}
type Context struct {
MaxThreads int
UseAVX bool
UseNEON bool
//Graph *Graph
Compute chan *ComputeParams
Allocator *Allocator
}
func NewContext(maxThreads int, useAVX, useNEON bool) *Context {
ch := make(chan *ComputeParams, maxThreads) // TODO: +1 for safety?
for i := 0; i < maxThreads; i++ {
go Job(ch, i)
}
return &Context{
MaxThreads: maxThreads,
UseAVX: useAVX,
UseNEON: useNEON,
Compute: ch,
Allocator: NewAllocator(),
}
}
// ReleaseContext frees all context resources - channel will be closed and goroutines stopped
func (ctx *Context) ReleaseContext() {
close(ctx.Compute)
// TODO: Maybe some steps for Allocator too
}
type DType uint8
// Data types are the same as in llama.cpp so full compatibility there
const (
TYPE_F32 DType = 0
TYPE_F16 DType = 1
TYPE_Q4_0 DType = 2
TYPE_Q4_1 DType = 3
TYPE_I8 DType = 4
TYPE_I16 DType = 5
TYPE_I32 DType = 6
TYPE_COUNT DType = 8
)
func printTensor(tensor *Tensor, name string) {
var dt string
switch tensor.Type {
case TYPE_F16:
dt = "FP16"
case TYPE_F32:
dt = "FP32"
case TYPE_Q4_0:
dt = "INT4"
}
fmt.Printf("\n\n=== [ %s | %s | %d:%d:%d ] ===\n",
name, dt, tensor.NE[0], tensor.NE[1], tensor.NE[2])
for nn := 0; nn < min(12, int(tensor.NE[1])); nn++ {
fmt.Printf("\n %d x %d ...\t", nn, tensor.NE[0])
for ii := 0; ii < min(12, int(tensor.NE[0])); ii++ {
fmt.Printf("%.3f\t", tensor.Data[nn*int(tensor.NE[0])+ii])
}
}
}
// precomputed exp table for f16 (128 KB)
// static ggml_fp16_t table_exp_f16[1 << 16];
var TableExpFP16 [1 << 16]float16.Float16
var BLCK_SIZE [TYPE_COUNT]uint32 = [TYPE_COUNT]uint32{1, 1, QK, QK, 1, 1, 1, 0}
var TYPE_SIZE [TYPE_COUNT]uint32 = [TYPE_COUNT]uint32{4, 2, 4 + QK/2, 4*2 + QK/2, 1, 2, 4, 0}
func TypeSizeFloat(dt DType) float32 {
return float32(TYPE_SIZE[dt]) / float32(BLCK_SIZE[dt])
}
// available tensor operations
type optype uint8
const (
OP_NONE optype = iota
OP_DUP
OP_ADD
OP_SUB
OP_MUL
OP_DIV
OP_SQR
OP_SQRT
OP_SUM
OP_MEAN
OP_REPEAT
OP_ABS
OP_SGN
OP_NEG
OP_STEP
OP_RELU
OP_GELU
OP_SILU
OP_NORM
OP_RMS_NORM
OP_MUL_MAT
OP_SCALE
OP_CPY
OP_RESHAPE
OP_VIEW
OP_PERMUTE
OP_TRANSPOSE
OP_GET_ROWS
OP_DIAG_MASK_INF
OP_SOFT_MAX
OP_ROPE
OP_CONV_1D_1S
OP_CONV_1D_2S
OP_FLASH_ATTN
OP_FLASH_FF
OP_COUNT
)
// Tensor of up to 4x dimensions
// The multi-dimensional tensors are stored in row-major order
// and the array indexes are written row-first (lexicographical access order)
type Tensor struct {
Type DType
Reusable bool // this tensor Data buffer might be reused with pooling
Dims uint32
NE [MAX_DIMS]uint32 // number of elements
NB [MAX_DIMS]uint32 // stride in bytes
op optype
isParam bool
grad *Tensor
src0 *Tensor
src1 *Tensor
opt [MAX_OPT]*Tensor // FIXME: Do we need this?
TasksCount int
Data []float32
}
// ggml_is_contiguous
func (tensor *Tensor) IsContiguous() bool {
return tensor.NB[0] == TYPE_SIZE[tensor.Type] &&
tensor.NB[1] == tensor.NB[0]*tensor.NE[0]/BLCK_SIZE[tensor.Type] &&
tensor.NB[2] == tensor.NB[1]*tensor.NE[1] &&
tensor.NB[3] == tensor.NB[2]*tensor.NE[2]
}
func AreSameShape(a, b *Tensor) bool {
return (a.NE[0] == b.NE[0]) && (a.NE[1] == b.NE[1]) && (a.NE[2] == b.NE[2]) && (a.NE[3] == b.NE[3])
}
func (t *Tensor) Nelements() uint32 {
return t.NE[0] * t.NE[1] * t.NE[2] * t.NE[3]
}
func (t *Tensor) Nrows() uint32 {
return t.NE[1] * t.NE[2] * t.NE[3]
}
// ggml_nbytes
func (t *Tensor) Nbytes() uint32 {
return (t.Nelements() * TYPE_SIZE[t.Type]) / BLCK_SIZE[t.Type]
}
// ggml_view_tensor
func ViewTensor(ctx *Context, src *Tensor) *Tensor {
return NewTensor(ctx, src.Type, src.Dims, src.NE[0], src.NE[1], src.NE[2], src.NE[3], src.Data)
}
// ggml_dup_tensor
func DupTensor(ctx *Context, src *Tensor) *Tensor {
return NewTensor(ctx, src.Type, src.Dims, src.NE[0], src.NE[1], src.NE[2], src.NE[3], nil) // Reusbale OK
}
// struct ggml_tensor * Mul(
func Mul(ctx *Context, a, b *Tensor) *Tensor {
return MulImpl(ctx, a, b, false)
}
// struct ggml_tensor * Mul_inplace(
func MulInplace(ctx *Context, a, b *Tensor) *Tensor {
return MulImpl(ctx, a, b, true)
}
// struct ggml_tensor * Mul_impl(
func MulImpl(ctx *Context, a, b *Tensor, inplace bool) *Tensor {
////ASSERT(ggml_are_same_shape(a, b));
if !AreSameShape(a, b) {
fmt.Printf("\n[STOP] MulImpl - tensors of different shapes!")
os.Exit(1)
}
isNode := false
if inplace && (a.grad != nil || b.grad != nil) {
isNode = true
}
if inplace {
////ASSERT(is_node == false);
}
var result *Tensor
if inplace {
result = ViewTensor(ctx, a)
} else {
result = DupTensor(ctx, a)
}
result.op = OP_MUL
result.src0 = a
result.src1 = b
if isNode {
result.grad = DupTensor(ctx, result)
} else {
result.grad = nil
}
return result
}
// ggml_can_mul_mat
func CanMulMat(t0, t1 *Tensor) bool {
return (t0.NE[0] == t1.NE[0]) && (t0.NE[2] == t1.NE[2]) && (t0.NE[3] == t1.NE[3])
}
// ggml_mul_mat
func MulMat(ctx *Context, a, b *Tensor) *Tensor {
////ASSERT(ggml_can_mul_mat(a, b));
////GGML_ASSERT(!ggml_is_transposed(a));
isNode := false
if a.grad != nil || b.grad != nil {
isNode = true
}
result := NewTensor(ctx, TYPE_F32, min32(a.Dims, b.Dims), a.NE[1], b.NE[1], a.NE[2], b.NE[3], nil) // Reusable OK
result.op = OP_MUL_MAT
result.src0 = a
result.src1 = b
if isNode {
result.grad = DupTensor(ctx, result)
} else {
result.grad = nil
}
return result
}
// ggml_add
func AddImpl(ctx *Context, a, b *Tensor, inplace bool) *Tensor {
////ASSERT(ggml_are_same_shape(a, b));
//bool is_node = false;
////if (!inplace && (a.grad || b.grad)) {
////is_node = true;
////}
////struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
var result *Tensor
if inplace {
result = ViewTensor(ctx, a)
} else {
result = DupTensor(ctx, a)
}
result.op = OP_ADD
////result.grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result.grad = nil
result.src0 = a
result.src1 = b
return result
}
func Add(ctx *Context, a, b *Tensor) *Tensor {
return AddImpl(ctx, a, b, false)
}
func AddInplace(ctx *Context, a, b *Tensor) *Tensor {
return AddImpl(ctx, a, b, true)
}
// ggml_sum
func Sum(ctx *Context, a *Tensor) *Tensor {
isNode := false
if a.grad != nil {
isNode = true
}
result := NewTensor1D(ctx, a.Type, 1) // Reusable OK
result.op = OP_SUM
result.src0 = a
result.src1 = nil
if isNode {
result.grad = DupTensor(ctx, result)
} else {
result.grad = nil
}
return result
}
// ggml_sub
func SubImpl(ctx *Context, a, b *Tensor, inplace bool) *Tensor {
////ASSERT(ggml_are_same_shape(a, b));
////bool is_node = false;
////if (!inplace && (a.grad || b.grad)) {
////is_node = true;
////}
var result *Tensor
if inplace {
result = ViewTensor(ctx, a)
} else {
result = DupTensor(ctx, a)
}
result.op = OP_SUB
////result.grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result.grad = nil
result.src0 = a
result.src1 = b
return result
}
func Sub(ctx *Context, a, b *Tensor) *Tensor {
return SubImpl(ctx, a, b, false)
}
func SubInplace(ctx *Context, a, b *Tensor) *Tensor {
return SubImpl(ctx, a, b, true)
}
// ggml_div
func DivImpl(ctx *Context, a, b *Tensor, inplace bool) *Tensor {
////ASSERT(ggml_are_same_shape(a, b));
////bool is_node = false;
////if (!inplace && (a->grad || b->grad)) {
////is_node = true;
////}
////if (inplace) {
////ASSERT(is_node == false);
////}
var result *Tensor
if inplace {
result = ViewTensor(ctx, a)
} else {
result = DupTensor(ctx, a)
}
result.op = OP_DIV
////result->grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result.grad = nil
result.src0 = a
result.src1 = b
return result
}
func Div(ctx *Context, a, b *Tensor) *Tensor {
return DivImpl(ctx, a, b, false)
}
func DivInplace(ctx *Context, a, b *Tensor, inplace bool) *Tensor {
return DivImpl(ctx, a, b, true)
}
// ggml_sgn
func SgnImpl(ctx *Context, a *Tensor, inplace bool) *Tensor {
isNode := false
if !inplace && a.grad != nil {
isNode = true
}
var result *Tensor
if inplace {
result = ViewTensor(ctx, a)
} else {
result = DupTensor(ctx, a)
}
result.op = OP_SGN
result.src0 = a
result.src1 = nil
if isNode {
result.grad = DupTensor(ctx, result)
} else {
result.grad = nil
}
return result
}
func Sgn(ctx *Context, a *Tensor) *Tensor {
return SgnImpl(ctx, a, false)
}
func SgnInplace(ctx *Context, a *Tensor) *Tensor {
return SgnImpl(ctx, a, true)
}
// struct ggml_tensor * Repeat(
func Repeat(ctx *Context, a, b *Tensor) *Tensor {
////ASSERT(ggml_can_repeat(a, b));
isNode := false
if a.grad != nil {
isNode = true
}
if AreSameShape(a, b) && !isNode {
return a
}
result := NewTensor(ctx, a.Type, b.Dims, b.NE[0], b.NE[1], b.NE[2], b.NE[3], nil) // Reusable OK
result.op = OP_REPEAT
result.src0 = a
result.src1 = b
if isNode {
result.grad = DupTensor(ctx, result)
} else {
result.grad = nil
}
return result
}
func IsScalar(tensor *Tensor) bool {
return tensor.NE[0] == 1 && tensor.NE[1] == 1 && tensor.NE[2] == 1 && tensor.NE[3] == 1
}
func IsVector(tensor *Tensor) bool {
return tensor.NE[1] == 1 && tensor.NE[2] == 1 && tensor.NE[3] == 1
}
func IsMatrix(tensor *Tensor) bool {
return tensor.NE[2] == 1 && tensor.NE[3] == 1
}
// ggml_get_rows
func GetRows(ctx *Context, a, b *Tensor) *Tensor {
////ASSERT(ggml_is_matrix(a) && ggml_is_vector(b) && b.type == TYPE_I32);
//if !IsMatrix(a) || !IsVector(b) /* || b.Type != TYPE_I32 */ {
// fmt.Printf("\n[ERROR] GetRows fail basic assertions")
// os.Exit(1)
//}
isNode := false
if a.grad != nil || b.grad != nil {
////ASSERT(false); // TODO: implement backward
isNode = true
fmt.Printf("\n[STOP] ml.GetRows")
os.Exit(1)
}
result := NewTensor2D(ctx, TYPE_F32, a.NE[0], b.NE[0]) // Reusable OK
result.op = OP_GET_ROWS
if isNode {
result.grad = DupTensor(ctx, result)
} else {
result.grad = nil
}
result.src0 = a
result.src1 = b
return result
}
func RMSNorm(ctx *Context, a *Tensor) *Tensor {
return RMSNormImpl(ctx, a, false)
}
func RMSNormInplace(ctx *Context, a *Tensor) *Tensor {
return RMSNormImpl(ctx, a, true)
}
// ggml_rms_norm_impl
func RMSNormImpl(ctx *Context, a *Tensor, inplace bool) *Tensor {
isNode := false
if !inplace && a.grad != nil {
////ASSERT(false); // TODO: implement backward
isNode = true
fmt.Printf("\n[STOP] ml.GetRows")
os.Exit(1)
}
////struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
var result *Tensor
if inplace {
result = ViewTensor(ctx, a)
} else {
result = DupTensor(ctx, a)
}
result.op = OP_RMS_NORM
result.src0 = a
result.src1 = nil // TODO: maybe store epsilon here?
if isNode {
result.grad = DupTensor(ctx, result)
} else {
result.grad = nil
}
return result
}
// ggml_view_1d
// NB! Originally offset in bytes, but here in floats (4-bytes)
func View1D(ctx *Context, a *Tensor, ne0 uint32, offset uint32) *Tensor {
////if a.grad != nil {
//// ////ASSERT(false); // gradient propagation is not supported
//// fmt.Printf("\n[STOP] View1D : gradient propagation is not supported")
//// os.Exit(1)
////}
slice := a.Data[offset:]
result := NewTensor(ctx, a.Type, 1, ne0, 1, 1, 1, slice)
result.op = OP_VIEW
result.grad = nil
result.src0 = a
result.src1 = nil // TODO: maybe store the offset here?
return result
}
// ggml_build_forward_impl
func BuildForwardImpl(graph *Graph, tensor *Tensor, expand bool) {
if !expand {
graph.NodesCount = 0
graph.LeafsCount = 0
}
n0 := graph.NodesCount
VisitParents(graph, tensor)
n_new := graph.NodesCount - n0
if n_new > 0 {
// the last added node should always be starting point
////ASSERT(cgraph.nodes[cgraph.n_nodes - 1] == tensor);
if !(graph.Nodes[graph.NodesCount-1] == tensor) {
fmt.Printf("\n[STOP] BuildForwardImpl : the last added node should always be starting point!")
os.Exit(1)
}
}
}
// ggml_build_forward_expand
func BuildForwardExpand(graph *Graph, tensor *Tensor) {
BuildForwardImpl(graph, tensor, true)
}
// ggml_visit_parents
func VisitParents(graph *Graph, node *Tensor) {
if node.grad == nil {
// this usually happens when we generate intermediate nodes from constants in the backward pass
// it can also happen during forward pass, if the user performs computations with constants
if node.op != OP_NONE {
//PRINT_DEBUG("%s: warning: node %p has no grad, but op %d\n", __func__, (void *) node, node.op);
}
}
// check if already visited
for i := uint32(0); i < graph.NodesCount; i++ {
if graph.Nodes[i] == node {
return
}
}
for i := uint32(0); i < graph.LeafsCount; i++ {
if graph.Leafs[i] == node {
return
}
}
if node.src0 != nil {
VisitParents(graph, node.src0)
}
if node.src1 != nil {
VisitParents(graph, node.src1)
}
for i := 0; i < MAX_OPT; i++ {
if node.opt[i] != nil {
VisitParents(graph, node.opt[i])
}
}
if node.op == OP_NONE && node.grad == nil {
// reached a leaf node, not part of the gradient graph (e.g. a constant)
////ASSERT(cgraph.n_leafs < MAX_NODES);
graph.Leafs[graph.LeafsCount] = node
graph.LeafsCount++
} else {
////ASSERT(cgraph.n_nodes < MAX_NODES);
graph.Nodes[graph.NodesCount] = node
graph.Grads[graph.NodesCount] = node.grad
graph.NodesCount++
}
}
// ggml_cpy
func CopyImpl(ctx *Context, a, b *Tensor, inplace bool) *Tensor {
////ASSERT(ggml_nelements(a) == ggml_nelements(b));
//if a.Nelements() != b.Nelements() {
// fmt.Printf("\n[HALT] Copy tensors of different dimensions!")
// os.Exit(1)
//}
isNode := false
if !inplace && (a.grad != nil || b.grad != nil) {
////ASSERT(false); // TODO: implement backward
isNode = true
fmt.Printf("\n[STOP] cpyImpl")
os.Exit(1)
}
// make a view of the destination
result := ViewTensor(ctx, b)
result.op = OP_CPY
result.src0 = a
result.src1 = b
if isNode {
result.grad = DupTensor(ctx, result)
} else {
result.grad = nil
}
return result
}
func Copy(ctx *Context, a, b *Tensor) *Tensor {
return CopyImpl(ctx, a, b, false)
}
func CopyInplace(ctx *Context, a, b *Tensor) *Tensor {
return CopyImpl(ctx, a, b, true)
}
// ggml_new_tensor_1d
func NewTensor1D(ctx *Context, dt DType, ne0 uint32) *Tensor {
return NewTensor(ctx, dt, 1, ne0, 1, 1, 1, nil)
}
// ggml_new_tensor_2d
func NewTensor2D(ctx *Context, dt DType, ne0, ne1 uint32) *Tensor {
return NewTensor(ctx, dt, 2, ne0, ne1, 1, 1, nil)
}
func NewTensor3D(ctx *Context, dt DType, ne0, ne1, ne2 uint32) *Tensor {
return NewTensor(ctx, dt, 3, ne0, ne1, ne2, 1, nil)
}
func NewTensor4D(ctx *Context, dt DType, ne0, ne1, ne2, ne3 uint32) *Tensor {
return NewTensor(ctx, dt, 4, ne0, ne1, ne2, ne3, nil)
}
// ggml_new_tensor_impl
func NewTensor(ctx *Context, dt DType, dims uint32, ne0, ne1, ne2, ne3 uint32, data []float32) *Tensor {
// TODO: Check allowed data types on graph creation
//if dt != TYPE_F32 && dt != TYPE_I32 {
// fmt.Printf("\n[ERROR] NewTensorImpl got not supported type : %d", dt)
// os.Exit(1)
//}
////ggml_assert_aligned(result);
if data == nil {
total := ne0 * ne1 * ne2 * ne3
data = make([]float32, total, total)
}
return &Tensor{
Type: dt,
Dims: dims,
NE: [4]uint32{ne0, ne1, ne2, ne3},
NB: [4]uint32{4, ne0 * 4, ne0 * ne1 * 4, ne0 * ne1 * ne2 * 4},
op: OP_NONE,
Data: data,
}
}
// ggml_permute
func Permute(ctx *Context, a *Tensor, axis0, axis1, axis2, axis3 uint32) *Tensor {
////ASSERT(axis0 >= 0 && axis0 < MAX_DIMS);
////ASSERT(axis1 >= 0 && axis1 < MAX_DIMS);
////ASSERT(axis2 >= 0 && axis2 < MAX_DIMS);
////ASSERT(axis3 >= 0 && axis3 < MAX_DIMS);
////ASSERT(axis0 != axis1);
////ASSERT(axis0 != axis2);
////ASSERT(axis0 != axis3);
////ASSERT(axis1 != axis2);
////ASSERT(axis1 != axis3);
////ASSERT(axis2 != axis3);
isNode := false
if a.grad != nil {
////ASSERT(false); // TODO: implement backward
isNode = true
fmt.Printf("\n[STOP] Permute error")
os.Exit(1)
}
result := ViewTensor(ctx, a)
var ne [MAX_DIMS]uint32
var nb [MAX_DIMS]uint32
ne[axis0] = a.NE[0]
ne[axis1] = a.NE[1]
ne[axis2] = a.NE[2]
ne[axis3] = a.NE[3]
nb[axis0] = a.NB[0]
nb[axis1] = a.NB[1]
nb[axis2] = a.NB[2]
nb[axis3] = a.NB[3]
result.NE[0] = ne[0]
result.NE[1] = ne[1]
result.NE[2] = ne[2]
result.NE[3] = ne[3]
result.NB[0] = nb[0]
result.NB[1] = nb[1]
result.NB[2] = nb[2]
result.NB[3] = nb[3]
result.op = OP_PERMUTE
result.src0 = a
result.src1 = nil // TODO: maybe store the permutation here?
if isNode {
result.grad = DupTensor(ctx, result)
} else {
result.grad = nil
}
return result
}
// ggml_rope
func Rope(ctx *Context, a *Tensor, past, dims, mode uint32) *Tensor {
////ASSERT(n_past >= 0);
isNode := false
if a.grad != nil {
////ASSERT(false); // TODO: implement backward
isNode = true
fmt.Printf("\n[STOP] Rope error")
os.Exit(1)
}
// TODO: when implement backward, fix this:
//struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
result := ViewTensor(ctx, a)
b := NewTensor1D(ctx, TYPE_I32, 3)
b.Data[0] = float32(past)
b.Data[1] = float32(dims)
b.Data[2] = float32(mode)
result.op = OP_ROPE
result.src0 = a
result.src1 = b
if isNode {
result.grad = DupTensor(ctx, result)
} else {
result.grad = nil
}
return result
}
func Reshape3D(ctx *Context, a *Tensor, ne0, ne1, ne2 uint32) *Tensor {
////ASSERT(ggml_is_contiguous(a));
////ASSERT(ggml_nelements(a) == ne0*ne1*ne2);
//if !a.IsContiguous() {
// fmt.Printf("\n[STOP] Reshape3D : tensor is NOT contiguous!")
// os.Exit(1)
//}
//if a.Nelements() != ne0*ne1*ne2 {
// fmt.Printf("\n[STOP] Reshape3D : different elements number!")
// os.Exit(1)
//}
////bool is_node = false;
////if (a.grad) {
//// //// ASSERT(false); // TODO: implement backward
//// is_node = true;
////}
result := NewTensor(ctx, a.Type, 3, ne0, ne1, ne2, 1, a.Data) // Reusable OK
result.op = OP_RESHAPE
////result.grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result.grad = nil
result.src0 = a
result.src1 = nil
return result
}
// ggml_new_f32
func NewFP32(ctx *Context, value float32) *Tensor {
result := NewTensor1D(ctx, TYPE_F32, 1) // Reusable OK
SetFP32(result, value)
return result
}
// ggml_set_f32
func SetFP32(tensor *Tensor, value float32) *Tensor {
// FIXME Optimize with mem zeroing
n := tensor.Nelements()
for i := uint32(0); i < n; i++ {
////ggml_vec_set_f32(nc, (float *)(data + i*n1), value);
tensor.Data[i] = value
}
return tensor
}
// ggml_scale
func ScaleImpl(ctx *Context, a, b *Tensor, inplace bool) *Tensor {
////ASSERT(ggml_is_scalar(b));
////ASSERT(ggml_is_padded_1d(a));
////bool is_node = false;
if !inplace && (a.grad != nil || b.grad != nil) {
////ASSERT(false); // TODO: implement backward
////is_node = true;
fmt.Printf("\n[STOP] ScaleImpl : assertion failed")
os.Exit(1)
}
// TODO: when implement backward, fix this:
//struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
result := ViewTensor(ctx, a)
result.op = OP_SCALE
////result.grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result.grad = nil
result.src0 = a
result.src1 = b
return result
}
func Scale(ctx *Context, a, b *Tensor) *Tensor {
return ScaleImpl(ctx, a, b, false)
}
func ScaleInplace(ctx *Context, a, b *Tensor) *Tensor {
return ScaleImpl(ctx, a, b, true)
}
// ggml_diag_mask_inf
func DiagMaskInf(ctx *Context, a *Tensor, past uint32) *Tensor {
////bool is_node = false;
if a.grad != nil {
////ASSERT(false); // TODO: implement backward
////is_node = true;
fmt.Printf("\n[STOP] DiagMaskInf : assertion failed")
os.Exit(1)
}
// TODO: when implement backward, fix this:
//struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
result := ViewTensor(ctx, a)
b := NewFP32(ctx, float32(past)) // FIXME NewI32(ctx, past)
result.op = OP_DIAG_MASK_INF
////result.grad = is_node ? ggml_dup_tensor(ctx, result) : NULL;
result.grad = nil
result.src0 = a
result.src1 = b
return result
}
// ggml_soft_max
func SoftMax(ctx *Context, a *Tensor) *Tensor {
////bool is_node = false;
if a.grad != nil {
////ASSERT(false); // TODO: implement backward
////is_node = true;
fmt.Printf("\n[STOP] SoftMax : assertion failed")
os.Exit(1)