Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cxx/include/tensorwrapper/operations/operations.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
#include <tensorwrapper/operations/approximately_equal.hpp>
#include <tensorwrapper/operations/norm.hpp>
#include <tensorwrapper/operations/power.hpp>
#include <tensorwrapper/operations/stack.hpp>

/// Namespace for free functions that act on tensors
namespace tensorwrapper::operations {}
55 changes: 55 additions & 0 deletions cxx/include/tensorwrapper/operations/stack.hpp
Original file line number Diff line number Diff line change
@@ -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 <tensorwrapper/tensor/tensor.hpp>
#include <vector>

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<Tensor>& tensors, int axis = 0);

} // namespace tensorwrapper::operations
112 changes: 112 additions & 0 deletions cxx/src/tensorwrapper/operations/stack.cpp
Original file line number Diff line number Diff line change
@@ -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 <algorithm>
#include <tensorwrapper/buffer/contiguous.hpp>
#include <tensorwrapper/operations/stack.hpp>

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<typename FloatType>
void operator()(std::span<FloatType> in) const {
using clean_type = std::remove_const_t<FloatType>;
// Throws if the output (i.e., tensor 0) holds a different type
auto out = buffer::get_raw_data<clean_type>(*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<Tensor>& 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<int>(shape0.rank());
if(axis < -(rank + 1) || axis > rank)
throw std::runtime_error("stack: axis is out of range");
const auto uaxis =
static_cast<size_type>(axis < 0 ? axis + rank + 1 : axis);

const size_type n_tensors = tensors.size();
std::vector<size_type> 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
133 changes: 133 additions & 0 deletions tests/cxx/unit_tests/tensorwrapper/operations/stack.cpp
Original file line number Diff line number Diff line change
@@ -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 <tensorwrapper/operations/approximately_equal.hpp>
#include <tensorwrapper/operations/stack.hpp>
#include <tensorwrapper/utilities/make_tensor.hpp>
#include <testing/testing.hpp>

using namespace tensorwrapper;
using namespace tensorwrapper::operations;

namespace {

// Makes a tensor of FloatType with the given shape and (row-major) values
template<typename FloatType>
Tensor make(std::vector<std::size_t> shape, std::vector<double> values) {
std::vector<FloatType> 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<typename FloatType>
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<FloatType>()));
}

} // namespace

TEMPLATE_LIST_TEST_CASE("stack", "", types::floating_point_types) {
using error_t = std::runtime_error;

SECTION("scalars") {
std::vector<Tensor> ts{make<TestType>({}, {1.0}),
make<TestType>({}, {2.0}),
make<TestType>({}, {3.0})};
auto corr = make<TestType>({3}, {1.0, 2.0, 3.0});
check<TestType>(stack(ts), corr);
check<TestType>(stack(ts, -1), corr);
REQUIRE_THROWS_AS(stack(ts, 1), error_t);
REQUIRE_THROWS_AS(stack(ts, -2), error_t);
}

SECTION("vectors") {
std::vector<Tensor> ts{make<TestType>({3}, {0.0, 1.0, 2.0}),
make<TestType>({3}, {3.0, 4.0, 5.0})};

auto corr0 = make<TestType>({2, 3}, {0.0, 1.0, 2.0, 3.0, 4.0, 5.0});
check<TestType>(stack(ts), corr0);
check<TestType>(stack(ts, 0), corr0);
check<TestType>(stack(ts, -2), corr0);

auto corr1 = make<TestType>({3, 2}, {0.0, 3.0, 1.0, 4.0, 2.0, 5.0});
check<TestType>(stack(ts, 1), corr1);
check<TestType>(stack(ts, -1), corr1);

REQUIRE_THROWS_AS(stack(ts, 2), error_t);
REQUIRE_THROWS_AS(stack(ts, -3), error_t);
}

SECTION("matrices") {
std::vector<Tensor> ts{
make<TestType>({2, 3}, {0.0, 1.0, 2.0, 3.0, 4.0, 5.0}),
make<TestType>({2, 3}, {6.0, 7.0, 8.0, 9.0, 10.0, 11.0})};

auto corr0 =
make<TestType>({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<TestType>(stack(ts, 0), corr0);
check<TestType>(stack(ts, -3), corr0);

auto corr1 =
make<TestType>({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<TestType>(stack(ts, 1), corr1);
check<TestType>(stack(ts, -2), corr1);

auto corr2 =
make<TestType>({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<TestType>(stack(ts, 2), corr2);
check<TestType>(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<Tensor> ts{make<TestType>({3}, {0.0, 1.0, 2.0})};
check<TestType>(stack(ts, 0), make<TestType>({1, 3}, {0.0, 1.0, 2.0}));
check<TestType>(stack(ts, 1), make<TestType>({3, 1}, {0.0, 1.0, 2.0}));
}

SECTION("empty input") {
REQUIRE_THROWS_AS(stack(std::vector<Tensor>{}), error_t);
}

SECTION("different shapes") {
std::vector<Tensor> ts{make<TestType>({3}, {0.0, 1.0, 2.0}),
make<TestType>({2}, {3.0, 4.0})};
REQUIRE_THROWS_AS(stack(ts), error_t);
}

SECTION("different ranks") {
std::vector<Tensor> ts{make<TestType>({2}, {0.0, 1.0}),
make<TestType>({2, 1}, {2.0, 3.0})};
REQUIRE_THROWS_AS(stack(ts), error_t);
}
}

TEST_CASE("stack: different floating-point types") {
std::vector<Tensor> ts{make<float>({2}, {0.0, 1.0}),
make<double>({2}, {2.0, 3.0})};
REQUIRE_THROWS_AS(stack(ts), std::runtime_error);
}
Loading