-
Notifications
You must be signed in to change notification settings - Fork 0
/
pig_solver.hpp
3725 lines (3545 loc) · 116 KB
/
pig_solver.hpp
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
//
// Created by jinyuanfeng.
//
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <vector>
#include <set>
#include <cmath>
#include <omp.h>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <random>
#include <chrono>
#include <string.h>
using namespace std;
#ifdef OPENBLAS
#include <cblas.h>
#endif
#ifdef USE_SSE
#include <x86intrin.h>
#endif
#define ROUND_UP(x, s) (((x)+((s)-1)) & -(s))
#define ALIGN_WIDTH (8)
#define DIM0_ADDR(a) (a.begin()) //N
#define DIM1_ADDR(a) (*DIM0_ADDR(a)).begin() //C
#define DIM2_ADDR(a) (*DIM1_ADDR(a)).begin() //T
#define DIM3_ADDR(a) (*DIM2_ADDR(a)).begin() //H
#define DIM4_ADDR(a) (*DIM3_ADDR(a)).begin() //W
#define DIM0_SIZE(a) (a.size())
#define DIM1_SIZE(a) (*DIM0_ADDR(a)).size()
#define DIM2_SIZE(a) (*DIM1_ADDR(a)).size()
#define DIM3_SIZE(a) (*DIM2_ADDR(a)).size()
#define DIM4_SIZE(a) (*DIM3_ADDR(a)).size()
#define DIM1_R(a,index) (*(a.begin()+index))
#define DIM2_R(a,index0,index1) (*(DIM1_R(a,index0).begin()+index1))
#define DIM3_R(a,index0,index1,index2) (*(DIM2_R(a,index0,index1).begin()+index2))
#define DIM4_R(a,index0,index1,index2,index3) (*(DIM3_R(a,index0,index1,index2).begin()+index3))
#define DIM5_R(a,index0,index1,index2,index3,index4) (*(DIM4_R(a,index0,index1,index2,index3).begin()+index4))
inline void transpose4x4_SSE(float *A, float *B, const int lda, const int ldb) {
__m128 row1 = _mm_loadu_ps(&A[0*lda]);
__m128 row2 = _mm_loadu_ps(&A[1*lda]);
__m128 row3 = _mm_loadu_ps(&A[2*lda]);
__m128 row4 = _mm_loadu_ps(&A[3*lda]);
_MM_TRANSPOSE4_PS(row1, row2, row3, row4);
_mm_storeu_ps(&B[0*ldb], row1);
_mm_storeu_ps(&B[1*ldb], row2);
_mm_storeu_ps(&B[2*ldb], row3);
_mm_storeu_ps(&B[3*ldb], row4);
}
inline void transpose_block_SSE4x4(float *A, float *B, const int n, const int m, const int lda, const int ldb ,const int block_size) {
#pragma omp parallel for
for(int i=0; i<n; i+=block_size) {
for(int j=0; j<m; j+=block_size) {
int max_i2 = i+block_size < n ? i + block_size : n;
int max_j2 = j+block_size < m ? j + block_size : m;
for(int i2=i; i2<max_i2; i2+=4) {
for(int j2=j; j2<max_j2; j2+=4) {
transpose4x4_SSE(&A[i2*lda +j2], &B[j2*ldb + i2], lda, ldb);
}
}
}
}
}
template <class T, std::size_t I>
struct new_initializer_list
{
using type = std::initializer_list<typename new_initializer_list<T, I - 1>::type>;
};
template <class T>
struct new_initializer_list<T, 0>
{
using type = T;
};
template <class T, std::size_t I>
using new_initializer_list_t = typename new_initializer_list<T, I>::type;
template <typename T>
class OP;
namespace PS {
//Global Info
unsigned long global_mem_size=0;
unsigned long node_count=0;
unsigned long random_seed=666;
vector<void*> tensor_collector;
template <typename T>
void clean_tensor() {
//cout<<"clear extra tensor...."<<endl;
for(unsigned long i=0;i<tensor_collector.size();i++) {
T* tmp = (T*)tensor_collector[i];
if(tmp->get_id().substr(0,6) == "tensor") {
delete tmp;
}
}
tensor_collector.clear();
}
void seed(size_t value) {
srand(value);
}
void split(const string& s, vector<string>& tokens, char delim = ' ') {
tokens.clear();
auto string_find_first_not = [s, delim](size_t pos = 0) -> size_t {
for (size_t i = pos; i < s.size(); i++) {
if (s[i] != delim) return i;
}
return string::npos;
};
size_t lastPos = string_find_first_not(0);
size_t pos = s.find(delim, lastPos);
while (lastPos != string::npos) {
tokens.emplace_back(s.substr(lastPos, pos - lastPos));
lastPos = string_find_first_not(pos);
pos = s.find(delim, lastPos);
}
}
double generateRandomNoise() {
return rand() % (1000) / (float)(1000);
}
double generateGaussianNoise(double mu, double sigma)
{
const double epsilon = std::numeric_limits<double>::min();
const double two_pi = 2.0*3.14159265358979323846;
static double z0, z1;
static bool generate;
generate = !generate;
if (!generate)
return z1 * sigma + mu;
double u1, u2;
do
{
u1 = rand() * (1.0 / RAND_MAX);
u2 = rand() * (1.0 / RAND_MAX);
}
while ( u1 <= epsilon );
z0 = sqrt(-2.0 * log(u1)) * cos(two_pi * u2);
z1 = sqrt(-2.0 * log(u1)) * sin(two_pi * u2);
return z0 * sigma + mu;
}
template<typename T>
class NStorage {
private:
T *handle;
unsigned long mem_size;
public:
NStorage();
NStorage(const NStorage<T> &t);
~NStorage() = default;
void set_handle(T* new_handle);
void set_mem_size(unsigned long new_mem_size);
T *get_handle();
unsigned long get_mem_size();
T* copy();
void alloc(unsigned int size);
void exalloc(unsigned int size);
T read(unsigned int pos);
int write(unsigned int pos, T value);
int addself(unsigned int pos, T value);
void set(T value);
void set_random();
void release();
int continuous_copy_5(const vector<size_t> &axis_weight, const vector<size_t> &map_index,
const vector<size_t> &dims);
int continuous_copy_4(const vector<size_t> &axis_weight, const vector<size_t> &map_index,
const vector<size_t> &dims);
int continuous_copy_3(const vector<size_t> &axis_weight, const vector<size_t> &map_index,
const vector<size_t> &dims);
int continuous_copy_2(const vector<size_t> &axis_weight, const vector<size_t> &map_index,
const vector<size_t> &dims);
int continuous_copy_1(const vector<size_t> &axis_weight, const vector<size_t> &map_index,
const vector<size_t> &dims);
};
class NShape {
private:
vector<size_t> axis_weight;
vector<size_t> map_index;
vector<size_t> dims;
unsigned long dims_product = 1;
unsigned long sub_dims_product = 1;
public:
bool is_continuous;
NShape();
NShape(const NShape &t);
~NShape() = default;
NShape(vector<size_t> params);
void init_map_index();
void init_axis_weight(const vector<size_t> ¶ms);
void change_axis(const vector<size_t> ¶ms);
void refresh_attribute();
void refresh_map_index();
void refresh_axis_weight(const vector<size_t> ¶ms);
long get_index(const vector<size_t> ¶ms);
int reshape(const vector<size_t> ¶ms);
vector<size_t> get_axis_weight();
vector<size_t> get_map_index();
vector<size_t> get_dims();
size_t get_dims(int axis);
unsigned long get_dims_product();
unsigned long get_sub_dims_product();
void show_dims();
void show_map_index();
void show_axis_weight();
void reset();
static void p_vector(size_t v) {
cout << v << " ";
}
};
template<typename T>
class NMatrix {
private:
NStorage<T> storage;
NShape visitor;
public:
NMatrix();
~NMatrix() = default;
NMatrix(const NMatrix<T> &t);
NMatrix(const new_initializer_list_t<T, 1> &t);
NMatrix(const new_initializer_list_t<T, 2> &t);
NMatrix(const new_initializer_list_t<T, 3> &t);
NMatrix(const new_initializer_list_t<T, 4> &t);
NMatrix(const new_initializer_list_t<T, 5> &t);
void clear();
void create(const vector<size_t> &t);
void save_data(string file_path);
void load_data(string file_path, size_t data_length,const vector<size_t> &t);
NMatrix<T> copy();
bool is_empty();
T get(const vector<size_t> &query_list);
T get(size_t pos);
void set(size_t pos, T value);
void set(const vector<size_t> &query_list, T value);
void set_value(T value);
void set_random();
void kaiming_normal_init(); //fout,relu
void normal_init(double mu,double sigma);
void addself(const vector<size_t> &query_list, T value);
void addself(size_t pos, T value);
void shape();
void map_index();
void axis_weight();
void enable_continuous();
void chg_axis(const vector<size_t> &query_list, bool en_continuous = false);
void reshape(const vector<size_t> &query_list);
bool check_dims_consistency(const vector<size_t> &a, const vector<size_t> &b);
bool check_dims_consistency_dot(const vector<size_t> &a, const vector<size_t> &b);
void fill_data(vector<size_t> dim_index, NMatrix<T> &a);
size_t get_dims(int axis);
vector<size_t> get_dims();
T get_local_max_2D(size_t n_index, size_t c_index, size_t s_h,size_t s_w,size_t h_size,size_t w_size,size_t *pos_w_h);
//viusal data
void basic_dim1(T *addr, size_t w);
void basic_dim2(T *addr, size_t h, size_t w);
void basic_dim3(T *addr, size_t t, size_t h, size_t w);
void basic_dimN(T *addr, const vector<size_t> &dims);
void show();
//define calculate
void basic_dot_omp(T *op1, T *op2, T *out, size_t rows, size_t cols, size_t K);
void basic_dot(T *op1, T *op2, T *out, size_t rows, size_t cols, size_t K);
NMatrix<T> transpose();
NMatrix<T> padding(vector<size_t> pad_list);
NMatrix<T> unpadding(vector<size_t> pad_list);
//add c = a+b
NMatrix<T> operator+(NMatrix<T> &a);
NMatrix<T> operator+(T a);
//sub
NMatrix<T> operator-(NMatrix<T> &a);
NMatrix<T> operator-(T a);
//mul
NMatrix<T> operator*(NMatrix<T> &a);
NMatrix<T> operator*(T a);
//div
NMatrix<T> operator/(NMatrix<T> &a);
NMatrix<T> operator/(T a);
//exp
NMatrix<T> exp();
//log
NMatrix<T> log();
//add_inplace a=a+b
void add_inplace(NMatrix<T> &a);
// a.inverse == 1/a
NMatrix<T> inverse();
// a.inverse_square == -1/a^2
NMatrix<T> inverse_square();
// a.pow(size_t n) == a^n
NMatrix<T> pow(size_t n);
// a.abs() == |a|
NMatrix<T> nabs();
// inflate [N,1,H,W]->[N,C,H,W]
NMatrix<T> inflate(size_t axis,size_t n);
// reduce [N,C,H,W]->[N,1,H,W]
NMatrix<T> reduce(size_t axis);
NMatrix<T> dot(NMatrix<T> &a);
NMatrix<T> img2col(vector<size_t> khw_size,int c_in,int stride_h,int stride_w,bool padding,unsigned long *newhw);
void col2img(vector<size_t> khw_size,int c_in,int stride_h,int stride_w,bool padding,unsigned long *newhw,NMatrix<T> &img2col_nmatrix);
};
template <typename T>
class NTensor:public NMatrix<T>{
private:
string id;
public:
NMatrix<T> grad;
OP<T> *parent_op;
bool requires_grad;
void init_tensor(string name) {
PS::node_count++;
if (name!="") {
id="params_"+to_string(PS::node_count)+"_"+name;
}else {
id = "tensor" + to_string(PS::node_count);
}
parent_op= nullptr;
requires_grad= false;
}
NTensor(string name=""){
init_tensor(name);
};
~NTensor()=default;
NTensor(const new_initializer_list_t<T, 1> &t):NMatrix<T>(t){
init_tensor("");
};
NTensor(const new_initializer_list_t<T, 2> &t):NMatrix<T>(t){
init_tensor("");
};
NTensor(const new_initializer_list_t<T, 3> &t):NMatrix<T>(t){
init_tensor("");
};
NTensor(const new_initializer_list_t<T, 4> &t):NMatrix<T>(t){
init_tensor("");
};
NTensor(const new_initializer_list_t<T, 5> &t):NMatrix<T>(t){
init_tensor("");
};
NTensor(const NMatrix<T> &t):NMatrix<T>(t){
init_tensor("");
}
NTensor<T> dcopy(){
NTensor<T> out(this->copy());
return out;
}
string get_id(){
return id;
}
void * operator new(size_t size)
{
void * p = ::new NTensor<T>();
tensor_collector.push_back(p);
return p;
}
void operator delete(void * p)
{
NTensor<T> * tmp = (NTensor<T>*)p;
tmp->parent_op= nullptr;
tmp->id="";
if(tmp->grad.is_empty()) {
;
}else {
tmp->grad.clear();
}
tmp->clear();
free(tmp);
}
//BP
void bp(NMatrix<T> from_grad=NMatrix<T> ()){
if(from_grad.is_empty()){
from_grad = this->copy();
from_grad.set_value(1);
grad=from_grad.copy();
}
if (parent_op!= nullptr){
vector<NMatrix<T>> next_grad = parent_op->backward(from_grad);
vector<NTensor<T>*> pt = parent_op->get_context();
for(int i=0; i<next_grad.size();i++){
if(pt[i]->requires_grad) {
if (isnan(next_grad[i].get(0))) {
cout<< pt[i]->get_id()<<endl;
}
if (pt[i]->grad.is_empty()) {
pt[i]->grad = pt[i]->copy();
pt[i]->grad.set_value(0);
pt[i]->grad.add_inplace(next_grad[i]);
} else {
pt[i]->grad.add_inplace(next_grad[i]);
}
}
pt[i]->bp(next_grad[i]);
}
parent_op->clear_context();
}else{
from_grad.clear();
return;
}
}
};
template <typename T>
class NImageData {
private:
vector<vector<string>> dataset;
public:
size_t dataset_size;
vector<size_t> image_shape;
vector<int> data_index;
size_t img_size=1;
int b_size;
NImageData(string meta_file_path,int batch_size,vector<size_t> img_shape) {
//load meta_file
ifstream ifs(meta_file_path,ios::in);
if(!ifs.good()) {
cout<<"file not exists"<<endl;
exit(-1);
}
string str;
int cnt=0;
while(getline(ifs,str)){
vector<string> items;
PS::split(str,items,' ');
//cout<<items[0].size()<<" "<<items[1].size()<<endl;
dataset.push_back(items);
data_index.push_back(cnt);
cnt++;
}
ifs.close();
image_shape = img_shape;
b_size = batch_size;
dataset_size = dataset.size();
for(auto v:image_shape) {
img_size*=v;
}
if(data_index.size()==dataset_size) {
cout << "Load Dataset Size: " << dataset_size << endl;
cout << "Dataset Tail Index: "<<data_index[dataset_size-1]<<endl;
}
}
~NImageData()=default;
vector<vector<int>> get_batch_id_generator() {
vector<vector<int>> batch_id;
shuffle(data_index.begin(),data_index.end(),default_random_engine(PS::random_seed));
int seg_num = dataset_size/b_size;
for(int i=0;i<seg_num;i++) {
batch_id.push_back(vector<int>(data_index.begin()+i*b_size,data_index.begin()+i*b_size+b_size));
}
if (dataset_size%b_size !=0) {
batch_id.push_back(vector<int>(data_index.begin()+seg_num*b_size,data_index.end()));
}
return batch_id;
}
vector<NMatrix<T>> get_batch_data(vector<int>& batch_id) {//N,H,W,C
size_t N = batch_id.size();
vector<size_t> out_shape({N});
for(auto v: image_shape) {
out_shape.push_back(v);
}
NMatrix<T> data;
data.create(out_shape);
NMatrix<T> label;
label.create({N,1});
for(size_t i=0;i<N;i++) {
//cout<<dataset[batch_id[i]][0]<<" "<<stof(dataset[batch_id[i]][1])<<endl;
NMatrix<T> tmp;
tmp.load_data(dataset[batch_id[i]][0],img_size,image_shape); //HWC
data.fill_data({i},tmp);
float label_value = stof(dataset[batch_id[i]][1]);
label.set({i,0},label_value);
tmp.clear();
}
return {data,label};
};
};
template <typename T>
class NOptimizer {
float lr;
vector<PS::NTensor<T>*> *m_params;
public:
NOptimizer( vector<PS::NTensor<T>*> *model_params, float learning_rate) {
m_params = model_params;
lr = learning_rate;
}
void set_zero_grad() {
for(PS::NTensor<T>* v:(*m_params)) {
v->grad.set_value(0);
}
}
void show_model_params_info() {
for(PS::NTensor<T>* v:(*m_params)) {
cout<<"NAME: "<<v->get_id()<<" ";
cout<<"DATA Shape: ";
v->shape();
if(!(v->grad.is_empty())) {
cout<<"Grad Shape: ";
v->grad.shape();
}
}
}
void step() {
for(int i=0;i<(*m_params).size();i++) {
PS::NTensor<T> *v = (*m_params)[i];
//cout<<v->get_id()<<endl;
auto tmp = (v->grad) * (lr);
v->add_inplace(tmp);
tmp.clear();
}
}
};
};
//Implemention of NStorage
template <typename T>
PS::NStorage<T>::NStorage() {
handle= nullptr;
mem_size=0;
}
template <typename T>
PS::NStorage<T>::NStorage(const NStorage<T> &t){
handle = t.handle;
mem_size = t.mem_size;
}
template <typename T>
T* PS::NStorage<T>::copy(){
T * new_handle = (T*)malloc(sizeof(T)*(mem_size));
PS::global_mem_size +=sizeof(T)*(mem_size);
memcpy(new_handle,handle,sizeof(T)*(mem_size));
return new_handle;
}
template <typename T>
void PS::NStorage<T>::set_handle(T* new_handle){
handle=new_handle;
}
template <typename T>
void PS::NStorage<T>::set_mem_size(unsigned long new_mem_size){
mem_size=new_mem_size;
}
template <typename T>
unsigned long PS::NStorage<T>::get_mem_size(){
return mem_size;
}
template <typename T>
void PS::NStorage<T>::alloc(unsigned int size){
mem_size = size;
handle = (T*)malloc(sizeof(T)*size);
PS::global_mem_size +=sizeof(T)*size;
memset(handle,0,sizeof(T)*mem_size);
}
template <typename T>
void PS::NStorage<T>::exalloc(unsigned int size){
PS::global_mem_size-=mem_size*sizeof(T);
PS::global_mem_size+=size*sizeof(T);
mem_size = size;
handle = (T*) realloc(handle,sizeof(T)*size);
}
template <typename T>
T PS::NStorage<T>::read(unsigned int pos){
return *(handle+pos);
}
template <typename T>
int PS::NStorage<T>::write(unsigned int pos,T value){
*(handle+pos)=value;
return 0;
}
template <typename T>
int PS::NStorage<T>::addself(unsigned int pos, T value) {
*(handle + pos) = *(handle + pos) + value;
return 0;
}
template <typename T>
void PS::NStorage<T>::set(T value){
fill(handle,handle+mem_size,value);
}
template <typename T>
void PS::NStorage<T>::set_random(){
for(size_t i= 0;i<mem_size;i++) {
T v = (T)PS::generateRandomNoise();
*(handle + i)=v;
}
}
template <typename T>
int PS::NStorage<T>::continuous_copy_5(const vector<size_t> &axis_weight,const vector<size_t> &map_index,const vector<size_t> &dims){
T* new_handle = (T*)malloc(sizeof(T)*mem_size);
memset(new_handle,0,sizeof(T)*mem_size);
long index = 0;
long dst_index=0;
long dims_size = dims.size();
for(int i=0;i<dims[map_index[0]];i++){
for(int j=0;j<dims[map_index[1]];j++){
for(int k=0;k<dims[map_index[2]];k++){
for(int l=0;l<dims[map_index[3]];l++){
for(int m=0;m<dims[map_index[4]];m++){
index = i*axis_weight[dims_size-map_index[0]-1]+
j*axis_weight[dims_size-map_index[1]-1]+
k*axis_weight[dims_size-map_index[2]-1]+
l*axis_weight[dims_size-map_index[3]-1]+
m*axis_weight[dims_size-map_index[4]-1];
*(new_handle+dst_index) = read(index);
dst_index++;
}
}
}
}
}
free(handle);
handle=new_handle;
return 0;
}
template <typename T>
int PS::NStorage<T>::continuous_copy_4(const vector<size_t> &axis_weight,const vector<size_t> &map_index,const vector<size_t> &dims){
T* new_handle = (T*)malloc(sizeof(T)*mem_size);
memset(new_handle,0,sizeof(T)*mem_size);
long index = 0;
long dst_index=0;
long dims_size = dims.size();
for(int i=0;i<dims[map_index[0]];i++){
for(int j=0;j<dims[map_index[1]];j++){
for(int k=0;k<dims[map_index[2]];k++){
for(int l=0;l<dims[map_index[3]];l++){
index = i*axis_weight[dims_size-map_index[0]-1]+
j*axis_weight[dims_size-map_index[1]-1]+
k*axis_weight[dims_size-map_index[2]-1]+
l*axis_weight[dims_size-map_index[3]-1];
*(new_handle+dst_index) = read(index);
dst_index++;
}
}
}
}
free(handle);
handle=new_handle;
return 0;
}
template <typename T>
int PS::NStorage<T>::continuous_copy_3(const vector<size_t> &axis_weight,const vector<size_t> &map_index,const vector<size_t> &dims){
T* new_handle = (T*)malloc(sizeof(T)*mem_size);
memset(new_handle,0,sizeof(T)*mem_size);
long index = 0;
long dst_index=0;
long dims_size = dims.size();
for(int i=0;i<dims[map_index[0]];i++){
for(int j=0;j<dims[map_index[1]];j++){
for(int k=0;k<dims[map_index[2]];k++){
index = i*axis_weight[dims_size-map_index[0]-1]+
j*axis_weight[dims_size-map_index[1]-1]+
k*axis_weight[dims_size-map_index[2]-1];
*(new_handle+dst_index) = read(index);
dst_index++;
}
}
}
free(handle);
handle=new_handle;
return 0;
}
template <typename T>
int PS::NStorage<T>::continuous_copy_2(const vector<size_t> &axis_weight,const vector<size_t> &map_index,const vector<size_t> &dims){
T* new_handle = (T*)malloc(sizeof(T)*mem_size);
memset(new_handle,0,sizeof(T)*mem_size);
long index = 0;
long dst_index=0;
long dims_size = dims.size();
unsigned long i_size = dims[map_index[0]]; // dims[1]
unsigned long j_size = dims[map_index[1]]; // dims[0]
unsigned long i_prefix = axis_weight[dims_size-map_index[0]-1];
unsigned long j_prefix = axis_weight[dims_size-map_index[1]-1];
int i,j;
for (i = 0; i < i_size; i++) {
for (j = 0; j < j_size; j++) {
index = i * i_prefix + j * j_prefix;
*(new_handle + dst_index) = *(handle + index);
dst_index++;
}
}
free(handle);
handle=new_handle;
return 0;
}
template <typename T>
int PS::NStorage<T>::continuous_copy_1(const vector<size_t> &axis_weight,const vector<size_t> &map_index,const vector<size_t> &dims){
T* new_handle = (T*)malloc(sizeof(T)*mem_size);
memset(new_handle,0,sizeof(T)*mem_size);
long index = 0;
long dst_index=0;
long dims_size = dims.size();
for(int i=0;i<dims[map_index[0]];i++){
index = i*axis_weight[dims_size-map_index[0]-1];
*(new_handle+dst_index) = read(index);
dst_index++;
}
free(handle);
handle=new_handle;
return 0;
}
template <typename T>
void PS::NStorage<T>::release(){
PS::global_mem_size-=sizeof(T)*mem_size;
free(handle);
mem_size=0;
}
template <typename T>
T* PS::NStorage<T>::get_handle(){
return handle;
}
//Implemention of NShape
PS::NShape::NShape() {
dims_product = 1;
is_continuous = true;
sub_dims_product = 1;
}
PS::NShape::NShape(const NShape&t){
axis_weight = t.axis_weight;
map_index = t.map_index;
dims = t.dims;
dims_product = t.dims_product;
is_continuous = t.is_continuous;
sub_dims_product = t.sub_dims_product;
}
PS::NShape::NShape(vector<size_t> params){
is_continuous = true;
dims=params; //dims={axis0_size,axis1_size,...}
init_axis_weight(params);
init_map_index();
for(int i=0;i<params.size()-1;i++){
dims_product*=params[i];
sub_dims_product*=params[i];
}
dims_product*=params[params.size()-1];
}
void PS::NShape::init_map_index(){
for(int i=0;i<dims.size();i++){
map_index.push_back(i); //0,1,2,3,4
}
}
void PS::NShape::init_axis_weight(const vector<size_t> ¶ms){
if(params.size()!=1){ // >=2
axis_weight.push_back(1);
int tmp = params[params.size()-1];
axis_weight.push_back(tmp);
for(int i=params.size()-2;i>0;i--){
tmp*=params[i];
axis_weight.push_back(tmp);
}
}else{//==1
axis_weight.push_back(1);
}
}
void PS::NShape::change_axis(const vector<size_t> ¶ms){
is_continuous = false;
ostringstream oss;
try {
//check params size
if (params.size() != map_index.size()) {
oss << "params size != map_index size " <<"info: map_index size("<< map_index.size() << ") params size(" << params.size() <<")"<<endl;
throw oss.str();
}
//check param repeat value
set<size_t> s(params.begin(), params.end());
if (s.size() != params.size()) {
oss << "exist repeat value" << endl;
throw oss.str();
}
//check value limit
for (auto v:params) {
if (v >= params.size()) {
oss << "value exceeds limits " << "info: max value("<<params.size() - 1 <<")"<<endl;
throw oss.str();
}
}
}catch (string e){
cout<<"[CLASS:NShape FUNC:change_axis]=> "<<e<<endl;
exit(-1);
}
map_index.assign(params.begin(),params.end());
}
void PS::NShape::refresh_attribute(){
vector<size_t> new_dims;
for(int i=0;i<map_index.size();i++){
new_dims.push_back(dims[map_index[i]]);
}
dims=new_dims;
// cout<<"refresh_dims"<<endl;
// for_each(dims.begin(),dims.end(), p_vector);
// cout<<endl;
refresh_map_index();
refresh_axis_weight(dims);
}
void PS::NShape::refresh_map_index(){
for(int i=0;i<dims.size();i++){
map_index[i]=i; //0,1,2,3,4
}
// cout<<"refresh_map_index"<<endl;
// for_each(map_index.begin(),map_index.end(), p_vector);
// cout<<endl;
}
void PS::NShape::refresh_axis_weight(const vector<size_t> ¶ms){
axis_weight.clear();
if(params.size()!=1){ // >=2
axis_weight.push_back(1);
int tmp = params[params.size()-1];
axis_weight.push_back(tmp);
for(int i=params.size()-2;i>0;i--){
tmp*=params[i];
axis_weight.push_back(tmp);
}
}else{//==1
axis_weight.push_back(1);
}
// cout<<"refresh_axis_weight"<<endl;
// for_each(axis_weight.begin(),axis_weight.end(), p_vector);
// cout<<endl;
}
long PS::NShape::get_index(const vector<size_t> ¶ms){
ostringstream oss;
try{
if (params.size()!=axis_weight.size()) {
oss<<"params list size != axis_weight size"<<endl;
throw oss.str();
}else{
long ret = 0;
vector<size_t>::iterator iter_axis_weight = axis_weight.begin();
for(int i = 0; i<params.size();i++){
if (params[i]>=dims[map_index[i]]){
oss<<"axis exceeds limit !!! "<<"info: axis("<<i<<") "<<"input("<<params[i]<<") exceeds limit of ("<<dims[map_index[i]]<<")"<<endl;
throw oss.str();
}
ret += params[i]*iter_axis_weight[params.size()-map_index[i]-1];
}
return ret;
}
}catch (string e){
cout<<"[CLASS:NShape FUNC:get_index]=> "<<e<<endl;
exit(-1);
}
return 0;
}
int PS::NShape::reshape(const vector<size_t> ¶ms){
ostringstream oss;
//check dims
try {
int new_dims = 1;
for (auto v:params) {
new_dims *= v;
}
if (new_dims != dims_product) {
oss<<"don't equal dims_prodcut!!! "<<"info: dims_product("<<dims_product<<")"<<endl;
throw oss.str();
}
}catch (string e){
cout<<"[CLASS:NShape FUNC:reshape]=> "<<e<<endl;
exit(-1);
}
//强制连续
//重置shape
axis_weight.clear();
dims.clear();
map_index.clear();
dims=params;
init_axis_weight(params);
init_map_index();
return 0;
}
vector<size_t> PS::NShape::get_axis_weight(){
return axis_weight;
}
vector<size_t> PS::NShape::get_map_index(){
return map_index;
}
vector<size_t> PS::NShape::get_dims(){
return dims;
}
size_t PS::NShape::get_dims(int axis){
return dims[axis];
}
unsigned long PS::NShape::get_sub_dims_product(){
return sub_dims_product;
}
unsigned long PS::NShape::get_dims_product(){
return dims_product;
}
void PS::NShape::show_dims(){
cout<<"dims: [";
for(int i=0;i<dims.size()-1;i++){
cout<<dims[map_index[i]]<<",";
}
cout<<dims[map_index[dims.size()-1]]<<"]"<<endl;
}
void PS::NShape::show_map_index(){
cout<<"map_index: [";
for(int i=0;i<map_index.size()-1;i++){
cout<<map_index[i]<<",";