-
Notifications
You must be signed in to change notification settings - Fork 80
/
mf.cpp
4678 lines (4195 loc) · 145 KB
/
mf.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
#include <algorithm>
#include <cmath>
#include <condition_variable>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <memory>
#include <numeric>
#include <queue>
#include <random>
#include <stdexcept>
#include <string>
#include <thread>
#include <unordered_set>
#include <vector>
#include <limits>
#include "mf.h"
#if defined USESSE
#include <pmmintrin.h>
#endif
#if defined USEAVX
#include <immintrin.h>
#endif
#if defined USEOMP
#include <omp.h>
#endif
namespace mf
{
using namespace std;
namespace // unnamed namespace
{
mf_int const kALIGNByte = 32;
mf_int const kALIGN = kALIGNByte/sizeof(mf_float);
//--------------------------------------
//---------Scheduler of Blocks----------
//--------------------------------------
class Scheduler
{
public:
Scheduler(mf_int nr_bins, mf_int nr_threads, vector<mf_int> cv_blocks);
mf_int get_job();
mf_int get_bpr_job(mf_int first_block, bool is_column_oriented);
void put_job(mf_int block, mf_double loss, mf_double error);
void put_bpr_job(mf_int first_block, mf_int second_block);
mf_double get_loss();
mf_double get_error();
mf_int get_negative(mf_int first_block, mf_int second_block,
mf_int m, mf_int n, bool is_column_oriented);
void wait_for_jobs_done();
void resume();
void terminate();
bool is_terminated();
private:
mf_int nr_bins;
mf_int nr_threads;
mf_int nr_done_jobs;
mf_int target;
mf_int nr_paused_threads;
bool terminated;
vector<mf_int> counts;
vector<mf_int> busy_p_blocks;
vector<mf_int> busy_q_blocks;
vector<mf_double> block_losses;
vector<mf_double> block_errors;
vector<minstd_rand0> block_generators;
unordered_set<mf_int> cv_blocks;
mutex mtx;
condition_variable cond_var;
default_random_engine generator;
uniform_real_distribution<mf_float> distribution;
priority_queue<pair<mf_float, mf_int>,
vector<pair<mf_float, mf_int>>,
greater<pair<mf_float, mf_int>>> pq;
};
Scheduler::Scheduler(mf_int nr_bins, mf_int nr_threads,
vector<mf_int> cv_blocks)
: nr_bins(nr_bins),
nr_threads(nr_threads),
nr_done_jobs(0),
target(nr_bins*nr_bins),
nr_paused_threads(0),
terminated(false),
counts(nr_bins*nr_bins, 0),
busy_p_blocks(nr_bins, 0),
busy_q_blocks(nr_bins, 0),
block_losses(nr_bins*nr_bins, 0),
block_errors(nr_bins*nr_bins, 0),
cv_blocks(cv_blocks.begin(), cv_blocks.end()),
distribution(0.0, 1.0)
{
for(mf_int i = 0; i < nr_bins*nr_bins; ++i)
{
if(this->cv_blocks.find(i) == this->cv_blocks.end())
pq.emplace(distribution(generator), i);
block_generators.push_back(minstd_rand0(rand()));
}
}
mf_int Scheduler::get_job()
{
bool is_found = false;
pair<mf_float, mf_int> block;
while(!is_found)
{
lock_guard<mutex> lock(mtx);
vector<pair<mf_float, mf_int>> locked_blocks;
mf_int p_block = 0;
mf_int q_block = 0;
while(!pq.empty())
{
block = pq.top();
pq.pop();
p_block = block.second/nr_bins;
q_block = block.second%nr_bins;
if(busy_p_blocks[p_block] || busy_q_blocks[q_block])
locked_blocks.push_back(block);
else
{
busy_p_blocks[p_block] = 1;
busy_q_blocks[q_block] = 1;
counts[block.second] += 1;
is_found = true;
break;
}
}
for(auto &block1 : locked_blocks)
pq.push(block1);
}
return block.second;
}
mf_int Scheduler::get_bpr_job(mf_int first_block, bool is_column_oriented)
{
lock_guard<mutex> lock(mtx);
mf_int another = first_block;
vector<pair<mf_float, mf_int>> locked_blocks;
while(!pq.empty())
{
pair<mf_float, mf_int> block = pq.top();
pq.pop();
mf_int p_block = block.second/nr_bins;
mf_int q_block = block.second%nr_bins;
auto is_rejected = [&] ()
{
if(is_column_oriented)
return first_block%nr_bins != q_block ||
busy_p_blocks[p_block];
else
return first_block/nr_bins != p_block ||
busy_q_blocks[q_block];
};
if(is_rejected())
locked_blocks.push_back(block);
else
{
busy_p_blocks[p_block] = 1;
busy_q_blocks[q_block] = 1;
another = block.second;
break;
}
}
for(auto &block : locked_blocks)
pq.push(block);
return another;
}
void Scheduler::put_job(mf_int block_idx, mf_double loss, mf_double error)
{
// Return the held block to the scheduler
{
lock_guard<mutex> lock(mtx);
busy_p_blocks[block_idx/nr_bins] = 0;
busy_q_blocks[block_idx%nr_bins] = 0;
block_losses[block_idx] = loss;
block_errors[block_idx] = error;
++nr_done_jobs;
mf_float priority =
(mf_float)counts[block_idx]+distribution(generator);
pq.emplace(priority, block_idx);
++nr_paused_threads;
// Tell others that a block is available again.
cond_var.notify_all();
}
// Wait if nr_done_jobs (aka the number of processed blocks) is too many
// because we want to print out the training status roughly once all blocks
// are processed once. This is the only place that a solver thread should
// wait for something.
{
unique_lock<mutex> lock(mtx);
cond_var.wait(lock, [&] {
return nr_done_jobs < target;
});
}
// Nothing is blocking and this thread is going to take another block
{
lock_guard<mutex> lock(mtx);
--nr_paused_threads;
}
}
void Scheduler::put_bpr_job(mf_int first_block, mf_int second_block)
{
if(first_block == second_block)
return;
lock_guard<mutex> lock(mtx);
{
busy_p_blocks[second_block/nr_bins] = 0;
busy_q_blocks[second_block%nr_bins] = 0;
mf_float priority =
(mf_float)counts[second_block]+distribution(generator);
pq.emplace(priority, second_block);
}
}
mf_double Scheduler::get_loss()
{
lock_guard<mutex> lock(mtx);
return accumulate(block_losses.begin(), block_losses.end(), 0.0);
}
mf_double Scheduler::get_error()
{
lock_guard<mutex> lock(mtx);
return accumulate(block_errors.begin(), block_errors.end(), 0.0);
}
mf_int Scheduler::get_negative(mf_int first_block, mf_int second_block,
mf_int m, mf_int n, bool is_column_oriented)
{
mf_int rand_val = (mf_int)block_generators[first_block]();
auto gen_random = [&] (mf_int block_id)
{
mf_int v_min, v_max;
if(is_column_oriented)
{
mf_int seg_size = (mf_int)ceil((double)m/nr_bins);
v_min = min((block_id/nr_bins)*seg_size, m-1);
v_max = min(v_min+seg_size, m-1);
}
else
{
mf_int seg_size = (mf_int)ceil((double)n/nr_bins);
v_min = min((block_id%nr_bins)*seg_size, n-1);
v_max = min(v_min+seg_size, n-1);
}
if(v_max == v_min)
return v_min;
else
return rand_val%(v_max-v_min)+v_min;
};
if(rand_val % 2)
return (mf_int)gen_random(first_block);
else
return (mf_int)gen_random(second_block);
}
void Scheduler::wait_for_jobs_done()
{
unique_lock<mutex> lock(mtx);
// The first thing the main thread should wait for is that solver threads
// process enough matrix blocks.
// [REVIEW] Is it really needed? Solver threads automatically stop if they
// process too many blocks, so the next wait should be enough for stopping
// the main thread when nr_done_job is not enough.
cond_var.wait(lock, [&] {
return nr_done_jobs >= target;
});
// Wait for all threads to stop. Once a thread realizes that all threads
// have processed enough blocks it should stop. Then, the main thread can
// print values safely.
cond_var.wait(lock, [&] {
return nr_paused_threads == nr_threads;
});
}
void Scheduler::resume()
{
lock_guard<mutex> lock(mtx);
target += nr_bins*nr_bins;
cond_var.notify_all();
}
void Scheduler::terminate()
{
lock_guard<mutex> lock(mtx);
terminated = true;
}
bool Scheduler::is_terminated()
{
lock_guard<mutex> lock(mtx);
return terminated;
}
//--------------------------------------
//------------Block of matrix-----------
//--------------------------------------
class BlockBase
{
public:
virtual bool move_next() { return false; };
virtual mf_node* get_current() { return nullptr; }
virtual void reload() {};
virtual void free() {};
virtual mf_long get_nnz() { return 0; };
virtual ~BlockBase() {};
};
class Block : public BlockBase
{
public:
Block() : first(nullptr), last(nullptr), current(nullptr) {};
Block(mf_node *first_, mf_node *last_)
: first(first_), last(last_), current(nullptr) {};
bool move_next() { return ++current != last; }
mf_node* get_current() { return current; }
void tie_to(mf_node *first_, mf_node *last_);
void reload() { current = first-1; };
mf_long get_nnz() { return last-first; };
private:
mf_node* first;
mf_node* last;
mf_node* current;
};
void Block::tie_to(mf_node *first_, mf_node *last_)
{
first = first_;
last = last_;
}
class BlockOnDisk : public BlockBase
{
public:
BlockOnDisk() : first(0), last(0), current(0),
source_path(""), buffer(0) {};
bool move_next() { return ++current < last-first; }
mf_node* get_current() { return &buffer[static_cast<size_t>(current)]; }
void tie_to(string source_path_, mf_long first_, mf_long last_);
void reload();
void free() { buffer.resize(0); };
mf_long get_nnz() { return last-first; };
private:
mf_long first;
mf_long last;
mf_long current;
string source_path;
vector<mf_node> buffer;
};
void BlockOnDisk::tie_to(string source_path_, mf_long first_, mf_long last_)
{
source_path = source_path_;
first = first_;
last = last_;
}
void BlockOnDisk::reload()
{
ifstream source(source_path, ifstream::in|ifstream::binary);
if(!source)
throw runtime_error("can not open "+source_path);
buffer.resize(static_cast<size_t>(last-first));
source.seekg(first*sizeof(mf_node));
source.read((char*)buffer.data(), (last-first)*sizeof(mf_node));
current = -1;
}
//--------------------------------------
//-------------Miscellaneous------------
//--------------------------------------
struct sort_node_by_p
{
bool operator() (mf_node const &lhs, mf_node const &rhs)
{
return tie(lhs.u, lhs.v) < tie(rhs.u, rhs.v);
}
};
struct sort_node_by_q
{
bool operator() (mf_node const &lhs, mf_node const &rhs)
{
return tie(lhs.v, lhs.u) < tie(rhs.v, rhs.u);
}
};
struct deleter
{
void operator() (mf_problem *prob)
{
delete[] prob->R;
delete prob;
}
};
class Utility
{
public:
Utility(mf_int f, mf_int n) : fun(f), nr_threads(n) {};
void collect_info(mf_problem &prob, mf_float &avg, mf_float &std_dev);
void collect_info_on_disk(string data_path, mf_problem &prob,
mf_float &avg, mf_float &std_dev);
void shuffle_problem(mf_problem &prob, vector<mf_int> &p_map,
vector<mf_int> &q_map);
vector<mf_node*> grid_problem(mf_problem &prob, mf_int nr_bins,
vector<mf_int> &omega_p,
vector<mf_int> &omega_q,
vector<Block> &blocks);
void grid_shuffle_scale_problem_on_disk(mf_int m, mf_int n, mf_int nr_bins,
mf_float scale, string data_path,
vector<mf_int> &p_map,
vector<mf_int> &q_map,
vector<mf_int> &omega_p,
vector<mf_int> &omega_q,
vector<BlockOnDisk> &blocks);
void scale_problem(mf_problem &prob, mf_float scale);
mf_double calc_reg1(mf_model &model, mf_float lambda_p, mf_float lambda_q,
vector<mf_int> &omega_p, vector<mf_int> &omega_q);
mf_double calc_reg2(mf_model &model, mf_float lambda_p, mf_float lambda_q,
vector<mf_int> &omega_p, vector<mf_int> &omega_q);
string get_error_legend() const;
mf_double calc_error(vector<BlockBase*> &blocks,
vector<mf_int> &cv_block_ids,
mf_model const &model);
void scale_model(mf_model &model, mf_float scale);
static mf_problem* copy_problem(mf_problem const *prob, bool copy_data);
static vector<mf_int> gen_random_map(mf_int size);
// A function used to allocate all aligned float array.
// It hides platform-specific function calls. Memory
// allocated by malloc_aligned_float must be freed by using
// free_aligned_float.
static mf_float* malloc_aligned_float(mf_long size);
// A function used to free all aligned float array.
// It hides platform-specific function calls.
static void free_aligned_float(mf_float* ptr);
// Initialization function for stochastic gradient method.
// Factor matrices P and Q are both randomly initialized.
static mf_model* init_model(mf_int loss, mf_int m, mf_int n,
mf_int k, mf_float avg,
vector<mf_int> &omega_p,
vector<mf_int> &omega_q);
// Initialization function for one-class CD.
// It does zero-initialization on factor matrix P and random initialization
// on factor matrix Q.
static mf_model* init_model(mf_int m, mf_int n, mf_int k);
static mf_float inner_product(mf_float *p, mf_float *q, mf_int k);
static vector<mf_int> gen_inv_map(vector<mf_int> &map);
static void shrink_model(mf_model &model, mf_int k_new);
static void shuffle_model(mf_model &model,
vector<mf_int> &p_map,
vector<mf_int> &q_map);
mf_int get_thread_number() const { return nr_threads; };
private:
mf_int fun;
mf_int nr_threads;
};
void Utility::collect_info(
mf_problem &prob,
mf_float &avg,
mf_float &std_dev)
{
mf_double ex = 0;
mf_double ex2 = 0;
#if defined USEOMP
#pragma omp parallel for num_threads(nr_threads) schedule(static) reduction(+:ex,ex2)
#endif
for(mf_long i = 0; i < prob.nnz; ++i)
{
mf_node &N = prob.R[i];
ex += (mf_double)N.r;
ex2 += (mf_double)N.r*N.r;
}
ex /= (mf_double)prob.nnz;
ex2 /= (mf_double)prob.nnz;
avg = (mf_float)ex;
std_dev = (mf_float)sqrt(ex2-ex*ex);
}
void Utility::collect_info_on_disk(
string data_path,
mf_problem &prob,
mf_float &avg,
mf_float &std_dev)
{
mf_double ex = 0;
mf_double ex2 = 0;
ifstream source(data_path);
if(!source.is_open())
throw runtime_error("cannot open " + data_path);
for(mf_node N; source >> N.u >> N.v >> N.r;)
{
if(N.u+1 > prob.m)
prob.m = N.u+1;
if(N.v+1 > prob.n)
prob.n = N.v+1;
prob.nnz += 1;
ex += (mf_double)N.r;
ex2 += (mf_double)N.r*N.r;
}
source.close();
ex /= (mf_double)prob.nnz;
ex2 /= (mf_double)prob.nnz;
avg = (mf_float)ex;
std_dev = (mf_float)sqrt(ex2-ex*ex);
}
void Utility::scale_problem(mf_problem &prob, mf_float scale)
{
if(scale == 1.0)
return;
#if defined USEOMP
#pragma omp parallel for num_threads(nr_threads) schedule(static)
#endif
for(mf_long i = 0; i < prob.nnz; ++i)
prob.R[i].r *= scale;
}
void Utility::scale_model(mf_model &model, mf_float scale)
{
if(scale == 1.0)
return;
mf_int k = model.k;
model.b *= scale;
auto scale1 = [&] (mf_float *ptr, mf_int size, mf_float factor_scale)
{
#if defined USEOMP
#pragma omp parallel for num_threads(nr_threads) schedule(static)
#endif
for(mf_int i = 0; i < size; ++i)
{
mf_float *ptr1 = ptr+(mf_long)i*model.k;
for(mf_int d = 0; d < k; ++d)
ptr1[d] *= factor_scale;
}
};
scale1(model.P, model.m, sqrt(scale));
scale1(model.Q, model.n, sqrt(scale));
}
mf_float Utility::inner_product(mf_float *p, mf_float *q, mf_int k)
{
#if defined USESSE
__m128 XMM = _mm_setzero_ps();
for(mf_int d = 0; d < k; d += 4)
XMM = _mm_add_ps(XMM, _mm_mul_ps(
_mm_load_ps(p+d), _mm_load_ps(q+d)));
__m128 XMMtmp = _mm_add_ps(XMM, _mm_movehl_ps(XMM, XMM));
XMM = _mm_add_ps(XMM, _mm_shuffle_ps(XMMtmp, XMMtmp, 1));
mf_float product;
_mm_store_ss(&product, XMM);
return product;
#elif defined USEAVX
__m256 XMM = _mm256_setzero_ps();
for(mf_int d = 0; d < k; d += 8)
XMM = _mm256_add_ps(XMM, _mm256_mul_ps(
_mm256_load_ps(p+d), _mm256_load_ps(q+d)));
XMM = _mm256_add_ps(XMM, _mm256_permute2f128_ps(XMM, XMM, 1));
XMM = _mm256_hadd_ps(XMM, XMM);
XMM = _mm256_hadd_ps(XMM, XMM);
mf_float product;
_mm_store_ss(&product, _mm256_castps256_ps128(XMM));
return product;
#else
return std::inner_product(p, p+k, q, (mf_float)0.0);
#endif
}
mf_double Utility::calc_reg1(mf_model &model,
mf_float lambda_p, mf_float lambda_q,
vector<mf_int> &omega_p, vector<mf_int> &omega_q)
{
auto calc_reg1_core = [&] (mf_float *ptr, mf_int size,
vector<mf_int> &omega)
{
mf_double reg = 0;
for(mf_int i = 0; i < size; ++i)
{
if(omega[i] <= 0)
continue;
mf_float tmp = 0;
for(mf_int j = 0; j < model.k; ++j)
tmp += abs(ptr[(mf_long)i*model.k+j]);
reg += omega[i]*tmp;
}
return reg;
};
return lambda_p*calc_reg1_core(model.P, model.m, omega_p)+
lambda_q*calc_reg1_core(model.Q, model.n, omega_q);
}
mf_double Utility::calc_reg2(mf_model &model,
mf_float lambda_p, mf_float lambda_q,
vector<mf_int> &omega_p, vector<mf_int> &omega_q)
{
auto calc_reg2_core = [&] (mf_float *ptr, mf_int size,
vector<mf_int> &omega)
{
mf_double reg = 0;
#if defined USEOMP
#pragma omp parallel for num_threads(nr_threads) schedule(static) reduction(+:reg)
#endif
for(mf_int i = 0; i < size; ++i)
{
if(omega[i] <= 0)
continue;
mf_float *ptr1 = ptr+(mf_long)i*model.k;
reg += omega[i]*Utility::inner_product(ptr1, ptr1, model.k);
}
return reg;
};
return lambda_p*calc_reg2_core(model.P, model.m, omega_p) +
lambda_q*calc_reg2_core(model.Q, model.n, omega_q);
}
mf_double Utility::calc_error(
vector<BlockBase*> &blocks,
vector<mf_int> &cv_block_ids,
mf_model const &model)
{
mf_double error = 0;
if(fun == P_L2_MFR || fun == P_L1_MFR || fun == P_KL_MFR ||
fun == P_LR_MFC || fun == P_L2_MFC || fun == P_L1_MFC)
{
#if defined USEOMP
#pragma omp parallel for num_threads(nr_threads) schedule(static) reduction(+:error)
#endif
for(mf_long i = 0; i < (mf_long)cv_block_ids.size(); ++i)
{
BlockBase *block = blocks[cv_block_ids[i]];
block->reload();
while(block->move_next())
{
mf_node const &N = *(block->get_current());
mf_float z = mf_predict(&model, N.u, N.v);
switch(fun)
{
case P_L2_MFR:
error += pow(N.r-z, 2);
break;
case P_L1_MFR:
error += abs(N.r-z);
break;
case P_KL_MFR:
error += N.r*log(N.r/z)-N.r+z;
break;
case P_LR_MFC:
if(N.r > 0)
error += log(1.0+exp(-z));
else
error += log(1.0+exp(z));
break;
case P_L2_MFC:
case P_L1_MFC:
if(N.r > 0)
error += z > 0? 1: 0;
else
error += z < 0? 1: 0;
break;
default:
throw invalid_argument("unknown error function");
break;
}
}
block->free();
}
}
else
{
minstd_rand0 generator(rand());
switch(fun)
{
case P_ROW_BPR_MFOC:
{
uniform_int_distribution<mf_int> distribution(0, model.n-1);
#if defined USEOMP
#pragma omp parallel for num_threads(nr_threads) schedule(static) reduction(+:error)
#endif
for(mf_long i = 0; i < (mf_long)cv_block_ids.size(); ++i)
{
BlockBase *block = blocks[cv_block_ids[i]];
block->reload();
while(block->move_next())
{
mf_node const &N = *(block->get_current());
mf_int w = distribution(generator);
error += log(1+exp(mf_predict(&model, N.u, w)-
mf_predict(&model, N.u, N.v)));
}
block->free();
}
break;
}
case P_COL_BPR_MFOC:
{
uniform_int_distribution<mf_int> distribution(0, model.m-1);
#if defined USEOMP
#pragma omp parallel for num_threads(nr_threads) schedule(static) reduction(+:error)
#endif
for(mf_long i = 0; i < (mf_long)cv_block_ids.size(); ++i)
{
BlockBase *block = blocks[cv_block_ids[i]];
block->reload();
while(block->move_next())
{
mf_node const &N = *(block->get_current());
mf_int w = distribution(generator);
error += log(1+exp(mf_predict(&model, w, N.v)-
mf_predict(&model, N.u, N.v)));
}
block->free();
}
break;
}
default:
{
throw invalid_argument("unknown error function");
break;
}
}
}
return error;
}
string Utility::get_error_legend() const
{
switch(fun)
{
case P_L2_MFR:
return string("rmse");
break;
case P_L1_MFR:
return string("mae");
break;
case P_KL_MFR:
return string("gkl");
break;
case P_LR_MFC:
return string("logloss");
break;
case P_L2_MFC:
case P_L1_MFC:
return string("accuracy");
break;
case P_ROW_BPR_MFOC:
case P_COL_BPR_MFOC:
return string("bprloss");
break;
case P_L2_MFOC:
return string("sqerror");
default:
return string();
break;
}
}
void Utility::shuffle_problem(
mf_problem &prob,
vector<mf_int> &p_map,
vector<mf_int> &q_map)
{
#if defined USEOMP
#pragma omp parallel for num_threads(nr_threads) schedule(static)
#endif
for(mf_long i = 0; i < prob.nnz; ++i)
{
mf_node &N = prob.R[i];
if(N.u < (mf_long)p_map.size())
N.u = p_map[N.u];
if(N.v < (mf_long)q_map.size())
N.v = q_map[N.v];
}
}
vector<mf_node*> Utility::grid_problem(
mf_problem &prob,
mf_int nr_bins,
vector<mf_int> &omega_p,
vector<mf_int> &omega_q,
vector<Block> &blocks)
{
vector<mf_long> counts(nr_bins*nr_bins, 0);
mf_int seg_p = (mf_int)ceil((double)prob.m/nr_bins);
mf_int seg_q = (mf_int)ceil((double)prob.n/nr_bins);
auto get_block_id = [=] (mf_int u, mf_int v)
{
return (u/seg_p)*nr_bins+v/seg_q;
};
for(mf_long i = 0; i < prob.nnz; ++i)
{
mf_node &N = prob.R[i];
mf_int block = get_block_id(N.u, N.v);
counts[block] += 1;
omega_p[N.u] += 1;
omega_q[N.v] += 1;
}
vector<mf_node*> ptrs(nr_bins*nr_bins+1);
mf_node *ptr = prob.R;
ptrs[0] = ptr;
for(mf_int block = 0; block < nr_bins*nr_bins; ++block)
ptrs[block+1] = ptrs[block] + counts[block];
vector<mf_node*> pivots(ptrs.begin(), ptrs.end()-1);
for(mf_int block = 0; block < nr_bins*nr_bins; ++block)
{
for(mf_node* pivot = pivots[block]; pivot != ptrs[block+1];)
{
mf_int curr_block = get_block_id(pivot->u, pivot->v);
if(curr_block == block)
{
++pivot;
continue;
}
mf_node *next = pivots[curr_block];
swap(*pivot, *next);
pivots[curr_block] += 1;
}
}
#if defined USEOMP
#pragma omp parallel for num_threads(nr_threads) schedule(dynamic)
#endif
for(mf_int block = 0; block < nr_bins*nr_bins; ++block)
{
if(prob.m > prob.n)
sort(ptrs[block], ptrs[block+1], sort_node_by_p());
else
sort(ptrs[block], ptrs[block+1], sort_node_by_q());
}
for(mf_long i = 0; i < (mf_long)blocks.size(); ++i)
blocks[i].tie_to(ptrs[i], ptrs[i+1]);
return ptrs;
}
void Utility::grid_shuffle_scale_problem_on_disk(
mf_int m, mf_int n, mf_int nr_bins,
mf_float scale, string data_path,
vector<mf_int> &p_map, vector<mf_int> &q_map,
vector<mf_int> &omega_p, vector<mf_int> &omega_q,
vector<BlockOnDisk> &blocks)
{
string const buffer_path = data_path+string(".disk");
mf_int seg_p = (mf_int)ceil((double)m/nr_bins);
mf_int seg_q = (mf_int)ceil((double)n/nr_bins);
vector<mf_long> counts(nr_bins*nr_bins+1, 0);
vector<mf_long> pivots(nr_bins*nr_bins, 0);
ifstream source(data_path);
fstream buffer(buffer_path, fstream::in|fstream::out|
fstream::binary|fstream::trunc);
auto get_block_id = [=] (mf_int u, mf_int v)
{
return (u/seg_p)*nr_bins+v/seg_q;
};
if(!source)
throw ios::failure(string("cannot to open ")+data_path);
if(!buffer)
throw ios::failure(string("cannot to open ")+buffer_path);
for(mf_node N; source >> N.u >> N.v >> N.r;)
{
N.u = p_map[N.u];
N.v = q_map[N.v];
mf_int bid = get_block_id(N.u, N.v);
omega_p[N.u] += 1;
omega_q[N.v] += 1;
counts[bid+1] += 1;
}
for(mf_int i = 1; i < nr_bins*nr_bins+1; ++i)
{
counts[i] += counts[i-1];
pivots[i-1] = counts[i-1];
}
source.clear();
source.seekg(0);
for(mf_node N; source >> N.u >> N.v >> N.r;)
{
N.u = p_map[N.u];
N.v = q_map[N.v];
N.r /= scale;
mf_int bid = get_block_id(N.u, N.v);
buffer.seekp(pivots[bid]*sizeof(mf_node));
buffer.write((char*)&N, sizeof(mf_node));
pivots[bid] += 1;
}
for(mf_int i = 0; i < nr_bins*nr_bins; ++i)
{
vector<mf_node> nodes(static_cast<size_t>(counts[i+1]-counts[i]));
buffer.clear();
buffer.seekg(counts[i]*sizeof(mf_node));
buffer.read((char*)nodes.data(), sizeof(mf_node)*nodes.size());
if(m > n)
sort(nodes.begin(), nodes.end(), sort_node_by_p());
else
sort(nodes.begin(), nodes.end(), sort_node_by_q());
buffer.clear();
buffer.seekp(counts[i]*sizeof(mf_node));
buffer.write((char*)nodes.data(), sizeof(mf_node)*nodes.size());
buffer.read((char*)nodes.data(), sizeof(mf_node)*nodes.size());
}
for(mf_long i = 0; i < (mf_long)blocks.size(); ++i)
blocks[i].tie_to(buffer_path, counts[i], counts[i+1]);
}
mf_float* Utility::malloc_aligned_float(mf_long size)
{
// Check if conversion from mf_long to size_t causes overflow.
if (size >= 0 && sizeof(unsigned long) >= sizeof(mf_long) &&
(unsigned long)size > numeric_limits<std::size_t>::max() / sizeof(mf_float) + 1)
throw bad_alloc();
// [REVIEW] I hope one day we can use C11 aligned_alloc to replace
// platform-depedent functions below. Both of Windows and OSX currently
// don't support that function.
void *ptr = nullptr;
#ifdef _WIN32
ptr = _aligned_malloc(static_cast<size_t>(size*sizeof(mf_float)),
kALIGNByte);
#else
int status = posix_memalign(&ptr, kALIGNByte, size*sizeof(mf_float));
if(status != 0)
throw bad_alloc();
#endif
if(ptr == nullptr)
throw bad_alloc();
return (mf_float*)ptr;
}
void Utility::free_aligned_float(mf_float *ptr)