`as_tensor_variable` / `constant` ignore `floatX` for lists and tuples of Python floats

未关闭
#2,689 3 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

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

调研方向

Start in pytensor/scalar/basic.py at ps.convert, then inspect the sequence branch and autocast_float to understand how floatX and cast_policy="numpy+floatX" apply. Run the scalar and core tensor tests under both floatX settings, as described in the issue. Done means lists and tuples of Python floats follow the configured policy while arrays and NumPy scalars keep their dtype; check the behavior for NumPy scalars inside sequences.

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

描述

Description

With floatX="float32", a Python float scalar is autocast to floatX, but a list or tuple of Python floats is not. It comes out as float64.

import numpy as np
import pytensor
import pytensor.tensor as pt

pytensor.config.floatX = "float32"

pt.as_tensor_variable(1.0).dtype             # float32
pt.as_tensor_variable([1.0, 2.0]).dtype      # float64  <- surprising
pt.as_tensor_variable((1.0, 2.0)).dtype      # float64  <- surprising
pt.as_tensor_variable(np.array([1.0, 2.0])).dtype  # float64 (expected, array has its own dtype)
pt.as_tensor_variable([]).dtype              # float32 (empty list already uses floatX)

Cause

ps.convert (pytensor/scalar/basic.py) sends Python float through autocast_float, which respects floatX under the default cast_policy="numpy+floatX". Lists and tuples fall into the final else branch, which only calls np.asarray(x). NumPy infers float64 and nothing downcasts it. The only special case there is the empty one (x_.size == 0), which already uses floatX.

Why it matters

A list of Python floats has no dtype of its own, so it is just as untyped as a bare 1.0. The two paths disagree, and the list/tuple path can silently upcast a float32 graph to float64.

Related

#1073 and #1913 cover the same problem for scalars under the custom cast policy. This is the same gap for lists and tuples.

Proposed fix

Under cast_policy="numpy+floatX", have the sequence branch of ps.convert cast a float64 result to floatX when the input has no dtype attribute. Arrays and numpy scalars keep their dtype. A prototype passes the scalar and core tensor tests under both floatX settings. I haven't run the full suite.

Open question: should a list containing numpy float64 scalars, e.g. [np.float64(1.), 2.], also be downcast? The list has no .dtype, so the prototype would downcast it.

Workaround

pt.as_tensor_variable(x, dtype="floatX")

主要语言
Python
星标
654
派生
258
平均合并
3 天 41 分钟
30 天内合并 PR
42

环境准备

从这里开始

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

pymc-devs/pytensor 的其他 Issue

查看 pymc-devs/pytensor 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

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