Adoptive timeout ...
[satune.git] / src / Tuner / multituner.cc
1 #include "multituner.h"
2 #include "csolver.h"
3 #include "searchtuner.h"
4 #include <math.h>
5 #include <stdlib.h>
6 #include <float.h>
7 #include <string.h>
8 #include <iostream>
9 #include <fstream>
10
11 #define UNSETVALUE -1
12
13 Problem::Problem(const char *_problem) : problemnumber(-1), result(UNSETVALUE) {
14         uint len = strlen(_problem);
15         problem = (char *) ourmalloc(len + 1);
16         memcpy(problem, _problem, len + 1);
17 }
18
19 Problem::~Problem() {
20         ourfree(problem);
21 }
22
23 void TunerRecord::setTime(Problem *problem, long long time) {
24         timetaken.put(problem, time);
25 }
26
27 long long TunerRecord::getTime(Problem *problem) {
28         if (timetaken.contains(problem))
29                 return timetaken.get(problem);
30         else return -1;
31 }
32
33 TunerRecord *TunerRecord::changeTuner(SearchTuner *_newtuner) {
34         TunerRecord *tr = new TunerRecord(_newtuner);
35         for (uint i = 0; i < problems.getSize(); i++) {
36                 tr->problems.push(problems.get(i));
37         }
38         return tr;
39 }
40
41 MultiTuner::MultiTuner(uint _budget, uint _rounds, uint _timeout) :
42         budget(_budget), rounds(_rounds), timeout(_timeout), besttime(_timeout), execnum(0) {
43 }
44
45 MultiTuner::~MultiTuner() {
46         for (uint i = 0; i < problems.getSize(); i++)
47                 ourfree(problems.get(i));
48         for (uint i = 0; i < allTuners.getSize(); i++)
49                 delete allTuners.get(i);
50 }
51
52 void MultiTuner::addProblem(const char *filename) {
53         Problem *p = new Problem(filename);
54         p->problemnumber = problems.getSize();
55         problems.push(p);
56 }
57
58 void MultiTuner::printData() {
59         model_print("*********** DATA DUMP ***********\n");
60         for (uint i = 0; i < allTuners.getSize(); i++) {
61                 TunerRecord *tuner = allTuners.get(i);
62                 SearchTuner *stun = tuner->getTuner();
63                 model_print("Tuner %u\n", i);
64                 stun->print();
65                 model_print("----------------------------------\n\n\n");
66                 for (uint j = 0; j < tuner->problems.getSize(); j++) {
67                         Problem *problem = tuner->problems.get(j);
68                         model_print("Problem %s\n", problem->getProblem());
69                         model_print("Time = %lld\n", tuner->getTime(problem));
70                 }
71         }
72 }
73
74 void MultiTuner::addTuner(SearchTuner *tuner) {
75         TunerRecord *t = new TunerRecord(tuner);
76         tuners.push(t);
77         t->tunernumber = allTuners.getSize();
78         allTuners.push(t);
79 }
80
81
82 void MultiTuner::readData(uint numRuns) {
83         for (uint i = 0; i < numRuns; i++) {
84                 ifstream myfile;
85                 char buffer[512];
86                 uint tunernumber;
87                 snprintf(buffer, sizeof(buffer), "tunernum%u", i);
88                 myfile.open (buffer, ios::in);
89                 myfile >> tunernumber;
90                 myfile.close();
91                 if (allTuners.getSize() <= tunernumber)
92                         allTuners.setSize(tunernumber + 1);
93                 if (allTuners.get(tunernumber) == NULL) {
94                         snprintf(buffer, sizeof(buffer), "tuner%u", i);
95                         allTuners.set(tunernumber, new TunerRecord(new SearchTuner(buffer)));
96                 }
97                 //Add any new used records
98                 snprintf(buffer, sizeof(buffer), "tuner%uused", i);
99                 TunerRecord *tuner = allTuners.get(tunernumber);
100                 tuner->getTuner()->addUsed(buffer);
101
102                 char problemname[512];
103                 uint problemnumber;
104                 snprintf(buffer, sizeof(buffer), "problem%u", i);
105                 myfile.open(buffer, ios::in);
106                 myfile.getline(problemname, sizeof(problemname));
107                 myfile >> problemnumber;
108                 myfile.close();
109                 if (problems.getSize() <= problemnumber)
110                         problems.setSize(problemnumber + 1);
111                 if (problems.get(problemnumber) == NULL)
112                         problems.set(problemnumber, new Problem(problemname));
113                 Problem *problem = problems.get(problemnumber);
114                 long long metric = -1;
115                 int sat = IS_INDETER;
116                 //Read data in from results file
117                 snprintf(buffer, sizeof(buffer), "result%u", i);
118
119                 myfile.open (buffer, ios::in);
120
121
122                 if (myfile.is_open()) {
123                         myfile >> metric;
124                         myfile >> sat;
125                         myfile.close();
126                 }
127                 if (problem->result == UNSETVALUE && sat != IS_INDETER) {
128                         problem->result = sat;
129                 } else if (problem->result != sat && sat != IS_INDETER) {
130                         model_print("******** Result has changed ********\n");
131                 }
132
133                 if (metric != -1) {
134                         if (tuner->getTime(problem) == -1)
135                                 tuner->problems.push(problem);
136                         tuner->setTime(problem, metric);
137                 }
138
139         }
140
141 }
142
143 long long MultiTuner::evaluate(Problem *problem, TunerRecord *tuner) {
144         char buffer[512];
145         {
146                 snprintf(buffer, sizeof(buffer), "problem%u", execnum);
147
148                 ofstream myfile;
149                 myfile.open (buffer, ios::out);
150
151
152                 if (myfile.is_open()) {
153                         myfile << problem->getProblem() << endl;
154                         myfile << problem->problemnumber << endl;
155                         myfile.close();
156                 }
157         }
158
159         {
160                 snprintf(buffer, sizeof(buffer), "tunernum%u", execnum);
161
162                 ofstream myfile;
163                 myfile.open (buffer, ios::out);
164
165
166                 if (myfile.is_open()) {
167                         myfile << tuner->tunernumber << endl;
168                         myfile.close();
169                 }
170         }
171
172         //Write out the tuner
173         snprintf(buffer, sizeof(buffer), "tuner%u", execnum);
174         tuner->getTuner()->serialize(buffer);
175
176         //Do run
177         snprintf(buffer, sizeof(buffer), "./run.sh deserializerun %s %u tuner%u result%u > log%u", problem->getProblem(), timeout, execnum, execnum, execnum);
178         int status = system(buffer);
179
180         long long metric = -1;
181         int sat = IS_INDETER;
182
183         if (status == 0) {
184                 //Read data in from results file
185                 snprintf(buffer, sizeof(buffer), "result%u", execnum);
186
187                 ifstream myfile;
188                 myfile.open (buffer, ios::in);
189
190
191                 if (myfile.is_open()) {
192                         myfile >> metric;
193                         myfile >> sat;
194                         myfile.close();
195                 }
196                 updateTimeout(metric);
197                 snprintf(buffer, sizeof(buffer), "tuner%uused", execnum);
198                 tuner->getTuner()->addUsed(buffer);
199         }
200         //Increment execution count
201         execnum++;
202
203         if (problem->result == UNSETVALUE && sat != IS_INDETER) {
204                 problem->result = sat;
205         } else if (problem->result != sat && sat != IS_INDETER) {
206                 model_print("******** Result has changed ********\n");
207         }
208         if(sat == IS_INDETER && metric != -1){ //The case when we have a timeout
209                 metric = -1; 
210         }
211         return metric;
212 }
213
214 void MultiTuner::updateTimeout(long long metric){
215         double currentTime= metric / NANOSEC;
216         if(currentTime < besttime){
217                 besttime = currentTime;
218         }
219         uint adoptive;
220         if(besttime > 30){
221                 adoptive = besttime * 5;
222         }else {
223                 adoptive = 150;
224         }
225         if(adoptive < timeout){
226                 timeout = adoptive;
227         }
228 }
229
230 void MultiTuner::tuneComp() {
231         Vector<TunerRecord *> *tunerV = new Vector<TunerRecord *>(&tuners);
232         for (uint b = 0; b < budget; b++) {
233                 model_print("Round %u of %u\n", b, budget);
234                 uint tSize = tunerV->getSize();
235                 for (uint i = 0; i < tSize; i++) {
236                         SearchTuner *tmpTuner = mutateTuner(tunerV->get(i)->getTuner(), b);
237                         TunerRecord *tmp = new TunerRecord(tmpTuner);
238                         tmp->tunernumber = allTuners.getSize();
239                         model_print("Mutated tuner %u to generate tuner %u\n", tunerV->get(i)->tunernumber, tmp->tunernumber);
240                         allTuners.push(tmp);
241                         tunerV->push(tmp);
242                 }
243
244                 Hashtable<TunerRecord *, int, uint64_t> scores;
245                 for (uint i = 0; i < problems.getSize(); i++) {
246                         Problem *problem = problems.get(i);
247                         Vector<TunerRecord *> places;
248                         for (uint j = 0; j < tunerV->getSize(); j++) {
249                                 TunerRecord *tuner = tunerV->get(j);
250                                 long long metric = tuner->getTime(problem);
251                                 if (metric == -1) {
252                                         metric = evaluate(problem, tuner);
253                                         if (tuner->getTime(problem) == -1) {
254                                                 tuner->problems.push(problem);
255                                         }
256                                         DEBUG("%u.Problem<%s>\tTuner<%p, %d>\tMetric<%lld>\n", i, problem->problem,tuner, tuner->tunernumber, metric);
257                                         DEBUG("*****************************\n");
258                                         if (metric != -1)
259                                                 tuner->setTime(problem, metric);
260                                 }
261                                 if (metric != -1) {
262                                         uint k = 0;
263                                         for (; k < places.getSize(); k++) {
264                                                 if (metric < places.get(k)->getTime(problem))
265                                                         break;
266                                         }
267                                         DEBUG("place[%u]=Tuner<%p,%d>\n", k, tuner, tuner->tunernumber);
268                                         places.insertAt(k, tuner);
269                                 }
270                         }
271                         int points = 9;
272                         for (uint k = 0; k < places.getSize() && points; k++) {
273                                 TunerRecord *tuner = places.get(k);
274                                 int currScore = 0;
275                                 if (scores.contains(tuner))
276                                         currScore = scores.get(tuner);
277                                 currScore += points;
278                                 DEBUG("Problem<%s>\tTuner<%p,%d>\tmetric<%d>\n", problem->problem, tuner, tuner->tunernumber,  currScore);
279                                 DEBUG("**************************\n");
280                                 scores.put(tuner, currScore);
281                                 points = points / 3;
282                         }
283                 }
284                 Vector<TunerRecord *> ranking;
285                 for (uint i = 0; i < tunerV->getSize(); i++) {
286                         TunerRecord *tuner = tunerV->get(i);
287                         int score = 0;
288                         if (scores.contains(tuner))
289                                 score = scores.get(tuner);
290                         uint j = 0;
291                         for (; j < ranking.getSize(); j++) {
292                                 TunerRecord *t = ranking.get(j);
293                                 int tscore = 0;
294                                 if (scores.contains(t))
295                                         tscore = scores.get(t);
296                                 if (score > tscore)
297                                         break;
298                         }
299                         DEBUG("ranking[%u]=tuner<%p,%u>(Score=%d)\n", j, tuner, tuner->tunernumber, score);
300                         DEBUG("************************\n");
301                         ranking.insertAt(j, tuner);
302                 }
303                 LOG("tunerSize=%u\trankingSize=%u\ttunerVSize=%u\n", tuners.getSize(), ranking.getSize(), tunerV->getSize());
304                 for (uint i = tuners.getSize(); i < ranking.getSize(); i++) {
305                         TunerRecord *tuner = ranking.get(i);
306                         model_print("Removing tuner %u\n", tuner->tunernumber);
307                         for (uint j = 0; j < tunerV->getSize(); j++) {
308                                 if (tunerV->get(j) == tuner)
309                                         tunerV->removeAt(j);
310                         }
311                 }
312         }
313         printData();
314 }
315
316 void MultiTuner::mapProblemsToTuners(Vector<TunerRecord *> *tunerV) {
317         for (uint i = 0; i < problems.getSize(); i++) {
318                 Problem *problem = problems.get(i);
319                 TunerRecord *bestTuner = NULL;
320                 long long bestscore = 0;
321                 for (uint j = 0; j < tunerV->getSize(); j++) {
322                         TunerRecord *tuner = tunerV->get(j);
323                         long long metric = tuner->getTime(problem);
324                         if (metric == -1) {
325                                 metric = evaluate(problem, tuner);
326                                 if (metric != -1)
327                                         tuner->setTime(problem, metric);
328                         }
329                         if ((bestTuner == NULL && metric != -1) ||
330                                         (metric < bestscore && metric != -1)) {
331                                 bestTuner = tuner;
332                                 bestscore = metric;
333                         }
334                 }
335                 if (bestTuner != NULL)
336                         bestTuner->problems.push(problem);
337         }
338 }
339
340 void clearVector(Vector<TunerRecord *> *tunerV) {
341         for (uint j = 0; j < tunerV->getSize(); j++) {
342                 TunerRecord *tuner = tunerV->get(j);
343                 tuner->problems.clear();
344         }
345 }
346
347 void MultiTuner::tuneK() {
348         Vector<TunerRecord *> *tunerV = new Vector<TunerRecord *>(&tuners);
349         for (uint i = 0; i < rounds; i++) {
350                 clearVector(tunerV);
351                 mapProblemsToTuners(tunerV);
352                 improveTuners(tunerV);
353         }
354         model_print("Best tuners\n");
355         for (uint j = 0; j < tunerV->getSize(); j++) {
356                 TunerRecord *tuner = tunerV->get(j);
357                 char buffer[256];
358                 sprintf(buffer, "tuner%u.conf", j);
359                 tuner->getTuner()->serialize(buffer);
360                 tuner->getTuner()->print();
361         }
362         delete tunerV;
363 }
364
365 void MultiTuner::improveTuners(Vector<TunerRecord *> *tunerV) {
366         for (uint j = 0; j < tunerV->getSize(); j++) {
367                 TunerRecord *tuner = tunerV->get(j);
368                 TunerRecord *newtuner = tune(tuner);
369                 tunerV->set(j, newtuner);
370         }
371 }
372
373 double MultiTuner::evaluateAll(TunerRecord *tuner) {
374         double product = 1;
375         for (uint i = 0; i < tuner->problems.getSize(); i++) {
376                 Problem *problem = tuner->problems.get(i);
377                 long long metric = tuner->getTime(problem);
378                 if (metric == -1) {
379                         metric = evaluate(problem, tuner);
380                         if (metric != -1)
381                                 tuner->setTime(problem, metric);
382                 }
383
384                 double score = metric;
385                 product *= score;
386         }
387         return pow(product, 1 / ((double)tuner->problems.getSize()));
388 }
389
390 SearchTuner *MultiTuner::mutateTuner(SearchTuner *oldTuner, uint k) {
391         SearchTuner *newTuner = oldTuner->copyUsed();
392         uint numSettings = oldTuner->getSize();
393         uint settingsToMutate = (uint)(AUTOTUNERFACTOR * (((double)numSettings) * (budget - k)) / (budget));
394         if (settingsToMutate < 1)
395                 settingsToMutate = 1;
396         model_print("Mutating %u settings\n", settingsToMutate);
397         while (settingsToMutate-- != 0) {
398                 newTuner->randomMutate();
399         }
400         return newTuner;
401 }
402
403 TunerRecord *MultiTuner::tune(TunerRecord *tuner) {
404         TunerRecord *bestTuner = NULL;
405         double bestScore = DBL_MAX;
406
407         TunerRecord *oldTuner = tuner;
408         double base_temperature = evaluateAll(oldTuner);
409         double oldScore = base_temperature;
410
411         for (uint i = 0; i < budget; i++) {
412                 SearchTuner *tmpTuner = mutateTuner(oldTuner->getTuner(), i);
413                 TunerRecord *newTuner = oldTuner->changeTuner(tmpTuner);
414                 newTuner->tunernumber = allTuners.getSize();
415                 allTuners.push(newTuner);
416                 double newScore = evaluateAll(newTuner);
417                 newTuner->tuner->printUsed();
418                 model_print("Received score %f\n", newScore);
419                 double scoreDiff = newScore - oldScore; //smaller is better
420                 if (newScore < bestScore) {
421                         bestScore = newScore;
422                         bestTuner = newTuner;
423                 }
424
425                 double acceptanceP;
426                 if (scoreDiff < 0) {
427                         acceptanceP = 1;
428                 } else {
429                         double currTemp = base_temperature * (((double)budget - i) / budget);
430                         acceptanceP = exp(-scoreDiff / currTemp);
431                 }
432                 double ran = ((double)random()) / RAND_MAX;
433                 if (ran <= acceptanceP) {
434                         oldScore = newScore;
435                         oldTuner = newTuner;
436                 }
437         }
438
439         return bestTuner;
440 }
441