backprop_derivative.hpp 8.21 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

#pragma once

#include <memory>

Robert Kimball's avatar
Robert Kimball committed
21
#include "ngraph/log.hpp"
Scott Cyphers's avatar
Scott Cyphers committed
22
#include "ngraph/types/element_type.hpp"
Robert Kimball's avatar
Robert Kimball committed
23
#include "ngraph/util.hpp"
24
#include "util/all_close.hpp"
25
#include "util/test_tools.hpp"
Scott Cyphers's avatar
Scott Cyphers committed
26 27 28 29 30 31 32 33 34 35

namespace ngraph
{
    class Node;
    class Function;

    namespace runtime
    {
        class Backend;
        class Manager;
36
    }
Scott Cyphers's avatar
Scott Cyphers committed
37 38 39

    namespace autodiff
    {
40 41
        template <typename T>
        std::vector<std::shared_ptr<runtime::TensorView>>
42 43 44 45 46
            get_autodiff(const std::shared_ptr<runtime::Manager>& manager,
                         const std::shared_ptr<runtime::Backend>& backend,
                         std::shared_ptr<Function>& df,
                         const std::vector<std::shared_ptr<runtime::TensorView>>& df_input_args,
                         const std::vector<std::shared_ptr<op::Parameter>>& indep_params)
Robert Kimball's avatar
Robert Kimball committed
47
        {
48 49 50 51 52
            // df/dX* = f'(c, ...)
            // using X* to denote all x "of interest" (represented by indep_params)

            // return value for this function
            std::vector<std::shared_ptr<runtime::TensorView>> results;
Robert Kimball's avatar
Robert Kimball committed
53

54
            // adjoint
55 56
            auto c_arg = df_input_args[0];
            auto y_shape = c_arg->get_shape();
Robert Kimball's avatar
Robert Kimball committed
57

58
            // df/dX* arguments
59 60 61 62
            std::vector<std::shared_ptr<runtime::TensorView>> df_output_args;

            // for each x "of interest"
            for (auto x : indep_params)
Robert Kimball's avatar
Robert Kimball committed
63
            {
64
                // add df/dx to df/dX* arguments
65
                auto x_shape = x->get_shape();
66
                df_output_args.push_back(backend->make_primary_tensor_view<T>(x_shape));
67 68 69 70 71 72

                // each element of y has a derivative with respect to each element of x
                // hence, create a y by x sized tensor for this result
                auto y_by_x_shape = y_shape;
                y_by_x_shape.insert(y_by_x_shape.end(), x_shape.begin(), x_shape.end());
                results.push_back(backend->make_primary_tensor_view<T>(y_by_x_shape));
Robert Kimball's avatar
Robert Kimball committed
73 74
            }

75
            // create storage for results
76
            std::vector<std::vector<T>> result_vect;
77
            std::vector<typename std::vector<T>::iterator> result_pos;
Robert Kimball's avatar
Robert Kimball committed
78 79
            for (auto result : results)
            {
80
                result_vect.push_back(read_vector<T>(result));
Robert Kimball's avatar
Robert Kimball committed
81 82 83
                result_pos.push_back(result_vect.back().begin());
            }

84 85 86 87
            // compile f'
            auto external = manager->compile(df);
            auto cf = backend->make_call_frame(external);

88
            // get adjoint and force to all elements to zero
89
            auto c_vec = read_vector<T>(c_arg);
90
            fill(c_vec.begin(), c_vec.end(), 0);
91 92 93

            // for each element of the adjoint
            // same as saying for each element of y
Robert Kimball's avatar
Robert Kimball committed
94 95
            for (size_t i = 0; i < c_vec.size(); i++)
            {
96
                // set a single adjoint element
Robert Kimball's avatar
Robert Kimball committed
97
                c_vec[i] = 1;
98
                write_vector(c_arg, c_vec);
99 100 101 102 103

                // call modified df/dX* = f'(c, cached)
                cf->tensor_call(df_input_args, df_output_args);

                // reset the adjoint element
Robert Kimball's avatar
Robert Kimball committed
104
                c_vec[i] = 0;
105
                write_vector(c_arg, c_vec);
106 107 108

                // for each result
                // same as saying for each x "of interest"
Robert Kimball's avatar
Robert Kimball committed
109 110
                for (size_t j = 0; j < results.size(); j++)
                {
111 112 113
                    // copy df/dx to storage for this element of y
                    auto dfdx = read_vector<T>(df_output_args[j]);
                    result_pos[j] = std::copy(dfdx.begin(), dfdx.end(), result_pos[j]);
Robert Kimball's avatar
Robert Kimball committed
114 115 116
                }
            }

117
            // copy storage to results and return
Robert Kimball's avatar
Robert Kimball committed
118 119
            for (size_t j = 0; j < results.size(); j++)
            {
120
                write_vector(results[j], result_vect[j]);
Robert Kimball's avatar
Robert Kimball committed
121 122 123
            }
            return results;
        }
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208

        template <typename T>
        std::vector<std::shared_ptr<runtime::TensorView>> backprop_derivative(
            const std::shared_ptr<runtime::Manager>& manager,
            const std::shared_ptr<runtime::Backend>& backend,
            const std::shared_ptr<Function>& f,
            const std::vector<std::shared_ptr<runtime::TensorView>>& f_input_args,
            const std::vector<std::shared_ptr<op::Parameter>>& indep_params)
        {
            // y = f(X)
            // using X (upper case) to denote all paramenters of f (represented by f_input_args)
            // using x (lower case) to denote an individual paramemter of f
            // using X* to denote all x "of interest" (represented by indep_params)
            Shape y_shape = f->get_output_shape(0);

            // adjoint
            auto c_param = std::make_shared<op::Parameter>(element::from<T>(), y_shape);
            auto c_arg = backend->make_primary_tensor_view<T>(y_shape);

            // df/dX*
            std::vector<std::shared_ptr<Node>> df_output_params;

            // for each x "of interest"
            for (auto x : indep_params)
            {
                // add df/dx to df/dX*
                auto x_shape = x->get_shape();
                df_output_params.push_back(f->get_output_op(0)->backprop_node(x, c_param));
            }

            // (c, X)
            std::vector<std::shared_ptr<op::Parameter>> df_input_params = f->get_parameters();
            df_input_params.insert(df_input_params.begin(), c_param);

            // df/dX* = f'(c, X)
            auto df = std::make_shared<Function>(df_output_params, df_input_params);

            // (c, X) arguments
            std::vector<std::shared_ptr<runtime::TensorView>> df_input_args = f_input_args;
            df_input_args.insert(df_input_args.begin(), c_arg);

            // call f'(c,X) to get df/dX*
            auto dfdx = get_autodiff<T>(manager, backend, df, df_input_args, indep_params);

            // create fprop cache
            // creates modified forward function -> (y, cached) = f(x)
            // creates modified backward function -> df/dX* = f'(c, cached)
            auto fprop_cache = cache_fprop(f, df, {c_param});

            // (y, cached) arguments
            std::vector<std::shared_ptr<runtime::TensorView>> mod_f_output_args;
            mod_f_output_args.push_back(backend->make_primary_tensor_view<T>(y_shape));

            // (c, cached) arguments
            std::vector<std::shared_ptr<runtime::TensorView>> mod_df_input_args;
            mod_df_input_args.push_back(c_arg);

            // add cached nodes to both modified f output and modified f' input arguments
            for (auto node : fprop_cache.fprop_output_nodes)
            {
                auto tv = backend->make_primary_tensor_view<T>(node->get_shape());
                mod_f_output_args.push_back(tv);
                mod_df_input_args.push_back(tv);
            }

            // compile and run modified (y, cached) = f(x)
            auto cache_fwd = manager->compile(fprop_cache.fprop);
            auto cache_fwd_cf = backend->make_call_frame(cache_fwd);
            cache_fwd_cf->tensor_call(f_input_args, mod_f_output_args);

            // call modfied f'(c, cached) to get df/dX*
            auto cache_dfdx = get_autodiff<T>(
                manager, backend, fprop_cache.bprop, mod_df_input_args, indep_params);

            const auto numpy_atol = 1e-5f;
            const auto numpy_rtol = 1e-8f;
            auto close = ngraph::test::all_close<T>(dfdx, cache_dfdx, numpy_atol, numpy_rtol);
            if (!close)
            {
                throw ngraph_error(
                    "Derivatives mismatch between cache and non-cache bprop functions");
            }

            return dfdx;
        }
Scott Cyphers's avatar
Scott Cyphers committed
209 210
    }
}