Knapsack
Source: examples/knapsack/README.md
The 0/1 Knapsack problem: given N items with integer weights and values, select a subset maximising total value subject to a weight capacity constraint.
QUBO formulation
- Input: N item weights and values, capacity W
- Model: N binary variables.
x_i = 1means item i is selected. - Objective: minimise
-sum(v_i * x_i) - Constraints: capacity
sum(w_i * x_i) <= W(SLACK + EQUALITY)
The inequality is encoded via SLACK + EQUALITY. SLACK appends binary slack
variable entries (s_j with coefficients 2^j) to the index and coefficient
vectors, converting the inequality to the equality sum(w_i*x_i) + sum(s_j*2^j) = W.
EQUALITY then adds the penalty term P*(sum(a_k*x_k) - W)^2 to the QUBO.
DSL methods used
problem.vec()– allocate untyped vector registers for indices and coefficientsproblem.slack(indices, coeffs, start_index, capacity)– append slack entriesmodel.apply_equality(indices, coeffs, target, penalty)– EQUALITY constraint
Pipeline overview
- CP (
xqcp) – generate random item weights and values, declare binary variables, and encode the capacity inequality via SLACK + EQUALITY. - Assemble –
.xqasmtext to bytecode viaxquad.asm - Encode – run encoder on chosen XQVM to produce the XQMX model
- Sample – solver runs SA/QPU/GPU over the model
- Verify – verifier checks capacity constraint and computes energy
- Decode – decoder extracts the item selection
Usage
uv run python examples/knapsack/runner.py --seed 42
uv run python examples/knapsack/runner.py --n 6 --interpreter rust
| Flag | Default | Description |
|---|---|---|
--n | 5 | Number of items |
--solver | dwave-cpu | Solver backend (see Choosing a solver) |
--interpreter | python | XQVM backend: python or rust |
--seed | 42 | Random seed |
-o | stdout | Write JSON result to file |
Choosing a solver
| Name | Hardware | Install |
|---|---|---|
dwave-cpu | CPU (default) | pip install xquad |
dwave-qpu | D-Wave Leap account | pip install xquad[dwave] |
cuda-gpu | NVIDIA CUDA GPU | pip install xquad[cuda] |
metal-gpu | Apple Silicon (macOS) | pip install xquad[metal] |
See GPU/QPU installation for driver prerequisites and xqsa solver quick-starts for per-solver parameter tuning.
Non-default solvers will not reproduce the canonical output (different
RNG/hardware). example-smoke always runs dwave-cpu.
The canonical output and its invariants are defined in the source README.