Skip to content

Q-Learning: most of the runtime is spent by openmp waiting #1858

Closed

Description

@alberto-santini

Issue description

I am using QLearning with an FFN. I play each game for 150'000 turns (i.e., 150'000 actions are played). I would like to play 1000 such games (i.e., 1000 episodes).
Already at the first game, however, I noticed that the programme became abruptly slower after iteration 7500 and, from there on, it was just getting slower and slower. Memory, however, is under control and valgrind shows no leaks.
I used perf to figure out what was using so much cpu time, and it turns out that most of the time is consumed by two openmp functions: gomp_barrier_wait_end and gomp_team_barrier_wait_end.
Other relevant properties of my setup are a batch size of 100, a total buffer size of 15'000 (parameters passed to the constructor of RandomReplay).
The step size is 0.01, the discount 0.95, the interval between sync of the two networks is 7'500, the number of exploration steps is also 7'500 (this might be important, given the programme slows down at that point), double q-learning is disabled, the step limit is 150'000.
If it is relevant, all rewards are 0 but for the reward at iteration 150'000 which is a double between 0 and 1 (we never get there anyways).

I have a flamegraph generated from perf output, but GitHub won't allow me to upload. svg.
Programme htop shows all four cores almost always at 100% workload.

Your environment

  • version of mlpack: 3.0.4 (I am on Arch Linux where it's called 3.0.4-1)
  • operating system: Linux x1 5.0.5-arch1-1-ARCH #1 SMP PREEMPT
  • compiler: g++ (GCC) 8.2.1 20181127
  • version of dependencies (Boost/Armadillo): Boost 1.69.0, Armadillo 9.300.2
  • I am on a quad-core i7.

Steps to reproduce

Below are two files I use that reproduce the problem. Unfortunately they include other files from a large project by someone else. I could make the whole project available, with some effort, if this is needed.

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <cstdint>
#include <cassert>

#include "QAPInstance.h"
#include "PALNS-QAP.h"
#include "DestroyMethods.h"
#include "RepairMethods.h"
#include "PALNS-ML-QAP.h"

#include <mlpack/core.hpp>
#include <mlpack/core/optimizers/adam/adam_update.hpp>
#include <mlpack/methods/ann/ffn.hpp>
#include <mlpack/methods/ann/init_rules/gaussian_init.hpp>
#include <mlpack/methods/ann/layer/layer.hpp>
#include <mlpack/methods/ann/loss_functions/mean_squared_error.hpp>
#include <mlpack/methods/reinforcement_learning/q_learning.hpp>
#include <mlpack/methods/reinforcement_learning/policy/greedy_policy.hpp>
#include <mlpack/methods/reinforcement_learning/training_config.hpp>

int main(int argc, char** argv) {
  using namespace QAP;
  using namespace mlpack;
  using namespace mlpack::optimization;
  using namespace mlpack::ann;
  using namespace mlpack::rl;

  if(argc != 2) {
    std::cerr << "Just pass one parameter: the instance file.\n";
    std::_Exit(1);
  }

  std::ifstream ifs{argv[1]};
  
  if(ifs.fail()) {
    std::cerr << "Cannot open instance file.\n";
    std::_Exit(1);
  }

  // Load instance.
  QAPInstance inst;
  inst.load(ifs);

  // Create initial solution.
  QAPSolution sol{inst};
  QAPInitialSolutionCreator creator;
  TSRandom rng;
  creator.createInitialSolution(sol, rng);

  QAPMLSol solver{inst};

  // Initialise the weights as normal standard distributions with variance = 0.01
  FFN<MeanSquaredError<>, GaussianInitialization> model{
    MeanSquaredError<>{}, GaussianInitialization{0, 0.01} // mean, variance
  };

  // Neural network architecture ---

  // Input layer: from the state dimension to 32
  model.Add<Linear<>>(QAPMLSol::State::dimension, 64);
  // First activation function: ReLU
  model.Add<ReLULayer<>>();
  // Hidden layer: from 32 to 32
  model.Add<Linear<>>(64, 64);
  // Second activation function: ReLU
  model.Add<ReLULayer<>>();
  // Output layer: from 32 to the number of possible actions
  model.Add<Linear<>>(64, QAPMLSol::Action::size);

  // Epsilon-greedy policy to choose the action.
  // Think of this as a multi-armed bandit policy.
  const double initial_epsilon = 1.0;
  const double minimum_epsilon = 0.1;
  const std::size_t annealing_steps = solver.max_iter * 0.9;
  GreedyPolicy<QAPMLSol> epislon_greedy{initial_epsilon, annealing_steps, minimum_epsilon};

  // Replay buffer window.
  const std::size_t batch_size = 100; // Size of each batch we extract from the replay buffer.
  const std::size_t total_buffer_size = solver.max_iter * 0.1; // Total size of the replay buffer.
  RandomReplay<QAPMLSol> replay{batch_size, total_buffer_size};

  TrainingConfig config;

  // Weight that the new information has over the old information.
  config.StepSize() = 0.01;
  // Importance of future rewards over the immediate reward.
  config.Discount() = 0.95;
  // Iterations to synchronise the target network (theta) with the training one (theta minus).
  config.TargetNetworkSyncInterval() = solver.max_iter * 0.05;
  // Initial exploration steps before starting learning.
  config.ExplorationSteps() = solver.max_iter * 0.05;
  // Disable double Q learning, as it's not useful for us.
  config.DoubleQLearning() = false;
  // Number of steps per each episode.
  config.StepLimit() = solver.max_iter;

  // We initialise the "agent" to train.
  // Notice how we use Adam Update for training: gradient descent is not good enough for a DQN.
  QLearning<QAPMLSol, decltype(model), AdamUpdate, decltype(epislon_greedy)> agent{
    std::move(config), std::move(model), std::move(epislon_greedy), std::move(replay), AdamUpdate(), solver
  };

  arma::running_stat<double> training_reward;
  const std::size_t training_episodes = 1000u;

  for(auto episode = 1u; episode <= training_episodes; ++episode) {
    const double reward = agent.Episode();

    std::cout << "Episode " << episode << ", reward: " << reward << "\n";

    training_reward(reward);
  }

  std::cout << "Average reward over " << training_episodes << " training episodes: " << training_reward.mean() << "\n";

  // Now let's use the trained model.
  agent.Deterministic() = true;

  arma::running_stat<double> test_reward;
  const std::size_t test_reruns = 5u;
  
  for(auto test_episode = 1u; test_episode <= test_reruns; ++test_episode) {
    test_reward(agent.Episode());
  }

  std::cout << "Average test reward: " << test_reward.mean() << "\n";

  return 0;
}
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <cstdint>
#include <cassert>
#include <functional>
#include <memory>
#include <limits>

#include <mlpack/prereqs.hpp>

#include "QAPInstance.h"
#include "PALNS-QAP.h"
#include "DestroyMethods.h"
#include "RepairMethods.h"

namespace QAP {
  struct QAPMLSol {
    // Destroy/repair combinations.
    enum Action {
      random_greedy,
      random_worstfac,
      random_random,
      // ---
      size
    };

    struct State {
      // Pointer to the corresponding solution.
      std::unique_ptr<QAPSolution> sol = nullptr;

      // State variables ---

      // (Hamming) Distance to the best solution so far.
      double distance_to_best = 0.0;

      // Gap with the best solution so far.
      double gap_with_best = 0.0;

      // Number of iterations without improvement.
      std::uint32_t iter_without_improvement = 0u;

      // --- End State variables

      // State dimension (= # of state variables).
      static constexpr std::size_t dimension = 3u;

      State(const QAPSolution& sol_) : sol{std::make_unique<QAPSolution>(sol_)} {}

      State(const State& other) :
        sol{std::make_unique<QAPSolution>(*other.sol)},
        distance_to_best{other.distance_to_best},
        gap_with_best{other.gap_with_best},
        iter_without_improvement{other.iter_without_improvement} {}

      State() = default;

      void operator=(const State& other) {
        if(sol) {
          *sol = *other.sol;
        } else {
          sol = std::make_unique<QAPSolution>(*other.sol);
        }

        distance_to_best = other.distance_to_best;
        gap_with_best = other.gap_with_best;
        iter_without_improvement = other.iter_without_improvement;
      }

      arma::colvec Encode() const {
        return arma::colvec{
          distance_to_best,
          gap_with_best,
          static_cast<double>(iter_without_improvement)
        };
      }
    };

    // Destroy methods.
    RandomDestroy random_destroy = RandomDestroy{};

    // Repair methods.
    GreedyRepair greedy_repair = GreedyRepair{0.1};
    WorstFacFirstRepair worstfac_repair = WorstFacFirstRepair{0.1};
    RandomFacSeqRepair random_repair = RandomFacSeqRepair{0.1};

    // Instance of QAP to use.
    QAPInstance instance;

    // Best solution encountered so far.
    QAPSolution best_solution;

    // PRNG used by Stefan.
    TSRandom rng = TSRandom{};

    // Best known value for the instance (this is our target!).
    double instance_bks = 2344.0; // TODO - change this!

    // Stores the cost of the best solution.
    double best_cost = 0.0;

    // Acceptance criterion initial threshold (end threshold is 0).
    double init_threshold = 0.1;

    // Keeps track of the current threshold for the acceptance criterion.
    double threshold = 0.1;

    // Number of iterations of the algorithm.
    std::uint32_t max_iter = 150000u;

    // Keeps track of the current iteration number.
    std::uint32_t curr_iter = 0u;

    QAPMLSol(const QAPInstance& inst) : instance{inst}, best_solution{inst} {}

    // Re-initialise the agent.
    // In our case this means: restore the ALNS params and get an initial solution.
    State InitialSample() {
      QAPSolution sol{instance};
      QAPInitialSolutionCreator creator;
      TSRandom rng;

      creator.createInitialSolution(sol, rng);

      curr_iter = 0u;
      best_solution = sol;
      best_cost = std::numeric_limits<double>::max();
      threshold = 0.1;

      return State{sol};
    }

    // A state is terminal if we ran out of iterations.
    bool IsTerminal(const State&) const {
      return curr_iter == max_iter;
    }

    // Perform the action on the state, to obtain a next state.
    // The action implies applying the corresponding destroy/repair methods to the current solution;
    // the resulting new solution is then passed to the acceptance criterion.
    // We also update all the state variables in the state.
    double Sample(const State& state, const Action& action, State& next_state) {
      // Start from the current solution.
      next_state = state;

      // Only one destroy method.
      random_destroy.destroySolution(*next_state.sol, rng);

      // Choose the appropriate repair method.
      switch(action) {
        case random_greedy:
          greedy_repair.repairSolution(*next_state.sol, rng);
          break;
        case random_worstfac:
          worstfac_repair.repairSolution(*next_state.sol, rng);
          break;
        case random_random:
          random_repair.repairSolution(*next_state.sol, rng);
          break;
        default:
          assert(false);
      }

      // Update the best and iters without global improvement.
      const double cost = next_state.sol->getCost();

      if(cost < best_cost) {
        best_cost = cost;
        best_solution = *next_state.sol;
        next_state.iter_without_improvement = 0u;
      } else {
        ++next_state.iter_without_improvement;
      }

      // Compute the gap with the best solution so far.
      const double gap = (cost - best_cost) / cost;

      // If does not pass RRT acceptance, revert to sol.
      threshold -= init_threshold / max_iter;
      assert(threshold >= 0.0);
      if(gap > threshold) {
        // Revert! (reject new solution)
        assert(next_state.sol);
        assert(state.sol);
        *next_state.sol = *state.sol;
      } else {
        // Accept new solution
        next_state.distance_to_best = next_state.sol->dist(best_solution);
        next_state.gap_with_best = gap;
      }

      ++curr_iter;

      // If out of iterations, return the reward of the best solution.
      if(curr_iter == max_iter) {
        // To give high rewards to low gaps, we use 1 - bestgap.
        const double bestgap = (best_cost - instance_bks) / best_cost;
        return 1.0 - bestgap;
      }

      if(curr_iter % 1000 == 0) {
        std::cout << "iter " << curr_iter << "\n";
      }
      
      return 0.0;
    }
  };
}

Expected behavior

The programme should not abruptly slow down.

Actual behavior

The programme slows down considerably. A hypothesis is that it slows down when the exploration phase is over.

Activity

  1. alberto-santini commented on Apr 10, 2019

    @alberto-santini
    Author

    I can confirm that the slow-down starts after the exploration phase is over. I validated this by just changing the number of exploration steps to 15000 and the slow-down started at that point. One could think this is normal, except the profiler shows most of the time is spent in the openmp waiting functions, which I think is not normal.

  2. zoq commented on Apr 11, 2019

    @zoq
    Member

    Thanks for the bug report, at a first glance I think the sample code is good enough to reproduce the issue. One more thing, can you post the output of omp_get_thread_num(); Also do you see the same problem if you set omp_set_num_threads(1) at the beginning?

  3. alberto-santini commented on Apr 12, 2019

    @alberto-santini
    Author

    Hi zoq. Thanks for your answer.

    I am not sure if you really meant omp_get_num_threads (1) instead of omp_get_thread_num (2), so I collect both statistics.

    If I print these values before calling the first .Episode(), then I get that there is 1 thread in the team from (1) and that I am currently in thread 0 from (2). Unsurprising, I think.

    If I print the values from inside Sample(), however, I also get the same results. This is a bit more suspicious, as I see activity on all four cores. If only one core is being used to do the "real work", what are the other 3 doing? Are they waiting for some mutex? Is this the reason why som much time is spent in gomp_barrier_wait_end? I don't know.

    If I set omp_set_num_threads(1) then I can see that only one core is being used (again using htop). Furthermore, analysis with perf shows that no time is spend in the OMP wait functions. What is interesting, is that I still see a difference in performance between the pure exploration phase and the next phase. I am talking, here, about an order-of-magnitude difference.
    This is output obtained with omp_set_num_threads(1):

    Time for the last 500 iterations: 0.157778
    Time for the last 500 iterations: 0.123372
    Time for the last 500 iterations: 0.135202
    Time for the last 500 iterations: 0.140642
    Time for the last 500 iterations: 0.116866
    Time for the last 500 iterations: 0.166998
    Time for the last 500 iterations: 0.134346
    Time for the last 500 iterations: 0.148431
    Time for the last 500 iterations: 0.139219
    Time for the last 500 iterations: 0.139521
    Time for the last 500 iterations: 0.126131
    Time for the last 500 iterations: 0.135662
    Time for the last 500 iterations: 0.157964
    Time for the last 500 iterations: 0.150069
    Time for the last 500 iterations: 0.143616
    --- Here exploration ends ---
    Time for the last 500 iterations: 1.17963
    Time for the last 500 iterations: 1.16184
    Time for the last 500 iterations: 1.2662
    Time for the last 500 iterations: 1.21501
    Time for the last 500 iterations: 1.34459
    Time for the last 500 iterations: 1.22636
    Time for the last 500 iterations: 1.20782
    Time for the last 500 iterations: 1.24238
    Time for the last 500 iterations: 1.24119
    Time for the last 500 iterations: 1.21615
    Time for the last 500 iterations: 1.20411
    Time for the last 500 iterations: 1.2111
    Time for the last 500 iterations: 1.25297
    Time for the last 500 iterations: 1.3999
    Time for the last 500 iterations: 1.34759
    ...
    

    While this output is obtained without omp_set_num_threads(1):

    Time for the last 500 iterations: 0.149637
    Time for the last 500 iterations: 0.126199
    Time for the last 500 iterations: 0.136265
    Time for the last 500 iterations: 0.141523
    Time for the last 500 iterations: 0.125617
    Time for the last 500 iterations: 0.1719
    Time for the last 500 iterations: 0.138523
    Time for the last 500 iterations: 0.138666
    Time for the last 500 iterations: 0.144331
    Time for the last 500 iterations: 0.145882
    Time for the last 500 iterations: 0.129022
    Time for the last 500 iterations: 0.151131
    Time for the last 500 iterations: 0.161567
    Time for the last 500 iterations: 0.153611
    Time for the last 500 iterations: 0.132605
    --- Here exploration ends ---
    Time for the last 500 iterations: 1.7721
    Time for the last 500 iterations: 1.71117
    Time for the last 500 iterations: 1.76272
    Time for the last 500 iterations: 2.01902
    Time for the last 500 iterations: 1.78165
    Time for the last 500 iterations: 1.80061
    Time for the last 500 iterations: 1.77397
    Time for the last 500 iterations: 1.81706
    Time for the last 500 iterations: 1.82944
    Time for the last 500 iterations: 1.82595
    Time for the last 500 iterations: 1.82768
    Time for the last 500 iterations: 1.83973
    Time for the last 500 iterations: 1.83825
    

    One can see that the second output shows worse times, perhaps due to synchronisation overhead. But still, I would love to see no 10x increase in time at all. Or... is such an increase physiological?

    Thanks.

  4. cascala commented on Apr 13, 2019

    @cascala
    Contributor

    Side question: How does one retrieve the learned parameters from a QLearning agent instance?

  5. alberto-santini commented on Apr 14, 2019

    @alberto-santini
    Author

    @cascala : I don't think it's a great idea to mix questions in unrelated issues. However, I think you can serialise your whole neural network, have a look at ::serialize.

  6. cascala commented on Apr 14, 2019

    @cascala
    Contributor

    @cascala : I don't think it's a great idea to mix questions in unrelated issues. However, I think you can serialise your whole neural network, have a look at ::serialize.

    Good point, I moved my question to another issue. Thank you for the suggestion.

  7. mlpack-bot commented on May 14, 2019

    @mlpack-bot

    This issue has been automatically marked as stale because it has not had any recent activity. It will be closed in 7 days if no further activity occurs. Thank you for your contributions! 👍

  8. zoq commented on May 14, 2019

    @zoq
    Member

    Let's keep this open, still have to take a closer look into the issue.

  9. mattg-sp commented on Apr 13, 2021

    @mattg-sp

    Hello. I stumbled across this while researching a similar issue. The workaround I've found is to export the environment variable OMP_WAIT_POLICY=passive.

    However, from reading the source code of libgomp, it seems to me there's a possibility the dependent variable won't be set. In that case, you might get lucky and find it's 0 (as seems to be the case, for me), but you could be sure by also exporting GOMP_SPINCOUNT=0.

    For details, see: https://github.com/gcc-mirror/gcc/blob/master/libgomp/env.c

    And the place where these variables are influencing the problematic behavior is in: https://github.com/gcc-mirror/gcc/blob/master/libgomp/config/linux/wait.h

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions