qcs 0.26.2-rc.0

High level interface for running Quil on a QPU
Documentation
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
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
//! This module provides bindings for compiling programs with the Quilc compiler.

use std::collections::HashMap;
use std::convert::TryFrom;

use quil_rs::program::{Program, ProgramError};
use serde::{Deserialize, Deserializer, Serialize};

use qcs_api_client_openapi::models::InstructionSetArchitecture;

use super::isa::{self, Compiler};
use super::rpcq;

#[cfg(feature = "stubs")]
use pyo3_stub_gen::derive::gen_stub_pyclass;

/// Number of seconds to wait before timing out.
pub const DEFAULT_COMPILER_TIMEOUT: f64 = 30.0;

/// The Quilc compiler methods
pub trait Client {
    /// Compile the program `quil` for the given target device `isa`
    /// with the compilation options `options`.
    fn compile_program(
        &self,
        quil: &str,
        isa: TargetDevice,
        options: CompilerOpts,
    ) -> Result<CompilationResult, Error>;

    /// Get the version of Quilc
    fn get_version_info(&self) -> Result<String, Error>;

    /// Given a circuit that consists only of elements of the Clifford group,
    /// return its action on a `PauliTerm`.
    ///
    /// In particular, for Clifford `C`, and Pauli `P`, this returns the Pauli Term
    /// representing `CPC^{\dagger}`.
    fn conjugate_pauli_by_clifford(
        &self,
        request: ConjugateByCliffordRequest,
    ) -> Result<ConjugatePauliByCliffordResponse, Error>;

    /// Construct a randomized benchmarking experiment on the given qubits, decomposing into
    /// gateset.
    ///
    /// If interleaver is not provided, the returned sequence will have the form
    /// `C_1 C_2 ... C_(depth-1) C_inv ,`
    ///
    /// where each C is a Clifford element drawn from gateset, `C_{< depth}` are randomly selected,
    /// and `C_inv` is selected so that the entire sequence composes to the identity.  If an
    /// interleaver `G` (which must be a Clifford, and which will be decomposed into the native
    /// gateset) is provided, then the sequence instead takes the form
    /// `C_1 G C_2 G ... C_(depth-1) G C_inv .`
    fn generate_randomized_benchmarking_sequence(
        &self,
        request: RandomizedBenchmarkingRequest,
    ) -> Result<GenerateRandomizedBenchmarkingSequenceResponse, Error>;
}

/// The result of compiling a Quil program to native quil with `quilc`
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "stubs", gen_stub_pyclass)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "qcs_sdk.compiler.quilc", get_all, frozen)
)]
pub struct CompilationResult {
    /// The compiled program
    pub program: Program,
    /// Metadata about the compiled program
    pub native_quil_metadata: Option<NativeQuilMetadata>,
}

/// A set of options that determine the behavior of compiling programs with quilc
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "stubs", gen_stub_pyclass)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "qcs_sdk.compiler.quilc", frozen)
)]
pub struct CompilerOpts {
    /// The number of seconds to wait before timing out. If `None`, there is no timeout.
    pub(crate) timeout: Option<f64>,

    /// If the compiler should produce "protoquil" as output. If `None`, the default
    /// behavior configured in the compiler service is used.
    pub(crate) protoquil: Option<bool>,
}

/// Functions for building a [`CompilerOpts`] instance
impl CompilerOpts {
    /// Creates a new instance of [`CompilerOpts`] with zero values for each option.
    /// Consider using [`CompilerOpts::default()`] to create an instance with recommended defaults.
    #[must_use]
    pub fn new() -> Self {
        Self {
            timeout: None,
            protoquil: None,
        }
    }

    /// Set the number of seconds to wait before timing out. If set to None, the timeout is disabled.
    #[must_use]
    pub fn with_timeout(&mut self, seconds: Option<f64>) -> Self {
        self.timeout = seconds;
        *self
    }

    /// Set to control whether the compiler should produce "protoquil" as output.
    /// If `None`, the default behavior configured in the compiler service is used.
    #[must_use]
    pub fn with_protoquil(&mut self, protoquil: Option<bool>) -> Self {
        self.protoquil = protoquil;
        *self
    }
}

impl Default for CompilerOpts {
    /// Default compiler options
    /// * `timeout`: See [`DEFAULT_COMPILER_TIMEOUT`]
    fn default() -> Self {
        Self {
            timeout: Some(DEFAULT_COMPILER_TIMEOUT),
            protoquil: None,
        }
    }
}

/// Pauli Term
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, PartialOrd)]
#[serde(tag = "_type")]
#[cfg_attr(feature = "stubs", gen_stub_pyclass)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "qcs_sdk.compiler.quilc", frozen, get_all)
)]
pub struct PauliTerm {
    /// Qubit indices onto which the factors of the Pauli term are applied.
    pub indices: Vec<u64>,

    /// Ordered factors of the Pauli term.
    pub symbols: Vec<String>,
}

/// Request to conjugate a Pauli Term by a Clifford element.
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, PartialOrd)]
#[serde(tag = "_type")]
#[cfg_attr(feature = "stubs", gen_stub_pyclass)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "qcs_sdk.compiler.quilc", frozen, get_all)
)]
pub struct ConjugateByCliffordRequest {
    /// Pauli Term to conjugate.
    pub pauli: PauliTerm,

    /// Clifford element.
    pub clifford: String,
}

/// The "outer" request shape for a `conjugate_pauli_by_clifford` request.
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, PartialOrd)]
#[cfg_attr(feature = "stubs", gen_stub_pyclass)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "qcs_sdk.compiler.quilc", frozen, get_all)
)]
pub(crate) struct ConjugatePauliByCliffordRequest {
    #[serde(rename = "*args")]
    args: [ConjugateByCliffordRequest; 1],
}

impl From<ConjugateByCliffordRequest> for ConjugatePauliByCliffordRequest {
    fn from(value: ConjugateByCliffordRequest) -> Self {
        Self { args: [value] }
    }
}

/// Conjugate Pauli by Clifford response.
#[derive(Clone, Deserialize, Debug, PartialEq, PartialOrd)]
#[cfg_attr(feature = "stubs", gen_stub_pyclass)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "qcs_sdk.compiler.quilc", frozen, get_all)
)]
pub struct ConjugatePauliByCliffordResponse {
    /// Encoded global phase factor on the emitted Pauli.
    pub phase: i64,

    /// Description of the encoded Pauli.
    pub pauli: String,
}

/// Request to generate a randomized benchmarking sequence.
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, PartialOrd)]
#[serde(tag = "_type")]
#[cfg_attr(feature = "stubs", gen_stub_pyclass)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "qcs_sdk.compiler.quilc", frozen, get_all)
)]
pub struct RandomizedBenchmarkingRequest {
    /// Depth of the benchmarking sequence.
    pub depth: u64,

    /// Number of qubits involved in the benchmarking sequence.
    pub qubits: u64,

    /// List of Quil programs, each describing a Clifford.
    pub gateset: Vec<String>,

    /// PRNG seed. Set this to guarantee repeatable results.
    pub seed: Option<u64>,

    /// Fixed Clifford, specified as a Quil string, to interleave through an RB sequence.
    pub interleaver: Option<String>,
}

/// The "outer" request shape for a `generate_rb_sequence` request.
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, PartialOrd)]
pub(crate) struct GenerateRandomizedBenchmarkingSequenceRequest {
    #[serde(rename = "*args")]
    args: [RandomizedBenchmarkingRequest; 1],
}

impl From<RandomizedBenchmarkingRequest> for GenerateRandomizedBenchmarkingSequenceRequest {
    fn from(value: RandomizedBenchmarkingRequest) -> Self {
        Self { args: [value] }
    }
}

/// Randomly generated benchmarking sequence response.
#[derive(Clone, Deserialize, Debug, PartialEq, PartialOrd)]
#[cfg_attr(feature = "stubs", gen_stub_pyclass)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "qcs_sdk.compiler.quilc", frozen, get_all)
)]
pub struct GenerateRandomizedBenchmarkingSequenceResponse {
    /// List of Cliffords, each expressed as a list of generator indices.
    pub sequence: Vec<Vec<i64>>,
}

/// All of the errors that can occur within this module.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// An ISA-related error.
    #[error(
        "Problem converting ISA to quilc format. This is a bug in this library or in QCS: {0}"
    )]
    Isa(#[from] isa::Error),
    /// An error when trying to connect to quilc.
    #[error("Problem connecting to quilc at {0}: {1}")]
    QuilcConnection(String, #[source] rpcq::Error),
    /// An error when trying to compile using quilc.
    #[error("Problem compiling quil program: {0}")]
    QuilcCompilation(CompilationError),
    /// An error when trying to parse the compiled program.
    #[error("Problem when trying to parse the compiled program: {0}")]
    Parse(ProgramError),
}

/// Errors during compilation with one of the supported clients
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum CompilationError {
    #[cfg(feature = "libquil")]
    /// Errors during compilation when using libquil
    #[error("compilation error from libquil: {0}")]
    Libquil(crate::compiler::libquil::Error),
    /// Errors during compilation when using RPCQ
    #[error("compilation error from RPCQ: {0}")]
    Rpcq(rpcq::Error),
}

/// The response from quilc for a `quil_to_native_quil` request.
#[derive(Clone, Deserialize, Debug, PartialEq, PartialOrd)]
pub(crate) struct QuilToNativeQuilResponse {
    /// The compiled program
    pub(crate) quil: String,
    /// Metadata about the compiled program
    #[serde(default)]
    pub(crate) metadata: Option<NativeQuilMetadata>,
}

#[allow(unused_qualifications)]
fn deserialize_none_as_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
where
    D: Deserializer<'de>,
    T: Deserialize<'de> + std::default::Default,
{
    let opt = Option::deserialize(deserializer)?;
    Ok(opt.unwrap_or_default())
}

/// Metadata about a program compiled to native quil.
#[derive(Clone, Deserialize, Serialize, Debug, PartialEq, PartialOrd)]
#[cfg_attr(feature = "stubs", gen_stub_pyclass)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "qcs_sdk.compiler.quilc", eq)
)]
pub struct NativeQuilMetadata {
    /// Output qubit index relabeling due to SWAP insertion.
    #[serde(deserialize_with = "deserialize_none_as_default")]
    pub final_rewiring: Vec<u64>,
    /// Maximum number of successive gates in the native Quil program.
    pub gate_depth: Option<u64>,
    /// Total number of gates in the native Quil program.
    pub gate_volume: Option<u64>,
    /// Maximum number of two-qubit gates in the native Quil program.
    pub multiqubit_gate_depth: Option<u64>,
    /// Rough estimate of native quil program length in seconds.
    pub program_duration: Option<f64>,
    /// Rough estimate of fidelity of the native Quil program.
    pub program_fidelity: Option<f64>,
    /// Total number of swaps in the native Quil program.
    pub topological_swaps: Option<u64>,
    /// The estimated runtime of the program on a Rigetti QPU, in milliseconds. Available only for
    /// protoquil compliant programs.
    pub qpu_runtime_estimation: Option<f64>,
}

#[derive(Clone, Deserialize, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub(crate) struct QuilcVersionResponse {
    pub(crate) quilc: String,
}

/// The top level params that get passed to quilc
#[derive(Serialize, Debug, Clone, PartialEq)]
pub(crate) struct QuilcParams {
    pub(crate) protoquil: Option<bool>,
    #[serde(rename = "*args")]
    args: [NativeQuilRequest; 1],
}

impl QuilcParams {
    pub(crate) fn new(quil: &str, isa: TargetDevice) -> Self {
        Self {
            protoquil: None,
            args: [NativeQuilRequest::new(quil, isa)],
        }
    }

    pub(crate) fn with_protoquil(self, protoquil: Option<bool>) -> Self {
        Self { protoquil, ..self }
    }
}

/// The expected request structure for sending Quil to quilc to be compiled
#[derive(Serialize, Debug, Clone, PartialEq)]
#[serde(tag = "_type")]
struct NativeQuilRequest {
    quil: String,
    target_device: TargetDevice,
}

impl NativeQuilRequest {
    fn new(quil: &str, target_device: TargetDevice) -> Self {
        Self {
            quil: String::from(quil),
            target_device,
        }
    }
}

/// Description of a device to compile for.
#[cfg_attr(feature = "stubs", gen_stub_pyclass)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "qcs_sdk.compiler.quilc", frozen)
)]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(tag = "_type")]
pub struct TargetDevice {
    isa: Compiler,
    specs: HashMap<String, String>,
}

impl TryFrom<InstructionSetArchitecture> for TargetDevice {
    type Error = Error;

    fn try_from(isa: InstructionSetArchitecture) -> Result<Self, Self::Error> {
        Ok(Self {
            isa: Compiler::try_from(isa)?,
            specs: HashMap::new(),
        })
    }
}

#[cfg(test)]
mod tests {
    use crate::qvm::{self, http::AddressRequest};

    use super::*;
    use crate::client::Qcs;
    use qcs_api_client_openapi::models::InstructionSetArchitecture;
    use quil_rs::quil::Quil;
    use regex::Regex;
    use std::{fs::File, num::NonZeroU16};

    const EXPECTED_H0_OUTPUT: &str = "MEASURE 0\n";

    fn aspen_9_isa() -> InstructionSetArchitecture {
        serde_json::from_reader(File::open("tests/aspen_9_isa.json").unwrap()).unwrap()
    }

    pub(crate) fn qvm_isa() -> InstructionSetArchitecture {
        serde_json::from_reader(File::open("tests/qvm_isa.json").unwrap()).unwrap()
    }

    fn rpcq_client() -> rpcq::Client {
        let qcs = Qcs::load();
        let endpoint = qcs.get_config().quilc_url();
        rpcq::Client::new(endpoint).unwrap()
    }

    #[tokio::test]
    async fn compare_native_quil_to_expected_output() {
        let output = rpcq_client()
            .compile_program(
                "MEASURE 0",
                TargetDevice::try_from(qvm_isa()).expect("Couldn't build target device from ISA"),
                CompilerOpts::default(),
            )
            .expect("Could not compile");
        assert_eq!(output.program.to_quil_or_debug(), EXPECTED_H0_OUTPUT);
    }

    const BELL_STATE: &str = r"DECLARE ro BIT[2]

H 0
CNOT 0 1

MEASURE 0 ro[0]
MEASURE 1 ro[1]
";

    #[tokio::test]
    async fn run_compiled_bell_state_on_qvm() {
        let client = Qcs::load();
        let client = qvm::http::HttpClient::from(&client);
        let output = rpcq_client()
            .compile_program(
                BELL_STATE,
                TargetDevice::try_from(aspen_9_isa())
                    .expect("Couldn't build target device from ISA"),
                CompilerOpts::default(),
            )
            .expect("Could not compile");
        let mut results = qvm::Execution::new(&output.program.to_quil_or_debug())
            .unwrap()
            .run(
                NonZeroU16::new(10).expect("value is non-zero"),
                [("ro".to_string(), AddressRequest::IncludeAll())]
                    .iter()
                    .cloned()
                    .collect(),
                &HashMap::default(),
                &client,
            )
            .await
            .expect("Could not run program on QVM");
        for shot in results
            .memory
            .remove("ro")
            .expect("Did not receive ro buffer")
            .into_i8()
            .unwrap()
        {
            assert_eq!(shot.len(), 2);
            assert_eq!(shot[0], shot[1]);
        }
    }

    #[tokio::test]
    async fn test_compile_declare_only() {
        let output = rpcq_client()
            .compile_program(
                "DECLARE ro BIT[1]\n",
                TargetDevice::try_from(aspen_9_isa())
                    .expect("Couldn't build target device from ISA"),
                CompilerOpts::default(),
            )
            .expect("Should be able to compile");
        assert_eq!(output.program.to_quil_or_debug(), "DECLARE ro BIT[1]\n");
        assert_ne!(output.native_quil_metadata, None);
    }

    #[tokio::test]
    async fn get_version_info_from_quilc() {
        let rpcq_client = rpcq_client();
        let version = rpcq_client
            .get_version_info()
            .expect("Should get version info from quilc");
        let semver_re = Regex::new(r"^([0-9]+)\.([0-9]+)\.([0-9]+)$").unwrap();
        assert!(semver_re.is_match(&version));
    }

    #[tokio::test]
    async fn test_conjugate_pauli_by_clifford() {
        let rpcq_client = rpcq_client();
        let request = ConjugateByCliffordRequest {
            pauli: PauliTerm {
                indices: vec![0],
                symbols: vec!["X".into()],
            },
            clifford: "H 0".into(),
        };
        let response = rpcq_client
            .conjugate_pauli_by_clifford(request)
            .expect("Should conjugate pauli by clifford");

        assert_eq!(
            response,
            ConjugatePauliByCliffordResponse {
                phase: 0,
                pauli: "Z".into(),
            }
        );
    }

    #[tokio::test]
    async fn test_generate_randomized_benchmark_sequence() {
        let rpcq_client = rpcq_client();
        let request = RandomizedBenchmarkingRequest {
            depth: 2,
            qubits: 1,
            gateset: vec!["X 0", "H 0"].into_iter().map(String::from).collect(),
            seed: Some(314),
            interleaver: Some("Y 0".into()),
        };
        let response = rpcq_client
            .generate_randomized_benchmarking_sequence(request)
            .expect("Should generate randomized benchmark sequence");

        assert_eq!(
            response,
            GenerateRandomizedBenchmarkingSequenceResponse {
                sequence: vec![vec![1, 0], vec![0, 1, 0, 1], vec![1, 0]],
            }
        );
    }
}