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
|
#ifndef _TNET_PLATFORM_H
#define _TNET_PLATFORM_H
/**
* \file Platform.h
* \brief DNN training class multicore version
*/
#include "Thread.h"
#include "Matrix.h"
#include "Features.h"
#include "Labels.h"
#include "Cache.h"
#include "Nnet.h"
#include "ObjFun.h"
#include "Mutex.h"
#include "Semaphore.h"
#include "Barrier.h"
#include "Thread.h"
#include <vector>
#include <list>
#include <iterator>
namespace TNet {
class PlatformThread;
class Platform {
/*
* Variables to be initialized directly from the main function
*/
public:
FeatureRepository feature_; ///< Features specified in the input arguments and script file
LabelRepository label_; ///< Labels specified in the lable map file
Network nnet_transf_; ///< NNet transform
Network nnet_; ///< N network
ObjectiveFunction* obj_fun_; ///< Specified in the ObjectiveFunction
int bunchsize_;
int cachesize_;
bool randomize_;
int start_frm_ext_;
int end_frm_ext_;
int trace_;
bool crossval_;
long int seed_;
/*
* Variables to be used internally during the multi-threaded training
*/
private:
Semaphore semaphore_read_;
std::vector<std::list<Matrix<BaseFloat>*> > feature_buf_;
std::vector<std::list<Matrix<BaseFloat>*> > label_buf_;
std::vector<Mutex> mutex_buf_;
std::vector<Network*> nnet_transf2_;
std::vector<Cache> cache_;
std::vector<Network*> nnet2_;
std::vector<ObjectiveFunction*> obj_fun2_;
std::vector<bool> sync_mask_;
Barrier barrier_;
bool end_reading_;
std::vector<Timer> tim_;
std::vector<double> tim_accu_;
int num_thr_;
Semaphore semaphore_endtrain_;
Semaphore semaphore_endtrain2_;
public:
Mutex cout_mutex_;
/*
* Methods
*/
public:
Platform()
: bunchsize_(0), cachesize_(0), randomize_(false),
start_frm_ext_(0), end_frm_ext_(0), trace_(0),
crossval_(false), seed_(0),
end_reading_(false), num_thr_(0)
{ }
~Platform()
{
for(size_t i=0; i<nnet_transf2_.size(); i++) {
delete nnet_transf2_[i];
}
for(size_t i=0; i<nnet2_.size(); i++) {
delete nnet2_[i];
}
for(size_t i=0; i<obj_fun2_.size(); i++) {
delete obj_fun2_[i];
}
}
/// Run the training using num_threads threads
void RunTrain(int num_threads);
private:
/// The data-reading thread
void ReadData();
/// The training thread
void Thread(int thr);
friend class PlatformThread;
};
/**
* Inherit Thread for the training threads
*/
class PlatformThread : public Thread {
public:
PlatformThread(Platform* pf)
: platform_(*pf)
{ }
private:
void Execute(void* arg) {
long long thr_id = reinterpret_cast<long long>(arg);
platform_.Thread(thr_id);
}
private:
Platform& platform_;
};
void Platform::RunTrain(int num_thr) {
num_thr_ = num_thr;
/*
* Initialize parallel training
*/
feature_buf_.resize(num_thr);
label_buf_.resize(num_thr);
mutex_buf_.resize(num_thr);
cache_.resize(num_thr);
sync_mask_.resize(num_thr);
barrier_.SetThreshold(num_thr);
tim_.resize(num_thr);
tim_accu_.resize(num_thr,0.0);
int bunchsize = bunchsize_/num_thr;
int cachesize = (cachesize_/num_thr/bunchsize)*bunchsize;
std::cout << "Bunchsize:" << bunchsize << "*" << num_thr << "=" << bunchsize*num_thr
<< " Cachesize:" << cachesize << "*" << num_thr << "=" << cachesize*num_thr << "\n";
for(int i=0; i<num_thr; i++) {
//clone transforms
nnet_transf2_.push_back(nnet_transf_.Clone());
//create cache
cache_[i].Init(cachesize,bunchsize,seed_);
cache_[i].Trace(trace_);
//clone networks
nnet2_.push_back(nnet_.Clone());
//clone objective function objects
obj_fun2_.push_back(obj_fun_->Clone());
//enable threads to sync weights
sync_mask_[i] = true;
}
/*
* Run training threads
*/
std::vector<PlatformThread*> threads;
for(intptr_t i=0; i<num_thr; i++) {
PlatformThread* t = new PlatformThread(this);
t->Start(reinterpret_cast<void*>(i));
threads.push_back(t);
}
/*
* Read the training data
*/
ReadData();
/*
* Wait for training to finish
*/
semaphore_endtrain2_.Wait();
}
void Platform::ReadData() try {
cout_mutex_.Lock();
std::cout << "queuesize " << feature_.QueueSize() << "\n";
cout_mutex_.Unlock();
int thr = 0;
for(feature_.Rewind();!feature_.EndOfList();feature_.MoveNext()) {
Matrix<BaseFloat>* fea = new Matrix<BaseFloat>;
Matrix<BaseFloat>* lab = new Matrix<BaseFloat>;
feature_.ReadFullMatrix(*fea);
label_.GenDesiredMatrix(*lab,
fea->Rows()-start_frm_ext_-end_frm_ext_,
feature_.CurrentHeader().mSamplePeriod,
feature_.Current().Logical().c_str());
fea->CheckData(feature_.Current().Logical());
mutex_buf_[thr].Lock();
feature_buf_[thr].push_back(fea);
label_buf_[thr].push_back(lab);
mutex_buf_[thr].Unlock();
//suspend reading when shortest buffer has 50 matrices
if(thr == 0) {
int minsize=1e6;
for(size_t i=0; i<feature_buf_.size(); i++) {
int s = feature_buf_[i].size();
if(s < minsize) minsize = s;
}
if(minsize > 20) semaphore_read_.Wait();
}
thr = (thr+1) % num_thr_;
}
std::cout << "[Reading finished]\n" << std::flush;
end_reading_ = true;
} catch (std::exception& rExc) {
std::cerr << "Exception thrown" << std::endl;
std::cerr << rExc.what() << std::endl;
exit(1);
}
void Platform::Thread(int thr_id) try {
const int thr = thr_id; //make id const for safety!
while(1) {
//fill the cache
while(!cache_[thr].Full() && !(end_reading_ && (feature_buf_[thr].size() == 0))) {
if(feature_buf_[thr].size() <= 5) {
semaphore_read_.Post();//wake the reader
}
if(feature_buf_[thr].size() == 0) {
cout_mutex_.Lock();
std::cout << "Thread" << thr << ",waiting for data\n";
cout_mutex_.Unlock();
sleep(1);
} else {
//get the matrices
mutex_buf_[thr].Lock();
Matrix<BaseFloat>* fea = feature_buf_[thr].front();
Matrix<BaseFloat>* lab = label_buf_[thr].front();
feature_buf_[thr].pop_front();
label_buf_[thr].pop_front();
mutex_buf_[thr].Unlock();
//transform the features
Matrix<BaseFloat> fea_transf;
nnet_transf2_[thr]->Propagate(*fea,fea_transf);
//trim the ext
SubMatrix<BaseFloat> fea_trim(
fea_transf,
start_frm_ext_,
fea_transf.Rows()-start_frm_ext_-end_frm_ext_,
0,
fea_transf.Cols()
);
//add to cache
cache_[thr].AddData(fea_trim,*lab);
delete fea; delete lab;
}
}
//no more data, end training...
if(cache_[thr].Empty()) break;
if(randomize_) { cache_[thr].Randomize(); }
//std::cout << "Thread" << thr << ", Cache#" << nr_cache++ << "\n";
//train from cache
Matrix<BaseFloat> fea2,lab2,out,err;
while(!cache_[thr].Empty()) {
cache_[thr].GetBunch(fea2,lab2);
nnet2_[thr]->Propagate(fea2,out);
obj_fun2_[thr]->Evaluate(out,lab2,&err);
if(!crossval_) {
nnet2_[thr]->Backpropagate(err);
tim_[thr].Start();
barrier_.Wait();//*********/
tim_[thr].End(); tim_accu_[thr] += tim_[thr].Val();
//sum the gradient and bunchsize
for(int i=0; i<num_thr_; i++) {
if(sync_mask_[i]) {
nnet_.AccuGradient(*nnet2_[i],thr,num_thr_);
if(thr == 0) nnet_.AccuBunchsize(*nnet2_[i]);
}
}
tim_[thr].Start();
barrier_.Wait();//*********/
tim_[thr].End(); tim_accu_[thr] += tim_[thr].Val();
//update
nnet_.Update(thr,num_thr_);
tim_[thr].Start();
barrier_.Wait();//*********/
tim_[thr].End(); tim_accu_[thr] += tim_[thr].Val();
//reset the bunchsize counter
if(thr == 0) nnet_.ResetBunchsize();
}
}
}
std::cout << "Thread" << thr << " end of data\n";
//deactivate threads' update from summing
sync_mask_[thr] = false;
//increase number of finished threads
semaphore_endtrain_.Post();
//synchronize the updates of other threads
while(1) {
barrier_.Wait();//*********/
if(semaphore_endtrain_.GetValue() == num_thr_) break;
//sum the gradient and bunchsize
for(int i=0; i<num_thr_; i++) {
if(sync_mask_[i]) {
nnet_.AccuGradient(*nnet2_[i],thr,num_thr_);
if(thr == 0) nnet_.AccuBunchsize(*nnet2_[i]);
}
}
barrier_.Wait();//*********/
//update
nnet_.Update(thr,num_thr_);
barrier_.Wait();//*********/
//reset bunchsize counter
if(thr == 0) nnet_.ResetBunchsize();
}
//finally merge objfun stats
if(thr == 0) {
for(int i=0; i<num_thr_; i++) {
obj_fun_->MergeStats(*obj_fun2_[i]);
}
cout_mutex_.Lock();
std::cout << "Barrier waiting times per thread\n";
std::copy(tim_accu_.begin(),tim_accu_.end(),std::ostream_iterator<double>(std::cout," "));
std::cout << "\n";
cout_mutex_.Unlock();
}
cout_mutex_.Lock();
std::cout << "[Thread" << thr << " finished]\n";
cout_mutex_.Unlock();
if(thr == 0) {
semaphore_endtrain2_.Post();
}
} catch (std::exception& rExc) {
std::cerr << "Exception thrown" << std::endl;
std::cerr << rExc.what() << std::endl;
exit(1);
}
}//namespace TNet
#endif
|