arXiv:2609.08088cs.CLcs.SE2026-09

自动将NumPy循环代码转为高效向量化代码,提升运行速度74倍以上。

Vectorizer: Vectorizing NumPy Programs with Shape-Guided Rewrite

  • 基于数组形状和数据流分析,从内到外重写循环体为向量化操作
  • 在150个测试用例中成功转化144个,平均耗时仅0.53秒,提速74.83倍
  • 适合不熟悉NumPy向量化但需高效数值计算的开发者使用

NumPy是广泛使用的Python数值计算库,以其声明式API和优化实现著称。然而,编写高效的NumPy程序(如使用向量化数组操作而非显式Python循环)对习惯于命令式数组遍历的程序员来说可能并不直观,尤其当涉及形状、广播和高级索引时。本文提出一种基于重写的向量化方法,通过数组形状和数据流分析,指导源代码到源代码的转换,将循环体替换为向量化语句。该方法遵循构造上正确的重写规则,始终快速高效。我们实现了名为Vectorizer的工具,并在150个来自先前工作和Stack Overflow的基准测试上进行评估。结果表明,Vectorizer可直接向量化142个基准,另有2个经轻微修改后成功转化,平均每个用例耗时0.53秒,生成代码相较原循环实现平均快74.83倍。

原文摘要 · Abstract (English)

NumPy is a widely used Python library for numerical scientific computing, known for its declarative APIs and its optimized implementations. However, writing efficient NumPy programs, which often entails using vectorized array operations instead of explicit Python loops, may not be straightforward. This can be difficult for programmers who are accustomed to imperative array traversal, especially when vectorized API invocations require careful reasoning about shapes, broadcasting, and advanced indexing. This paper presents a rewrite-based approach for vectorizing Numpy programs with explicit loops over array data. Our approach vectorizes loops from the inside out, using array shapes and dataflow analysis to guide a source-to-source transformation that replaces loop bodies with vectorized statements. Following a set of rewrite rules that are correct by construction, our approach is consistently fast. We have implemented the approach as a tool called Vectorizer and evaluated it on 150 benchmarks collected from prior work and Stack Overflow. The evaluation shows that Vectorizer vectorizes 142 of the 150 benchmarks directly and 2 more after minor changes to the original benchmarks, with only 0.53 seconds on average to rewrite each one. The resulting programs are, on average, 74.83x faster than the original loop-based implementations.

NumPy代码优化向量化自动重构

Thank you to arXiv for use of its open access interoperability. PaperDance 不是 arXiv 官方产品;中文卡片由大模型生成,请以原文为准。