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

Gemma 4 transformer (decoder-only) for autoregressive inference. More...

Inheritance diagram for Mila::Dnn::GemmaTransformer< TDeviceType, TPrecision, TWeightQuantization, TKvCachePolicy >:
Mila::Dnn::LanguageNetwork< TDeviceType, TPrecision > Mila::Dnn::Network< TDeviceType, TPrecision > Mila::Dnn::CompositeComponent< TDeviceType, TPrecision > Mila::Dnn::Component< TDeviceType, TPrecision >

Public Types

using ComponentPtr = typename NetworkBase::ComponentPtr
using DecoderLayerType = IDecoderLayer<TDeviceType, TPrecision>
using GlobalBlockType = GemmaBlock<TDeviceType, TPrecision, true, TWeightQuantization, NoKvCompression>
using LmHeadLinearType = Linear<TDeviceType, TPrecision, TableQuantizationPolicy>
using LocalBlockType = GemmaBlock<TDeviceType, TPrecision, false, TWeightQuantization, TKvCachePolicy>
using MR = typename DeviceTypeTraits<TDeviceType>::memory_resource
using NetworkBase = LanguageNetwork<TDeviceType, TPrecision>
using RmsNormType = RmsNorm<TDeviceType, TPrecision>
using TableQuantizationPolicy
using TensorType = Tensor<TPrecision, MR>
using TokenEmbeddingType = TokenEmbedding<TDeviceType, dtype_t::INT32, TPrecision, TableQuantizationPolicy>
using TokenIndexType = Tensor<dtype_t::INT32, MR>
Public Types inherited from Mila::Dnn::LanguageNetwork< TDeviceType, TPrecision >
using MR = typename DeviceTypeTraits<TDeviceType>::memory_resource
using NetworkBase = Network<TDeviceType, TPrecision>
using StageProbe = std::function<void( std::string_view stage, const TensorType& value )>
 Observer called with each intermediate activation during prefill.
using TensorType = Tensor<TPrecision, MR>
using TokenIndexType = Tensor<TensorDataType::INT32, MR>
Public Types inherited from Mila::Dnn::Network< TDeviceType, TPrecision >
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

 GemmaTransformer (const std::string &name, const GemmaConfig &config, DeviceId device_id)
TokenIndexType & backward (const TokenIndexType &, const TensorType &) override
TensorType & decode (const TokenIndexType &input, dim_t position) override
TensorType & forward (const TokenIndexType &) override
IExecutionContextgetExecutionContext () const
MemoryStats getMemoryStats () const override
 Return the current memory allocation breakdown for this component.
ModelType getModelType () const
MemoryStats getRequiredMemory (const BuildContext &context) const override
 What build( context ) would allocate for the whole model, without allocating.
void loadParameters (PretrainedModelReader &reader)
dim_t parameterCount () const override
 Count parameters across all children.
TensorType & prefill (const TokenIndexType &input) override
TensorType & prefillFrom (const TokenIndexType &input, dim_t start_offset) override
 Chunked prefill starting at an absolute position (prompt-prefix reuse).
void resetKVCache ()
bool rewindKvCache (dim_t position) override
 Rewind every layer's KV cache to position for prefix reuse.
void setStageProbe (typename NetworkBase::StageProbe probe) override
 Install a stage probe on the prefill path.
std::string toString () const override
 Generate a human-readable description.
Public Member Functions inherited from Mila::Dnn::LanguageNetwork< TDeviceType, TPrecision >
 LanguageNetwork (const std::string &name)
virtual TokenIndexType & backward (const TokenIndexType &input, const TensorType &output_grad)=0
 Full backward pass (training).
virtual TensorType & decode (const TokenIndexType &input, dim_t position)=0
 Inference decode – single-token autoregressive step.
virtual TensorType & forward (const TokenIndexType &input)=0
 Full-sequence forward pass.
virtual TensorType & prefill (const TokenIndexType &input)=0
 Inference prefill – process full prompt and populate the KV cache.
virtual TensorType & prefillFrom (const TokenIndexType &input, dim_t start_offset)
 Chunked prefill starting at an absolute position (prompt-prefix reuse).
Public Member Functions inherited from Mila::Dnn::Network< TDeviceType, TPrecision >
 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.
IExecutionContextgetExecutionContext () 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.
CompositeComponentaddComponent (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.
CompositeComponentoperator= (CompositeComponent &&) noexcept=default
CompositeComponentoperator= (const CompositeComponent &)=delete
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).
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.
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

void onBuilding (const BuildContext &context) override
 Hook invoked by build() to allocate component buffers.
void onTrainingModeChanging (TrainingMode training_mode) override
 Hook invoked when training mode is about to change.
void save_ (ModelArchive &archive, SerializationMode) const override
 Hook for concrete classes to save type-specific state.
Protected Member Functions inherited from Mila::Dnn::Network< TDeviceType, TPrecision >
virtual void load_ (ModelArchive &archive, SerializationMode mode) override
 Hook for concrete classes to validate type-specific state on load.
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.
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 >
IExecutionContextgetExecutionContext () 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 &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.
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
 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, WeightQuantPolicy TWeightQuantization = NoWeightQuant, KvCachePolicy TKvCachePolicy = NoKvCompression>
requires PrecisionSupportedOnDevice<TPrecision, TDeviceType>
class Mila::Dnn::GemmaTransformer< TDeviceType, TPrecision, TWeightQuantization, TKvCachePolicy >

Gemma 4 transformer (decoder-only) for autoregressive inference.

Graph: TokenEmbedding -> GemmaBlock x N (heterogeneous local/global) -> RmsNorm -> Linear (lm_head). The embedding sqrt(d) scale and the final logit softcap are handled by the converter and the sampler respectively (see the file header).

Member Typedef Documentation

◆ TableQuantizationPolicy

template<DeviceType TDeviceType, TensorDataType TPrecision, WeightQuantPolicy TWeightQuantization = NoWeightQuant, KvCachePolicy TKvCachePolicy = NoKvCompression>
using Mila::Dnn::GemmaTransformer< TDeviceType, TPrecision, TWeightQuantization, TKvCachePolicy >::TableQuantizationPolicy
Initial value:
std::conditional_t<
TWeightQuantization::kIsQuantized, PerChannelFp8<>, NoWeightQuant>
Definition Policies.ixx:24
Definition Policies.ixx:48

Member Function Documentation

◆ getMemoryStats()

template<DeviceType TDeviceType, TensorDataType TPrecision, WeightQuantPolicy TWeightQuantization = NoWeightQuant, KvCachePolicy TKvCachePolicy = NoKvCompression>
MemoryStats Mila::Dnn::GemmaTransformer< TDeviceType, TPrecision, TWeightQuantization, TKvCachePolicy >::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 >.

◆ getRequiredMemory()

template<DeviceType TDeviceType, TensorDataType TPrecision, WeightQuantPolicy TWeightQuantization = NoWeightQuant, KvCachePolicy TKvCachePolicy = NoKvCompression>
MemoryStats Mila::Dnn::GemmaTransformer< TDeviceType, TPrecision, TWeightQuantization, TKvCachePolicy >::getRequiredMemory ( const BuildContext & context) const
inlineoverridevirtual

What build( context ) would allocate for the whole model, without allocating.

Mirrors onBuilding(): resolve the prefill chunk first, then recurse with the same per-child contexts, then add the transformer's own pooled buffers and apply the two no-double-count corrections. See Specifications/MemoryFootprint.md.

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

◆ onBuilding()

template<DeviceType TDeviceType, TensorDataType TPrecision, WeightQuantPolicy TWeightQuantization = NoWeightQuant, KvCachePolicy TKvCachePolicy = NoKvCompression>
void Mila::Dnn::GemmaTransformer< TDeviceType, TPrecision, TWeightQuantization, TKvCachePolicy >::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:533

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

◆ onTrainingModeChanging()

template<DeviceType TDeviceType, TensorDataType TPrecision, WeightQuantPolicy TWeightQuantization = NoWeightQuant, KvCachePolicy TKvCachePolicy = NoKvCompression>
void Mila::Dnn::GemmaTransformer< TDeviceType, TPrecision, TWeightQuantization, TKvCachePolicy >::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, WeightQuantPolicy TWeightQuantization = NoWeightQuant, KvCachePolicy TKvCachePolicy = NoKvCompression>
dim_t Mila::Dnn::GemmaTransformer< TDeviceType, TPrecision, TWeightQuantization, TKvCachePolicy >::parameterCount ( ) const
inlineoverridevirtual

Count parameters across all children.

Returns
Total number of trainable parameters
Exceptions
std::runtime_errorif called before build()

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

◆ prefillFrom()

template<DeviceType TDeviceType, TensorDataType TPrecision, WeightQuantPolicy TWeightQuantization = NoWeightQuant, KvCachePolicy TKvCachePolicy = NoKvCompression>
TensorType & Mila::Dnn::GemmaTransformer< TDeviceType, TPrecision, TWeightQuantization, TKvCachePolicy >::prefillFrom ( const TokenIndexType & input,
dim_t start_offset )
inlineoverride

Chunked prefill starting at an absolute position (prompt-prefix reuse).

input is the FULL prompt tensor, so the token index and the absolute position coincide; chunking simply starts at start_offset instead of 0. Positions [0, start_offset) must already be resident in the KV caches (rewindKvCache). start_offset must lie inside the prompt so at least one position is prefilled and the returned last-position logits are fresh.

◆ rewindKvCache()

template<DeviceType TDeviceType, TensorDataType TPrecision, WeightQuantPolicy TWeightQuantization = NoWeightQuant, KvCachePolicy TKvCachePolicy = NoKvCompression>
bool Mila::Dnn::GemmaTransformer< TDeviceType, TPrecision, TWeightQuantization, TKvCachePolicy >::rewindKvCache ( dim_t position)
inlineoverridevirtual

Rewind every layer's KV cache to position for prefix reuse.

All-or-nothing from the caller's perspective: returns true only when every layer accepted. On false the caller falls back to a full prefill, which positionally overwrites all caches – so a partial rewind (some layers moved, a bounded ring refused) needs no cleanup.

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

◆ save_()

template<DeviceType TDeviceType, TensorDataType TPrecision, WeightQuantPolicy TWeightQuantization = NoWeightQuant, KvCachePolicy TKvCachePolicy = NoKvCompression>
void Mila::Dnn::GemmaTransformer< TDeviceType, TPrecision, TWeightQuantization, TKvCachePolicy >::save_ ( ModelArchive & archive,
SerializationMode mode ) const
inlineoverrideprotectedvirtual

Hook for concrete classes to save type-specific state.

REQUIRED override for concrete networks. Must write:

  • Type identifier (e.g., "type": "MnistClassifier")
  • Configuration parameters (batch_size, architecture constants)
  • Shape metadata (for validation during Load())

This metadata enables the concrete class's Load() method to reconstruct the network.

Example implementation:

void save_(ModelArchive& archive, SerializationMode mode) const override
{
json meta;
meta["type"] = "MnistClassifier"; // Type identifier for runtime dispatch
meta["batch_size"] = batch_size_;
meta["input_shape"] = leading_shape_;
// ... other configuration
archive.writeJson("network/classifier_meta.json", meta);
}
void save_(ModelArchive &archive, SerializationMode) const override
Hook for concrete classes to save type-specific state.
Definition Gemma.ixx:698
ModelArchive provides high-level helpers for component serialization.
Definition ModelArchive.ixx:47
Parameters
archiveArchive to write to
modeSerialization mode (passed from save())

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

◆ setStageProbe()

template<DeviceType TDeviceType, TensorDataType TPrecision, WeightQuantPolicy TWeightQuantization = NoWeightQuant, KvCachePolicy TKvCachePolicy = NoKvCompression>
void Mila::Dnn::GemmaTransformer< TDeviceType, TPrecision, TWeightQuantization, TKvCachePolicy >::setStageProbe ( typename NetworkBase::StageProbe probe)
inlineoverridevirtual

Install a stage probe on the prefill path.

Empty function clears it.

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

◆ toString()

template<DeviceType TDeviceType, TensorDataType TPrecision, WeightQuantPolicy TWeightQuantization = NoWeightQuant, KvCachePolicy TKvCachePolicy = NoKvCompression>
std::string Mila::Dnn::GemmaTransformer< TDeviceType, TPrecision, TWeightQuantization, TKvCachePolicy >::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/Transformers/Gemma/Gemma.ixx