BUG: `config.change_flags` is not thread-safe: concurrent graph construction can permanently clear `config.cxx`

Aberta
#2,575 2 comentários 0 reações 0 responsáveis Ver no GitHub

Mantenedores costumam responder em até 1 dia

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
4/5
Tempo estimado
3-5 dias
Facilidade para iniciantes
52/100
Tipo de issue
Bug
Clareza
Claramente especificada
Status de atividade
Ativa
Stack de tecnologia
python
Domínio
backend

Direção de pesquisa

Start by reading _ChangeFlagsDecorator in pytensor/configparser.py, then inspect the config.change_flags uses in pytensor/tensor/basic.py and the concurrent reproduction in the issue. Identify how overlapping or recursive scopes affect restoration, and add regression coverage for both cases. Done means concurrent graph construction leaves config.cxx and optdb__max_use_ratio at their original values.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

bug
Describe the issue:

config.change_flags saves the current global values on entry and writes them back on exit (pytensor/configparser.py, _ChangeFlagsDecorator). When two threads' scopes over the same flag interleave, the scope that exits last restores the temporary value that the other scope had set:

A enters: saves "g++", sets cxx=""
B enters: saves "",    sets cxx=""
A exits:  restores "g++"
B exits:  restores ""            <- process-wide, permanently

Every later scope then saves and restores the corrupted value.

Graph construction enters such a scope. Static-shape inference (pytensor/tensor/basic.py, with config.change_flags(optdb__max_use_ratio=10, cxx="")) runs whenever a shape is symbolic, for example in pt.zeros((n,)). PyMC's resolve_shapes (pymc/pytensorf.py) does the same. Building graphs on several threads at once therefore leaves cxx == "" and optdb__max_use_ratio == 10 for the rest of the process.

A shared decorator instance has the same problem without threads. For example, @config.change_flags(warn_float64="ignore") in pytensor/tensor/basic.py is a single object, and a recursive or concurrent call overwrites the values it saved.

Reproducible code example:
from concurrent.futures import ThreadPoolExecutor

import pytensor
import pytensor.tensor as pt

before = pytensor.config.cxx, pytensor.config.optdb__max_use_ratio


def build(_):
    n = pt.lscalar("n")
    for _ in range(500):
        pt.zeros((n + 1,))  # static-shape inference enters change_flags(cxx="")


with ThreadPoolExecutor(8) as executor:
    list(executor.map(build, range(8)))

print(before, (pytensor.config.cxx, pytensor.config.optdb__max_use_ratio))
# ('/usr/bin/g++', 8.0) ('', 10.0)

xs = pt.dvectors(*(f"x{i}" for i in range(33)))
f = pytensor.function(xs, pt.exp(sum(xs)), mode="CVM")
f(*[[0.0]] * 33)
Error message:
NotImplementedError: Elemwise.perform (Python mode) does not support more than 32 operands. Use the C backend or disable Elemwise fusion.
PyTensor version information:

PyTensor 3.3.1 (pip), Python 3.14, Linux x86_64, with g++ as cxx. The same code is on main (332ea8fb7).

Context for the issue:
  • Every C-linked function compiled afterwards in the process silently falls back to Python implementations. Already compiled functions are unaffected.
  • Fused elemwise graphs with more than 32 operands then raise the error above.
  • Python and C implementations differ at rounding level, so seeded results can change without an error, depending on thread timing earlier in the process. I measured differences of about 1e-14 in a downstream PyMC model.

I hit this in a library that fits independent models on worker threads with PyMC. A long-running process lost C compilation after one threaded fit, and an unrelated later computation failed with the error above.

Linguagem predominante
Python
Estrelas
654
Forks
258
Merge médio
3d 41min
PRs com merge (30d)
42

Preparar o ambiente

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de pymc-devs/pytensor

Todas as issues de pymc-devs/pytensor

Issues semelhantes

Mais issues de Python

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.