qaoa.cpp 17.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
/*******************************************************************************
 * Copyright (c) 2019 UT-Battelle, LLC.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Eclipse Distribution License v1.0 which accompanies this
 * distribution. The Eclipse Public License is available at
 * http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution
 *License is available at https://eclipse.org/org/documents/edl-v10.php
 *
 * Contributors:
 *   Thien Nguyen - initial API and implementation
 *******************************************************************************/
13

14
#include "qaoa.hpp"
15

Nguyen, Thien's avatar
Nguyen, Thien committed
16
#include "xacc.hpp"
17
#include "Circuit.hpp"
Nguyen, Thien's avatar
Nguyen, Thien committed
18
#include "xacc_service.hpp"
19
#include "PauliOperator.hpp"
20
#include "xacc_observable.hpp"
21
22
#include "CompositeInstruction.hpp"
#include "AlgorithmGradientStrategy.hpp"
Nguyen, Thien's avatar
Nguyen, Thien committed
23
#include "IRTransformation.hpp"
Nguyen, Thien's avatar
Nguyen, Thien committed
24
#include <cassert>
25
#include <iomanip>
26
27
28

namespace xacc {
namespace algorithm {
29

30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
bool QAOA::initialize(const HeterogeneousMap &parameters) {
  bool initializeOk = true;
  // Hyper-parameters for QAOA:
  // (1) Accelerator (QPU)
  if (!parameters.pointerLikeExists<Accelerator>("accelerator")) {
    std::cout << "'accelerator' is required.\n";
    // We check all required params; hence don't early return on failure.
    initializeOk = false;
  }

  // (2) Classical optimizer
  if (!parameters.pointerLikeExists<Optimizer>("optimizer")) {
    std::cout << "'optimizer' is required.\n";
    initializeOk = false;
  }

  // (3) Number of mixing and cost function steps to use (default = 1)
  m_nbSteps = 1;
  if (parameters.keyExists<int>("steps")) {
    m_nbSteps = parameters.get<int>("steps");
  }

52
  // (4) Cost Hamiltonian to construct the max-cut cost Hamiltonian from.
53
  if (!parameters.pointerLikeExists<Observable>("observable")) {
54
        std::cout << "'observable' is required.\n";
55
        initializeOk = false;
56
    }
57

58
  // Default is Extended ParameterizedMode (less steps, more params)
59
60
  m_parameterizedMode = "Extended";
  if (parameters.stringExists("parameter-scheme")) {
61
    m_parameterizedMode = parameters.getString("parameter-scheme");
62
  }
63
64

  if (initializeOk) {
65
    m_costHamObs = parameters.getPointerLike<Observable>("observable");
66
67
68
69
70
71
    m_qpu = parameters.getPointerLike<Accelerator>("accelerator");
    m_optimizer = parameters.getPointerLike<Optimizer>("optimizer");
    // Optional ref-hamiltonian
    m_refHamObs = nullptr;
    if (parameters.pointerLikeExists<Observable>("ref-ham")) {
      m_refHamObs = parameters.getPointerLike<Observable>("ref-ham");
Nguyen, Thien's avatar
Nguyen, Thien committed
72
    }
Nguyen, Thien's avatar
Nguyen, Thien committed
73
74
75
76
77
78
79
80
81
82
83
84
85
    m_irTransformation = nullptr;
    // This QPU has topology-constraint
    if (!m_qpu->getConnectivity().empty()) {
      if (parameters.pointerLikeExists<xacc::IRTransformation>("placement")) {
        m_irTransformation = xacc::as_shared_ptr(
            parameters.getPointerLike<xacc::IRTransformation>("placement"));
        if (m_irTransformation->type() !=
            xacc::IRTransformationType::Placement) {
          xacc::error(m_irTransformation->name() +
                      " is not a placement service.");
        }
      }
    }
86
  }
Nguyen, Thien's avatar
Nguyen, Thien committed
87

88
89
90
  // Check if an initial composite instruction set has been provided
  if (parameters.pointerLikeExists<CompositeInstruction>("initial-state")) {
        m_initial_state = parameters.getPointerLike<CompositeInstruction>("initial-state");
91
92
  }

93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
  // we need this for ADAPT-QAOA (Daniel)
  if (parameters.pointerLikeExists<CompositeInstruction>("ansatz")) {
    externalAnsatz =
        parameters.get<std::shared_ptr<CompositeInstruction>>("ansatz");
  }

  if (parameters.pointerLikeExists<AlgorithmGradientStrategy>(
          "gradient_strategy")) {
    gradientStrategy =
        parameters.get<std::shared_ptr<AlgorithmGradientStrategy>>(
            "gradient_strategy");
  }

  if (parameters.stringExists("gradient_strategy") &&
      !parameters.pointerLikeExists<AlgorithmGradientStrategy>(
          "gradient_strategy") &&
      m_optimizer->isGradientBased()) {
    gradientStrategy = xacc::getService<AlgorithmGradientStrategy>(
        parameters.getString("gradient_strategy"));
112
    gradientStrategy->initialize(parameters);
113
114
115
116
117
118
119
120
121
122
  }

  if ((parameters.stringExists("gradient_strategy") ||
       parameters.pointerLikeExists<AlgorithmGradientStrategy>(
           "gradient_strategy")) &&
      !m_optimizer->isGradientBased()) {
    xacc::warning(
        "Chosen optimizer does not support gradients. Using default.");
  }

123
124
125
  if (parameters.keyExists<bool>("maximize")) {
      m_maximize = parameters.get<bool>("maximize");
  }
126

127
128
129
130
131
  m_shuffleTerms = false;
  if (parameters.keyExists<bool>("shuffle-terms")) {
    m_shuffleTerms = parameters.get<bool>("shuffle-terms");
  }

132
133
  if (m_optimizer && m_optimizer->isGradientBased() &&
      gradientStrategy == nullptr) {
Nguyen, Thien's avatar
Nguyen, Thien committed
134
135
136
137
138
    // No gradient strategy was provided, just use autodiff.
    gradientStrategy = xacc::getService<AlgorithmGradientStrategy>("autodiff");
    gradientStrategy->initialize(
        {{"observable", xacc::as_shared_ptr(m_costHamObs)}});
  }
139
  return initializeOk;
140
141
}

142
143
const std::vector<std::string> QAOA::requiredParameters() const {
  return {"accelerator", "optimizer", "observable"};
Nguyen, Thien's avatar
Nguyen, Thien committed
144
145
}

146
147
148
149
150
151
152
void QAOA::execute(const std::shared_ptr<AcceleratorBuffer> buffer) const {
  const int nbQubits = buffer->size();
  // we need this for ADAPT-QAOA (Daniel)
  std::shared_ptr<CompositeInstruction> kernel;
  if (externalAnsatz) {
    kernel = externalAnsatz;
  } else {
153
154
155
156
157
158
      HeterogeneousMap m;
      kernel = std::dynamic_pointer_cast<CompositeInstruction>(
          xacc::getService<Instruction>("qaoa"));
      m.insert("nbQubits", nbQubits);
      m.insert("nbSteps", m_nbSteps);
      m.insert("ref-ham", m_refHamObs);
159
      m.insert("cost-ham", m_costHamObs);
160
      m.insert("parameter-scheme", m_parameterizedMode);
161
      if (m_initial_state){
162
163
          m.insert("initial-state", m_initial_state);
      }
164
      m.insert("shuffle-terms", m_shuffleTerms);
165
166
      kernel->expand(m);
  } 
167

168
169
170
171
  // Handle Max-cut optimization on shots-based backends (including physical
  // backends). We only want to execute a single circuit for observable with all
  // commuting terms such as the maxcut Hamiltonian.
  // Limitation: this grouping cannot handle gradient strategy at the moment.
172
  // Observe the cost Hamiltonian:
173
174
175
176
177
178
179
  auto kernels = [&] {
    if (dynamic_cast<xacc::quantum::PauliOperator *>(m_costHamObs)) {
      return m_costHamObs->observe(kernel, {{"accelerator", m_qpu}});
    } else {
      return m_costHamObs->observe(kernel);
    }
  }();
180

181
182
  // Grouping is possible (no gradient strategy)
  // TODO: Gradient strategy to handle grouping as well.
183
  int iterCount = 0;
184
185
186
187
188
189
190
  if (m_costHamObs->getNonIdentitySubTerms().size() > 1 &&
      kernels.size() == 1 && !gradientStrategy) {
    OptFunction f(
        [&, this](const std::vector<double> &x, std::vector<double> &dx) {
          auto tmpBuffer = xacc::qalloc(buffer->size());
          std::vector<std::shared_ptr<CompositeInstruction>> fsToExec{
              kernels[0]->operator()(x)};
Nguyen, Thien's avatar
Nguyen, Thien committed
191
192
193
194
195
196
          if (m_irTransformation) {
            for (auto &composite : fsToExec) {
              m_irTransformation->apply(
                  composite, xacc::as_shared_ptr<xacc::Accelerator>(m_qpu));
            }
          }
197
198
199
200
201
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
228
229
230
231
232
233
234
          m_qpu->execute(tmpBuffer, fsToExec);
          double energy = m_costHamObs->postProcess(tmpBuffer);
          // We will only have one child buffer for each parameter set.
          assert(tmpBuffer->getChildren().size() == 1);
          auto result_buf = tmpBuffer->getChildren()[0];
          result_buf->addExtraInfo("parameters", x);
          result_buf->addExtraInfo("energy", energy);
          buffer->appendChild("Iter" + std::to_string(iterCount), result_buf);

          std::stringstream ss;

          ss << "Iter " << iterCount << ": E("
             << (!x.empty() ? std::to_string(x[0]) : "");
          for (int i = 1; i < x.size(); i++) {
            ss << "," << std::setprecision(3) << x[i];
            if (i > 4) {
              // Don't print too many params
              ss << ", ...";
              break;
            }
          }
          ss << ") = " << std::setprecision(12) << energy;
          xacc::info(ss.str());
          iterCount++;
          if (m_maximize)
            energy *= -1.0;
          return energy;
        }, kernel->nVariables());
    auto result = m_optimizer->optimize(f);
    // Reports the final cost:
    double finalCost = result.first;
    if (m_maximize)
      finalCost *= -1.0;
    buffer->addExtraInfo("opt-val", ExtraInfo(finalCost));
    buffer->addExtraInfo("opt-params", ExtraInfo(result.second));
    return;
  }

235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
  // Construct the optimizer/minimizer:
  OptFunction f(
      [&, this](const std::vector<double> &x, std::vector<double> &dx) {
        std::vector<double> coefficients;
        std::vector<std::string> kernelNames;
        std::vector<std::shared_ptr<CompositeInstruction>> fsToExec;

        double identityCoeff = 0.0;
        int nInstructionsEnergy = 0, nInstructionsGradient = 0;
        for (auto &f : kernels) {
          kernelNames.push_back(f->name());
          std::complex<double> coeff = f->getCoefficient();

          int nFunctionInstructions = 0;
          if (f->getInstruction(0)->isComposite()) {
            nFunctionInstructions =
                kernel->nInstructions() + f->nInstructions() - 1;
          } else {
253
            nFunctionInstructions = f->nInstructions();
254
          }
255

256
          if (nFunctionInstructions > kernel->nInstructions()) {
257
258
259
            auto evaled = f->operator()(x);
            fsToExec.push_back(evaled);
            coefficients.push_back(std::real(coeff));
260
          } else {
261
            identityCoeff += std::real(coeff);
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
          }
        }

        // enables gradients (Daniel)
        if (gradientStrategy) {

          auto gradFsToExec =
              gradientStrategy->getGradientExecutions(kernel, x);
          // Add gradient instructions to be sent to the qpu
          nInstructionsEnergy = fsToExec.size();
          nInstructionsGradient = gradFsToExec.size();
          for (auto inst : gradFsToExec) {
            fsToExec.push_back(inst);
          }
          xacc::info("Number of instructions for energy calculation: " +
                     std::to_string(nInstructionsEnergy));
          xacc::info("Number of instructions for gradient calculation: " +
                     std::to_string(nInstructionsGradient));
280
        }
281
282

        auto tmpBuffer = xacc::qalloc(buffer->size());
Nguyen, Thien's avatar
Nguyen, Thien committed
283
284
285
286
287
288
        if (m_irTransformation) {
          for (auto &composite : fsToExec) {
            m_irTransformation->apply(
                composite, xacc::as_shared_ptr<xacc::Accelerator>(m_qpu));
          }
        }
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
        m_qpu->execute(tmpBuffer, fsToExec);
        auto buffers = tmpBuffer->getChildren();

        double energy = identityCoeff;
        auto idBuffer = xacc::qalloc(buffer->size());
        idBuffer->addExtraInfo("coefficient", identityCoeff);
        idBuffer->setName("I");
        idBuffer->addExtraInfo("kernel", "I");
        idBuffer->addExtraInfo("parameters", x);
        idBuffer->addExtraInfo("exp-val-z", 1.0);
        buffer->appendChild("I", idBuffer);

        if (gradientStrategy) { // gradient-based optimization

          for (int i = 0; i < nInstructionsEnergy; i++) { // compute energy
            auto expval = buffers[i]->getExpectationValueZ();
            energy += expval * coefficients[i];
            buffers[i]->addExtraInfo("coefficient", coefficients[i]);
            buffers[i]->addExtraInfo("kernel", fsToExec[i]->name());
            buffers[i]->addExtraInfo("exp-val-z", expval);
            buffers[i]->addExtraInfo("parameters", x);
            buffer->appendChild(fsToExec[i]->name(), buffers[i]);
          }

          std::stringstream ss;
          ss << std::setprecision(12) << "Current Energy: " << energy;
          xacc::info(ss.str());
          ss.str(std::string());

          // If gradientStrategy is numerical, pass the energy
          // We subtract the identityCoeff from the energy
          // instead of passing the energy because the gradients
          // only take the coefficients of parameterized instructions
          if (gradientStrategy->isNumerical()) {
            gradientStrategy->setFunctionValue(energy - identityCoeff);
          }

          // update gradient vector
          gradientStrategy->compute(
              dx, std::vector<std::shared_ptr<AcceleratorBuffer>>(
                      buffers.begin() + nInstructionsEnergy, buffers.end()));

        } else { // normal QAOA run

          for (int i = 0; i < buffers.size(); i++) {
            auto expval = buffers[i]->getExpectationValueZ();
            energy += expval * coefficients[i];
            buffers[i]->addExtraInfo("coefficient", coefficients[i]);
            buffers[i]->addExtraInfo("kernel", fsToExec[i]->name());
            buffers[i]->addExtraInfo("exp-val-z", expval);
            buffers[i]->addExtraInfo("parameters", x);
            buffer->appendChild(fsToExec[i]->name(), buffers[i]);
          }
        }
343
   
344
345
346
347
348
349
350
351
352
353
354
355
356
        std::stringstream ss;
        iterCount++;
        ss << "Iter " << iterCount << ": E("
           << (!x.empty() ? std::to_string(x[0]) : "");
        for (int i = 1; i < x.size(); i++) {
          ss << "," << std::setprecision(3) << x[i];
          if (i > 4) {
            // Don't print too many params
            ss << ", ...";
            break;
          }
        }
        ss << ") = " << std::setprecision(12) << energy;
357
        xacc::info(ss.str());
358
359
        
        if (m_maximize) energy *= -1.0;
360
361
362
363
364
        return energy;
      },
      kernel->nVariables());

  auto result = m_optimizer->optimize(f);
365
  
366
  // Reports the final cost:
367
  double finalCost = result.first;
368
  if (m_maximize) finalCost *= -1.0;
369
  buffer->addExtraInfo("opt-val", ExtraInfo(finalCost));
370
371
372
373
374
375
376
377
378
379
  buffer->addExtraInfo("opt-params", ExtraInfo(result.second));
}

std::vector<double>
QAOA::execute(const std::shared_ptr<AcceleratorBuffer> buffer,
              const std::vector<double> &x) {
  const int nbQubits = buffer->size();
  std::shared_ptr<CompositeInstruction> kernel;
  if (externalAnsatz) {
    kernel = externalAnsatz;
380
381
  } else if (m_single_exec_kernel) {
    kernel = m_single_exec_kernel;
382
  } else {
383
    HeterogeneousMap m;
384
    kernel = std::dynamic_pointer_cast<CompositeInstruction>(
385
386
387
388
          xacc::getService<Instruction>("qaoa"));
    m.insert("nbQubits", nbQubits);
    m.insert("nbSteps", m_nbSteps);
    m.insert("ref-ham", m_refHamObs);
389
    m.insert("cost-ham", m_costHamObs);
390
391
392
393
    m.insert("parameter-scheme", m_parameterizedMode);
    if (m_initial_state){
        m.insert("initial-state", m_initial_state);
    }
394
    m.insert("shuffle-terms", m_shuffleTerms);
395
    kernel->expand(m);
396
397
    // save this kernel for future calls to execute
    m_single_exec_kernel = kernel;
398
399
  }

400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
  // Observe the cost Hamiltonian, with the input Accelerator:
  // i.e. perform grouping (e.g. max-cut QAOA, Pauli) if possible:
  auto kernels = [&] {
    if (dynamic_cast<xacc::quantum::PauliOperator *>(m_costHamObs)) {
      return m_costHamObs->observe(kernel, {{"accelerator", m_qpu}});
    } else {
      return m_costHamObs->observe(kernel);
    }
  }();

  if (m_costHamObs->getNonIdentitySubTerms().size() > 1 &&
      kernels.size() == 1) {
    // Grouping was done:
    // just execute the single observed kernel:
    std::vector<std::shared_ptr<CompositeInstruction>> fsToExec{
        kernels[0]->operator()(x)};
Nguyen, Thien's avatar
Nguyen, Thien committed
416
417
418
419
420
421
    if (m_irTransformation) {
      for (auto &composite : fsToExec) {
        m_irTransformation->apply(
            composite, xacc::as_shared_ptr<xacc::Accelerator>(m_qpu));
      }
    }
422
423
424
425
426
427
    m_qpu->execute(buffer, fsToExec);
    const double finalCost = m_costHamObs->postProcess(buffer);
    // std::cout << "Compute energy from grouping: " << finalCost << "\n";
    return { finalCost };
  }

428
429
430
431
432
433
434
435
436
437
438
439
440
441
  std::vector<double> coefficients;
  std::vector<std::string> kernelNames;
  std::vector<std::shared_ptr<CompositeInstruction>> fsToExec;

  double identityCoeff = 0.0;
  for (auto &f : kernels) {
    kernelNames.push_back(f->name());
    std::complex<double> coeff = f->getCoefficient();

    int nFunctionInstructions = 0;
    if (f->getInstruction(0)->isComposite()) {
      nFunctionInstructions = kernel->nInstructions() + f->nInstructions() - 1;
    } else {
      nFunctionInstructions = f->nInstructions();
442
443
    }

444
445
446
447
448
449
    if (nFunctionInstructions > kernel->nInstructions()) {
      auto evaled = f->operator()(x);
      fsToExec.push_back(evaled);
      coefficients.push_back(std::real(coeff));
    } else {
      identityCoeff += std::real(coeff);
450
    }
451
452
453
  }

  auto tmpBuffer = xacc::qalloc(buffer->size());
Nguyen, Thien's avatar
Nguyen, Thien committed
454
455
456
457
458
459
  if (m_irTransformation) {
    for (auto &composite : fsToExec) {
      m_irTransformation->apply(composite,
                                xacc::as_shared_ptr<xacc::Accelerator>(m_qpu));
    }
  }
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
  m_qpu->execute(tmpBuffer, fsToExec);
  auto buffers = tmpBuffer->getChildren();

  double energy = identityCoeff;
  auto idBuffer = xacc::qalloc(buffer->size());
  idBuffer->addExtraInfo("coefficient", identityCoeff);
  idBuffer->setName("I");
  idBuffer->addExtraInfo("kernel", "I");
  idBuffer->addExtraInfo("parameters", x);
  idBuffer->addExtraInfo("exp-val-z", 1.0);
  buffer->appendChild("I", idBuffer);

  for (int i = 0; i < buffers.size(); i++) {
    auto expval = buffers[i]->getExpectationValueZ();
    energy += expval * coefficients[i];
    buffers[i]->addExtraInfo("coefficient", coefficients[i]);
    buffers[i]->addExtraInfo("kernel", fsToExec[i]->name());
    buffers[i]->addExtraInfo("exp-val-z", expval);
    buffers[i]->addExtraInfo("parameters", x);
    buffer->appendChild(fsToExec[i]->name(), buffers[i]);
  }
481
482
483
484
485
486
487
  
  // WARNING: Removing the parameter shifting here. Remember for later
  // in case of any tests that fail. 
  const double finalCost = energy;
    //   m_maxcutProblem ? (-0.5 * energy +
    //                      0.5 * (m_costHamObs->getNonIdentitySubTerms().size()))
    //                   : energy;
488
  return {finalCost};
489
490
491
492
}

} // namespace algorithm
} // namespace xacc