Skip to content
项目
群组
代码片段
帮助
当前项目
正在载入...
登录 / 注册
切换导航面板
P
pytensor
项目
项目
详情
活动
周期分析
仓库
仓库
文件
提交
分支
标签
贡献者
图表
比较
统计图
议题
0
议题
0
列表
看板
标记
里程碑
合并请求
0
合并请求
0
CI / CD
CI / CD
流水线
作业
日程
统计图
Wiki
Wiki
代码片段
代码片段
成员
成员
折叠边栏
关闭边栏
活动
图像
聊天
创建新问题
作业
提交
问题看板
Open sidebar
testgroup
pytensor
Commits
911c6a33
提交
911c6a33
authored
1月 27, 2025
作者:
Ricardo Vieira
提交者:
Ricardo Vieira
1月 28, 2025
浏览文件
操作
浏览文件
下载
电子邮件补丁
差异文件
Rewrite batched dots that do not reduce as multiplication
上级
f86a0dc1
隐藏空白字符变更
内嵌
并排
正在显示
3 个修改的文件
包含
146 行增加
和
9 行删除
+146
-9
math.py
pytensor/tensor/math.py
+34
-8
math.py
pytensor/tensor/rewriting/math.py
+60
-0
test_math.py
tests/tensor/rewriting/test_math.py
+52
-1
没有找到文件。
pytensor/tensor/math.py
浏览文件 @
911c6a33
...
@@ -29,7 +29,7 @@ from pytensor.tensor.basic import (
...
@@ -29,7 +29,7 @@ from pytensor.tensor.basic import (
stack
,
stack
,
switch
,
switch
,
)
)
from
pytensor.tensor.blockwise
import
Blockwise
,
vectorize_node_fallback
from
pytensor.tensor.blockwise
import
Blockwise
from
pytensor.tensor.elemwise
import
(
from
pytensor.tensor.elemwise
import
(
CAReduce
,
CAReduce
,
Elemwise
,
Elemwise
,
...
@@ -2726,6 +2726,22 @@ def logsumexp(x, axis=None, keepdims=False):
...
@@ -2726,6 +2726,22 @@ def logsumexp(x, axis=None, keepdims=False):
return
log
(
sum
(
exp
(
x
),
axis
=
axis
,
keepdims
=
keepdims
))
return
log
(
sum
(
exp
(
x
),
axis
=
axis
,
keepdims
=
keepdims
))
# Predefine all batched variations of Dot
_inner_prod
=
Blockwise
(
_dot
,
signature
=
"(n),(n)->()"
,
)
_matrix_vec_prod
=
Blockwise
(
_dot
,
signature
=
"(m,k),(k)->(m)"
,
)
_vec_matrix_prod
=
Blockwise
(
_dot
,
signature
=
"(k),(k,n)->(n)"
,
)
_matrix_matrix_matmul
=
Blockwise
(
_matrix_matrix_matmul
=
Blockwise
(
_dot
,
_dot
,
signature
=
"(m,k),(k,n)->(m,n)"
,
signature
=
"(m,k),(k,n)->(m,n)"
,
...
@@ -2795,14 +2811,24 @@ def matmul(x1: "ArrayLike", x2: "ArrayLike", dtype: Optional["DTypeLike"] = None
...
@@ -2795,14 +2811,24 @@ def matmul(x1: "ArrayLike", x2: "ArrayLike", dtype: Optional["DTypeLike"] = None
@_vectorize_node.register
(
Dot
)
@_vectorize_node.register
(
Dot
)
def
vectorize_node_dot
_to_matmul
(
op
,
node
,
batched_x
,
batched_y
):
def
vectorize_node_dot
(
op
,
node
,
batched_x
,
batched_y
):
old_x
,
old_y
=
node
.
inputs
old_x
,
old_y
=
node
.
inputs
if
old_x
.
type
.
ndim
==
2
and
old_y
.
type
.
ndim
==
2
:
old_x_ndim
=
old_x
.
type
.
ndim
# If original input is equivalent to a matrix-matrix product,
old_y_ndim
=
old_y
.
type
.
ndim
# return specialized Matmul Op to avoid unnecessary new Ops.
match
(
old_x_ndim
,
old_y_ndim
):
return
matmul
(
batched_x
,
batched_y
)
.
owner
case
(
1
,
1
):
else
:
batch_op
=
_inner_prod
return
vectorize_node_fallback
(
op
,
node
,
batched_x
,
batched_y
)
case
(
2
,
1
):
batch_op
=
_matrix_vec_prod
case
(
1
,
2
):
batch_op
=
_vec_matrix_prod
case
(
2
,
2
):
batch_op
=
_matrix_matrix_matmul
case
_
:
raise
ValueError
(
f
"Core dot Op should have 1D or 2D inputs, got {old_x_ndim}D and {old_y_ndim}D."
)
return
batch_op
(
batched_x
,
batched_y
)
.
owner
def
nan_to_num
(
x
,
nan
=
0.0
,
posinf
=
None
,
neginf
=
None
):
def
nan_to_num
(
x
,
nan
=
0.0
,
posinf
=
None
,
neginf
=
None
):
...
...
pytensor/tensor/rewriting/math.py
浏览文件 @
911c6a33
...
@@ -44,6 +44,10 @@ from pytensor.tensor.math import (
...
@@ -44,6 +44,10 @@ from pytensor.tensor.math import (
Prod
,
Prod
,
Sum
,
Sum
,
_conj
,
_conj
,
_inner_prod
,
_matrix_matrix_matmul
,
_matrix_vec_prod
,
_vec_matrix_prod
,
add
,
add
,
digamma
,
digamma
,
dot
,
dot
,
...
@@ -242,6 +246,62 @@ def local_batched_matmul_to_core_matmul(fgraph, node):
...
@@ -242,6 +246,62 @@ def local_batched_matmul_to_core_matmul(fgraph, node):
return
None
return
None
@register_canonicalize
@register_specialize
@node_rewriter
([
_inner_prod
,
_matrix_vec_prod
,
_vec_matrix_prod
,
_matrix_matrix_matmul
])
def
local_blockwise_dot_to_mul
(
fgraph
,
node
):
"""Rewrite blockwise dots that correspond to multiplication without summation.
We don't touch the regular dot, to not interfere with the BLAS optimizations.
"""
a
,
b
=
node
.
inputs
a_static_shape
=
a
.
type
.
shape
b_static_shape
=
b
.
type
.
shape
core_a_ndim
=
len
(
node
.
op
.
inputs_sig
[
0
])
core_b_ndim
=
len
(
node
.
op
.
inputs_sig
[
1
])
if
core_a_ndim
>
2
or
core_b_ndim
>
2
:
# Shouldn't happen, but here just in case
return
None
if
core_b_ndim
==
1
:
if
a_static_shape
[
-
1
]
==
1
or
b_static_shape
[
-
1
]
==
1
:
if
core_a_ndim
==
1
:
# inner product: (..., 1) * (..., 1) -> (...)
# just squeeze the last dimensions of a and b
new_a
=
a
.
squeeze
(
-
1
)
new_b
=
b
.
squeeze
(
-
1
)
else
:
# matrix vector product: (..., m, 1) * (..., 1) -> (..., m)
# the last dimension of b is already aligned for the elemwise multiplication
# after we squeeze the last dimension of a
new_a
=
a
.
squeeze
(
-
1
)
new_b
=
b
else
:
return
None
else
:
if
a_static_shape
[
-
1
]
==
1
or
b_static_shape
[
-
2
]
==
1
:
if
core_a_ndim
==
1
:
# vector_matrix product: (..., 1) * (..., 1, n) -> (..., n)
# the last dimension of a is already aligned for the elemwise multiplication
# after we squeeze the one to last dimension of b
new_a
=
a
new_b
=
b
.
squeeze
(
-
2
)
else
:
# matrix matrix product: (..., m, 1) * (..., 1, n) -> (..., m, n)
# the dimensions of a and b are already aligned for the elemwise multiplication
new_a
=
a
new_b
=
b
else
:
return
None
new_a
=
copy_stack_trace
(
a
,
new_a
)
new_b
=
copy_stack_trace
(
b
,
new_b
)
new_out
=
copy_stack_trace
(
node
.
out
,
mul
(
new_a
,
new_b
))
return
[
new_out
]
def
is_inverse_pair
(
node_op
,
prev_op
,
inv_pair
):
def
is_inverse_pair
(
node_op
,
prev_op
,
inv_pair
):
"""
"""
Given two consecutive operations, check if they are the
Given two consecutive operations, check if they are the
...
...
tests/tensor/rewriting/test_math.py
浏览文件 @
911c6a33
...
@@ -16,7 +16,8 @@ from pytensor.compile.function import function
...
@@ -16,7 +16,8 @@ from pytensor.compile.function import function
from
pytensor.compile.mode
import
Mode
,
get_default_mode
,
get_mode
from
pytensor.compile.mode
import
Mode
,
get_default_mode
,
get_mode
from
pytensor.compile.ops
import
DeepCopyOp
,
deep_copy_op
from
pytensor.compile.ops
import
DeepCopyOp
,
deep_copy_op
from
pytensor.configdefaults
import
config
from
pytensor.configdefaults
import
config
from
pytensor.graph.basic
import
Apply
,
equal_computations
from
pytensor.graph
import
vectorize_graph
from
pytensor.graph.basic
import
Apply
,
ancestors
,
equal_computations
from
pytensor.graph.fg
import
FunctionGraph
from
pytensor.graph.fg
import
FunctionGraph
from
pytensor.graph.rewriting.basic
import
(
from
pytensor.graph.rewriting.basic
import
(
SequentialNodeRewriter
,
SequentialNodeRewriter
,
...
@@ -4590,3 +4591,53 @@ def test_pow_1_rewrite(shape):
...
@@ -4590,3 +4591,53 @@ def test_pow_1_rewrite(shape):
x_val
=
np
.
random
.
random
(
shape
)
.
astype
(
config
.
floatX
)
x_val
=
np
.
random
.
random
(
shape
)
.
astype
(
config
.
floatX
)
np
.
testing
.
assert_allclose
(
z
.
eval
({
x
:
x_val
}),
f
(
x_val
))
np
.
testing
.
assert_allclose
(
z
.
eval
({
x
:
x_val
}),
f
(
x_val
))
@pytest.mark.parametrize
(
"a_shape,b_shape"
,
[
((
1
,),
(
1
,)),
((
3
,
1
),
(
1
,)),
((
1
,),
(
1
,
3
)),
((
3
,
1
),
(
1
,
3
)),
],
ids
=
str
,
)
@pytest.mark.parametrize
(
"batched"
,
(
False
,
True
))
def
test_local_dot_to_mul
(
batched
,
a_shape
,
b_shape
):
a
=
tensor
(
"a"
,
shape
=
a_shape
)
b
=
tensor
(
"b"
,
shape
=
b_shape
)
out
=
dot
(
a
,
b
)
if
batched
:
batch_a
=
tensor
(
"batch_a"
,
shape
=
(
1
,
5
,
*
a_shape
))
batch_b
=
tensor
(
"batch_b"
,
shape
=
(
7
,
1
,
*
b_shape
))
out
=
vectorize_graph
(
out
,
{
a
:
batch_a
,
b
:
batch_b
})
a
=
batch_a
b
=
batch_b
assert
(
sum
(
isinstance
(
var
.
owner
.
op
,
(
Blockwise
|
Dot
))
for
var
in
ancestors
([
out
])
if
var
.
owner
)
==
1
)
# For now rewrite only applies to Batched Dots
rewritten_out
=
rewrite_graph
(
out
)
assert
rewritten_out
.
type
.
shape
==
out
.
type
.
shape
assert
sum
(
isinstance
(
var
.
owner
.
op
,
(
Blockwise
|
Dot
))
for
var
in
ancestors
([
rewritten_out
])
if
var
.
owner
)
==
(
0
if
batched
else
1
)
a_test
=
np
.
random
.
normal
(
size
=
a
.
type
.
shape
)
.
astype
(
a
.
type
.
dtype
)
b_test
=
np
.
random
.
normal
(
size
=
b
.
type
.
shape
)
.
astype
(
b
.
type
.
dtype
)
test_mode
=
Mode
(
linker
=
"py"
,
optimizer
=
None
)
np
.
testing
.
assert_allclose
(
out
.
eval
({
a
:
a_test
,
b
:
b_test
},
mode
=
test_mode
),
rewritten_out
.
eval
({
a
:
a_test
,
b
:
b_test
},
mode
=
test_mode
),
)
编写
预览
Markdown
格式
0%
重试
或
添加新文件
添加附件
取消
您添加了
0
人
到此讨论。请谨慎行事。
请先完成此评论的编辑!
取消
请
注册
或者
登录
后发表评论