Skip to main content

DifferentiableGraph

Struct DifferentiableGraph 

Source
pub struct DifferentiableGraph<T = Vec<f64>> { /* private fields */ }
Expand description

可微图结构:支持梯度计算的结构变换

核心思想:将离散的图结构参数化为连续空间, 使得梯度可以反向传播到结构参数。

§Architecture Notes

§与自动微分框架的集成

当前实现使用手动梯度计算。要与真正的自动微分框架(如 dfdx)集成, 需要:

  1. logits 存储为 Tensor1D<f64> 而非 f64
  2. 构建计算图:logits → probability → adjacency_matrix → loss
  3. 调用 loss.backward() 获取梯度

§与 Graph 的转换

使用 to_graph() 将可微图转换为普通 Graph, 使用 from_graph() 从现有图初始化可微图。

Implementations§

Source§

impl<T: Clone + Default> DifferentiableGraph<T>

Source

pub fn new(num_nodes: usize) -> Self

创建新的可微图

Source

pub fn with_config(num_nodes: usize, config: GradientConfig) -> Self

创建带配置的可微图

Source

pub fn init_nodes(&mut self, features: Option<T>)

初始化节点

Source

pub fn add_learnable_edge(&mut self, src: usize, dst: usize, init_prob: f64)

添加可学习边

Source

pub fn remove_edge( &mut self, src: usize, dst: usize, ) -> Option<DifferentiableEdge>

移除边

Source

pub fn get_edge_probability(&self, src: usize, dst: usize) -> Option<f64>

获取边的存在概率

Source

pub fn get_edge_exists(&self, src: usize, dst: usize) -> Option<bool>

获取边的存在性(离散)

Source

pub fn get_probability_matrix(&self) -> Vec<Vec<f64>>

获取所有边的概率矩阵

Source

pub fn get_adjacency_matrix(&self) -> Vec<Vec<f64>>

获取离散邻接矩阵(使用 STE)

Source

pub fn anneal_temperature(&mut self)

温度退火

Source

pub fn with_temperature_annealing(self, steps: usize) -> Self

设置温度退火

Source

pub fn discretize(&mut self)

离散化所有边(前向传播)

如果启用了 STE 模式,会存储 STE 修正项 (hard - soft), 用于后续梯度计算时修正梯度。

Source

pub fn compute_structure_gradients( &mut self, loss_gradients: &HashMap<(usize, usize), f64>, ) -> HashMap<(usize, usize), f64>

计算结构梯度

§Arguments
  • loss_gradients - 损失对边存在性的梯度 {(src, dst): ∂L/∂A_ij}
§Returns

HashMap {(src, dst): ∂L/∂logits},可用于更新边的 logits 参数

§Gradient Computation

梯度计算遵循链式法则:

∂L/∂logits = ∂L/∂A * ∂A/∂logits

其中 A = σ(logits/τ),所以:

∂A/∂logits = A * (1 - A) / τ
§STE 修正

当启用 STE 模式时,梯度会加上 STE 修正项:

gradient = ∂L/∂logits + (hard - soft)

这确保了前向传播的离散化与反向传播的连续梯度一致。

§Regularization
§L1 稀疏正则化

L_sparse = λ_sparse * Σ|logits| ∂L_sparse/∂logits = λ_sparse * sign(logits)

梯度下降更新:logits -= lr * gradient

  • 正 logits → 正梯度 → logits 减小 → 概率趋向 0 → 稀疏
  • 负 logits → 负梯度 → logits 增大 → 概率趋向 0 → 稀疏
§L2 平滑正则化

L_smooth = λ_smooth * Σ_{(i,j),(i,k)∈E} (A_ij - A_ik)² ∂L_smooth/∂A_ij = 2 * λ_smooth * Σ_k (A_ij - A_ik)

平滑正则化鼓励:

  • 共享源节点的边有相似概率
  • 共享目标节点的边有相似概率
Source

pub fn update_structure(&mut self, gradients: &HashMap<(usize, usize), f64>)

基于梯度更新结构

Source

pub fn optimization_step( &mut self, loss_gradients: HashMap<(usize, usize), f64>, ) -> HashMap<(usize, usize), f64>

一步优化:离散化 -> 计算梯度 -> 更新

Source

pub fn get_learnable_edges(&self) -> Vec<&DifferentiableEdge>

获取可微边列表

Source

pub fn num_edges(&self) -> usize

获取边数

Source

pub fn num_nodes(&self) -> usize

获取节点数

Source

pub fn config(&self) -> &GradientConfig

获取配置

Source

pub fn set_config(&mut self, config: GradientConfig)

设置配置

Source

pub fn temperature(&self) -> f64

获取当前温度

Source

pub fn set_temperature(&mut self, temp: f64)

设置温度

Source

pub fn edges( &self, ) -> impl Iterator<Item = (&(usize, usize), &DifferentiableEdge)>

获取边迭代器

Source

pub fn to_graph(&self) -> Graph<usize, f64>

转换为普通 Graph

使用离散化的边存在性构建 Graph。 边的权重为 1.0(如果存在)或 0.0(如果不存在)。

§Note

此方法创建的图使用节点索引作为节点数据,边权重为 f64。 节点索引通过 NodeIndex::new(index, generation) 创建, 其中 generation 由 Graph 内部管理。

Source

pub fn to_graph_with_types( &self, node_types: &HashMap<usize, OperatorType>, edge_weights: &HashMap<(usize, usize), WeightTensor>, ) -> Graph<OperatorType, WeightTensor>

转换为带类型信息的 Graph(保留 OperatorType 和 WeightTensor)

使用离散化的边存在性构建 Graph,保留原始的节点和边类型信息。

§Arguments
  • node_types - 节点类型映射 (node_index -> OperatorType)
  • edge_weights - 边权重映射 ((src, dst) -> WeightTensor)
§Returns

带类型信息的 Graph<OperatorType, WeightTensor>

Source

pub fn from_graph<U, V>( graph: &Graph<U, V>, init_probs: Option<HashMap<(usize, usize), f64>>, ) -> DifferentiableGraph<()>
where U: Clone, V: Clone,

从普通 Graph 初始化可微图

§Arguments
  • graph - 源图
  • init_probs - 边的初始存在概率
    • 如果提供,只初始化指定的边
    • 如果为 None,根据图中存在的边初始化(概率设为 1.0)
§Note

此方法忽略原图的节点和边数据,只使用图结构。 节点数据默认为 (),边数据默认为 ().

Source

pub fn from_graph_with_prob<U, V>( graph: &Graph<U, V>, init_prob: Option<f64>, ) -> DifferentiableGraph<()>
where U: Clone, V: Clone,

从普通图构建可微图(使用统一的初始概率)

§Arguments
  • graph - 原始图
  • init_prob - 边的初始存在概率(0.0~1.0)
§Returns

DifferentiableGraph<()> - 可微图

§Note

此方法忽略原图的节点和边数据,只使用图结构。

Source

pub fn set_ste(&mut self, use_ste: bool)

启用/禁用 STE 模式

Source

pub fn get_ste_corrections(&self) -> &HashMap<(usize, usize), f64>

获取 STE 修正项

Trait Implementations§

Source§

impl<T: Clone> Clone for DifferentiableGraph<T>

Source§

fn clone(&self) -> DifferentiableGraph<T>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Debug> Debug for DifferentiableGraph<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<T> Freeze for DifferentiableGraph<T>

§

impl<T> RefUnwindSafe for DifferentiableGraph<T>
where T: RefUnwindSafe,

§

impl<T> Send for DifferentiableGraph<T>
where T: Send,

§

impl<T> Sync for DifferentiableGraph<T>
where T: Sync,

§

impl<T> Unpin for DifferentiableGraph<T>
where T: Unpin,

§

impl<T> UnsafeUnpin for DifferentiableGraph<T>

§

impl<T> UnwindSafe for DifferentiableGraph<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> Conv for T

Source§

fn conv<T>(self) -> T
where Self: Into<T>,

Converts self into T using Into<T>. Read more
Source§

impl<T> FmtForward for T

Source§

fn fmt_binary(self) -> FmtBinary<Self>
where Self: Binary,

Causes self to use its Binary implementation when Debug-formatted.
Source§

fn fmt_display(self) -> FmtDisplay<Self>
where Self: Display,

Causes self to use its Display implementation when Debug-formatted.
Source§

fn fmt_lower_exp(self) -> FmtLowerExp<Self>
where Self: LowerExp,

Causes self to use its LowerExp implementation when Debug-formatted.
Source§

fn fmt_lower_hex(self) -> FmtLowerHex<Self>
where Self: LowerHex,

Causes self to use its LowerHex implementation when Debug-formatted.
Source§

fn fmt_octal(self) -> FmtOctal<Self>
where Self: Octal,

Causes self to use its Octal implementation when Debug-formatted.
Source§

fn fmt_pointer(self) -> FmtPointer<Self>
where Self: Pointer,

Causes self to use its Pointer implementation when Debug-formatted.
Source§

fn fmt_upper_exp(self) -> FmtUpperExp<Self>
where Self: UpperExp,

Causes self to use its UpperExp implementation when Debug-formatted.
Source§

fn fmt_upper_hex(self) -> FmtUpperHex<Self>
where Self: UpperHex,

Causes self to use its UpperHex implementation when Debug-formatted.
Source§

fn fmt_list(self) -> FmtList<Self>
where &'a Self: for<'a> IntoIterator,

Formats each item in a sequence. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pipe for T
where T: ?Sized,

Source§

fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R
where Self: Sized,

Pipes by value. This is generally the method you want to use. Read more
Source§

fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> R
where R: 'a,

Borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> R
where R: 'a,

Mutably borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
where Self: Borrow<B>, B: 'a + ?Sized, R: 'a,

Borrows self, then passes self.borrow() into the pipe function. Read more
Source§

fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
where Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Source§

fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
where Self: AsRef<U>, U: 'a + ?Sized, R: 'a,

Borrows self, then passes self.as_ref() into the pipe function.
Source§

fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
where Self: AsMut<U>, U: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.as_mut() into the pipe function.
Source§

fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
where Self: Deref<Target = T>, T: 'a + ?Sized, R: 'a,

Borrows self, then passes self.deref() into the pipe function.
Source§

fn pipe_deref_mut<'a, T, R>( &'a mut self, func: impl FnOnce(&'a mut T) -> R, ) -> R
where Self: DerefMut<Target = T> + Deref, T: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.deref_mut() into the pipe function.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T> Tap for T

Source§

fn tap(self, func: impl FnOnce(&Self)) -> Self

Immutable access to a value. Read more
Source§

fn tap_mut(self, func: impl FnOnce(&mut Self)) -> Self

Mutable access to a value. Read more
Source§

fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Immutable access to the Borrow<B> of a value. Read more
Source§

fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Mutable access to the BorrowMut<B> of a value. Read more
Source§

fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Immutable access to the AsRef<R> view of a value. Read more
Source§

fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Mutable access to the AsMut<R> view of a value. Read more
Source§

fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Immutable access to the Deref::Target of a value. Read more
Source§

fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Mutable access to the Deref::Target of a value. Read more
Source§

fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self

Calls .tap() only in debug builds, and is erased in release builds.
Source§

fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self

Calls .tap_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Calls .tap_borrow() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Calls .tap_ref() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Calls .tap_deref() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> TryConv for T

Source§

fn try_conv<T>(self) -> Result<T, Self::Error>
where Self: TryInto<T>,

Attempts to convert self into T using TryInto<T>. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V