Skip to content

src/modules/optim/optimizer.cc

Namespaces

Name
tenzr
tenzr::optim

Source code

// Copyright 2026 The Tenzr Project Authors
//
// SPDX-License-Identifier: Apache-2.0
//
// 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
//
//      https://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 "tenzr/modules/optim/optimizer.h"

#include <vector>

#include "tenzr/common/error.h"

namespace tenzr::optim {

  Optimizer::Optimizer(std::unordered_map<std::string, Tensor> params, std::shared_ptr<GradientTransformation> transform)
      : params_(std::move(params)), transform_(std::move(transform)) {
    TENZR_CHECK(transform_ != nullptr, "GradientTransformation must not be null");
    state_ = transform_->Init(params_);
  }

  Optimizer::Optimizer(nn::Module& module, std::shared_ptr<GradientTransformation> transform)
      : params_(module.NamedParameters("", true)), transform_(std::move(transform)) {
    TENZR_CHECK(transform_ != nullptr, "GradientTransformation must not be null");
    state_ = transform_->Init(params_);
  }

  void Optimizer::Step(const std::unordered_map<std::string, Tensor>& grads) {
    auto updates = transform_->Update(grads, state_, params_);

    for (auto& [name, p] : params_) {
      auto u_it = updates.find(name);
      // A lazy update is consumed here (to_vector materializes it).
      if (u_it == updates.end() || !p.HasData()) {
        continue;
      }

      auto p_raw = p.ToVectorAs<double>();
      auto u_raw = u_it->second.ToVectorAs<double>();
      size_t n = p_raw.size();

      for (size_t i = 0; i < n; ++i) {
        p_raw[i] += u_raw[i];
      }
      auto updated = Tensor::FromVector<double>(p_raw, p.shape()).Astype(p.Dtype());
      p.BindData(updated.Data());
    }
  }

}  // namespace tenzr::optim