BUG: cumsum and cumprod keep bool and small integer dtypes, so cumsum(x > 0) is wrong

Abierto Apto para principiantes
#2,727 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

@rishabhsai ya está trabajando en esto.

Desde el 26/11/2026.

  • #2728 de @rishabhsai — abierto

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
76/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
numpy, python
Área
backend, data

Línea de trabajo

El issue apunta a CumOp.make_node en pytensor/tensor/extra_ops.py y describe diferencias entre el código C, los kernels de Numba y perform. Empieza leyendo CumOp y las pruebas correspondientes de operaciones acumulativas; después, compara los resultados para entradas bool y enteras pequeñas en los distintos backends. Se considera terminado cuando las salidas usan el tipo de dato de acumulación esperado y coinciden en los ejemplos reportados.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

Describe the issue:

pt.cumsum and pt.cumprod give the result the input's dtype. NumPy and pt.sum accumulate bool and small integers in int64 (uint64 for unsigned), so a running count over a mask comes out wrong. In the default (Numba) mode pt.cumsum(x > 0, axis=1) is all True, and pt.cumsum(x > 0).max() returns True instead of 3. The C backend also wraps int8 totals.

The output type comes from CumOp.make_node (return Apply(self, [x], [x.type()]) in pytensor/tensor/extra_ops.py). The C code and the Numba kernels for ndim > 1 accumulate in the input dtype, while perform and the 1-d Numba kernel call np.cumsum, which upcasts and returns int64 data for a variable typed bool or int8. So the backends disagree with each other as well as with NumPy.

Reproducible code example:
import numpy as np
import pytensor
import pytensor.tensor as pt

x = pt.matrix("x")
n = pt.cumsum(x > 0, axis=1)
v = np.array([[1.0, 2.0, -1.0, 3.0]])

print(n.dtype)
print(pytensor.function([x], n)(v), np.cumsum(v > 0, axis=1))
print(pytensor.function([x], n.max())(v), np.cumsum(v > 0, axis=1).max())

i = pt.vector("i", dtype="int8")
c_mode = pytensor.compile.mode.Mode(linker="cvm", optimizer="fast_run")
print(pytensor.function([i], pt.cumsum(i), mode=c_mode)(np.array([100, 100, 2], dtype="int8")))
Error message:
bool
[[ True  True  True  True]] [[1 2 2 3]]
True 3
[100 -56 -54]
PyTensor version information:

main at e213406 (3.3.8+65), NumPy 2.5.5, Numba 0.68.1, Python 3.12.7, macOS arm64

Context for the issue:

cumsum(mask) is a common way to number the selected entries. Casting these inputs to int64/uint64 in cumsum/cumprod, with the same mapping Sum uses, fixes it for every backend. I have that change with a test and can open a PR.

Lenguaje dominante
Python
Estrellas
654
Forks
258
Merge medio
3 d 17 h
PR fusionados (30 d)
43

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de pymc-devs/pytensor

Todos los issues de pymc-devs/pytensor

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.