py-qcor.cpp 15.9 KB
Newer Older
1
2
#include <pybind11/complex.h>
#include <pybind11/eigen.h>
3
#include <pybind11/functional.h>
4
#include <pybind11/iostream.h>
5
#include <pybind11/numpy.h>
6
#include <pybind11/operators.h>
7
8
9
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
10
11

#include "base/qcor_qsim.hpp"
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
12
#include "py_costFunctionEvaluator.hpp"
13
#include "py_qsimWorkflow.hpp"
14
#include "qcor_jit.hpp"
15
#include "qcor_observable.hpp"
16
17
18
#include "qrt.hpp"
#include "xacc.hpp"
#include "xacc_internal_compiler.hpp"
19
#include "xacc_service.hpp"
20

21
namespace py = pybind11;
22
23
24
25
26
27
28
using namespace xacc;

namespace pybind11 {
namespace detail {
template <typename... Ts>
struct type_caster<Variant<Ts...>> : variant_caster<Variant<Ts...>> {};

29
30
template <>
struct visit_helper<Variant> {
31
32
33
34
35
36
37
38
39
40
  template <typename... Args>
  static auto call(Args &&... args) -> decltype(mpark::visit(args...)) {
    return mpark::visit(args...);
  }
};

template <typename... Ts>
struct type_caster<mpark::variant<Ts...>>
    : variant_caster<mpark::variant<Ts...>> {};

41
42
template <>
struct visit_helper<mpark::variant> {
43
44
45
46
47
  template <typename... Args>
  static auto call(Args &&... args) -> decltype(mpark::visit(args...)) {
    return mpark::visit(args...);
  }
};
48
49
}  // namespace detail
}  // namespace pybind11
50

51
namespace {
52

53
54
// We only allow certain argument types for quantum kernel functors in python
// Here we enumerate them as a Variant
55
using AllowedKernelArgTypes =
56
57
    xacc::Variant<bool, int, double, std::string, xacc::internal_compiler::qreg,
                  std::vector<double>>;
58
59

// We will take as input a mapping of arg variable names to the argument itself.
60
using KernelArgDict = std::map<std::string, AllowedKernelArgTypes>;
61
62

// Utility for mapping KernelArgDict to a HeterogeneousMap
63
64
65
66
67
68
69
70
71
72
73
74
75
76
class KernelArgDictToHeterogeneousMap {
 protected:
  xacc::HeterogeneousMap &m;
  const std::string &key;

 public:
  KernelArgDictToHeterogeneousMap(xacc::HeterogeneousMap &map,
                                  const std::string &k)
      : m(map), key(k) {}
  template <typename T>
  void operator()(const T &t) {
    m.insert(key, t);
  }
};
77

78
// Add type name to this list to support receiving from Python.
79
80
using PyHeterogeneousMapTypes = xacc::Variant<bool, int, double, std::string,
                                              std::shared_ptr<qcor::Optimizer>>;
81
82
83
84
using PyHeterogeneousMap = std::map<std::string, PyHeterogeneousMapTypes>;

// Helper to convert a Python *dict* (as a map of variants) into a native
// HetMap.
85
86
xacc::HeterogeneousMap heterogeneousMapConvert(
    const PyHeterogeneousMap &in_pyMap) {
87
88
89
90
91
92
93
94
  xacc::HeterogeneousMap result;
  for (auto &item : in_pyMap) {
    auto visitor = [&](const auto &value) { result.insert(item.first, value); };
    mpark::visit(visitor, item.second);
  }

  return result;
}
95
}  // namespace
96

97
98
namespace qcor {

Mccaskey, Alex's avatar
Mccaskey, Alex committed
99
100
101
102
103
104
105
106
107
108
// PyObjectiveFunction implements ObjectiveFunction to
// enable the utility of pythonic quantum kernels with the
// existing qcor ObjectiveFunction infrastructure. This class
// keeps track of the quantum kernel as a py::object, which it uses
// in tandem with the QCOR QJIT engine to create an executable
// functor representation of the quantum code at runtime. It exposes
// the ObjectiveFunction operator()() overloads to map vector<double>
// x to the correct pythonic argument structure. It delegates to the
// usual helper ObjectiveFunction (like vqe) for execution of the
// actual pre-, execution, and post-processing.
109
110
111
112
113
114
115
116
117
118
119
120
121
class PyObjectiveFunction : public qcor::ObjectiveFunction {
 protected:
  py::object py_kernel;
  std::shared_ptr<ObjectiveFunction> helper;
  xacc::internal_compiler::qreg qreg;
  QJIT qjit;

 public:
  const std::string name() const override { return "py-objective-impl"; }
  const std::string description() const override { return ""; }
  PyObjectiveFunction(py::object q, qcor::PauliOperator &qq, const int n_dim,
                      const std::string &helper_name)
      : py_kernel(q) {
122
    // Set the OptFunction dimensions
123
    _dim = n_dim;
124
125

    // Set the helper objective
126
    helper = xacc::getService<qcor::ObjectiveFunction>(helper_name);
127
128

    // Store the observable pointer and give it to the helper
129
130
    observable = xacc::as_shared_ptr(&qq);
    helper->update_observable(observable);
131
132

    // Extract the QJIT source code
133
134
    auto src = py_kernel.attr("get_internal_src")().cast<std::string>();

135
    // QJIT compile
136
137
    // this will be fast if already done, and we just do it once
    qjit.jit_compile(src, true);
138
    qjit.write_cache();
139
140
  }

Mccaskey, Alex's avatar
Mccaskey, Alex committed
141
142
  // Evaluate this ObjectiveFunction at the dictionary of kernel args,
  // return the scalar value
143
  double operator()(const KernelArgDict args) {
144
    // Map the kernel args to a hetmap
145
146
147
148
149
    xacc::HeterogeneousMap m;
    for (auto &item : args) {
      KernelArgDictToHeterogeneousMap vis(m, item.first);
      mpark::visit(vis, item.second);
    }
150
151

    // Get the kernel as a CompositeInstruction
152
153
154
    auto kernel_name = py_kernel.attr("kernel_name")().cast<std::string>();
    kernel = qjit.extract_composite_with_hetmap(kernel_name, m);
    helper->update_kernel(kernel);
155
156

    // FIXME, handle gradients
157
158
159
    std::vector<double> dx;
    return (*helper)(qreg, dx);
  }
160
161

  // Evaluate this ObjectiveFunction at the parameters x
162
163
164
165
166
167
168
169
170
171
172
  double operator()(const std::vector<double> &x,
                    std::vector<double> &dx) override {
    current_iterate_parameters = x;
    helper->update_current_iterate_parameters(x);

    // Translate x into kernel args
    qreg = ::qalloc(observable->nBits());
    auto args = py_kernel.attr("translate")(qreg, x).cast<KernelArgDict>();
    // args will be a dictionary, arg_name to arg
    return operator()(args);
  }
173

174
175
176
177
178
179
180
  virtual double operator()(xacc::internal_compiler::qreg &qreg,
                            std::vector<double> &dx) {
    throw std::bad_function_call();
    return 0.0;
  }
};

Mccaskey, Alex's avatar
Mccaskey, Alex committed
181
182
183
184
185
// PyKernelFunctor is a subtype of KernelFunctor from the qsim library
// that returns a CompositeInstruction representation of a pythonic
// quantum kernel given a vector of parameters x. This will
// leverage the QJIT infrastructure to create executable functor
// representation of the python kernel.
186
187
188
189
190
191
192
193
194
195
196
197
198
class PyKernelFunctor : public qcor::KernelFunctor {
 protected:
  py::object py_kernel;
  QJIT qjit;
  std::size_t n_qubits;

 public:
  PyKernelFunctor(py::object q, const std::size_t nq, const std::size_t np)
      : py_kernel(q), n_qubits(nq) {
    nbParams = np;
    auto src = py_kernel.attr("get_internal_src")().cast<std::string>();
    // this will be fast if already done, and we just do it once
    qjit.jit_compile(src, true);
199
    qjit.write_cache();
200
201
  }

Mccaskey, Alex's avatar
Mccaskey, Alex committed
202
203
  // Delegate to QJIT to create a CompositeInstruction representation
  // of the pythonic quantum kernel.
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
  std::shared_ptr<xacc::CompositeInstruction> evaluate_kernel(
      const std::vector<double> &x) override {
    // Translate x into kernel args
    auto qreg = ::qalloc(n_qubits);
    auto args = py_kernel.attr("translate")(qreg, x).cast<KernelArgDict>();
    xacc::HeterogeneousMap m;
    for (auto &item : args) {
      KernelArgDictToHeterogeneousMap vis(m, item.first);
      mpark::visit(vis, item.second);
    }
    auto kernel_name = py_kernel.attr("kernel_name")().cast<std::string>();
    return qjit.extract_composite_with_hetmap(kernel_name, m);
  }
};
}  // namespace qcor

220
221
PYBIND11_MODULE(_pyqcor, m) {
  m.doc() = "Python bindings for QCOR.";
222
223
224
225
226
227
228
229
230
231

  py::class_<AllowedKernelArgTypes>(
      m, "AllowedKernelArgTypes",
      "The AllowedKernelArgTypes provides a variant structure "
      "to provide parameters to qcor quantum kernels HeterogeneousMaps.")
      .def(py::init<int>(), "Construct as an int.")
      .def(py::init<bool>(), "Construct as a bool")
      .def(py::init<double>(), "Construct as a double.")
      .def(py::init<std::string>(), "Construct as a string.")
      .def(py::init<xacc::internal_compiler::qreg>(), "Construct as qreg")
232
      .def(py::init<std::vector<double>>(), "Construct as a List[double].");
233

234
  // Expose QCOR API functions
235
  // Handle QCOR CLI arguments:
236
  // when using via Python, we use this to set those runtime parameters.
237
  m.def(
238
239
240
241
242
243
244
      "Initialize",
      [](py::kwargs kwargs) {
        if (kwargs) {
          for (auto arg : kwargs) {
            const auto key = std::string(py::str(arg.first));
            // Handle "qpu" key
            if (key == "qpu") {
245
246
247
248
249
              const auto value = std::string(py::str(arg.second));
              ::quantum::initialize(value, "empty");
            } else if (key == "shots") {
              const auto value = arg.second.cast<int>();
              ::quantum::set_shots(value);
250
251
252
            }
            /// TODO: handle other CLI parameters.
          }
253
        }
254
255
      },
      "Initialize QCOR runtime environment.");
256

257
258
259
  // Expose QCOR API functions
  m.def(
      "createOptimizer",
260
261
      [](const std::string &name, PyHeterogeneousMap p = {}) {
        return qcor::createOptimizer(name, heterogeneousMapConvert(p));
262
      },
263
      py::arg("name"), py::arg("p") = PyHeterogeneousMap(),
264
265
      py::return_value_policy::reference,
      "Return the Optimizer with given name.");
266

267
268
  m.def(
      "set_qpu",
Mccaskey, Alex's avatar
Mccaskey, Alex committed
269
270
271
      [](const std::string &name, PyHeterogeneousMap p = {}) {
        xacc::internal_compiler::qpu =
            xacc::getAccelerator(name, heterogeneousMapConvert(p));
272
      },
Mccaskey, Alex's avatar
Mccaskey, Alex committed
273
      py::arg("name"), py::arg("p") = PyHeterogeneousMap(),
274
275
276
277
278
      "Set the QPU backend.");

  m.def("qalloc", &::qalloc, py::return_value_policy::reference, "");
  py::class_<xacc::internal_compiler::qreg>(m, "qreg", "")
      .def("size", &xacc::internal_compiler::qreg::size, "")
Mccaskey, Alex's avatar
Mccaskey, Alex committed
279
280
281
      .def("print", &xacc::internal_compiler::qreg::print, "")
      .def("counts", &xacc::internal_compiler::qreg::counts, "")
      .def("exp_val_z", &xacc::internal_compiler::qreg::exp_val_z, "");
282

283
  // m.def("createObjectiveFunction", [](const std::string name, ))
284
285
  py::class_<qcor::QJIT, std::shared_ptr<qcor::QJIT>>(m, "QJIT", "")
      .def(py::init<>(), "")
286
      .def("write_cache", &qcor::QJIT::write_cache, "")
287
      .def("jit_compile", &qcor::QJIT::jit_compile, "")
Mccaskey, Alex's avatar
Mccaskey, Alex committed
288
289
290
291
292
293
294
      .def(
          "internal_python_jit_compile",
          [](qcor::QJIT &qjit, const std::string src) {
            bool turn_on_hetmap_kernel_ctor = true;
            qjit.jit_compile(src, turn_on_hetmap_kernel_ctor);
          },
          "")
295
296
297
298
299
300
301
302
303
304
305
      .def("run_syntax_handler", &qcor::QJIT::run_syntax_handler, "")
      .def(
          "invoke",
          [](qcor::QJIT &qjit, const std::string name, KernelArgDict args) {
            xacc::HeterogeneousMap m;
            for (auto &item : args) {
              KernelArgDictToHeterogeneousMap vis(m, item.first);
              mpark::visit(vis, item.second);
            }
            qjit.invoke_with_hetmap(name, m);
          },
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
          "")
      .def("extract_composite",
           [](qcor::QJIT &qjit, const std::string name, KernelArgDict args) {
             xacc::HeterogeneousMap m;
             for (auto &item : args) {
               KernelArgDictToHeterogeneousMap vis(m, item.first);
               mpark::visit(vis, item.second);
             }
             return qjit.extract_composite_with_hetmap(name, m);
           });

  py::class_<qcor::ObjectiveFunction, std::shared_ptr<qcor::ObjectiveFunction>>(
      m, "ObjectiveFunction", "")
      .def("dimensions", &qcor::ObjectiveFunction::dimensions, "")
      .def(
          "__call__",
          [](qcor::ObjectiveFunction &obj, std::vector<double> x) {
            return obj(x);
          },
325
326
          "");

327
328
329
330
331
332
333
334
335
336
337
  m.def(
      "createObjectiveFunction",
      [](py::object kernel, qcor::PauliOperator &obs, const int n_params) {
        auto q = ::qalloc(obs.nBits());
        std::shared_ptr<qcor::ObjectiveFunction> obj =
            std::make_shared<qcor::PyObjectiveFunction>(kernel, obs, n_params,
                                                        "vqe");
        return obj;
      },
      "");

338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
  // qsim sub-module bindings:
  {
    py::module qsim = m.def_submodule("qsim", "QCOR's python qsim submodule");

    // QuantumSimulationModel bindings:
    py::class_<qcor::qsim::QuantumSimulationModel>(
        qsim, "QuantumSimulationModel",
        "The QuantumSimulationModel captures the quantum simulation problem "
        "description.")
        .def(py::init<>());

    // ModelBuilder bindings:
    py::class_<qcor::qsim::ModelBuilder>(
        qsim, "ModelBuilder",
        "The ModelBuilder interface provides methods to "
        "construct qsim problem models.")
        .def(py::init<>())
        .def(
            "createModel",
            [](qcor::PauliOperator &obs, qcor::qsim::TdObservable ham_func) {
              return qcor::qsim::ModelBuilder::createModel(obs, ham_func);
            },
360
            "Return the Model for a time-dependent problem.")
Mccaskey, Alex's avatar
Mccaskey, Alex committed
361
362
363
364
365
366
367
368
369
370
371
372
373
374
        .def(
            "createModel",
            [](py::object py_kernel, qcor::PauliOperator &obs,
               const int n_params) {
              qcor::qsim::QuantumSimulationModel model;
              auto nq = obs.nBits();
              auto kernel_functor = std::make_shared<qcor::PyKernelFunctor>(
                  py_kernel, nq, n_params);
              model.observable = &obs;
              model.user_defined_ansatz = kernel_functor;
              return std::move(model);
            },
            "")
            
375
376
377
378
379
380
381
382
383
384
385
386
        .def(
            "createModel",
            [](py::object py_kernel, qcor::PauliOperator &obs,
               const int n_qubits, const int n_params) {
              qcor::qsim::QuantumSimulationModel model;
              auto kernel_functor = std::make_shared<qcor::PyKernelFunctor>(
                  py_kernel, n_qubits, n_params);
              model.observable = &obs;
              model.user_defined_ansatz = kernel_functor;
              return std::move(model);
            },
            "");
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415

    // CostFunctionEvaluator bindings
    py::class_<qcor::qsim::CostFunctionEvaluator,
               std::shared_ptr<qcor::qsim::CostFunctionEvaluator>,
               qcor::qsim::PyCostFunctionEvaluator>(
        qsim, "CostFunctionEvaluator",
        "The CostFunctionEvaluator interface provides methods to "
        "evaluate the observable operator expectation value on quantum "
        "backends.")
        .def(py::init<>())
        .def(
            "initialize",
            [](qcor::qsim::CostFunctionEvaluator &self,
               qcor::PauliOperator &obs) { return self.initialize(&obs); },
            "Initialize the evaluator")
        .def(
            "evaluate",
            [](qcor::qsim::CostFunctionEvaluator &self,
               std::shared_ptr<CompositeInstruction> state_prep) -> double {
              return self.evaluate(state_prep);
            },
            "Initialize the evaluator");
    qsim.def(
        "getObjEvaluator",
        [](qcor::PauliOperator &obs, const std::string &name = "default",
           py::dict p = {}) { return qcor::qsim::getObjEvaluator(obs, name); },
        py::arg("obs"), py::arg("name") = "default", py::arg("p") = py::dict(),
        py::return_value_policy::reference,
        "Return the CostFunctionEvaluator.");
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434

    // QuantumSimulationWorkflow bindings
    py::class_<qcor::qsim::QuantumSimulationWorkflow,
               std::shared_ptr<qcor::qsim::QuantumSimulationWorkflow>,
               qcor::qsim::PyQuantumSimulationWorkflow>(
        qsim, "QuantumSimulationWorkflow",
        "The QuantumSimulationWorkflow interface provides methods to "
        "execute a quantum simulation workflow.")
        .def(py::init<>())
        .def(
            "execute",
            [](qcor::qsim::QuantumSimulationWorkflow &self,
               const qcor::qsim::QuantumSimulationModel &model)
                -> qcor::qsim::QuantumSimulationResult {
              return self.execute(model);
            },
            "Execute the workflow for the input problem model.");
    qsim.def(
        "getWorkflow",
435
436
437
        [](const std::string &name, PyHeterogeneousMap p = {}) {
          auto nativeHetMap = heterogeneousMapConvert(p);
          return qcor::qsim::getWorkflow(name, nativeHetMap);
438
        },
439
        py::arg("name"), py::arg("p") = PyHeterogeneousMap(),
440
441
        py::return_value_policy::reference,
        "Return the quantum simulation workflow.");
442
  }
443
}