Lesson 36 · 80 min · core
Amplitude Encoding & State Preparation
Amplitude encoding stores a vector in the amplitudes of qubits, . This lesson derives the binary-tree state-preparation circuit: a cascade of uniformly controlled rotations whose angles are ratios of partial norms, compiled into and CNOT gates with the Gray-code angle transform. It extends the construction to signed and complex amplitudes, counts rotations and CNOTs, proves by parameter counting that generic states need CNOTs, and explains why this loading cost can cancel claimed exponential speedups.
Prerequisites: Basis Encoding, Controlled Gates: CNOT, CZ, SWAP
Objectives and key results
Write the amplitude encoding of on qubits, including zero padding and normalisation.
Derive the binary-tree angles and prove by induction that the cascade of uniformly controlled rotations prepares .
Compile a uniformly controlled rotation with controls into rotations and CNOTs with the Gray-code transform , and prove .
Handle signed amplitudes with and complex amplitudes with a uniformly controlled cascade.
Count rotations and CNOTs, and prove the parameter-counting lower bound for generic states.
Explain why an state-preparation cost can erase an exponential quantum speedup.
- definition · Amplitude encoding
- formula · Binary-tree angles
- identity · Uniformly controlled R_Y with one control
- algorithm · Gray-code angle transform
- theorem · Cost and lower bound
Amplitude encoding of a real vector#
Basis encoding spends one qubit per bit of data and induces the kernel . Amplitude encoding takes the opposite extreme: the components of a real vector become the amplitudes of a quantum state, so only qubits are needed. This exponential compression is the starting point of many proposed quantum linear-algebra and machine-learning algorithms. In this lesson we construct an explicit circuit that prepares the encoded state, prove that it is correct, count its gates, and prove that no circuit can do essentially better for generic data.
Definition
Amplitude encoding
Let with and , and let . Extend by zeros to length , i.e. set for . The amplitude encoding of is the -qubit state where is the computational basis state whose big-endian index is . A state-preparation circuit for is a unitary with , possibly up to a global phase.
Register size, padding and normalisation
- Step 1:An -qubit register has amplitudes; the smallest integer with is the ceiling of .
- Step 2:Example: five features need three qubits and three padding zeros.
- Step 3:Zero padding does not change the Euclidean norm.
- Step 4:Expand the inner product bilinearly ( are real) and use the orthonormality of the computational basis.
- Step 5:, so rescaling the data changes the state at most by the global sign : the norm of is not stored and must be supplied separately if it matters.
- Step 6:Born rule: measuring in the computational basis returns index with probability , so the data cannot be read out by a single measurement.
Result
Fidelity kernel of amplitude encoding
For nonzero , The kernel is a smooth function of the data and equals if and only if is a nonzero multiple of .
Proof (5 steps)
- Step 1:Bilinear expansion with orthonormal basis states, exactly as in the normalisation computation.
- Step 2:Definition of the angle between two nonzero vectors of ; the bound is the Cauchy–Schwarz inequality.
- Step 3:Square the modulus of the real number above.
- Step 4:Equality in Cauchy–Schwarz holds exactly for linearly dependent vectors.
- Step 5:The kernel vanishes only for orthogonal data vectors, in contrast to basis encoding, where every pair of distinct inputs has kernel .
∎
Quick check
How many qubits does the amplitude encoding of a vector require?
The binary-tree state-preparation circuit#
The construction prepares one qubit at a time, from the most significant to the least significant. Qubit decides between the first and the second half of the index range, so it must receive the share of the norm that lies in each half. Qubit then splits each half into quarters, with a rotation that depends on the value of qubit , and so on. The bookkeeping is done with prefix sets.
Definition
Prefix sets and partial norms
Fix and a padded vector . For and a bit string (a prefix of length ; the empty prefix is written ) let be the set of indices whose first bits equal . For a prefix of length we write and , the indices whose bit is . The partial norm of is . Since is the disjoint union of and ,
Definition
Uniformly controlled rotation
Let , let , and let be real angles. The uniformly controlled rotation with control qubits and one target qubit is where runs over the computational basis of the controls (first control = most significant bit of ). It applies to the target whenever the controls are in state ; for it is the single rotation . It is unitary because it is block diagonal with unitary blocks.
Definition
Binary-tree angles and circuit
For a nonzero with non-negative entries, level and prefix define and when . The tree circuit is , where is the uniformly controlled with controls , target and angles , acting as the identity on qubits .
The binary-tree cascade prepares the amplitude encoding
Let be nonzero with non-negative entries, and let . Then for every and in particular .
Proof (8 steps)
- Step 1:Base case: no gate has acted, the only prefix of length is , and .
- Step 2:Induction step, assuming the claim for : by definition of the uniformly controlled rotation, applies to qubit when qubits are in .
- Step 3:First column of the matrix.
- Step 4:, where the sine is non-negative, and .
- Step 5:Multiply the amplitude of from the hypothesis by the amplitude of produced by the rotation; cancels.
- Step 6:A prefix with zero partial norm has zero amplitude, and both children have zero partial norm because with non-negative terms; the convention is therefore harmless.
- Step 7:Linearity of applied to the hypothesis; every prefix of length is uniquely of the form . This completes the induction.
- Step 8:At the prefixes are complete indices with , and because the entries are non-negative.
∎
Compiling uniformly controlled rotations#
Conjugation of rotations by X
For all real : , , and likewise , .
Proof (6 steps)
- Step 1:and commute, and for commuting matrices. The same argument with gives the identity.
- Step 2:Direct matrix multiplication.
- Step 3:Direct matrix multiplication.
- Step 4:Since , the exponential series gives ; conjugation by fixes () and flips ; cosine is even and sine is odd.
- Step 5:Same computation with .
- Step 6:Matrix check of the case: conjugation by swaps both the rows and the columns.
∎
Uniformly controlled R_Y with one control
Let , and . On a control qubit and a target qubit , the circuit on , then , then on , then implements The same holds with in place of .
Proof (6 steps)
- Step 1:The operator of a circuit is the product of its gates in reverse order; CNOT is written in block form with respect to the control.
- Step 2:Mixed-product rule; the cross terms vanish because .
- Step 3:Multiply on the right by .
- Step 4:Additivity of angles (lemma) and .
- Step 5:(lemma), additivity, and .
- Step 6:Substitute the two blocks. The version is identical because the lemma holds for as well.
∎
Definition
Gray code and the Walsh–Gray matrix
The binary-reflected Gray code of is (bitwise XOR). For : . Consecutive codes differ in exactly one bit, including the cyclic pair and , and is a bijection of . For bit strings write . The Walsh–Gray matrix is the matrix with rows indexed by control states (in binary) and columns by rotation slots .
Orthogonality of the Walsh–Gray matrix
. Consequently is invertible with , and the linear system has the unique solution .
Proof (6 steps)
- Step 1:Definition of the matrix product; the dot product modulo is linear in its second argument over .
- Step 2:The sum over factorises over the bits of because .
- Step 3:Each factor is if and if .
- Step 4:The Gray code is a bijection.
- Step 5:Combine the previous steps with .
- Step 6:For square matrices a left inverse is also a right inverse; multiply by .
∎
Gray-code compilation of a uniformly controlled rotation
Let , , and target angles . Put . For apply to the target, followed by a CNOT onto the target whose control is the control qubit of the unique bit in which and differ. This circuit of rotations and CNOTs equals .
Proof (9 steps)
- Step 1:has a single bit set; CNOT number is controlled by the qubit carrying that bit of , so it flips the target exactly when .
- Step 2:No gate changes the control qubits, so the circuit is block diagonal in the control basis; the target block is the ordered product of its gates.
- Step 3:Linearity of the dot product modulo ; , and we set for the cyclic last step.
- Step 4:, so for bits .
- Step 5:Substitute , which stands between and : the factor joins the bracket of and joins the bracket of . The two outermost factors are and .
- Step 6:Conjugation lemma for ; trivial for .
- Step 7:Additivity of rotation angles about a fixed axis and the definition .
- Step 8:Orthogonality lemma: as well, since .
- Step 9:Insert into the block form. Each slot contributes one rotation and one CNOT. For this reproduces , .
∎
The case k = 2: four rotations and four CNOTs
- Step 1:Gray codes and their cyclic differences; selects the second control , the first control .
- Step 2:Entry is ; for example meets and in one bit, giving the signs .
- Step 3:Distinct columns of are orthogonal and each has squared norm , as the lemma predicts.
- Step 4:The rows of are the columns of divided by .
- Step 5:The compiled circuit in time order: four rotations and four CNOTs.
- Step 6:Check for one control state: only the CNOTs controlled by flip the target. Summing the four with these signs cancels every angle except ; the states , , follow in the same way from the other rows of .
Result
Worked example: x = (1, 2, 3, 4)#
Tree angles of x = (1, 2, 3, 4)
- Step 1:, so and no padding is needed. Qubit separates from .
- Step 2:Level (empty prefix): .
- Step 3:Prefix : . An angle with has , hence .
- Step 4:Prefix : , so , .
- Step 5:and because both angles exceed ; the angle in with tangent is .
- Step 6:Subtraction formula for the tangent; the difference lies in , where inverts .
Result
State evolution through the five gates
- Step 1:and : the two halves carry the partial norms and .
- Step 2:Both branches are multiplied by .
- Step 3:The CNOT exchanges the amplitudes of and .
- Step 4:In the branch qubit has seen then , and .
- Step 5:and .
- Step 6:Multiply the branch weights and by the two branch states.
- Step 7:The second CNOT removes the in the branch . Without it the state stays .
Result
Circuit · 2 qubits
Amplitude encoding of : on qubit , then the uniformly controlled rotation , , , on qubit . The statevector is .
Quick check
For the uniform vector , what is the angle of the second slot on qubit ?
The TypeScript program below implements the complete construction for any real vector of length : it computes the tree angles level by level, applies the Gray-code transform, and runs the resulting and CNOT gates on the platform simulator. It encodes the example vector and the signed three-qubit vector treated in the next section.
import { Statevector } from '@/lib/quantum-simulator';
// Binary-tree amplitude encoding (qubit 0 = most significant bit, RY(t) = exp(-i t Y / 2)).
// Level s rotates qubit s by theta[p] for every prefix p of qubits 0..s-1 (a uniformly controlled RY),
// compiled into 2^s RY gates and 2^s CNOTs with the Gray-code angle transform a = 2^-s M^T theta.
const parity = (v) => {
let p = 0;
for (let m = v; m !== 0; m &= m - 1) p ^= 1;
return p;
};
const fmt = (v) => (Math.abs(v) < 1e-12 ? 0 : v).toFixed(10);
for (const x of [[1, 2, 3, 4], [0.5, -0.5, 0.5, 0.5, 0, 0, 0, 0.5]]) {
const n = Math.log2(x.length);
const sv = Statevector.zero(n);
let rotations = 0;
let cnots = 0;
console.log('x = (' + x.join(', ') + ')');
for (let s = 0; s < n; s++) {
const size = 2 ** (n - s);
const theta = [];
for (let p = 0; p < 2 ** s; p++) {
const lo = p * size;
const mid = lo + size / 2;
if (s === n - 1) {
theta.push(2 * Math.atan2(x[mid], x[lo])); // leaf level: the signed angle
} else {
let left = 0;
let total = 0;
for (let i = lo; i < lo + size; i++) {
total += x[i] * x[i];
if (i < mid) left += x[i] * x[i];
}
theta.push(total === 0 ? 0 : 2 * Math.acos(Math.sqrt(left / total)));
}
}
console.log(' level ' + s + ' angles: ' + theta.map(fmt).join(' '));
const d = theta.length;
for (let j = 0; j < d; j++) {
const g = j ^ (j >> 1);
let a = 0;
for (let c = 0; c < d; c++) a += (parity(c & g) ? -1 : 1) * theta[c];
sv.applyGate('RY', [s], [a / d]);
rotations++;
if (s > 0) {
const next = ((j + 1) % d) ^ (((j + 1) % d) >> 1);
sv.applyGate('X', [s], [], [s - 1 - Math.log2(g ^ next)]); // CNOT: control qubit, target s
cnots++;
}
}
}
const norm = Math.sqrt(x.reduce((acc, v) => acc + v * v, 0));
console.log(' gates: ' + rotations + ' RY + ' + cnots + ' CNOT');
console.log(' amplitudes * ||x||: ' + sv.amplitudes().map((z) => fmt(z.re * norm)).join(' '));
}Expected output
x = (1, 2, 3, 4) level 0 angles: 2.3005239830 level 1 angles: 2.2142974356 1.8545904360 gates: 3 RY + 2 CNOT amplitudes * ||x||: 1.0000000000 2.0000000000 3.0000000000 4.0000000000 x = (0.5, -0.5, 0.5, 0.5, 0, 0, 0, 0.5) level 0 angles: 0.9272952180 level 1 angles: 1.5707963268 3.1415926536 level 2 angles: -1.5707963268 1.5707963268 0.0000000000 3.1415926536 gates: 7 RY + 6 CNOT amplitudes * ||x||: 0.5000000000 -0.5000000000 0.5000000000 0.5000000000 0.0000000000 0.0000000000 0.0000000000 0.5000000000
The NumPy version builds the two-qubit circuit as explicit matrices, checks that the compiled rotation is block diagonal with blocks and , and confirms that the output is .
import numpy as np
def ry(t):
c, s = np.cos(t / 2), np.sin(t / 2)
return np.array([[c, -s], [s, c]])
I2 = np.eye(2)
CNOT01 = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])
x = np.array([1.0, 2.0, 3.0, 4.0])
theta0 = 2 * np.arccos(np.sqrt((x[0] ** 2 + x[1] ** 2) / np.sum(x ** 2)))
theta10 = 2 * np.arctan2(x[1], x[0])
theta11 = 2 * np.arctan2(x[3], x[2])
a, b = (theta10 + theta11) / 2, (theta10 - theta11) / 2
ucr = CNOT01 @ np.kron(I2, ry(b)) @ CNOT01 @ np.kron(I2, ry(a))
psi = ucr @ np.kron(ry(theta0), I2) @ np.array([1.0, 0.0, 0.0, 0.0])
print(f"theta0 = {theta0:.12f} a = {a:.12f} b = {b:.12f}")
print(np.allclose(ucr[:2, :2], ry(theta10)), np.allclose(ucr[2:, 2:], ry(theta11)), np.allclose(ucr[:2, 2:], 0))
print(np.round(psi * np.sqrt(30), 10))
print(np.allclose(psi, x / np.linalg.norm(x)))Expected output
theta0 = 2.300523983022 a = 2.034443935796 b = 0.179853499792 True True True [1. 2. 3. 4.] True
Signed and complex amplitudes#
The angles only produce non-negative amplitudes. Signs are obtained by changing the leaf level alone, because can rotate to any real unit vector. General complex amplitudes need an additional cascade of rotations.
Signed real amplitudes
Let be nonzero with entries of arbitrary sign. Use the angles of the tree definition for the levels , computed from the squares , and at the leaf level set where is the entry with index and . Then the tree circuit prepares exactly , signs included.
Proof (6 steps)
- Step 1:The levels use only the partial norms, which depend on the squares ; the induction of the tree theorem applies verbatim up to .
- Step 2:Definition of the two-argument arctangent: the polar angle of the point of the plane.
- Step 3:; cosine and sine carry the signs of the coordinates, unlike the arccos formula, which returns an angle in with non-negative sine of the half angle.
- Step 4:Apply the leaf rotation in the branch ; cancels.
- Step 5:The branch has amplitude and the target entries are , so any angle is correct.
- Step 6:Every index is uniquely with of length . For non-negative entries and , so the leaf rule agrees with the arccos rule.
∎
Signed example x = (0.5, −0.5, 0.5, 0.5, 0, 0, 0, 0.5)
- Step 1:Five entries of modulus ; the half holds four of them.
- Step 2:Level : gives .
- Step 3:Level : the prefix splits its norm equally between and ; the prefix has , so all of its norm goes to .
- Step 4:Leaf level with signs: the negative entry produces the negative angle .
- Step 5:Levels , , compile into uniformly controlled rotations with , , controls.
Result
Circuit · 3 qubits
Tree circuit of the signed vector : one rotation on qubit , a one-control rotation on qubit (two , two CNOTs) and a two-control rotation on qubit (four , four CNOTs). The statevector is .
Definition
Mean phase of a prefix
Let have entries with and ( arbitrary when ). For a prefix of length the mean phase is so and is the mean of all phases. The phase angles are for and .
The R_Z phase cascade
Prepare the magnitudes with the tree, then apply for the uniformly controlled with controls , target and angles . The result is the amplitude encoding of up to the global phase . The cascades are diagonal and commute with each other.
Proof (6 steps)
- Step 1:Each block is diagonal and the projectors are diagonal in the computational basis. Diagonal matrices commute, so the order of the levels is irrelevant.
- Step 2:The control state is the prefix of , and multiplies by and by .
- Step 3:is the disjoint union of and , which have equal size : the mean over a prefix is the average of the means of its two children.
- Step 4:Insert and the averaging identity.
- Step 5:The total phase of is the sum over the levels; the sum telescopes.
- Step 6:and . The common factor is a global phase, which no measurement can detect.
∎
Quick check
A leaf pair has entries . What leaf angle (in radians) does the signed construction use?
Resource count, lower bound and the input problem#
Gate count of the tree construction
For real amplitudes the tree circuit uses rotations and CNOTs. For complex amplitudes the cascade doubles both numbers, to rotations and CNOTs. Hence state preparation costs gates, and the depth is also because consecutive gates of a level share the target qubit.
Proof (5 steps)
- Step 1:Compilation theorem for ; the level is a single uncontrolled rotation.
- Step 2:Geometric series.
- Step 3:The same series without the term .
- Step 4:The phase cascade has the same level structure as the magnitude cascade.
- Step 5:. Every gate of level acts on qubit , so these rotations run one after another and the depth is as well.
∎
Parameter-counting lower bound
Let , , and let be the set of -qubit states (modulo global phase) that can be prepared exactly from by circuits with at most CNOT gates and arbitrarily many one-qubit gates. If , then has measure zero in the state space. Consequently almost every -qubit state requires CNOTs, and for this is at least , i.e. . The measure-zero step uses Sard's theorem (cited, not proved here).
Proof (11 steps)
- Step 1:States modulo normalisation and global phase form the complex projective space , a smooth manifold of real dimension : the unit sphere removes one real parameter and the phase another.
- Step 2:A layout is the ordered list of CNOT (control, target) pairs; between the CNOTs only one-qubit gates occur.
- Step 3:All one-qubit gates on a wire between two consecutive CNOTs touching that wire multiply to one element of . Each wire starts with one such segment, and each CNOT ends one segment on each of its two wires and starts two new ones.
- Step 4:is diffeomorphic to the unit sphere of quaternions. The phases of all slots multiply to one global phase of the output state, which is invisible in .
- Step 5:The entries of are polynomials in the entries of the , the output is never the zero vector, and the projection to is smooth on nonzero vectors, so is smooth.
- Step 6:The rank of the differential is bounded by the dimension of the domain. Under the hypothesis every point of the domain is critical.
- Step 7:Sard's theorem: the set of critical values of a smooth map between manifolds has measure zero. Here every value is critical, so the whole image is a null set.
- Step 8:Every circuit with at most CNOTs has some layout, and each CNOT has ordered (control, target) choices.
- Step 9:A finite union of null sets is a null set.
- Step 10:If a generic state could be prepared with CNOTs violating the inequality, it would lie in the null set . Solving the inequality for gives the bound.
- Step 11:, and the left side doubles while the right side grows by per step. Hence .
∎
Lower bound versus construction
- Step 1:Round the bound up to an integer.
- Step 2:The bound and the construction both grow like .
- Step 3:For large the ratio of the construction to the bound tends to .
- Step 4:The corollary improves the constant: the ratio of the complex construction to tends to , and for real vectors the CNOTs of the tree are within a factor of the bound.
Result
Quick check
How many CNOTs does the tree construction use to amplitude-encode a real vector with entries?
Quick check
A quantum algorithm processes for a generic in time . What is the end-to-end cost when is given as a classical list and loaded with a gate-based state-preparation circuit?
Summary. Amplitude encoding stores numbers in qubits, and its fidelity kernel varies smoothly with the data. Preparing the state costs gates for generic inputs: the binary tree of uniformly controlled rotations achieves , and parameter counting shows that CNOTs are necessary. The next lesson, Angle & Phase Encoding, uses one rotation per feature. It needs more qubits, but only one layer of gates, and its kernel has a product form.
References
- M. Möttönen, J. J. Vartiainen, V. Bergholm and M. M. Salomaa, Transformation of quantum states using uniformly controlled rotations, Quantum Information and Computation 5, 467–473 (2005).arxiv.org
- L. Grover and T. Rudolph, Creating superpositions that correspond to efficiently integrable probability distributions (2002).arxiv.org
- V. V. Shende, S. S. Bullock and I. L. Markov, Synthesis of quantum-logic circuits, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 25, 1000–1010 (2006).doi:10.1109/TCAD.2005.855930
- M. Plesch and Č. Brukner, Quantum-state preparation with universal gate decompositions, Physical Review A 83, 032302 (2011).doi:10.1103/PhysRevA.83.032302
- M. Schuld and F. Petruccione, Machine Learning with Quantum Computers, 2nd ed., Springer (2021), Ch. 4 "Representing Data on a Quantum Computer" (amplitude encoding and state preparation).doi:10.1007/978-3-030-83098-4
- S. Aaronson, Read the fine print, Nature Physics 11, 291–293 (2015).doi:10.1038/nphys3272
- V. Giovannetti, S. Lloyd and L. Maccone, Quantum random access memory, Physical Review Letters 100, 160501 (2008).doi:10.1103/PhysRevLett.100.160501
- A. Sard, The measure of the critical values of differentiable maps, Bulletin of the American Mathematical Society 48, 883–890 (1942).doi:10.1090/S0002-9904-1942-07811-6
Hands-on labs
Amplitude-encode the vector (1, 2, 3, 4)
1 step · auto-gradedOpen labPrepare the amplitude encoding of on two qubits with at most five gates from : one rotation for the split on qubit and a uniformly controlled on qubit , compiled into two rotations and two CNOTs.