Skip to content

include/tenzr/modules/nn/module.h

Namespaces

Name
tenzr
tenzr::nn

Classes

Name
class tenzr::nn::Module
Base class for neural-network layers holding parameters, submodules, and training state.

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.

#ifndef TENZR_MODULES_NN_MODULE_H_
#define TENZR_MODULES_NN_MODULE_H_

#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

#include "tenzr/common/error.h"
#include "tenzr/frontend/tensor.h"

namespace tenzr::nn {

  class Module {
   public:
    virtual ~Module() = default;

    virtual Tensor Forward(const Tensor& input) = 0;

    Tensor operator()(const Tensor& input) { return Forward(input); }

    virtual void Train(bool mode) {
      training_ = mode;
      for (auto& [name, submod] : submodules_) {
        if (submod) {
          submod->Train(mode);
        }
      }
    }

    void Train() { Train(true); }

    void Eval() { Train(false); }

    bool IsTraining() const { return training_; }

    Tensor& RegisterParameter(std::string name, Tensor param) {
      auto [it, _] = parameters_.insert_or_assign(std::move(name), std::move(param));
      return it->second;
    }

    template <typename T, typename... Args> std::shared_ptr<T> RegisterSubmodule(std::string name, Args&&... args) {
      auto submod = std::make_shared<T>(std::forward<Args>(args)...);
      submodules_.insert_or_assign(std::move(name), submod);
      return submod;
    }

    std::shared_ptr<Module> RegisterSubmodule(std::string name, std::shared_ptr<Module> submod) {
      submodules_.insert_or_assign(std::move(name), submod);
      return submod;
    }

    std::vector<Tensor> Parameters(bool recurse = true) const {
      std::vector<Tensor> result;
      for (const auto& [name, p] : parameters_) {
        result.push_back(p);
      }
      if (recurse) {
        for (const auto& [name, submod] : submodules_) {
          if (submod) {
            auto sub_params = submod->Parameters(true);
            result.insert(result.end(), sub_params.begin(), sub_params.end());
          }
        }
      }
      return result;
    }

    std::unordered_map<std::string, Tensor> NamedParameters(std::string prefix = "", bool recurse = true) const {
      std::unordered_map<std::string, Tensor> result;
      for (const auto& [name, p] : parameters_) {
        std::string full_name = prefix.empty() ? name : prefix + "." + name;
        result[full_name] = p;
      }
      if (recurse) {
        for (const auto& [name, submod] : submodules_) {
          if (submod) {
            std::string sub_prefix = prefix.empty() ? name : prefix + "." + name;
            auto sub_named = submod->NamedParameters(sub_prefix, true);
            result.insert(sub_named.begin(), sub_named.end());
          }
        }
      }
      return result;
    }

    std::unordered_map<std::string, Tensor> StateDict() const {
      auto dict = NamedParameters("", true);
      std::unordered_map<std::string, Tensor> result;
      for (const auto& [name, p] : dict) {
        result[name] = p.Clone();
      }
      return result;
    }

    void LoadStateDict(const std::unordered_map<std::string, Tensor>& state) {
      auto current_params = NamedParameters("", true);
      for (const auto& [name, p] : state) {
        auto it = current_params.find(name);
        TENZR_CHECK(it != current_params.end(), "Unexpected key in state_dict: " + name);
        TENZR_CHECK(it->second.shape() == p.shape(), "Shape mismatch loading parameter " + name);
        TENZR_CHECK(it->second.Dtype() == p.Dtype(), "DType mismatch loading parameter " + name);
        if (p.HasData()) {
          it->second.BindData(p.Clone().Data());
        }
      }
    }

    virtual std::string Name() const { return "Module"; }

   protected:
    std::unordered_map<std::string, Tensor> parameters_;
    std::unordered_map<std::string, std::shared_ptr<Module>> submodules_;
    bool training_{true};
  };

}  // namespace tenzr::nn

#endif  // TENZR_MODULES_NN_MODULE_H_