πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
NEWSLIVESearch All Content
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

Quantum NLP

Quantum ComputingQuantum NLP🟒 Free Lesson

Why Grammar Maps to Circuits

Quantum natural language processing (QNLP) rests on a structural observation rather than a performance claim: a sentence parse is a network of typed wires, and a quantum circuit is a network of typed wires. Where a classical pipeline processes language in stages β€” tokenize, embed, attend, classify β€” DisCoCat folds the grammar and the meaning into one object that can be executed as a single circuit.

Three pieces make up the pipeline:

  1. Words become linear maps between spaces, one per grammatical type
  2. Grammar becomes a string diagram: nouns attach to verbs with cups, adjectives compose with wires
  3. Meaning becomes a vector or a quantum state in the resulting sentence space

The payoff is compositional structure: the meaning of "Alice loves Bob" is built from the meanings of its parts by the shape of its parse, so word order and argument structure are enforced by the wiring rather than learned from data. The cost is that the diagram must be compiled down to gates on a device whose connectivity rarely matches the diagram's topology.

Pregroup Grammars and String Diagrams

The grammar formalism behind DisCoCat is Lambek's pregroup, chosen because its reduction rules translate directly into cup and cap tensors. Every word gets a type: a noun phrase is , a sentence is , and the verb "loves" has type .

Reduction uses exactly two rules on adjacent types: collapses and collapses. In "Alice loves Bob" the sequence therefore loses its first pair to and its second to , leaving a bare . Read off the structure while doing it: the leading is consumed by the noun immediately before the verb, which is the subject, and the trailing by the noun after it, which is the object. Each cancellation is a cup β€” a tensor that pairs a space with its dual β€” and the compiled diagram is three wires with two cups closing two of them.

That contraction is the source of the method's efficiency. The cups sum over the paired indices, so a phrase that would occupy a product space collapses into the sentence space . In tensor-network terms the parse is the contraction pattern, and its treewidth sets the number of qubits needed: a subject-object-verb triangle contracts with no intermediate blow-up, while a heavily nested relative clause raises the peak intermediate dimension.

ℹ️Wire bending is free in principle

Cups and caps let a diagram be rewritten without changing its meaning β€” a noun can be moved across a verb by bending its wire. On hardware this freedom is not free: every bend becomes a SWAP network on a device with fixed coupling.

Quantum Word Embeddings

A word meaning is a vector in a concept space:

with concept basis states . For example:

Storing that as qubits gives amplitudes: 10 qubits address 1024 concepts, which is the scale at which a quantum embedding starts to rival a classical 1024-dimensional vector while offering something the classical one lacks β€” the ability to hold phases. Two senses of "bank" can be written as and with a relative phase, and a superposition carries context as interference rather than as a summed probability. Measuring in a different basis recovers a different reading of the same stored word.

Three properties follow. Polysemy: distinct senses coexist in superposition rather than being averaged. Context dependence: the effective meaning changes with the basis the sentence forces. Compositionality: multi-word expressions are tensor products or contracted maps, not concatenations of vectors.

Circuit Models for Sentences

A QNLP circuit has three layers, and the middle one is where the linguistic content lives:

  1. Encoding layer: classical features β€” one-hot, frequency, pre-trained vector β€” rotated into amplitudes with and gates
  2. Interaction layer: entanglement gates placed where the parse places cups, so the circuit topology mirrors the grammar
  3. Measurement layer: expectation values of observables on the sentence wire, read out as class features

The mapping is literal: one qubit per word wire, one two-qubit gate per cup, and the circuit depth grows with the nesting depth of the clause rather than with the sentence length. A flat three-word sentence compiles shallow; a sentence with two nested relative clauses compiles to a much deeper circuit on the same word count.

Real demonstrations sit between 8 and 30 qubits, run on statevector simulators or on small hardware backends, and classify short sentences into two or three classes. That scale is worth stating plainly, because it is where the honest boundary of the field currently sits.

The resource picture follows directly from the parse, and it is cheap to compute before any circuit is built:

python
# Each cup is one adjoint pair cancelled during reduction, and compiles to a
# two-qubit gate; one rotation layer sits on every wire.
PATTERNS = {
    "intransitive":    {"words": 3, "cups": 1},   # John sleeps
    "transitive":      {"words": 3, "cups": 2},   # Alice loves Bob
    "ditransitive":    {"words": 4, "cups": 3},   # Kim gives Lee the book
    "with adjective":  {"words": 4, "cups": 3},
    "relative clause": {"words": 6, "cups": 5},
    "nested relative": {"words": 8, "cups": 9},
}

def compile_size(name, shots=1000, params_per_wire=4):
    p = PATTERNS[name]
    wires, cups = p["words"], p["cups"]
    params = wires * params_per_wire
    depth = cups + wires
    shots_per_step = 2 * params * shots      # parameter-shift: two runs per parameter
    return wires, cups, depth, params, shots_per_step

print(f"{'pattern':<18} {'wires':>6} {'cups':>5} {'depth':>6} "
      f"{'params':>7} {'shots/step':>11}")
for name in PATTERNS:
    w, c, d, pr, s = compile_size(name)
    print(f"{name:<18} {w:>6} {c:>5} {d:>6} {pr:>7} {s:>11,}")

The last column is the number that decides feasibility. A transitive sentence costs 24,000 circuit executions per gradient step at 1000 shots, and the nested relative clause costs 64,000 β€” before any restarts, any validation pass, or any noise-mitigation overhead. Datasets are therefore batched by parse shape so that circuits can be reused across sentences, and sentences are truncated or simplified not because the grammar cannot express them but because the shot budget cannot.

Training QNLP Models

The loop is the standard hybrid one:

  1. Parse each sentence and compile the diagram to a parameterised circuit
  2. Run the circuit and read out measurement expectations
  3. Compute a classical loss against the labels
  4. Update the rotation parameters with parameter-shift gradients

The QNLP-specific complications are structural. Circuit count: every distinct parse is a distinct circuit, so a dataset of 5000 sentences may compile to 5000 circuits that differ only in wire layout β€” batching means grouping by parse shape. Barren plateaus: rotation layers applied to every wire push the effective qubit count up quickly, and gradient variance falls as , so the number of wires you can train is bounded by the shot budget rather than by the dataset. Parameter sharing: tying the encoder parameters across words β€” so "cat" and "dog" use the same rotation angles offset by their feature vector β€” cuts the parameter count by the vocabulary size and is effectively mandatory at these scales.

Evaluation has to test composition, not just accuracy. A model that memorises label correlations fails the diagnostic that matters: hold out entire verb–noun pairings seen in training and test whether the circuit composes them correctly from the parts it has seen.

Python: Embedding and Composition

Embedding words and composing a sentence two different ways, so the structural difference is a number rather than a claim:

python
import numpy as np

def _seed(word):
    """Stable seed from the word's bytes β€” Python's hash() is salted per process."""
    return int.from_bytes(word.encode("utf-8"), "little") % (2 ** 32)

def embed(word, dim=8):
    rng = np.random.default_rng(_seed(word))
    v = rng.normal(size=dim) + 1j * rng.normal(size=dim)
    return v / np.linalg.norm(v)

def flat_compose(sentence, dim=8):
    """Concatenate meanings: the sentence lives in dim ** len(sentence) dimensions."""
    vec = embed(sentence[0], dim=dim)
    for word in sentence[1:]:
        vec = np.kron(vec, embed(word, dim=dim))
    return vec / np.linalg.norm(vec)

def contracted_compose(subject, verb_obj, obj, dim=8):
    """Grammar-guided contraction: the verb is a map between noun spaces."""
    s, o = embed(subject, dim=dim), embed(obj, dim=dim)
    rng = np.random.default_rng(_seed(verb_obj))
    V = rng.normal(size=(dim, dim)) + 1j * rng.normal(size=(dim, dim))
    sentence = V @ o                        # object drives the verb, result a noun
    overlap = float(np.real(np.vdot(s, sentence)))
    return sentence / np.linalg.norm(sentence), overlap

flat = flat_compose(["Alice", "loves", "Bob"], dim=8)
ab, sim_ab = contracted_compose("Alice", "loves", "Bob", dim=8)
ba, sim_ba = contracted_compose("Bob", "loves", "Alice", dim=8)

print(f"flat representation:        {flat.shape[0]} amplitudes")
print(f"contracted representation:  {ab.shape[0]} amplitudes")
print(f"alice-loves-bob overlap:    {sim_ab:.4f}")
print(f"bob-loves-alice overlap:    {sim_ba:.4f}")
print(f"order sensitivity (cosine): {float(np.real(np.vdot(ab, ba))):.4f}")

The shape comparison is the point: at dimension 8 and sentence length 3, the flat encoding needs amplitudes while the contracted one needs 8. The gap widens exponentially with sentence length, which is the concrete form of the claim that grammatical structure saves resources β€” and it is also why the compilation step, not the embedding step, is where QNLP research effort now goes.

What QNLP Can and Cannot Do

An honest capability table, since the gap between demonstration and deployment is where most confusion lives:

TaskCurrent QNLP statusClassical baseline
Binary sentiment on short sentencesdemonstrated at 8–30 qubitsmature, near-ceiling accuracy
Compositional generalisationsmall controlled studiesstrong with the right architecture
Long-document understandingnot attemptedstandard practice
Semantic similarity retrievalproof of conceptdense vectors, millions of scale
Grammar-constrained generationdiagram-level onlyLLMs dominate

The defensible near-term case is not accuracy but structure: DisCoCat gives a principled, executable account of compositionality that classical embeddings approximate with attention. Whether that account pays off on a device large enough to matter is an open hardware question, not a modelling one.

Common Mistakes

Assuming a QNLP accuracy number is evidence of quantum advantage

Fix: Quote the dataset size, qubit count and the classical baseline in the same table β€” most demonstrations sit under 30 qubits on binary classification where classical models are near ceiling

Deriving word seeds with hash() in Python

Fix: hash() on a string is salted per process, so embeddings change between runs; seed an explicit generator from a stable value instead

Flattening a sentence with Kronecker products and then blaming the qubit count on the hardware

Fix: Contract along the parse: the verb should act as a map between noun spaces, which keeps the representation at the concept dimension instead of raising it to the power of sentence length

Evaluating only on random train/test splits

Fix: Hold out verb-noun pairings seen individually in training; a model that composes correctly from known parts is the property DisCoCat claims to provide

Key Takeaways

  • DisCoCat turns a pregroup parse into a string diagram where each grammatical reduction becomes a cup, so word order and argument structure are enforced by wiring rather than learned from data
  • Circuit depth follows clause nesting rather than sentence length, because each cup compiles to a two-qubit gate and each nested relative clause raises the peak intermediate dimension
  • Contracting along the parse keeps a sentence at the concept dimension while flat Kronecker composition grows as dimension to the power of sentence length β€” 8 amplitudes against 512 for three words at dimension 8
  • Current demonstrations sit between 8 and 30 qubits on small classification tasks; the honest claim is structural compositionality, not accuracy superiority over classical embeddings
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-15

β€”
β˜†β˜†β˜†β˜†β˜†
0 ratings

Rate & Feedback

Need Expert Quantum Computing Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement