root icon indicating copy to clipboard operation
root copied to clipboard

Cling JIT out-of-memory error when using large number of expression-based NormFactors

Open tianzhuli2002 opened this issue 10 months ago • 9 comments

Check duplicate issues.

  • [x] Checked for duplicates

Description

Hello,

We are encountering a reproducible out-of-memory error in ROOT when creating a large number of expression-based parameters during RooFit workspace construction.

Similar issues: https://github.com/root-project/root/issues/14156 https://root-forum.cern.ch/t/cling-jit-session-error-cannot-allocate-memory/56744

As a stress test, we programmatically create many parameters defined via expressions (schematically of the form):

define a base parameter SF_i

define a derived parameter SquaredSF_i = SF_i * SF_i

Each derived parameter is implemented as a RooFit expression (e.g. via RooFormulaVar / expression factories), and all are inserted into a single workspace.

When scaling this up to O(10⁴–10⁵) such expression-based parameters (≈30,000 in our test), the job crashes during workspace creation with:

cling JIT session error: Cannot allocate memory LLVM ERROR: out of memory

Our practical use case is a large simultaneous likelihood fit with many regions and samples, where custom normalisation scale factors are defined through algebraic expressions and applied consistently across subsets of regions and samples. In our real configuration, this corresponds to:

O(500) regions

O(4000) samples

O(70) expression-based scale factors (slightly more complex than a simple square)

While we do not require O(30,000) such expressions in production, we observe that the job already crashes reliably at this realistic scale, with the same Cling JIT out-of-memory failure. Reducing the number of expression-based scale factors to ~10–20 makes the problem disappear, even with the same regions and samples.

Reproducer

To run:

root -l .L cling_test.C+

cling_test(30000)

cling_test.C

ROOT version

ROOT 6.37.01

Installation method

~/miniforge3/bin/root

Operating system

Platform: linuxx8664gcc

Additional context

No response

tianzhuli2002 avatar Jan 27 '26 20:01 tianzhuli2002

Thanks for the report! I think RooFit/HistFactory should not force you to use the interpreter. It's nice to have it for some of the high-level abstractions like the RooWorkspace factory language, but there should be always a way to do everything without the interpreter if possible.

In the case of Measurement::AddPreprocessFunction, I think the solution would be to add an additional overload that can take any C++ function callback as an argument, which specifies how the preprocess functions are created. Something like:

void createPreprocessFunction(RooWorkspace &ws) {
   // you write this function
   ws.import(RooProduct("SquaredSF", ... etc));
}

/// later you do:
meas.AddPreprocessFunctionCallback(createPreprocessFunction);

You think that would work for your use case?

By the way, do you intend to create the workspaces from Python? Then I'd have to take extra case that this add preprocess function callback also works from Python.

guitargeek avatar Jan 28 '26 08:01 guitargeek

Thanks @guitargeek, I think this could work. But to add a bit of context, one very nice advatange of the JITting code is that one can pass a string from some config file without modifying the code. In this example there is a simple formula (prodcut) that can be easily passed in the code, but not so easily via the config. So the solution would work in this particular case, but its not a general solution unfortunately.

TomasDado avatar Jan 28 '26 08:01 TomasDado

I see. We could consider writing a little expression to RooFit parser, that translates the expression to existing RooFit classes like RooProduct etc. Or to reuse already jitted code if the math is the same. I think the latter would not be a big change but could have a big positive impact on memory usage and runtime, provided the expressions are similar.

guitargeek avatar Jan 28 '26 09:01 guitargeek

Hi yes I think adding the additional overload would work in our case! Also reusing already jitted code would also be a nice add as well. Thanks!

tianzhuli2002 avatar Jan 28 '26 09:01 tianzhuli2002

Also sorry - forgot to answer your question on creating the workspaces from python! We don't plan to use python - we are using trex-fitter to build this RooFit/HistFactory workspace. Really appreciate the help on this!

tianzhuli2002 avatar Jan 29 '26 20:01 tianzhuli2002

Hello — I just wanted to check whether there have been any updates or timeline on this. I really appreciate the work that’s gone into the bugfix so far!

tianzhuli2002 avatar Feb 11 '26 11:02 tianzhuli2002

Hello,

Just a quick follow-up to ask if there have been any updates on this, or a rough timeline for the possible solutions that were discussed.

No worries at all if it’s still in progress and thanks again for looking into it!

tianzhuli2002 avatar Mar 13 '26 11:03 tianzhuli2002

Hi @guitargeek , @ferdymercury

I hope you're good!

Any updates regarding this issue? We are also happy to help creating a pull request if we are pointed to the places where this is happening.

We understand the ROOT team has a lot of other issues to solve, but we are also not able to produce our results if this is not fixed.

Thanks!

diegobaronm avatar Mar 25 '26 14:03 diegobaronm

Hi all,

I wanted to share a working workaround we have implemented for the Cling JIT memory exhaustion issue during workspace creation when using many expression-based NormFactors in TRExFitter. Applying these changes allows us to create the workspace for previously problematic configs.

When TRExFitter processes configurations with many expression-based normalisation factors such as:

NormFactor: AntiSFb_20_40
Expression: (1-(SFb_pcbt90_20_40*0.035)-(SFc_pcbt85_20_40*0.138))/0.518: SFb_pcbt90_20_40[1,0.1,3.0],SFc_pcbt85_20_40[1,0.1,3.0]

the original flow is:

  1. TRExFitter reads the expression string from the config

  2. Calls Measurement::AddPreprocessFunction(name, formula, dependencies)

  3. During workspace creation, HistoToWorkspaceFactoryFast calls:

    proto.factory(formula);
    
  4. This triggers Cling/LLVM JIT compilation of the string

  5. With O(100) expressions and memory issues...


Changes in ROOT (HistFactory)

Measurement.h

Added:

#include <functional>
class RooWorkspace;

New interface:

using PreprocessFunctionCallback = std::function<void(RooWorkspace&)>;

void AddPreprocessFunctionCallback(PreprocessFunctionCallback callback);
void ApplyPreprocessFunctionCallbacks(RooWorkspace& ws) const;

Measurement.cxx

Added:

void Measurement::AddPreprocessFunctionCallback(PreprocessFunctionCallback callback)
{
  if (callback) {
    fPreprocessFunctionCallbacks.push_back(callback);
  }
}

void Measurement::ApplyPreprocessFunctionCallbacks(RooWorkspace& ws) const
{
  for (const auto& callback : fPreprocessFunctionCallbacks) {
    if (callback) {
      callback(ws);
    }
  }
}

HistoToWorkspaceFactoryFast.cxx

Added:

measurement.ApplyPreprocessFunctionCallbacks(proto);

This executes callbacks during workspace construction.


Changes in TRExFitter

In Root/TRExFit.cc, I introduced a helper:

void addFormulaPreprocess(Measurement& meas,
                          const std::string& name,
                          const std::string& formula,
                          const std::string& dependencies)
{
    meas.AddPreprocessFunctionCallback(
        [name, formula, dependencies](RooWorkspace& ws) {

        auto specs = parseDependents(dependencies);
        RooArgList args;

        for (const auto& dep : specs) {
            RooAbsArg* arg = ws.arg(dep.name.c_str());

            if (!arg && dep.hasRange) {
                auto var = std::make_unique<RooRealVar>(
                    dep.name.c_str(), "",
                    dep.nominal, dep.min, dep.max);

                ws.import(*var, RooFit::RecycleConflictNodes(true));
                arg = ws.arg(dep.name.c_str());
            }

            if (!arg) {
                throw std::runtime_error("Missing dependency: " + dep.name);
            }

            args.add(*arg);
        }

        auto formulaVar = std::make_unique<RooFormulaVar>(
            name.c_str(), formula.c_str(), args);

        ws.import(*formulaVar, RooFit::RecycleConflictNodes(true));
    });
}

And replaced:

meas.AddPreprocessFunction(...)

with:

addFormulaPreprocess(...)

In terms of why this works essentially when we do addFormulaPreprocess(meas, ...), this just registers a function callback instead of JITing at this point. The memory issue seems to come mainly from repeatedly using RooWorkspace::factory(...) for many expression-based preprocess functions. The callback fix doesn't use that factory path by directly constructing the RooFormulaVars.

I've also attached two patch files showing the changes! Thanks and let me know if there is anything else needed or further clarification.

trex_preprocess_callback.patch root_preprocess_callback.patch

tianzhuli2002 avatar Apr 17 '26 13:04 tianzhuli2002