Manuscript Offprint
arXiv:2610.26803A simplified proof of the FPRAS for counting perfect matchings
Abstract
We give a simplified, self-contained proof of OpenAI's FPRAS for counting perfect matchings in general graphs. As in the original proof, we use a restricted Poincaré inequality for two matchings to sample weighted perfect matchings and estimate their total weight. We simplify the proof of this inequality by isolating parts of alternating cycles directly on the original vertex set and controlling the resulting error terms. This avoids the auxiliary vertices and tree constructions used in the original proof. The argument preserves the required parameter bounds and yields the same FPRAS guarantee.
1 Introduction
A perfect matching of a graph is a set of edges that covers every vertex exactly once. Finding one and counting all of them have very different complexity. Edmonds [7] gave a polynomial-time algorithm for maximum matching in general graphs, whereas Valiant [16] proved that counting perfect matchings is #P-complete even in bipartite graphs. In the bipartite case, the count is the permanent of the bipartite adjacency matrix. Planar graphs admit polynomial-time exact counting through Kasteleyn's Pfaffian method [12]. For unrestricted graphs, can the count be approximated to prescribed relative error in randomized polynomial time?
Approximate counting is closely tied to almost-uniform sampling through the reductions of Jerrum, Valiant, and Vazirani [11] for self-reducible counting problems. Jerrum and Sinclair [9] gave a fully polynomial randomized approximation scheme (FPRAS) for counting all matchings in an arbitrary graph, summed over all cardinalities. For counting perfect matchings, their method also allows near-perfect matchings, which leave exactly two vertices unmatched. Its guarantee requires a polynomial bound on the ratio of near-perfect to perfect matchings. Otherwise, rejection from the enlarged state space may succeed with exponentially small probability. Jerrum, Sinclair, and Vigoda [10] removed this restriction for bipartite graphs, obtaining an FPRAS for the permanent of every nonnegative matrix. They reweighted the near-perfect classes according to their unmatched vertices and learned these weights during annealing. Bezáková, Štefankovič, Vazirani, and Vigoda [2] subsequently improved the cooling schedule and mixing analysis.
The extension to general graphs encounters concrete obstructions. Štefankovič, Vigoda, and Wilmes [15, full version, Theorem 2.2] constructed graphs on which every chain with the transitions in [10] and weights depending only on the unmatched vertices either mixes exponentially slowly or assigns exponentially small stationary mass to perfect matchings. Reweighting these classes alone therefore cannot repair the chain. Blossoms, the odd-cycle structures used in Edmonds' algorithm, do not give an immediate remedy: uniformly sampling all blossoms through a specified unmatched vertex is intractable unless NP = RP, while restricting to minimum blossoms leaves the bottleneck [15, full version, Section 3]. Their recursion based on the Gallai–Edmonds decomposition handles further structured cases and the slow-mixing examples, but can take exponential time in general [15, full version, Section 4].
Restricting the state space to perfect matchings raises a different difficulty. Two-edge switches are not even irreducible on a chordless even cycle of length at least six. On quasimonotone graphs, Dyer and Müller [5] proved rapid mixing of the two-edge switch chain, but they also exhibited exponentially slow mixing on examples in a larger hereditary class. A sampler based on two-edge switches therefore needs both a connectivity argument and a mixing bound.
Other approaches obtain approximation guarantees under additional assumptions on the graph or its edge weights. When a graph is regular and has sufficiently strong expansion, Ebrahimnejad, Nagda, and Oveis Gharan [6] bound the ratio of near-perfect to perfect matchings. When its degree is also bounded, this yields a polynomial-time sampler. Analytic methods provide a different route through hafnians, the weighted perfect-matching sums for general graphs. When all off-diagonal entries lie in for fixed , Barvinok [1] gives deterministic quasipolynomial-time relative approximation. When the support has minimum degree at least and nonzero weights lie in , with fixed and , Yi [17] gives a deterministic fully polynomial-time approximation scheme. An FPRAS for general graphs must also handle arbitrary sparse graphs without any expansion assumption.
Mixing analyses also developed beyond the original matching chains. Sinclair’s multicommodity-flow bounds [14] relate mixing to the load placed on chain transitions. In the bipartite setting, recent improvements for the permanent use restricted Poincaré inequalities and energy-based flows [4, 3]. For arbitrary graphs, OpenAI’s September 2026 manuscript [13] obtains an FPRAS for counting perfect matchings by combining a two-matching energy comparison with replication, completion, and marked-edge estimators. We give a simplified proof of their result, including its worst-case bit guarantee.
Theorem 1.1 (OpenAI [13]). There is a randomized algorithm which, given a finite simple graph G and rational , returns a nonnegative rational such that
where is the number of perfect matchings of . Its worst-case bit running time and number of fair random bits are polynomial in the total input length, , and .
The simplification concerns the comparison argument in Sections 4–6 of [13]. We carry it out directly on the original vertex set and retain OpenAI's framework for converting the comparison into sampling and counting algorithms. We give the required arguments below.
To describe this framework, let n be even and assign each edge e of the complete graph a positive weight , also called its activity. A perfect matching has weight equal to the product of its edge weights. Its sampling probability is proportional to this product:
where M ranges over perfect matchings and , the total weight, is the partition function. The counting algorithm starts with every edge weight equal to one. The initial total weight can then be computed directly. The algorithm gradually lowers the weights of edges absent from G, keeping the weights of graph edges equal to one. This procedure is called annealing. At the end, the total weight differs from by the small contribution of matchings using nonedges. Each successive ratio of total weights is estimated by averaging the multiplicative changes in matching weights over samples from the current distribution. Multiplying the estimated ratios by the known initial total weight gives the final estimate. The main algorithmic task is therefore to sample the weighted matching distributions along this sequence.
Sampling must remain efficient even when edge weights differ greatly. OpenAI's completion [13, proof of Theorem 3.1] uses the following hierarchy. Keep only edges above a chosen weight threshold. As the threshold decreases, connected components merge into larger groups, forming a hierarchy. OpenAI use these connection thresholds to assign auxiliary weights to vertex pairs. Adding these to the original weights gives completed weights that are within a polynomial factor of hierarchical reference weights. They also show how to apply this completion while increasing the total matching weight by at most a constant factor.
For a distribution with this structure, consider two independent matchings . Their differing edges form disjoint even cycles, with edges alternating between the two matchings.
The comparison uses two operations: a two-edge switch replaces two edges in by another pairing of their endpoints, and a cycle exchange swaps the alternating patterns of and on an entire cycle. These operations are combined into a reversible random update. For a numerical quantity on matchings, we compare its overall fluctuation, measured by variance, with its mean squared change in one update. The restricted Poincaré inequality in Theorem 2.1 provides the comparison needed for the sampling construction. Its constant depends polynomially only on the number of vertices and the largest ratio of an edge weight to its corresponding reference weight, even when the reference weights differ greatly.
To prove Theorem 2.1, we first reduce the variance bound to controlling changes in the chosen quantity under cycle exchanges. We call these changes cycle gains. We view each cycle as a polygon and divide it along the weight hierarchy. Adapting OpenAI's identity [13, Lemma 6.3], we express its gain through changes under two-edge switches and gains on smaller cycles, with errors from different exterior matchings. OpenAI's proof introduces auxiliary vertices for this decomposition. We instead isolate each smaller region directly from the original matching pair by one two-edge switch, so that a cycle exchange can act on it alone. The resulting weight loss has the same bound at every depth, and the construction uses only the original vertices.
We apply the same gain identity to each smaller cycle. Its gain appears in the larger cycle's expansion and on the left-hand side of its own identity. Direct isolation can change the exterior matching and hence the gain. Combining the identities leaves the difference between the two gains as an error. Subtracting the same mean from both gains expresses this error as a difference of centered gains. Cycle exchanges control these errors after summing over matching pairs. This adapts OpenAI's use of centering to control exterior errors [13, Section 6.4].
The expansion contains two-edge switch gains and centered gains controlled by cycle exchanges. Summing either type requires bounds on repeated contributions from different matching pairs. Adapting OpenAI's encoding [13, Lemma 6.4], we encode each contribution by an ordered matching pair for weight comparison and an auxiliary record. These data recover the original pair and the chosen expansion term. Since the record takes polynomially many values, only polynomially many contributions can give the same output pair. Comparing input and output weights then bounds their total probability mass. For a centered gain, the output pair contains the two alternating patterns on its cycle, allowing cycle exchanges to control the errors after summation. Finally, Cauchy–Schwarz bounds the square of the full gain expansion by a polynomial factor times the sum of squared terms. These estimates prove Theorem 2.1.
OpenAI’s replication construction uses joint matching updates to turn the comparison into a polynomial-time approximate sampler for the completed weights. To relate these samples to the weights before completion, OpenAI mark sampled edges as real or virtual, distinguishing original and auxiliary weight contributions. The marked samples estimate the successive total-weight ratios used in annealing, completing the counting algorithm [13, Section 8.2].
We begin in Section 2 by proving the comparison under the hierarchical weight assumption. Section 3 uses it to construct a sampler. Section 4 gives the completion and controls its increase in total matching weight, then applies the sampler to obtain marked matchings. Section 5 combines these ingredients to prove Theorem 1.1. Appendix A supplies a finite-precision implementation with worst-case polynomial bounds on bit running time and random-bit use.
Throughout, log denotes the natural logarithm. Let be the set of perfect matchings of for even , and the law in (1.1) for positive activities . Take independent . Their differing edges form vertex-disjoint alternating even cycles, called discrepancy cycles. Each has at least four vertices, so there are at most .
We formalize the hierarchical reference weights as a positive ultrametric similarity on : for distinct . If , then . Edges with form disjoint cliques merging as decreases. Here means for all .
Define a Markov chain on with transition kernel . With probabilities each, propose a two-edge switch in , hold, or propose a cycle exchange on a uniformly chosen discrepancy cycle of . A two-edge switch chooses two distinct edges of uniformly and either alternative pairing with probability . Accept the proposed matching with Metropolis probability , and otherwise hold. Cycle exchanges are always accepted because they preserve the product of the two matching weights, and hence . If no discrepancy cycle exists, the cycle exchange branch holds. The proposals are symmetric, so is reversible with stationary law .
For a reversible kernel P with stationary law and a real function F on its state space, define
This is half the expected squared change in after one step at stationarity. Write .
The following theorem plays the role of OpenAI's pair energy inequality [13, Theorem 6.1]. Our proof uses direct isolation on the original vertex set, avoiding the edge subdivision and colored tree-bag analysis in OpenAI's proof.
Theorem 2.1. Suppose , where and is a positive ultrametric similarity. Then, for all ,
Changes in may offset changes in during cycle exchanges. The theorem still bounds by the total energy for every , with a constant polynomial only in and . This form is used in the sampling construction of Section 3.
We first bound the variance by the expected sum of squared changes in f under cycle exchanges. We then bound this sum by the energies of two-edge switches and cycle exchanges.
2.1 Cycle gains and cycle exchange energy
A cycle exchange can have different gains for different matchings outside the cycle. For each geometric even cycle of (a simple cycle viewed as an edge set), label its two alternating edge sets . Let be the matching law with activities on the vertices outside , with weight one for the empty matching. For a perfect matching on these vertices, define
(2.1)
Here measures variation of the gain with the exterior matching, and is the probability that and . The factor two in accounts for the reverse assignment. Unrestricted sums over count each geometric even cycle once.
Write for the pair obtained by a cycle exchange on a discrepancy cycle of . The expected sum of squared gains satisfies
For the inequality, condition on the multiset union , counting common edges twice. Given , the assignments of the two alternating patterns on each discrepancy cycle to are independent fair bits, since every assignment preserves . The conditional laws of and agree. Bounding the squared difference by twice the sum of the centered squares therefore gives a factor of 4. For each bit with the others fixed, the conditional variance of is one quarter of its squared change. Variance tensorization cancels these factors, giving
Averaging gives the inequality in (2.2).
For the equality, condition on , , an event of probability . The remainders and are independent with law , since the fixed pattern weights cancel upon conditioning. The reverse assignment contributes equally.
Let be the two-edge switch proposal probability, including the factor 1/3. Put and . The energies of two-edge switches and cycle exchanges are respectively and :
(2.3)
Here k is the number of discrepancy cycles, and the last integrand is zero when k = 0.
Condition again on , . Define by replacing with in (2.1). Then , and independence of gives
The reverse assignment gives the same bound. Summing over cycles and using yields
By Equations (2.2) to (2.4), it remains to bound by a polynomial in times . We do this by dissecting each discrepancy cycle and comparing gains on its smaller parts.
2.2 A hierarchy and independent isolation
To bound , we first organize each discrepancy cycle into intervals that can be isolated with a uniform weight loss. Fix a source indexing a summand of , with mass . Choose a minimum- edge of as its closing edge and number the complementary path , where . Resolve ties and direction by vertex labels. All intervals below follow this path. We may take in (2.1).
To make the hierarchy follow the path, define symmetric weights on by
These weights form an ultrametric similarity on satisfying , with equality on the edges of . Equality on the closing edge follows because a cycle cannot have a unique minimum edge weight under an ultrametric similarity. The components of the graph on with edges satisfying are its threshold clusters. These intervals form an inclusion tree with root , singleton leaves, and maximal proper subclusters as children. Each nonsingleton node has height , where is the set of two-element subsets of . In this tree, heights strictly increase towards nonsingleton children.
Form a binary tree T by merging the first two children, then their union with each remaining child in path order. The inserted unions, called intermediate nodes, inherit the original parent's height and remain nested with or disjoint from threshold clusters. Write for a nonroot node's parent.
For perfect matchings on , let be the total number of their edges inside , with multiplicity. We have for the smallest node containing . Successive log-height differences along its path from the root telescope to . Summing over the edge occurrences by node gives, by (1.1),
The coefficients are nonnegative and zero at intermediate nodes.
Closing an interval of even size gives two alternating matchings on :
Starting at the root, the recursion selects even nodes of T of size at least four as basins.
Isolate each basin directly from , placing the matching containing first by interchanging the two whole matchings if necessary. For proper , let , on the original -circle. Reconnect the second matching's two edges crossing by the two-edge switch
Edge-set sums denote multiset unions. For the root, do nothing. The resulting pair and the pair after a cycle exchange on E are
where , are perfect matchings on , which may differ.
The two-edge switch in (2.5) cannot decrease the number of edges inside any threshold cluster . If or , neither removed edge lies inside . If , the change is . The tree and heights are unchanged, so the product formula above shows that this switch cannot decrease the product of the two matching weights on under . Write , with . The unchanged weights outside cancel. Since on the discrepancy cycle and on added chords, the -weight product cannot decrease. The removed factors satisfy , while the new factors satisfy . Hence
also after a cycle exchange on E. Every isolation starts from the original pair, so the factor does not accumulate with depth.
2.3 Cell identities and centering
We bound by cell identities, basin dissections, and centering to reconcile exterior matchings.
Fix a basin . Here denotes the arc from to along the directed -boundary . A quadrilateral with cyclically ordered corners is called a cell. For the local identity, assume the corners have alternating index parities. The four intervening boundary paths are then odd arcs, with odd numbers of edges and even numbers of vertices. Put and , and assume at least one arc is short, meaning it has one edge. For an odd arc , define

Figure 1: Patterns on an odd arc. match all its vertices, whereas matches only its interior.
match all arc vertices and only the interior. Short arcs have (Figure 1).
For any basin or odd arc X and a matching U on its complementary vertices, write . For the fixed basin E, take an exterior matching R and set , . An arc J is through in when . A pair is through when both arcs are. Since the four arcs are odd, their first edges alternate between and . Thus G is through in one of , and H in the other. For a through arc, put .
Set . For , put
Each is a perfect matching. Starting from , in which is through, replace by and then by to obtain and . On a nonshort arc, this is a cycle exchange along the arc and its endpoint chord.
Writing for the matching on the four arc interiors, define
Here , and differ by a two-edge switch. Exchanging Y changes the exterior seen by the subsequent exchange on X. The change in the X gain is
Thus exchanging both arcs has gain . The corresponding error is zero because has a short arc. Also if either arc is short. Put when is through in , and use its negative when is through in . Comparing the exchanges on and gives the signed cell identity of [13, Lemma 6.3]
The sums range over the four arcs of this cell.
We now use to select such cells, leaving even subpolygons as polygon holes for recursion. A basin may yield several cells. The children of have the same parity. If both are even, say and , select cell , leaving both children as polygon holes. For odd children , split along the chord joining their last vertices into and . For an odd interval , denotes the polygon with cyclic vertex order , where immediately precedes on the -boundary. A singleton gives an edge. For , the children of in split into a cell, a polygon hole on the even child, and a smaller even polygon on the odd child plus one vertex:
-
odd, even, : select and continue with .
-
even, odd, : select and continue with .
Every new chord closes an even interval or joins a to the last vertex of O in a polygon . Its endpoints therefore have opposite index parities. Thus each cell has alternating corner parities, and G has a short arc in every case, as required for (2.9). The ordering places X on the even child for the weight comparisons in Section 2.4.
For each polygon hole of , put . The matching containing and its exterior are
To derive the basin identity, sum (2.9) over the cells selected for before recursion. Each new cell attaches along one shared diagonal without crossings, so their adjacency graph is a tree. Each shared diagonal determines complementary -boundary arcs , whose exchanges both reach , so their signed gains sum to . These diagonals cancel all but one copy of . Original boundary edges have zero gain, yielding
where both sums range over the dissection of . Polygon holes of size two have and zero gain. Starting at the root, recurse on larger polygon holes as child basins, isolating each directly by (2.5). They are strict descendants in with disjoint sibling subtrees, so no basin repeats. The inherited exterior may differ from the independently isolated exterior . Following [13, Section 6.4], let be the matching law outside , and set , , and . For basins and nonshort arcs , is a geometric cycle , and for either alternating pattern. Short arcs satisfy .
Set for each independently isolated basin. The two gains on a child basin use the same , , so subtracting the same mean gives
The terms will cancel between parent and child identities. The exteriors may differ outside E because isolation can interchange the source matchings. With h ranging over the child basins of E, substitution into (2.11) yields
Replacing by in (2.8) likewise leaves unchanged.
Set at the root and for each child basin. Multiplying (2.12) by and summing over basins cancels every nonroot gain:
At the root, is evaluated after interchanging the source matchings if needed to place first. Conditional on either assignment of , to , , this first exterior has law . Both assignments have probability , giving
To bound the number of gain terms, note that a full dissection of E has cells, giving
Summing (2.15) cancels the polygon-hole terms. With basins and cells,
The expansion contains only two-edge switch gains and centered evaluations. We next bound their source masses to control . Figure 2 compares the two gains on a child basin.

| Source | Gain on |
| Inherited from | |
| Independent isolation | |
Figure 2: One cell and two polygon holes in . Here . The first gain minus the second is the centered error in .
2.4 Weight comparisons and congestion
We bound the squared contributions in (2.13) by comparing weights and bounding how many terms share an output. For each source , assign each term an ordered pair of perfect matchings . The first matching determines the function evaluation, while the guide is used to compare weights. For centered terms, we retain and .
Cell comparisons. For an odd arc of the current cell, obtain from by replacing with when . Set when . Thus matches only the arc interior. Set and, for , define
Together with in (2.7), these give full matching pairs . Use for the switch between , and for the respective terms of (2.8). For , the guide contains . Before guide repair, the multiset union is independent of . If the basin's children are even, the chords cross the children and the chords lie within them. The comparison using threshold clusters in (2.5) shows that the local -weight products do not decrease from the isolated pair.
For two odd children, modify only the guide by two-edge switches outside , preserving . Write and . We compare the isolated product with the local output products, since exterior factors cancel. Successors and predecessors refer to the whole -boundary.
For an odd prefix and even suffix , the cell is . If is short, no repair is needed. For a nonshort , put , , , and . Cancellation gives , and the ratio at is . Apply
Vertices lie outside . For each, the -weight is constant on this interval, so each switch multiplies the guide's weight by . Both switches leave untouched.
For an even prefix and odd suffix , the cell is , with . If is short, the ratios are . Otherwise set , , giving
Here , , and by the interval hierarchy. Apply
Vertices lie outside . For each, the -weight is constant on this interval. Each switch multiplies the guide's weight by and leaves untouched. If is short, , and the switch in remains valid with . All these switches use four distinct vertices.
To pass to a-weights, we bound the number of changed edge occurrences, with multiplicity. In the following sums, ranges over the four cell arcs and chord denotes its endpoint chord. The isolated pair has union on . Before guide repair, equals
This adds the two chords and replaces by on each arc. A short arc removes one occurrence, while a nonshort one removes two and adds one. Since has a short arc, at most three occurrences are removed and three added. Isolation and guide repair each remove at most two further occurrences, giving . Replacing by raises this bound to nine. Additions satisfy the same bounds because each pair contains edge occurrences. After guide repair, let be the two switch matchings and their common full guide. For either term of (2.8), let be its full pair. As in (2.6), compare with using to obtain
Polygon-hole comparisons. For a nontrivial polygon hole of , the two terms in (2.12) are and . For the first, take . By (2.10), this is the first matching of , after a cycle exchange on if . Let immediately precede and follow on the -boundary. In the second matching, apply the two-edge switch
The resulting guide Q contains . Since is a node of , the threshold-cluster argument in (2.5) shows that this switch cannot decrease the -weight product. Both this switch and the isolation of use on , even if the switch removes 's closing chord. Together they remove at most four edge occurrences from the source, giving
For , use the independently isolated pair . By (2.6),
Taking here, these bounds and (2.17) give for every centered evaluation, with and . For a two-edge switch, choose its endpoint of smaller -probability as , breaking ties by a fixed matching order. Its guide is common to both endpoints.
One encoding for all levels. An occurrence is a source and a term of (2.13), fully expanded before repeated terms are combined. There are five types: a two-edge switch gain, either evaluation of a cell error, or the parent or child evaluation of a polygon-hole error. Adapting [13, Lemma 6.4], the following record and output pair recover each occurrence.
Record seven vertex slots: the least vertex of c, the basin endpoints, and the four cell corners. For a parent–child link, replace the corners by child endpoints and fixed padding. Record the type and four binary flags: which alternating pattern on c belongs to , parity of interchanges of the two whole matchings, choice of switch endpoint, and order of the H arcs. Fix unused flags. Two sorted lists, padded to nine entries each, record deletions and additions in the multiset union, retaining multiplicities but omitting matching labels. Cycle exchanges preserve this union and require no entries.
Recover the occurrence from and this record as follows.
-
Reverse the recorded additions and deletions in to recover . Its discrepancy cycle containing the first recorded vertex is .
-
On c, the flag for fixes both alternating patterns. All edited edges lie in c, so outside c we only undo the recorded interchange of the two whole matchings.
-
Reconstruct the hierarchy and selected basins from c, B, and the fixed tie rules.
-
Locate the term using the basin endpoints, cell corners or child endpoints, type, and flags. Each child basin has a unique parent in the recursion.
The seven vertex slots have at most choices, the type and flags have , and each list entry has at most . Thus each output pair has at most
occurrences in total, over all sources, basins, and depths.
Summing the loads. The load is the sum of over occurrences assigned to a fixed switch or centered evaluation. For a fixed unordered switch , use the endpoint chosen above. By (2.17), at most occurrences per and give a load of at most . To compare with , use to bound the load by
For a nonshort directed odd path with its closing chord and a matching , let be the load of . Summing Equations (2.17) to (2.19) over guides , with at most occurrences per , gives
Multiply by and extend the nonnegative sum to all . Under conditioned on , the exterior has law , so the total centered contribution is at most
The guide and matching sums supply and , respectively. Closing gives a geometric cycle with and . The closing edge and direction give at most representations of . Since ,
Each cell contributes one switch gain and at most two centered evaluations, and each nontrivial parent–child link contributes two centered evaluations. By (2.16), the sum W of absolute coefficients in the expansion of (2.13) satisfies
Apply Cauchy–Schwarz once to this expansion, multiply by , and sum over sources. Equations (2.14) and (2.20) to (2.22) give
Using Equations (2.2) and (2.4), , , and , we obtain
This proves Theorem 2.1.
11
☐
3 A replicated sampler
Theorem 2.1 controls additive functions of two matchings. Sampling requires a variance bound for arbitrary functions of the chain's state. We connect the uniform and target laws through nearby levels, then apply OpenAI's replication argument with several matchings per level.
3.1 A path of nearby laws
Suppose integers are given and
for some positive ultrametric similarity . Multiplying every activity by multiplies every matching weight by , so . Set , , and take the least integer such that . Define
Since , is uniform and . Capping preserves the ultrametric inequality for , and gives
so Theorem 2.1 applies at every level with the same .
Between adjacent levels, edge weights increase by factors in , so both matching weights and the partition function increase by factors in . Since and ,
The path uses only , with certifying the comparison. To sample , repeatedly match the least unused vertex to a uniformly chosen unused partner. Each matching has probability .
3.2 The replicated chain and its gap
Use matchings per level, , , with stationary law . A coordinate is one matching position . This product law makes the matchings independent under , with single-coordinate distribution, or marginal, . Number the positions from highest to lowest level, then by . Thus lower-level positions come later in this order.
The level-zero positions are the base coordinates. A refresh independently resamples one such matching from , leaving all others fixed. The guides of a level-t position, , are the positions at level . Pair updates use the two-edge switch, cycle exchange, and holding proposals of , with the higher-level matching first. All proposals, including cycle exchanges, use Metropolis acceptance for . The chain holds with probability and otherwise chooses uniformly among these updates. All updates, hence , are -reversible.
Use the energy defined in Section 2. For (a base refresh) and (a pair update), fix the other coordinates, compute the local energy of , then average over their values under . For a refresh, the local energy equals the variance under its marginal.
The following lemma, extracted from OpenAI's replication proof [13, Lemma 7.2], converts an additive pair bound into a bound for every function of the full state.
Lemma 3.1. Let , where is a law on a finite set . Let index base coordinates, and choose guide sets
Refresh each from . For , , let be a -reversible kernel depending only on , with energy . If and, for each such pair and all , ,
then every satisfies
Proof. All norms are in . With , revealing adds the increment . By orthogonality, . For , subtracting single-coordinate terms from the conditional mean leaves the interaction part
For a chosen guide pair, conditional on , is additive in , , and its summand has averaged variance . Jensen's inequality gives . Using (3.4), , and for stationary kernels yields
For fixed y, independence and the tower property give
Reveal first, then . These are orthogonal increments of , so . Summing over guide pairs gives . At a base coordinate, refresh and Jensen's inequality give . Average (3.6) over and sum over :
Moving the variance term to the left proves (3.5).
Apply the lemma with the level-zero positions and the positions one level below . By (3.3), pointwise. The symmetric proposal rule is unchanged. For each unordered state pair, its Metropolis energy coefficient is the proposal probability times the smaller endpoint density, hence at least half its equal-level value. Thus Theorem 2.1 gives (3.4) with . Since and chooses each update with probability , Lemma 3.1 gives
Hence P has gap at least and is irreducible: a nonconstant closed-class indicator would violate this bound. The holding probability makes P lazy.
Adapting OpenAI’s mixing and finite-precision analysis [13, Theorem 7.3 and Section 9] to this gap bound gives the following sampler. Write bit(a) for the activities’ total binary encoding length and for total variation distance.
Theorem 3.2. Given even , positive rational a satisfying (3.1), and an integer , there is a sampler within of in total variation. Its bit running time and fair-random-bit budget are polynomial in , , , bit(a), b on every execution. Only a, , , b are inputs.
Proof. The implementation in Section A.1 runs P from fixed matchings and outputs one top-level matching, whose stationary law is . It uses fixed time and random-bit budgets and bounds mixing and total rounding errors by each.
4 Completion and marking
Completion gives the comparison required by Theorem 3.2. We bound its increase in total weight and mark edges by their weight contributions.
For positive activities , set and define
where ranges over simple -to- paths in . Concatenating paths and removing loops gives the ultrametric inequality for , and one-edge paths give . To compute , initialize , , and, for each , replace by . After step , the allowed internal vertices are . This takes comparisons, and every finite value is one or an input activity. The completion satisfies
providing the ultrametric comparison in (3.1).
4.1 The increase in total weight
For positive activities , let be the total weight of matchings leaving exactly the hole set unmatched. The ratio can exceed one and is not a probability. We omit braces, writing , and have , . Set . We call balanced if
Thus all , and for each some has . Growth of the total weight involves two-hole ratios, whose changes involve four-hole ratios. The next lemma bounds both.
Lemma 4.1 (OpenAI [13, Lemmas 3.2–3.3]). For positive activities a and distinct i, j, u, v,
If also and for every , then for and distinct ,
Proof. For even hole sets and , we first show
Overlay an ordered pair of matchings missing . The alternating path from ends at a unique . Exchanging their edges along it preserves the product of their weights and gives the displayed hole sets. For fixed , the output path from recovers the input. Summing over endpoints and dividing by proves (4.4). Taking , gives (4.2), hence four-hole ratios are at most when every .
We also use edge insertion: for an even hole set C and distinct ,
because adjoining xz injects matchings missing into matchings missing C.
For (4.3), write , . The bounds 4, 48 suffice if . Otherwise (4.1) and give a simple i-to-j path with edge weights at least . Starting with
, move until it meets another original hole. We transfer the bound on so intermediate terms cancel on summation. If the next vertex lies in , (4.5) gives
If , choose with . Since , we have . Apply (4.4) with , then (4.5) to terms containing both . Writing gives
The endpoint gives the first term using . The bracket contains the term for when and those for . For four holes the bracket is at most , and for two holes at most . Since ,
By (4.6) and , at most steps of (4.7) give .
Following [13, proof of Theorem 3.1], we obtain the completion bound.
Lemma 4.2. If is balanced and , with , then
Proof. Set , , and for . Differentiating, with sums over unordered edges, gives
While for every , Lemma 4.1 bounds each product or by . Since ,
Integration gives , hence . If any first reaches 1/8 or 4, these bounds still hold by continuity, keeping every strictly inside, a contradiction. The derivative bounds thus hold on , and integration proves (4.8).
4.2 The marked law
Each edge can be labeled real for or virtual for in , following [13, Proposition 4.2]. A marked matching has virtual edges and law
Summing over gives . Balance ensures that the all-real event has probability , by Lemma 4.2. Sampling needs no balance: combine Theorem 3.2 with the marking rule of [13, Proposition 4.2].
Theorem 4.3. Given even , positive rational with , and integers , an algorithm returns a marked matching with law within of in total variation. Bit running time and fair-random-bit use are polynomial in , bit( ), on every run, regardless of balance.
Proof. Since and , the completion satisfies
Apply Theorem 3.2 to and independently mark each sampled edge virtual with probability . Internal scaling preserves , while marking uses the original weights. An exact sample gives (4.9). The rounding budget in Section A.1 includes the marking coins. Mixing and total rounding errors each at most prove the claim.
For balance in Section 5, use vertex scaling , with . Every full matching weight gains , preserving its law and dividing by .
5 Counting with one marked batch
We prove Theorem 1.1 using OpenAI's marked annealing method [13, Section 8]. Each stage uses one batch to estimate the next partition-function ratio and restore balance.
5.1 Annealing and marked samples
For , return one. For , return zero. Otherwise, polynomial time in is polynomial in input length, even for binary . Use Edmonds' algorithm [7] to test for a perfect matching, returning zero if none exists. Handle exactly. Henceforth is even and .
Let . The outer schedule assigns weights to graph edges and to nonedges, with . To suppress nonedges, take the least satisfying
Since , we have . The weight multiplier for a full or two-hole matching and the full partition-function ratio are
These bounds follow from , and .
At outer stage , scale the weights to with . Sampling uses their completion and the internal levels of Section 3. Set , advancing the outer schedule before rebalancing. Vertex scaling gives and . Initialize , where , so initially every two-hole ratio is . The balance condition is
Full and two-hole partition sums both change by factors in . Under , this gives
To estimate the next two-hole ratios, record from each marked sample at
Here records all-real samples and reweights them to . Removing the unique virtual edge gives a bijection to perfect matchings after deleting its endpoints (written ). In , leaves the factor 1/D from (4.9), and u reweights the remaining matching. All three observables lie in since , with exact means
Taking ratios yields
By Lemma 4.2, balance gives and .
5.2 Estimation and a dyadic balancing pass
For observables and failure probability per stage, set
(5.5)
Here controls the ratios and final product, the failure probability, and the sampling bias. Use in all calls, as justified in Section A.2.
At each stage , form empirical means from fresh independent marked samples at . Floors and clipping keep updates defined even when estimates fail:
where . Always and .
To restore balance, adapt OpenAI's pass [13, Lemmas 8.1–8.2] by rounding scale multipliers upward to powers of two. Start . Visit the vertices once in a fixed order, replacing by the smallest member of
Then replace by and advance to stage .
Suppose is balanced and each empirical mean differs from its exact mean in (5.4) by at most . The denominator floors are inactive. Writing , we obtain
The cap at three is inactive, and adding makes an upper bound:
Clipping the partition-function ratio cannot increase its error relative to , so
Lemma 5.1. The pass is defined for all symmetric data . If (5.3) and (5.7) hold, it restores (5.2).
Proof. Initially . The current is feasible, so updates only decrease multipliers and preserve the constraints. Vertex scaling divides each true ratio by , giving the upper bound one under (5.7).
For the lower bound, at vertex let , attained at . Minimality gives , hence . Later decreases cannot reduce this ratio. Under (5.3) and (5.7), , so final products are at least 1/256. The additive error on therefore gives
5.3 Accuracy and termination
Since the weights depend on earlier samples, condition on the history before each stage, fixing the activities and observables. By Theorem 4.3, independent calls have law within of , so each observable has mean bias at most . Hoeffding's inequality [8], applied around the actual means, gives
A union bound over the observables, allowing dependence within a sample, yields
Averaging over histories and summing over stages gives simultaneous empirical accuracy with probability at least . On this event, Lemma 5.1 propagates balance by induction, and (5.8) controls every ratio. We return
On the same event, multiplying (5.8) over stages gives
At most matchings use a nonedge, each with final weight at most . Hence
For , , so the combined error is within . The deterministic polynomial cost bound in Section A.2 also holds when estimates fail.
A Finite precision
A.1 Simulation of the replicated chain
There are at most perfect matchings, and the capped activities in (3.2) lie in . Thus . With the parameters of Section 3, set
Here . For any initial , contraction and Cauchy–Schwarz give
The same bound holds for the top-level output.
Precompute and . Decode update indices by integer division, compute Metropolis ratios from edge products (partition functions cancel), and list discrepancy cycles when choosing a cycle exchange. A uniform refresh takes partner choices. By (3.3), all exponents and arithmetic lengths are polynomial in , , , .
For a rational law , use fair bits to choose uniformly in and select the half-open cumulative interval containing . The total variation error is at most . A run, including final marking coins when used, has at most
choices and options per choice, respectively. Take the least with . Conditional coupling over these choices bounds the total rounding error by . Exact marking cannot increase total variation distance, so the unmarked or marked output has error at most and uses at most fair bits. With or , this proves Theorems 3.2 and 4.3, respectively. Marking probabilities have polynomial bit length.
A.2 The adaptive counter
Each multiplier in (5.6) adds an integer in to the scale exponent. Thus, after j passes,
on every history. Activities are positive and at most , validating and have bits, as does , since is one or an input activity.
Within a stage, the share denominator , and for fixed , is zero or . Averaging adds denominator bits, so means and floored ratios have polynomial bit length. The data only choose dyadic multipliers, so means' denominators never enter cumulative scales. In the final ratio product, the factors' bit lengths add.
There are exactly marked sampler calls and updates over the finite grid (5.6). The parameters in (5.1) and (5.5), and f, are computable by rational arithmetic, integer power comparisons and integer square root. In particular,
With , these bounds are polynomial in and the input encodings. Summing the deterministic time and random-bit budgets of Theorem 4.3 over the fixed calls proves the worst-case bounds, without requiring balance on failed histories.
References
[1] Alexander Barvinok. Approximating permanents and hafnians. Discrete Analysis, 2017:2, 34 pp., 2017. doi:10.19086/da.1244.
[2] Ivona Bezáková, Daniel Štefankovič, Vijay V. Vazirani, and Eric Vigoda. Accelerating simulated annealing for the permanent and combinatorial counting problems. SIAM Journal on Computing, 37(5):1429–1454, 2008. doi:10.1137/050644033.
[3] Xiaoyu Chen, Heng Guo, Eric Vigoda, and Xiongxin Yang. Fast FPRAS for the permanent. arXiv:2609.20717v1, 2026.
[4] Xiaoyu Chen, Eric Vigoda, and Xiongxin Yang. Faster FPRAS for the permanent via restricted Poincaré inequalities and coupled flows. arXiv:2608.26599v1, 2026.
[5] Martin Dyer and Haiko Müller. Counting perfect matchings and the switch chain. SIAM Journal on Discrete Mathematics, 33(3):1146–1174, 2019. doi:10.1137/18M1172910.
[6] Farzam Ebrahimnejad, Ansh Nagda, and Shayan Oveis Gharan. Counting and sampling perfect matchings in regular expanding non-bipartite graphs. In ITCS 2022, LIPIcs 215, pp. 61:1–61:12, 2022. doi:10.4230/LIPIcs.ITCS.2022.61.
[7] Jack Edmonds. Paths, trees, and flowers. Canadian Journal of Mathematics, 17:449–467, 1965. doi:10.4153/CJM-1965-045-4.
[8] Wassily Hoeffding. Probability inequalities for sums of bounded random variables. Journal of the American Statistical Association, 58(301):13–30, 1963. doi:10.1080/01621459.1963.10500830.
[9] Mark Jerrum and Alistair Sinclair. Approximating the permanent. SIAM Journal on Computing, 18(6):1149–1178, 1989. doi:10.1137/0218077.
[10] Mark Jerrum, Alistair Sinclair, and Eric Vigoda. A polynomial-time approximation algorithm for the permanent of a matrix with nonnegative entries. Journal of the ACM, 51(4):671–697, 2004. doi:10.1145/1008731.1008738.
[11] Mark R. Jerrum, Leslie G. Valiant, and Vijay V. Vazirani. Random generation of combinatorial structures from a uniform distribution. Theoretical Computer Science, 43:169–188, 1986. doi:10.1016/0304-3975(86)90174-X.
[12] P. W. Kasteleyn. Dimer statistics and phase transitions. Journal of Mathematical Physics, 4(2):287–293, 1963. doi:10.1063/1.1703953.
[13] OpenAI. A Fully Polynomial Randomized Approximation Scheme for Perfect Matchings in General Graphs. Manuscript, September 23, 2026. Fixed source, commit adc7f1241b42e322a6451854ab7e4b4c146bf78a. This version is used throughout.
[14] Alistair Sinclair. Improved bounds for mixing rates of Markov chains and multicommodity flow. Combinatorics, Probability and Computing, 1(4):351–370, 1992. doi:10.1017/S0963548300000390.
[15] Daniel Štefankovič, Eric Vigoda, and John Wilmes. On counting perfect matchings in general graphs. In LATIN 2018, LNCS 10807, pp. 873–885, 2018. doi:10.1007/978-3-319-77404-6_63. Full version: arXiv:1712.07504v1, 2017. Theorem and section numbers cited here refer to this version.
[16] Leslie G. Valiant. The complexity of computing the permanent. Theoretical Computer Science, 8(2):189–201, 1979. doi:10.1016/0304-3975(79)90044-6.
[17] Zihong Yi. Diffuse Gaussian truncation for deterministic approximate counting. arXiv:2609.04079v1, 2026.