runner_pt.cpp 24.9 KB
Newer Older
1
#include "runner_pt.h"
2
#include <fstream>
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

namespace loadl {

enum {
	S_IDLE,
	S_BUSY,
	S_READY_FOR_GLOBAL,
	S_TIMEUP,

	A_CONTINUE,
	A_EXIT,
	A_NEW_JOB,
	A_PROCESS_DATA_NEW_JOB,

	// global update status response
	GA_DONE,
	GA_SKIP,
	GA_CALC_WEIGHT,

22
	MASTER = 0
23 24
};

25 26 27 28 29 30
enum {
	TR_CONTINUE,
	TR_CHECKPOINT,
	TR_TIMEUP,
};

Lukas Weber's avatar
Lukas Weber committed
31
pt_chain_run::pt_chain_run(const pt_chain &chain, int run_id) : id{chain.id}, run_id{run_id} {
32 33
	rank_to_pos.resize(chain.params.size());
	weight_ratios.resize(chain.params.size(), -1);
34
	switch_partners.resize(chain.params.size());
Lukas Weber's avatar
Lukas Weber committed
35

36 37 38 39
	last_visited.resize(chain.params.size());

	for(size_t i = 0; i < rank_to_pos.size(); i++) {
		rank_to_pos[i] = i;
40 41 42
	}
}

43 44 45 46
void pt_chain_run::clear_histograms() {
	std::fill(last_visited.begin(), last_visited.end(), 0);
}

47
pt_chain_run pt_chain_run::checkpoint_read(const iodump::group &g) {
48 49 50
	pt_chain_run run;
	g.read("id", run.id);
	g.read("run_id", run.run_id);
51
	g.read("rank_to_pos", run.rank_to_pos);
52 53 54 55
	g.read("last_visited", run.last_visited);
	uint8_t swap_odd;
	g.read("swap_odd", swap_odd);
	run.swap_odd = swap_odd;
56

57
	run.weight_ratios.resize(run.rank_to_pos.size(), -1);
58
	run.switch_partners.resize(run.rank_to_pos.size());
59 60 61 62

	return run;
}

63
void pt_chain_run::checkpoint_write(const iodump::group &g) {
64 65
	g.write("id", id);
	g.write("run_id", run_id);
66
	g.write("rank_to_pos", rank_to_pos);
67 68
	g.write("last_visited", last_visited);
	g.write("swap_odd", static_cast<uint8_t>(swap_odd));
69 70 71 72 73 74 75 76 77 78
}

void pt_chain::checkpoint_read(const iodump::group &g) {
	g.read("params", params);
	g.read("nup_histogram", nup_histogram);
	g.read("ndown_histogram", ndown_histogram);
	g.read("entries_before_optimization", entries_before_optimization);
}

void pt_chain::checkpoint_write(const iodump::group &g) {
79
	g.write("params", params);
80 81 82
	g.write("nup_histogram", nup_histogram);
	g.write("ndown_histogram", ndown_histogram);
	g.write("entries_before_optimization", entries_before_optimization);
83 84 85 86
}

int pt_chain::histogram_entries() {
	return nup_histogram.at(0);
87 88 89 90 91 92 93
}

void pt_chain::clear_histograms() {
	std::fill(nup_histogram.begin(), nup_histogram.end(), 0);
	std::fill(ndown_histogram.begin(), ndown_histogram.end(), 0);
}

94

Lukas Weber's avatar
Lukas Weber committed
95 96 97 98
static double linear_regression(const std::vector<double> &x, const std::vector<double> &y, int i,
                                int range) {
	int lower = std::max(0, i - range + 1);
	int upper = std::min(static_cast<int>(y.size() - 1), i + range);
99 100 101 102

	double sxy = 0;
	double sx = 0, sy = 0;
	double sx2 = 0;
Lukas Weber's avatar
Lukas Weber committed
103

104
	for(int j = lower; j <= upper; j++) {
Lukas Weber's avatar
Lukas Weber committed
105
		sxy += x[j] * y[j];
106 107
		sx += x[j];
		sy += y[j];
Lukas Weber's avatar
Lukas Weber committed
108
		sx2 += x[j] * x[j];
109 110
	}

Lukas Weber's avatar
Lukas Weber committed
111 112
	int n = upper - lower + 1;
	return (sxy - sx * sy / n) / (sx2 - sx * sx / n);
113
}
114

115
/*
116 117 118 119 120 121 122 123
// x and y are ordered
static double linear_inverse(const std::vector<double> &x, const std::vector<double> &y, double y0) {
	for(size_t i = 0; i < y.size()-1; i++) {
		if((y[i]-y0)*(y[i+1]-y0) <= 0) {
			return x[i]+(x[i+1]-x[i])/(y[i+1]-y[i])*(y0-y[i]);
		}
	}
	throw std::out_of_range{"y0 outside of image of y(x)"};
124
}*/
125

126
std::tuple<double, double> pt_chain::optimize_params(double relaxation_fac) {
127 128 129 130 131
	std::vector<double> eta(params.size());
	std::vector<double> f(params.size());
	std::vector<double> new_params(params.size());

	assert(params.size() > 1);
Lukas Weber's avatar
Lukas Weber committed
132

133
	new_params[0] = params[0];
Lukas Weber's avatar
Lukas Weber committed
134
	new_params[params.size() - 1] = params[params.size() - 1];
135

Lukas Weber's avatar
ehhhh  
Lukas Weber committed
136 137 138
	double fnonlinearity = 0;
	// in the worst case, f=0 or f=1 for [1,N-2]
	int n = params.size();
139
	double fnonlinearity_worst = sqrt(n/3. + 1./(6*(n-1))-5./6.);
140 141 142 143
	for(size_t i = 0; i < params.size(); i++) {
		if(nup_histogram[i] + ndown_histogram[i] == 0) {
			f[i] = 0;
		} else {
Lukas Weber's avatar
Lukas Weber committed
144
			f[i] = nup_histogram[i] / static_cast<double>(nup_histogram[i] + ndown_histogram[i]);
145
		}
Lukas Weber's avatar
Lukas Weber committed
146

147
		double ideal_f = 1 - i / static_cast<double>(params.size()-1);
Lukas Weber's avatar
Lukas Weber committed
148
		fnonlinearity += (f[i] - ideal_f) * (f[i] - ideal_f);
149
	}
Lukas Weber's avatar
Lukas Weber committed
150
	fnonlinearity = sqrt(fnonlinearity) / fnonlinearity_worst;
151

152
	double norm = 0;
Lukas Weber's avatar
Lukas Weber committed
153
	for(size_t i = 0; i < params.size() - 1; i++) {
154 155
		double dfdp = 0;
		size_t linreg_len = 0;
Lukas Weber's avatar
Lukas Weber committed
156
		double dp = params[i + 1] - params[i];
157 158 159 160 161
		do {
			linreg_len++;
			dfdp = linear_regression(params, f, i, linreg_len);
		} while(dfdp * dp > 0 && linreg_len < params.size()/2);
			
Lukas Weber's avatar
Lukas Weber committed
162 163
		eta[i] = sqrt(std::max(0.01, -dfdp / dp));
		norm += eta[i] * dp;
164 165 166 167
	}
	for(auto &v : eta) {
		v /= norm;
	}
Lukas Weber's avatar
Lukas Weber committed
168 169

	double convergence = 0;
Lukas Weber's avatar
Lukas Weber committed
170 171
	for(size_t i = 1; i < params.size() - 1; i++) {
		double target = static_cast<double>(i) / (params.size() - 1);
172
		int etai = 0;
Lukas Weber's avatar
Lukas Weber committed
173 174
		for(etai = 0; etai < static_cast<int>(params.size()) - 1; etai++) {
			double deta = eta[etai] * (params[etai + 1] - params[etai]);
175 176 177 178 179
			if(deta > target) {
				break;
			}
			target -= deta;
		}
Lukas Weber's avatar
Lukas Weber committed
180
		new_params[i] = params[etai] + target / eta[etai];
Lukas Weber's avatar
Lukas Weber committed
181
		convergence += (new_params[i] - params[i]) * (new_params[i] - params[i]);
182 183
	}
	/*
184 185 186 187 188
	double convergence = 0;
	for(size_t i = 1; i < params.size() - 1; i++) {
		double target = 1-static_cast<double>(i) / (params.size()-1);
		new_params[i] = linear_inverse(params, f, target);
		convergence += (new_params[i] - params[i]) * (new_params[i] - params[i]);
189
	}*/
Lukas Weber's avatar
Lukas Weber committed
190

Lukas Weber's avatar
Lukas Weber committed
191
	convergence = sqrt(convergence) / (params.size() - 2);
Lukas Weber's avatar
Lukas Weber committed
192 193

	for(size_t i = 0; i < params.size(); i++) {
Lukas Weber's avatar
Lukas Weber committed
194
		params[i] = params[i] * (1 - relaxation_fac) + relaxation_fac * new_params[i];
Lukas Weber's avatar
Lukas Weber committed
195 196
	}

Lukas Weber's avatar
ehhhh  
Lukas Weber committed
197
	return std::tie(fnonlinearity, convergence);
198 199 200
}

bool pt_chain::is_done() {
201
	return sweeps >= target_sweeps + target_thermalization;
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
}

int runner_pt_start(jobinfo job, const mc_factory &mccreator, int argc, char **argv) {
	MPI_Init(&argc, &argv);

	int rank;
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);

	if(rank == 0) {
		runner_pt_master r{std::move(job)};
		r.start();
	} else {
		runner_pt_slave r{std::move(job), mccreator};
		r.start();
	}

	MPI_Finalize();

	return 0;
}

runner_pt_master::runner_pt_master(jobinfo job) : job_{std::move(job)} {
	rng_ = std::make_unique<random_number_generator>();
}

void runner_pt_master::construct_pt_chains() {
228 229 230
	std::string pt_param =
	    job_.jobfile["jobconfig"].get<std::string>("parallel_tempering_parameter");

231 232 233
	for(size_t i = 0; i < job_.task_names.size(); i++) {
		auto task = job_.jobfile["tasks"][job_.task_names[i]];

Lukas Weber's avatar
Lukas Weber committed
234
		auto [chain_id, chain_pos] = task.get<std::pair<int, int>>("pt_chain");
235 236 237 238 239
		if(chain_id < 0 || chain_pos < 0) {
			throw std::runtime_error{"parallel tempering pt_chain indices must be nonnegative"};
		}

		if(chain_id >= static_cast<int>(pt_chains_.size())) {
240
			pt_chains_.resize(chain_id + 1);
241 242 243 244 245 246
		}

		auto &chain = pt_chains_.at(chain_id);
		chain.id = chain_id;

		if(chain_pos >= static_cast<int>(chain.task_ids.size())) {
247
			chain.task_ids.resize(chain_pos + 1, -1);
248
			chain.params.resize(chain_pos + 1);
249
		}
250

251 252 253 254
		if(chain.task_ids.at(chain_pos) != -1) {
			throw std::runtime_error{"parallel tempering pt_chain map not unique"};
		}

255
		chain.params.at(chain_pos) = task.get<double>(pt_param);
256 257
		chain.task_ids.at(chain_pos) = i;

Lukas Weber's avatar
Lukas Weber committed
258 259
		const char *pt_sweep_error =
		    "in parallel tempering mode, sweeps are measured in global updates and need to be the "
260
		    "same within each chain: {} = {} != {}";
261

262
		int target_sweeps = task.get<int>("sweeps");
263
		if(chain.target_sweeps >= 0 && target_sweeps != chain.target_sweeps) {
Lukas Weber's avatar
Lukas Weber committed
264 265
			throw std::runtime_error{
			    fmt::format(pt_sweep_error, "target_sweeps", chain.target_sweeps, target_sweeps)};
266
		}
267
		chain.target_sweeps = target_sweeps;
Lukas Weber's avatar
Lukas Weber committed
268

269
		int target_thermalization = task.get<int>("thermalization");
Lukas Weber's avatar
Lukas Weber committed
270 271 272 273 274
		if(chain.target_thermalization >= 0 &&
		   target_thermalization != chain.target_thermalization) {
			throw std::runtime_error{fmt::format(pt_sweep_error, "thermalization",
			                                     chain.target_thermalization,
			                                     target_thermalization)};
275
		}
276
		chain.target_thermalization = target_thermalization;
Lukas Weber's avatar
Lukas Weber committed
277

278
		int sweeps_per_global_update = task.get<int>("pt_sweeps_per_global_update");
Lukas Weber's avatar
Lukas Weber committed
279
		int sweeps = job_.read_dump_progress(i) / sweeps_per_global_update;
280 281
		if(chain.sweeps >= 0 && sweeps != chain.sweeps) {
			throw std::runtime_error{fmt::format(pt_sweep_error, "sweeps", chain.sweeps != sweeps)};
282
		}
283
		chain.sweeps = sweeps;
284
	}
Lukas Weber's avatar
Lukas Weber committed
285

286 287 288 289 290
	chain_len_ = -1;
	for(auto &c : pt_chains_) {
		if(c.id == -1) {
			throw std::runtime_error{"parallel tempering pt_chain map contains gaps"};
		}
291

292 293 294
		if(chain_len_ != -1 && chain_len_ != static_cast<int>(c.task_ids.size())) {
			throw std::runtime_error{"parallel tempering pt_chains do not have the same length"};
		}
295

296
		chain_len_ = c.task_ids.size();
297 298 299

		c.nup_histogram.resize(chain_len_);
		c.ndown_histogram.resize(chain_len_);
300 301 302 303

		if(po_config_.enabled) {
			c.entries_before_optimization = po_config_.nsamples_initial;
		}
304 305
	}
	if(chain_len_ == -1) {
306 307 308
		throw std::runtime_error{
		    "parallel tempering pt_chain mapping missing. You need to specify 'pt_chain: "
		    "[chain_id, chain_position]' for every task in the job."};
309 310
	}

311 312 313 314
	if((num_active_ranks_ - 1) % chain_len_ != 0) {
		throw std::runtime_error{
		    "parallel tempering: number of ranks should be of the form chain_length*n+1 for best "
		    "efficiency"};
315 316 317 318 319 320 321
	}
}

void runner_pt_master::checkpoint_read() {
	construct_pt_chains();

	std::string master_dump_name = job_.jobdir() + "/pt_master.dump.h5";
322
	if(file_exists(master_dump_name)) {
323
		job_.log(fmt::format("master reading dump from '{}'", master_dump_name));
324 325 326 327 328 329
		iodump dump = iodump::open_readonly(master_dump_name);
		auto g = dump.get_root();

		rng_->checkpoint_read(g.open_group("random_number_generator"));
		auto pt_chain_runs = g.open_group("pt_chain_runs");
		for(std::string name : pt_chain_runs) {
330 331
			pt_chain_runs_.emplace_back(
			    pt_chain_run::checkpoint_read(pt_chain_runs.open_group(name)));
332 333
		}

334 335 336 337 338
		auto pt_chains = g.open_group("pt_chains");
		for(std::string name : pt_chains) {
			int id = std::stoi(name);
			pt_chains_.at(id).checkpoint_read(pt_chains.open_group(name));
		}
339 340 341
	}
}

342 343 344 345 346 347 348 349 350 351 352 353 354 355
void runner_pt_master::write_params_yaml() {
	using namespace YAML;
	Emitter params;
	params << BeginMap;
	for(auto c : pt_chains_) {
		params << Key << fmt::format("chain{:04d}", c.id);
		params << Value << Flow << c.params;
	}
	params << EndMap;

	std::ofstream file{job_.jobdir() + "/pt_optimized_params.yml"};
	file << params.c_str() << "\n";
}

356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
void runner_pt_master::write_param_optimization_stats() {
	std::string stat_name = job_.jobdir() + "/pt_param_stats.h5";
	iodump stat = iodump::open_readwrite(stat_name);
	auto g = stat.get_root();

	g.write("chain_length", chain_len_);
	
	for(auto &chain : pt_chains_) {
		auto cg = g.open_group(fmt::format("chain{:04d}", chain.id));
		std::vector<double> f(chain_len_);
		for(size_t i = 0; i < f.size(); i++) {
			f[i] = chain.nup_histogram[i]*1./(chain.ndown_histogram[i] + chain.nup_histogram[i]);
		}
		cg.insert_back("f", f);
		cg.insert_back("params", chain.params);
	}
}

374 375 376 377
void runner_pt_master::checkpoint_write() {
	std::string master_dump_name = job_.jobdir() + "/pt_master.dump.h5";

	job_.log(fmt::format("master: checkpoint {}", master_dump_name));
378

379 380 381 382 383 384
	iodump dump = iodump::create(master_dump_name);
	auto g = dump.get_root();

	rng_->checkpoint_write(g.open_group("random_number_generator"));
	auto pt_chain_runs = g.open_group("pt_chain_runs");
	for(auto &c : pt_chain_runs_) {
385 386
		c.checkpoint_write(
		    pt_chain_runs.open_group(fmt::format("chain{:04d}_run{:04d}", c.id, c.run_id)));
387 388
	}

389 390 391 392 393
	auto pt_chains = g.open_group("pt_chains");
	for(auto &c : pt_chains_) {
		c.checkpoint_write(pt_chains.open_group(fmt::format("{:04d}", c.id)));
	}

394
	if(po_config_.enabled) {
395 396
		write_params_yaml();
	}
397 398 399 400 401 402
}

void runner_pt_master::start() {
	MPI_Comm_size(MPI_COMM_WORLD, &num_active_ranks_);


403 404 405
	po_config_.enabled =
	    job_.jobfile["jobconfig"].defined("pt_parameter_optimization");
	if(po_config_.enabled) {
406
		job_.log("using feedback parameter optimization");
407 408 409 410
		const auto &po = job_.jobfile["jobconfig"]["pt_parameter_optimization"];
		po_config_.nsamples_initial = po.get<int>("nsamples_initial");
		po_config_.nsamples_growth = po.get<double>("nsamples_growth");
		po_config_.relaxation_fac = po.get<double>("relaxation_fac");
411 412
	}

413 414 415
	job_.log(fmt::format("starting job '{}' in parallel tempering mode", job_.jobname));
	checkpoint_read();

416 417
	std::vector<int> group_idx(num_active_ranks_);
	for(int i = 1; i < num_active_ranks_; i++) {
Lukas Weber's avatar
Lukas Weber committed
418
		group_idx[i] = (i - 1) / chain_len_;
419
	}
Lukas Weber's avatar
Lukas Weber committed
420
	MPI_Scatter(group_idx.data(), 1, MPI_INT, MPI_IN_PLACE, 1, MPI_INT, MASTER, MPI_COMM_WORLD);
Lukas Weber's avatar
Lukas Weber committed
421

422 423
	MPI_Comm tmp;
	MPI_Comm_split(MPI_COMM_WORLD, MPI_UNDEFINED, 0, &tmp);
Lukas Weber's avatar
Lukas Weber committed
424

425 426
	for(int rank_section = 0; rank_section < (num_active_ranks_ - 1) / chain_len_; rank_section++) {
		assign_new_chain(rank_section);
427 428 429
	}

	time_last_checkpoint_ = MPI_Wtime();
430

431 432 433 434 435 436 437
	while(num_active_ranks_ > 1) {
		react();
		if(MPI_Wtime() - time_last_checkpoint_ > job_.checkpoint_time) {
			time_last_checkpoint_ = MPI_Wtime();
			checkpoint_write();
		}
	}
438
	checkpoint_write();
439 440 441 442 443 444 445
}

int runner_pt_master::schedule_chain_run() {
	int old_id = current_chain_id_;
	int nchains = pt_chains_.size();
	for(int i = 1; i <= nchains; i++) {
		if(!pt_chains_[(old_id + i) % nchains].is_done()) {
446 447
			current_chain_id_ = (old_id + i) % nchains;
			auto &chain = pt_chains_[current_chain_id_];
448
			chain.scheduled_runs++;
449

450 451 452 453 454 455 456 457 458
			int idx = 0;
			for(auto &run : pt_chain_runs_) {
				if(run.id == chain.id && run.run_id == chain.scheduled_runs) {
					return idx;
				}
				idx++;
			}

			pt_chain_runs_.emplace_back(chain, chain.scheduled_runs);
459
			return pt_chain_runs_.size() - 1;
460 461 462 463 464 465 466
		}
	}

	// everything done!
	return -1;
}

467
int runner_pt_master::assign_new_chain(int rank_section) {
468 469 470
	int chain_run_id = schedule_chain_run();

	for(int target = 0; target < chain_len_; target++) {
471
		int msg[3] = {-1, 0, 0};
Lukas Weber's avatar
ehhhh  
Lukas Weber committed
472
		if(chain_run_id >= 0) {
473 474 475 476
			auto &chain_run = pt_chain_runs_[chain_run_id];
			auto &chain = pt_chains_[chain_run.id];
			msg[0] = chain.task_ids[target];
			msg[1] = chain_run.run_id;
477
			msg[2] = chain.target_sweeps + chain.target_thermalization - chain.sweeps;
478 479 480 481
		} else {
			// this will prompt the slave to quit
			num_active_ranks_--;
		}
482
		MPI_Send(&msg, sizeof(msg) / sizeof(msg[0]), MPI_INT,
483
		         rank_section * chain_len_ + target + 1, 0, MPI_COMM_WORLD);
484
	}
485
	rank_to_chain_run_[rank_section] = chain_run_id;
486 487 488
	return chain_run_id;
}

Lukas Weber's avatar
Lukas Weber committed
489 490 491 492 493
void runner_pt_master::pt_param_optimization(pt_chain &chain, pt_chain_run &chain_run) {
	for(size_t rank = 0; rank < chain_run.rank_to_pos.size(); rank++) {
		if(chain_run.rank_to_pos[rank] == 0) {
			chain_run.last_visited[rank] = 1;
		}
Lukas Weber's avatar
Lukas Weber committed
494
		if(chain_run.rank_to_pos[rank] == static_cast<int>(chain_run.rank_to_pos.size()) - 1) {
Lukas Weber's avatar
Lukas Weber committed
495 496 497
			chain_run.last_visited[rank] = -1;
		}

Lukas Weber's avatar
Lukas Weber committed
498 499
		chain.ndown_histogram[chain_run.rank_to_pos[rank]] += chain_run.last_visited[rank] == -1;
		chain.nup_histogram[chain_run.rank_to_pos[rank]] += chain_run.last_visited[rank] == 1;
Lukas Weber's avatar
Lukas Weber committed
500
	}
501
	if(chain.histogram_entries() >= chain.entries_before_optimization) {
502 503
		chain.entries_before_optimization *= po_config_.nsamples_growth;

504 505 506 507 508 509 510 511 512 513 514 515 516
		auto [fnonlinearity, convergence] = chain.optimize_params(po_config_.relaxation_fac);
		job_.log(
		    fmt::format("chain {}: pt param optimization: entries={}, f nonlinearity={:.2g}, "
		                "convergence={:.2g}",
		                chain.id, chain.histogram_entries(), fnonlinearity, convergence));
		checkpoint_write();
		write_param_optimization_stats();
		chain.clear_histograms();

		for(auto &cr : pt_chain_runs_) {
			if(cr.id == chain.id) {
				cr.clear_histograms();
			}
517
		}
Lukas Weber's avatar
Lukas Weber committed
518 519 520
	}
}

521
void runner_pt_master::react() {
522
	int rank_status;
523
	MPI_Status stat;
524 525 526
	MPI_Recv(&rank_status, 1, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &stat);
	int rank = stat.MPI_SOURCE - 1;
	if(rank_status == S_BUSY) {
527
		int msg[1];
Lukas Weber's avatar
Lukas Weber committed
528
		MPI_Recv(msg, sizeof(msg) / sizeof(msg[0]), MPI_INT, rank + 1, 0, MPI_COMM_WORLD, &stat);
529 530
		int completed_sweeps = msg[0];

531
		int chain_run_id = rank_to_chain_run_[rank / chain_len_];
532 533 534
		auto &chain_run = pt_chain_runs_[chain_run_id];
		auto &chain = pt_chains_[chain_run.id];

535
		chain.sweeps += completed_sweeps;
536
		if(chain.is_done()) {
537 538 539 540
			chain.scheduled_runs--;
			int action = A_NEW_JOB;

			if(chain.scheduled_runs > 0) {
Lukas Weber's avatar
Lukas Weber committed
541 542
				job_.log(fmt::format("chain {} has enough sweeps. Waiting for {} busy rank sets.",
				                     chain.id, chain.scheduled_runs));
543 544 545 546
			} else {
				job_.log(fmt::format("chain {} rank {} is done. Merging.", chain.id, rank + 1));
				action = A_PROCESS_DATA_NEW_JOB;
				checkpoint_write();
547
			}
548 549 550 551
			for(int target = 0; target < chain_len_; target++) {
				send_action(action, rank / chain_len_ * chain_len_ + target + 1);
			}
			assign_new_chain(rank / chain_len_);
552
		} else {
553 554 555
			for(int target = 0; target < chain_len_; target++) {
				send_action(A_CONTINUE, rank / chain_len_ * chain_len_ + target + 1);
			}
556
		}
557 558
	} else if(rank_status == S_READY_FOR_GLOBAL) {
		int chain_run_id = rank_to_chain_run_[rank / chain_len_];
559 560
		auto &chain_run = pt_chain_runs_[chain_run_id];
		auto &chain = pt_chains_[chain_run.id];
561
		int rank_section = rank / chain_len_;
Lukas Weber's avatar
Lukas Weber committed
562

563
		if(po_config_.enabled) {
Lukas Weber's avatar
Lukas Weber committed
564
			pt_param_optimization(chain, chain_run);
565 566 567
		}

		for(int target = 0; target < chain_len_; target++) {
Lukas Weber's avatar
Lukas Weber committed
568
			int target_rank = rank_section * chain_len_ + target + 1;
569
			int pos = chain_run.rank_to_pos[target];
570
			// keep consistent with pt_global_update
571
			int partner_pos = pos + (2 * (pos & 1) - 1) * (2 * chain_run.swap_odd - 1);
572 573
			if(partner_pos < 0 || partner_pos >= chain_len_) {
				int response = GA_SKIP;
574
				MPI_Send(&response, 1, MPI_INT, target_rank, 0, MPI_COMM_WORLD);
Lukas Weber's avatar
Lukas Weber committed
575
				chain_run.weight_ratios[pos] = 1;
576 577
			} else {
				int response = GA_CALC_WEIGHT;
578
				MPI_Send(&response, 1, MPI_INT, target_rank, 0, MPI_COMM_WORLD);
579

580 581 582 583
				double partner_param = chain.params[partner_pos];
				MPI_Send(&partner_param, 1, MPI_DOUBLE, target_rank, 0, MPI_COMM_WORLD);
			}
		}
584

585
		for(int target = 0; target < chain_len_; target++) {
Lukas Weber's avatar
Lukas Weber committed
586
			int target_rank = rank_section * chain_len_ + target + 1;
587 588
			int pos = chain_run.rank_to_pos[target];
			if(chain_run.weight_ratios[pos] < 0) {
589
				double weight;
590
				MPI_Recv(&weight, 1, MPI_DOUBLE, target_rank, 0, MPI_COMM_WORLD, &stat);
591
				assert(weight >= 0);
Lukas Weber's avatar
Lukas Weber committed
592
				chain_run.weight_ratios[pos] = weight;
593
			}
594
		}
595

596 597 598 599 600
		pt_global_update(chain, chain_run);
		std::fill(chain_run.weight_ratios.begin(), chain_run.weight_ratios.end(), -1);

		for(int target = 0; target < chain_len_; target++) {
			int new_task_id = chain.task_ids[chain_run.rank_to_pos[target]];
Lukas Weber's avatar
Lukas Weber committed
601
			int partner_rank = rank_section * chain_len_ + chain_run.switch_partners[target] + 1;
602
			int msg[2] = {new_task_id, partner_rank};
Lukas Weber's avatar
Lukas Weber committed
603 604
			MPI_Send(msg, sizeof(msg) / sizeof(msg[0]), MPI_INT,
			         rank_section * chain_len_ + target + 1, 0, MPI_COMM_WORLD);
605
			double new_param = chain.params[chain_run.rank_to_pos[target]];
Lukas Weber's avatar
Lukas Weber committed
606 607
			MPI_Send(&new_param, 1, MPI_DOUBLE, rank_section * chain_len_ + target + 1, 0,
			         MPI_COMM_WORLD);
608 609 610 611 612 613 614
		}
	} else { // S_TIMEUP
		num_active_ranks_--;
	}
}

void runner_pt_master::pt_global_update(pt_chain &chain, pt_chain_run &chain_run) {
615
	int i = 0;
Lukas Weber's avatar
Lukas Weber committed
616
	for(auto &p : chain_run.switch_partners) {
617 618 619
		p = i++;
	}
	for(int i = chain_run.swap_odd; i < static_cast<int>(chain.task_ids.size()) - 1; i += 2) {
620
		double w1 = chain_run.weight_ratios[i];
621
		double w2 = chain_run.weight_ratios[i + 1];
622 623 624

		double r = rng_->random_double();

625
		if(r < w1 * w2) {
626 627 628 629
			int rank0{};
			int rank1{};

			int rank = 0;
630
			for(auto &p : chain_run.rank_to_pos) {
Lukas Weber's avatar
Lukas Weber committed
631
				if(p == i) {
632
					rank0 = rank;
Lukas Weber's avatar
Lukas Weber committed
633
				} else if(p == i + 1) {
634
					rank1 = rank;
Lukas Weber's avatar
Lukas Weber committed
635
				}
636
				rank++;
Lukas Weber's avatar
Lukas Weber committed
637
			}
Lukas Weber's avatar
Lukas Weber committed
638
			chain_run.rank_to_pos[rank0] = i + 1;
639 640 641 642
			chain_run.rank_to_pos[rank1] = i;

			chain_run.switch_partners[rank0] = rank1;
			chain_run.switch_partners[rank1] = rank0;
643 644 645
		}
	}

646
	chain_run.swap_odd = !chain_run.swap_odd;
647 648 649 650 651 652 653 654 655 656
}

runner_pt_slave::runner_pt_slave(jobinfo job, mc_factory mccreator)
    : job_{std::move(job)}, mccreator_{std::move(mccreator)} {}

void runner_pt_slave::start() {
	MPI_Comm_rank(MPI_COMM_WORLD, &rank_);
	time_start_ = MPI_Wtime();
	time_last_checkpoint_ = time_start_;

657
	int group_idx;
Lukas Weber's avatar
Lukas Weber committed
658
	MPI_Scatter(NULL, 1, MPI_INT, &group_idx, 1, MPI_INT, MASTER, MPI_COMM_WORLD);
659
	MPI_Comm_split(MPI_COMM_WORLD, group_idx, 0, &chain_comm_);
Lukas Weber's avatar
Lukas Weber committed
660

661 662
	MPI_Comm_rank(chain_comm_, &chain_rank_);

Lukas Weber's avatar
Lukas Weber committed
663
	bool use_param_optimization =
664
	    job_.jobfile["jobconfig"].defined("pt_parameter_optimization");
665

666 667 668 669 670 671
	if(!accept_new_chain()) {
		return;
	}

	int action{};
	do {
672 673
		int timeout{TR_CHECKPOINT};

674 675 676
		while(sweeps_since_last_query_ < sweeps_before_communication_) {
			sys_->_do_update();

677
			if(sys_->is_thermalized() && !use_param_optimization) {
678 679 680 681 682
				sys_->_do_measurement();
			}

			if(sys_->sweep() % sweeps_per_global_update_ == 0) {
				pt_global_update();
683
				sweeps_since_last_query_++;
684

685 686 687 688
				timeout = negotiate_timeout();
				if(timeout != TR_CONTINUE) {
					break;
				}
689 690
			}
		}
691

692 693
		checkpoint_write();

694
		if(timeout == TR_TIMEUP) {
695
			send_status(S_TIMEUP);
696 697
			job_.log(fmt::format("rank {} exits: walltime up (safety interval = {} s)", rank_,
			                     sys_->safe_exit_interval()));
698 699 700 701 702 703 704 705 706 707 708
			break;
		}
		action = what_is_next(S_BUSY);
	} while(action != A_EXIT);

	if(action == A_EXIT) {
		job_.log(fmt::format("rank {} exits: out of work", rank_));
	}
}

void runner_pt_slave::send_status(int status) {
709
	MPI_Send(&status, 1, MPI_INT, MASTER, 0, MPI_COMM_WORLD);
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
int runner_pt_slave::negotiate_timeout() {
	double safe_interval = 0, max_safe_interval = 0;
	if(sys_ != nullptr) {
		safe_interval = sys_->safe_exit_interval();
	}

	MPI_Reduce(&safe_interval, &max_safe_interval, 1, MPI_DOUBLE, MPI_MAX, 0, chain_comm_);

	int result = TR_CONTINUE;
	if(chain_rank_ == 0) {
		if(MPI_Wtime() - time_last_checkpoint_ > job_.checkpoint_time) {
			result = TR_CHECKPOINT;
		}

		if(MPI_Wtime() - time_start_ > job_.walltime - max_safe_interval) {
			result = TR_TIMEUP;
		}
	}

	MPI_Bcast(&result, 1, MPI_INT, 0, chain_comm_);
	return result;
}

735
void runner_pt_slave::pt_global_update() {
736 737 738
	if(chain_rank_ == 0) {
		send_status(S_READY_FOR_GLOBAL);
	}
739 740

	int response;
741
	MPI_Recv(&response, 1, MPI_INT, MASTER, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
Lukas Weber's avatar
Lukas Weber committed
742
	// job_.log(fmt::format(" * rank {}: ready for global update", rank_));
743

Lukas Weber's avatar
Lukas Weber committed
744 745
	const std::string &param_name =
	    job_.jobfile["jobconfig"].get<std::string>("parallel_tempering_parameter");
746

747
	if(response == GA_CALC_WEIGHT) {
748
		double partner_param;
749
		MPI_Recv(&partner_param, 1, MPI_DOUBLE, MASTER, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
750
		double weight_ratio = sys_->_pt_weight_ratio(param_name, partner_param);
751
		MPI_Send(&weight_ratio, 1, MPI_DOUBLE, MASTER, 0, MPI_COMM_WORLD);
Lukas Weber's avatar
Lukas Weber committed
752
		// job_.log(fmt::format(" * rank {}: weight sent", rank_));
753
	} else {
Lukas Weber's avatar
Lukas Weber committed
754
		// job_.log(fmt::format(" * rank {}: no weight needed", rank_));
755
	}
756
	MPI_Barrier(chain_comm_);
757 758 759

	// this may be a long wait

760
	int msg[2];
Lukas Weber's avatar
Lukas Weber committed
761 762
	MPI_Recv(&msg, sizeof(msg) / sizeof(msg[0]), MPI_INT, MASTER, 0, MPI_COMM_WORLD,
	         MPI_STATUS_IGNORE);
763 764
	int new_task_id = msg[0];
	int target_rank = msg[1];
Lukas Weber's avatar
Lukas Weber committed
765

766
	double new_param;
767 768 769 770
	MPI_Recv(&new_param, 1, MPI_DOUBLE, MASTER, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);

	if(new_task_id != task_id_ || current_param_ != new_param) {
		task_id_ = new_task_id;
Lukas Weber's avatar
Lukas Weber committed
771 772
		sweeps_per_global_update_ = job_.jobfile["tasks"][job_.task_names[task_id_]].get<int>(
		    "pt_sweeps_per_global_update");
773
		sys_->_pt_update_param(target_rank, param_name, new_param);
774 775
	}
	current_param_ = new_param;
776 777 778 779
}

bool runner_pt_slave::accept_new_chain() {
	int msg[3];
780
	MPI_Recv(&msg, sizeof(msg) / sizeof(msg[0]), MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
781 782 783 784 785 786 787 788
	task_id_ = msg[0];
	run_id_ = msg[1];
	sweeps_before_communication_ = msg[2];

	if(task_id_ < 0) {
		return false;
	}

789 790
	sweeps_per_global_update_ =
	    job_.jobfile["tasks"][job_.task_names[task_id_]].get<int>("pt_sweeps_per_global_update");
791

792
	sys_ = std::unique_ptr<mc>{mccreator_(job_.jobfile["tasks"][job_.task_names[task_id_]])};
793
	sys_->pt_mode_ = true;
794 795 796 797 798 799 800 801 802 803 804 805
	if(!sys_->_read(job_.rundir(task_id_, run_id_))) {
		sys_->_init();
		job_.log(fmt::format("* initialized {}", job_.rundir(task_id_, run_id_)));
		checkpoint_write();
	} else {
		job_.log(fmt::format("* read {}", job_.rundir(task_id_, run_id_)));
	}

	return true;
}

int runner_pt_slave::what_is_next(int status) {
806 807
	if(chain_rank_ == 0) {
		send_status(status);
808

809 810 811
		int msg[1] = {sweeps_since_last_query_};
		MPI_Send(msg, sizeof(msg) / sizeof(msg[0]), MPI_INT, 0, 0, MPI_COMM_WORLD);
	}
812 813
	sweeps_since_last_query_ = 0;
	int new_action = recv_action();
814

815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
	if(new_action == A_EXIT) {
		return A_EXIT;
	}

	if(new_action != A_CONTINUE) {
		if(new_action == A_PROCESS_DATA_NEW_JOB) {
			merge_measurements();
		}

		if(!accept_new_chain()) {
			return A_EXIT;
		}
	}
	return A_CONTINUE;
}

void runner_pt_slave::checkpoint_write() {
	time_last_checkpoint_ = MPI_Wtime();
	sys_->_write(job_.rundir(task_id_, run_id_));
Lukas Weber's avatar
Lukas Weber committed
834
	job_.log(fmt::format("* rank {}: checkpoint {}", rank_, job_.rundir(task_id_, run_id_)));
835 836 837
}

void runner_pt_master::send_action(int action, int destination) {
838
	MPI_Send(&action, 1, MPI_INT, destination, 0, MPI_COMM_WORLD);
839 840 841 842
}

int runner_pt_slave::recv_action() {
	int new_action;
843
	MPI_Recv(&new_action, 1, MPI_INT, MASTER, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
844 845 846 847 848 849 850 851
	return new_action;
}

void runner_pt_slave::merge_measurements() {
	std::string unique_filename = job_.taskdir(task_id_);
	sys_->_write_output(unique_filename);

	std::vector<evalable> evalables;
852
	if(job_.jobfile["jobconfig"].defined("pt_parameter_optimization")) {
853 854 855 856 857 858
		if(rank_ == 1) {
			job_.log("Running in parameter optimization mode. No evalables are calculated.");
		}
	} else {
		sys_->register_evalables(evalables);
	}
859 860 861 862
	job_.merge_task(task_id_, evalables);
}

}