Skip to main content

Linear

Struct Linear 

Source
pub struct Linear { /* private fields */ }
Expand description

A linear transformation layer (fully connected layer).

The Linear layer applies a linear transformation to the incoming data: y = xW^T + b. This is one of the most fundamental building blocks in neural networks.

§Parameters

  • weight: Learnable weight matrix of shape [out_features, in_features]
  • bias: Optional learnable bias vector of shape [out_features]

§Input/Output Shapes

  • Input: [..., in_features] - Can be 2D or 3D
  • Output: [..., out_features] - Same number of dimensions as input

§Example

use trustformers_core::layers::Linear;
use trustformers_core::tensor::Tensor;
use trustformers_core::traits::Layer;

// Create a linear layer: 768 → 3072
let linear = Linear::new(768, 3072, true);

// Apply to 2D input: [seq_len, in_features]
let input_2d = Tensor::randn(&[128, 768])?;
let output_2d = linear.forward(input_2d)?;  // Shape: [128, 3072]

// Apply to 3D input: [batch, seq_len, in_features]
let input_3d = Tensor::randn(&[4, 128, 768])?;
let output_3d = linear.forward(input_3d)?;  // Shape: [4, 128, 3072]

Implementations§

Source§

impl Linear

Source

pub fn new(in_features: usize, out_features: usize, bias: bool) -> Self

Creates a new linear layer.

§Arguments
  • in_features - Size of each input sample
  • out_features - Size of each output sample
  • bias - Whether to include a learnable bias
§Returns

A new Linear layer with randomly initialized weights using a normal distribution, and bias initialized to zeros if enabled.

§Example
use trustformers_core::layers::Linear;

// Linear layer without bias
let linear1 = Linear::new(512, 1024, false);

// Linear layer with bias
let linear2 = Linear::new(512, 1024, true);
Source

pub fn new_with_device( in_features: usize, out_features: usize, bias: bool, device: Device, ) -> Self

Creates a new linear layer with specified device.

§Arguments
  • in_features - Size of each input sample
  • out_features - Size of each output sample
  • bias - Whether to include a learnable bias
  • device - Device to use for computations (CPU, Metal, CUDA, etc.)
§Returns

A new Linear layer with randomly initialized weights.

§Example
use trustformers_core::layers::Linear;
use trustformers_core::Device;

// Create a linear layer on Metal GPU
let linear = Linear::new_with_device(768, 3072, true, Device::metal_if_available(0));
Source

pub fn device(&self) -> Device

Returns the device this layer uses for computations.

Source

pub fn to_device(self, device: Device) -> Self

Move this layer to a different device.

§Arguments
  • device - Target device
§Returns

Self with updated device.

Source

pub fn set_weight(&mut self, weight: Tensor) -> Result<()>

Sets the weight matrix for this layer.

§Arguments
  • weight - The new weight tensor, must have shape [out_features, in_features]
§Returns

Ok(()) if successful.

§Note

This method is typically used when loading pretrained weights.

Source

pub fn set_bias(&mut self, bias: Tensor) -> Result<()>

Sets the bias vector for this layer.

§Arguments
  • bias - The new bias tensor, must have shape [out_features]
§Returns

Ok(()) if successful.

§Note

This will enable bias even if the layer was created without bias.

Source

pub fn weight(&self) -> &Tensor

Returns a reference to the weight matrix.

§Returns

A reference to the weight tensor of shape [out_features, in_features].

Source

pub fn bias(&self) -> Option<&Tensor>

Returns a reference to the bias vector if present.

§Returns

Some(&bias) if bias is enabled, None otherwise.

Source

pub fn parameter_count(&self) -> usize

Returns the total number of learnable parameters in this layer.

§Returns

The total parameter count including weights and bias (if present).

Trait Implementations§

Source§

impl Clone for Linear

Source§

fn clone(&self) -> Linear

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 Debug for Linear

Source§

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

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

impl Layer for Linear

Source§

type Input = Tensor

Source§

type Output = Tensor

Source§

fn forward(&self, input: Self::Input) -> Result<Self::Output>

Performs the forward computation of this layer. Read more

Auto Trait Implementations§

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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> 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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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, 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

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more