|
Mila
Deep Neural Network Library
|
Routes each token to its top_k experts. More...
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 ¶m_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 ¶meter_name, const Tensor< TParameterPrecision, TMemoryResource > ¶meter) 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 > ¶meter, 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. | |
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).
|
inline |
Select experts for every token of input.
| input | [..., hidden_size], the residual stream the router reads unnormalized. |
|
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.
Implements Mila::Dnn::Component< TDeviceType, TPrecision >.
|
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.
Reimplemented from Mila::Dnn::Component< TDeviceType, TPrecision >.
|
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 >.
|
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 >.
|
inlineoverridevirtual |
Get the component type identifier.
Used for serialization and runtime type identification.
Implements Mila::Dnn::Component< TDeviceType, TPrecision >.
|
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.
| archive | Archive to read from, scoped to this composite. |
| mode | Serialization mode (passed to children). |
| std::runtime_error | if the composite is not built. |
Reimplemented from Mila::Dnn::CompositeComponent< TDeviceType, TPrecision >.
|
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:
Takes the parameter name used to locate the target tensor, and a blob holding serialized tensor metadata and raw bytes.
| std::runtime_error | if component has no parameters to load. |
| std::runtime_error | if blob shape doesn't match parameter shape. |
Reimplemented from Mila::Dnn::Component< TDeviceType, TPrecision >.
|
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.
The default implementation forwards to the legacy onBuilding( const shape_t& ) overload for backwards compatibility. New components should override this overload directly.
Takes the build-time configuration; use its allocationSeqLen() to obtain the correct output buffer sequence dimension.
Reimplemented from Mila::Dnn::Component< TDeviceType, TPrecision >.
|
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 >.
|
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().
| training_mode | New training mode (Normal or Eval) |
Reimplemented from Mila::Dnn::CompositeComponent< TDeviceType, TPrecision >.
|
inlineoverridevirtual |
The projection and the two owned vectors; the norm's derived weight is not counted.
Reimplemented from Mila::Dnn::CompositeComponent< TDeviceType, TPrecision >.
|
inlineoverrideprotectedvirtual |
Reimplemented from Mila::Dnn::CompositeComponent< TDeviceType, TPrecision >.
|
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 >.
|
inlineoverridevirtual |
Generate a human-readable description.
Reimplemented from Mila::Dnn::CompositeComponent< TDeviceType, TPrecision >.