From ed0d90746e1fc86f0ca46e6ab28baf3abde7f2f0 Mon Sep 17 00:00:00 2001 From: "Ryan M. Richard" Date: Mon, 23 Nov 2026 09:55:17 -0600 Subject: [PATCH] adds a stack function --- .../tensorwrapper/operations/operations.hpp | 1 + .../tensorwrapper/operations/stack.hpp | 55 ++++++++ cxx/src/tensorwrapper/operations/stack.cpp | 112 +++++++++++++++ .../tensorwrapper/operations/stack.cpp | 133 ++++++++++++++++++ 4 files changed, 301 insertions(+) create mode 100644 cxx/include/tensorwrapper/operations/stack.hpp create mode 100644 cxx/src/tensorwrapper/operations/stack.cpp create mode 100644 tests/cxx/unit_tests/tensorwrapper/operations/stack.cpp diff --git a/cxx/include/tensorwrapper/operations/operations.hpp b/cxx/include/tensorwrapper/operations/operations.hpp index 0b9854a1..bca232f7 100644 --- a/cxx/include/tensorwrapper/operations/operations.hpp +++ b/cxx/include/tensorwrapper/operations/operations.hpp @@ -18,6 +18,7 @@ #include #include #include +#include /// Namespace for free functions that act on tensors namespace tensorwrapper::operations {} diff --git a/cxx/include/tensorwrapper/operations/stack.hpp b/cxx/include/tensorwrapper/operations/stack.hpp new file mode 100644 index 00000000..84e9c705 --- /dev/null +++ b/cxx/include/tensorwrapper/operations/stack.hpp @@ -0,0 +1,55 @@ +/* + * Copyright 2026 NWChemEx-Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once +#include +#include + +namespace tensorwrapper::operations { + +/** @brief Joins a series of same-shaped tensors along a new mode. + * + * This function is modeled after `numpy.stack`. Given @f$N@f$ tensors, each + * with rank @f$r@f$ and shape @f$s@f$, the result is a rank @f$r+1@f$ tensor + * whose shape is @f$s@f$ with an extent of @f$N@f$ inserted at mode + * @p axis, i.e., `s[:axis] + [N] + s[axis:]` in Python notation. Fixing the + * index of the new mode to @f$k@f$ yields the @f$k@f$-th input tensor. + * + * For example, stacking two vectors of length 3 with @p axis equal to 0 + * yields a 2 by 3 matrix whose rows are the vectors, whereas @p axis equal + * to 1 yields a 3 by 2 matrix whose columns are the vectors. + * + * Like `numpy.stack`, @p axis may be negative, in which case it counts from + * the end of the result's modes (e.g., -1 makes the new mode the last mode). + * Unlike `numpy.stack`, no type promotion occurs; all tensors must hold the + * same floating-point type. + * + * @param[in] tensors The tensors to stack. Must be non-empty and every tensor + * must have the same shape and floating-point type. + * @param[in] axis The mode of the result along which the tensors are + * stacked. Must be in the range [-(r+1), r]. Defaults to 0. + * + * @return A new tensor containing the stacked tensors. + * + * @throw std::runtime_error if @p tensors is empty, if the tensors do not + * all have the same shape, if @p axis is out of + * range, if the tensors do not all hold the same + * floating-point type, or if any tensor's buffer + * is not contiguous. Strong throw guarantee. + */ +Tensor stack(const std::vector& tensors, int axis = 0); + +} // namespace tensorwrapper::operations diff --git a/cxx/src/tensorwrapper/operations/stack.cpp b/cxx/src/tensorwrapper/operations/stack.cpp new file mode 100644 index 00000000..8e0961ed --- /dev/null +++ b/cxx/src/tensorwrapper/operations/stack.cpp @@ -0,0 +1,112 @@ +/* + * Copyright 2026 NWChemEx-Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +namespace tensorwrapper::operations { +namespace { + +/* Copies one input tensor into its slot of the stacked output. + * + * In row-major order the input is @p outer contiguous blocks of @p inner + * elements. Block o of input k lands at block (o * n_tensors + k) of the + * output. + */ +class StackKernel { +public: + using size_type = std::size_t; + + StackKernel(buffer::Contiguous& out, size_type k, size_type n_tensors, + size_type outer, size_type inner) : + m_pout_(&out), + m_k_(k), + m_n_tensors_(n_tensors), + m_outer_(outer), + m_inner_(inner) {} + + template + void operator()(std::span in) const { + using clean_type = std::remove_const_t; + // Throws if the output (i.e., tensor 0) holds a different type + auto out = buffer::get_raw_data(*m_pout_); + for(size_type o = 0; o < m_outer_; ++o) { + auto in_begin = in.begin() + o * m_inner_; + auto offset = (o * m_n_tensors_ + m_k_) * m_inner_; + std::copy(in_begin, in_begin + m_inner_, out.begin() + offset); + } + } + +private: + buffer::Contiguous* m_pout_; + size_type m_k_; + size_type m_n_tensors_; + size_type m_outer_; + size_type m_inner_; +}; + +} // namespace + +Tensor stack(const std::vector& tensors, int axis) { + using size_type = std::size_t; + + if(tensors.empty()) + throw std::runtime_error("stack: need at least one tensor to stack"); + + const auto& buffer0 = buffer::make_contiguous(tensors.front().buffer()); + const auto shape0 = buffer0.shape(); + for(const auto& t : tensors) { + if(buffer::make_contiguous(t.buffer()).shape() != shape0) + throw std::runtime_error( + "stack: all input tensors must have the same shape"); + } + + // N.b. rank is the rank of the input tensors. The output tensor has + // rank + 1. axis will be the rank of the output tensor. + const int rank = static_cast(shape0.rank()); + if(axis < -(rank + 1) || axis > rank) + throw std::runtime_error("stack: axis is out of range"); + const auto uaxis = + static_cast(axis < 0 ? axis + rank + 1 : axis); + + const size_type n_tensors = tensors.size(); + std::vector extents; + size_type outer = 1; + size_type inner = 1; + for(size_type i = 0; i < shape0.rank(); ++i) { + if(i == uaxis) extents.push_back(n_tensors); + extents.push_back(shape0.extent(i)); + if(i < uaxis) + outer *= shape0.extent(i); + else + inner *= shape0.extent(i); + } + if(uaxis == shape0.rank()) extents.push_back(n_tensors); + + shape::Smooth out_shape(extents.begin(), extents.end()); + auto out_buffer = buffer::make_contiguous(buffer0, out_shape); + + for(size_type k = 0; k < n_tensors; ++k) { + StackKernel kernel(out_buffer, k, n_tensors, outer, inner); + const auto& buffer_k = buffer::make_contiguous(tensors[k].buffer()); + buffer::visit_contiguous_buffer(kernel, buffer_k); + } + + return Tensor(std::move(out_shape), std::move(out_buffer)); +} + +} // namespace tensorwrapper::operations diff --git a/tests/cxx/unit_tests/tensorwrapper/operations/stack.cpp b/tests/cxx/unit_tests/tensorwrapper/operations/stack.cpp new file mode 100644 index 00000000..5a25fde7 --- /dev/null +++ b/tests/cxx/unit_tests/tensorwrapper/operations/stack.cpp @@ -0,0 +1,133 @@ +/* + * Copyright 2026 NWChemEx-Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +using namespace tensorwrapper; +using namespace tensorwrapper::operations; + +namespace { + +// Makes a tensor of FloatType with the given shape and (row-major) values +template +Tensor make(std::vector shape, std::vector values) { + std::vector data; + for(auto v : values) data.push_back(FloatType(v)); + return tensorwrapper::utilities::make_tensor(shape, data.begin(), + data.end()); +} + +// Checks that rv has the same shape as corr and the same elements +template +void check(const Tensor& rv, const Tensor& corr) { + const auto& rv_buffer = buffer::make_contiguous(rv.buffer()); + const auto& corr_buffer = buffer::make_contiguous(corr.buffer()); + REQUIRE(rv_buffer.shape() == corr_buffer.shape()); + REQUIRE( + approximately_equal(rv, corr, testing::default_tolerance())); +} + +} // namespace + +TEMPLATE_LIST_TEST_CASE("stack", "", types::floating_point_types) { + using error_t = std::runtime_error; + + SECTION("scalars") { + std::vector ts{make({}, {1.0}), + make({}, {2.0}), + make({}, {3.0})}; + auto corr = make({3}, {1.0, 2.0, 3.0}); + check(stack(ts), corr); + check(stack(ts, -1), corr); + REQUIRE_THROWS_AS(stack(ts, 1), error_t); + REQUIRE_THROWS_AS(stack(ts, -2), error_t); + } + + SECTION("vectors") { + std::vector ts{make({3}, {0.0, 1.0, 2.0}), + make({3}, {3.0, 4.0, 5.0})}; + + auto corr0 = make({2, 3}, {0.0, 1.0, 2.0, 3.0, 4.0, 5.0}); + check(stack(ts), corr0); + check(stack(ts, 0), corr0); + check(stack(ts, -2), corr0); + + auto corr1 = make({3, 2}, {0.0, 3.0, 1.0, 4.0, 2.0, 5.0}); + check(stack(ts, 1), corr1); + check(stack(ts, -1), corr1); + + REQUIRE_THROWS_AS(stack(ts, 2), error_t); + REQUIRE_THROWS_AS(stack(ts, -3), error_t); + } + + SECTION("matrices") { + std::vector ts{ + make({2, 3}, {0.0, 1.0, 2.0, 3.0, 4.0, 5.0}), + make({2, 3}, {6.0, 7.0, 8.0, 9.0, 10.0, 11.0})}; + + auto corr0 = + make({2, 2, 3}, {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, + 8.0, 9.0, 10.0, 11.0}); + check(stack(ts, 0), corr0); + check(stack(ts, -3), corr0); + + auto corr1 = + make({2, 2, 3}, {0.0, 1.0, 2.0, 6.0, 7.0, 8.0, 3.0, 4.0, + 5.0, 9.0, 10.0, 11.0}); + check(stack(ts, 1), corr1); + check(stack(ts, -2), corr1); + + auto corr2 = + make({2, 3, 2}, {0.0, 6.0, 1.0, 7.0, 2.0, 8.0, 3.0, 9.0, + 4.0, 10.0, 5.0, 11.0}); + check(stack(ts, 2), corr2); + check(stack(ts, -1), corr2); + + REQUIRE_THROWS_AS(stack(ts, 3), error_t); + REQUIRE_THROWS_AS(stack(ts, -4), error_t); + } + + SECTION("single tensor") { + std::vector ts{make({3}, {0.0, 1.0, 2.0})}; + check(stack(ts, 0), make({1, 3}, {0.0, 1.0, 2.0})); + check(stack(ts, 1), make({3, 1}, {0.0, 1.0, 2.0})); + } + + SECTION("empty input") { + REQUIRE_THROWS_AS(stack(std::vector{}), error_t); + } + + SECTION("different shapes") { + std::vector ts{make({3}, {0.0, 1.0, 2.0}), + make({2}, {3.0, 4.0})}; + REQUIRE_THROWS_AS(stack(ts), error_t); + } + + SECTION("different ranks") { + std::vector ts{make({2}, {0.0, 1.0}), + make({2, 1}, {2.0, 3.0})}; + REQUIRE_THROWS_AS(stack(ts), error_t); + } +} + +TEST_CASE("stack: different floating-point types") { + std::vector ts{make({2}, {0.0, 1.0}), + make({2}, {2.0, 3.0})}; + REQUIRE_THROWS_AS(stack(ts), std::runtime_error); +}