compstate.cpp 13.1 KB
Newer Older
1 2 3 4

#include "compstate.h"
#include "workerconn.h"
#include "server.h"
5
#include "solver.h"
6 7 8

#include "libloom/log.h"

9 10
constexpr static double TRANSFER_COST_COEF = 1.0 / (1024 * 1024); // 1MB = 1cost

11 12 13

ComputationState::ComputationState(Server &server) : server(server)
{
14 15 16 17 18
   loom::Dictionary &dictionary = server.get_dictionary();
   slice_task_id = dictionary.find_or_create("loom/base/slice");
   get_task_id = dictionary.find_or_create("loom/base/get");
   dslice_task_id = dictionary.find_or_create("loom/scheduler/dslice");
   dget_task_id = dictionary.find_or_create("loom/scheduler/dget");
19 20 21 22
}

void ComputationState::set_plan(Plan &&plan)
{
23
   this->plan = std::move(plan);
24 25 26 27
}

TaskDistribution ComputationState::compute_initial_distribution()
{
28 29 30
   auto task_ids = plan.get_init_tasks();
   add_ready_nodes(task_ids);
   return compute_distribution();
31 32 33 34
}

void ComputationState::add_worker(WorkerConnection* wconn)
{
35 36 37 38
   int index = workers.size();
   auto &w = workers[wconn];
   w.index = index;
   w.n_tasks = 0;
39 40 41 42
}

void ComputationState::set_running_task(WorkerConnection *wc, loom::Id id)
{
43
   TaskState &state = get_state(id);
44 45 46 47 48 49 50
   auto it = pending_tasks.find(id);
   assert(it != pending_tasks.end());
   pending_tasks.erase(it);

   assert(state.get_worker_status(wc) == TaskState::S_NONE);
   state.set_worker_status(wc, TaskState::S_RUNNING);
   workers[wc].n_tasks++;
51 52 53 54
}

void ComputationState::set_task_finished(loom::Id id, size_t size, size_t length, WorkerConnection *wc)
{
55 56 57 58 59 60
   TaskState &state = get_state(id);
   assert(state.get_worker_status(wc) == TaskState::S_RUNNING);
   state.set_worker_status(wc, TaskState::S_OWNER);
   state.set_size(size);
   state.set_length(length);
   workers[wc].n_tasks--;
61 62 63 64
}

void ComputationState::remove_state(loom::Id id)
{
65 66 67
   auto it = states.find(id);
   assert(it != states.end());
   states.erase(it);
68 69
}

70
void ComputationState::add_ready_nexts(const PlanNode &node)
71
{
72 73 74 75 76 77
   for (loom::Id id : node.get_nexts()) {
      const PlanNode &node = get_node(id);
      if (is_ready(node)) {
         if (node.get_policy() == PlanNode::POLICY_SCHEDULER) {
            expand_node(node);
         } else {
78
            add_pending_task(id);
79 80 81
         }
      }
   }
82 83
}

84 85 86 87 88
bool ComputationState::is_finished() const
{
    return states.empty();
}

89 90 91 92 93 94 95 96
void ComputationState::add_pending_task(loom::Id id)
{
   loom::llog->debug("Add pending task and creating state id={}", id);
   auto pair = states.emplace(std::make_pair(id, TaskState(get_node(id))));
   assert(pair.second);
   pending_tasks.insert(id);
}

97
void ComputationState::expand_node(const PlanNode &node)
98
{
99 100 101 102 103 104 105 106 107 108
   loom::Id id = node.get_task_type();

   if (id == dslice_task_id) {
      expand_dslice(node);
   } else if (id == dget_task_id) {
      expand_dget(node);
   } else {
      loom::llog->critical("Unknown scheduler task: {}", id);
      exit(1);
   }
109 110
}

111
void ComputationState::expand_dslice(const PlanNode &node)
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
   size_t n_cpus = 0;
   for (auto& pair : workers) {
      n_cpus += pair.first->get_resource_cpus();
   }
   assert(n_cpus);

   const PlanNode &node1 = node;
   assert(node1.get_nexts().size() == 1);
   // Do a copy again
   const PlanNode &node2 = get_node(node.get_nexts()[0]);

   std::vector<loom::Id> inputs = node.get_inputs();
   assert(inputs.size() == 1);
   TaskState &input = get_state(inputs[0]);
   size_t length = input.get_length();

   size_t slice_size = round(static_cast<double>(length) / (n_cpus * 4));
   // * 4 is just an heuristic, we probably need a better adjustment
   if (slice_size == 0) {
      slice_size = 1;
   }

   size_t i = 0;
   std::vector<std::string> configs;
   while (i < length) {
      size_t indices[2];
      indices[0] = i;
      indices[1] = i + slice_size;
      if (indices[1] > length) {
         indices[1] = length;
      }
      i = indices[1];
      configs.push_back(std::string(reinterpret_cast<char*>(&indices), sizeof(size_t) * 2));
   }

   loom::Id id_base1 = server.new_id(configs.size());
   loom::Id id_base2 = server.new_id(configs.size());

   loom::llog->debug("Expanding 'dslice' id={} length={} pieces={} new_id_base={}",
                     node1.get_id(), length, configs.size(), id_base1);

154
   PlanNode new_node(node1.get_id(),-1, PlanNode::POLICY_SIMPLE, -1, false,
155 156
                     slice_task_id, "", node1.get_inputs());
   make_expansion(configs, new_node, node2, id_base1, id_base2);
157 158
}

159
void ComputationState::expand_dget(const PlanNode &node)
160
{
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
   const PlanNode &node1 = node;
   assert(node1.get_nexts().size() == 1);
   // Do a copy again
   const PlanNode &node2 = get_node(node.get_nexts()[0]);

   std::vector<loom::Id> inputs = node.get_inputs();
   assert(inputs.size() == 1);
   TaskState &input = get_state(inputs[0]);
   size_t length = input.get_length();

   std::vector<std::string> configs;
   for (size_t i = 0; i < length; i++) {
      configs.push_back(std::string(reinterpret_cast<char*>(&i), sizeof(size_t)));
   }

   loom::Id id_base1 = server.new_id(configs.size());
   loom::Id id_base2 = server.new_id(configs.size());

   loom::llog->debug("Expanding 'dget' id={} length={} new_id_base={}",
                     node1.get_id(), length, id_base1);

182
   PlanNode new_node(node1.get_id(),-1, PlanNode::POLICY_SIMPLE, -1, false,
183 184
                     get_task_id, "", node1.get_inputs());
   make_expansion(configs, new_node, node2, id_base1, id_base2);
185 186 187
}

void ComputationState::make_expansion(std::vector<std::string> &configs,
188 189
                                      const PlanNode &n1,
                                      const PlanNode &n2,
190 191 192 193
                                      loom::Id id_base1,
                                      loom::Id id_base2)

{
194 195 196 197 198 199 200 201 202 203 204 205 206 207
   PlanNode node1 = n1; // Make copy
   PlanNode node2 = n2; // Make copy
   plan.remove_node(node1.get_id());
   plan.remove_node(node2.get_id());

   size_t size = configs.size();
   std::vector<int> ids1;
   ids1.reserve(size);

   std::vector<int> ids2;
   ids2.reserve(size);

   for (std::string &config1 : configs) {
      PlanNode t1(id_base1, -1,
208
                  node1.get_policy(), node1.get_n_cpus(), false,
209 210 211 212
                  node1.get_task_type(), config1, node1.get_inputs());
      t1.set_nexts(std::vector<loom::Id>{id_base2});
      plan.add_node(std::move(t1));

213
      add_pending_task(id_base1);
214 215

      PlanNode t2(id_base2, -1,
216
                  node2.get_policy(), node1.get_n_cpus(), false,
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
                  node2.get_task_type(), node2.get_config(),
                  std::vector<int>{id_base1});
      t2.set_nexts(node2.get_nexts());
      plan.add_node(std::move(t2));

      ids1.push_back(id_base1);
      id_base1++;
      ids2.push_back(id_base2);
      id_base2++;
   }

   for (loom::Id id : node1.get_inputs()) {
      plan.get_node(id).replace_next(node1.get_id(), ids1);
      get_state(id).inc_ref_counter(size - 1);
   }

   for (loom::Id id : node2.get_nexts()) {
      plan.get_node(id).replace_input(node2.get_id(), ids2);
   }
236 237 238
}


239
bool ComputationState::is_ready(const PlanNode &node)
240
{
241 242 243 244 245 246 247 248 249
   for (loom::Id id : node.get_inputs()) {
      if (states.find(id) == states.end()) {
         return false;
      }
      if (get_state(id).get_first_owner() == nullptr) {
         return false;
      }
   }
   return true;
250 251
}

252
int ComputationState::get_max_cpus()
253
{
254
    int max_cpus = 0;
255 256 257 258 259 260 261 262 263
    for (auto &pair : workers) {
        if (max_cpus < pair.first->get_resource_cpus()) {
            max_cpus = pair.first->get_resource_cpus();
        }
    }
    return max_cpus;
}


264 265
TaskDistribution ComputationState::compute_distribution()
{
266 267
   loom::llog->debug("Computation for distribution of {} task(s)", pending_tasks.size());

268 269 270 271 272 273 274 275 276
   TaskDistribution result;
   if (pending_tasks.empty()) {
      return result;
   }
   size_t n_workers = workers.size();
   if (n_workers == 0) {
      return result;
   }

277
   int max_cpus = get_max_cpus();
278 279 280 281
   if (max_cpus == 0) {
       max_cpus = 1;
   }

282 283 284 285 286 287
   size_t n_tasks = pending_tasks.size();

   size_t t_variables = n_workers * n_tasks;
   // + 1 because lp solve indexes from 1 :(
   std::vector<double> costs(t_variables + 1, 0.0);

288
   std::vector<loom::Id> tasks(pending_tasks.begin(), pending_tasks.end());
289 290 291 292 293 294

   /* [t_0,A] [t_0,B] ... [t_1,A] [t_1,B] ... [m_0,A] [m_0,B] ... [m_2,A] [m_2,B]
     * pending tasks t_X,A - X=task_index, A=worker_index
     * movable tasks m_X,A - X=task_index, A=worker_index
     */

295 296
   /* Gather all inputs
      and estimate the max transfer cost */
297
   std::unordered_map<loom::Id, int> inputs;
298
   std::vector<double> n_cpus; // we will later use it for coefs, we store it directly as double
299
   n_cpus.reserve(tasks.size());
300
   size_t total_size = 0;
301
   for (loom::Id id : tasks) {
302
      const PlanNode &node = get_node(id);
303
      n_cpus.push_back(node.get_n_cpus());
304 305 306 307 308 309 310 311 312 313 314 315 316 317
      for (loom::Id id2 : node.get_inputs()) {
         auto it = inputs.find(id2);
         if (it == inputs.end()) {
            inputs[id2] = costs.size();
            TaskState &state = get_state(id2);
            total_size += state.get_size();
            double cost = static_cast<double>(state.get_size()) * TRANSFER_COST_COEF;
            for (size_t i = 0; i < n_workers; i++) {
               costs.push_back(cost);
            }
         }
      }
   }

318
   /* Setup coeficients for exexuting a task */
319
   double task_cost = (total_size + 1) * 2 * TRANSFER_COST_COEF;
320 321 322 323 324 325 326 327 328 329 330 331
   for (size_t i = 0; i < n_tasks; i++) {
      double cpus = n_cpus[i];
      double coef;
      if (cpus < 1) {
          coef = task_cost;
      } else {
          coef = task_cost * (cpus + (cpus * cpus) / (max_cpus * max_cpus));
      }
      for (size_t j = 0; j < n_workers; j++) {
        // + 1 because we are counting from 1 ...
        costs[i * n_workers + j + 1] = -coef;
      }
332 333
   }

334
   /* Initialize solver and helper structures */
335 336 337 338 339 340 341 342
   size_t variables = costs.size() - 1;
   Solver solver(variables);
   std::vector<int> indices;
   indices.reserve(n_workers * n_tasks);
   std::vector<double> ones(variables, 1.0);

   size_t task_id = 1;

343
   /* Task constraints */
344 345 346 347 348
   for (loom::Id id : tasks) {
      indices.clear();
      for (size_t i = 0; i < n_workers; i++) {
         indices.push_back(task_id + i);
      }
349
      /* Task can be executed only once */
350 351 352 353 354 355 356 357 358 359
      solver.add_constraint_lq(indices, ones, 1);

      const PlanNode &node = get_node(id);
      std::unordered_set<loom::Id> nonlocals;
      for (auto pair : workers) {
         WorkerConnection *wc = pair.first;
         size_t index = pair.second.index;
         nonlocals.clear();
         collect_requirements_for_node(wc, node, nonlocals);
         for (loom::Id id2 : nonlocals) {
360
             /* What dataobjects have to be transfered? */
361 362 363 364 365 366 367 368 369 370 371 372 373 374
            solver.add_constraint_lq(task_id + index, inputs[id2] + index);
         }
      }
      task_id += n_workers;
   }

   indices.resize(n_tasks);
   for (auto &pair : workers) {
      WorkerConnection *wc = pair.first;
      size_t index = pair.second.index;
      size_t free_cpus = wc->get_resource_cpus() - pair.second.n_tasks;
      for (size_t j = 0; j < n_tasks; j++) {
         indices[j] = j * n_workers + index + 1;
      }
375
      /* Capacity limit for each worker */
376
      solver.add_constraint_lq(indices, n_cpus, free_cpus);
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
   }
   solver.set_objective_fn(costs);

   std::vector<double> solution = solver.solve();
   assert(solution.size() == variables);

   std::vector<WorkerConnection*> wconns(n_workers, nullptr);
   for (auto &pair : workers) {
      wconns[pair.second.index] = pair.first;
   }

   for (size_t i = 0; i < t_variables; i++) {
      if (solution[i]) {
         size_t worker_index = i % n_workers;
         size_t task_index = i / n_workers;
         assert(task_index < n_tasks);
         result[wconns[worker_index]].push_back(tasks[task_index]);
      }
   }


   return result;

   /*
401 402 403 404 405 406 407 408 409
    std::vector<WorkerConnection*> wc(n_workers, NULL);

    int i = 0;
    for (auto &pair : workers) {
        wc[i] = pair.first;
        i++;
    }

    for (loom::Id id : pending_tasks) {
410
        const PlanNode &node = get_node(id);
411 412 413 414 415 416 417 418
        int index;
        if (node.get_inputs().size() == 1) {
            index = node.get_inputs()[0];
        } else {
            index = id;
        }
        result[wc[index % n_workers]].push_back(id);
    }
419
    */
420 421
}

422
TaskState &ComputationState::get_state(loom::Id id)
423
{
424 425 426 427 428 429 430 431 432
   auto it = states.find(id);
   if (it == states.end()) {
      loom::llog->critical("Cannot find state for id={}", id);
      abort();
   }
   return it->second;

}

433
/*TaskState &ComputationState::get_state_or_create(loom::Id id)
Stanislav Bohm's avatar
Stanislav Bohm committed
434 435 436 437 438 439 440 441
{
   auto it = states.find(id);
   if (it == states.end()) {
      loom::llog->debug("Creating state id={}", id);
      auto p = states.emplace(std::make_pair(id, TaskState(get_node(id))));
      it = p.first;
   }
   return it->second;
442
}*/
Stanislav Bohm's avatar
Stanislav Bohm committed
443

444 445 446
void ComputationState::add_ready_nodes(const std::vector<loom::Id> &ids)
{
   for (loom::Id id : ids) {
447
      add_pending_task(id);
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
   }
}

void ComputationState::collect_requirements_for_node(WorkerConnection *wc,
                                                     const PlanNode &node,
                                                     std::unordered_set<loom::Id> &nonlocals)
{
   for (loom::Id id : node.get_inputs()) {
      TaskState &state = get_state(id);
      if (state.get_worker_status(wc) == TaskState::S_OWNER) {
         // nothing
      } else {
         nonlocals.insert(id);
      }
   }
463
}