forked from NVIDIA/cuda-quantum
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTranslateToIQMJson.cpp
More file actions
218 lines (191 loc) · 8.48 KB
/
TranslateToIQMJson.cpp
File metadata and controls
218 lines (191 loc) · 8.48 KB
1
2
3
4
5
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
/*******************************************************************************
* Copyright (c) 2022 - 2025 NVIDIA Corporation & Affiliates. *
* All rights reserved. *
* Copyright 2025 IQM Quantum Computers *
* *
* This source code and the accompanying materials are made available under *
* the terms of the Apache License 2.0 which accompanies this distribution. *
******************************************************************************/
#include "cudaq/Frontend/nvqpp/AttributeNames.h"
#include "cudaq/Optimizer/CodeGen/Emitter.h"
#include "cudaq/Optimizer/CodeGen/IQMJsonEmitter.h"
#include "cudaq/Optimizer/Dialect/Quake/QuakeOps.h"
#include "nlohmann/json.hpp"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/FormatAdapters.h"
#include <algorithm>
#include <cmath>
#include <numeric>
using namespace mlir;
static LogicalResult emitOperation(nlohmann::json &json,
cudaq::Emitter &emitter, Operation &op);
static LogicalResult emitEntryPoint(nlohmann::json &json,
cudaq::Emitter &emitter, func::FuncOp op) {
if (op.getBody().getBlocks().size() != 1)
op.emitError("Cannot translate kernels with more than 1 block to IQM Json. "
"Must be a straight-line representation.");
cudaq::Emitter::Scope scope(emitter, /*isEntryPoint=*/true);
json["name"] = op.getName().str();
std::vector<nlohmann::json> instructions;
for (Operation &op : op.getOps()) {
nlohmann::json instruction = nlohmann::json::object();
if (failed(emitOperation(instruction, emitter, op)))
return failure();
if (!instruction.empty())
instructions.push_back(instruction);
}
json["instructions"] = instructions;
return success();
}
static LogicalResult emitOperation(nlohmann::json &json,
cudaq::Emitter &emitter, ModuleOp moduleOp) {
func::FuncOp entryPoint = nullptr;
for (Operation &op : moduleOp) {
if (op.hasAttr(cudaq::entryPointAttrName)) {
if (entryPoint)
return moduleOp.emitError("has multiple entrypoints");
entryPoint = dyn_cast_or_null<func::FuncOp>(op);
continue;
}
}
if (!entryPoint)
return moduleOp.emitError("does not contain an entrypoint");
return emitEntryPoint(json, emitter, entryPoint);
}
static LogicalResult emitOperation(nlohmann::json &json,
cudaq::Emitter &emitter,
quake::AllocaOp op) {
Value refOrVeq = op.getRefOrVec();
auto name = emitter.createName("QB", 1);
emitter.getOrAssignName(refOrVeq, name);
return success();
}
static LogicalResult emitOperation(nlohmann::json &json,
cudaq::Emitter &emitter,
quake::BorrowWireOp op) {
auto name = std::string("QB") + std::to_string(op.getIdentity() + 1);
emitter.getOrAssignName(op.getResult(), name);
return success();
}
static LogicalResult emitOperation(nlohmann::json &json,
cudaq::Emitter &emitter,
quake::ExtractRefOp op) {
std::optional<int64_t> index = std::nullopt;
if (op.hasConstantIndex())
index = op.getConstantIndex();
else
index = cudaq::getIndexValueAsInt(op.getIndex());
if (!index.has_value())
return op.emitError("cannot translate runtime index to IQM Json");
auto qrefName = llvm::formatv("{0}{1}", "QB", *index + 1);
emitter.getOrAssignName(op.getRef(), qrefName);
return success();
}
static LogicalResult emitOperation(nlohmann::json &json,
cudaq::Emitter &emitter,
quake::OperatorInterface optor) {
auto name = optor->getName().stripDialect();
std::vector<std::string> validInstructions{"z", "phased_rx"};
if (std::find(validInstructions.begin(), validInstructions.end(),
name.str()) == validInstructions.end())
optor.emitError(
"Invalid operation, code not lowered to IQM native gate set (" + name +
").");
std::vector<std::string> qubits;
if (name == "z") {
if (optor.getControls().size() != 1)
optor.emitError(
"IQM gate set only supports Z gates with exactly one control.");
json["name"] = "cz";
json["args"] = nlohmann::json::object();
for (auto control : optor.getControls())
qubits.push_back(emitter.getOrAssignName(control).str());
// Propagate the name of this qubit into the operation output values.
emitter.getOrAssignName(
optor->getResult(0),
emitter.getOrAssignName(optor.getControls()[0]).str());
emitter.getOrAssignName(optor->getResult(1),
emitter.getOrAssignName(optor.getTarget(0)).str());
} else {
json["name"] = "prx";
if (optor.getParameters().size() != 2)
optor.emitError("IQM prx gate expects exactly two parameters.");
auto parameter0 =
cudaq::getParameterValueAsDouble(optor.getParameters()[0]);
auto parameter1 =
cudaq::getParameterValueAsDouble(optor.getParameters()[1]);
auto convertToFullTurns = [](double &angleInRadians) {
return angleInRadians / (2 * M_PI);
};
json["args"]["angle_t"] = convertToFullTurns(*parameter0);
json["args"]["phase_t"] = convertToFullTurns(*parameter1);
// Propagate the name of this qubit into the operation output values.
emitter.getOrAssignName(optor->getResult(0),
emitter.getOrAssignName(optor.getTarget(0)).str());
}
if (optor.getTargets().size() != 1)
optor.emitError("IQM operation " + name + " supports exactly one target.");
qubits.push_back(emitter.getOrAssignName(optor.getTargets().front()).str());
json["qubits"] = qubits;
return success();
}
static LogicalResult emitOperation(nlohmann::json &json,
cudaq::Emitter &emitter, quake::MzOp op) {
json["name"] = "measure";
std::vector<std::string> qubits;
for (auto target : op.getTargets())
qubits.push_back(emitter.getOrAssignName(target).str());
json["qubits"] = qubits;
json["args"] = nlohmann::json::object();
auto join_lambda = [](std::string a, std::string b) {
return a + std::string("_") + b;
};
auto regName = op.getRegisterName();
if (regName)
json["args"]["key"] = *regName;
else
json["args"]["key"] =
"m_" + (qubits.empty() ? ""
: std::accumulate(++qubits.begin(), qubits.end(),
*qubits.begin(), join_lambda));
return success();
}
static LogicalResult emitOperation(nlohmann::json &json,
cudaq::Emitter &emitter, Operation &op) {
return llvm::TypeSwitch<Operation *, LogicalResult>(&op)
.Case<ModuleOp>([&](auto op) { return emitOperation(json, emitter, op); })
// Quake
.Case<quake::AllocaOp>(
[&](auto op) { return emitOperation(json, emitter, op); })
.Case<quake::BorrowWireOp>(
[&](auto op) { return emitOperation(json, emitter, op); })
.Case<quake::ExtractRefOp>(
[&](auto op) { return emitOperation(json, emitter, op); })
.Case<quake::OperatorInterface>(
[&](auto op) { return emitOperation(json, emitter, op); })
.Case<quake::MzOp>(
[&](auto op) { return emitOperation(json, emitter, op); })
// Ignore
.Case<quake::DiscriminateOp>([](auto) { return success(); })
.Case<quake::DeallocOp>([](auto) { return success(); })
.Case<quake::ReturnWireOp>([](auto) { return success(); })
.Case<func::ReturnOp>([](auto) { return success(); })
.Case<arith::ConstantOp>([](auto) { return success(); })
.Default([&](Operation *) -> LogicalResult {
// Allow LLVM and cc dialect ops (for storing measure results).
if (op.getName().getDialectNamespace().equals("llvm") ||
op.getName().getDialectNamespace().equals("cc") ||
op.getName().getDialectNamespace().equals("arith"))
return success();
return op.emitOpError() << "unable to translate op to IQM Json "
<< op.getName().getIdentifier().str();
});
}
LogicalResult cudaq::translateToIQMJson(Operation *op, llvm::raw_ostream &os) {
nlohmann::json j;
Emitter emitter(os);
auto ret = emitOperation(j, emitter, *op);
os << j.dump(4);
return ret;
}