GateMergeOptimizer.cpp 17.4 KB
Newer Older
1
#include <cassert>
2
3
4
#include "GateMergeOptimizer.hpp"
#include "GateFusion.hpp"
#include "xacc_service.hpp"
5
#include <optional>
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
namespace {
bool compareMatIgnoreGlobalPhase(const Eigen::Matrix4cd& in_a, const Eigen::Matrix4cd& in_b)
{
    const auto flipKronOrder = [](const Eigen::Matrix4cd& in_mat){
        Eigen::Matrix4cd result = Eigen::Matrix4cd::Zero();
        const std::vector<size_t> order { 0, 2, 1, 3 };
        for (size_t i = 0; i < in_mat.rows(); ++i)
        {
            for (size_t j = 0; j < in_mat.cols(); ++j)
            {
                result(order[i], order[j]) = in_mat(i, j);
            }
        }
        return result;
    };
    
    const auto bFixed = flipKronOrder(in_b);

    // Find index of the largest element to normalize global phase.
    size_t colIdx = 0;
    size_t rowIdx = 0;
    double maxVal = std::abs(in_a(0,0));
    for (size_t i = 0; i < in_a.rows(); ++i)
    {
        for (size_t j = 0; j < in_a.cols(); ++j)
        {
            if (std::abs(in_a(i,j)) > maxVal)
            {
                maxVal = std::abs(in_a(i,j));
                colIdx = j;
                rowIdx = i;
            }
        }
    }

    const double TOL = 1e-6;
    if (std::abs(std::abs(in_a(rowIdx, colIdx)) - std::abs(bFixed(rowIdx, colIdx))) > TOL)
    {
        return false;
    }

    const std::complex<double> globalFactor = in_a(rowIdx, colIdx) / bFixed(rowIdx, colIdx);
    auto bFixedPhase = globalFactor * bFixed;
    const auto diff = (bFixedPhase - in_a).norm();
    return std::abs(diff) < TOL;
}
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
void flattenComposite(std::shared_ptr<CompositeInstruction> io_composite) 
{
  std::vector<xacc::InstPtr> flatten;
  InstructionIterator iter(io_composite);
  while (iter.hasNext()) 
  {
    auto inst = iter.next();
    if (!inst->isComposite()) 
    {
      flatten.emplace_back(inst->clone());
    }
  }
  io_composite->clear();
  io_composite->addInstructions(flatten);
}
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Check if the composite uses a single qubit register,
// the qubit line is determined by the qubit idx, 
// hence we don't want to accidentally merge wrong gates.
std::vector<std::string>
getBufferList(const std::shared_ptr<CompositeInstruction> &program) {
  std::set<std::string> allBuffers;
  InstructionIterator it(program);
  while (it.hasNext()) {
    auto nextInst = it.next();
    for (const auto &bufferName : nextInst->getBufferNames()) {
      allBuffers.emplace(bufferName);
    }
  }

  std::vector<std::string> result(allBuffers.begin(), allBuffers.end());
  return result;
83
}
84
} // namespace
85
86
87
88
namespace xacc {
namespace quantum {
void MergeSingleQubitGatesOptimizer::apply(std::shared_ptr<CompositeInstruction> program, const std::shared_ptr<Accelerator> accelerator, const HeterogeneousMap &options)
{
89
90
91
92
93
94
95
96
    const auto buffer_names = getBufferList(program);
    if (buffer_names.size() > 1) 
    {
        // If there are multiple buffers, we cannot apply gate merging
        // due to qubit Id ambiguity.
        return;
    }

97
    auto gateRegistry = xacc::getService<xacc::IRProvider>("quantum");
98
    flattenComposite(program);
99
100
    for (size_t instIdx = 0; instIdx < program->nInstructions(); ++instIdx)
    {
101
        const auto sequence = findSingleQubitGateSequence(program, instIdx, 2);
102
103
        if (!sequence.empty()) 
        {
104
105
106
107
108
109
110
111
112
113
114
115
            auto tmpKernel = gateRegistry->createComposite("__TMP__");
            for (const auto& instIdx: sequence)
            {
                auto instrPtr = program->getInstruction(instIdx)->clone();
                assert(instrPtr->bits().size() == 1);
                // Remap to bit 0 for fusing
                instrPtr->setBits({ 0 });
                tmpKernel->addInstruction(instrPtr);
            }

            auto fuser = xacc::getService<xacc::quantum::GateFuser>("default");
            fuser->initialize(tmpKernel);
116
117
118
119
120
121
122
            Eigen::Matrix2cd uMat = fuser->calcFusedGate(1);
            uMat.transposeInPlace();
            Eigen::Vector4cd matAsVec(Eigen::Map<Eigen::Vector4cd>(uMat.data(), uMat.cols()*uMat.rows()));
            std::vector<std::complex<double>> flattenedUnitary;
            flattenedUnitary.resize(matAsVec.size());
            Eigen::Vector4cd::Map(&flattenedUnitary[0], flattenedUnitary.size()) = matAsVec;

123
124
            auto zyz = std::dynamic_pointer_cast<quantum::Circuit>(xacc::getService<Instruction>("z-y-z"));
            const bool expandOk = zyz->expand({ 
125
                std::make_pair("unitary", flattenedUnitary)
126
            });
127
            assert(expandOk);
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
            // Optimized decomposed sequence:
            const auto nbInstructionsAfter = zyz->nInstructions();
            // A simplified sequence was found.
            if (nbInstructionsAfter < sequence.size())
            {
                // Rewrite:
                const size_t bitIdx = program->getInstruction(sequence[0])->bits()[0];
                // Disable to remove:
                const auto programLengthBefore = program->nInstructions();
                for (const auto& instIdx: sequence)
                {
                    auto instrPtr = program->getInstruction(instIdx);
                    instrPtr->disable();
                }
                program->removeDisabled();
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
143
                if (program->nInstructions() == sequence[0])
144
                {
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
145
146
147
                    for (auto& newInst: zyz->getInstructions())
                    {
                        newInst->setBits({bitIdx});
148
                        newInst->setBufferNames({ buffer_names[0] });
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
149
150
                        program->addInstruction(newInst->clone());
                    }
151
                }
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
152
153
                else
                {
154
                    auto locationToInsert = sequence[0];
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
155
156
157
                    for (auto& newInst: zyz->getInstructions())
                    {
                        newInst->setBits({bitIdx});
158
                        newInst->setBufferNames({ buffer_names[0] });
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
159
                        program->insertInstruction(locationToInsert, newInst->clone());
160
                        locationToInsert++;
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
161
162
163
                    }
                }
                
164
165
166
                const auto programLengthAfter = program->nInstructions();
                assert(programLengthAfter < programLengthBefore);
            }
167
168
169
170
        }
    }
}

171
std::vector<size_t> MergeSingleQubitGatesOptimizer::findSingleQubitGateSequence(const std::shared_ptr<CompositeInstruction> in_program, size_t in_startIdx, size_t in_lengthLimit) const
172
173
{
    const auto nbInstructions = in_program->nInstructions();
174
175
176
177
    assert(in_startIdx < nbInstructions);
    auto firstInst = in_program->getInstruction(in_startIdx);
    // Not a single-qubit gate.
    if (firstInst->bits().size() > 1 || firstInst->name() == "Measure")
178
    {
179
180
        return {};
    }
181

182
183
184
185
186
187
188
189
190
191
192
193
194
    const size_t bitIdx = firstInst->bits()[0];
    std::vector<size_t> gateSequence;
    gateSequence.emplace_back(in_startIdx);

    const auto returnSeq = [&](const std::vector<size_t>& in_seq) -> std::vector<size_t> {
        return (in_seq.size() >= in_lengthLimit) ? in_seq : std::vector<size_t>{};
    };

    for (size_t instIdx = in_startIdx + 1; instIdx < nbInstructions; ++instIdx)
    {
        auto instPtr = in_program->getInstruction(instIdx);
        // Matching bitIdx
        if (instPtr->bits().size() == 1 && instPtr->bits()[0] == bitIdx)
195
        {
196
            if (instPtr->name() != "Measure")
197
            {
198
                gateSequence.emplace_back(instIdx);
199
            }
200
            else 
201
            {
202
                return returnSeq(gateSequence);
203
204
            }
        }
205
206
207
        // If this is a two-qubit gate that involves this qubit wire,
        // terminate the scan and return.
        else if (instPtr->bits().size() == 2 && xacc::container::contains(instPtr->bits(), bitIdx))
208
        {
209
            return returnSeq(gateSequence);
210
        }
211
212
213
    }  
    // Reach the end of the circuit:  
    return returnSeq(gateSequence);    
214
}
215
216
217

void MergeTwoQubitBlockOptimizer::apply(std::shared_ptr<CompositeInstruction> program, const std::shared_ptr<Accelerator> accelerator, const HeterogeneousMap& options)
{
218
219
220
221
222
223
224
    const auto buffer_names = getBufferList(program);
    if (buffer_names.size() > 1) 
    {
        // If there are multiple buffers, we cannot apply gate merging
        // due to qubit Id ambiguity.
        return;
    }
225
    auto gateRegistry = xacc::getService<xacc::IRProvider>("quantum");
226
    flattenComposite(program);
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
    // No need to optimize block with less than 6 gates
    // since the KAK decomposition will result in at least 5 gate.
    const size_t MIN_SIZE = 6;
    if (program->nInstructions() < MIN_SIZE)
    {
        return;
    }
    for (size_t instIdx = 0; instIdx < program->nInstructions(); ++instIdx)
    {
        std::pair<size_t, size_t> qubitPair = std::make_pair(0, 0);
        const auto sequence = findGateSequence(program, instIdx, MIN_SIZE, qubitPair);
        if (!sequence.empty()) 
        {
            auto tmpKernel = gateRegistry->createComposite("__TMP__");
            
            const auto mapBits = [&qubitPair](const std::vector<size_t>& in_bits){
                const auto translate = [&qubitPair](size_t bit) {
                    assert(bit == qubitPair.first || bit == qubitPair.second);
                    assert(qubitPair.first  != qubitPair.second);
                    if (qubitPair.first < qubitPair.second)
                    {
248
                        return (bit == qubitPair.first) ? 1 : 0;
249
250
251
                    }
                    else
                    {
252
                        return (bit == qubitPair.first) ? 0 : 1;
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
                    }
                }; 

                std::vector<size_t> newBits;
                for (const auto& bit: in_bits)         
                {
                    newBits.emplace_back(translate(bit));
                }   
                return newBits;
            };

            // Map { 0, 1 } bits back to original bits
            const auto remapBits = [&qubitPair](const std::vector<size_t>& in_bits){
                const auto translate = [&qubitPair](size_t bit) {
                    assert(bit == 0 || bit == 1);
                    assert(qubitPair.first  != qubitPair.second);
                    if (qubitPair.first < qubitPair.second)
                    {
                        return (bit == 0) ? qubitPair.first : qubitPair.second;
                    }
                    else
                    {
                        return (bit == 0) ? qubitPair.second : qubitPair.first;
                    }
                }; 

                std::vector<size_t> newBits;
                for (const auto& bit: in_bits)         
                {
                    newBits.emplace_back(translate(bit));
                }   
                return newBits;
            };

            for (const auto& instIdx: sequence)
            {
                auto instrPtr = program->getInstruction(instIdx)->clone();
                instrPtr->setBits(mapBits(instrPtr->bits()));
                tmpKernel->addInstruction(instrPtr);
            }
            auto fuser = xacc::getService<xacc::quantum::GateFuser>("default");
            fuser->initialize(tmpKernel);
295
296
297
298
299
300
            Eigen::Matrix4cd uMat = fuser->calcFusedGate(2);
            uMat.transposeInPlace();
            Eigen::VectorXcd matAsVec(Eigen::Map<Eigen::VectorXcd>(uMat.data(), uMat.cols()*uMat.rows()));
            std::vector<std::complex<double>> flattenedUnitary;
            flattenedUnitary.resize(matAsVec.size());
            Eigen::VectorXcd::Map(&flattenedUnitary[0], flattenedUnitary.size()) = matAsVec;
301
302
            auto kak = std::dynamic_pointer_cast<quantum::Circuit>(xacc::getService<Instruction>("kak"));
            const bool expandOk = kak->expand({ 
303
                std::make_pair("unitary", flattenedUnitary)
304
305
            });
            assert(expandOk);
306
307
308
309
310
311
312
            
            const auto calcUopt = [](const std::shared_ptr<CompositeInstruction> composite) {
                auto fuser = xacc::getService<xacc::quantum::GateFuser>("default");
                fuser->initialize(composite);
                return fuser->calcFusedGate(2);
            };
            
313
314
            // Optimized decomposed sequence:
            const auto nbInstructionsAfter = kak->nInstructions();
315
            uMat.transposeInPlace();
316
            // A simplified sequence was found.
317
            if (nbInstructionsAfter < sequence.size() && compareMatIgnoreGlobalPhase(uMat, calcUopt(kak)))
318
319
320
321
322
323
324
325
326
            {
                // Disable to remove:
                const auto programLengthBefore = program->nInstructions();
                for (const auto& instIdx: sequence)
                {
                    auto instrPtr = program->getInstruction(instIdx);
                    instrPtr->disable();
                }
                program->removeDisabled();
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
327
                if (program->nInstructions() == sequence[0])
328
                {
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
329
330
331
                    for (auto& newInst: kak->getInstructions())
                    {
                        newInst->setBits(remapBits(newInst->bits()));
332
                        newInst->setBufferNames(std::vector<std::string>(newInst->bits().size(), buffer_names[0]));
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
333
334
335
336
337
                        program->addInstruction(newInst->clone());
                    }
                }
                else
                {
338
                    auto locationToInsert = sequence[0];
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
339
340
341
                    for (auto& newInst: kak->getInstructions())
                    {
                        newInst->setBits(remapBits(newInst->bits()));
342
                        newInst->setBufferNames(std::vector<std::string>(newInst->bits().size(), buffer_names[0]));
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
343
                        program->insertInstruction(locationToInsert, newInst->clone());
344
                        locationToInsert++;
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
345
                    }
346
                }
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
347
348
                // Jump forward since we don't want to re-analyze this block.
                instIdx += nbInstructionsAfter;
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
                const auto programLengthAfter = program->nInstructions();
                assert(programLengthAfter < programLengthBefore);
            }
        }
    }
}

std::vector<size_t> MergeTwoQubitBlockOptimizer::findGateSequence(const std::shared_ptr<CompositeInstruction> in_program, size_t in_startIdx, size_t in_lengthLimit, std::pair<size_t, size_t>& out_qubitPair) const
{
    const auto nbInstructions = in_program->nInstructions();
    assert(in_startIdx < nbInstructions);
    auto firstInst = in_program->getInstruction(in_startIdx);
    if (firstInst->name() == "Measure")
    {
        return {};
    }

    const auto qubitPairIfAny = [&]() -> std::optional<std::pair<size_t, size_t>> {
        if (firstInst->bits().size() == 2)
        {
            return std::make_pair(firstInst->bits()[0], firstInst->bits()[1]);
        }

        // Single qubit gate:
        // Scan forward to find the *first* two-qubit gate which involves this qubit.
        assert(firstInst->bits().size() == 1);
        const auto firstBitIdx =  firstInst->bits()[0];
        for (size_t instIdx = in_startIdx + 1; instIdx < nbInstructions; ++instIdx)
        {
            auto instPtr = in_program->getInstruction(instIdx);
            if (instPtr->bits().size() == 2 && xacc::container::contains(instPtr->bits(), firstBitIdx))
            {
                return std::make_pair(instPtr->bits()[0], instPtr->bits()[1]);
            }
        }
        // Cannot find the boundary: i.e. no two-qubit gates
        return std::optional<std::pair<size_t, size_t>>();
    }();

    if (!qubitPairIfAny.has_value())
    {
        return {};
    }
    const auto qubitPair = qubitPairIfAny.value();
    std::vector<size_t> gateSequence;
    gateSequence.emplace_back(in_startIdx);
    out_qubitPair = qubitPair;
    const auto returnSeq = [&](const std::vector<size_t>& in_seq) -> std::vector<size_t> {
        return (in_seq.size() >= in_lengthLimit) ? in_seq : std::vector<size_t>{};
    };

    for (size_t instIdx = in_startIdx + 1; instIdx < nbInstructions; ++instIdx)
    {
        auto instPtr = in_program->getInstruction(instIdx);
        if (instPtr->bits().size() == 1)
        {
            if (instPtr->bits()[0] == qubitPair.first || instPtr->bits()[0] == qubitPair.second)
            {
                if (instPtr->name() == "Measure")
                {
                    return returnSeq(gateSequence);
                }
                else
                {
                    gateSequence.emplace_back(instIdx);
                }
            }
        }
        else if (instPtr->bits().size() == 2)
        {
            const auto areQubitOperandsMatched = [&qubitPair](const std::vector<size_t>& in_bits) {
                const bool match1 =  (in_bits[0] == qubitPair.first) && (in_bits[1] == qubitPair.second); 
                const bool match2 =  (in_bits[1] == qubitPair.first) && (in_bits[0] == qubitPair.second); 
                return match1 || match2;
            };

            const auto hasOnlyOneBitMatched = [&qubitPair](const std::vector<size_t>& in_bits) {
                const bool oneMatched = xacc::container::contains(in_bits, qubitPair.first) || xacc::container::contains(in_bits, qubitPair.second);
                const bool oneNotMatched = !xacc::container::contains(in_bits, qubitPair.first) || !xacc::container::contains(in_bits, qubitPair.second);
                return oneMatched && oneNotMatched;
            };

            if (areQubitOperandsMatched(instPtr->bits()))
            {
                gateSequence.emplace_back(instIdx);
            }
            else if (hasOnlyOneBitMatched(instPtr->bits()))
            {
                return returnSeq(gateSequence);
            }
        }
    }
    // End of circuit:
    return returnSeq(gateSequence);
}
444
445
}
}