Meta tags:
description= What each quantum gate actually does to a qubit state, with circuit diagrams and matrix forms for Hadamard, Pauli-X/Y/Z, CNOT, Toffoli, and the…;
author= QuantumComputingCourses.com;
Headings (most frequently used words):
gate, the, gates, and, cnot, controlled, identity, clifford, to, quantum, toffoli, is, phase, cz, hadamard, pauli, with, not, are, fidelity, circuit, qubits, decomposition, in, native, go, global, of, diagrams, what, ccnot, swap, rotation, rx, ry, rz, sets, universality, how, physically, implemented, error, rates, iswap, proofs, multi, qubit, group, ancilla, noise, practice, parameterized, variational, algorithms, transpilation, common, mistakes, avoid, where, next, try, it, yourself, builder, related, tutorials, get, one, email, week, its, own, inverse, creating, entanglement, pi, superconducting, ibm, google, rigetti, trapped, ions, ionq, quantinuum, speed, coherence, trade, off, comparison, across, platforms, 2024, benchmarks, relationship, hxh, hzh, xz, iy, up, decomposing, into, significance, why, special, gottesman, knill, theorem, vqe, style, ansatz, qaoa, structure, parameter, shift, rule, confusing, cx, using, degrees, instead, radians, treating, as, significant, forgetting, that, measurement, misidentifying, vs, non, ready, deeper, learn, reference, careers, about,
Text of the page (most frequently used words):
the (243), gate (142), gates (120), and (106), quantum (90), cnot (86), qubit (77), #circuit (48), are (46), rangle (46), with (44), this (41), for (40), two (38), from (36), quantumcircuit (35), clifford (34), qiskit (33), qubits (30), you (30), import (30), error (28), not (28), that (28), control (28), phase (26), print (26), target (26), text (24), hadamard (21), controlled (21), iswap (21), can (20), single (20), state (19), array (18), theta (18), hardware (17), native (17), rotation (17), toffoli (17), pauli (17), all (16), measurement (16), cdot (16), identity (15), fidelity (15), when (15), states (15), computing (14), operation (14), classical (14), otimes (14), into (14), matrix (14), superconducting (14), ibm (13), read (13), any (13), courses (12), how (12), set (12), params (12), dagger (12), pulse (12), cos (12), sin (12), use (11), time (11), numpy (11), applies (11), both (11), each (11), guide (10), one (10), where (10), variational (10), algorithms (10), noise (10), need (10), using (10), result (10), true (10), 100 (10), ion (10), your (9), algorithm (9), tutorials (9), decomposition (9), group (9), swap (9), correction (9), only (9), axis (9), allclose (9), unitary (9), about (8), bloch (8), sphere (8), min (8), bell (8), these (8), which (8), circuits (8), same (8), global (8), why (8), shift (8), layer (8), trapped (8), what (7), because (7), also (7), every (7), measure (7), apply (7), they (7), langle (7), degree (7), around (7), count (7), gamma (7), between (7), platforms (7), google (7), coupling (7), superposition (7), entanglement (6), common (6), ancilla (6), implemented (6), here (6), universal (6), non (6), operations (6), fault (6), tolerant (6), than (6), qc_right (6), qc_wrong (6), rotate (6), rotations (6), transpiled (6), draw (6), beta (6), roughly (6), its (6), conjugation (6), means (6), through (6), 1000 (6), coherence (6), pmatrix (6), symbol (6), 2026 (5), com (5), framework (5), case (5), free (5), level (5), transpilation (5), parameterized (5), practice (5), physically (5), sets (5), hello (5), world (5), has (5), full (5), optimization (5), gives (5), does (5), wrong (5), after (5), errors (5), conj (5), degrees (5), flips (5), cost (5), while (5), original (5), like (5), heron (5), parameter (5), rule (5), cost_fn (5), vqe (5), parameters (5), understanding (5), total (5), output (5), noise_model (5), computation (5), times (5), sqrt (5), basis (5), standard (5), 200 (5), typically (5), see (4), terms (4), learning (4), zeitgeist (4), donovan (4), real (4), related (4), next (4), multi (4), rates (4), more (4), first (4), have (4), end (4), other (4), probabilities (4), explore (4), above (4), simulable (4), verify (4), matters (4), theorem (4), efficiently (4), always (4), results (4), produce (4), them (4), comparison (4), but (4), rotates (4), radians (4), produces (4), abstract (4), run (4), three (4), processors (4), eagle (4), ecr (4), property (4), example (4), param_index (4), requires (4), frac (4), qaoa (4), outcomes (4), rate (4), tdg (4), maps (4), special (4), important (4), key (4), plus (4), frequency (4), some (4), unchanged (4), chips (4), implement (4), ions (4), energy (4), equivalent (4), qc2 (4), rightarrow (4), reversible (4), inverse (4), policy (3), amazon (3), team (3), careers (3), programming (3), types (3), glossary (3), studies (3), frameworks (3), written (3), writes (3), research (3), cirq (3), pennylane (3), get (3), implementing (3), beginner (3), mistakes (3), avoid (3), proofs (3), universality (3), ccnot (3), simulation (3), browse (3), built (3), choice (3), code (3), discussed (3), fundamental (3), creates (3), classically (3), non_clifford (3), based (3), gottesman (3), knill (3), expensive (3), correct (3), before (3), undo (3), cannot (3), may (3), identical (3), state1 (3), state2 (3), expectation (3), will (3), different (3), instead (3), psi (3), approximately (3), without (3), used (3), simple (3), number (3), transpile (3), compiler (3), devices (3), directly (3), below (3), their (3), gradient (3), return (3), params_minus (3), params_plus (3), def (3), partial (3), theta_k (3), provides (3), derivative (3), rzz (3), approximate (3), create (3), ansatz (3), typical (3), uses (3), ideal (3), leakage (3), depolarizing_error (3), build (3), however (3), physical (3), essential (3), known (3), operator (3), computational (3), space (3), define (3), operators (3), decomposed (3), identities (3), sequence (3), cnot_10 (3), equals (3), diag (3), several (3), rigetti (3), rather (3), then (3), shared (3), quantinuum (3), ionq (3), probability (3), 999 (3), 300 (3), microseconds (3), takes (3), tunable (3), nanoseconds (3), shape (3), r_z (3), begin (3), flip (3), interference (3), equal (3), answers (3), diagrams (3), braket (3), cookies (2), experience (2), affiliate (2), quantumcomputingcourses (2), books (2), podcasts (2), events (2), faq (2), editorial (2), jobs (2), interview (2), certifications (2), salary (2), timeline (2), reference (2), news (2), compare (2), paths (2), learn (2), who (2), industry (2), references (2), tools (2), quantumcomputing (2), email (2), worth (2), week (2), reaching (2), point (2), bernstein (2), vazirani (2), hidden (2), string (2), finder (2), inequalities (2), chsh (2), test (2), know (2), python (2), language (2), intermediate (2), guides (2), coursera (2), edx (2), udemy (2), brilliant (2), tutorial (2), put (2), down (2), since (2), out (2), there (2), hand (2), physics (2), entirely (2), action (2), shor (2), via (2), stabilizer (2), contains (2), clifford_gates (2), name (2), barrier (2), check (2), adding (2), including (2), second (2), distillation (2), magic (2), place (2), distinct (2), bit (2), values (2), depending (2), works (2), array_equal (2), direct (2), phases (2), phi (2), entangling (2), whether (2), expand (2), become (2), gate_counts (2), type (2), size (2), equivalently (2), composed (2), square (2), depends (2), processor (2), generation (2), current (2), simplest (2), specific (2), value (2), would (2), compute (2), cost_minus (2), cost_plus (2), copy (2), evaluate (2), respect (2), evaluations (2), per (2), gradients (2), numerical (2), qaoa_layer (2), mixer (2), pair (2), n_qubits (2), vqe_ansatz (2), angles (2), function (2), budget (2), making (2), approx (2), shots (2), across (2), multiple (2), noisy (2), 4925 (2), 5000 (2), counts (2), simulator (2), aersimulator (2), add_all_qubit_quantum_error (2), error_2q (2), depolarizing (2), error_1q (2), noisemodel (2), model (2), qiskit_aer (2), simulate (2), low (2), called (2), setting (2), reducing (2), most (2), decomposing (2), well (2), either (2), measured (2), complex (2), outside (2), speedup (2), particularly (2), another (2), holds (2), generates (2), nothing (2), compilers (2), simplify (2), result4 (2), kron (2), swapped (2), result3 (2), result2 (2), hzh (2), result1 (2), hxh (2), eye (2), basic (2), conjugating (2), state_01 (2), swaps (2), natural (2), those (2), resonant (2), cnot_from_cz (2), symmetry (2), makes (2), relationship (2), acts (2), phonon (2), additional (2), neighboring (2), mechanism (2), adds (2), decoherence (2), harder (2), small (2), actual (2), connectivity (2), faster (2), internal (2), process (2), laser (2), individual (2), drives (2), microwave (2), couplers (2), envelope (2), levels (2), gaussian (2), shaped (2), affects (2), angle (2), happens (2), providers (2), actually (2), possible (2), r_y (2), appears (2), logic (2), just (2), change (2), forms (2), followed (2), flipped (2), interfere (2), prerequisites (2), wave (2), accept, decline, improve, track, performance, our, cookie, privacy, disclosure, llc, associate, earn, qualifying, purchases, contact, site, talent, pool, post, job, training, questions, cheatsheets, history, docs, maintained, curated, anyone, 241, 220, 112, subscribe, address, new, taking, changed, spam, unsubscribe, anytime, introduction, openhpi, skillsbuild, paid, fundamentals, information, aug, updated, glance, page, tensorflow, accelerating, cuda, gpu, previous, continue, structured, ready, deeper, share, yes, was, helpful, quantumzeitgeist, ran, his, 2018, subject, material, forced, nobody, should, make, pop, science, waving, phd, ramp, had, usually, stopped, working, found, drop, watch, vector, update, instantly, runs, browser, signup, install, open, screen, try, yourself, builder, shows, protect, computations, study, problems, combinations, committing, memory, factoring, eigensolvers, pieces, purely, formalism, else, warning, data, sdg, running, testing, purposes, accidentally, cause, slow, dramatically, simulators, distinction, reasons, says, even, trivial, way, push, beyond, simulability, far, due, misidentifying, defined, behavior, conditional, feedforward, explicitly, conditions, subsequent, mid, collapses, undone, collapse, placed, unpredictable, backend, forgetting, correctly, identifies, dot, abs, false, fails, state3, represent, observables, compares, statevectors, often, fail, implementations, treating, significant, writing, effectively, random, 180, message, valid, producing, unexpected, vice, versa, meant, confusing, determines, looks, significantly, larger, transpiler, optimizations, adjacent, merged, redundant, cancelled, dict, breakdown, count_ops, optimization_level, basis_gates, decompose, write, must, translate, natives, root, older, falcon, exposed, exactly, eigenvalues, generator, mathematical, analogue, hamiltonian, parameter_shift_gradient, optimize, exact, approximations, appearing, problem, layers, alternate, structure, eigensolver, style, workhorses, adjusts, minimize, critical, deciding, feasible, unreliable, contamination, tells, effective, matches, expect, remainder, depolarization, spreading, get_counts, 10000, 001, realistic, imperfect, understand, impact, aer, enormously, transversally, relatively, require, resource, costs, quite, active, area, surface, primitives, therefore, along, requiring, helper, starts, participates, restored, discarded, enable, construction, simpler, paulis, member, checking, profound, alone, sufficient, advantage, starting, measurements, simulated, computer, polynomial, regardless, spreads, propagate, central, propagation, rules, involve, relations, generators, transform, generated, products, consists, map, under, precisely, yields, position, computers, breaks, together, dense, unitaries, ingredient, enables, hierarchy, significance, cases, include, form, general, sequences, sees, replace, thirds, depth, wrapping, hadamards, compared, product, reverse, intuitively, verification, confirming, arises, naturally, coupled, excitation, accumulation, origin, earlier, left, applying, factor, scheme, numerically, natively, compiled, targeting, backends, lacks, designated, symmetric, again, closely, convert, otherwise, oscillators, bus, introduces, pathways, exchange, environment, collisions, potential, source, reason, focuses, heavily, minimizing, crosstalk, forte, sycamore, platform, 2024, benchmarks, sounds, accumulates, nearly, useless, dimension, fidelities, randomized, benchmarking, robust, estimate, insensitive, preparation, hilbert, average, perfect, quantifies, close, nearest, neighbor, 500, seconds, minutes, maintain, ratio, perform, dominates, comparable, allowing, hundreds, thousands, sequential, speed, trade, off, motion, modes, chain, molmer, sorensen, light, entangles, collective, vibrational, mode, shining, focused, beam, onto, stimulated, raman, transitions, system, slower, atomic, commonly, ytterbium, 171, barium, 133, held, electromagnetic, fields, inside, vacuum, chamber, electronic, serve, rely, resonator, coupler, echoed, cross, resonance, implements, 600, newer, tens, causes, leak, population, higher, pulses, reduce, drag, removal, adiabatic, term, proportional, suppressing, third, exist, precise, electronics, send, absorbs, amplitude, duration, rabi, oscillation, calibration, tiny, containing, cooled, millikelvin, behaves, artificial, atom, separated, ghz, josephson, junction, helps, explain, others, dominant, fundamentally, ways, compile, execute, section, phasedxz, notes, collection, zyz, euler, proves, alpha, delta, r_x, matrices, fine, grained, appear, constantly, exchanges, limited, route, past, ccx, arithmetic, adders, boolean, within, features, computes, bits, reversibly, achieved, controls, having, allows, arbitrary, precision, solovay, kitaev, affect, superdense, coding, distribution, teleportation, never, entangle, perhaps, procedure, maximally, entangled, creating, truth, table, operates, give, twice, back, started, involution, own, misconception, deserves, mean, tries, simultaneously, exists, linear, combination, manipulate, amplitudes, constructively, destructively, could, claims, relies, similar, prepare, parallelism, placing, mixture, combines, effects, decompositions, ixz, leaves, patterns, serves, counterpart, involves, applied, building, blocks, such, differences, apart, recover, inputs, knowing, mathematically, represented, meaning, constraint, guarantees, preserved, sections, background, needed, variables, functions, loops, mar, series, concepts, home, search, troubleshooting, prep, universities, career, cheat, sheets, migration, pinball, ocean, tket, pyquil, grover, quera, azure, course, skip, main, content,
Text of the page (random words):
ndard cnot np allclose cnot_from_cz cnot output true the iswap gate the iswap gate is native on some superconducting platforms particularly those that use a resonant coupling scheme between qubits its matrix is iswap matrix 1 0 0 0 0 0 i 0 0 i 0 0 0 0 0 1 the iswap gate swaps 01 01 rangle 01 and 10 10 rangle 10 while applying a phase factor of i i i iswap 01 i 10 text iswap 01 rangle i 10 rangle iswap 01 i 10 iswap 10 i 01 text iswap 10 rangle i 01 rangle iswap 10 i 01 the states 00 00 rangle 00 and 11 11 rangle 11 are left unchanged physically the iswap arises naturally when two superconducting qubits with the same frequency are coupled the excitation swaps between them with a phase accumulation this natural origin is why some platforms including google s earlier processors use iswap as a native gate to build a cnot from iswap gates you need two iswap gates plus single qubit rotations import numpy as np iswap matrix iswap np array 1 0 0 0 0 0 1 j 0 0 1 j 0 0 0 0 0 1 verify action on 01 state_01 np array 0 1 0 0 result iswap state_01 print 01 after iswap result output 0 0 j 0 0 j 0 1 j 0 0 j this is i 10 confirming the swap with phase i circuit identity proofs understanding circuit identities is essential for both hand optimization and understanding how compilers simplify quantum circuits here are several important identities with numerical verification identity 1 hxh z conjugating x by hadamard gates produces z intuitively h rotates the bloch sphere so that the x axis maps to the z axis identity 2 hzh x the reverse also holds conjugating z by hadamard gives x identity 3 xz iy up to global phase the product of x and z gates equals i y iy iy identity 4 cnot h h cz h h wrapping cz with hadamards on both qubits also produces a cnot with swapped control and target compared to the single hadamard identity above import numpy as np define basic gates x np array 0 1 1 0 y np array 0 1 j 1 j 0 z np array 1 0 0 1 h np array 1 1 1 1 np sqrt 2 i np eye 2 identity 1 h x h z result1 h x h print hxh z np allclose result1 z true identity 2 h z h x result2 h z h print hzh x np allclose result2 x true identity 3 x z iy result3 x z print xz iy np allclose result3 1 j y true identity 4 h h cz h h gives a cnot with swapped control target cz np diag 1 1 1 1 hh np kron h h result4 hh cz hh this equals cnot with qubit 1 as control qubit 0 as target cnot_10 np array 1 0 0 0 0 0 0 1 0 0 1 0 0 1 0 0 print h h cz h h cnot_10 np allclose result4 cnot_10 true these identities are how quantum circuit compilers simplify gate sequences for example if a compiler sees h x h in sequence it can replace it with a single z gate reducing the circuit depth by two thirds multi qubit controlled gates the cnot gate is a special case of a general controlled u gate where u is any single qubit unitary the controlled u gate applies u to the target qubit only when the control qubit is 1 1 rangle 1 the matrix form is c u 0 0 i 1 1 u c u 0 rangle langle 0 otimes i 1 rangle langle 1 otimes u c u 0 0 i 1 1 u this means if the control is 0 0 rangle 0 do nothing if the control is 1 1 rangle 1 apply u u u important special cases include controlled z cz u z u z u z the gate we discussed above controlled s cs u s u s u s applies a 90 degree phase when both qubits are 1 1 rangle 1 controlled t ct u t u t u t applies a 45 degree phase when both qubits are 1 1 rangle 1 decomposing controlled s into native gates any controlled phase gate can be decomposed into cnot gates plus single qubit rotations for the controlled s gate from qiskit import quantumcircuit import numpy as np build controlled s from cnot and rz gates qc quantumcircuit 2 qc rz np pi 4 1 rz pi 4 on target qc cx 0 1 cnot qc rz np pi 4 1 rz pi 4 on target qc cx 0 1 cnot qc rz np pi 4 0 rz pi 4 on control for global phase correction print qc draw the significance of controlled t the controlled t gate holds a special position in fault tolerant quantum computing the gate set h s cnot generates the clifford group discussed below which is efficiently simulable by classical computers adding the t gate breaks out of the clifford group and together with the clifford gates generates a set that is dense in all unitaries the controlled t gate is the key ingredient that enables the full clifford t hierarchy which is the standard framework for fault tolerant quantum computation clifford gates and the clifford group the clifford group consists of all unitary operations that map pauli operators to pauli operators under conjugation more precisely a unitary c c c is clifford if for every pauli operator p p p the conjugation c p c c p c dagger c p c yields another pauli operator up to a phase of 1 pm 1 1 or i pm i i the clifford group is generated by three gates h s cnot all pauli gates x y z are also clifford gates since they are products of h and s here are the key conjugation relations that define how clifford generators transform pauli operators import numpy as np x np array 0 1 1 0 y np array 0 1 j 1 j 0 z np array 1 0 0 1 h np array 1 1 1 1 np sqrt 2 s np array 1 0 0 1 j h conjugation h maps x z print h x h z np allclose h x h conj t z true print h z h x np allclose h z h conj t x true s conjugation s maps x y print s x s y np allclose s x s conj t y true print s z s z np allclose s z s conj t z true for cnot the pauli propagation rules involve both qubits cnot x i cnot x x text cnot cdot x otimes i cdot text cnot dagger x otimes x cnot x i cnot x x cnot i x cnot i x text cnot cdot i otimes x cdot text cnot dagger i otimes x cnot i x cnot i x cnot z i cnot z i text cnot cdot z otimes i cdot text cnot dagger z otimes i cnot z i cnot z i cnot i z cnot z z text cnot cdot i otimes z cdot text cnot dagger z otimes z cnot i z cnot z z the first rule is particularly important an x error on the control qubit spreads to the target qubit through a cnot understanding how errors propagate through clifford gates is central to quantum error correction why clifford gates are special the gottesman knill theorem the gottesman knill theorem states that any quantum circuit composed entirely of clifford gates starting from computational basis states with measurements only in the computational basis can be efficiently simulated on a classical computer efficiently means in polynomial time and space regardless of the number of qubits this is a profound result it means that entanglement alone is not sufficient for quantum speedup a bell state circuit h cnot is a clifford circuit and is classically simulable quantum advantage requires non clifford gates and the t gate is the simplest non clifford gate you can verify that t is not clifford by checking its conjugation of x t x t 1 2 x y t x t dagger frac 1 sqrt 2 x y t x t 2 1 x y this is not a pauli operator the t gate maps paulis outside the pauli group so t is not a member of the clifford group ancilla qubits and gate decomposition an ancilla qubit is a helper qubit that starts in a known state participates in a computation and is either restored to its original state or measured and discarded ancilla qubits enable the construction of complex multi qubit gates from simpler operations the toffoli decomposition the toffoli gate is a three qubit gate but most hardware only provides one and two qubit native gates decomposing the toffoli into these primitives is therefore essential a well known decomposition uses 6 cnot gates along with h t and t t dagger t gates requiring no ancilla qubits from qiskit import quantumcircuit toffoli decomposition into h t t cnot control qubits 0 1 target qubit 2 qc quantumcircuit 3 qc h 2 qc cx 1 2 qc tdg 2 qc cx 0 2 qc t 2 qc cx 1 2 qc tdg 2 qc cx 0 2 qc t 1 qc t 2 qc h 2 qc cx 0 1 qc t 0 qc tdg 1 qc cx 0 1 print qc draw this decomposition matters enormously for fault tolerant quantum computing in surface code error correction clifford gates h s cnot can be implemented transversally at relatively low cost t gates however require a resource called magic state distillation which is expensive each t gate costs roughly 10 to 100 times more than a clifford gate in terms of physical qubits and time the toffoli decomposition above uses 7 t t t dagger t gates so a single toffoli is quite expensive in a fault tolerant setting reducing the t count of circuits is an active area of research gate noise in practice real quantum gates are imperfect to understand the impact of noise on a computation you can simulate gate errors using qiskit aer s noise model from qiskit import quantumcircuit from qiskit_aer import aersimulator from qiskit_aer noise import noisemodel depolarizing_error build a bell state circuit qc quantumcircuit 2 2 qc h 0 qc cx 0 1 qc measure 0 1 0 1 create a noise model with realistic error rates noise_model noisemodel single qubit depolarizing error 0 1 error rate error_1q depolarizing_error 0 001 1 noise_model add_all_qubit_quantum_error error_1q h x y z s t two qubit depolarizing error 1 error rate error_2q depolarizing_error 0 01 2 noise_model add_all_qubit_quantum_error error_2q cx run with noise simulator aersimulator noise_model noise_model result simulator run qc shots 10000 result counts result get_counts print noisy bell state results counts ideal result 00 5000 11 5000 noisy result typical 00 4925 11 4925 01 75 10 75 in the ideal case a bell state produces only 00 and 11 outcomes with noise you see leakage into 01 and 10 the contamination rate tells you the effective circuit error if about 1 5 of shots produce wrong outcomes your total circuit error is approximately 1 5 this matches what you would expect from the error budget one h gate with 0 1 error and one cnot with 1 error gives roughly 1 1 total error with the remainder from depolarization spreading errors across multiple outcomes understanding this error budget is critical for deciding whether a quantum circuit is feasible on current hardware if your circuit has 100 cnot gates at 1 error each the total error is approximately 1 0 99 100 63 1 0 99 100 approx 63 1 0 99 100 63 making the output unreliable parameterized gates in variational algorithms the rotation gates rx ry and rz are the workhorses of variational quantum algorithms where classical optimization adjusts gate parameters to minimize a cost function vqe style ansatz in the variational quantum eigensolver vqe a typical ansatz uses ry gates for single qubit rotations and cnot for entanglement here is a 2 qubit example with 4 parameters import numpy as np from qiskit import quantumcircuit def vqe_ansatz params create a 2 qubit vqe ansatz with 4 parameters qc quantumcircuit 2 layer 1 single qubit rotations qc ry params 0 0 qc ry params 1 1 entangling layer qc cx 0 1 layer 2 single qubit rotations qc ry params 2 0 qc ry params 3 1 return qc example circuit with specific angles params 0 3 0 7 1 2 0 5 qc vqe_ansatz params print qc draw qaoa gate structure in the quantum approximate optimization algorithm qaoa two types of parameterized layers alternate the cost layer applies rzz gates implemented as cnot rz cnot and the mixer layer applies rx gates import numpy as np from qiskit import quantumcircuit def qaoa_layer gamma beta n_qubits 2 one layer of qaoa for a simple 2 qubit problem qc quantumcircuit n_qubits cost layer rzz gamma on each pair rzz gamma cnot i rz gamma cnot qc cx 0 1 qc rz gamma 1 qc cx 0 1 mixer layer rx beta on each qubit qc rx beta 0 qc rx beta 1 return qc qc qaoa_layer gamma 0 5 beta 0 3 print qc draw the parameter shift rule to optimize variational circuits you need gradients the parameter shift rule provides exact gradients not numerical approximations for rotation gates for any rotation gate r θ r theta r θ appearing in a circuit the partial derivative of the expectation value e langle e rangle e with respect to θ theta θ is e θ k e θ k π 2 e θ k π 2 2 frac partial langle e rangle partial theta_k frac langle e theta_k pi 2 rangle langle e theta_k pi 2 rangle 2 θ k e 2 e θ k π 2 e θ k π 2 this requires two circuit evaluations per parameter for a circuit with p p p parameters computing the full gradient requires 2 p 2p 2 p circuit evaluations import numpy as np def parameter_shift_gradient cost_fn params param_index compute the gradient of cost_fn with respect to params param_index using the parameter shift rule shift np pi 2 evaluate at theta pi 2 params_plus params copy params_plus param_index shift cost_plus cost_fn params_plus evaluate at theta pi 2 params_minus params copy params_minus param_index shift cost_minus cost_fn params_minus return cost_plus cost_minus 2 0 example compute gradient for all 4 parameters params np array 0 3 0 7 1 2 0 5 in practice cost_fn would run the vqe circuit and measure the expectation value of a hamiltonian the parameter shift rule works because rotation gates have exactly two eigenvalues 1 2 pm 1 2 1 2 in their generator this is a mathematical property specific to quantum gates and has no classical analogue native gate transpilation when you write a circuit using abstract gates like h t or s the quantum compiler must translate these into the hardware s native gate set on ibm quantum processors the single qubit natives are rz sx x where sx is the square root of x a 90 degree rotation around the x axis the two qubit native depends on the processor generation older falcon devices exposed cx directly eagle devices used ecr and the current heron devices use cz we use the cx based set below because it is the simplest to read here is how common gates decompose into this native set h gate rz π 2 sx rz π 2 text rz pi 2 cdot text sx cdot text rz pi 2 rz π 2 sx rz π 2 t gate rz π 4 text rz pi 4 rz π 4 s gate rz π 2 text rz pi 2 rz π 2 y gate x rz π text x cdot text rz pi x rz π or equivalently sx composed with rz gates from qiskit import quantumcircuit from qiskit compiler import transpile original circuit with abstract gates qc quantumcircuit 2 qc h 0 qc t 0 qc s 1 qc cx 0 1 qc h 1 print original circuit print qc draw print f original gate count qc size transpile to ibm s native gate set transpiled transpile qc basis_gates rz sx x cx optimization_level 2 print n transpiled circuit print transpiled draw print f transpiled gate count transpiled size count each gate type gate_counts transpiled count_ops print f gate breakdown dict gate_counts when you run this you will see that the 5 abstract gates expand into a larger number of native gates the h gates each become three native gates rz sx rz while t and s gates each become a single rz the transpiler also applies optimizations adjacent rz gates are merged and redundant gates are cancelled this is why native gate count not abstract gate count determines the true cost of a circuit a circuit that looks simple in terms of h and t gates may expand significantly after transpilation common mistakes to avoid 1 confusing cx and cz cx cnot flips the target qubit when the control is 1 1 rangle 1 cz applies a phase of 1 1 1 when both qubits are 1 1 rangle 1 they are related by hadamard gates on the target cx i h cz i h text cx i otimes h cdot text cz cdot i oti...
|