Skip to main content

CustomFunction

Trait CustomFunction 

Source
pub trait CustomFunction:
    Send
    + Sync
    + 'static {
    // Required methods
    fn name(&self) -> &str;
    fn output_shape(
        &self,
        input_shapes: &[&[usize]],
    ) -> Result<Vec<usize>, AutodiffError>;
    fn forward(
        &self,
        inputs: &[&Tensor<f32>],
    ) -> Result<Tensor<f32>, AutodiffError>;
    fn backward(
        &self,
        inputs: &[&Tensor<f32>],
        out_value: &Tensor<f32>,
        upstream: &Tensor<f32>,
        requires_grad: &[bool],
    ) -> Result<Vec<Option<Tensor<f32>>>, AutodiffError>;
}
Expand description

ユーザー定義の forward/backward 対(docs/autodiff-custom-function- decision.md §12.4)。crate::Tape::custom(tape.rs)経由で テープへ登録する唯一の実装口。

契約(§12.4 表・§6「数値契約」):

  • forward/backward は host Tensor<f32> のみを受け渡す (BackendOps 非露出。REQ-12 §7 読み (i) に整合。デバイス側 カーネルへの直接アクセスは与えない)。
  • 決定的・副作用なしの純関数として実装すること。同一ノードの backward は Tape::backward_accumulate(#1749)・ retain_graph 常時保持契約(グラフを reset/drop まで保持する 契約)により複数回呼ばれうる。
  • 'static 境界により &Tape・Var<'t> を捕捉できない (backward 中に Tape を再入すると RefCell 二重可変借用の panic になるため、型で構造的に禁止する。§3 項 7)。
  • 数値一致の複合判定(REQ-2)の対象外——host 実行のみで、丸め 契約・バックエンド間一致はユーザー実装の責任とする。
  • GPU 上に構築した Tape でも常に host 実行になる(性能は非保証。 §9 のスコープ外整理)。

Required Methods§

Source

fn name(&self) -> &str

ログ・エラーメッセージ表示用の識別名。Op::Custom の手書き Debug 実装(CustomFn)が参照する。

Source

fn output_shape( &self, input_shapes: &[&[usize]], ) -> Result<Vec<usize>, AutodiffError>

入力 shape 列から出力 shape を宣言する。forward の実出力 shape との不一致は Tape::custom が fail-closed (AutodiffError::Shape)で検出する(§6「shape 検証」)。

Source

fn forward(&self, inputs: &[&Tensor<f32>]) -> Result<Tensor<f32>, AutodiffError>

forward 計算。inputs は Tape::custom 呼び出し時点で層 1 (materialize_fallible)により実体化済みの値。

Source

fn backward( &self, inputs: &[&Tensor<f32>], out_value: &Tensor<f32>, upstream: &Tensor<f32>, requires_grad: &[bool], ) -> Result<Vec<Option<Tensor<f32>>>, AutodiffError>

backward 計算。戻り値は inputs と同じ長さ・順序。

requires_grad は inputs と同じ長さで、各要素は呼び出し元 (grad::vjp)が該当入力について判断済みの要否 (TapeNode::requires_grad 前方伝播の結果。イシュー #1748・ docs/autodiff-nograd-leaf-dinput-skip-decision.md)を渡す。 requires_grad[i] == false の入力は計算を省略し None を 返してよい(Some を返すこと自体は禁止しない——false の入力 への寄与は呼び出し元〈backward_impl〉が破棄する)。 requires_grad[i] == true の入力に対して None を返した場合は fail-closed で Err(勾配欠落をユーザー実装の不備として 早期検出するため)。Some の要素は対応する入力と同じ shape で なければならず、不一致も fail-closed で拒否する。

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§