include/tenzr/txpr/custom_vjp.h¶
Namespaces¶
| Name |
|---|
| tenzr |
| tenzr::txpr |
Classes¶
| Name | |
|---|---|
| struct | tenzr::txpr::CustomVJPRule A forward/backward rule pair defining the gradient of an operation that autodiff cannot derive on its own. |
| class | tenzr::txpr::CustomVJPRegistry Process-wide registry mapping operation names to custom VJP rules. |
| class | tenzr::txpr::CustomVJPFunction Callable wrapper that applies a function decorated with a registered custom VJP rule. |
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_TXPR_CUSTOM_VJP_H_
#define TENZR_TXPR_CUSTOM_VJP_H_
#include <functional>
#include <memory>
#include <string>
#include <string_view>
#include <unordered_map>
#include <utility>
#include "tenzr/array.h"
#include "tenzr/common/export.h"
namespace tenzr::txpr {
struct CustomVJPRule {
std::function<std::pair<Array, Array>(const Array&)> fwd;
std::function<Array(const Array&, const Array&)> bwd;
};
class TENZR_API CustomVJPRegistry {
public:
static CustomVJPRegistry& Instance();
void RegisterRule(std::string name, CustomVJPRule rule);
[[nodiscard]] bool HasRule(std::string_view name) const;
[[nodiscard]] const CustomVJPRule& GetRule(std::string_view name) const;
private:
CustomVJPRegistry() = default;
std::unordered_map<std::string, CustomVJPRule> rules_;
};
class TENZR_API CustomVJPFunction {
public:
CustomVJPFunction(std::string name, std::function<Array(const Array&)> fn, std::function<std::pair<Array, Array>(const Array&)> fwd,
std::function<Array(const Array&, const Array&)> bwd);
Array operator()(const Array& x) const;
private:
std::string name_;
std::function<Array(const Array&)> fn_;
};
[[nodiscard]] TENZR_API CustomVJPFunction CustomVjp(std::string name, std::function<Array(const Array&)> fn,
std::function<std::pair<Array, Array>(const Array&)> fwd,
std::function<Array(const Array&, const Array&)> bwd);
TENZR_API void RegisterCustomVjp(const std::string& name, std::function<Array(const Array&, const Array&)> bwd_fn);
TENZR_API void SetGradTracingActive(bool active) noexcept;
[[nodiscard]] TENZR_API bool IsGradTracingActive() noexcept;
} // namespace tenzr::txpr
namespace tenzr {
using txpr::CustomVjp;
using txpr::CustomVJPFunction;
using txpr::CustomVJPRegistry;
using txpr::RegisterCustomVjp;
} // namespace tenzr
#endif // TENZR_TXPR_CUSTOM_VJP_H_