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

Device-templated RoPE component. More...

Inheritance diagram for Mila::Dnn::Rope< TDeviceType, TPrecision >:
Collaboration diagram for Mila::Dnn::Rope< TDeviceType, TPrecision >:

Public Types

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

Public Member Functions

 Rope (const std::string &name, const RopeConfig &config, std::optional< DeviceId > device_id=std::nullopt)
 ~Rope () override=default
std::pair< TensorType &, TensorType & > backward (TensorType &grad_Q, TensorType &grad_K)
 Backpropagate gradients through RoPE.
void decode (TensorType &Q, TensorType &K, int position)
 Single-token decode with explicit position.
void forward (TensorType &Q, TensorType &K)
 Apply rotary position embeddings to Q and K in-place.
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< ITensor * > getParameters () const override
 Return non-owning pointers to parameter tensors.
const ComponentType getType () const override
 Get the component type identifier.
size_t parameterCount () const override
 Return number of trainable parameters.
void prefill (TensorType &Q, TensorType &K, int position_offset)
 Apply rotary position embeddings with an explicit position offset.
void save_ (ModelArchive &archive, SerializationMode mode) 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.
void zeroGradients () override
 Clear all model-owned gradients for this component.
Public Member Functions inherited from Mila::Dnn::Component< TDeviceType, TPrecision >
 Component (const std::string &name)
 Construct component with required name identifier.
virtual ~Component ()=default
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.
RuntimeMode getRuntimeMode () const noexcept
 Convenience accessor — true if currently in Eval mode.
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 loadParameter (const std::string &name, const Serialization::ITensorBlob &blob)
 Load a parameter from serialized tensor data.
void setTrainingMode (TrainingMode mode)
 Set the runtime behavioral mode for this Component.

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 >
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.
void setExecutionContext (IExecutionContext *context)
 Set the execution context for this component.

Private Types

using OpType = typename OperationTraits<OperationType::RopeOp, TDeviceType, TPrecision>::type

Private Member Functions

void createOperation ()
void validateBuildContext (const BuildContext &context) const

Private Attributes

RopeConfig config_
shape_t k_shape_
std::shared_ptr< OpTypeoperation_ { nullptr }
std::unique_ptr< IExecutionContextowned_exec_context_ { nullptr }
std::unique_ptr< TensorTypeowned_K_grad_ { nullptr }
std::unique_ptr< TensorTypeowned_Q_grad_ { nullptr }
IPositionalPairedOppositional_op_ { nullptr }
shape_t q_shape_

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 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::Rope< TDeviceType, TPrecision >

Device-templated RoPE component.

Rotates Q and K in-place using a PairedOperation backend registered as "RopeOp". The component owns no forward output buffers — rotation writes directly back into the caller-provided tensors (typically views into a fused QKV projection buffer).

Supports three dispatch modes: forward(Q, K) — training, positions 0..T-1 prefill(Q, K, position_offset) — chunked prefill, positions offset..offset+T-1 decode(Q, K, position) — single-token KV-cache decode

Positional dispatch (prefill/decode) is available when the backend implements IPositionalPairedOp. The interface pointer is cached at operation creation via dynamic_cast.

This component has no trainable parameters.

Constructor & Destructor Documentation

◆ Rope()

template<DeviceType TDeviceType, TensorDataType TPrecision>
Mila::Dnn::Rope< TDeviceType, TPrecision >::Rope ( const std::string & name,
const RopeConfig & config,
std::optional< DeviceId > device_id = std::nullopt )
inlineexplicitexport

◆ ~Rope()

template<DeviceType TDeviceType, TensorDataType TPrecision>
Mila::Dnn::Rope< TDeviceType, TPrecision >::~Rope ( )
overrideexportdefault

Member Function Documentation

◆ backward()

template<DeviceType TDeviceType, TensorDataType TPrecision>
std::pair< TensorType &, TensorType & > Mila::Dnn::Rope< TDeviceType, TPrecision >::backward ( TensorType & grad_Q,
TensorType & grad_K )
inlineexport

Backpropagate gradients through RoPE.

RoPE is an orthogonal rotation (R^T = R^{-1}), so input gradients are the upstream gradients rotated by the transpose (negative) angles.

Parameters
grad_QUpstream gradient w.r.t. rotated Q.
grad_KUpstream gradient w.r.t. rotated K.
Returns
Pair of references: (grad_Q_in, grad_K_in).
Here is the call graph for this function:

◆ createOperation()

template<DeviceType TDeviceType, TensorDataType TPrecision>
void Mila::Dnn::Rope< TDeviceType, TPrecision >::createOperation ( )
inlineexportprivate
Here is the call graph for this function:
Here is the caller graph for this function:

◆ decode()

template<DeviceType TDeviceType, TensorDataType TPrecision>
void Mila::Dnn::Rope< TDeviceType, TPrecision >::decode ( TensorType & Q,
TensorType & K,
int position )
inlineexport

Single-token decode with explicit position.

Rotates Q and K in-place using the cos/sin cache row at position. Required for KV-cache autoregressive generation where T=1.

Parameters
QQuery tensor [B, 1, n_heads * head_dim]. Mutated in-place.
KKey tensor [B, 1, n_kv_heads * head_dim]. Mutated in-place.
positionAbsolute position of the token in the full sequence.
Here is the call graph for this function:

◆ forward()

template<DeviceType TDeviceType, TensorDataType TPrecision>
void Mila::Dnn::Rope< TDeviceType, TPrecision >::forward ( TensorType & Q,
TensorType & K )
inlineexport

Apply rotary position embeddings to Q and K in-place.

Uses implicit positions 0..T-1. Suitable for training forward passes.

Parameters
QQuery tensor [B, T, n_heads * head_dim]. Mutated in-place.
KKey tensor [B, T, n_kv_heads * head_dim]. Mutated in-place.
Here is the call graph for this function:

◆ getDeviceId()

template<DeviceType TDeviceType, TensorDataType TPrecision>
DeviceId Mila::Dnn::Rope< TDeviceType, TPrecision >::getDeviceId ( ) const
inlineoverrideexportvirtual

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

Here is the call graph for this function:

◆ getGradients()

template<DeviceType TDeviceType, TensorDataType TPrecision>
std::vector< ITensor * > Mila::Dnn::Rope< TDeviceType, TPrecision >::getGradients ( ) const
inlineoverrideexportvirtual

Return non-owning pointers to parameter gradient tensors.

Only valid when isTraining() is true.

Exceptions
std::runtime_errorif called when not in training mode or before the component has been built.

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

◆ getMemoryStats()

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

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 — parameters only After build( Inference ) — parameters + T=1 state buffers After build( Training ) — parameters + T=full state buffers After setEvaluation( false ) — 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 >.

◆ getParameters()

template<DeviceType TDeviceType, TensorDataType TPrecision>
std::vector< ITensor * > Mila::Dnn::Rope< TDeviceType, TPrecision >::getParameters ( ) const
inlineoverrideexportvirtual

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

◆ getType()

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

Get the component type identifier.

Used for serialization and runtime type identification.

Returns
Component type enum value.

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

◆ onBuilding()

template<DeviceType TDeviceType, TensorDataType TPrecision>
void Mila::Dnn::Rope< TDeviceType, TPrecision >::onBuilding ( const BuildContext & config)
inlineoverrideexportprotectedvirtual

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" );
RopeConfig config_
Definition Rope.ixx:295
TensorShape shape_t
Row-major shape descriptor for tensor dimensional sizes.
Definition Tensor.Types.ixx:143

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.
Parameters
configBuild-time configuration. Use config.allocationSeqLen() to obtain the correct output buffer sequence dimension.

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

Here is the call graph for this function:

◆ onExecutionContextSet()

template<DeviceType TDeviceType, TensorDataType TPrecision>
void Mila::Dnn::Rope< TDeviceType, TPrecision >::onExecutionContextSet ( )
inlineoverrideexportprotectedvirtual

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

Here is the call graph for this function:

◆ onTrainingModeChanging()

template<DeviceType TDeviceType, TensorDataType TPrecision>
void Mila::Dnn::Rope< TDeviceType, TPrecision >::onTrainingModeChanging ( TrainingMode mode)
inlineoverrideexportprotectedvirtual

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.

Parameters
modeThe incoming TrainingMode.

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

◆ parameterCount()

template<DeviceType TDeviceType, TensorDataType TPrecision>
size_t Mila::Dnn::Rope< TDeviceType, TPrecision >::parameterCount ( ) const
inlineoverrideexportvirtual

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

◆ prefill()

template<DeviceType TDeviceType, TensorDataType TPrecision>
void Mila::Dnn::Rope< TDeviceType, TPrecision >::prefill ( TensorType & Q,
TensorType & K,
int position_offset )
inlineexport

Apply rotary position embeddings with an explicit position offset.

Each token at chunk-local position t is rotated using the cos/sin cache row at absolute position (t + position_offset). Required for chunked prefill where successive chunks use increasing offsets.

Parameters
QQuery tensor [B, T, n_heads * head_dim]. Mutated in-place.
KKey tensor [B, T, n_kv_heads * head_dim]. Mutated in-place.
position_offsetAbsolute position of the first token in this chunk.
Here is the call graph for this function:

◆ save_()

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

◆ synchronize()

template<DeviceType TDeviceType, TensorDataType TPrecision>
void Mila::Dnn::Rope< TDeviceType, TPrecision >::synchronize ( )
inlineoverrideexportvirtual

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

Here is the call graph for this function:

◆ toString()

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

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

Implementations should keep output concise and avoid throwing.

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

Here is the call graph for this function:

◆ validateBuildContext()

template<DeviceType TDeviceType, TensorDataType TPrecision>
void Mila::Dnn::Rope< TDeviceType, TPrecision >::validateBuildContext ( const BuildContext & context) const
inlineexportprivate
Here is the call graph for this function:
Here is the caller graph for this function:

◆ zeroGradients()

template<DeviceType TDeviceType, TensorDataType TPrecision>
void Mila::Dnn::Rope< TDeviceType, TPrecision >::zeroGradients ( )
inlineoverrideexportvirtual

Clear all model-owned gradients for this component.

Default implementation is a no-op. Composite components should override to recurse to children. Leaf components should override to zero their parameter and activation gradients using device-aware helpers.

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


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