Struct kn_graph::graph::Graph

source ·
pub struct Graph { /* private fields */ }
Expand description

The core graph datastructure.

This is a Directed Acyclic Graph (DAG) with values and their creating operations as nodes, and input operands as edges. The data structure is append-only, values cannot be removed and so will never become invalid.

This type implements Index<Value> trait, so you can use graph[value] to get information about the given value.

// create a new graph
let mut graph = Graph::new();

// define the inputs
let x = graph.input(shape![Size::BATCH, 4, 8, 8]);

// define constants
let w_data = vec![0.5; 4 * 4 * 3 * 3];
let w = graph.constant(shape![4, 4, 3, 3], w_data);
let b_data = vec![0.5; 4];
let b = graph.constant(shape![4, 1, 1], b_data);

// build operation graph
let y0 = graph.conv(x, w, 1, 1, 1, 1);
let y = graph.add(y0, b);

graph.output(y);

println!("{}", graph);

Results in the following output:

Graph {
  check: 1504812640,
  input_shapes: [Shape(B x 4 x 8 x 8)],
  output_shapes: [Shape(B x 4 x 8 x 8)],
  inputs: [Value(0)],
  outputs: [Value(6)],
  values: [
    Value(0) = ValueInfo { shape: Shape(B x 4 x 8 x 8), operation: Input { index: 0 }, debug_id: "", non_output_uses: 1 },
    Value(1) = ValueInfo { shape: Shape(4 x 4 x 3 x 3), operation: Constant { data: [..; 144] }, debug_id: "", non_output_uses: 1 },
    Value(2) = ValueInfo { shape: Shape(4 x 1 x 1), operation: Constant { data: [0.5, 0.5, 0.5, 0.5] }, debug_id: "", non_output_uses: 1 },
    Value(3) = ValueInfo { shape: Shape(B x 4 x 8 x 8), operation: Conv { input: Value(0), filter: Value(1), details: ConvDetails { batch_size: Size(B), input_channels: 4, output_channels: 4, input_h: 8, input_w: 8, kernel_h: 3, kernel_w: 3, stride_y: 1, stride_x: 1, padding_y: 1, padding_x: 1, output_h: 8, output_w: 8 } }, debug_id: "", non_output_uses: 1 },
    Value(4) = ValueInfo { shape: Shape(1 x 4 x 1 x 1), operation: View { input: Value(2) }, debug_id: "", non_output_uses: 1 },
    Value(5) = ValueInfo { shape: Shape(B x 4 x 8 x 8), operation: Broadcast { input: Value(4) }, debug_id: "", non_output_uses: 1 },
    Value(6) = ValueInfo { shape: Shape(B x 4 x 8 x 8), operation: Binary { left: Value(3), right: Value(5), op: Add }, debug_id: "", non_output_uses: 0 },
  ],
}

Implementations§

source§

impl Graph

source

pub fn new() -> Self

source

pub fn values(&self) -> impl Iterator<Item = Value>

Iterate over the values in this graph, in topological order, which means that nodes will only be visited after all of their inputs have been visited.

source

pub fn inputs(&self) -> &[Value]

source

pub fn input_shapes(&self) -> Vec<Shape>

source

pub fn outputs(&self) -> &[Value]

source

pub fn output_shapes(&self) -> Vec<Shape>

source

pub fn outputs_mut(&mut self) -> &mut Vec<Value>

source

pub fn is_hidden(&self, value: Value) -> bool

source

pub fn is_hidden_with_uses(&self, value: Value, users: usize) -> bool

source

pub fn is_const(&self, value: Value) -> bool

source

pub fn as_const(&self, value: Value) -> Option<Tensor>

Try to evaluate value as a constant.

source

pub fn is_const_filled_with(&self, value: Value, f: f32) -> bool

Returns whether value is effectively a constant with every element equal to f.

source

pub fn as_single_const(&self, value: Value) -> Option<f32>

Returns Some(f) if value is effectively a constant with every element equal to f.

source

pub fn take_new_values(&mut self) -> Vec<Value>

Return all newly crated values since the last call to take_new_values.

source

pub fn set_debug_id(&mut self, value: Value, id: String)

Equivalent to self[value].debug_id = id, but that would not work since there is intentionally no implementation of IndexMut for Graph.

source

pub fn input(&mut self, shape: Shape) -> Value

Declare a new input value.

source

pub fn scalar(&mut self, value: f32) -> Value

source

pub fn constant(&mut self, shape: Shape, data: Vec<f32>) -> Value

Declare a new constant.

source

pub fn constant_tensor(&mut self, tensor: Tensor) -> Value

source

pub fn view(&mut self, input: Value, new_shape: Shape) -> Value

View an existing value as a new shape.

source

pub fn broadcast(&mut self, input: Value, new_shape: Shape) -> Value

Broadcast the input towards new_shape. Additional unit axes are are inserted at the front and unit axes are repeated as necessary.

source

pub fn repeat_unary(&mut self, input: Value, axis: usize, count: Size) -> Value

source

pub fn flatten(&mut self, input: Value, start_axis: usize) -> Value

View a value with a flattened shape. All axis starting from start_axis inclusive are flattened into a single axis.

source

pub fn permute(&mut self, input: Value, permutation: Vec<usize>) -> Value

Change the order of axis in the shape.

source

pub fn slice(&mut self, input: Value, axis: usize, range: SliceRange) -> Value

Slice a value along an axis.

source

pub fn index(&mut self, input: Value, axis: usize, index: usize) -> Value

Index along a given axis. Similar to slice with a 1-sized interval except that the the resulting value doesn’t have the extra axis.

source

pub fn flip(&mut self, input: Value, axis: usize) -> Value

Flip the given axis.

source

pub fn repeat(&mut self, input: Value, axis: usize, count: Size) -> Value

Repeat input along a given axis, count times. This starts by emitting the entire tensor before repeating elements, similar to torch.repeat or numpy.tile.

source

pub fn repeat_interleave( &mut self, input: Value, axis: usize, count: Size ) -> Value

Repeat elements of input along a given axis, count times. This starts by repeat each element before going to the next one, similar to torch.repeat_interleave or numpy.repeat.

source

pub fn gather(&mut self, input: Value, axis: usize, indices: Value) -> Value

Index input along the given axis with indices given by indices.

The output shape is the input shape with axis replaced by the shape of indices.

source

pub fn concat( &mut self, inputs: Vec<Value>, axis: usize, base_shape: Option<Shape> ) -> Value

Concatenate inputs along axis. base_shape can be provided to allow the result shape to be inferred in case inputs is empty.

source

pub fn conv( &mut self, input: Value, filter: Value, stride_y: usize, stride_x: usize, padding_y: usize, padding_x: usize ) -> Value

Apply 2D convolution.

source

pub fn linear(&mut self, input: Value, weight: Value) -> Value

Apply a linear transformation. Input shape [b, Ci] and weight shape [Co, Ci] result in an output with shape [b, Co].

source

pub fn mat_mul(&mut self, left: Value, right: Value) -> Value

General matrix multiply, with broadcasting.

  • The last two axes should have shapes [n, p] and [p, m] and will result in an output shape [n, m]
  • The preceding axes are broadcast together and reappear in the output as-is.
source

pub fn batched_mat_mul(&mut self, left: Value, right: Value) -> Value

Batched matrix multiply, without any automatic broadcasting. Inputs must have shapes [b, m, n], [b, n, p] and the result has shape [b, m, p].

source

pub fn softmax(&mut self, input: Value, axis: usize) -> Value

source

pub fn layernorm(&mut self, input: Value, axis: usize, eps: f32) -> Value

source

pub fn reduce(&mut self, input: Value, axes: Vec<usize>, op: ReduceOp) -> Value

Reduce input along the given axes. The result shape is the same as the input shape but without the reduces axes.

source

pub fn sigmoid(&mut self, input: Value) -> Value

Elementwise sigmoid.

source

pub fn relu(&mut self, input: Value) -> Value

Elementwise relu.

source

pub fn clamp(&mut self, input: Value, min: f32, max: f32) -> Value

Elementwise clamp.

source

pub fn add(&mut self, left: Value, right: Value) -> Value

source

pub fn sub(&mut self, left: Value, right: Value) -> Value

source

pub fn mul(&mut self, left: Value, right: Value) -> Value

source

pub fn pow(&mut self, left: Value, right: Value) -> Value

source

pub fn unary(&mut self, op: UnaryOp, input: Value) -> Value

source

pub fn binary(&mut self, op: BinaryOp, left: Value, right: Value) -> Value

Compute elementwise binary operation. Both inputs must have the same rank (or right must have rank 0), the right shape is broadcasted to the left shape.

source

pub fn call(&mut self, graph: &Graph, inputs: &[Value]) -> Vec<Value>

Computes the operations described by graph on the given inputs.

This can be used to cleanly compose multiple graphs together.

source

pub fn output(&mut self, value: Value)

Register an existing value as an output

source

pub fn output_all(&mut self, values: &[Value])

Register multiple values as output at once, in order.

Trait Implementations§

source§

impl Clone for Graph

source§

fn clone(&self) -> Graph

Returns a copy 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 Debug for Graph

source§

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

Formats the value using the given formatter. Read more
source§

impl Display for Graph

source§

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

Formats the value using the given formatter. Read more
source§

impl Index<Value> for Graph

§

type Output = ValueInfo

The returned type after indexing.
source§

fn index(&self, value: Value) -> &Self::Output

Performs the indexing (container[index]) operation. Read more

Auto Trait Implementations§

§

impl RefUnwindSafe for Graph

§

impl Send for Graph

§

impl Sync for Graph

§

impl Unpin for Graph

§

impl UnwindSafe for Graph

Blanket Implementations§

source§

impl<S, D, Swp, Dwp, T> AdaptInto<D, Swp, Dwp, T> for Swhere T: Real + Zero + Arithmetics + Clone, Swp: WhitePoint<T>, Dwp: WhitePoint<T>, D: AdaptFrom<S, Swp, Dwp, T>,

source§

fn adapt_into_using<M>(self, method: M) -> Dwhere M: TransformMatrix<T>,

Convert the source color to the destination color using the specified method.
source§

fn adapt_into(self) -> D

Convert the source color to the destination color using the bradford method by default.
source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T, C> ArraysFrom<C> for Twhere C: IntoArrays<T>,

source§

fn arrays_from(colors: C) -> T

Cast a collection of colors into a collection of arrays.
source§

impl<T, C> ArraysInto<C> for Twhere C: FromArrays<T>,

source§

fn arrays_into(self) -> C

Cast this collection of arrays into a collection of colors.
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

source§

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

Mutably borrows from an owned value. Read more
source§

impl<T, C> ComponentsFrom<C> for Twhere C: IntoComponents<T>,

source§

fn components_from(colors: C) -> T

Cast a collection of colors into a collection of color components.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> FromAngle<T> for T

source§

fn from_angle(angle: T) -> T

Performs a conversion from angle.
source§

impl<T, U> FromStimulus<U> for Twhere U: IntoStimulus<T>,

source§

fn from_stimulus(other: U) -> T

Converts other into Self, while performing the appropriate scaling, rounding and clamping.
source§

impl<T, U> Into<U> for Twhere 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, U> IntoAngle<U> for Twhere U: FromAngle<T>,

source§

fn into_angle(self) -> U

Performs a conversion into T.
source§

impl<T, U> IntoColor<U> for Twhere U: FromColor<T>,

source§

fn into_color(self) -> U

Convert into T with values clamped to the color defined bounds Read more
source§

impl<T, U> IntoColorUnclamped<U> for Twhere U: FromColorUnclamped<T>,

source§

fn into_color_unclamped(self) -> U

Convert into T. The resulting color might be invalid in its color space Read more
source§

impl<T> IntoStimulus<T> for T

source§

fn into_stimulus(self) -> T

Converts self into T, while performing the appropriate scaling, rounding and clamping.
source§

impl<T> ToOwned for Twhere T: Clone,

§

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> ToString for Twhere T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<'a, T, C> TryComponentsInto<C> for Twhere C: TryFromComponents<T>,

§

type Error = <C as TryFromComponents<T>>::Error

The error for when try_into_colors fails to cast.
source§

fn try_components_into(self) -> Result<C, <T as TryComponentsInto<C>>::Error>

Try to cast this collection of color components into a collection of colors. Read more
source§

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

§

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 Twhere U: TryFrom<T>,

§

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<T, U> TryIntoColor<U> for Twhere U: TryFromColor<T>,

source§

fn try_into_color(self) -> Result<U, OutOfBounds<U>>

Convert into T, returning ok if the color is inside of its defined range, otherwise an OutOfBounds error is returned which contains the unclamped color. Read more
source§

impl<C, U> UintsFrom<C> for Uwhere C: IntoUints<U>,

source§

fn uints_from(colors: C) -> U

Cast a collection of colors into a collection of unsigned integers.
source§

impl<C, U> UintsInto<C> for Uwhere C: FromUints<U>,

source§

fn uints_into(self) -> C

Cast this collection of unsigned integers into a collection of colors.
§

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

§

fn vzip(self) -> V