|
Mila
Deep Neural Network Library
|
Root composite network container. More...
Public Types | |
| using | ComponentPtr = typename CompositeBase::ComponentPtr |
| using | CompositeBase = CompositeComponent<TDeviceType, TPrecision> |
| using | MR = typename DeviceTypeTraits<TDeviceType>::memory_resource |
| 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 | |
| Network (const std::string &name) | |
| Construct network (context managed by derived class). | |
| template<typename TOptimizer, typename TConfig> | |
| std::shared_ptr< TOptimizer > | createOptimizer (const TConfig &config) |
| Create and configure an optimizer for this network's parameters. | |
| DeviceId | getDeviceId () const noexcept override |
| Get the compute device for this composite. | |
| IExecutionContext * | getExecutionContext () const |
| Public access to the network's shared execution context. | |
| const ComponentType | getType () const override |
| Get the component type identifier. | |
| void | load (ModelArchive &archive, SerializationMode mode) |
| Restore this network's parameters from an archive. | |
| void | save (ModelArchive &archive, SerializationMode mode) const |
| Save network to archive. | |
| void | synchronize () override |
| Synchronize all child components. | |
| 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. | |
| 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. | |
| 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. | |
| CompositeComponent & | operator= (CompositeComponent &&) noexcept=default |
| CompositeComponent & | operator= (const CompositeComponent &)=delete |
| dim_t | parameterCount () const override |
| Count parameters across all children. | |
| bool | removeComponent (const std::string &name) |
| void | saveFlatTensors (Serialization::SafeTensorsWriter &writer, const std::string &prefix, Serialization::TensorSavePass pass) const override |
| Recurse into children, extending the flat dotted prefix. | |
| 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). | |
| virtual MemoryStats | getMemoryStats () const =0 |
| Return the current memory allocation breakdown for this component. | |
| const std::string | getName () const |
| Get the component's name identifier. | |
| virtual std::vector< std::string > | getParameterNames () const |
| List all available parameter names for this component. | |
| virtual MemoryStats | getRequiredMemory (const BuildContext &context) const |
| Report what build( context ) would allocate, without allocating it. | |
| TrainingMode | getTrainingMode () const noexcept |
| The current runtime behavioral mode of this Component. | |
| virtual bool | isBuilt () const final |
| Returns true if build() has completed successfully. | |
| virtual void | loadParameter (const std::string &, const Serialization::ITensorBlob &) |
| Load a parameter from serialized tensor data. | |
| 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 | |
| virtual void | load_ (ModelArchive &archive, SerializationMode mode) override |
| Hook for concrete classes to validate type-specific state on load. | |
| virtual void | save_ (ModelArchive &archive, SerializationMode mode) const override=0 |
| Hook for concrete classes to save type-specific state. | |
| void | verifyArchitectureCompatibility (const PretrainedMetadata &metadata) |
| Verify that imported model is compatible with network architecture. | |
| 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. | |
| void | onExecutionContextSet () override |
| Hook invoked after ExecutionContext is set. | |
| void | onTrainingModeChanging (TrainingMode training_mode) override |
| Hook invoked when training mode is about to change. | |
| 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 > | |
| IExecutionContext * | getExecutionContext () const |
| Get the shared execution context. | |
| 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. | |
| virtual void | onBuilding (const BuildContext &) |
| Hook invoked by build() to allocate component buffers. | |
| 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 |
| 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. | |
Root composite network container.
Network is a specialized CompositeComponent that represents a complete neural network model and serves as the top-level entry point. It provides high-level serialization semantics while delegating lifecycle management to concrete subclasses.
Ownership Model:
Construction Pattern (Concrete Subclass):
Serialization Contract:
Deserialization Pattern (Concrete Subclass):
Design Rationale:
|
inlineexplicit |
Construct network (context managed by derived class).
Base constructor for concrete network classes. Derived classes are responsible for:
| name | Network name for identification and serialization |
| std::invalid_argument | if name is not a valid identifier |
|
inline |
Create and configure an optimizer for this network's parameters.
Factory method that creates an optimizer, enables training mode on the network, and registers all network parameters and gradients in a single atomic operation.
Lifecycle:
Usage Pattern:
| TOptimizer | Optimizer type (e.g., AdamWOptimizer, SGD) |
| TConfig | Optimizer configuration type |
| config | Optimizer configuration |
| std::runtime_error | if network is not built |
| std::runtime_error | if parameter/gradient count mismatch |
|
inlineoverridevirtualnoexcept |
Get the compute device for this composite.
Returns the device from the shared execution context.
Reimplemented from Mila::Dnn::CompositeComponent< TDeviceType, TPrecision >.
|
inline |
Public access to the network's shared execution context.
Exposes the Component-level context so model-level orchestrator tools (e.g. TokenSampler) can be constructed on the network's context. Wraps the protected Component accessor.
|
inlineoverridevirtual |
Get the component type identifier.
Used for serialization and runtime type identification.
Implements Mila::Dnn::Component< TDeviceType, TPrecision >.
|
inline |
Restore this network's parameters from an archive.
The inverse of save(). Restores into the LIVE graph: the network must already be constructed with the same topology and built, which is why this is a member and not a factory. Concrete models reconstruct themselves through their own fromCheckpoint() – read the config, construct, build, then call this.
The child manifest is not replayed. saveComponentGraph records names into per-child descriptor files rather than a list, so the live children are the authoritative enumeration; network/architecture.json is read only to check the count, which catches the common "loaded into a different model" mistake before any tensor is touched.
| archive | Archive to read from. |
| mode | Serialization mode. |
| std::runtime_error | if the archive's component count disagrees with this network, or if any component's blobs are missing. |
|
inlineoverrideprotectedvirtual |
Hook for concrete classes to validate type-specific state on load.
Deliberately NOT pure, where save_() is. A concrete network must write its config, because nothing else can; it rarely needs to read it back here, because the config is consumed by the static factory before construction – by the time this runs the network already exists with that geometry. Override only to assert the archive matches what was built.
The empty body also keeps this from being a breaking change for every existing Network subclass.
| archive | Archive to read from. |
| mode | Serialization mode. |
Reimplemented from Mila::Dnn::CompositeComponent< TDeviceType, TPrecision >.
Reimplemented in Mila::Dnn::GptTransformer< TDeviceType, TPrecision >.
|
inline |
Save network to archive.
Saves component graph structure and delegates to concrete class via save_() hook for type-specific configuration.
Archive structure produced:
| archive | Archive to write to |
| mode | Serialization mode (Checkpoint, WeightsOnly, Architecture) |
| std::runtime_error | if save_() is not overridden by concrete class |
|
overrideprotectedpure virtual |
Hook for concrete classes to save type-specific state.
REQUIRED override for concrete networks. Must write:
This metadata enables the concrete class's Load() method to reconstruct the network.
Example implementation:
| archive | Archive to write to |
| mode | Serialization mode (passed from save()) |
Reimplemented from Mila::Dnn::CompositeComponent< TDeviceType, TPrecision >.
Implemented in Mila::Dnn::GemmaTransformer< TDeviceType, TPrecision, TWeightQuantization, TKvCachePolicy >, Mila::Dnn::GptTransformer< TDeviceType, TPrecision >, and Mila::Dnn::LlamaTransformer< TDeviceType, TPrecision, TWeightQuantization, TKvCachePolicy >.
|
inlineoverridevirtual |
Synchronize all child components.
Waits for outstanding device operations on all children.
Reimplemented from Mila::Dnn::CompositeComponent< TDeviceType, TPrecision >.
|
inlineoverridevirtual |
Generate a human-readable description.
Reimplemented from Mila::Dnn::CompositeComponent< TDeviceType, TPrecision >.