Skip to main content

Layer

Struct Layer 

pub struct Layer<M>
where M: Module,
{ pub norm: RmsNorm, pub block: M, pub norm2: Option<RmsNorm>, pub mlp: Option<GatedMlp>, pub class_latents: Vec<ClassLatent>, pub class_latents_emb: Option<Param<Tensor<2>>>, }
Expand description

A single Pre-LN block wrapper computing M(RMSNorm(x)) — the residual is not applied here. The enclosing Layers owns that decision (add the input back, suppress it on the first/last layer, or thread it through Multi-Gate streams), so no input clone / zero-add is wasted when no residual is wanted.

With Self::mlp set the layer additionally runs a second Pre-LN sub-block, a SwiGLU feed-forward (see GatedMlp). It has a residual of its own, inside the layer, which is the reason the methods below return the layer’s total delta rather than the mixer output:

  h₁ = M(norm(x))                     the mixer sub-block
  h₂ = mlp(norm2(x + h₁))             the feed-forward sub-block
  return h₁ + h₂                      so that Layers' `x + delta` is
                                      (x + h₁) + h₂ — both residuals

Folding it this way keeps Layers the single owner of the outer residual (and of the ignore_first/last_residual ablations, which therefore govern only that outer add — the feed-forward’s inner residual is intrinsic to the sub-block and always applies). Without an mlp the delta is just h₁ and nothing changes for a block family that carries no feed-forward.

May carry its own ClassLatents, placed from a [ClassCursor]: step splices them around the token it is given, while in forward the caller splices them first (via Self::insert_latents) so the residual it adds sees the same lengthened sequence; Self::prime steps the ones waiting for the next token without that token. They are independent of any class latents on the enclosing Layers.

Fields§

§norm: RmsNorm

Pre-norm applied before the inner block.

§block: M

The inner mixer block.

§norm2: Option<RmsNorm>

Pre-norm of the feed-forward sub-block. Some exactly when Self::mlp is (norm2 in the reference checkpoints).

§mlp: Option<GatedMlp>

Optional SwiGLU feed-forward sub-block run after the mixer, with its own residual. None ⇒ the layer is mixer-only.

§class_latents: Vec<ClassLatent>

Positions of this layer’s class latents (empty ⇒ none).

§class_latents_emb: Option<Param<Tensor<2>>>

The class-latent embeddings, [num_class_latents, d_model] (None ⇒ none).

Implementations§

§

impl<M> Layer<M>
where M: Block,

pub fn insert_latents( &self, x: Tensor<3>, class: Option<&mut ClassCursor>, ) -> Tensor<3>

Splice this layer’s class latents into the chunk x (no-op when there are none), advancing class past it.

Public so a caller driving a bare Layer can lengthen the sequence itself (and add the matching residual) before calling Self::forward. None cursors ⇒ this chunk is the whole sequence. Layers splices its layers’ latents itself, since under MultiGate residuals the same rows must also enter the carried streams.

pub fn forward( &self, x: Tensor<3>, cache: Option<<M as Block>::Cache>, options: <M as Block>::Options, ) -> (Tensor<3>, <M as Block>::Cache)

Full-sequence Pre-LN block without the outer residual: the layer’s total delta M(RMSNorm(x)), plus the feed-forward sub-block’s own contribution when Self::mlp is set (see the type docs).

The caller owns any class-latent insertion (Self::insert_latents) and the outer residual.

pub fn step( &self, x: Tensor<2>, cache: Option<<M as Block>::Cache>, class: Option<&mut ClassCursor>, ) -> (Tensor<2>, <M as Block>::Cache)

Single-token Pre-LN block step without the residual.

class is this layer’s own class-latent cursor. With Some, every latent whose position falls on this token is stepped around it — before it (Start/Middle/Custom, which precede a token) or after it (End, which closes the sequence) — each a step of its own. What comes back is the last token the step emitted (see ClassCursors): the user token, unless an End latent follows it, that latent being then the sequence’s true last token. With None no class latents are injected — and Middle/End latents panic (their positions need the full sequence length). The residual is the caller’s responsibility.

pub fn prime( &self, batch: usize, cache: Option<<M as Block>::Cache>, class: Option<&mut ClassCursor>, ) -> (Option<(Tensor<2>, Tensor<2>)>, Option<<M as Block>::Cache>)

Step the class latents this layer has waiting for its next token — with no token of its own, so nothing but class data is consumed.

This is Self::step’s opening half on its own (see ClassCursors): the latents that would have preceded the next token are stepped now, in the same order, so a prime followed by a step runs exactly the sequence that step alone would have. End latents are never primed — closing the sequence, they belong to the step carrying its last token.

Returns the last latent stepped, as the pair (delta, latent) — this layer’s own embedding row alongside the delta it produced, since the caller has no other way to complete the residual (delta + latent, as it does with the token it hands to Self::step). None ⇒ nothing was waiting, and the cache comes back exactly as it went in (None included: a layer that stepped nothing has the state it already had).

pub fn step_one( &self, x: Tensor<2>, cache: Option<<M as Block>::Cache>, ) -> (Tensor<2>, <M as Block>::Cache)

The actual one-token work: no class injection, no outer residual.

Layers’s cascade uses it to place this layer’s class latents from the stack-wide ClassCursors itself, bypassing Self::step’s cursorless guard (that guard rejects Middle/End, which the cascade has already resolved). It is public because an external container that owns the residual — one threading its own state between layers rather than a per-layer cache — needs exactly this: the layer’s delta and the cache it produced, with nothing added.

pub fn step_infinite(&self, x: Tensor<2>) -> Tensor<2>

Stationary fixed point of the Pre-LN block under a constant token, without the residual: the step counterpart of infinitely many identical tokens (closed form, no cache — see Block::block_step_infinite). Cursorless: class latents are not injected (Middle/End latents panic, as in a None-cursor step). The feed-forward sub-block is point-wise, so it composes with the limit: once the mixer output settles, x + h₁ is constant and so is h₂.

Trait Implementations§

§

impl<M> AutodiffModule for Layer<M>
where M: Module + AutodiffModule + ModuleDisplay,

§

fn valid(&self) -> Layer<M>

Returns the same module, but on the inner backend without auto-differentiation.
§

fn from_inner(module: Layer<M>) -> Layer<M>

Wraps an inner module back into an auto-diff module.
§

impl<M> Clone for Layer<M>
where M: Module + ModuleDisplay,

§

fn clone(&self) -> Layer<M>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
§

impl<M> Debug for Layer<M>
where M: Debug + Module,

§

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

Formats the value using the given formatter. Read more
§

impl<M> Display for Layer<M>
where M: Module + ModuleDisplay,

§

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

Formats the value using the given formatter. Read more
§

impl<M> Module for Layer<M>
where M: Module + ModuleDisplay,

§

fn num_params(&self) -> usize

Get the number of parameters the module has, including all of its sub-modules.
§

fn visit<Visitor>(&self, visitor: &mut Visitor)
where Visitor: ModuleVisitor,

Visit each tensor parameter in the module with a visitor.
§

fn map<Mapper>(self, mapper: &mut Mapper) -> Layer<M>
where Mapper: ModuleMapper,

Map each tensor parameter in the module with a mapper.
§

fn collect_devices(&self, devices: Vec<Device>) -> Vec<Device>

Return all the devices found in the underneath module tree added to the given vector without duplicates.
§

fn to_device(self, device: &Device) -> Layer<M>

Move the module and all of its sub-modules to the given device. Read more
§

fn fork(self, device: &Device) -> Layer<M>

Fork the module and all of its sub-modules to the given device. Read more
§

fn devices(&self) -> Vec<Device>

Return all the devices found in the underneath module tree without duplicates.
§

fn no_grad(self) -> Self

Each tensor in the module tree will not require grad. Read more
§

fn freeze_group(self, group: ParamGroup) -> Self

Set require_grad to false for every parameter in the given group, leaving the rest of the module untouched. Read more
§

fn unfreeze_group(self, group: ParamGroup) -> Self

Set require_grad to true for every parameter in the given group, leaving the rest of the module untouched. Read more
§

fn train(self) -> Self
where Self: AutodiffModule,

Move the module and all of its sub-modules to the autodiff backend. Read more
§

fn quantize_weights(self, quantizer: &mut Quantizer) -> Self

Quantize the weights of the module.
§

fn quantize_weights_group( self, quantizer: &mut Quantizer, group: ParamGroup, ) -> Self

Quantize the weights of the given parameter group.
§

fn apply_reparameterization<R>(self, reparameterizer: R) -> Self
where Self: Sized, R: Reparameterizer,

Attach reparameterizations using the given [Reparameterizer]. Read more
§

fn apply_lora(self, lora: Lora) -> Self
where Self: Sized,

Attach LoRA adapters to the module’s 2-D weights, freezing the base weights. Read more
§

fn apply_qlora(self, qlora: QLora) -> Self
where Self: Sized,

Apply QLoRA to the module: quantize the (frozen) base weights and attach trainable LoRA adapters to 2-D weights.
§

fn into_record(self) -> ModuleRecord
where Self: Sized,

Collect this module’s parameters into a ModuleRecord. Read more
§

fn into_record_group(self, group: ParamGroup) -> ModuleRecord
where Self: Sized,

Collect the parameters group names into a ModuleRecord. Read more
§

fn try_load_record(self, record: ModuleRecord) -> Result<Self, RecordError>
where Self: Sized,

Apply a ModuleRecord to this module, returning the loaded module. Read more
§

fn load_record(self, record: ModuleRecord) -> Self
where Self: Sized,

Apply a ModuleRecord to this module, consuming and returning it. Read more
§

fn save_file<P>(self, path: P) -> Result<(), RecordError>
where P: AsRef<Path>, Self: Sized,

Save this module’s parameters to a burnpack file on disk. Read more
§

fn load_file<P>(self, path: P) -> Self
where P: AsRef<Path>, Self: Sized,

Load this module’s parameters from a burnpack file on disk, returning the loaded module. Read more
§

fn try_load_file<P>(self, path: P) -> Result<Self, RecordError>
where P: AsRef<Path>, Self: Sized,

Fallible variant of load_file. Read more
§

impl<M> ModuleDisplay for Layer<M>
where M: Module + ModuleDisplay,

§

fn format(&self, passed_settings: DisplaySettings) -> String

Formats the module with provided display settings. Read more
§

fn custom_settings(&self) -> Option<DisplaySettings>

Custom display settings for the module. Read more
§

fn custom_content(&self, _content: Content) -> Option<Content>

Custom attributes for the module. Read more
§

impl<M> ModuleDisplayDefault for Layer<M>
where M: Module + ModuleDisplay,

§

fn content(&self, content: Content) -> Option<Content>

Attributes of the module used for display purposes. Read more
§

fn num_params(&self) -> usize

Gets the number of the parameters of the module.

Auto Trait Implementations§

§

impl<M> !RefUnwindSafe for Layer<M>

§

impl<M> !UnwindSafe for Layer<M>

§

impl<M> Freeze for Layer<M>
where M: Freeze,

§

impl<M> Send for Layer<M>

§

impl<M> Sync for Layer<M>
where M: Sync,

§

impl<M> Unpin for Layer<M>
where M: Unpin,

§

impl<M> UnsafeUnpin for Layer<M>
where M: UnsafeUnpin,

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
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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, 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.

§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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

Source§

fn to_string(&self) -> String

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

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

Source§

type Error = !

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.