|
| 1 | +/* |
| 2 | + * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | + * All rights reserved. |
| 4 | + * |
| 5 | + * This source code is licensed under the BSD-style license found in the |
| 6 | + * LICENSE file in the root directory of this source tree. |
| 7 | + */ |
| 8 | + |
| 9 | +#include <executorch/extension/training/optimizer/sgd.h> |
| 10 | +#include <executorch/kernels/test/FunctionHeaderWrapper.h> // Declares the operator |
| 11 | + |
| 12 | +#include <executorch/runtime/core/error.h> |
| 13 | +#include <executorch/runtime/kernel/kernel_runtime_context.h> |
| 14 | + |
| 15 | +namespace torch { |
| 16 | +namespace executor { |
| 17 | +namespace training { |
| 18 | +namespace optimizer { |
| 19 | + |
| 20 | +bool SGDParamGroup::has_options() const { |
| 21 | + return options_ != nullptr; |
| 22 | +} |
| 23 | + |
| 24 | +SGDOptions& SGDParamGroup::options() { |
| 25 | + return *options_.get(); |
| 26 | +} |
| 27 | + |
| 28 | +const SGDOptions& SGDParamGroup::options() const { |
| 29 | + return *options_.get(); |
| 30 | +} |
| 31 | + |
| 32 | +void SGDParamGroup::set_options(std::unique_ptr<SGDOptions> options) { |
| 33 | + options_ = std::move(options); |
| 34 | +} |
| 35 | + |
| 36 | +Span<const char*> SGDParamGroup::param_names() { |
| 37 | + return param_names_; |
| 38 | +} |
| 39 | + |
| 40 | +const Span<const char*> SGDParamGroup::param_names() const { |
| 41 | + return param_names_; |
| 42 | +} |
| 43 | + |
| 44 | +Span<Tensor> SGDParamGroup::param_data() { |
| 45 | + return param_data_; |
| 46 | +} |
| 47 | + |
| 48 | +const Span<Tensor> SGDParamGroup::param_data() const { |
| 49 | + return param_data_; |
| 50 | +} |
| 51 | + |
| 52 | +void SGD::add_param_group(const SGDParamGroup& param_group) { |
| 53 | + SGDParamGroup param_group_( |
| 54 | + param_group.param_names(), param_group.param_data()); |
| 55 | + if (!param_group.has_options()) { |
| 56 | + param_group_.set_options(defaults_->clone()); |
| 57 | + } else { |
| 58 | + param_group_.set_options(param_group.options().clone()); |
| 59 | + } |
| 60 | + param_groups_.emplace_back(std::move(param_group_)); |
| 61 | +} |
| 62 | + |
| 63 | +Error SGD::step(Span<const char*> gradient_names, Span<Tensor> gradient_data) { |
| 64 | + // check that the number of gradient names matches the number of gradients |
| 65 | + ET_CHECK_OR_RETURN_ERROR( |
| 66 | + gradient_names.size() == gradient_data.size(), |
| 67 | + InvalidState, |
| 68 | + "Gradient names and gradients must have the same length."); |
| 69 | + |
| 70 | + RuntimeContext context; |
| 71 | + for (auto& group : param_groups_) { |
| 72 | + auto& options = static_cast<SGDOptions&>(group.options()); |
| 73 | + auto weight_decay = options.weight_decay(); |
| 74 | + auto momentum = options.momentum(); |
| 75 | + auto dampening = options.dampening(); |
| 76 | + auto nesterov = options.nesterov(); |
| 77 | + |
| 78 | + for (int i = 0; i < group.param_names().size(); i++) { |
| 79 | + for (int j = 0; j < gradient_names.size(); j++) { |
| 80 | + // if param name and gradient name match, run the optimizer step |
| 81 | + if (strcmp(group.param_names()[i], gradient_names[j]) == 0) { |
| 82 | + auto d_p = gradient_data[j]; |
| 83 | + auto p = group.param_data()[i]; |
| 84 | + if (weight_decay != 0) { |
| 85 | + // uses weight_decay specified and adds it to the gradient |
| 86 | + torch::executor::aten::add_outf(context, d_p, p, weight_decay, d_p); |
| 87 | + if (context.failure_state() != Error::Ok) { |
| 88 | + return context.failure_state(); |
| 89 | + } |
| 90 | + } |
| 91 | + if (momentum != 0) { |
| 92 | + Tensor buf(nullptr); |
| 93 | + auto param_state = state_.find(p.unsafeGetTensorImpl()); |
| 94 | + // look for the momentum buffer for the given parameter. this is the |
| 95 | + // momentum as of the previous epoch |
| 96 | + if (param_state == state_.end()) { |
| 97 | + // create a new momentum buffer if it doesn't exist. this memory |
| 98 | + // needs to be freed when the optimizer is destroyed |
| 99 | + void* buf_ptr = malloc(d_p.nbytes()); |
| 100 | + |
| 101 | +#ifdef USE_ATEN_LIB |
| 102 | + std::vector<int64_t> sizes( |
| 103 | + d_p.sizes().begin(), d_p.sizes().end()); |
| 104 | + buf = torch::from_blob(buf_ptr, sizes, d_p.scalar_type()); |
| 105 | +#else |
| 106 | + TensorImpl* buf_impl = new TensorImpl( |
| 107 | + d_p.scalar_type(), |
| 108 | + d_p.sizes().size(), |
| 109 | + const_cast<TensorImpl::SizesType*>(d_p.sizes().data()), |
| 110 | + buf_ptr, |
| 111 | + const_cast<TensorImpl::DimOrderType*>( |
| 112 | + d_p.dim_order().data())); |
| 113 | + buf = Tensor(buf_impl); |
| 114 | +#endif |
| 115 | + torch::executor::aten::clone_outf( |
| 116 | + context, d_p, exec_aten::MemoryFormat::Contiguous, buf); |
| 117 | + if (context.failure_state() != Error::Ok) { |
| 118 | + return context.failure_state(); |
| 119 | + } |
| 120 | + |
| 121 | + // save the state of the momentum buffer to be reused in later |
| 122 | + // epochs |
| 123 | + auto state = std::make_unique<SGDParamState>(buf); |
| 124 | + state_[p.unsafeGetTensorImpl()] = std::move(state); |
| 125 | + } else { |
| 126 | + buf = static_cast<SGDParamState&>(*param_state->second) |
| 127 | + .momentum_buffer(); |
| 128 | + |
| 129 | + // update the momentum buffer and apply dampening |
| 130 | + torch::executor::aten::mul_outf(context, buf, momentum, buf); |
| 131 | + if (context.failure_state() != Error::Ok) { |
| 132 | + return context.failure_state(); |
| 133 | + } |
| 134 | + torch::executor::aten::add_outf( |
| 135 | + context, buf, d_p, 1 - dampening, buf); |
| 136 | + if (context.failure_state() != Error::Ok) { |
| 137 | + return context.failure_state(); |
| 138 | + } |
| 139 | + } |
| 140 | + if (nesterov) { |
| 141 | + // apply nesterov momentum |
| 142 | + torch::executor::aten::add_outf(context, d_p, buf, momentum, d_p); |
| 143 | + if (context.failure_state() != Error::Ok) { |
| 144 | + return context.failure_state(); |
| 145 | + } |
| 146 | + } else { |
| 147 | + d_p = buf; |
| 148 | + } |
| 149 | + } |
| 150 | + // update the parameter using the gradient and learning rate |
| 151 | + torch::executor::aten::add_outf( |
| 152 | + context, p, d_p, -1 * options.lr(), p); |
| 153 | + if (context.failure_state() != Error::Ok) { |
| 154 | + return context.failure_state(); |
| 155 | + } |
| 156 | + break; |
| 157 | + } |
| 158 | + } |
| 159 | + } |
| 160 | + } |
| 161 | + return Error::Ok; |
| 162 | +} |
| 163 | + |
| 164 | +SGD::~SGD() { |
| 165 | + for (const auto& state_kv : state_) { |
| 166 | + auto state_tensor = static_cast<SGDParamState&>(*state_kv.second); |
| 167 | + free(state_tensor.momentum_buffer().unsafeGetTensorImpl()->mutable_data()); |
| 168 | +#ifndef USE_ATEN_LIB |
| 169 | + delete state_tensor.momentum_buffer().unsafeGetTensorImpl(); |
| 170 | +#endif |
| 171 | + } |
| 172 | +} |
| 173 | +} // namespace optimizer |
| 174 | +} // namespace training |
| 175 | +} // namespace executor |
| 176 | +} // namespace torch |
0 commit comments