Mila
Deep Neural Network Library
Loading...
Searching...
No Matches
Mila::Dnn::Router< TDeviceType, TPrecision > Class Template Referenceexport

Routes each token to its top_k experts. More...

Inheritance diagram for Mila::Dnn::Router< TDeviceType, TPrecision >:
Mila::Dnn::CompositeComponent< TDeviceType, TPrecision > Mila::Dnn::Component< TDeviceType, TPrecision >

Classes

struct  Routing
 One call's result. Both views are router-owned and valid until the next forward(). More...

Public Types

using CompositeComponentBase = CompositeComponent<TDeviceType, TPrecision>
using IndexTensorType = Tensor<TensorDataType::INT32, MR>
using LinearType = Linear<TDeviceType, TPrecision>
using MR = typename DeviceTypeTraits<TDeviceType>::memory_resource
using RmsNormType = RmsNorm<TDeviceType, TPrecision>
using TensorType = Tensor<TPrecision, MR>
Public Types inherited from Mila::Dnn::CompositeComponent< TDeviceType, TPrecision >
using ComponentBase = Component<TDeviceType, TPrecision>
using ComponentPtr = std::shared_ptr<Component<TDeviceType, TPrecision>>

Public Member Functions

 Router (const std::string &name, const RouterConfig &config, std::optional< DeviceId > device_id=std::nullopt)
Routing forward (const TensorType &input)
 Select experts for every token of input.
MemoryStats getMemoryStats () const override
 Return the current memory allocation breakdown for this component.
std::vector< ObservableStage > getObservableStages () const override
 Stages this component publishes, and the passes each is published on.
std::vector< std::string > getParameterNames () const override
 List all available parameter names for this component.
MemoryStats getRequiredMemory (const BuildContext &context) const override
 What onBuilding() would allocate for this context, without allocating.
const ComponentType getType () const override
 Get the component type identifier.
void loadParameter (const std::string &name, const ITensorBlob &blob) override
 Load a parameter from serialized tensor data.
dim_t parameterCount () const override
 The projection and the two owned vectors; the norm's derived weight is not counted.
void saveFlatTensors (Serialization::SafeTensorsWriter &writer, const std::string &prefix, Serialization::TensorSavePass pass) const override
 The checkpoint's vocabulary: the projection, then the two owned vectors.
std::string toString () const override
 Generate a human-readable description.
Public Member Functions inherited from Mila::Dnn::CompositeComponent< TDeviceType, TPrecision >
 CompositeComponent (CompositeComponent &&) noexcept=default
 CompositeComponent (const CompositeComponent &)=delete
 CompositeComponent (const std::string &name)
 Construct composite component with name.
CompositeComponent & addComponent (ComponentPtr component)
 Add a pre-constructed child component (chainable).
size_t childCount () const noexcept
 Get the number of direct children.
void clearComponents ()
 Clear all child components.
std::vector< std::string > componentPaths () const
 Every component path in this subtree, in traversal order.
ComponentPtr findComponent (const std::string &path) const
 Resolve a dot-separated component path within this composite.
ComponentPtr getComponent (const std::string &name) const
 Retrieve a direct child component by name.
const std::vector< ComponentPtr > & getComponents () const
 Get all child components in insertion order.
DeviceId getDeviceId () const override
 Get the compute device for this composite.
std::vector< ITensor * > getGradients () const override
 Get all parameter gradients from all children.
std::vector< ITensor * > getParameters () const override
 Get all parameters from all children.
bool hasChildren () const noexcept
 Check if this composite has any children.
bool hasComponent (const std::string &name) const
 Check if a named child component exists.
size_t observe (std::string_view pattern, Compute::ComputePassMask passes, Compute::ActivationObserver sink)
 Attach sink to every component in this subtree whose path matches.
CompositeComponent & operator= (CompositeComponent &&) noexcept=default
CompositeComponent & operator= (const CompositeComponent &)=delete
bool removeComponent (const std::string &name)
 Remove a child component by name.
void stopObserving ()
 Detach every observer in this subtree and clear the shared sink.
void synchronize () override
 Synchronize all child components.
ComponentPtr tryFindComponent (const std::string &path) const
 Try to resolve a dot-separated component path within this composite.
Public Member Functions inherited from Mila::Dnn::Component< TDeviceType, TPrecision >
 Component (const std::string &name)
 Construct component with required name identifier.
virtual void build (const BuildContext &context) final
 Build the component with the provided BuildContext (canonical overload).
IExecutionContext * getExecutionContext () const
 Get the shared execution context.
const std::string getName () const
 Get the component's name identifier.
Compute::ComputePassMask getObservedPasses () const noexcept
virtual std::vector< const ITensor * > getOutputs () const
 Return non-owning pointers to the tensors this component produces.
RuntimeMode getRuntimeMode () const noexcept
TrainingMode getTrainingMode () const noexcept
 The current runtime behavioral mode of this Component.
virtual bool isBuilt () const final
 Returns true if build() has completed successfully.
bool isInferenceMode () const noexcept
bool isTrainingMode () const noexcept
void setObservedPasses (Compute::ComputePassMask passes) noexcept
 Select which passes this component publishes on.
void setTrainingMode (TrainingMode mode)
 Set the runtime behavioral mode for this Component.
virtual void zeroGradients ()
 Clear all model-owned gradients for this component.

Protected Member Functions

void load_ (ModelArchive &archive, SerializationMode mode) override
 Restore children from their nested scopes, mirroring save_().
void onBuilding (const BuildContext &context) override
 Hook invoked by build() to allocate component buffers.
void onExecutionContextSet () override
 Hook invoked after ExecutionContext is set.
void onTrainingModeChanging (TrainingMode training_mode) override
 Hook invoked when training mode is about to change.
void save_ (ModelArchive &archive, SerializationMode mode) const override
Protected Member Functions inherited from Mila::Dnn::CompositeComponent< TDeviceType, TPrecision >
template<typename TComponent>
std::shared_ptr< TComponent > getComponentAs (const std::string &name) const
 Retrieve a typed child component by name.
virtual void optimize ()
 Virtual hook for graph optimization after construction.
void requireSerializableParameters () const override
 No-op override: a composite names no parameters of its own.
Protected Member Functions inherited from Mila::Dnn::Component< TDeviceType, TPrecision >
bool hasExecutionContext () const noexcept
 Check if execution context has been set.
template<TensorDataType TParameterPrecision, typename TMemoryResource>
void loadParameterFromBlob (const std::string &param_name, const Serialization::ITensorBlob &blob, Tensor< TParameterPrecision, TMemoryResource > &target, const shape_t &expected_shape)
 Load a tensor blob into a parameter tensor with validation.
void publish (Compute::ComputePass pass, std::string_view stage, const ITensor &value) const
 Publish one activation to the observer, if this pass is being observed.
template<TensorDataType TParameterPrecision, typename TMemoryResource>
void saveParameterToArchive (ModelArchive &archive, const std::string &parameter_name, const Tensor< TParameterPrecision, TMemoryResource > &parameter) const
 Write one parameter tensor into the archive under "tensors/<name>".
template<TensorDataType TParameterPrecision, typename TMemoryResource>
void saveParameterToWriter (Serialization::SafeTensorsWriter &writer, const std::string &flat_name, const Tensor< TParameterPrecision, TMemoryResource > &parameter, Serialization::TensorSavePass pass) const
 Drive one parameter through one pass of a flat safetensors save.
void setExecutionContext (IExecutionContext *context)
 Set the execution context for this component.

Additional Inherited Members

Static Public Member Functions inherited from Mila::Dnn::Component< TDeviceType, TPrecision >
static constexpr DeviceType getDeviceType ()
 Compile-time device type for this component instance.
static constexpr TensorDataType getPrecision () noexcept
 Compile-time tensor precision for this component instance.
Protected Types inherited from Mila::Dnn::Component< TDeviceType, TPrecision >
using HostStagingMemoryResource = typename DeviceTypeTraits<TDeviceType>::host_staging_memory_resource
 Host memory a device-resident parameter stages through.
Protected Attributes inherited from Mila::Dnn::Component< TDeviceType, TPrecision >
BuildContext build_context_ { shape_t{ 1 }, RuntimeMode::Training }
 The BuildContext stored at build time.

Detailed Description

template<DeviceType TDeviceType, TensorDataType TPrecision>
requires PrecisionSupportedOnDevice<TPrecision, TDeviceType>
class Mila::Dnn::Router< TDeviceType, TPrecision >

Routes each token to its top_k experts.

The unscaled RMS norm and the learned scale are expressed as one RmsNorm child whose weight is scale * hidden_size^-0.5, derived whenever scale is initialized or loaded. That weight is therefore not a parameter of its own: the flat vocabulary is the checkpoint's – proj.weight, scale, per_expert_scale – and the derived weight is never written to it.

Inference-only. The projection stays unquantized: the router is a precision holdout (MixtureOfExperts.md section 7.5).

Member Function Documentation

◆ forward()

template<DeviceType TDeviceType, TensorDataType TPrecision>
Routing Mila::Dnn::Router< TDeviceType, TPrecision >::forward ( const TensorType & input)
inline

Select experts for every token of input.

Parameters
input[..., hidden_size], the residual stream the router reads unnormalized.
Returns
Combine weights [..., top_k] and expert indices [..., top_k]. Order within a row carries no meaning: the combine is a sum over the selected experts.

◆ getMemoryStats()

template<DeviceType TDeviceType, TensorDataType TPrecision>
MemoryStats Mila::Dnn::Router< TDeviceType, TPrecision >::getMemoryStats ( ) const
inlineoverridevirtual

Return the current memory allocation breakdown for this component.

Reflects allocations at the moment of the call. The returned stats naturally track the component lifecycle:

After construction – nothing; construction allocates none After build( Inference ) – parameters + T=1 state buffers After build( Training ) – parameters + T=full state buffers After setTrainingMode( Train ) – parameters + state + gradients

For CompositeComponent and Network, the returned stats are the recursive aggregate of all child components.

May be called at any time – no lifecycle preconditions.

Returns
MemoryStats reflecting current allocations.

Implements Mila::Dnn::Component< TDeviceType, TPrecision >.

◆ getObservableStages()

template<DeviceType TDeviceType, TensorDataType TPrecision>
std::vector< ObservableStage > Mila::Dnn::Router< TDeviceType, TPrecision >::getObservableStages ( ) const
inlineoverridevirtual

Stages this component publishes, and the passes each is published on.

Lets a caller tell an uninstrumented component from a clean one before running anything. The pass qualifier is load-bearing rather than decorative: the stage set genuinely differs by pass, since a prefill can produce intermediates its decode never materializes.

Returns
Vector of stages; empty for components that publish nothing.

Reimplemented from Mila::Dnn::Component< TDeviceType, TPrecision >.

◆ getParameterNames()

template<DeviceType TDeviceType, TensorDataType TPrecision>
std::vector< std::string > Mila::Dnn::Router< TDeviceType, TPrecision >::getParameterNames ( ) const
inlineoverridevirtual

List all available parameter names for this component.

Returns an empty vector by default. Leaf components with parameters should override to return their canonical parameter name list in the same stable order used by save_() and loadParameter().

Reimplemented from Mila::Dnn::Component< TDeviceType, TPrecision >.

◆ getRequiredMemory()

template<DeviceType TDeviceType, TensorDataType TPrecision>
MemoryStats Mila::Dnn::Router< TDeviceType, TPrecision >::getRequiredMemory ( const BuildContext & context) const
inlineoverridevirtual

What onBuilding() would allocate for this context, without allocating.

Children by name, sized as onBuilding() builds them: both read the input shape.

Reimplemented from Mila::Dnn::Component< TDeviceType, TPrecision >.

◆ getType()

template<DeviceType TDeviceType, TensorDataType TPrecision>
const ComponentType Mila::Dnn::Router< TDeviceType, TPrecision >::getType ( ) const
inlineoverridevirtual

Get the component type identifier.

Used for serialization and runtime type identification.

Returns
Component type enum value.

Implements Mila::Dnn::Component< TDeviceType, TPrecision >.

◆ load_()

template<DeviceType TDeviceType, TensorDataType TPrecision>
void Mila::Dnn::Router< TDeviceType, TPrecision >::load_ ( ModelArchive & archive,
SerializationMode mode )
inlineoverrideprotectedvirtual

Restore children from their nested scopes, mirroring save_().

Walks the same children in the same order under the same scopes, so a child's blobs are read from exactly the paths they were written to. Restores into the live graph – the composite and its children must already be constructed and built.

Parameters
archiveArchive to read from, scoped to this composite.
modeSerialization mode (passed to children).
Exceptions
std::runtime_errorif the composite is not built.

Reimplemented from Mila::Dnn::CompositeComponent< TDeviceType, TPrecision >.

◆ loadParameter()

template<DeviceType TDeviceType, TensorDataType TPrecision>
void Mila::Dnn::Router< TDeviceType, TPrecision >::loadParameter ( const std::string & name,
const ITensorBlob & blob )
inlineoverridevirtual

Load a parameter from serialized tensor data.

Loads raw tensor bytes directly into an existing parameter tensor, handling precision conversion and device upload as needed.

The component validates that the blob's shape matches the parameter's expected shape, then delegates to the backend to perform:

  • Precision conversion (blob dtype -> parameter dtype)
  • Device upload (CPU bytes -> target device)

Takes the parameter name used to locate the target tensor, and a blob holding serialized tensor metadata and raw bytes.

Exceptions
std::runtime_errorif component has no parameters to load.
std::runtime_errorif blob shape doesn't match parameter shape.

Reimplemented from Mila::Dnn::Component< TDeviceType, TPrecision >.

◆ onBuilding()

template<DeviceType TDeviceType, TensorDataType TPrecision>
void Mila::Dnn::Router< TDeviceType, TPrecision >::onBuilding ( const BuildContext & context)
inlineoverrideprotectedvirtual

Hook invoked by build() to allocate component buffers.

Receives the stored BuildContext. Implementations must use config.allocationSeqLen() when sizing output buffers – this is the single call that makes Inference and Training allocate the correct buffer sizes automatically without per-component logic.

// Example -- Linear component:
shape_t out_shape =
{
config.batchSize(),
config.allocationSeqLen(), // 1 for Inference, T for Training
config_.getOutputFeatures()
};
output_ = std::make_unique<TensorType>( device, out_shape,
this->getName() + ".output" );
TensorShape shape_t
Row-major shape descriptor for tensor dimensional sizes.
Definition Tensor.Types.ixx:173
const std::string getName() const
Get the component's name identifier.
Definition Component.ixx:522

The default implementation forwards to the legacy onBuilding( const shape_t& ) overload for backwards compatibility. New components should override this overload directly.

Note
Do not call build() or onBuilding() from within this hook.
Implementations should either succeed fully or leave no partial state, as a failed build() may be retried.

Takes the build-time configuration; use its allocationSeqLen() to obtain the correct output buffer sequence dimension.

Reimplemented from Mila::Dnn::Component< TDeviceType, TPrecision >.

◆ onExecutionContextSet()

template<DeviceType TDeviceType, TensorDataType TPrecision>
void Mila::Dnn::Router< TDeviceType, TPrecision >::onExecutionContextSet ( )
inlineoverrideprotectedvirtual

Hook invoked after ExecutionContext is set.

Propagates the execution context to all child components that don't already have one. This enables the pattern where composites define their architecture graph in the constructor (context-independent) and context is bound later when available.

Called by Component::setExecutionContext() after the context is registered. Automatically invoked for both standalone mode (component creates own context) and shared mode (parent provides context).

Override this in derived classes if additional context-dependent initialization is required beyond context propagation to children.

Reimplemented from Mila::Dnn::CompositeComponent< TDeviceType, TPrecision >.

◆ onTrainingModeChanging()

template<DeviceType TDeviceType, TensorDataType TPrecision>
void Mila::Dnn::Router< TDeviceType, TPrecision >::onTrainingModeChanging ( TrainingMode training_mode)
inlineoverrideprotectedvirtual

Hook invoked when training mode is about to change.

Propagates the new mode to all child components. The hook runs with the Component's training mutex held; it MUST NOT call setTrainingMode().

Parameters
training_modeNew training mode (Normal or Eval)

Reimplemented from Mila::Dnn::CompositeComponent< TDeviceType, TPrecision >.

◆ parameterCount()

template<DeviceType TDeviceType, TensorDataType TPrecision>
dim_t Mila::Dnn::Router< TDeviceType, TPrecision >::parameterCount ( ) const
inlineoverridevirtual

The projection and the two owned vectors; the norm's derived weight is not counted.

Reimplemented from Mila::Dnn::CompositeComponent< TDeviceType, TPrecision >.

◆ save_()

template<DeviceType TDeviceType, TensorDataType TPrecision>
void Mila::Dnn::Router< TDeviceType, TPrecision >::save_ ( ModelArchive & archive,
SerializationMode mode ) const
inlineoverrideprotectedvirtual

◆ saveFlatTensors()

template<DeviceType TDeviceType, TensorDataType TPrecision>
void Mila::Dnn::Router< TDeviceType, TPrecision >::saveFlatTensors ( Serialization::SafeTensorsWriter & writer,
const std::string & prefix,
Serialization::TensorSavePass pass ) const
inlineoverridevirtual

The checkpoint's vocabulary: the projection, then the two owned vectors.

Deliberately not the base recursion, which would also write the norm child's derived weight – a tensor no checkpoint carries and every load would have to ignore.

Reimplemented from Mila::Dnn::CompositeComponent< TDeviceType, TPrecision >.

◆ toString()

template<DeviceType TDeviceType, TensorDataType TPrecision>
std::string Mila::Dnn::Router< TDeviceType, TPrecision >::toString ( ) const
inlineoverridevirtual

Generate a human-readable description.

Returns
String representation showing children

Reimplemented from Mila::Dnn::CompositeComponent< TDeviceType, TPrecision >.


The documentation for this class was generated from the following file:
  • Mila/Src/Dnn/Components/MixtureOfExperts/Router.ixx