Skip to content
class

RotaryPosEmbeddingBackward

RotaryPosEmbeddingBackward

Autograd node for Rotary Position Embedding (RoPE, Su et al. 2021).

Rotates pairs of features in the last dimension of input by position-dependent angles, encoding absolute position information in a way that lets dot-product attention recover relative position. During the forward, the backend returns a triple {rotated_input, cos, sin}; the cos/sin tables are saved into saved_cos_ and saved_sin_ so the backward can apply the conjugate rotation without recomputing the trigonometry.

interleaved_ selects the pair layout:

  • true — adjacent pairs (d=0, d=1), (d=2, d=3), …
    • false — split-half (d=0, d=D/2), (d=1, d=D/2+1), …

The chosen layout must match how the model was trained or attention scores will be silently corrupted.

Attributes

schema_v1OpSchema
Registered schema (name "rotary_pos_embedding", version 1, AmpPolicy::ForceFP32). Forced to F32 because the rotation math is precision-sensitive at long sequence lengths.
interleaved_bool
Pair-layout flag (see above).
orig_shape_Shape
Saved input shape; used by backward to size the gradient.
saved_cos_Storage
Cosine table produced by the forward kernel.
saved_sin_Storage
Sine table produced by the forward kernel.

Static methods

1
static

forward

→TensorImplPtr
int forward(const int & input, const int & position_ids_or_null, bool interleaved)

Apply RoPE to input.

Parameters

inputTensorImplPtr
Input of shape (…,L,D)(\ldots, L, D) with D even. L is the sequence axis and D is rotated in pairs.
position_ids_or_nullTensorImplPtr
Optional integer position-index tensor of shape (L,). When null, the kernel uses [0, 1, …, L-1] implicitly.
interleavedbool
Pair-layout flag (see class docstring).

Returns

TensorImplPtr

Rotated output with the same shape as input.

Raises

ShapeMismatch
If input is fewer than 2-D or its last dim is odd.
DeviceMismatch
If position_ids_or_null lives on a different device than input.

Methods

3
fn

apply

→std::vector<Storage>
int apply(int grad_out)

Apply the conjugate rotation to grad_out using the saved cos/sin tables.

Parameters

grad_outStorage
Incoming gradient with shape orig_shape_.

Returns

std::vector<Storage>

Single-element {grad_in} of the same shape.

fn

apply_for_graph

int apply_for_graph(const int & grad_out)

The same rotation by −θ-\theta from tracked ops, for create_graph=True; the saved tables are constants.

fn

release_own_saved

void release_own_saved()