-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsdm.clj
2198 lines (1971 loc) · 72.5 KB
/
sdm.clj
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
(ns bennischwerdtner.sdm.sdm
(:require
[bennischwerdtner.pyutils :as pyutils :refer
[*torch-device*]]
[bennischwerdtner.hd.binary-sparse-segmented :as hd]
[tech.v3.datatype.functional :as f]
[tech.v3.tensor :as dtt]
[fastmath.random :as fm.rand]
[libpython-clj2.require :refer [require-python]]
[libpython-clj2.python :refer [py. py..] :as py]))
;;
;; This is a sparse distributed memory for binary sparse segmented hypervectors
;;
;;
;;
;; Adapted from Kanerva 1993[1]:
;; And mapping to neuroanatomy of cerebellum
;;
;;
;;
;; ADDRESS REGISTER WORD IN REGISTER
;;
;; N = 10.000 U = N = 10.000
;; +--------------+ +------------------+
;; x | | w | 1 |1 | 1 | | (sparse, segmented)
;; +------+-------+ +----------+-------+
;; | |
;; | |
;; | N d y | U
;; +------v-------+ +-+ +-+ +----------v-------+
;; | | |3| |1+----> |
;; | | |0| |0| | |
;; | A +--> |2| ---------> |1|----> C |
;; | M hard addr. | |0| threshold |0| | M x U counters |
;; M | | |1| |0| M | |
;; +--------------+ +-+ +-+ +---------+--------+
;; |
;; | |
;; | | v
;; | | +-----------------+
;; | | S | | sums
;; v | +--+-----+----+---+
;; address overlap | | | |
;; ~d of [1,2] | | | |
;; | v v v (where S >= read-threshold)
;; activations <----+ --+-----+----+----
;; ( 2 <= d) v v v top-k per segment
;; +-----+----+------+
;; z | | | |
;; +-----+----+------+
;; s1 s2, ... segment-count
;;
;;
;; word out register
;;
;; 10.000 bits = segment-count * segment-length
;;
;;
;;
;; x - address word 'mossy fiber input'
;; A - Address Matrix 'mossy fibers -> granule cells synapses'
;; M - hard-locations-count 'granule cell count'
;; y - address-activations 'granule cell activations'
;; w - input word 'climbing fiber input'
;; C - Content Matrix 'parallel fibers -> purkinje synapses'
;; S - content sums 'purkinje inputs'
;; z - output word 'purkinje activations', or downstream purkinje reader
;;
;; -----------------
;; Address decoder
;; -----------------
;;
;; - M hard address locations of N (address-word-lenght) width
;; - address locations are sparse 0s and 1s with address-density << 1
;; - Each address location models one granule cell, granule cells outnumber mossy fibers (their inputs) 200 to 1
;; (https://en.wikipedia.org/wiki/Cerebellar_granule_cell#:~:text=Granule%20cells%20receive%20all%20of,a%20much%20more%20expansive%20way.)
;;
;;
;; Since addreses are not dense, this is a 'intermediate design' (Jaeckel, L.A. 1989b)
;;
;; Address Decoding
;; -----------------
;; - let `address` (query) be `x`
;; - find the overlap for each row in `A`, that is a vector of overlaps `d` (~ golgi inputs)
;; - cutoff with `decoder-threshold` (e.g. decoder-threshold = 2),
;; - this is the address location activation vector `y`
;; - this is a tensor of size [M], with a tiny fraction non zero, e.g. 36 out of 10.000
;; - (y ~= golgi cell activations)
;; - subsequently, either read or write using active locations.
;;
;; In the address decoder step, we massively benefit from parallelism.
;;
;; -----------------
;; Storage / Content Matrix `C`
;; -----------------
;;
;; - M x U counters
;; - here, U == N, allowing for auto association. I.e. address-word == input-word.
;; - Different from Kanerva 1993, where each location is in range {-15...15},
;; here range is {0..`counter-max`}, counter-max = 100 (?)
;;
;; Read (y):
;; - sum up counters of the y activated address content locations of `C`, sums `S` ~ purkinje inputs.
;; - Optionally (not here): Remove sums below read-threshold, reducing noise, trading signal strenght. In other words, this increases
;; the count and strength of address locations for a stored word `a` to be retrieved.
;; - The bit count active is a meassure of the `confidence` for the query relating to a stored word.
;; - In Kanerva 1993: take the sign of the sums, output vector `z` elements are in {-1,1}
;; - Here, take top-k (`read-k`) non zero bits for each word segment, to accomodate a binary segmented sparse design.
;; - output vector `z` (size N), has read-k * segment-count non zero bits, `z` elements are in {0,1}, where the count of non-zero is << N
;; - iff `read-k` == 1, then `z` is maximally sparse [[hd/maximally-sparse?]]
;;
;;
;;
;; Write (y, input-word):
;;
;; - For each active location, increment the in C where input-word has a non-zero bit
;; - clamp C to the counter range
;; - this is flipped from cerebellum where mossy fiber + parallel fiber input makes LTD on the synapse (i.e. it decrements the weight),
;; presumably, this flips back by the purkinje being inhibitory.
;; The reason for this flipped arrangement remains elusive.
;; The answer lies with the microcircuits of purkinje readers in deep cerebellar nuclei.
;; Presumably, you would find a reason for inhibitory inputs to be more useful.
;;
;; ========================
;; Parameters
;; M - memory count (e.g. 1e6)
;; T - (data set) should be 1-5% of M
;; p - probability of activation, ideally p = 0.000368 (depends on M and T)
;; This is important, number of hard locations activated for an input
;; The best p maximizes signal to noise, is approx. 2MT^-1/3
;;
;;
(comment
;; what is p?
;; depends on the M the hard locations count,
;; density of the address matrix
;; density of address words
;; and decoder threshold
;;
(require-python '[numpy.random :as nprandom])
(defn calculate-activation-probability [address-word-length address-density word-density decoder-threshold num-samples]
(let [p-match (* address-density word-density)
samples (nprandom/binomial address-word-length p-match num-samples)]
(float (/ (np/sum (np/greater_equal samples decoder-threshold)) num-samples))))
(defn ideal-p [dataset-count address-count]
(Math/pow (* 2 dataset-count address-count) (- (/ 1 3))))
(ideal-p 1e3 1e6)
;; 0.003872
;; for
;; T = 1.000
;; M = 10.000
;; address density = 0.0009, decoder threshold = 2
;; seem to be in a good balpark
;; (unless the calculation is wrong)
;; ==>
;; One can simply setup an address decoder and empircally play until one finds a good config
;; where good means the address-locations decoded are roughly p = (address-locations / M) = idea-p = 2MT^-1/3
;;
;;
;; I do this by playing around with such numbers:
;;
(torch/sum
(decode-address (->decoder-coo
{:address-count (long 1e6)
:address-density 0.00001
:word-length (long 1e4)})
(hd/->hv)
1))
;; tensor(187, device='cuda:0')
;; (/ 200 1e6)
;; 2.0E-4
;; (ideal-p 1e3 1e6)
;; 7.937005259841001E-4
(torch/sum
(decode-address
(->decoder-coo
{:address-count (long 1e5)
:address-density 0.002
:word-length (long 1e4)})
(hd/->hv)
2))
(torch/sum
(decode-address (->decoder-coo
{:address-count (long 1e6)
:address-density 0.000003
:word-length (long 1e4)})
(hd/->seed)
1))
(py..
(torch/sum
(decode-address
(->decoder-coo {:address-count (long 1e6)
:address-density 0.0005
:word-length (long 1e4)})
(hd/->hv)
3))
item)
(py..
(torch/sum
(decode-address
(->decoder-coo
{:address-count (long 1e6)
:address-density 0.00003
:word-length (long 1e4)})
(hd/drop (hd/->hv) 0.5)
1))
item)
(float (/ (py.. (torch/sum (decode-address
(->decoder-coo
{:address-count (long 1e6)
:address-density 0.000006
:word-length (long 1e4)})
(hd/->hv)
1))
item)
10))
(float
(/ (py.. (torch/sum (decode-address
(->decoder-coo
{:address-count (long 1e5)
:address-density 0.0026
:k-delays 3
:word-length (long 1e4)})
(hd/->hv)
2))
item)
3))
41.0
(/ (long 1e5)))
;; ----------------------
;; Concrete torch implementation
;; ----------------------
;;
;; The following are 2 concrete implementations of the SDM.
;;
;; The first is a dense implementation, where the programatic structure is hopefully easier to follow.
;;
;; The second is a torch.sparse 'coo' implementation, where the semantic is supposed to be the same.
;;
(do
;;
;; Anything backed by a :native-buffer has a zero
;; copy pathway to and from numpy.
;; Https://clj-python.github.io/libpython-clj/Usage.html
(alter-var-root #'hd/default-opts
(fn [m]
(assoc m
:tensor-opts {:container-type
:native-heap})))
(require-python '[numpy :as np])
(require-python '[torch :as torch])
(require-python '[torch.sparse :as torch.sparse])
(require '[libpython-clj2.python.np-array]))
(def counter-max 15)
;; https://pytorch.org/docs/stable/sparse.html#sparse-csr-tensor
;; The primary advantage of the CSR format over the COO format is better use of storage and much faster computation operations such as sparse matrix-vector multiplication using MKL and MAGMA backends.
;; (I ended up using coo at the moment. It was easier to create and use tensors).
;;
(defn ->address-matrix
[address-count address-length density]
(py.. (torch/less (torch/rand [address-count
address-length]
:device
*torch-device*)
density)
(to torch/float16)))
;; kinda funny that many rows are never activated
;; in lieu of the amount of granule cells, you can wonder
;;
;; outcome here has less density than advertised because random indices overlap
;;
(defn ->address-matrix-coo
[address-count word-length density]
(let [nse (long (* address-count word-length density))
row-indices (torch/randint 0
address-count
[nse]
:device
*torch-device*)
col-indices (torch/randint 0
word-length
[nse]
:device
*torch-device*)
i (torch/stack [row-indices col-indices])
v (torch/ones [nse]
:dtype torch/float32
:device *torch-device*)
A (py.. (torch/sparse_coo_tensor i
v
:size
[address-count
word-length])
(coalesce))
_ (py.. A (values) (clamp_ 0 1))]
A))
(defn ->address-locations
[address-count indices]
(py/set-item! (torch/zeros [address-count]
:dtype torch/bool
:device *torch-device*)
indices
true))
(comment
(->address-locations 10 (torch/tensor [1 2 3] :dtype torch/long :device *torch-device*)))
(defn ->content-matrix
[address-count word-length]
(torch/zeros [address-count word-length]
:device
*torch-device*))
(defn ->content-matrix-coo
[address-count word-length]
(torch/sparse_coo_tensor :size [address-count word-length]
:device *torch-device*
:dtype torch/uint8))
;; -----------------------------
;; Address Decoding
;; -----------------------------
;;
;; ADDRESS REGISTER
;;
;; N = 10.000
;; +--------------+
;; x | |
;; +------+-------+
;; |
;; |
;; | N d y
;; +------v-------+ +-+ +-+
;; | | |3| |1+
;; | | |0| |0|
;; | A +--> |2| ---------> |1|
;; | M hard addr. | |0| threshold |0|
;; M | | |1| |0|
;; +--------------+ +-+ +-+
;;
;; |
;; | |
;; | |
;; | |
;; v |
;; address overlap |
;; ~d of [1,2] |
;; |
;; activations <----+
;; ( 2 <= d)
;;
;;
;;
(defn decode-addresses
[address-matrix address decoder-threshold]
;; d
(let [address (py.. (pyutils/ensure-torch address)
(to :dtype torch/float16))
inputs (torch/mv address-matrix address)
activations (torch/ge inputs decoder-threshold)]
;; y
activations))
(defn decode-addresses-coo
[address-matrix address decoder-threshold]
(let [address (py.. (pyutils/ensure-torch address)
(to :dtype torch/float32))
N (py.. address-matrix (size 1))
addresses (py.. address (view -1 N))
out (torch/zeros [(py.. addresses (size 0))
(py.. address-matrix (size 0))]
:dtype torch/bool
:device *torch-device*)]
(py/with-gil-stack-rc-context
(let [inputs (torch/stack
;; sparse coo doesn't have a batch
;; mv
(into []
(for [adr addresses]
(torch/mv address-matrix
adr))))
activations (torch/ge inputs decoder-threshold)]
(py.. out (copy_ activations))
out))))
(comment
(decode-addresses-coo address-matrix address decoder-threshold)
(decode-addresses (->address-matrix 3 3 0)
(torch/tensor [0 1 1]
:dtype torch/float16
:device *torch-device*)
1)
(decode-addresses-coo (->address-matrix-coo 3 3 0)
(torch/tensor [0 1 1]
:dtype torch/float32
:device
*torch-device*)
1)
(decode-addresses-coo (->address-matrix-coo 3 3 0.5)
(torch/tensor [0 1 1]
:dtype torch/float
:device
*torch-device*)
1)
(py.. (torch/tensor [0 1 1]
:dtype torch/float
:device *torch-device*)
-dtype))
;; ---------------------------------
;; Write
;; ---------------------------------
;;
;; WORD IN REGISTER
;;
;; U = N = 10.000
;; +------------------+
;; w | 1 |1 | 1 | | (sparse, segmented)
;; +----------+-------+
;; |
;; |
;; y | U
;; +-+ +----------v-------+
;; |1+----> +1 |
;; |0| | |
;; |1|----> C |
;; |0| | M x U counters |
;; |0| M | |
;; +-+ +------------------+
;;
;; - increment where input and address activations meet
;; - clamp to [[counter-max]]
(defn write!
[content-matrix address-locations input-word]
(let [input-word (pyutils/ensure-torch input-word)]
(py/set-item! content-matrix
address-locations
(py.. (py/get-item content-matrix
address-locations)
(add_ input-word)
(clamp_ :min 0 :max counter-max)))))
;; ---
;; I can implement a batch version, writing the content matrix is synchronized at the moment,
;; makes sense because we clamp the matrix every write, but we don't need to.
;; We could write a batch and clamp in the end.
;; Will need to think about overflow for a moment though.
;; ---
(defn write-coo!
"Has broadcast semantics for `input-word`."
[content-matrix address-locations input-word]
(let [address-locations (pyutils/ensure-torch
address-locations)
input-word (pyutils/ensure-torch input-word)]
(py/with-gil-stack-rc-context
(let [[M U] (into [] (py.. content-matrix (size)))
address-locations-1 (py.. address-locations
(view -1 M))
batch-size (py.. address-locations-1 (size 0))
input-word (torch/broadcast_to input-word
[batch-size U])]
(doseq [batch-idx (range batch-size)]
(let [address-locations-1 (py/get-item
address-locations-1
batch-idx)
input-word (py/get-item input-word
batch-idx)
;; -----------------------------------
;; makes a host-device synchronization
;; ----------------------------------
activated-locations
(py.. (torch/nonzero address-locations-1)
(view -1))
word-nonzero (py.. (torch/nonzero
input-word)
(view -1))
indices (py.. (torch/cartesian_prod
activated-locations
word-nonzero)
(t))
values (torch/ones (py.. indices (size 1))
:dtype torch/uint8
:device *torch-device*)
update (torch/sparse_coo_tensor indices
values
[M U])]
(py.. content-matrix (add_ update))))
(py.. content-matrix
(coalesce)
values
(clamp_ 0 counter-max))
content-matrix))))
;; --------------------------------------
(defn read-coo-1
"
Returns the `sums` for each counter column in `content-matrix`,
selecting the activated `address-locations` rows.
+---+
| | address-locations
+-+---+------------------+ |
-> | | 2 | | on |
+-+---+------------------+ |
| | | | off |
+-+---+------------------+ |
-> | | 8 | | on v
+-+---+------------------+ ...
| |
++--+ ... C address-count x word-length
|
| ^
| +---------------------- activated counters
|
|
|
|
v
+------+-------------------+
S | 10 | 0 11 , .... | sums size [word-lenght]
+------+-------------------+
per columm
"
[content-matrix address-locations]
;; (1000 times write and read)
;; "Elapsed time: 3649.408776 msecs"
;; (let
;; [mask (py.. address-locations (float))]
;; (torch/matmul mask (py.. content-matrix
;; (float))))
;; "Elapsed time: 3010.933935 msecs"
(let [addr-indices (torch/squeeze (torch/nonzero
address-locations)
1)
sums (py.. (torch/sum (torch/index_select
content-matrix
0
addr-indices)
0)
(to_dense))]
sums))
(defn ensure-cpu [tens]
(py.. tens (to "cpu")))
(defn torch->numpy [tens]
(py.. tens (numpy)))
(defn torch->jvm
[torch-tensor]
(-> torch-tensor
ensure-cpu
torch->numpy
dtt/ensure-tensor))
(defn ensure-jvm [tens]
(if (dtt/tensor? tens)
tens
(torch->jvm tens)))
(defn sdm-read-coo
"Returns a lookup result for the address-actions `address-locations`, and a confidence value.
`result`: A binary segmented hypervector reading from `address-locations`.
`confidence`: The normalized sum of storage counters that contribute to the result.
This repesents an approximation of the confidence of the result being an item in memory.
If `top-k` > 1 this would increase accordingly.
This can exceed 1, if counter locations are higher than 1, then an item was stored multiple times.
If close to one, the confidence is high. If close to zero, the confidence is low.
`top-k`: number of non zero bits to take from each segment.
If `top-k` == 1, the output is usually maximally sparse.
y - address activations
+--+ +---+----------------------+
| +------->| | |
| | +---+----------------------+
| | | | |
| | | | |
| | | | |
| | | | C |
| | | | |
+--+ +---+----------------------+
y s0| s1 , ... segment-count
|
| SUM
|
v
+-------+------+-----------+
| s0 | | |
+-------+------+-----------+
segment1, ....
top-k per segment s0,s1,... the summed counter 'winning' values for each segment.
The bit counter content amount contributing to the result is a confidence meassure.
|
|
v
+--------------------------+
| |
+--------------------------+
output hdv
top-k non zero bits per segment
See [[hd/maximally-sparse?]].
"
([content-matrix address-locations top-k]
(sdm-read-coo content-matrix
address-locations
top-k
hd/default-opts))
([content-matrix address-locations top-k
{:bsdc-seg/keys [segment-count segment-length N]}]
(let [[M U] (into [] (py.. content-matrix (size)))
address-locations (py.. address-locations
(view -1 M))
batch-size (py.. address-locations (size 0))
outcomes
(doall
(for [batch-idx (range batch-size)]
(let [out (torch/zeros [N]
:device
*torch-device*)
address-locations (py/get-item
address-locations
batch-idx)]
;; you must be careful to not let
;; python objects escape the
;; rc-context, this is the reason why
;; we do this datatransfer at the end,
;; (it's a very fast operation
;; gpu->gpu)
(py/with-gil-stack-rc-context
(let [s (read-coo-1 content-matrix
address-locations)
topk-result
(-> s
(torch/reshape
[segment-count
segment-length])
(torch/topk
(min top-k
segment-length)))
result
(torch/scatter
(torch/zeros [segment-count
segment-length]
:device
*torch-device*)
1
(py.. topk-result -indices)
1)
address-location-count
(do (def the-addr-locations
address-locations)
(py.. (torch/sum
address-locations)
item))]
{:address-location-count
address-location-count
:confidence
(if (zero? address-location-count)
0
(py..
(torch/div
(torch/sum (py.. topk-result
-values))
;; also divide by top-k?
;;
;; scaling this with the
;; address-locations
;; count is probably
;; taste. It turns out
;; to say high
;; confidence, if the
;; count of address is
;; low, when the address
;; is a
;; 'weak' (sub sparsity)
;; hypervector. The
;; caller would have to
;; take this into
;; account themselves.
;;
(* segment-count
address-location-count))
item))
:result (do
;; you don't need to
;; synchronize cuda here
;; apparently
(py.. out
(copy_ (torch/reshape
result
[N])))
out)})))))]
(if (= 1 batch-size)
(first outcomes)
(into [] outcomes)))))
(defn sdm-read
"See [[sdm-read-coo]]"
([content-matrix address-locations top-k]
(sdm-read content-matrix
address-locations
top-k
hd/default-opts))
([content-matrix address-locations top-k
{:bsdc-seg/keys [segment-count segment-length N]}]
(let [s (torch/sum (py/get-item content-matrix
address-locations)
:dim
0)
topk-result (-> s
(torch/reshape [segment-count
segment-length])
(torch/topk (min top-k
segment-length)))
result (torch/scatter (torch/zeros
[segment-count
segment-length]
:dtype torch/uint8
:device *torch-device*)
1
(py.. topk-result -indices)
1)
address-location-count (py.. (torch/nonzero
address-locations)
(size 0))]
{:address-location-count address-location-count
:confidence
(if (zero? address-location-count)
0
(py.. (torch/div
(torch/sum (py.. topk-result -values))
(* segment-count address-location-count))
item))
:result (torch/reshape result [N])})))
;; not sure yet
;; these interfaces are just exploratory here
(defprotocol AddressDecoder
(decode-address [this address decoder-threshold]))
(defprotocol SDMStorage
(lookup-1 [this address-locations top-k opts]
[this address-locations top-k])
(write-1 [this address-locations content])
(storage-decay [this drop-chance]))
(defprotocol SDM
(known? [this address]
[this address decoder-threshold])
(lookup [this address top-k]
[this address top-k decoder-threshold])
(converged-lookup [this address top-k]
[this address top-k decoder-threshold])
(write [this address content]
[this address content decoder-threshold])
(decay [this drop-chance]))
(defn ->decoder-coo
[{:keys [address-count word-length address-density]}]
(let [address-matrix (->address-matrix-coo
address-count
word-length
address-density)]
(reify
AddressDecoder
(decode-address [this address decoder-threshold]
(decode-addresses-coo address-matrix
address
decoder-threshold)))))
;;
;; 'dense' refers to the underlying torch backend
;; dense is easier to implement, serving as a reference implementation
;;
(defn dense-sdm
[{:keys [address-count word-length address-density]}]
(let [content-matrix (->content-matrix address-count
word-length)
address-matrix (->address-matrix address-count
word-length
address-density)]
(reify
AddressDecoder
(decode-address [this address decoder-threshold]
(decode-addresses address-matrix
address
decoder-threshold))
SDMStorage
(write-1 [this address-locations content]
(write! content-matrix address-locations content))
(lookup-1 [this address-locations top-k]
(sdm-read content-matrix address-locations top-k))
SDM
(write [this address content decoder-threshold]
(write-1
this
(decode-address this address decoder-threshold)
content))
(lookup [this address top-k decoder-threshold]
(lookup-1
this
(decode-address this address decoder-threshold)
top-k)))))
;; ----------------------------
;; Decay content
;; -----------------------------
;;
;; This is inspired by synapsembles
;; https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3005627/
;;
;; This way we can model temporary memory
;;
;; This effectively gives every synapse a life time
;; (in the aggregation of many content bits, one can calculate the half time)
;;
;; So you have a time-evolving variable or how that is called.
;;
(defn drop-random-indices-coo
[tensor drop-chance]
(let [tensor (py.. tensor (coalesce))
indices (py.. tensor indices)
indices-to-keep
(py.. (torch/nonzero (torch/ge
(torch/rand
[(py.. indices (size 1))]
:device
pyutils/*torch-device*)
drop-chance))
(view -1))
values (py.. tensor values)
new-indices
(torch/index_select indices 1 indices-to-keep)
new-values
(torch/index_select values 0 indices-to-keep)
new-tensor (torch/sparse_coo_tensor new-indices
new-values
(py.. tensor
(size)))]
;; (def new-tensor new-tensor)
new-tensor))
(comment
(torch/ge (torch/rand [10] :device pyutils/*torch-device*) 0.001))
(defn ->sdm-storage-coo
[{:keys [address-count word-length]}]
(let [content-matrix (atom (->content-matrix-coo
address-count
word-length))]
(reify
SDMStorage
(write-1 [this address-locations content]
(write-coo! @content-matrix
address-locations
content))
(lookup-1 [this address-locations top-k]
(sdm-read-coo @content-matrix
address-locations
top-k))
(lookup-1 [this address-locations top-k opts]
(sdm-read-coo @content-matrix
address-locations
top-k
opts))
(storage-decay [this drop-chance]
(swap! content-matrix drop-random-indices-coo
drop-chance)))))
;; Not yet figured out.
;; is the same as 'iterative' lookup
;; same for sequences and auto associative converge
(defn converged-lookup-impl
[sdm address
{:keys [stop? top-k decoder-threshold max-steps]}]
(reduce
(fn [{:as acc :keys [address result-xs]} n]
(let [next-outcome
(lookup sdm address top-k decoder-threshold)
{:keys [stop-reason success?]}
(stop? acc next-outcome)]
(if stop-reason
(cond (not success?) (ensure-reduced
(assoc acc
:stop-reason stop-reason
:stop-result
next-outcome))
success?
(ensure-reduced
(assoc acc
:result-xs (conj result-xs
next-outcome)
:success? true
:stop-reason stop-reason
:result-address (:result next-outcome)
:address (:result next-outcome))))
{:address (:result next-outcome)
:n n
:result-xs (conj result-xs next-outcome)})))
{:address address
:result-xs [{:input? true :result address}]}
;; taste
(range (or max-steps 7))))
(defn sparse-sdm
[{:as opts :keys [decoder]}]
(let [decoder (or decoder (->decoder-coo opts))
storage (->sdm-storage-coo opts)]
(reify
SDM
(write [this address content decoder-threshold]
(write-1 storage
(decode-address decoder
address
decoder-threshold)
content))
(lookup [this address top-k decoder-threshold]
(lookup-1 storage
(decode-address decoder
address
decoder-threshold)
top-k))
(decay [this drop-chance]
(storage-decay storage drop-chance)))))
(def ->sdm sparse-sdm)
;; --------------------
;; Unit Tests