-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfxcm.cpp
More file actions
5855 lines (5436 loc) · 205 KB
/
fxcm.cpp
File metadata and controls
5855 lines (5436 loc) · 205 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* fxcm file compressor is based on paq8 model.
Copyright (C) 2025 Kaido Orav
LICENSE
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details at
Visit <http://www.gnu.org/copyleft/gpl.html>.
To compress: fxcm c input output
To decompress: fxcm d input output
This compressor contains changed parts (mostly marked with comments) from fallowing open source programs:
paq8hp12
paq8px_v208
paq8pxv
cmix
*/
#define PLAINTEXT // uncomment for plain text input, otherwise dictionray encoded input is expected
#ifdef PLAINTEXT
#define VERSION 25
#else
#define VERSION 26
#endif
#include <stdio.h>
#include <time.h>
#include <mem.h>
#define NDEBUG // remove for debugging (turns on Array bound checks)
#include <assert.h>
#ifdef UNIX // not tested
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <memory.h>
#include <cstdio>
#include <ctype.h>
#include <sys/cdefs.h>
#include <dirent.h>
#include <errno.h>
#endif
// AVX2
#include <immintrin.h>
// 8, 16, 32 bit unsigned types (adjust as appropriate)
typedef unsigned char U8;
typedef unsigned short U16;
typedef unsigned int U32;
typedef unsigned long long int U64;
//
typedef __m128i XMM;
typedef __m256i YMM;
// min, max functions
#if !defined(WINDOWS) || !defined (min)
inline int min(int a, int b) {return a<b?a:b;}
inline int max(int a, int b) {return a<b?b:a;}
#endif
#define ispowerof2(x) ((x&(x-1))==0)
#include <math.h>
#include <windows.h>
const int num_models = 560;// 16
short *model_predictions1,*model_predictions1_ptr;
unsigned int prediction_index=0;
void AddPrediction(int x) {
model_predictions1[prediction_index++]=x;
assert(prediction_index >= 0 && prediction_index < num_models);
}
void ResetPredictions() {
assert(prediction_index >= 0 && prediction_index <= num_models);
prediction_index = 0;
}
// Array
template <class T> void alloc(T*&ptr, int c) {
ptr=(T*)calloc(c, sizeof(T));
if (!ptr) exit(1);
}
// for aligned data
template <class T> void alloc1(T*&data, int c,T*&ptr,const int align=16) {
ptr=(T*)calloc(c, sizeof(T));
if (!ptr) exit(1);
data=(T*)(((uintptr_t)ptr+(align-1)) & ~(uintptr_t)(align-1));
}
// Squash returns p = 1/(1 + exp(-d)), d scaled by 8 bits, p scaled by 12 bits
short sqt[4096];
int squashc(int d ) {
if (d < -2047)return 1;
if (d > 2047)return 4095;
float p = 1.0f / (1.0f + exp(-d / 256.0));
p *= 4096.0;
U32 pi = (U32)round(p);
if (pi > 4095)pi = 4095;
if (pi < 1)pi = 1;
return pi;
}
inline int squash(int d) {
if (d < -2047)return 1;
if (d > 2047)return 4095;
return sqt[d + 2047];
}
// Stretch is inverse of squash. d = ln(p/(1-p)), d scaled by 8 bits, p by 12 bits.
// d has range -2047 to 2047 representing -8 to 8. p has range 0 to 4095.
short strt[4096];
inline short clp(int z) {
if (z<-2047) {
z=-2047;
} else if (z>2047) {
z=2047;
}
return z;
}
inline short clp1(int z){
if (z<0) {
z=0;
} else if (z>4095) {
z=4095;
}
return z;
}
int stretchc(int p) {
assert(p>=0 && p<=4095);
if (p==0) p=1;
float f=p/4096.0f;
float d=log(f/(1.0f-f))*256.0f;
int di=(int)round(d);
if (di>2047) di = 2047;
if (di<-2047) di = -2047;
return di;
}
inline short stretch(int p) {
assert(p>=0 && p<=4095);
if (p<0) p=0;
if (p>4095) p=4095;
return strt[p];
}
template <const int S=256>
struct alignas(64) Inputs {
short n[S];
int ncount; // mixer input count
void add(int p){
assert(p>-2048 && p<2048);// fixme, when enabled compression is different
n[ncount++]=clp(p);
assert(ncount>=0 && ncount<=S);
AddPrediction((clp(p)));
}
};
template <const int S>
struct BlockData {
int y; // Last bit, 0 or 1, set by encoder
int c0; // Last 0-7 bits of the partial byte with a leading 1 bit (1-255)
U32 c4; // Last 4 whole bytes, packed.
int bpos; // bits in c0 (0 to 7)
int blpos; // Relative position in block
int bposshift;
int c0shift_bpos;
int cmBitState;
Inputs<S> mxInputs1; // array of inputs, for two layers
Inputs<64> mxInputs2;
Inputs<64> mxInputs4;
void Init() {
y=0, c0=1, c4=0 ,bpos=0, blpos=0, bposshift=0, c0shift_bpos=0, cmBitState=0;
}
};
BlockData<544> x; //maintains current global data block
// ilog(x) = round(log2(x) * 16), 0 <= x < 256
U8 ilog[256];
// Compute lookup table by numerical integration of 1/x
void InitIlog() {
U32 x=14155776;
for (int i=2; i<257; ++i) {
x+=774541002/(i*2-1); // numerator is 2^29/ln 2
ilog[i-1]=x>>24;
}
}
// State table
// nex(state, 0) = next state if bit y is 0, 0 <= state < 256
// nex(state, 1) = next state if bit y is 1
// nex(state, 2) = number of zeros in bit history represented by state
// nex(state, 3) = number of ones represented
//
// States represent a bit history within some context.
struct StateTable {
int mdc; // maximum discount
enum {B=5, N=64}; // sizes of b, t
int b[6]; // x -> max y, y -> max x
unsigned char ns[1024]; // state*4 -> next state if 0, if 1, n0, n1
unsigned char t[N][N][2]={{{0}}};
int num_states(int x, int y) {
if (x<y) return num_states(y, x);
if (x<0 || y<0 || x>=N || y>=N || y>=B || x>=b[y]) return 0;
return 1+(y>0 && x+y<b[5]);
}
// New value of count x if the opposite bit is observed
void discount(int& x) {
int y=0;
if (x>2){
for (int i=1;i<mdc;i++) y+=x>=i;
x=y;
}
}
// compute next x,y (0 to N) given input b (0 or 1)
void next_state(int& x, int& y, int b) {
if (x<y)
next_state(y, x, 1-b);
else {
if (b) {
++y;
discount(x);
}
else {
++x;
discount(y);
}
while (!t[x][y][1]) {
if (y<2) --x;
else {
x=(x*(y-1)+(y/2))/y;
--y;
}
}
}
}
// Initialize next state table ns[state*4] -> next if 0, next if 1, x, y
void generate() {
memset(ns, 0, sizeof(ns));
memset(t, 0, sizeof(t));
// Assign states
int state=0;
for (int i=0; i<256; ++i) {
for (int y=0; y<=i; ++y) {
int x=i-y;
int n=num_states(x, y);
if (n) {
t[x][y][0]=state;
t[x][y][1]=n;
state+=n;
}
}
}
// Print/generate next state table
state=0;
for (int i=0; i<N; ++i) {
for (int y=0; y<=i; ++y) {
int x=i-y;
for (int k=0; k<t[x][y][1]; ++k) {
int x0=x, y0=y, x1=x, y1=y; // next x,y for input 0,1
int ns0=0, ns1=0;
next_state(x0, y0, 0);
next_state(x1, y1, 1);
ns[state*4]=ns0=t[x0][y0][0];
ns[state*4+1]=ns1=t[x1][y1][0]+(t[x1][y1][1]>1);
ns[state*4+2]=x;
ns[state*4+3]=y;
// uncomment to print table above
//printf("{%3d,%3d,%2d,%2d},", ns[state*4], ns[state*4+1],
// ns[state*4+2], ns[state*4+3]);
//if (state%4==3) printf(" // %d-%d\n", state-3, state);
if (state>0xff || t[x][y][1]==0 || t[x0][y0][1]==0 || t[x1][y1][1]==0) return;
assert(state>=0 && state<256);
assert(t[x][y][1]>0);
assert(t[x][y][0]<=state);
assert(t[x][y][0]+t[x][y][1]>state);
assert(t[x][y][1]<=6);
assert(t[x0][y0][1]>0);
assert(t[x1][y1][1]>0);
assert(ns0-t[x0][y0][0]<t[x0][y0][1]);
assert(ns0-t[x0][y0][0]>=0);
assert(ns1-t[x1][y1][0]<t[x1][y1][1]);
assert(ns1-t[x1][y1][0]>=0);
++state;
if (state>0xff) return;
}
}
}
}
void __attribute__ ((noinline)) Init(int s0,int s1,int s2,int s3,int s4,int s5,int s6,U8 *table) {
b[0]=s0;b[1]=s1;b[2]=s2;b[3]=s3;b[4]=s4;b[5]=s5;mdc=s6;
generate();
memcpy(table, ns, 1024);
}
};
//State tables
U8 STA1[256][4];
U8 STA2[256][4];
U8 STA4[256][4];
U8 STA5[256][4];
U8 STA6[256][4];
U8 STA7[256][4];
// Dictionary reverse
int wfgets(char *str, int count, FILE *fp) {
int c, i = 0;
while (i<count-1 && ((c=getc(fp))!=EOF)) {
str[i++]=c; if (c=='\n')str[i-1]=0;
if (c=='\n')
break;
}
str[i]=0;
return i;
}
char *s;
char *dictW[44515];
U8 dictWLen[44515];
char *dictM[472];
int codeword2sym[256];
int dict1size=80;
int dict2size=32;
int dict12size=dict1size*dict2size;
int sizeDict,sizeDict2;
// decoded codewords for wordmodel
U32 cwTEXT; // text
U32 cwNOWIKI; // nowiki
U32 cwMATH; // math
U32 cwPRE; // pre
U32 cwPAGE; // page image category user wikipedia
U32 cwIMAGE;
U32 cwCATEGORY;
U32 cwUSER;
U32 cwWIKIPEDIA;
//
U32 cwTABLE;
U32 cwTD;
//
U32 cwSEE;
U32 cwALSO;
//
U32 cwEXTERNAL;
U32 cwLINKS;
//
U32 cwREFERENCES; // References
U32 cwBIBLIOGRAPHY; // Bibliography
U32 cwIS;
U32 cwWITH;
U32 cwTHE;
U32 cwON,cwIN;
U32 cwWWW,cwHTTP;
U32 cwISBN;
void loaddict(FILE *file){
int line_count=0,len=0;
s=(char *)malloc(8192*8);
while ((len=wfgets(s, 8192*8, file)) ) {
dictW[line_count]=(char *)malloc(len);
memcpy(dictW[line_count], s, len);
dictWLen[line_count]=U8(len-1);
//printf("%d,%s\n",len,dictW[line_count]);
if (cwTEXT==0 && strcmp(dictW[line_count], "text")==0) cwTEXT=line_count;
else if (cwNOWIKI==0 && strcmp(dictW[line_count], "nowiki")==0) cwNOWIKI=line_count;
else if (cwMATH==0 && strcmp(dictW[line_count], "math")==0) cwMATH=line_count;
else if (cwPRE==0 && strcmp(dictW[line_count], "pre")==0) cwPRE=line_count;
else if (cwPAGE==0 && strcmp(dictW[line_count], "page")==0) cwPAGE=line_count;
else if (cwIMAGE==0 && strcmp(dictW[line_count], "image")==0) cwIMAGE=line_count;
else if (cwCATEGORY==0 && strcmp(dictW[line_count], "category")==0) cwCATEGORY=line_count;
else if (cwUSER==0 && strcmp(dictW[line_count], "user")==0) cwUSER=line_count;
else if (cwWIKIPEDIA==0 && strcmp(dictW[line_count], "wikipedia")==0) cwWIKIPEDIA=line_count;
else if (cwTABLE==0 && strcmp(dictW[line_count], "table")==0) cwTABLE=line_count;
else if (cwTD==0 && strcmp(dictW[line_count], "td")==0) cwTD=line_count;
else if (cwEXTERNAL==0 && strcmp(dictW[line_count], "external")==0) cwEXTERNAL=line_count;
else if (cwLINKS==0 && strcmp(dictW[line_count], "links")==0) cwLINKS=line_count;
else if (cwSEE==0 && strcmp(dictW[line_count], "see")==0) cwSEE=line_count;
else if (cwALSO==0 && strcmp(dictW[line_count], "also")==0) cwALSO=line_count;
else if (cwREFERENCES==0 && strcmp(dictW[line_count], "references")==0) cwREFERENCES=line_count;
else if (cwBIBLIOGRAPHY==0 && strcmp(dictW[line_count], "bibliography")==0) cwBIBLIOGRAPHY=line_count;
else if (cwIS==0 && strcmp(dictW[line_count], "is")==0) cwIS=line_count;
else if (cwWITH==0 && strcmp(dictW[line_count], "with")==0) cwWITH=line_count;
else if (cwTHE==0 && strcmp(dictW[line_count], "the")==0) cwTHE=line_count;
else if (cwON==0 && strcmp(dictW[line_count], "on")==0) cwON=line_count;
else if (cwIN==0 && strcmp(dictW[line_count], "in")==0) cwIN=line_count;
else if (cwWWW==0 && strcmp(dictW[line_count], "www")==0) cwWWW=line_count;
else if (cwHTTP==0 && strcmp(dictW[line_count], "http")==0) cwHTTP=line_count;
else if (cwISBN==0 && strcmp(dictW[line_count], "isbn")==0) cwISBN=line_count;
line_count++;
}
free(s);
printf("Loaded %d words\n",line_count);
//printf("Loaded %d %d %d %d %d %d %d %d %d, %d %d %d, %d %d, %d %d, %d\n", cwTEXT,cwNOWIKI,cwMATH,cwPRE,cwPAGE,cwIMAGE,cwCATEGORY,cwUSER,cwWIKIPEDIA ,cwIS,cwWITH,cwTHE,cwON,cwIN,cwWWW ,cwHTTP,cwISBN);
sizeDict=line_count;
}
inline int decodeCodeWord(int cw) {
int i=0;
int c=cw&255;
if (codeword2sym[c]<dict1size) {
i=codeword2sym[c];
return i;
}
i=dict1size*(codeword2sym[c]-dict1size);
c=(cw>>8)&255;
if (codeword2sym[c]<dict1size) {
i+=codeword2sym[c];
return i+dict1size;
}
i=(i-dict12size)*dict2size;
i+=dict1size*(codeword2sym[c]-dict1size);
c=(cw>>16)&255;
i+=codeword2sym[c];
return i+80*49;
}
void dosym() {
FILE *f=fopen("english.dic","rb");
loaddict(f);
fclose(f);
for (int c=0; c<256; c++) {
codeword2sym[c]=0;
}
int charsUsed=0;
for (int c=128; c<256; c++) {
codeword2sym[c]=charsUsed;
charsUsed++;
}
}
U32 lastCW=0;
void decodeWord(int c) {
lastCW=decodeCodeWord(c);
assert(lastCW>=0 && lastCW<44515);
}
struct Mix {
int N; // n
int* wt; // weights, scaled 24 bits
int x1, x2; // inputs, scaled 8 bits (-2047 to 2047)
int cxt; // last context (0..n-1)
int pr; // last output
void Init(int n=256) {
N=n, x1=0, x2=0, cxt=0, pr=0;
alloc(wt, n*2);
for (int i=0; i<N*2; ++i)
wt[i]=1<<23;
}
int pp(int p1, int p2, int cx) {
assert(cx>=0 && cx<N);
cxt=cx*2;
return pr=((x1=p1)*(wt[cxt]>>16)+(x2=p2)*(wt[cxt+1]>>16)+128)>>8;
}
void update(int y) {
assert(y==0 || y==1);
int err=((y<<12)-squash(pr));
if ((wt[cxt]&3)<3)
err*=4-(++wt[cxt]&3);
err=(err+8)>>4;
wt[cxt]+=x1*err&-4;
wt[cxt+1]+=x2*err;
}
};
// Mixer m(N, M, S=1, w=0) combines models using M neural networks with
// N inputs each, of which up to S may be selected. If S > 1 then
// the outputs of these neural networks are combined using another
// neural network (with parameters S, 1, 1). If S = 1 then the
// output is direct. The weights are initially w (+-32K).
// It is used as follows:
// m.update() trains the network where the expected output is the
// last bit (in the global variable y).
// m.add(stretch(p)) inputs prediction from one of N models. The
// prediction should be positive to predict a 1 bit, negative for 0,
// nominally +-256 to +-2K. The maximum allowed value is +-32K but
// using such large values may cause overflow if N is large.
// m.set(cxt, range) selects cxt as one of 'range' neural networks to
// use. 0 <= cxt < range. Should be called up to S times such
// that the total of the ranges is <= M.
// m.p() returns the output prediction that the next bit is 1 as a
// 12 bit number (0 to 4095).
// Vector product a*b of n signed words, returning signed integer scaled down by 8 bits.
// n is rounded up to a multiple of 8.
//static int dot_product (const short* const t, const short* const w, int n);
// Train n neural network weights w[n] on inputs t[n] and err.
// w[i] += ((t[i]*2*err)+(1<<16))>>17 bounded to +- 32K.
// n is rounded up to a multiple of 8.
//int mix1SK=0,mix1TO=0;
struct Mixer1 {
int N, M; // max inputs, max contexts, max context sets
short *tx; // N inputs from add()
short *wx ; // N*M weights
short *ptr;
int cxt; // S contexts
int pr; // last result (scaled 12 bits)
int shift1;
int elim;
int uperr;
int err;
int dot_product (const short* const t, const short* const w, int n) {
assert(n == ((n + 15) & -16));
YMM sum = _mm256_setzero_si256 ();
while ((n -= 16) >= 0) { // Each loop sums 16 products
YMM tmp = _mm256_madd_epi16 (*(YMM *) &t[n], *(YMM *) &w[n]); // t[n] * w[n] + t[n+1] * w[n+1]
tmp = _mm256_srai_epi32 (tmp, 8); // (t[n] * w[n] + t[n+1] * w[n+1]) >> 8
sum = _mm256_add_epi32 (sum, tmp); // sum += (t[n] * w[n] + t[n+1] * w[n+1]) >> 8
}
sum =_mm256_hadd_epi32(sum,_mm256_setzero_si256 ()); //add [1]=[1]+[2], [2]=[3]+[4], [3]=0, [4]=0, [5]=[5]+[6], [6]=[7]+[8], [7]=0, [8]=0
sum =_mm256_hadd_epi32(sum,_mm256_setzero_si256 ()); //add [1]=[1]+[2], [2]=0, [3]=0, [4]=0, [5]=[5]+[6], [6]=0, [7]=0, [8]=0
XMM lo = _mm256_extractf128_si256(sum, 0);
XMM hi = _mm256_extractf128_si256(sum, 1);
XMM newsum = _mm_add_epi32(lo, hi); //sum last two
return _mm_cvtsi128_si32(newsum);
}
void train (const short* const t, short* const w, int n, const int e) {
assert(n == ((n + 15) & -16));
if (e) {
const YMM one = _mm256_set1_epi16 (1);
const YMM err = _mm256_set1_epi16 (short(e));
while ((n -= 16) >= 0) { // Each iteration adjusts 16 weights
YMM tmp = _mm256_adds_epi16 (*(YMM *) &t[n], *(YMM *) &t[n]); // t[n] * 2
tmp = _mm256_mulhi_epi16 (tmp, err); // (t[n] * 2 * err) >> 16
tmp = _mm256_adds_epi16 (tmp, one); // ((t[n] * 2 * err) >> 16) + 1
tmp = _mm256_srai_epi16 (tmp, 1); // (((t[n] * 2 * err) >> 16) + 1) >> 1
tmp = _mm256_adds_epi16 (tmp, *(YMM *) &w[n]); // ((((t[n] * 2 * err) >> 16) + 1) >> 1) + w[n]
*(YMM *) &w[n] = tmp; // save the new eight weights, bounded to +- 32K
}
}
}
/*
// dot_product returns dot product t*w of n elements. n is rounded
// up to a multiple of 8. Result is scaled down by 8 bits.
int dot_product(short *t, short *w, int n) {
int sum=0;
n=(n+15)&-16;
for (int i=0; i<n; i+=2)
sum+=(t[i]*w[i]+t[i+1]*w[i+1]) >> 8;
return sum;
}
// Train neural network weights w[n] given inputs t[n] and err.
// w[i] += t[i]*err, i=0..n-1. t, w, err are signed 16 bits (+- 32K).
// err is scaled 16 bits (representing +- 1/2). w[i] is clamped to +- 32K
// and rounded. n is rounded up to a multiple of 8.
void train(short *t, short *w, int n, int err) {
n=(n+15)&-16;
for (int i=0; i<n; ++i) {
int wt=w[i]+(((t[i]*err*2>>16)+1)>>1);
if (wt<-32768) wt=-32768;
if (wt>32767) wt=32767;
w[i]=wt;
}
}
*/
// Adjust weights to minimize coding cost of last prediction
void __attribute__ ((noinline)) update(int y) {
err=((y<<12)-pr)*uperr/4;
if (err>32767)
err=32767;
if (err<-32768)
err=-32768;
if(err>=-elim && err<=elim) err=0;
train(&tx[0], &wx[cxt*N], N, err);
}
// predict next bit
int __attribute__ ((noinline)) p() {
assert(cxt>=0 && cxt<M);
int dp=dot_product(&tx[0], &wx[cxt*N], N)*shift1>>11;
return pr=squash(dp);
}
int __attribute__ ((noinline)) p1() {
assert(cxt>=0 && cxt<M);
int dp=dot_product(&tx[0], &wx[cxt*N], N)*shift1>>11;
if (dp<-2047) {
dp=-2047;
}
else if (dp>2047) {
dp=2047;
}
pr=squash(dp);
return dp;
}
void setTxWx(int n,short* mn) {
N=n;
alloc1(wx,(N*M)+32,ptr,32);
tx=mn;
// Set bias
for (int j=0; j<M*N; ++j) wx[j]=129;
}
void reset() {
for (int j=0; j<M*N; ++j) wx[j]=wx[j]*2;
}
void Init(int m, U32 s,U32 e,U32 ue) {
M=m, cxt=0, shift1=s,elim=e,uperr=ue;err=0;
pr=2048; //initial p=0.5
}
void Free() {
free(ptr);
}
void Print() {
// print N weights averaged over context
printf("Mixer(%d,%d): ", N, M);
for (int i=0; i<N; ++i) {
int w=0;
for (int j=0; j<M; ++j)
w+=wx[j*N+i];//,printf("%d ",wx[j*N+i]);;
printf("%d ", w/M);
}
printf("\n");
}
};
// A StateMap maps a context to a probability.
static int dt[1024]; // i -> 16K/(i+i+3)
// No update limit
struct StateMap {
int N; // Number of contexts
int cxt; // Context of last prediction
U32 *t; // cxt -> prediction in high 22 bits, count in low 10 bits
int pr;
const U8 *nn;
int next(int i, int y){
return nn[ y + i*4];
}
void __attribute__ ((noinline)) Init(int n, const U8 *nn1){
nn=nn1;
N=n, cxt=0, pr=2048;
assert(ispowerof2(n));
alloc(t,n);
for (int i=0; i<N; ++i){
U32 n0=next(i, 2)*3+1;
U32 n1=next(i, 3)*3+1;
t[i]=(((n1<<20) / (n0+n1)) << 12);
}
}
void Free() {
free(t);
}
inline void update() {
U32 *p=&t[cxt], p0=p[0];
int pr1=p0>>14; // count, prediction
p0+=(x.y<<18)-pr1;
p[0]=p0;
}
// update bit y (0..1), predict next bit in context cx
void set(const int c) {
assert(cxt>=0 && cxt<N);
update();
pr=t[cxt=c]>>20;
}
};
// With update limit
struct StateMap1 {
int N; // Number of contexts
int cxt; // Context of last prediction
U32 *t; // cxt -> prediction in high 22 bits, count in low 10 bits
int pr;
int mask;
int limit;
void __attribute__ ((noinline)) Init(int n, int lim) {
N=n, cxt=0, pr=2048, mask=n-1,limit=lim;
assert(ispowerof2(n));
alloc(t,n);
assert(limit>0 && limit<1024);
for (int i=0; i<N; ++i)
t[i]=1<<31;
}
void Free() {
free(t);
}
inline void update() {
U32 *p=&t[cxt], p0=p[0];
int n=p0&1023, pr1=p0>>12; // count, prediction
p0+=(n<limit);
p0+=(((((x.y<<20)-pr1)))*dt[n]+512)&0xfffffc00;
p[0]=p0;
}
// update bit y (0..1), predict next bit in context cx
void set(const int c) {
assert(cxt>=0 && cxt<N);
update();
pr=t[cxt=(c&mask)]>>20;
}
};
// A RunContextMap maps a context into the next byte and a repeat
// count up to M. Size should be a power of 2. Memory usage is 3M/4.
struct RunContextMap {
enum {B=4,M=4};
U8 *t; // hash t
U8 *ptr;
U8* cp;
short rc[512];
U8 tmp[B];
U32 n;
void Init(int m,int rcm_ml=8){
alloc1(t,m,ptr,64);
n=(m/B-1);
for (int r=0;r<B;r++) tmp[r]=0;
cp=&t[0]+1;
for (int r=0;r<256;r++) {
int c=ilog[r]*8;
if ((r&1)==0) c=c*rcm_ml/4;
rc[r+256]=clp(c);
rc[r]=clp(-c);
}
}
void Free() {
free(ptr);
}
void __attribute__ ((noinline)) set(U32 cx,U8 c1) { // update count
if (cp[0]==0) cp[0]=2, cp[1]=c1;
else if (cp[1]!=c1) cp[0]=1, cp[1]=c1;
else if (cp[0]<254) cp[0]=cp[0]+2;
cp=find(cx)+1;
}
int p() { // predict next bit
int b=x.c0shift_bpos ^ (cp[1] >> x.bposshift);
if (b<=1)
return rc[b*256+cp[0]];
else
return 0;
}
int mix() { // return run length
x.mxInputs1.add(p());
return cp[0]!=0;
}
inline U8* find(U32 i) {
U16 chk=(i>>16^i)&0xffff;
i=i*M&n;
U8 *p;
U16 *cp1;
int j;
for (j=0; j<M; ++j) {
p=&t[(i+j)*B];
cp1=(U16*)p;
if (p[2]==0) {*cp1=chk;break;}
if (*cp1==chk) break; // found
}
if (j==0) return p+1; // front
if (j==M) {
--j;
memset(&tmp, 0, B);
memmove(&tmp, &chk, 2);
if (M>2 && t[(i+j)*B+2]>t[(i+j-1)*B+2]) --j;
}
else memcpy(&tmp, cp1, B);
memmove(&t[(i+1)*B], &t[i*B], j*B);
memcpy(&t[i*B], &tmp, B);
return &t[i*B+1];
}
};
// Map for modelling contexts of (nearly-)stationary data.
// The context is looked up directly. For each bit modelled, a 16bit prediction is stored.
// The adaptation rate is controlled by the caller, see mix().
// - BitsOfContext: How many bits to use for each context. Higher bits are discarded.
// - InputBits: How many bits [1..8] of input are to be modelled for each context.
// New contexts must be set at those intervals.
// Uses (2^(BitsOfContext+1))*((2^InputBits)-1) bytes of memory.
int sscmrate=0;
struct SmallStationaryContextMap {
U16 *Data;
int Context, Mask, Stride, bCount, bTotal, B, N;
U16 *cp;
void __attribute__ ((noinline)) Init(int BitsOfContext, int InputBits=8) {
assert(InputBits>0 && InputBits<=8);
Context=0, Mask=(1<<BitsOfContext)-1,
Stride=(1<<InputBits)-1, bCount=0, bTotal=InputBits, B=0;
N=(1ull<<BitsOfContext)*((1ull<<InputBits)-1);
alloc(Data,N);
for (int i=0; i<N; ++i)
Data[i]=0x7FFF;
cp=&Data[0];
}
void Free() {
free(Data);
}
void set(U32 ctx) {
Context = (ctx&Mask)*Stride;
bCount=B=0;
}
void __attribute__ ((noinline)) mix(int r) {
int rate =r +7; const int Multiplier=1;const int Divisor=4;
*cp+=((x.y<<16)-(*cp)+(1<<(rate-1)))>>rate;
B+=(x.y && B>0);
cp = &Data[Context+B];
int Prediction = (*cp)>>4;
x.mxInputs1.add((stretch(Prediction)*Multiplier)/Divisor);
x.mxInputs1.add(((Prediction-2048)*Multiplier)/(Divisor*2));
prediction_index--;
bCount++; B+=B+1;
if (bCount==bTotal)
bCount=B=0;
}
};
// Context map for large contexts. Most modeling uses this type of context
// map. It includes a built in RunContextMap to predict the last byte seen
// in the same context, and also bit-level contexts that map to a bit
// history state.
//
// Bit histories are stored in a hash table. The table is organized into
// 64-byte buckets alinged on cache page boundaries. Each bucket contains
// a hash chain of 7 elements, plus a 2 element queue (packed into 1 byte)
// of the last 2 elements accessed for LRU replacement. Each element has
// a 2 byte checksum for detecting collisions, and an array of 7 bit history
// states indexed by the last 0 to 2 bits of context. The buckets are indexed
// by a context ending after 0, 2, or 5 bits of the current byte. Thus, each
// byte modeled results in 3 main memory accesses per context, with all other
// accesses to cache.
//
// On bits 0, 2 and 5, the context is updated and a new bucket is selected.
// The most recently accessed element is tried first, by comparing the
// 16 bit checksum, then the 7 elements are searched linearly. If no match
// is found, then the element with the lowest priority among the 5 elements
// not in the LRU queue is replaced. After a replacement, the queue is
// emptied (so that consecutive misses favor a LFU replacement policy).
// In all cases, the found/replaced element is put in the front of the queue.
//
// The priority is the state number of the first element (the one with 0
// additional bits of context). The states are sorted by increasing n0+n1
// (number of bits seen), implementing a LFU replacement policy.
//
// When the context ends on a byte boundary (bit 0), only 3 of the 7 bit
// history states are used. The remaining 4 bytes implement a run model
// as follows: <count:7,d:1> <b1> <unused> <unused> where <b1> is the last byte
// seen, possibly repeated. <count:7,d:1> is a 7 bit count and a 1 bit
// flag (represented by count * 2 + d). If d=0 then <count> = 1..127 is the
// number of repeats of <b1> and no other bytes have been seen. If d is 1 then
// other byte values have been seen in this context prior to the last <count>
// copies of <b1>.
//
// As an optimization, the last two hash elements of each byte (representing
// contexts with 2-7 bits) are not updated until a context is seen for
// a second time. This is indicated by <count,d> = <1,0> (2). After update,
// <count,d> is updated to <2,0> or <1,1> (4 or 3).
inline int sc(int p){
if (p>0) return p>>7;
return (p+127)>>7;// p+((1<<s)-1);
}
// A BH maps a 32 bit hash to an array of B bytes (checksum and B-2 values)
//
// BH bh(N); creates N element table with B bytes each.
// N must be a power of 2. The first byte of each element is
// reserved for a checksum to detect collisions. The remaining
// B-1 bytes are values, prioritized by the first value. This
// byte is 0 to mark an unused element.
//
// bh[i] returns a pointer to the i'th element, such that
// bh[i][0] is a checksum of i, bh[i][1] is the priority, and
// bh[i][2..B-1] are other values (0-255).
// The low lg(n) bits as an index into the table.
// If a collision is detected, up to M nearby locations in the same
// cache line are tested and the first matching checksum or
// empty element is returned.
// If no match or empty element is found, then the lowest priority
// element is replaced.
// 2 byte checksum with LRU replacement (except last 2 by priority)
template <const int A, const int B> // Warning: values 3, 7 for A are the only valid parameters
union E { // hash element, 64 bytes
struct{ // this is bad uc
U16 chk[A]; // byte context checksums
U8 last; // last 2 accesses (0-6) in low, high nibble
U8 bh[A][7]; // byte context, 3-bit context -> bit history state
// bh[][0] = 1st bit, bh[][1,2] = 2nd bit, bh[][3..6] = 3rd bit
// bh[][0] is also a replacement priority, 0 = empty
// U8* get(U16 chk); // Find element (0-6) matching checksum.
// If not found, insert or replace lowest priority (not last).
};
U8 pad[B] ;
__attribute__ ((noinline)) U8* get(U16 ch,int keep) {
if (chk[last&15]==ch) return &bh[last&15][0];
int b=0xffff, bi=0;
for (int i=0; i<A; ++i) {
if (chk[i]==ch) return last=last<<4|i, (U8*)&bh[i][0];
int pri=bh[i][0];
if (pri<b && (last&15)!=i && last>>4!=i) b=pri, bi=i;
}
return last=last<<4|bi|keep, chk[bi]=ch, (U8*)memset(&bh[bi][0], 0, 7);
}
};
inline U32 getStateByteLocation(const int bpos, const int c0) {
U32 pis = 0; //state byte position in slot
const U32 smask = (U32(0x31031010) >> (bpos << 2)) & 0x0F;
pis = smask + (c0 & smask);
return pis;
}
#define MAXCXT 8
short st2_p0[4096];
short st2_p1[4096];
short rcpr[512]; //2-6 0-4
bool doCMprint=false;
template <const int A, const int B> // Warning: values 3, 7 for A are the only valid parameters
union E1 { // hash element, 64 bytes
struct{ // this is bad uc
U16 chk[A]; // byte context checksums
U8 last; // last 2 accesses (0-6) in low, high nibble
U8 bh[A][7]; // byte context, 3-bit context -> bit history state
// bh[][0] = 1st bit, bh[][1,2] = 2nd bit, bh[][3..6] = 3rd bit
// bh[][0] is also a replacement priority, 0 = empty
// U8* get(U16 chk); // Find element (0-6) matching checksum.
// If not found, insert or replace lowest priority (not last).
};
U8 pad[B] ;
__attribute__ ((noinline)) U8* get(U16 ch,int keep) {
if (chk[last&15]==ch) return &bh[last&15][0];
int b=0xffff, bi=0;
for (int i=0; i<A; ++i) {
if (chk[i]==ch) return last=last<<4|i, (U8*)&bh[i][0];
int pri=bh[i][0];
if (pri<b && (last&15)!=i && last>>4!=i) b=pri, bi=i;
}
return last=last<<4|bi|keep, chk[bi]=ch, (U8*)memset(&bh[bi][0], 0, 7);
}
};
struct ContextMap3 {
int C; // max number of contexts
U8* cp[MAXCXT]; // C pointers to current bit history
U8* cp0[MAXCXT]; // First element of 7 element array containing cp[i]
U32 cxt[MAXCXT]; // C whole byte contexts (hashes)
U8* runp[MAXCXT]; // C [0..3] = count, value, unused, unused
int cn; // Next context to set by set()
int result;
short st1[4096];
short *st2;
short st32[256];
int cms,cms3,cms4;
int kep;
const U8 *nn;
E1<14,128> *ptr,*t; // Double sized BH
U32 tmask;
int skip2;
int skip3;
U16 cxtMask;
//state
int cxtn[MAXCXT]; // Context of last prediction
U32 *ts; // cxt -> prediction in high 22 bits, count in low 10 bits
int sti;
inline U8 next(int i, int y) {
return nn[ y + i*4];
}
inline int pre(const int state) {