提交 7a0ea76e authored 作者: ricardoV94's avatar ricardoV94 提交者: Ricardo Vieira

Wrap literal constants in parenthesis in c-impl of ScalarOps

上级 718b1f72
......@@ -4349,7 +4349,7 @@ class Composite(ScalarInnerGraphOp):
if var not in self.fgraph.inputs:
# This is an orphan
if isinstance(var, Constant) and isinstance(var.type, CLinkerType):
subd[var] = var.type.c_literal(var.data)
subd[var] = f"({var.type.c_literal(var.data)})"
else:
raise ValueError(
"All orphans in the fgraph to Composite must"
......@@ -4408,7 +4408,7 @@ class Composite(ScalarInnerGraphOp):
return self.c_code_template % d
def c_code_cache_version_outer(self) -> tuple[int, ...]:
return (4,)
return (5,)
class Compositef32:
......
......@@ -239,7 +239,7 @@ class ScalarLoop(ScalarInnerGraphOp):
if var not in self.fgraph.inputs:
# This is an orphan
if isinstance(var, Constant) and isinstance(var.type, CLinkerType):
subd[var] = var.type.c_literal(var.data)
subd[var] = f"({var.type.c_literal(var.data)})"
else:
raise ValueError(
"All orphans in the fgraph to ScalarLoop must"
......@@ -342,4 +342,4 @@ class ScalarLoop(ScalarInnerGraphOp):
return res
def c_code_cache_version_outer(self):
return (2,)
return (3,)
......@@ -36,6 +36,7 @@ from pytensor.scalar.basic import (
floats,
int8,
int32,
int64,
ints,
invert,
log,
......@@ -44,6 +45,7 @@ from pytensor.scalar.basic import (
log10,
mean,
mul,
neg,
neq,
rad2deg,
reciprocal,
......@@ -156,6 +158,21 @@ class TestComposite:
(literal_value + test_y) * (test_x / test_y),
)
def test_negative_constant(self):
# Test that a negative constant is wrapped in parentheses to avoid confusing - (unary minus) and -- (decrement)
x = int64("x")
e = neg(constant(-1.5)) % x
comp_op = Composite([x], [e])
comp_node = comp_op.make_node(x)
c_code = comp_node.op.c_code(comp_node, "dummy", ["x", "y"], ["z"], dict(id=0))
assert "-1.5" in c_code
g = FunctionGraph([x], [comp_node.out])
fn = make_function(DualLinker().accept(g))
assert fn(2) == 1.5
assert fn(1) == 0.5
def test_many_outputs(self):
x, y, z = floats("xyz")
e0 = x + y + z
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论