Line data Source code
1 : // SPDX-License-Identifier: Apache-2.0
2 : /**
3 : * Copyright (C) 2025 Sumon Nath <sumon.nath@samsung.com>
4 : *
5 : * @file reduce_sum_layer.cpp
6 : * @date 24 July 2025
7 : * @see https://github.com/nnstreamer/nntrainer
8 : * @author Sumon Nath <sumon.nath@samsung.com>
9 : * @bug No known bugs except for NYI items
10 : * @brief This is Reduce Sum Layer Class for Neural Network
11 : */
12 :
13 : #include <layer_context.h>
14 : #include <nntrainer_error.h>
15 : #include <nntrainer_log.h>
16 : #include <node_exporter.h>
17 : #include <reduce_sum_layer.h>
18 :
19 : namespace nntrainer {
20 :
21 : static constexpr size_t SINGLE_INOUT_IDX = 0;
22 :
23 8 : void ReduceSumLayer::finalize(InitLayerContext &context) {
24 8 : NNTR_THROW_IF(context.getNumInputs() != 1, std::invalid_argument)
25 : << "Reduce sum only supports 1 input for now";
26 :
27 : const TensorDim &in_dim = context.getInputDimensions()[0];
28 8 : TensorDim out_dim = in_dim;
29 :
30 : /**
31 : * if reduce axis is not provided, reduction is performed across all the
32 : * dimensions except the batch
33 : */
34 : auto &reduce_axis = std::get<props::ReduceDimension>(reduce_sum_props);
35 8 : out_dim.setTensorDim(reduce_axis.get(), 1);
36 8 : context.setOutputDimensions({out_dim});
37 8 : }
38 :
39 6 : void ReduceSumLayer::forwarding(RunLayerContext &context, bool training) {
40 : auto &reduce_axis = std::get<props::ReduceDimension>(reduce_sum_props);
41 6 : context.getInput(SINGLE_INOUT_IDX)
42 6 : .sum(reduce_axis, context.getOutput(SINGLE_INOUT_IDX));
43 6 : }
44 :
45 3 : void ReduceSumLayer::calcDerivative(RunLayerContext &context) {
46 3 : auto &deriv = context.getIncomingDerivative(SINGLE_INOUT_IDX);
47 3 : auto &ret_deriv = context.getOutgoingDerivative(SINGLE_INOUT_IDX);
48 :
49 3 : ret_deriv.setZero();
50 3 : ret_deriv.add_i(deriv);
51 3 : }
52 :
53 55 : void ReduceSumLayer::setProperty(const std::vector<std::string> &values) {
54 55 : auto remain_props = loadProperties(values, reduce_sum_props);
55 54 : if (!remain_props.empty()) {
56 : std::string msg = "[ReduceSumLayer] Unknown Layer Properties count " +
57 2 : std::to_string(remain_props.size());
58 4 : throw exception::not_supported(msg);
59 : }
60 54 : }
61 :
62 2 : void ReduceSumLayer::exportTo(Exporter &exporter,
63 : const ml::train::ExportMethods &method) const {
64 2 : exporter.saveResult(reduce_sum_props, method, this);
65 2 : }
66 :
67 : } /* namespace nntrainer */
|