-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathConversionPatterns.cpp
More file actions
378 lines (315 loc) · 17.7 KB
/
ConversionPatterns.cpp
File metadata and controls
378 lines (315 loc) · 17.7 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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
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
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
343
344
345
346
347
348
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
// Copyright 2025 Xanadu Quantum Technologies Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <nlohmann/json.hpp>
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "mlir/IR/IRMapping.h"
#include "Catalyst/Utils/EnsureFunctionDeclaration.h"
#include "Ion/IR/IonOps.h"
#include "Ion/Transforms/Patterns.h"
#include "Quantum/IR/QuantumOps.h"
using namespace mlir;
using namespace catalyst::ion;
using namespace catalyst::quantum;
using json = nlohmann::json;
namespace {
LLVM::LLVMStructType createBeamStructType(MLIRContext *ctx, OpBuilder &rewriter, BeamAttr &beamAttr)
{
return LLVM::LLVMStructType::getLiteral(
ctx, {
IntegerType::get(ctx, 64), // transition index
Float64Type::get(ctx), // rabi
Float64Type::get(ctx), // detuning
LLVM::LLVMArrayType::get( // polarization
rewriter.getIntegerType(64), beamAttr.getPolarization().size()),
LLVM::LLVMArrayType::get( // wavevector
rewriter.getIntegerType(64), beamAttr.getWavevector().size()),
});
}
Value createBeamStruct(Location loc, OpBuilder &rewriter, MLIRContext *ctx, BeamAttr &beamAttr)
{
Type beamStructType = createBeamStructType(ctx, rewriter, beamAttr);
auto transitionIndex = beamAttr.getTransitionIndex();
auto rabi = beamAttr.getRabi();
auto detuning = beamAttr.getDetuning();
auto polarization = beamAttr.getPolarization().asArrayRef();
auto wavevector = beamAttr.getWavevector().asArrayRef();
Value beamStruct = LLVM::UndefOp::create(rewriter, loc, beamStructType);
beamStruct = LLVM::InsertValueOp::create(
rewriter, loc, beamStruct, LLVM::ConstantOp::create(rewriter, loc, transitionIndex),
SmallVector<int64_t>{0});
beamStruct = LLVM::InsertValueOp::create(rewriter, loc, beamStruct,
LLVM::ConstantOp::create(rewriter, loc, rabi),
SmallVector<int64_t>{1});
beamStruct = LLVM::InsertValueOp::create(rewriter, loc, beamStruct,
LLVM::ConstantOp::create(rewriter, loc, detuning),
SmallVector<int64_t>{2});
for (size_t i = 0; i < polarization.size(); i++) {
Value polarizaitonConst = LLVM::ConstantOp::create(
rewriter, loc, rewriter.getI64Type(),
rewriter.getIntegerAttr(rewriter.getI64Type(), polarization[i]));
beamStruct = LLVM::InsertValueOp::create(rewriter, loc, beamStruct, polarizaitonConst,
ArrayRef<int64_t>({3, static_cast<int64_t>(i)}));
}
for (size_t i = 0; i < wavevector.size(); i++) {
Value waveConst =
LLVM::ConstantOp::create(rewriter, loc, rewriter.getI64Type(),
rewriter.getIntegerAttr(rewriter.getI64Type(), wavevector[i]));
beamStruct = LLVM::InsertValueOp::create(rewriter, loc, beamStruct, waveConst,
ArrayRef<int64_t>({4, static_cast<int64_t>(i)}));
}
Type ptrType = LLVM::LLVMPointerType::get(rewriter.getContext());
Value c1 = LLVM::ConstantOp::create(rewriter, loc, rewriter.getI64IntegerAttr(1));
Value beamStructPtr = LLVM::AllocaOp::create(rewriter, loc, /*resultType=*/ptrType,
/*elementType=*/beamStructType, c1);
LLVM::StoreOp::create(rewriter, loc, beamStruct, beamStructPtr);
return beamStructPtr;
}
struct IonOpPattern : public OpConversionPattern<catalyst::ion::IonOp> {
using OpConversionPattern<catalyst::ion::IonOp>::OpConversionPattern;
// Create the ion JSON and pass it into the device kwargs as a JSON string
LogicalResult matchAndRewrite(catalyst::ion::IonOp op, catalyst::ion::IonOpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override
{
func::FuncOp funcOp = op->getParentOfType<func::FuncOp>();
DeviceInitOp deviceInitOp = *funcOp.getOps<DeviceInitOp>().begin();
StringRef deviceKwargs = deviceInitOp.getKwargs();
auto positionAttr = op.getPosition();
auto levelsAttr = op.getLevels();
auto transitionsAttr = op.getTransitions();
json ion_json = R"({
"class_": "Ion",
"levels": [],
"transitions" : []
})"_json;
ion_json["mass"] = op.getMass().getValue().convertToDouble();
ion_json["charge"] = op.getCharge().getValueAsDouble();
assert(positionAttr.size() == 3 && "Position must have 3 coordinates!");
std::array<double, 3> position = {positionAttr[0], positionAttr[1], positionAttr[2]};
ion_json["position"] = position;
std::map<std::string, size_t> LevelLabel2Index;
for (size_t i = 0; i < levelsAttr.size(); i++) {
auto levelAttr = cast<LevelAttr>(levelsAttr[i]);
json this_level =
json{{"class_", "Level"},
{"principal", levelAttr.getPrincipal().getInt()},
{"spin", levelAttr.getSpin().getValue().convertToDouble()},
{"orbital", levelAttr.getOrbital().getValue().convertToDouble()},
{"nuclear", levelAttr.getNuclear().getValue().convertToDouble()},
{"spin_orbital", levelAttr.getSpinOrbital().getValue().convertToDouble()},
{"spin_orbital_nuclear",
levelAttr.getSpinOrbitalNuclear().getValue().convertToDouble()},
{"spin_orbital_nuclear_magnetization",
levelAttr.getSpinOrbitalNuclearMagnetization().getValue().convertToDouble()},
{"energy", levelAttr.getEnergy().getValue().convertToDouble()},
{"label", levelAttr.getLabel().getValue().str()}};
ion_json["levels"].push_back(this_level);
LevelLabel2Index[levelAttr.getLabel().getValue().str()] = i;
}
for (size_t i = 0; i < transitionsAttr.size(); i++) {
auto transitionAttr = cast<TransitionAttr>(transitionsAttr[i]);
std::string multipole = transitionAttr.getMultipole().getValue().str();
std::string level0_label = transitionAttr.getLevel_0().getValue().str();
std::string level1_label = transitionAttr.getLevel_1().getValue().str();
assert(LevelLabel2Index.count(level0_label) == 1 &&
LevelLabel2Index.count(level1_label) == 1 &&
"A transition level's label must refer to an existing level in the ion!");
const json &level1 = ion_json["levels"][LevelLabel2Index[level0_label]];
const json &level2 = ion_json["levels"][LevelLabel2Index[level1_label]];
json this_transition =
json{{"class_", "Transition"},
{"einsteinA", transitionAttr.getEinsteinA().getValue().convertToDouble()},
{"level1", level1},
{"level2", level2},
{"label", level0_label + "->" + level1_label},
{"multipole", multipole}};
ion_json["transitions"].push_back(this_transition);
}
deviceInitOp.setKwargs(deviceKwargs.str() + "ION:" + std::string(ion_json.dump()));
deviceInitOp.setLib("oqd.qubit");
rewriter.eraseOp(op);
return success();
}
};
struct ModesOpPattern : public OpConversionPattern<catalyst::ion::ModesOp> {
using OpConversionPattern<catalyst::ion::ModesOp>::OpConversionPattern;
// Create the modes JSON and pass it into the device kwargs as a JSON string
LogicalResult matchAndRewrite(catalyst::ion::ModesOp op, catalyst::ion::ModesOpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override
{
func::FuncOp funcOp = op->getParentOfType<func::FuncOp>();
DeviceInitOp deviceInitOp = *funcOp.getOps<DeviceInitOp>().begin();
auto modesAttr = op.getModes();
for (size_t i = 0; i < modesAttr.size(); i++) {
StringRef deviceKwargs = deviceInitOp.getKwargs();
auto phononAttr = cast<PhononAttr>(modesAttr[i]);
json phonon_json = R"({
"class_": "Phonon",
"eigenvector" : []
})"_json;
phonon_json["energy"] = phononAttr.getEnergy().getValue().convertToDouble();
auto eigenvector = phononAttr.getEigenvector();
for (int j = 0; j < eigenvector.size(); j++) {
phonon_json["eigenvector"].push_back(eigenvector[j]);
}
deviceInitOp.setKwargs(deviceKwargs.str() +
"PHONON:" + std::string(phonon_json.dump()));
}
rewriter.eraseOp(op);
return success();
}
};
struct ParallelProtocolOpPattern : public OpConversionPattern<catalyst::ion::ParallelProtocolOp> {
using OpConversionPattern<catalyst::ion::ParallelProtocolOp>::OpConversionPattern;
LogicalResult matchAndRewrite(catalyst::ion::ParallelProtocolOp op,
catalyst::ion::ParallelProtocolOpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override
{
Location loc = op.getLoc();
MLIRContext *ctx = this->getContext();
const TypeConverter *conv = getTypeConverter();
// replace region args with parallelProtocolOp args
Block *regionBlock = &op.getBodyRegion().front();
assert((regionBlock->getNumArguments() == op.getNumOperands()) &&
"ParallelProtocolOp should have the same number of arguments as its region");
for (const auto &[regionArg, opArg] :
llvm::zip(regionBlock->getArguments(), op.getOperands())) {
regionArg.replaceAllUsesWith(opArg);
}
// Clone the region operations outside ParallelProtocolOp.
SmallVector<Value> parallelPulses;
rewriter.setInsertionPoint(op);
IRMapping irMapping;
for (auto ®ionOp : regionBlock->getOperations()) {
if (auto pulseOp = dyn_cast<catalyst::ion::PulseOp>(®ionOp)) {
auto *clonedPulseOp = rewriter.clone(regionOp, irMapping);
irMapping.map(regionOp.getResults(), clonedPulseOp->getResults());
// keep track of parallel Pulses for the runtime call
parallelPulses.push_back(clonedPulseOp->getResult(0));
}
else if (auto measurePulseOp = dyn_cast<catalyst::ion::MeasurePulseOp>(®ionOp)) {
auto *clonedMeasurePulseOp = rewriter.clone(regionOp, irMapping);
irMapping.map(regionOp.getResults(), clonedMeasurePulseOp->getResults());
parallelPulses.push_back(clonedMeasurePulseOp->getResult(0));
}
else if (!isa<catalyst::ion::YieldOp>(®ionOp)) {
// Clone other operations (e.g., llvm.fdiv) that aren't YieldOp
auto *clonedRegionOp = rewriter.clone(regionOp, irMapping);
irMapping.map(regionOp.getResults(), clonedRegionOp->getResults());
}
}
// Create an array of pulses
Type pulseArrayType =
LLVM::LLVMArrayType::get(conv->convertType(PulseType::get(ctx)), parallelPulses.size());
Value pulseArray = LLVM::UndefOp::create(rewriter, loc, pulseArrayType);
for (size_t i = 0; i < parallelPulses.size(); i++) {
auto convertedPulse =
UnrealizedConversionCastOp::create(rewriter, loc, LLVM::LLVMPointerType::get(ctx),
parallelPulses[i])
.getResult(0);
pulseArray = LLVM::InsertValueOp::create(rewriter, loc, pulseArray, convertedPulse, i);
}
Type ptrType = LLVM::LLVMPointerType::get(rewriter.getContext());
Value c1 = LLVM::ConstantOp::create(rewriter, loc, rewriter.getI64IntegerAttr(1));
Value pulseArrayPtr = LLVM::AllocaOp::create(rewriter, loc, /*resultType=*/ptrType,
/*elementType=*/pulseArrayType, c1);
LLVM::StoreOp::create(rewriter, loc, pulseArray, pulseArrayPtr);
Value pulseArraySize = LLVM::ConstantOp::create(
rewriter, loc, rewriter.getI64IntegerAttr(parallelPulses.size()));
SmallVector<Value> operands;
operands.push_back(pulseArrayPtr);
operands.push_back(pulseArraySize);
// Create the parallel protocol stub function
Type protocolFuncType = LLVM::LLVMFunctionType::get(LLVM::LLVMVoidType::get(ctx),
{ptrType, pulseArraySize.getType()});
std::string protocolFuncName = "__catalyst__oqd__ParallelProtocol";
LLVM::LLVMFuncOp protocolFnDecl = catalyst::ensureFunctionDeclaration<LLVM::LLVMFuncOp>(
rewriter, op, protocolFuncName, protocolFuncType);
LLVM::CallOp::create(rewriter, loc, protocolFnDecl, operands);
SmallVector<Value> values;
values.insert(values.end(), adaptor.getInQubits().begin(), adaptor.getInQubits().end());
rewriter.replaceOp(op, values);
return success();
}
};
LogicalResult buildPulseCall(Operation *op, Value inQubit, Value time, FloatAttr phaseAttr,
BeamAttr beamAttr, StringRef qirName, const TypeConverter *conv,
ConversionPatternRewriter &rewriter)
{
Location loc = op->getLoc();
MLIRContext *ctx = op->getContext();
Value phase = LLVM::ConstantOp::create(rewriter, loc, phaseAttr);
Type qubitTy = conv->convertType(catalyst::ion::QubitType::get(ctx));
Value beamStructPtr = createBeamStruct(loc, rewriter, ctx, beamAttr);
SmallVector<Value> operands = {inQubit, time, phase, beamStructPtr};
Type qirSignature =
LLVM::LLVMFunctionType::get(conv->convertType(PulseType::get(ctx)),
{conv->convertType(qubitTy), time.getType(),
Float64Type::get(ctx), LLVM::LLVMPointerType::get(ctx)});
LLVM::LLVMFuncOp fnDecl =
catalyst::ensureFunctionDeclaration<LLVM::LLVMFuncOp>(rewriter, op, qirName, qirSignature);
rewriter.replaceOpWithNewOp<LLVM::CallOp>(op, fnDecl, operands);
return success();
}
struct PulseOpPattern : public OpConversionPattern<catalyst::ion::PulseOp> {
using OpConversionPattern<catalyst::ion::PulseOp>::OpConversionPattern;
LogicalResult matchAndRewrite(catalyst::ion::PulseOp op, catalyst::ion::PulseOpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override
{
return buildPulseCall(op, adaptor.getInQubit(), op.getTime(), op.getPhase(), op.getBeam(),
"__catalyst__oqd__pulse", getTypeConverter(), rewriter);
}
};
struct MeasurePulseOpPattern : public OpConversionPattern<catalyst::ion::MeasurePulseOp> {
using OpConversionPattern<catalyst::ion::MeasurePulseOp>::OpConversionPattern;
LogicalResult matchAndRewrite(catalyst::ion::MeasurePulseOp op,
catalyst::ion::MeasurePulseOpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override
{
return buildPulseCall(op, adaptor.getInQubit(), op.getTime(), op.getPhase(), op.getBeam(),
"__catalyst__oqd__measure_pulse", getTypeConverter(), rewriter);
}
};
struct ReadoutBitOpPattern : public OpConversionPattern<catalyst::ion::ReadoutBitOp> {
using OpConversionPattern<catalyst::ion::ReadoutBitOp>::OpConversionPattern;
LogicalResult matchAndRewrite(catalyst::ion::ReadoutBitOp op,
catalyst::ion::ReadoutBitOpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override
{
Location loc = op.getLoc();
MLIRContext *ctx = this->getContext();
Type ptrType = LLVM::LLVMPointerType::get(ctx);
Type i32Ty = IntegerType::get(ctx, 32);
Type readoutFuncType = LLVM::LLVMFunctionType::get(i32Ty, {ptrType});
LLVM::LLVMFuncOp readoutFnDecl = catalyst::ensureFunctionDeclaration<LLVM::LLVMFuncOp>(
rewriter, op, "__catalyst__oqd__readout_bit", readoutFuncType);
Value cntVal =
LLVM::CallOp::create(rewriter, loc, readoutFnDecl, ValueRange{adaptor.getInQubit()})
.getResult();
// Thread the qubit through unchanged; the physical qubit pointer is the same.
rewriter.replaceOp(op, {adaptor.getInQubit(), cntVal});
return success();
}
};
} // namespace
namespace catalyst {
namespace ion {
void populateConversionPatterns(LLVMTypeConverter &typeConverter, RewritePatternSet &patterns)
{
patterns.add<IonOpPattern>(typeConverter, patterns.getContext());
patterns.add<ModesOpPattern>(typeConverter, patterns.getContext());
patterns.add<PulseOpPattern>(typeConverter, patterns.getContext());
patterns.add<MeasurePulseOpPattern>(typeConverter, patterns.getContext());
patterns.add<ReadoutBitOpPattern>(typeConverter, patterns.getContext());
patterns.add<ParallelProtocolOpPattern>(typeConverter, patterns.getContext());
}
} // namespace ion
} // namespace catalyst