-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCharTransformer.cpp
1997 lines (1826 loc) · 83.9 KB
/
CharTransformer.cpp
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
// Character-level transformer that generates random texts similar to an input text. This is what happens
// in the training of Chat GPT (where the input text is a large chunk of the internet, and where the
// tokens are words instead of characters).
// https://www.youtube.com/watch?v=kCc8FmEb1nY
// https://github.com/karpathy/nanoGPT
// The generation is one character at a time, using the previous n characters. n is called the context size.
// With n=5 this is similar to continuing sequences of numbers like 2 4 6 8 10 __. But instead of applying
// an a priori knowledge in arithmetic, we apply the patterns learnt in a training text.
// It is important to train the model for all contexts sizes from 0 up to n, because at the start of the
// generation the context is empty. If we try instead to start with a corrupted context (like n spaces,
// which never appears in a real text), the corruption will propagate infinitely, because the context
// rolls as more letters are generated.
// Differences with Karpathy:
// - matrix of keys merged with matrix of queries
// - no random approximation of the Loss, which is evaluated on the full training text at
// each optimization step.
// - English syntax, shows how to mix AI with usual programming
// - cleanup of tiny Shakespeare (_ instead of --, typos, remove character 3 which was a footer)
// - gradients manually coded, to get a better idea of what autograd does
// - trains on a CPU, does not need a GPU
// Here the training text is a subset of 40k lines of Shakespeare :
// https://www.opensourceshakespeare.org/
// https://shakespeare.mit.edu/
// tiny-shakespeare.txt probably taken from the MIT website, and removed didascaliae.
// Shakespeare sonnet generator :
// https://web.stanford.edu/class/archive/cs/cs224n/cs224n.1174/reports/2762063.pdf
// We start with an n-gram language model, and find it generalizes very badly. Because for n>=6 there are
// not enough n-character substrings in the training text to represent all possible n-character substrings
// of English. In other words, for n>=6 the generator rather copies entire substrings of the training text :
// that's plagiarism not generation. The problem of n-gram is rather clear : it looks for the exact same
// (n-1)-prefix in the training text, instead of searching for similar prefixes. But that notion of
// similar prefixes is very hard to define. For example if the context is "the red bli_", the last space
// indicates we are looking for a word that starts with "bli". So this context is highly correlated to
// the shorter context " bli_", which is easier to find in the training text.
// Instead of defining similar prefixes, we will learn them automatically from the data, using a language model
// called transformer. In the attention is all you need paper
// https://arxiv.org/pdf/1706.03762.pdf
// this corresponds to a decoder-only transformer (in the diagram page 3, we remove the inputs column and only
// implement the outputs column).
// Validation losses for different models:
// - Karpathy's full transformer: 165000 (equivalent of 1.48 in his youtube video cited above, at 1:40:33)
// - single-head attention, 2-layer perceptron, context 128 letters, embedding dimension 64: ????, 53568 parameters
// - single-head attention, 2-layer perceptron, context 64 letters, embedding dimension 16: 183000, 7808 parameters
// - 5-gram with bigram defaulting (plagiarism): 211415
// - single-head attention, context 32 letters, embedding dimension 16: 233000, 2816 parameters
// - 2-layer perceptron all context, context 64 letters, embedding dimension 10, hidden layer 100: 247000, 71000 parameters
// - just English syntax: 290000, 0 parameters
// - random: 463000 = 111457 * ln(64)
#include <string>
#include <set>
#include <map>
#include <random>
#include <cassert>
#include <iostream>
#include <numeric>
#include <chrono>
#include <filesystem>
#include <fstream>
#include <future>
#include "ParamFunc.h"
extern std::filesystem::path sDatasetDirectory;
// std::random_device is just a wrapper around function rand_s.
// rand_s calls the operating system for cryptographically secure random integers (between 0 to UINT_MAX).
static std::random_device rd;
static std::mt19937 gen(rd()); // mersenne_twister_engine seeded with rd()
std::set<char> CheckNextChars(char c)
{
std::stringstream ss;
std::ifstream f(sDatasetDirectory / "Shakespeare/vocabulary.txt");
std::set<char> letters;
std::string line;
while (std::getline(f, /*out*/line))
{
if (2 <= std::count(line.begin(), line.end(), '\''))
throw "bou";
}
f.close();
return letters;
}
double BigramProbability(const std::map<std::string, unsigned int>& bigramProbas,
char prefix, char target)
{
std::string s;
s += prefix;
auto b = bigramProbas.lower_bound(s);
s.back() = s.back() + 1;
auto e = bigramProbas.lower_bound(s);
unsigned int totalCount = 0;
double proba = 0.0;
for (auto c = b; c != e; c++)
{
totalCount += c->second;
if (c->first.back() == target)
proba = c->second;
}
return proba / totalCount;
}
class ScopedClock
{
public:
ScopedClock()
: fBegin(std::chrono::steady_clock::now()),
fName("Unnamed clock")
{}
ScopedClock(const char* name)
: fBegin(std::chrono::steady_clock::now()),
fName(name)
{
}
~ScopedClock()
{
auto end = std::chrono::steady_clock::now();
std::cout << fName << ": " << std::chrono::duration_cast<std::chrono::milliseconds>(end - fBegin) << std::endl;
}
std::chrono::steady_clock::time_point fBegin;
const char* fName = "";
};
class NgramModel
{
public:
// Compute the empirical (in trainingText) probabilities of a character,
// given an (n-1)-length prefix.
void Train(const std::string& trainingText,
unsigned int n) // length of the key string
{
fProbas.clear();
fBigramProbas.clear();
size_t lastChar = trainingText.length() - (n - 1);
for (auto i = 0; i < lastChar; i++)
{
const std::string k = trainingText.substr(i, n);
fProbas[k]++;
}
// Bigram training
for (size_t i = 0; i < trainingText.length() - 1; i++)
{
const std::string k = trainingText.substr(i, 2);
fBigramProbas[k]++;
}
// Add all possible bigrams from the English dictionary.
// This is a priori knowledge about English, not information
// from the training text.
fBigramProbas.emplace("bw", 1);
fBigramProbas.emplace("b?", 1);
fBigramProbas.emplace("dt", 1);
fBigramProbas.emplace("fn", 1);
fBigramProbas.emplace("ji", 1);
fBigramProbas.emplace("rz", 1);
fBigramProbas.emplace("tb", 1);
fBigramProbas.emplace("z'", 1);
fBigramProbas.emplace("z!", 1);
fBigramProbas.emplace("Aj", 1);
fBigramProbas.emplace("DR", 1);
fBigramProbas.emplace("EB", 1);
fBigramProbas.emplace("E'", 1);
fBigramProbas.emplace("FE", 1);
fBigramProbas.emplace("G-", 1);
fBigramProbas.emplace("IB", 1);
fBigramProbas.emplace("IP", 1);
fBigramProbas.emplace("NZ", 1);
fBigramProbas.emplace("O\n", 1);
fBigramProbas.emplace("RV", 1);
fBigramProbas.emplace("Sy", 1);
fBigramProbas.emplace("SP", 1);
fBigramProbas.emplace("_D", 1);
fBigramProbas.emplace("'N", 1);
}
unsigned int GetN() const
{
return fProbas.empty() ? 0 : static_cast<unsigned int>(fProbas.begin()->first.length());
}
std::set<char> GetAlphabet() const
{
std::set<char> alphabet;
for (const auto& [s, _] : fProbas)
alphabet.insert(s.begin(), s.end());
return alphabet;
}
// Compare different language models by likelihood.
// The likelihood is the probability that the model would produce the validation text.
// However this likelihood is so small that it cannot be represented by 64-bit
// floating-point numbers, because we have 65 characters in the alphabet and
// the validation text has around 100k characters, so that's around (1/65)^100000,
// even for the ideal language model.
// We therefore compute the logarithm of this likelihood, which splits into a sum of logarithms
// for each character drawn. That makes a negative number representable in 64 bits,
// and we finally return its opposite to get a positive number : the loss, or surprise
// to observe validationText given the model NgramProbabilities.
// The loss has no upper bound, because there is no likelihood lower bound :
// if NgramProbabilities is a bad model, its likelihood on validationText can be
// any number towards 0, even 0 itself.
// On the other end we want to model to accept many different validation texts
// (the text it could generate), so the propability of each is less than 1, and
// the loss should not be 0.
// Might be useful to divide by the length of text, to compare training loss
// and validation loss. For example the loss of a completely random generator is
// text.length() * std::log(alphabet.size()), which gives std::log(alphabet.size())
// if we divide by text.length().
double Loss(const std::string& text) const
{
// Loss of completely random model, for comparison
// const std::set<char> alphabet = GetAlphabet();
// const double noiseLoss = text.size() * std::log(alphabet.size()); // 465598
const size_t n = GetN();
double loss = 0.0;
double unexplainedLoss = 0.0;
for (size_t i = 0; i < text.size(); i++)
{
// Example, validationText=="ABCDEFGH", n==5, i==4
const std::string prefix = (n <= i + 1
? text.substr((i + 1) - n, n - 1)
: "\n" + text.substr(0, i));
auto b = fProbas.lower_bound(prefix);
const double bigramProba = BigramProbability(fBigramProbas, prefix.back(), text[i]);
if (prefix.length() + 1 < n || b->first.rfind(prefix, 0) != 0)
{
loss -= std::log(bigramProba);
}
else
{
// Can still be bigram, with 0.001 chance.
std::string s = prefix;
s.back() = s.back() + 1;
auto e = fProbas.lower_bound(s);
unsigned int totalCount = 0;
double proba = 0.0;
for (auto c = b; c != e; c++)
{
totalCount += c->second;
if (c->first.back() == text[i])
proba = c->second;
}
loss -= std::log(0.001 * bigramProba + 0.999 * proba / totalCount);
}
if (!std::isfinite(loss))
{
throw "bou";
}
}
return loss;
}
// In other words, this function uses the trained n-gram language model to generate a random character.
char GenerateCharacter(const std::string& prefix) const
{
// By counting the substrings of its training text, the n-gram model does not generalize well :
// it only generates n-substrings of its training text. We add a small probability of truncating
// the prefix to a single character, to improve generalization (and get a finite log-likelihood
// on the validation text). This random prefix is a first step towards the transformer model.
unsigned int totalCount = 0;
std::map<char, unsigned int> logits;
auto b = fProbas.lower_bound(prefix);
auto e = fProbas.end();
std::uniform_int_distribution<> distribGeneralize(0, 999);
size_t pLen = prefix.length();
if (prefix.length() + 1 < GetN() || b->first.rfind(prefix, 0) != 0 || distribGeneralize(gen) == 0)
{
// Default to BiGram
std::string lastCharacter;
lastCharacter += prefix.back();
b = fBigramProbas.lower_bound(lastCharacter);
lastCharacter.back() = lastCharacter.back() + 1;
e = fBigramProbas.lower_bound(lastCharacter);
pLen = 1;
}
else
{
std::string s = prefix;
s.back() = s.back() + 1;
e = fProbas.lower_bound(s);
}
for (auto c = b; c != e; c++)
{
totalCount += c->second;
logits[c->first[pLen]] += c->second;
}
// Draw random logit
std::uniform_int_distribution<> distrib(0, totalCount - 1);
unsigned int nextCharacterIndex = distrib(gen);
for (auto [c, count] : logits)
{
if (nextCharacterIndex < count)
{
// Postcondition: next character is found
return c;
}
else
nextCharacterIndex -= count;
}
assert(false); // logit not found
return 0;
}
std::string GenerateText() const
{
// Character based n-grams make invalid words, word-based n-grams would be better.
// And we should use forward context to understand sentences like
// "The bear walks towards the honey pot because it is ______".
// This unknown next word tells whether "it" refers to "bear" or to "honey".
const unsigned int n = GetN();
std::string prefix = "\n";
std::string s;
for (int i = 0; i < 1000; i++)
{
const char c = GenerateCharacter(prefix);
s += c;
prefix += c;
if (n <= prefix.length())
prefix = prefix.substr(1, n - 1);
}
return s;
}
private:
std::map<std::string, unsigned int> fProbas;
// Bigram is used rarely instead of full n-gram, to improve generalization
std::map<std::string, unsigned int> fBigramProbas;
};
class AttentionHead : public pf::ParamFunc
{
public:
// An attention head works on a sequence of characters of size fContextLength,
// embedded each as tokenEmbeddingDim floating-point numbers. Attention replaces
// each character by a weighted average of its previous characters, via the
// triangular matrix oWeights. These weights intend to sum up all past information
// at each character, for the purpose of predicting the next character.
// An attention head stores a square matrix H (alias fQueryMatrix) that defines
// he affinity between two tokens x,y by the inner product <| x, Hy |>.
// That's arguably one of the simplest learnable affinity formulas.
// Those affinities go through a softmax to produce oWeights. To reduce the number of
// parameters in H, we split it as a product of 2 rectangular matrices fKeys
// and fQueries (which usually degenerates H's rank). Finally the weights are
// applied to another parameter matrix fValues to produce the output.
// It receives fContextLength token embeddings (which also encode token positions)
// and produces logits for the next token.
AttentionHead(unsigned int contextLength,
unsigned int tokenEmbeddingDim,
unsigned int outputDim)
: fContextLength(contextLength),
fScale(std::sqrt(static_cast<double>(tokenEmbeddingDim))),
fQueryMatrix(tokenEmbeddingDim, tokenEmbeddingDim),
fValueMatrix(outputDim, tokenEmbeddingDim),
oWeights(contextLength, 0.0),
oAverageToken(tokenEmbeddingDim, 0.0),
oQuery(fQueryMatrix.GetOutputDim(), 0.0),
oQt(fQueryMatrix.GetInputDim(), 0.0),
oDiffV(fValueMatrix.GetInputDim(), 0.0)
{
fInputDim = contextLength * tokenEmbeddingDim;
fOutputDim = outputDim;
fParameterCount = fQueryMatrix.GetParameterCount() + fValueMatrix.GetParameterCount();
}
unsigned int GetTokenEmbeddingDim() const
{
return fQueryMatrix.GetInputDim();
}
unsigned int GetContextLength() const
{
return fContextLength;
}
unsigned int& GetContextLength()
{
// Allows to truncate context, for example at the beginning of generation
return fContextLength;
}
const pf::Linear& GetQueryMatrix() const
{
return fQueryMatrix;
}
const pf::Linear& GetValueMatrix() const
{
return fValueMatrix;
}
virtual double& GetParameter(unsigned int index) override
{
const unsigned int queryParams = fQueryMatrix.GetParameterCount();
if (index < queryParams)
return fQueryMatrix.GetParameter(index);
index -= queryParams;
return fValueMatrix.GetParameter(index);
}
// Softmax of the embedded tokens.
// Number of multiplications for query and inner products:
// tokenDim^2 + tokenDim * fContextLength.
// If we separate with a fKeyMatrix, then
// query = fKeyMatrix^t * fQueryMatrix * last token
// which takes 2*d*tokenDim multiplications (right multiplication first),
// where d is the common output dim of fKeyMatrix and fQueryMatrix.
// It is faster if d < tokenDim/2, and takes less parameters.
void Weights(const double* tokensB,
/*out*/std::vector<double>& weights,
/*out*/std::vector<double>& query) const
{
unsigned int tokenDim = GetTokenEmbeddingDim();
const double* tokensE = tokensB + fContextLength * tokenDim;
auto w = weights.begin();
const double* lastToken = tokensE - tokenDim;
fQueryMatrix.Apply(lastToken, /*out*/query.data());
for (const double* token = tokensB; token <= lastToken; token += tokenDim)
{
// All these inner products with query could be packed
// as a matrix multiplication by query.
*w = std::inner_product(query.begin(), query.end(), token, 0.0) / fScale;
w++;
}
pf::InPlaceSoftMax(weights.data(), fContextLength);
}
void AverageToken(const double* tokensB,
const std::vector<double>& weights,
/*out*/std::vector<double>& averageToken) const
{
const unsigned int tokenDim = GetTokenEmbeddingDim();
const double* tokensE = tokensB + fContextLength * tokenDim;
std::fill(averageToken.begin(), averageToken.end(), 0.0);
auto w = weights.begin();
for (const double* token = tokensB; token < tokensE; token += tokenDim, w++)
pf::AddScaledVector(token, token + tokenDim, *w, /*out*/averageToken.data());
}
// The logits (aka scores) for each next token to predict.
// The logits will go through a softmax to be converted into probabilities.
virtual void Apply(const double* tokens, /*out*/double* pastAverage) const override
{
Weights(tokens, /*out*/oWeights, /*out*/oQuery);
AverageToken(tokens, oWeights, /*out*/oAverageToken);
fValueMatrix.Apply(oAverageToken.data(), /*out*/pastAverage); // faster than applying fValues on each token before average
oPastAggregate = pastAverage;
}
// Differential of affinity_k with respect to tokens and fQueryMatrix
void DifferentialAffinity(unsigned int k,
const double* tokenK,
const double* lastToken, // i.e. token at position fContextLength - 1
const double* q, // = fQueryMatrix * lastToken
double comp,
/*out*/double* diff,
/*out*/double* diffQuery) const
{
// affinity_k = <| fQueryMatrix * lastToken, token_k |> / fScale
// d affinity_k = <| d (fQueryMatrix * lastToken), token_k |>
// + <| fQueryMatrix * lastToken, d token_k |>
const unsigned int tokenEmbeddingDim = GetTokenEmbeddingDim();
// Differential with respect to tokenK
pf::AddScaledVector(q, q + tokenEmbeddingDim, comp, /*out*/diff + (k * tokenEmbeddingDim));
// Differential with respect to lastToken (factorized to avoid multiplications by fQueryMatrix)
// fQueryMatrix.ApplyTransposed(tokenK, /*out*/oQt.data()); // fQt could be split by i
// pf::AddScaledVector(oQt.data(), oQt.data() + tokenDim, comp,
// /*out*/diff + ((fContextLength - 1) * tokenDim));
pf::AddScaledVector(tokenK, tokenK + tokenEmbeddingDim, comp, /*out*/oQt.data());
// Differential with respect to queries
for (unsigned int j = 0; j < tokenEmbeddingDim; j++)
{
// *lastToken[col] is factorized outside of DifferentialAffinity, to accelerate
diffQuery[j * tokenEmbeddingDim] += comp * tokenK[j];
}
}
// The gradient of a real function has the same shape as the function's parameters.
// The output stores the partial derivatives with respect to the corresponding parameters.
virtual void Differential(const double* tokens, const double* comp,
/*out*/double* diff, /*out*/double* diffParams) const override
{
// Precondition: the forward pass was already done.
//ScopedClock clk("Attention differential");
const unsigned int tokenEmbeddingDim = GetTokenEmbeddingDim();
const double* lastToken = tokens + (fContextLength - 1) * tokenEmbeddingDim;
std::fill(diff, diff + fInputDim, 0.0);
std::fill(diffParams, diffParams + fParameterCount, 0.0);
fValueMatrix.Differential(oAverageToken.data(), comp,
/*out*/oDiffV.data(), /*out*/diffParams + fQueryMatrix.GetParameterCount());
// Now the differential of average token = sum_k weight_k * token_k
std::fill(oQt.begin(), oQt.end(), 0.0);
const double averageDiffV = std::inner_product(oDiffV.begin(), oDiffV.begin() + tokenEmbeddingDim, oAverageToken.begin(), 0.0);
for (unsigned int k = 0; k < fContextLength; k++)
{
// Differential with respect to token_k :
// weight_k * d token_k
pf::AddScaledVector(oDiffV.data(), oDiffV.data() + tokenEmbeddingDim, oWeights[k],
/*out*/diff + (k * tokenEmbeddingDim));
// Differential of softmax :
// d weight_k = weight_k * d affinity_k - weight_k * \sum_j weight_j * d affinity_j
// Differential with respect to weights :
// \sum_k d weight_k * token_k
// = \sum_k weight_k * token_k * d affinity_k
// - \sum_k weight_k * (\sum_j weight_j * d affinity_j) * token_k
// = \sum_k (token_k - averageToken) * weight_k * d affinity_k
const double* token_k = tokens + k * tokenEmbeddingDim;
const double x = std::inner_product(oDiffV.begin(), oDiffV.begin() + tokenEmbeddingDim, token_k, 0.0) - averageDiffV;
DifferentialAffinity(k, token_k, lastToken, oQuery.data(),
x * oWeights[k] / fScale,
/*out*/diff, /*out*/diffParams);
}
// Add differential with respect to last token, that was factorized in DifferentialAffinity:
// oQt * fQueryMatrix
double* diffLast = diff + ((fContextLength - 1) * tokenEmbeddingDim);
const double* q = fQueryMatrix.GetRow(0);
for (unsigned int j = 0; j < tokenEmbeddingDim; j++)
{
const double diffQuery = diffParams[j * tokenEmbeddingDim];
for (unsigned int col = 0; col < tokenEmbeddingDim; col++)
{
diffParams[j * tokenEmbeddingDim + col] = diffQuery * lastToken[col];
diffLast[col] += oQt[j] * (*q);
q++;
}
}
}
private:
unsigned int fContextLength = 0;
// Scaled attention, prevents the softmax from becoming true max
// (which differential is 0, because its value is 1 on the maximum
// coordinate and 0 on all other coordinates). In other words,
// true max would force a predicted character (probability 1),
// and the parameters would have no (differential) effect on that
// prediction.
double fScale = 1.0;
// For the moment the alphabet is small (65 symbols) and we take it
// as the token embedding dimension. So we accept a full square
// fQueries matrix of size 65*65=4225. If the embedding dimension
// grows, we will reduce the attention's dimension by squashing
// fQueries into a rectangular matrix and adding another rectangular
// matrix fKeys, the product of which will be the square attention
// matrix (with degenerate rank).
pf::Linear fQueryMatrix;
// fValueMatrix reduces the number of parameters when there are
// n heads of attention. The n fValueMatrix have
// n * tokDim * tokDim / n = tokDim * tokDim
// parameters. And they reduce the input of the TLP to tokDim,
// parameters, so its first matrix has tokDim * 4 * tokDim
// parameters. Without fValueMatrix, the TLP would have a
// first matrix with n * tokDim * 4 * tokDim parameters.
pf::Linear fValueMatrix;
mutable std::vector<double> oWeights;
mutable std::vector<double> oAverageToken;
mutable std::vector<double> oQuery;
mutable std::vector<double> oQt;
mutable std::vector<double> oDiffV;
mutable double* oPastAggregate = nullptr;
};
class TLP : public pf::ParamFunc
{
public:
// 2-layer perceptron, i.e. fully connected neural network
// with only one hidden layer. By the universal approximation theorem,
// those can approximate any function, but at the cost of a huge
// number of neurons in the hidden layer.
TLP(unsigned int inputDim,
unsigned int hiddenLayerDim,
unsigned int outputDim,
bool biases)
: fU(hiddenLayerDim, inputDim),
fV(outputDim, hiddenLayerDim),
oU(fU.GetOutputDim(), 0.0)
{
fInputDim = inputDim;
fOutputDim = outputDim;
fParameterCount = fU.GetParameterCount() + fV.GetParameterCount();
for (unsigned int i = 0; i < GetParameterCount(); i++)
{
const double epsilon = (i % 2 == 0 ? 1.0 : -1.0);
GetParameter(i) = epsilon * (i * 2.0 / GetParameterCount() - 1.0);
}
if (biases)
SetBiases(std::vector<double>(hiddenLayerDim, 0.0), std::vector<double>(outputDim, 0.0));
}
virtual double& GetParameter(unsigned int index) override
{
const unsigned int queryParams = fU.GetParameterCount();
if (index < queryParams)
return fU.GetParameter(index);
index -= queryParams;
const unsigned int valueParams = fV.GetParameterCount();
if (index < valueParams)
return fV.GetParameter(index);
throw std::invalid_argument("bad parameter");
}
void SetU(unsigned int index, double d)
{
fU.GetParameter(index) = d;
}
void SetV(unsigned int index, double d)
{
fV.GetParameter(index) = d;
}
const pf::Linear& GetV() const
{
return fV;
}
virtual void Apply(const double* x, double* y) const override
{
// const_cast<TLP*>(this)->CenterBias();
fU.Apply(x, /*out*/oU.data());
for (double& d : oU)
if (d < 0.0)
d = 0.0; // ReLU
fV.Apply(oU.data(), /*out*/y);
}
virtual void Differential(const double* x, const double* comp,
/*out*/double* diff, /*out*/double* diffParams) const override
{
//ScopedClock clk("TLP differential");
std::fill(diff, diff + fInputDim, 0.0);
std::fill(diffParams, diffParams + GetParameterCount(), 0.0);
// RELU optimization: recode part of fV's Differential here
// to skip the coefficients that are blocked by the RELU.
// Differential with respect to V's parameters
const unsigned int VmatrixSize = fV.GetOutputDim() * fV.GetInputDim();
double* diffVParams = diffParams + fU.GetParameterCount();
for (unsigned int outputIdx = 0; outputIdx < fOutputDim; outputIdx++)
{
const double coef = comp[outputIdx];
// d biasVrow
if (VmatrixSize < fV.GetParameterCount()) // Postcondition: fV has bias
diffVParams[VmatrixSize + outputIdx] = coef /* *1.0 */;
// dVrow * sigma(u)
for (unsigned int i = 0; i < fU.GetOutputDim(); i++)
diffVParams[outputIdx * fV.GetInputDim() + i] = coef * oU[i];
}
// Write dLoss / dU in oU
for (unsigned int outputIdx = 0; outputIdx < fU.GetOutputDim(); outputIdx++)
{
double& o = oU[outputIdx];
if (o == 0.0)
continue; // This node is blocked by the RELU, so it does not affect the loss.
o = 0.0;
for (unsigned int row = 0; row < fOutputDim; row++)
o += comp[row] * fV.GetRow(row)[outputIdx];
}
fU.Differential(x, oU.data(), /*out*/diff, /*out*/diffParams);
}
// fV's bias is sent into a softmax, so we can subtract its mean
void CenterBias()
{
const unsigned int vSize = fV.GetInputDim() * fV.GetOutputDim();
double mean = 0.0;
for (unsigned int i = 0; i < fV.GetOutputDim(); i++)
mean += fV.GetParameter(vSize + i);
mean /= fV.GetOutputDim();
for (unsigned int i = 0; i < fV.GetOutputDim(); i++)
fV.GetParameter(vSize + i) = fV.GetParameter(vSize + i) - mean;
}
private:
void SetBiases(std::vector<double>&& Ubias, std::vector<double>&& Vbias)
{
fU.SetBiases(std::move(Ubias));
fV.SetBiases(std::move(Vbias));
fParameterCount = fU.GetParameterCount() + fV.GetParameterCount();
}
pf::Linear fU;
pf::Linear fV;
mutable std::vector<double> oU;
};
class AttentionStack : public pf::ParamFunc
{
public:
AttentionStack(unsigned int contextLength,
unsigned int tokenEmbeddingDim,
unsigned int attentionHeads,
unsigned int alphabetSize)
: fFirstAttention(BuildAttentionHeads(contextLength, tokenEmbeddingDim, attentionHeads), false),
fTLP(tokenEmbeddingDim, 4*tokenEmbeddingDim, alphabetSize, true),
oPastAverage(tokenEmbeddingDim, 0.0),
oLogits(alphabetSize, 0.0),
oConvolDiff(fTLP.GetInputDim(), 0.0)
{
fInputDim = contextLength * tokenEmbeddingDim;
fOutputDim = alphabetSize;
fParameterCount = fFirstAttention.GetParameterCount() + fTLP.GetParameterCount();
}
AttentionStack(const AttentionStack& other) = delete;
AttentionStack& operator=(const AttentionStack& other) = delete;
AttentionStack(AttentionStack&& other) = default;
AttentionStack& operator=(AttentionStack&& other) = default;
std::vector<std::unique_ptr<ParamFunc>> BuildAttentionHeads(unsigned int contextLength,
unsigned int tokenEmbeddingDim,
unsigned int attentionHeads)
{
std::vector<std::unique_ptr<ParamFunc>> ret;
ret.reserve(contextLength);
fContextLengths.resize(attentionHeads, nullptr);
for (unsigned int i = 0; i < attentionHeads; i++)
{
auto head = std::make_unique<AttentionHead>(contextLength, tokenEmbeddingDim, tokenEmbeddingDim / attentionHeads);
fContextLengths[i] = &head->GetContextLength();
ret.emplace_back(std::move(head));
}
return ret;
}
const pf::CartesianProduct& GetHeads() const
{
return fFirstAttention;
}
const TLP& GetTLP() const
{
return fTLP;
}
double& GetParameter(unsigned int index) override
{
const unsigned int fstAttParams = fFirstAttention.GetParameterCount();
if (index < fstAttParams)
return fFirstAttention.GetParameter(index);
index -= fstAttParams;
const unsigned int tlpParams = fTLP.GetParameterCount();
if (index < tlpParams)
return fTLP.GetParameter(index);
throw std::invalid_argument("bad parameter");
}
void SetContextLength(unsigned int contextLen)
{
// Allows to truncate context, for example at the beginning of generation
for (unsigned int* p : fContextLengths)
*p = contextLen;
}
std::vector<double>& GetLogits() const
{
// the final logits, output of this AttentionStack
return oLogits;
}
void Apply(const double* tokens, /*out*/double* logitsAllTokens) const override
{
// TODO layer norm tokens here (if exp args are too big)
fFirstAttention.Apply(tokens, /*out*/oPastAverage.data());
// TODO layer norm a here (if exp args are too big)
fTLP.Apply(oPastAverage.data(), /*out*/logitsAllTokens);
}
virtual void Differential(const double* tokens, const double* comp,
/*out*/double* diff, /*out*/double* diffParams) const override
{
// Precondition: the forward pass was already done (for example in DifferentialLoss).
// Backpropagation of the gradient
fTLP.Differential(oPastAverage.data(), comp,
/*out*/oConvolDiff.data(),
/*out*/diffParams + fFirstAttention.GetParameterCount());
fFirstAttention.Differential(tokens, oConvolDiff.data(),
/*out*/diff, /*out*/diffParams);
}
private:
std::vector<unsigned int*> fContextLengths;
pf::CartesianProduct fFirstAttention;
// there should be a single linear convolution at the end for tokDim -> alphabetSize.
// For now we take alphabetSize directly as the output dim of fTLP.
TLP fTLP;
mutable std::vector<double> oPastAverage;
mutable std::vector<double> oLogits;
mutable std::vector<double> oConvolDiff;
};
// Compare std::tolower(word) with lowerWord which has no caps.
int StrcmpLower(const char* wordB, const char* wordE, bool incrLastLetter,
const char* lowerWord)
{
while (1)
{
if (wordB == wordE)
{
// Postcondition: word is finished
if (*lowerWord == 0)
return 0; // word == lowerWord
else
return -1; // word < lowerWord
}
if (*lowerWord == 0)
return 1; // lowerWord < word
char c = std::tolower(*wordB);
if (incrLastLetter && wordB == wordE - 1)
c++;
if (c < *lowerWord)
return -1; // word < lowerWord
else if (*lowerWord < c)
return 1; // lowerWord < word
wordB++;
lowerWord++;
}
}
std::string Alphabet(const std::string& text)
{
std::set<char> s(text.begin(), text.end());
return std::string(s.begin(), s.end());
}
unsigned int GetCharacterIndex(const std::string& alphabet, char c)
{
auto it = std::lower_bound(alphabet.begin(), alphabet.end(), c);
return (it != alphabet.end() && *it == c) ? it - alphabet.begin() : alphabet.size();
}
// Get a valid prefix by going back to the first letter of a word
// sumExp == 0, context was ' in bigger text hat, man! 'tis not so
// TODO call this function in AllowWord
void MoveToStartOfWord(const std::string& text, /*out*/unsigned int& i)
{
// Same as AllowWord. A word may contain apostrophes.
char c = std::tolower(text[i]);
if (('a' <= c && c <= 'z') || c == '-' || c == '\'')
{
// i is probably inside a word, except if start or end of quotation.
while (0 < i && text[i - 1] != ' ' && text[i - 1] != '\n' && text[i - 1] != ',' && text[i - 1] != ';'
&& text[i - 1] != '_') // dash
i--;
}
}
class CharGenerator
{
// Embed prefix to continuous space, call prediction network to produce logits,
// filter logits by English rules, and softmax to get probabilities for character.
public:
CharGenerator(unsigned int contextLength,
unsigned int characterEmbeddingDim,
unsigned int attentionHeads,
unsigned int threadCount,
const std::string& alphabet)
: fAlphabet(Alphabet(alphabet)),
fCharacterEmbeddings(static_cast<unsigned int>(fAlphabet.size()), characterEmbeddingDim), // GetRow(i) gives the i-th embedding
fPositionEmbeddings(contextLength, characterEmbeddingDim),
fComputeLogits(contextLength, characterEmbeddingDim, attentionHeads, fAlphabet.size()),
fComment("// comment this character generator here"),
oEmbeddings(fComputeLogits.GetInputDim(), 0.0),
oDiffLoss(1, GetParameterCount()),
oDiffOneSample(1, GetParameterCount())
{
std::ifstream f(sDatasetDirectory / "Shakespeare/vocabulary.txt");
std::string word;
while (std::getline(f, /*out*/word))
fVocabulary.push_back(word);
std::mt19937 mt; // Mersenne twister pseudo-random generator, with a fixed default (not random) seed.
std::uniform_real_distribution<> distrib(-1.0, 1.0);
for (unsigned int i = 0; i < GetParameterCount(); i++)
GetParameter(i) = distrib(mt);
if (0 < threadCount)
fChildren.reserve(threadCount - 1);
for (unsigned int t = 1; t < threadCount; t++)
fChildren.emplace_back(contextLength, characterEmbeddingDim, attentionHeads, 0, alphabet);
}
unsigned int GetParameterCount() const
{
return fCharacterEmbeddings.GetParameterCount()
+ fPositionEmbeddings.GetParameterCount() + fComputeLogits.GetParameterCount();
}
unsigned int GetHeadCount() const
{
return fComputeLogits.GetHeads().GetFunctions().size();
}
const std::vector<CharGenerator>& GetChildren() const
{
return fChildren;
}
double& GetParameter(unsigned int index)
{
const unsigned int charParams = fCharacterEmbeddings.GetParameterCount();
if (index < charParams)
return fCharacterEmbeddings.GetParameter(index);
index -= charParams;
const unsigned int posParams = fPositionEmbeddings.GetParameterCount();
if (index < posParams)
return fPositionEmbeddings.GetParameter(index);
index -= posParams;
return fComputeLogits.GetParameter(index);
}
double GetParameter(unsigned int index) const
{
return const_cast<CharGenerator*>(this)->GetParameter(index);
}
void SyncChildren()
{
for (unsigned int i = 0; i < GetParameterCount(); i++)
for (CharGenerator& child : fChildren)
child.GetParameter(i) = GetParameter(i); // the parameters could be shared instead of copied
}
const pf::Linear& GetCharacterEmbeddings() const
{
return fCharacterEmbeddings;
}
const pf::Linear& GetPositionEmbeddings() const
{
return fPositionEmbeddings;
}
const AttentionStack& GetAttentionStack() const
{
return fComputeLogits;
}
unsigned int GetContextLength() const
{
return fComputeLogits.GetInputDim() / GetTokenEmbeddingDim();
}
unsigned int GetTokenEmbeddingDim() const
{
return fCharacterEmbeddings.GetInputDim(); // column count
}
// The characters generated by this CharGenerator
const std::string& GetAlphabet() const
{
return fAlphabet;
}
std::string GetComment() const
{
return fComment;
}
void SetComment(const std::string& comment)
{
fComment = comment;
}
pf::Linear& GetDiffLoss() const
{
return oDiffLoss;
}