XACC
mlpack_optimizer.hpp
1 /*******************************************************************************
2  * Copyright (c) 2019 UT-Battelle, LLC.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * and Eclipse Distribution License v1.0 which accompanies this
6  * distribution. The Eclipse Public License is available at
7  * http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution
8  *License is available at https://eclipse.org/org/documents/edl-v10.php
9  *
10  * Contributors:
11  * Alexander J. McCaskey - initial API and implementation
12  *******************************************************************************/
13 #ifndef XACC_MLPACK_OPTIMIZER_HPP_
14 #define XACC_MLPACK_OPTIMIZER_HPP_
15 
16 #include <type_traits>
17 #include <utility>
18 
19 #include "Optimizer.hpp"
20 #include <armadillo>
21 #include <ensmallen.hpp>
22 
23 namespace xacc {
24 
26 protected:
27  std::vector<double> grad;
28  OptFunction &opt_function;
29 
30 public:
32  : opt_function(optF), grad(std::vector<double>(optF.dimensions())) {}
33  std::size_t NumFunctions() const { return 1; }
34  void Shuffle() { /* Nothing to do here */
35  }
36 
37  // Given parameters x, return the value of f(x).
38  double Evaluate(const arma::mat &x) {
39  auto x_vec = arma::conv_to<std::vector<double>>::from(x);
40  return opt_function(x_vec, grad);
41  }
42 
43  double Evaluate(const arma::mat &coordinates, const size_t begin,
44  const size_t batchSize) {
45  return Evaluate(coordinates);
46  }
47  double EvaluateWithGradient(const arma::mat &coordinates,
48  arma::mat &gradient) {
49  auto val = Evaluate(coordinates);
50  Gradient(coordinates, gradient);
51  return val;
52  }
53  double EvaluateWithGradient(const arma::mat &coordinates, std::size_t bb,
54  arma::mat &gradient, std::size_t b) {
55  auto val = Evaluate(coordinates);
56  Gradient(coordinates, gradient);
57  return val;
58  }
59  // Given parameters x and a matrix g, store f'(x) in the provided matrix g.
60  // g should have the same size (rows, columns) as x.
61  void Gradient(const arma::mat &x, arma::mat &gradient) {
62  arma::mat g(grad);
63  gradient = g;
64  }
65 };
66 
67 class MLPACKOptimizer : public Optimizer {
68 public:
69  MLPACKOptimizer() = default;
70  OptResult optimize(OptFunction &function) override;
71 
72  const std::string name() const override { return "mlpack"; }
73  const std::string description() const override { return ""; }
74 };
75 } // namespace xacc
76 #endif
Definition: mlpack_optimizer.hpp:25
Definition: Accelerator.hpp:25
Definition: Optimizer.hpp:48
const std::string description() const override
Definition: mlpack_optimizer.hpp:73
const std::string name() const override
Definition: mlpack_optimizer.hpp:72
Definition: Optimizer.hpp:31
Definition: mlpack_optimizer.hpp:67