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

未关闭 适合新手
#2,727 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

@rishabhsai 已经在做这个了。

开始于 2026年11月26日。

  • #2728 来自 @rishabhsai —— 未关闭

评估

难度
2/5
预计耗时
1-3 小时
新手友好度
76/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
numpy, python
领域
backend, data

调研方向

该 issue 指向 pytensor/tensor/extra_ops.py 中的 CumOp.make_node,并描述了 C 代码、Numba 内核和 perform 之间的差异。先阅读 CumOp 和相应的累积操作测试,然后比较 bool 和小整数输入在各个后端上的结果。完成标准是:输出使用预期的累积 dtype,并且在报告的示例中结果一致。

由索引模型根据 Issue 内容生成。

描述

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.

主要语言
Python
星标
654
派生
258
平均合并
3 天 17 小时
30 天内合并 PR
43

环境准备

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

pymc-devs/pytensor 的其他 Issue

查看 pymc-devs/pytensor 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。