# Possible bug in 2D multi-range extended fit with EvalBackend("cpu")

**URL:** <https://root-forum.cern.ch/t/possible-bug-in-2d-multi-range-extended-fit-with-evalbackend-cpu/65000>\
**Category:** Roofit and RooStats\
**Created:** [September 23, 2026, 7:39am UTC](https://root-forum.cern.ch/t/possible-bug-in-2d-multi-range-extended-fit-with-evalbackend-cpu/65000 "2026-09-23T07:39:57Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Elia\_Giulio\_Grandoni](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/elia_giulio_grandoni/32/36714_2.png) [@Elia\_Giulio\_Grandoni](https://root-forum.cern.ch/u/Elia_Giulio_Grandoni)\
**Post date:** [September 23, 2026, 7:39am UTC](https://root-forum.cern.ch/t/possible-bug-in-2d-multi-range-extended-fit-with-evalbackend-cpu/65000/1 "2026-09-23T07:39:57Z")

</div>

## Possible bug in 2D multi-range extended fit with `EvalBackend("cpu")`

Hi,

I am observing a discrepancy between the `cpu` and `legacy` RooFit backends when performing an **extended fit in multiple disjoint ranges in 2D**.

The issue is reproducible with a completely standalone script, without any external input files.

I tested it with:

- ROOT 6.36.06

- ROOT 6.40.02

and I obtain exactly the same behaviour in both versions.

The full-range fit gives identical results with the two backends, while the multi-range sideband fit gives very different fitted yields.

Here is the minimal reproducer:

```auto
import ROOT

def main():
    ROOT.gROOT.SetBatch(True)
    ROOT.RooMsgService.instance().setGlobalKillBelow(ROOT.RooFit.ERROR)
    ROOT.RooRandom.randomGenerator().SetSeed(12345)

    ws = ROOT.RooWorkspace("ws")

    for expression in (
        "x[-5,5]",
        "y[-5,5]",
        "Gaussian::gx(x,mu[0],sigma[1])",
        "Gaussian::gy(y,mu,sigma)",
        "PROD::g(gx,gy)",
        "Uniform::u({x,y})",
        "SUM::model(ng[8000,0,30000]*g,nu[2000,0,30000]*u)",
    ):
        ws.factory(expression)

    obs = ROOT.RooArgSet(ws.var("x"), ws.var("y"))

    bounds = [(-5, -2), (-2, 2), (2, 5)]
    ranges = []

    for i, x_bounds in enumerate(bounds):
        for j, y_bounds in enumerate(bounds):
            if i == 1 and j == 1:
                continue

            name = f"sb{i}{j}"
            ranges.append(name)

            ws.var("x").setRange(name, *x_bounds)
            ws.var("y").setRange(name, *y_bounds)

    data = ws.pdf("model").generate(obs, 15000)

    n_sideband = data.sumEntries("abs(x)>2 || abs(y)>2")

    print(
        f"ROOT {ROOT.gROOT.GetVersion()}: "
        f"full={data.numEntries()}, SB={n_sideband}",
        flush=True,
    )

    results = {}

    for restricted in (False, True):
        for backend in ("cpu", "legacy"):

            # Fresh copy prevents a preceding fit from changing range settings.
            fit_ws = ws.Clone()
            model = fit_ws.pdf("model")

            options = (
                [ROOT.RooFit.Range(",".join(ranges))]
                if restricted else []
            )

            result = model.fitTo(
                data,
                ROOT.RooFit.Extended(True),
                ROOT.RooFit.Save(),
                ROOT.RooFit.PrintLevel(-1),
                ROOT.RooFit.EvalBackend(backend),
                *options,
            )

            yields = [
                fit_ws.var(n).getVal()
                for n in ("ng", "nu")
            ]

            fit_obs = ROOT.RooArgSet(
                fit_ws.var("x"),
                fit_ws.var("y"),
            )

            fractions = [
                sum(
                    fit_ws.pdf(pdf).createIntegral(
                        fit_obs,
                        ROOT.RooFit.NormSet(fit_obs),
                        ROOT.RooFit.Range(r),
                    ).getVal()
                    for r in ranges
                )
                for pdf in ("g", "u")
            ]

            expected_sb = sum(
                n * fraction
                for n, fraction in zip(yields, fractions)
            )

            label = "sidebands" if restricted else "full"

            print(
                f"{label:9s} {backend:6s}: "
                f"N_g={yields[0]:.3f}, "
                f"N_u={yields[1]:.3f}, "
                f"expected_SB={expected_sb:.3f}, "
                f"status={result.status()}, "
                f"covQual={result.covQual()}",
                flush=True,
            )

            results[restricted, backend] = yields

if __name__ == " __main__":
    main()

```

With ROOT 6.40.02 I get:

```auto
ROOT 6.40.02: full=15000, SB=3431.0

full cpu : N_g=12146.553, N_u=2854.253,
                   expected_SB=3477.756,
                   status=0, covQual=3

full legacy: N_g=12146.553, N_u=2854.253,
                   expected_SB=3477.756,
                   status=0, covQual=3

sidebands cpu : N_g=2818.327, N_u=729.358,
                   expected_SB=863.292,
                   status=0, covQual=3

sidebands legacy: N_g=11199.522, N_u=2899.005,
                   expected_SB=3431.129,
                   status=0, covQual=3

```

The full-range fits agree perfectly.

For the sideband fit, however, the `legacy` backend gives

```auto
expected_SB = 3431.129

```

which agrees with the actual number of events in the sidebands,

```auto
N_SB = 3431

```

while the `cpu` backend gives

```auto
expected_SB = 863.292.

```

Interestingly, the fitted yields differ essentially by a common scale factor:

```auto
11199.522 / 2818.327 ≈ 3.97
2899.005 / 729.358 ≈ 3.97

```

so the discrepancy looks more like a normalization / extended-term issue than a different likelihood minimum.

Both fits report

```auto
status = 0
covQual = 3

```

and the discrepancy is still present in ROOT 6.40.02.

Is this expected behaviour for `Extended(True)` combined with a comma-separated multi-range fit in more than one dimension, or is this a bug in the `cpu` backend normalization?

In my understanding, the fitted extended coefficients should correspond consistently to the full-range yields, with the expected number of events in the fitted sideband region obtained from the component integrals over the selected ranges.

Thanks!

---

<div class="post-metadata">

**Author:** ![jonas](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/jonas/32/24756_2.png) [@jonas](https://root-forum.cern.ch/u/jonas)\
**Post date:** [September 27, 2026, 9:21am UTC](https://root-forum.cern.ch/t/possible-bug-in-2d-multi-range-extended-fit-with-evalbackend-cpu/65000/2 "2026-09-27T09:21:38Z")

</div>

Thanks for the report! It’s important that these regressions get reported, before the legacy backend is removed, so I really appreciate this.

I opened a PR to fix it, and will backport the fix to the 6.40 release branch so it will be in the next 6.40 patch release:

> <https://github.com/root-project/root/pull/23513>
>
> In RooAddPdf::createExpectedEventsFunc(), the range fractions for the extended l…ikelihood term were computed via 1/(integral of the component pdf over the full default range). This only yields the fraction of the component inside the norm range if the component is normalized over the full default range.
> 
> That assumption is violated in the new evaluation backend, where pdfs are compiled with arbitrary internal normalization. For example, a RooProdPdf might have each factor normalized over the per-observable union of the fit ranges, which for disjoint multi-dimensional ranges is not the full default range. The extended likelihood term then used wrong expected events and produced wrong fitted yields, e.g. for the product of two Gaussians fitted over eight sideband boxes in two observables, where the Gaussian product got a range fraction of 1.0 instead of ~0.089.
> 
> Instead, multiply each coefficient with the ratio of two integrals of the same component: numerator over the norm range, denominator over the coefficient reference range (full default range by default, or the range fixed by selectNormalizationRange(), e.g. via the SumCoefRange fit option). Any constant normalization cancels in the ratio, matching the RooAddPdf::expectedEvents() semantics used by the legacy backend.
> 
> The new C++ unit test covers an extended fit of a Gaussian product plus uniform background in eight 2D sideband ranges, with reference values computed with plain math (erf and logarithms) instead of the legacy backend.
> 
> Closes #23512.
> 
> 🤖 Done with the help of AI
> 
> \# This Pull request:
> 
> \## Changes or fixes:
> 
> 
> \## Checklist:
> 
> \- \[\] tested changes locally
> \- \[\] updated the docs (if necessary)
> 
> This PR fixes #

---

<div class="post-metadata">

**Author:** ![cxclrfx](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/cxclrfx/32/38524_2.png) [@cxclrfx](https://root-forum.cern.ch/u/cxclrfx)\
**Post date:** [October 8, 2026, 8:00pm UTC](https://root-forum.cern.ch/t/possible-bug-in-2d-multi-range-extended-fit-with-evalbackend-cpu/65000/3 "2026-10-08T20:00:31Z")

</div>

Hey,

The result is quite clear: the behaviour reported here was a real bug in the `cpu` backend’s extended-term normalization, not expected behaviour.

The original reproducer is now covered by `root-project/root#23512` and has been fixed in current ROOT master. The fix is also present on the current `v6-40-00-patches` branch.

Below is the complete analytical explanation of both the observed factor of about 3.97 and the source-level normalization error.

## 1. Correct sideband fractions

The fitted region is the union of the eight boxes of the 3x3 grid, excluding the central square

[-2,2]\times[-2,2].

For the uniform component on

[-5,5]\times[-5,5],

the sideband fraction is simply the area fraction

f\_U = 1-\frac{4\cdot4}{10\cdot10} = \boxed{0.84}.

For the product of two unit Gaussians truncated to [-5,5],

g(x,y)=g\_x(x)g\_y(y),

the probability of the central square is

P\_{\mathrm{central}} = \left[\frac{\operatorname{erf}(2/\sqrt{2})} {\operatorname{erf}(5/\sqrt{2})} \right]^2.

Therefore the correct Gaussian sideband fraction is

f\_G = 1- \left[\frac{\operatorname{erf}(2/\sqrt{2})} {\operatorname{erf}(5/\sqrt{2})} \right]^2 = \boxed{0.08892920913888092}.

Using the `legacy` fitted yields from the reproducer,

N\_G=11199.522, \qquad N\_U=2899.005,

the expected number of sideband events is

N\_{\mathrm{SB}} = f\_GN\_G+f\_UN\_U,

so

N\_{\mathrm{SB}} = 0.08892920913888092\cdot11199.522 + 0.84\cdot2899.005 = \boxed{3431.128834\ldots}.

This matches the observed

N\_{\mathrm{SB}}=3431.

So the interpretation in the original post was correct: the fitted coefficients are full-range yields, and the expected sideband count is obtained by multiplying each yield by the corresponding component fraction in the selected union of ranges.

* * *

## 2. What the buggy `cpu` likelihood was actually doing

The surprising part is that the `cpu` fit also reports

```plaintext
status = 0
covQual = 3

```

despite returning

```plaintext
N_g = 2818.327
N_u = 729.358

```

which give only

f\_GN\_G+f\_UN\_U = \boxed{863.292311\ldots}

events in the physical sideband region.

The reason is that the buggy extended term was not using the physical Gaussian fraction f\_G.

For the Gaussian product it effectively used

\widetilde f\_G=1

instead of

f\_G=0.08892920913888092,

while the uniform fraction remained

\widetilde f\_U=0.84.

Now evaluate the expected number of events according to that buggy internal model:

\widetilde N\_{\mathrm{SB}} = \widetilde f\_GN\_G+\widetilde f\_UN\_U.

With the `cpu` fitted yields,

\widetilde N\_{\mathrm{SB}} = 2818.327 + 0.84\cdot729.358 = \boxed{3430.98772}.

That is essentially exactly the observed 3431 sideband events.

So Minuit was not failing.

It was successfully minimizing the likelihood that RooFit gave it.

The problem was that the extended term in that likelihood represented the wrong expected-event normalization.

This also explains why a successful

```plaintext
status = 0
covQual = 3

```

cannot diagnose this class of error: these values certify the minimization and covariance calculation of the supplied objective, not the physical correctness of how that objective was constructed.

* * *

## 3. Exact origin of the factor ~3.97

The fitted component ratio is approximately preserved:

r = \frac{N\_U}{N\_G} = \frac{729.358}{2818.327} = 0.2587911197\ldots

For a fixed component ratio r, the overall yield scale is determined by the extended term.

The scale change caused by replacing the correct fractions (f\_G,f\_U) by the buggy fractions (\widetilde f\_G,\widetilde f\_U) is therefore

K = \frac{ \widetilde f\_G+r\widetilde f\_U }{ f\_G+rf\_U }.

Substituting the values,

K = \frac{ 1+0.84(0.2587911197) }{ 0.08892920913888092+0.84(0.2587911197) } = \boxed{3.974305893\ldots}.

The two observed yield ratios are

\frac{11199.522}{2818.327} = \boxed{3.973819\ldots},

and

\frac{2899.005}{729.358} = \boxed{3.974735\ldots}.

So the apparently mysterious common factor of about 3.97 follows directly from the wrong component fraction used by the extended term.

* * *

## 4. Source-level cause

The problematic code was in the construction of the expected-events function for a ranged `RooAddPdf`.

The old implementation effectively inferred a range fraction from the reciprocal of a component integral over the coefficient reference range.

That is only valid under an additional assumption about how the compiled component is internally normalized.

Let an internal compiled representation of a physical component be

\widetilde p\_k(x) = c\_k\,p\_k(x),

where c\_k is an arbitrary constant introduced by internal normalization choices.

A physical range fraction must be invariant under this transformation.

The correct quantity is

\boxed{ f\_k(R;R\_0) = \frac{ \int\_R \widetilde p\_k(x)\,dx }{ \int\_{R\_0}\widetilde p\_k(x)\,dx } }.

Indeed,

f\_k = \frac{ c\_k\int\_Rp\_k(x)\,dx }{ c\_k\int\_{R\_0}p\_k(x)\,dx } = \frac{ \int\_Rp\_k(x)\,dx }{ \int\_{R\_0}p\_k(x)\,dx }.

The arbitrary internal normalization cancels exactly.

The old reciprocal construction did not have this invariance.

That is why it could work for some component representations and fail for the compiled `RooProdPdf` in the multi-range 2D case.

The ROOT fix changes the expected-event fraction to the ratio of two integrals of the same component:

- numerator: integral over the fit/norm range;
- denominator: integral over the coefficient reference range.

This is the correct invariant construction.

The corresponding ROOT fix is the commit

```plaintext
7b50e599c698c1439b9a6d59d6ff78f3a232ea3f
[RF] Fix fractions in expectedEvents for normed RooAddPdf components

```

and the issue is

```plaintext
root-project/root#23512

```

A regression test was added for exactly this geometry: a Gaussian product plus uniform background fitted in eight disjoint 2D sideband boxes, with the reference result calculated independently from `erf()` and logarithms rather than by comparing against the legacy backend.

So the original issue reported in this thread is now well identified and fixed.

* * *

## 5. Why this appears specifically in multi-dimensional multi-range geometry

There is a useful geometric reason why this class of bug is easy to miss.

Let the fitted region be

R = \bigcup\_{j=1}^{m}R\_j,

where each named range is a multidimensional box

R\_j = I\_{1j}\times I\_{2j}\times\cdots\times I\_{dj}.

For the eight-box sideband geometry in the reproducer,

R \neq \pi\_x(R)\times\pi\_y(R),

where \pi\_x and \pi\_y are the coordinate projections.

In fact,

\pi\_x(R)=[-5,5], \qquad \pi\_y(R)=[-5,5],

even though R excludes the central square.

Therefore all information about the central hole disappears if the joint range is replaced by its independent one-dimensional projections.

This is why the range labels have to stay coupled across observables until the joint integral has been constructed.

For a factorized density

p(x,y)=p\_x(x)p\_y(y),

the correct normalization over a disjoint union is

\boxed{ Z\_R = \sum\_j \left( \int\_{I\_{xj}}p\_x(x)\,dx \right) \left( \int\_{I\_{yj}}p\_y(y)\,dy \right) }.

It is **not**

\left[\sum\_j \int\_{I\_{xj}}p\_x(x)\,dx \right] \left[\sum\_j \int\_{I\_{yj}}p\_y(y)\,dy \right].

In compact form,

\boxed{ \sum\_j\prod\_a Z\_{a,j} \neq \prod\_a\sum\_j Z\_{a,j} }

in general.

The difference consists of cross terms that correspond to combinations of coordinate intervals that were never part of any named joint range.

This is the general mathematical boundary behind the problem.

* * *

## 6. A related RooProdPdf issue is still open

While checking the complete normalization path, I found a related but distinct issue that should not be confused with the now-fixed extended-term bug above.

`root-project/root#11486` is still open, and the current ROOT test suite still contains

```cpp
TEST(RooProdPdf, DISABLED_ChangeServerNormSetForProdPdfInAddPdf)

```

with the explicit note that this is still a problem.

The direct reproducer there uses

```cpp
bkg.setNormRange("SB1,SB2");
bkg.getVal(normSet);

```

for

bkg(x,y)=p\_x(x)p\_y(y)

with

SB1=[-10,10]\times[-10,0],

and

SB2=[-10,0]\times[0,10].

The two 2D boxes are disjoint up to a zero-measure boundary.

But their projection onto x is

[-10,10] \quad\text{and}\quad [-10,0],

which overlap.

This is an important distinction:

> disjointness of joint multidimensional ranges does not imply disjointness of their projections onto the observable subset of an individual factor.

For a uniform product density on the full 20\times20 square, the correct joint normalization fraction is simply

\frac{ 20\cdot10+10\cdot10 }{ 20\cdot20 } = \boxed{0.75}.

Therefore the correctly normalized density inside the union is

\frac{1/400}{0.75} = \boxed{\frac1{300}}.

Trying to normalize the individual factors independently with the comma-separated range list loses the joint pairing of the labels `SB1` and `SB2`.

This is why a factor-level multi-range integral can see overlapping 1D ranges even though the original 2D regions are perfectly disjoint.

Current ROOT already contains an explicit workaround around this limitation. In the multi-range case, `RooAddPdf::compileForNormSet()` deliberately does not propagate the comma-separated normalization range to a `RooProdPdf`, with the source comment that `RooProdPdf` cannot deal with such a multi-range normalization range there.

So this remaining issue is not a cache-only problem. `setNormRange()` already sterilizes client normalization caches. The deeper problem is preserving the joint range identity through factorization.

* * *

## 7. General solution for RooProdPdf multi-range normalization

For a union of named disjoint regions

R=\bigcup\_j R\_j,

the safe construction is to keep the range index j outside the product factorization.

For a product that factorizes into independent groups G\_a,

P(z)=\prod\_a G\_a(z\_a),

define

Z\_{a,j} = \int\_{\pi\_a(R\_j)} G\_a(z\_a)\,dz\_a.

Then the joint normalization is

\boxed{ Z\_R = \sum\_j \prod\_a Z\_{a,j}. }

The required operation order is therefore:

1. split the comma-separated range into its named joint components;
2. for each range name j, construct the contribution of every factor/group using that same range name;
3. multiply the factor/group contributions for that j;
4. only then sum over j.

In other words:

\boxed{ \text{split range} \rightarrow \text{evaluate joint component} \rightarrow \text{multiply} \rightarrow \text{sum} }

rather than

\text{split independently in every factor} \rightarrow \text{sum} \rightarrow \text{multiply}.

For components that share observables, they must first be combined into the same irreducible product group and integrated jointly. The existing `RooProdPdf` factorization machinery already identifies such grouped terms; the essential requirement is that the multi-range summation happens after preserving the range label through those groups.

There is also already a useful implementation precedent in `RooAbsReal::createIntegral()`: when given a comma-separated range, it splits the range names at the top level, creates one integral per range, checks the multidimensional ranges for overlap, and returns their sum.

The direct `RooProdPdf` normalization path should preserve the same semantics instead of allowing the comma-separated joint range to collapse into independent projected factor ranges.

* * *

## 8. Regression tests that fully cover the boundary

I would consider the normalization path fully protected only if the regression suite contains all of the following controls:

1. **Full range**  
`cpu` and reference calculation agree.

2. **Single named rectangular range**  
No multi-range composition is involved.

3. **One-dimensional disjoint multi-range**  
Confirms ordinary comma-separated range handling.

4. **Two-dimensional non-Cartesian union**  
For example the eight-box sideband region from this thread.

5. **L-shaped two-range union**  
The `SB1,SB2` geometry from `#11486`.

6. **Internal component-rescaling invariance**  
Replacing

7. **Range-order invariance**  
`Range("A,B,C")` and `Range("C,A,B")` must give identical results.

8. **Equivalent graph topology**  
A bare `RooAddPdf` and the same object wrapped in a `RooProdPdf` with a constraint term must give the same ranged yield semantics.

9. **Direct RooProdPdf normalization**  
A direct

These tests separate the two questions cleanly:

- `#23512`: wrong component fractions in the **extended expected-events term** вЂ” fixed;
- `#11486`: direct **RooProdPdf multi-range normalization / factor normalization-range dependence** вЂ” still open in current master.

* * *

## Conclusion

For the original question in this thread:

\boxed{\text{the observed behaviour was a bug, not expected behaviour.}}

The discrepancy is completely explained by the Gaussian component receiving an effective sideband fraction of

1

instead of

0.08892920913888092.

That single normalization error reproduces both:

- the apparently valid internal expected event count of about 3431;
- the observed common yield scale factor of about 3.97.

The correct construction is the normalization-invariant ratio

\boxed{ f\_k(R;R\_0) = \frac{\int\_Rp\_k}{\int\_{R\_0}p\_k} }

and this is what the ROOT fix now implements for the extended expected-events path.

The remaining `RooProdPdf` multi-range issue is a separate, older problem: the joint range label must remain coupled across factors. Mathematically, the required normalization is a **sum of joint products** , not a **product of independently projected sums**.

---

<div class="post-metadata">

**Author:** ![system](https://root-forum.cern.ch/uploads/default/original/3X/e/f/efe4f24398fd8ffeb76bccb6ecc46d9d9c003376.png) [@system](https://root-forum.cern.ch/u/system)\
**Post date:** [October 22, 2026, 8:00pm UTC](https://root-forum.cern.ch/t/possible-bug-in-2d-multi-range-extended-fit-with-evalbackend-cpu/65000/4 "2026-10-22T20:00:54Z")

</div>

Closed on October 22, 2026, 8:00pm UTC

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.
