Strengthened convergence criteria of various algorithms
[libdai.git] / src / bp.cpp
1 /* This file is part of libDAI - http://www.libdai.org/
2 *
3 * libDAI is licensed under the terms of the GNU General Public License version
4 * 2, or (at your option) any later version. libDAI is distributed without any
5 * warranty. See the file COPYING for more details.
6 *
7 * Copyright (C) 2006-2009 Joris Mooij [joris dot mooij at libdai dot org]
8 * Copyright (C) 2006-2007 Radboud University Nijmegen, The Netherlands
9 */
10
11
12 #include <iostream>
13 #include <sstream>
14 #include <map>
15 #include <set>
16 #include <algorithm>
17 #include <stack>
18 #include <dai/bp.h>
19 #include <dai/util.h>
20 #include <dai/properties.h>
21
22
23 namespace dai {
24
25
26 using namespace std;
27
28
29 const char *BP::Name = "BP";
30
31
32 #define DAI_BP_FAST 1
33
34
35 void BP::setProperties( const PropertySet &opts ) {
36 DAI_ASSERT( opts.hasKey("tol") );
37 DAI_ASSERT( opts.hasKey("maxiter") );
38 DAI_ASSERT( opts.hasKey("logdomain") );
39 DAI_ASSERT( opts.hasKey("updates") );
40
41 props.tol = opts.getStringAs<Real>("tol");
42 props.maxiter = opts.getStringAs<size_t>("maxiter");
43 props.logdomain = opts.getStringAs<bool>("logdomain");
44 props.updates = opts.getStringAs<Properties::UpdateType>("updates");
45
46 if( opts.hasKey("verbose") )
47 props.verbose = opts.getStringAs<size_t>("verbose");
48 else
49 props.verbose = 0;
50 if( opts.hasKey("damping") )
51 props.damping = opts.getStringAs<Real>("damping");
52 else
53 props.damping = 0.0;
54 if( opts.hasKey("inference") )
55 props.inference = opts.getStringAs<Properties::InfType>("inference");
56 else
57 props.inference = Properties::InfType::SUMPROD;
58 }
59
60
61 PropertySet BP::getProperties() const {
62 PropertySet opts;
63 opts.Set( "tol", props.tol );
64 opts.Set( "maxiter", props.maxiter );
65 opts.Set( "verbose", props.verbose );
66 opts.Set( "logdomain", props.logdomain );
67 opts.Set( "updates", props.updates );
68 opts.Set( "damping", props.damping );
69 opts.Set( "inference", props.inference );
70 return opts;
71 }
72
73
74 string BP::printProperties() const {
75 stringstream s( stringstream::out );
76 s << "[";
77 s << "tol=" << props.tol << ",";
78 s << "maxiter=" << props.maxiter << ",";
79 s << "verbose=" << props.verbose << ",";
80 s << "logdomain=" << props.logdomain << ",";
81 s << "updates=" << props.updates << ",";
82 s << "damping=" << props.damping << ",";
83 s << "inference=" << props.inference << "]";
84 return s.str();
85 }
86
87
88 void BP::construct() {
89 // create edge properties
90 _edges.clear();
91 _edges.reserve( nrVars() );
92 _edge2lut.clear();
93 if( props.updates == Properties::UpdateType::SEQMAX )
94 _edge2lut.reserve( nrVars() );
95 for( size_t i = 0; i < nrVars(); ++i ) {
96 _edges.push_back( vector<EdgeProp>() );
97 _edges[i].reserve( nbV(i).size() );
98 if( props.updates == Properties::UpdateType::SEQMAX ) {
99 _edge2lut.push_back( vector<LutType::iterator>() );
100 _edge2lut[i].reserve( nbV(i).size() );
101 }
102 foreach( const Neighbor &I, nbV(i) ) {
103 EdgeProp newEP;
104 newEP.message = Prob( var(i).states() );
105 newEP.newMessage = Prob( var(i).states() );
106
107 if( DAI_BP_FAST ) {
108 newEP.index.reserve( factor(I).states() );
109 for( IndexFor k( var(i), factor(I).vars() ); k.valid(); ++k )
110 newEP.index.push_back( k );
111 }
112
113 newEP.residual = 0.0;
114 _edges[i].push_back( newEP );
115 if( props.updates == Properties::UpdateType::SEQMAX )
116 _edge2lut[i].push_back( _lut.insert( make_pair( newEP.residual, make_pair( i, _edges[i].size() - 1 ))) );
117 }
118 }
119 }
120
121
122 void BP::init() {
123 Real c = props.logdomain ? 0.0 : 1.0;
124 for( size_t i = 0; i < nrVars(); ++i ) {
125 foreach( const Neighbor &I, nbV(i) ) {
126 message( i, I.iter ).fill( c );
127 newMessage( i, I.iter ).fill( c );
128 if( props.updates == Properties::UpdateType::SEQMAX )
129 updateResidual( i, I.iter, 0.0 );
130 }
131 }
132 }
133
134
135 void BP::findMaxResidual( size_t &i, size_t &_I ) {
136 DAI_ASSERT( !_lut.empty() );
137 LutType::const_iterator largestEl = _lut.end();
138 --largestEl;
139 i = largestEl->second.first;
140 _I = largestEl->second.second;
141 }
142
143
144 void BP::calcNewMessage( size_t i, size_t _I ) {
145 // calculate updated message I->i
146 size_t I = nbV(i,_I);
147
148 Factor Fprod( factor(I) );
149 Prob &prod = Fprod.p();
150 if( props.logdomain )
151 prod.takeLog();
152
153 // Calculate product of incoming messages and factor I
154 foreach( const Neighbor &j, nbF(I) )
155 if( j != i ) { // for all j in I \ i
156 // prod_j will be the product of messages coming into j
157 Prob prod_j( var(j).states(), props.logdomain ? 0.0 : 1.0 );
158 foreach( const Neighbor &J, nbV(j) )
159 if( J != I ) { // for all J in nb(j) \ I
160 if( props.logdomain )
161 prod_j += message( j, J.iter );
162 else
163 prod_j *= message( j, J.iter );
164 }
165
166 // multiply prod with prod_j
167 if( !DAI_BP_FAST ) {
168 /* UNOPTIMIZED (SIMPLE TO READ, BUT SLOW) VERSION */
169 if( props.logdomain )
170 Fprod += Factor( var(j), prod_j );
171 else
172 Fprod *= Factor( var(j), prod_j );
173 } else {
174 /* OPTIMIZED VERSION */
175 size_t _I = j.dual;
176 // ind is the precalculated IndexFor(j,I) i.e. to x_I == k corresponds x_j == ind[k]
177 const ind_t &ind = index(j, _I);
178 for( size_t r = 0; r < prod.size(); ++r )
179 if( props.logdomain )
180 prod[r] += prod_j[ind[r]];
181 else
182 prod[r] *= prod_j[ind[r]];
183 }
184 }
185
186 if( props.logdomain ) {
187 prod -= prod.max();
188 prod.takeExp();
189 }
190
191 // Marginalize onto i
192 Prob marg;
193 if( !DAI_BP_FAST ) {
194 /* UNOPTIMIZED (SIMPLE TO READ, BUT SLOW) VERSION */
195 if( props.inference == Properties::InfType::SUMPROD )
196 marg = Fprod.marginal( var(i) ).p();
197 else
198 marg = Fprod.maxMarginal( var(i) ).p();
199 } else {
200 /* OPTIMIZED VERSION */
201 marg = Prob( var(i).states(), 0.0 );
202 // ind is the precalculated IndexFor(i,I) i.e. to x_I == k corresponds x_i == ind[k]
203 const ind_t ind = index(i,_I);
204 if( props.inference == Properties::InfType::SUMPROD )
205 for( size_t r = 0; r < prod.size(); ++r )
206 marg[ind[r]] += prod[r];
207 else
208 for( size_t r = 0; r < prod.size(); ++r )
209 if( prod[r] > marg[ind[r]] )
210 marg[ind[r]] = prod[r];
211 marg.normalize();
212 }
213
214 // Store result
215 if( props.logdomain )
216 newMessage(i,_I) = marg.log();
217 else
218 newMessage(i,_I) = marg;
219
220 // Update the residual if necessary
221 if( props.updates == Properties::UpdateType::SEQMAX )
222 updateResidual( i, _I , dist( newMessage( i, _I ), message( i, _I ), Prob::DISTLINF ) );
223 }
224
225
226 // BP::run does not check for NANs for performance reasons
227 // Somehow NaNs do not often occur in BP...
228 Real BP::run() {
229 if( props.verbose >= 1 )
230 cerr << "Starting " << identify() << "...";
231 if( props.verbose >= 3)
232 cerr << endl;
233
234 double tic = toc();
235 Real maxDiff = INFINITY;
236
237 vector<Factor> oldBeliefsV, oldBeliefsF;
238 oldBeliefsV.reserve( nrVars() );
239 for( size_t i = 0; i < nrVars(); ++i )
240 oldBeliefsV.push_back( beliefV(i) );
241 oldBeliefsF.reserve( nrFactors() );
242 for( size_t I = 0; I < nrFactors(); ++I )
243 oldBeliefsF.push_back( beliefF(I) );
244
245 size_t nredges = nrEdges();
246 vector<Edge> update_seq;
247 if( props.updates == Properties::UpdateType::SEQMAX ) {
248 // do the first pass
249 for( size_t i = 0; i < nrVars(); ++i )
250 foreach( const Neighbor &I, nbV(i) )
251 calcNewMessage( i, I.iter );
252 } else {
253 update_seq.reserve( nredges );
254 /// \todo Investigate whether performance increases by switching the order of the following two loops:
255 for( size_t i = 0; i < nrVars(); ++i )
256 foreach( const Neighbor &I, nbV(i) )
257 update_seq.push_back( Edge( i, I.iter ) );
258 }
259
260 // do several passes over the network until maximum number of iterations has
261 // been reached or until the maximum belief difference is smaller than tolerance
262 for( _iters=0; _iters < props.maxiter && maxDiff > props.tol; ++_iters ) {
263 if( props.updates == Properties::UpdateType::SEQMAX ) {
264 // Residuals-BP by Koller et al.
265 for( size_t t = 0; t < nredges; ++t ) {
266 // update the message with the largest residual
267 size_t i, _I;
268 findMaxResidual( i, _I );
269 updateMessage( i, _I );
270
271 // I->i has been updated, which means that residuals for all
272 // J->j with J in nb[i]\I and j in nb[J]\i have to be updated
273 foreach( const Neighbor &J, nbV(i) ) {
274 if( J.iter != _I ) {
275 foreach( const Neighbor &j, nbF(J) ) {
276 size_t _J = j.dual;
277 if( j != i )
278 calcNewMessage( j, _J );
279 }
280 }
281 }
282 }
283 } else if( props.updates == Properties::UpdateType::PARALL ) {
284 // Parallel updates
285 for( size_t i = 0; i < nrVars(); ++i )
286 foreach( const Neighbor &I, nbV(i) )
287 calcNewMessage( i, I.iter );
288
289 for( size_t i = 0; i < nrVars(); ++i )
290 foreach( const Neighbor &I, nbV(i) )
291 updateMessage( i, I.iter );
292 } else {
293 // Sequential updates
294 if( props.updates == Properties::UpdateType::SEQRND )
295 random_shuffle( update_seq.begin(), update_seq.end() );
296
297 foreach( const Edge &e, update_seq ) {
298 calcNewMessage( e.first, e.second );
299 updateMessage( e.first, e.second );
300 }
301 }
302
303 // calculate new beliefs and compare with old ones
304 maxDiff = -INFINITY;
305 for( size_t i = 0; i < nrVars(); ++i ) {
306 Factor b( beliefV(i) );
307 maxDiff = std::max( maxDiff, dist( b, oldBeliefsV[i], Prob::DISTLINF ) );
308 oldBeliefsV[i] = b;
309 }
310 for( size_t I = 0; I < nrFactors(); ++I ) {
311 Factor b( beliefF(I) );
312 maxDiff = std::max( maxDiff, dist( b, oldBeliefsF[I], Prob::DISTLINF ) );
313 oldBeliefsF[I] = b;
314 }
315
316 if( props.verbose >= 3 )
317 cerr << Name << "::run: maxdiff " << maxDiff << " after " << _iters+1 << " passes" << endl;
318 }
319
320 if( maxDiff > _maxdiff )
321 _maxdiff = maxDiff;
322
323 if( props.verbose >= 1 ) {
324 if( maxDiff > props.tol ) {
325 if( props.verbose == 1 )
326 cerr << endl;
327 cerr << Name << "::run: WARNING: not converged within " << props.maxiter << " passes (" << toc() - tic << " seconds)...final maxdiff:" << maxDiff << endl;
328 } else {
329 if( props.verbose >= 3 )
330 cerr << Name << "::run: ";
331 cerr << "converged in " << _iters << " passes (" << toc() - tic << " seconds)." << endl;
332 }
333 }
334
335 return maxDiff;
336 }
337
338
339 void BP::calcBeliefV( size_t i, Prob &p ) const {
340 p = Prob( var(i).states(), props.logdomain ? 0.0 : 1.0 );
341 foreach( const Neighbor &I, nbV(i) )
342 if( props.logdomain )
343 p += newMessage( i, I.iter );
344 else
345 p *= newMessage( i, I.iter );
346 }
347
348
349 void BP::calcBeliefF( size_t I, Prob &p ) const {
350 Factor Fprod( factor( I ) );
351 Prob &prod = Fprod.p();
352
353 if( props.logdomain )
354 prod.takeLog();
355
356 foreach( const Neighbor &j, nbF(I) ) {
357 // prod_j will be the product of messages coming into j
358 Prob prod_j( var(j).states(), props.logdomain ? 0.0 : 1.0 );
359 foreach( const Neighbor &J, nbV(j) )
360 if( J != I ) { // for all J in nb(j) \ I
361 if( props.logdomain )
362 prod_j += newMessage( j, J.iter );
363 else
364 prod_j *= newMessage( j, J.iter );
365 }
366
367 // multiply prod with prod_j
368 if( !DAI_BP_FAST ) {
369 /* UNOPTIMIZED (SIMPLE TO READ, BUT SLOW) VERSION */
370 if( props.logdomain )
371 Fprod += Factor( var(j), prod_j );
372 else
373 Fprod *= Factor( var(j), prod_j );
374 } else {
375 /* OPTIMIZED VERSION */
376 size_t _I = j.dual;
377 // ind is the precalculated IndexFor(j,I) i.e. to x_I == k corresponds x_j == ind[k]
378 const ind_t & ind = index(j, _I);
379
380 for( size_t r = 0; r < prod.size(); ++r ) {
381 if( props.logdomain )
382 prod[r] += prod_j[ind[r]];
383 else
384 prod[r] *= prod_j[ind[r]];
385 }
386 }
387 }
388
389 p = prod;
390 }
391
392
393 Factor BP::beliefV( size_t i ) const {
394 Prob p;
395 calcBeliefV( i, p );
396
397 if( props.logdomain ) {
398 p -= p.max();
399 p.takeExp();
400 }
401 p.normalize();
402
403 return( Factor( var(i), p ) );
404 }
405
406
407 Factor BP::beliefF( size_t I ) const {
408 Prob p;
409 calcBeliefF( I, p );
410
411 if( props.logdomain ) {
412 p -= p.max();
413 p.takeExp();
414 }
415 p.normalize();
416
417 return( Factor( factor(I).vars(), p ) );
418 }
419
420
421 vector<Factor> BP::beliefs() const {
422 vector<Factor> result;
423 for( size_t i = 0; i < nrVars(); ++i )
424 result.push_back( beliefV(i) );
425 for( size_t I = 0; I < nrFactors(); ++I )
426 result.push_back( beliefF(I) );
427 return result;
428 }
429
430
431 Factor BP::belief( const VarSet &ns ) const {
432 if( ns.size() == 0 )
433 return Factor();
434 else if( ns.size() == 1 )
435 return beliefV( findVar( *(ns.begin() ) ) );
436 else {
437 size_t I;
438 for( I = 0; I < nrFactors(); I++ )
439 if( factor(I).vars() >> ns )
440 break;
441 if( I == nrFactors() )
442 DAI_THROW(BELIEF_NOT_AVAILABLE);
443 return beliefF(I).marginal(ns);
444 }
445 }
446
447
448 Real BP::logZ() const {
449 Real sum = 0.0;
450 for( size_t i = 0; i < nrVars(); ++i )
451 sum += (1.0 - nbV(i).size()) * beliefV(i).entropy();
452 for( size_t I = 0; I < nrFactors(); ++I )
453 sum -= dist( beliefF(I), factor(I), Prob::DISTKL );
454 return sum;
455 }
456
457
458 string BP::identify() const {
459 return string(Name) + printProperties();
460 }
461
462
463 void BP::init( const VarSet &ns ) {
464 for( VarSet::const_iterator n = ns.begin(); n != ns.end(); ++n ) {
465 size_t ni = findVar( *n );
466 foreach( const Neighbor &I, nbV( ni ) ) {
467 Real val = props.logdomain ? 0.0 : 1.0;
468 message( ni, I.iter ).fill( val );
469 newMessage( ni, I.iter ).fill( val );
470 if( props.updates == Properties::UpdateType::SEQMAX )
471 updateResidual( ni, I.iter, 0.0 );
472 }
473 }
474 }
475
476
477 void BP::updateMessage( size_t i, size_t _I ) {
478 if( recordSentMessages )
479 _sentMessages.push_back(make_pair(i,_I));
480 if( props.damping == 0.0 ) {
481 message(i,_I) = newMessage(i,_I);
482 if( props.updates == Properties::UpdateType::SEQMAX )
483 updateResidual( i, _I, 0.0 );
484 } else {
485 if( props.logdomain )
486 message(i,_I) = (message(i,_I) * props.damping) + (newMessage(i,_I) * (1.0 - props.damping));
487 else
488 message(i,_I) = (message(i,_I) ^ props.damping) * (newMessage(i,_I) ^ (1.0 - props.damping));
489 if( props.updates == Properties::UpdateType::SEQMAX )
490 updateResidual( i, _I, dist( newMessage(i,_I), message(i,_I), Prob::DISTLINF ) );
491 }
492 }
493
494
495 void BP::updateResidual( size_t i, size_t _I, Real r ) {
496 EdgeProp* pEdge = &_edges[i][_I];
497 pEdge->residual = r;
498
499 // rearrange look-up table (delete and reinsert new key)
500 _lut.erase( _edge2lut[i][_I] );
501 _edge2lut[i][_I] = _lut.insert( make_pair( r, make_pair(i, _I) ) );
502 }
503
504
505 std::vector<size_t> BP::findMaximum() const {
506 vector<size_t> maximum( nrVars() );
507 vector<bool> visitedVars( nrVars(), false );
508 vector<bool> visitedFactors( nrFactors(), false );
509 stack<size_t> scheduledFactors;
510 for( size_t i = 0; i < nrVars(); ++i ) {
511 if( visitedVars[i] )
512 continue;
513 visitedVars[i] = true;
514
515 // Maximise with respect to variable i
516 Prob prod;
517 calcBeliefV( i, prod );
518 maximum[i] = prod.argmax().first;
519
520 foreach( const Neighbor &I, nbV(i) )
521 if( !visitedFactors[I] )
522 scheduledFactors.push(I);
523
524 while( !scheduledFactors.empty() ){
525 size_t I = scheduledFactors.top();
526 scheduledFactors.pop();
527 if( visitedFactors[I] )
528 continue;
529 visitedFactors[I] = true;
530
531 // Evaluate if some neighboring variables still need to be fixed; if not, we're done
532 bool allDetermined = true;
533 foreach( const Neighbor &j, nbF(I) )
534 if( !visitedVars[j.node] ) {
535 allDetermined = false;
536 break;
537 }
538 if( allDetermined )
539 continue;
540
541 // Calculate product of incoming messages on factor I
542 Prob prod2;
543 calcBeliefF( I, prod2 );
544
545 // The allowed configuration is restrained according to the variables assigned so far:
546 // pick the argmax amongst the allowed states
547 Real maxProb = numeric_limits<Real>::min();
548 State maxState( factor(I).vars() );
549 for( State s( factor(I).vars() ); s.valid(); ++s ){
550 // First, calculate whether this state is consistent with variables that
551 // have been assigned already
552 bool allowedState = true;
553 foreach( const Neighbor &j, nbF(I) )
554 if( visitedVars[j.node] && maximum[j.node] != s(var(j.node)) ) {
555 allowedState = false;
556 break;
557 }
558 // If it is consistent, check if its probability is larger than what we have seen so far
559 if( allowedState && prod2[s] > maxProb ) {
560 maxState = s;
561 maxProb = prod2[s];
562 }
563 }
564
565 // Decode the argmax
566 foreach( const Neighbor &j, nbF(I) ) {
567 if( visitedVars[j.node] ) {
568 // We have already visited j earlier - hopefully our state is consistent
569 if( maximum[j.node] != maxState(var(j.node)) && props.verbose >= 1 )
570 cerr << "BP::findMaximum - warning: maximum not consistent due to loops." << endl;
571 } else {
572 // We found a consistent state for variable j
573 visitedVars[j.node] = true;
574 maximum[j.node] = maxState( var(j.node) );
575 foreach( const Neighbor &J, nbV(j) )
576 if( !visitedFactors[J] )
577 scheduledFactors.push(J);
578 }
579 }
580 }
581 }
582 return maximum;
583 }
584
585
586 } // end of namespace dai