backprop_function.cpp 1.74 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*******************************************************************************
* Copyright 2017-2018 Intel Corporation
*
* 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.
*******************************************************************************/
Scott Cyphers's avatar
Scott Cyphers committed
16 17 18 19 20 21 22

#include <cassert>
#include <list>
#include <memory>
#include <unordered_map>
#include <unordered_set>

23
#include "backprop_function.hpp"
Scott Cyphers's avatar
Scott Cyphers committed
24 25 26 27 28 29 30 31 32 33 34 35 36
#include "ngraph/autodiff/adjoints.hpp"
#include "ngraph/function.hpp"
#include "ngraph/node.hpp"
#include "ngraph/ops/add.hpp"
#include "ngraph/ops/broadcast.hpp"
#include "ngraph/ops/constant.hpp"
#include "ngraph/ops/convert.hpp"
#include "ngraph/types/type.hpp"

using namespace ngraph;

std::shared_ptr<Function> autodiff::backprop_function(const std::shared_ptr<Function>& f)
{
37
    auto Y_out = f->get_output_op(0);
Scott Cyphers's avatar
Scott Cyphers committed
38
    auto Xs = f->get_parameters();
39
    auto C = std::make_shared<op::Parameter>(Y_out->get_element_type(), Y_out->get_shape());
Scott Cyphers's avatar
Scott Cyphers committed
40
    std::vector<std::shared_ptr<Node>> dYdXs(Xs.size());
41 42
    transform(Xs.begin(), Xs.end(), dYdXs.begin(), [C, Y_out](const std::shared_ptr<Node>& X) {
        return Y_out->backprop_node(X, C);
Scott Cyphers's avatar
Scott Cyphers committed
43 44 45
    });
    std::vector<std::shared_ptr<op::Parameter>> params(Xs);
    params.push_back(C);
46
    return std::make_shared<Function>(dYdXs, params);
Scott Cyphers's avatar
Scott Cyphers committed
47
}