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

Elementwise gate over two same-shaped inputs: out = TGate(gate) * value. More...

Inheritance diagram for Mila::Dnn::AttentionOutputGate< TDeviceType, TPrecision, TGate >:
Mila::Dnn::Component< TDeviceType, TPrecision >

Public Types

using ComponentBase = Component<TDeviceType, TPrecision>
using MR = typename DeviceTypeTraits<TDeviceType>::memory_resource
using TensorType = Tensor<TPrecision, MR>

Public Member Functions

 AttentionOutputGate (const std::string &name, const AttentionOutputGateConfig &config=AttentionOutputGateConfig(), std::optional< DeviceId > device_id=std::nullopt)
TensorType & forward (const TensorType &gate, const TensorType &value)
 out = TGate(gate) * value.
DeviceId getDeviceId () const override
 Get the compute device id associated with this component.
std::vector< ITensor * > getGradients () const override
 Return non-owning pointers to parameter gradient tensors.
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< const ITensor * > getOutputs () const override
 Return non-owning pointers to the tensors this component produces.
std::vector< ITensor * > getParameters () const override
 Return non-owning pointers to parameter tensors.
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 installSharedOutput (std::shared_ptr< TensorType > output)
 Install a shared output slot (activation pooling).
dim_t parameterCount () const override
 Return number of trainable parameters.
void save_ (ModelArchive &archive, SerializationMode) const override
void synchronize () override
 Wait for outstanding device work submitted by this component.
std::string toString () const override
 Produce a short, human-readable description of the component.
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< std::string > getParameterNames () const
 List all available parameter names for this component.
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
virtual void load_ (ModelArchive &archive, SerializationMode mode)
 Restore this component's parameters from its archive scope.
virtual void loadParameter (const std::string &, const Serialization::ITensorBlob &)
 Load a parameter from serialized tensor data.
virtual void requireSerializableParameters () const
 Verify this component can serialize whatever parameters it owns.
virtual void saveFlatTensors (Serialization::SafeTensorsWriter &writer, const std::string &prefix, Serialization::TensorSavePass pass) const
 Drive this component's tensors through one pass of a flat safetensors save.
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.

Static Public Member Functions

static constexpr ActivationType getGateType () noexcept
 The compile-time gate function realized by this component.
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 Member Functions

void onBuilding (const BuildContext &build_context) override
 Hook invoked by build() to allocate component buffers.
void onExecutionContextSet () override
 Lifecycle hook: Called immediately after ExecutionContext is set.
void onTrainingModeChanging (TrainingMode training_mode) override
 Hook called before TrainingMode transitions.
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

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, ActivationType TGate = ActivationType::Silu>
requires PrecisionSupportedOnDevice<TPrecision, TDeviceType>
class Mila::Dnn::AttentionOutputGate< TDeviceType, TPrecision, TGate >

Elementwise gate over two same-shaped inputs: out = TGate(gate) * value.

Template Parameters
TDeviceTypeCompile-time device.
TPrecisionActivation/compute precision.
TGateGate function, fixed at compile time. SiLU is the default because it is the common case across gated architectures – NOT because of Qwen 3.8, whose output_gate_type: "swish" is a dead config key its reference implementation never reads. That block passes Sigmoid.

Stateless: no trainable parameters. The gate WEIGHTS are the second half of the query projection and belong to that Linear, not here – which is why this component owns nothing and the parameter budget in Qwen3.8.md section 2 counts the gate under "q (+gate)".

Two launches, not one: the activation runs through the shared ElementwiseActivationOp and the product through the TensorOps multiply, in place over this component's own output. Fusing them into a single kernel would need a new operation type and a dispatch row for a shape that runs on 16 of 64 layers; worth doing only if it ever measures, and the composition is the correct starting point either way.

Member Function Documentation

◆ forward()

template<DeviceType TDeviceType, TensorDataType TPrecision, ActivationType TGate = ActivationType::Silu>
TensorType & Mila::Dnn::AttentionOutputGate< TDeviceType, TPrecision, TGate >::forward ( const TensorType & gate,
const TensorType & value )
inline

out = TGate(gate) * value.

Parameters
gateThe gate half of the query projection, [B, T, num_heads * head_dim].
valueThe attention output, same shape.

The activation writes into this component's output and the product then runs in place over it, which is safe because both are elementwise. Doing it the other way – activating in place over gate – would corrupt a caller-owned buffer that on the pooled path is shared with every other layer.

◆ getDeviceId()

template<DeviceType TDeviceType, TensorDataType TPrecision, ActivationType TGate = ActivationType::Silu>
DeviceId Mila::Dnn::AttentionOutputGate< TDeviceType, TPrecision, TGate >::getDeviceId ( ) const
inlineoverridevirtual

Get the compute device id associated with this component.

Must return the device on which parameters and operations execute.

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

◆ getGradients()

template<DeviceType TDeviceType, TensorDataType TPrecision, ActivationType TGate = ActivationType::Silu>
std::vector< ITensor * > Mila::Dnn::AttentionOutputGate< TDeviceType, TPrecision, TGate >::getGradients ( ) const
inlineoverridevirtual

Return non-owning pointers to parameter gradient tensors.

Gradient buffers are allocated only when the component is built in training mode, so a component built for inference returns an empty vector. Stateless components return empty in either mode. This is the accessor counterpart to getParameters() and does not throw on mode.

Returns
Vector of gradient pointers; empty when built for inference.
Exceptions
std::runtime_errorif called before the component has been built.

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

◆ getMemoryStats()

template<DeviceType TDeviceType, TensorDataType TPrecision, ActivationType TGate = ActivationType::Silu>
MemoryStats Mila::Dnn::AttentionOutputGate< TDeviceType, TPrecision, TGate >::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, ActivationType TGate = ActivationType::Silu>
std::vector< ObservableStage > Mila::Dnn::AttentionOutputGate< TDeviceType, TPrecision, TGate >::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 >.

◆ getOutputs()

template<DeviceType TDeviceType, TensorDataType TPrecision, ActivationType TGate = ActivationType::Silu>
std::vector< const ITensor * > Mila::Dnn::AttentionOutputGate< TDeviceType, TPrecision, TGate >::getOutputs ( ) const
inlineoverridevirtual

Return non-owning pointers to the tensors this component produces.

The counterpart to getParameters(): that reports what a component HOLDS, this reports what it PRODUCES. Tensors are the built allocations, so their extents are the ceiling a forward pass may narrow within – an observer wanting the live value of a particular call receives it through publication instead.

An empty result means the component does not describe itself. That absence cannot be mistaken for a finding – a view renders no row for it – so no distinction beyond empty is offered.

Returns
Vector of output pointers; empty before build, and for undescribed components.

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

◆ getParameters()

template<DeviceType TDeviceType, TensorDataType TPrecision, ActivationType TGate = ActivationType::Silu>
std::vector< ITensor * > Mila::Dnn::AttentionOutputGate< TDeviceType, TPrecision, TGate >::getParameters ( ) const
inlineoverridevirtual

Return non-owning pointers to parameter tensors.

The returned tensor pointers remain valid for the lifetime of the component. Order should be canonical (weights before biases).

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

◆ getRequiredMemory()

template<DeviceType TDeviceType, TensorDataType TPrecision, ActivationType TGate = ActivationType::Silu>
MemoryStats Mila::Dnn::AttentionOutputGate< TDeviceType, TPrecision, TGate >::getRequiredMemory ( const BuildContext & context) const
inlineoverridevirtual

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

The build context carries ONE input shape; gate and value are the same shape, so the output matches it directly. See Specifications/MemoryFootprint.md.

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

◆ getType()

template<DeviceType TDeviceType, TensorDataType TPrecision, ActivationType TGate = ActivationType::Silu>
const ComponentType Mila::Dnn::AttentionOutputGate< TDeviceType, TPrecision, TGate >::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 >.

◆ installSharedOutput()

template<DeviceType TDeviceType, TensorDataType TPrecision, ActivationType TGate = ActivationType::Silu>
void Mila::Dnn::AttentionOutputGate< TDeviceType, TPrecision, TGate >::installSharedOutput ( std::shared_ptr< TensorType > output)
inline

Install a shared output slot (activation pooling).

Must be called before build(). Mirrors Swiglu::installSharedOutput: forward() always returns a shape-adjusted view, so a wider slot never leaks its geometry. The slot is owned and memory-accounted by the installer.

◆ onBuilding()

template<DeviceType TDeviceType, TensorDataType TPrecision, ActivationType TGate = ActivationType::Silu>
void Mila::Dnn::AttentionOutputGate< TDeviceType, TPrecision, TGate >::onBuilding ( const BuildContext & build_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, ActivationType TGate = ActivationType::Silu>
void Mila::Dnn::AttentionOutputGate< TDeviceType, TPrecision, TGate >::onExecutionContextSet ( )
inlineoverrideprotectedvirtual

Lifecycle hook: Called immediately after ExecutionContext is set.

Override this to perform initialization that requires a valid ExecutionContext. At the time this is called, getExecutionContext() is guaranteed to return a valid context.

Common uses:

  • Composite components: Create and configure child components.
  • Device resource allocation: Query device capabilities.

Default implementation does nothing.

Exceptions
Anyexception thrown will cause setExecutionContext() to fail and restore the component to a "context not set" state.

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

◆ onTrainingModeChanging()

template<DeviceType TDeviceType, TensorDataType TPrecision, ActivationType TGate = ActivationType::Silu>
void Mila::Dnn::AttentionOutputGate< TDeviceType, TPrecision, TGate >::onTrainingModeChanging ( TrainingMode training_mode)
inlineoverrideprotectedvirtual

Hook called before TrainingMode transitions.

Called by setTrainingMode() after validation and lock acquisition, before the internal state is updated. Derived classes override to respond to the transition – e.g. zeroing gradient buffers on transition to Eval, or re-enabling dropout on transition to Training.

The default implementation is a no-op.

Takes the incoming TrainingMode.

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

◆ parameterCount()

template<DeviceType TDeviceType, TensorDataType TPrecision, ActivationType TGate = ActivationType::Silu>
dim_t Mila::Dnn::AttentionOutputGate< TDeviceType, TPrecision, TGate >::parameterCount ( ) const
inlineoverridevirtual

Return number of trainable parameters.

For leaf components this is the element count of owned parameter tensors. CompositeComponent and Network implementations should return the recursive aggregate across all children.

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

◆ save_()

template<DeviceType TDeviceType, TensorDataType TPrecision, ActivationType TGate = ActivationType::Silu>
void Mila::Dnn::AttentionOutputGate< TDeviceType, TPrecision, TGate >::save_ ( ModelArchive & archive,
SerializationMode  ) const
inlineoverridevirtual

◆ synchronize()

template<DeviceType TDeviceType, TensorDataType TPrecision, ActivationType TGate = ActivationType::Silu>
void Mila::Dnn::AttentionOutputGate< TDeviceType, TPrecision, TGate >::synchronize ( )
inlineoverridevirtual

Wait for outstanding device work submitted by this component.

On CPU this may be a no-op. Use to ensure results are visible to the host or to measure synchronous timings.

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

◆ toString()

template<DeviceType TDeviceType, TensorDataType TPrecision, ActivationType TGate = ActivationType::Silu>
std::string Mila::Dnn::AttentionOutputGate< TDeviceType, TPrecision, TGate >::toString ( ) const
inlineoverridevirtual

Produce a short, human-readable description of the component.

Implementations should keep output concise and avoid throwing.

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


The documentation for this class was generated from the following file: