Skip to content

Conversation

@kctezcan
Copy link
Contributor

Description

This is @csjfwang 's implementation of 2D rope, coming from this orignal PR: #1445

Issue Number

Closes #1445
Closes #1109

Checklist before asking for review

  • I have performed a self-review of my code
  • My changes comply with basic sanity checks:
    • I have fixed formatting issues with ./scripts/actions.sh lint
    • I have run unit tests with ./scripts/actions.sh unit-test
    • I have documented my code and I have updated the docstrings.
    • I have added unit tests, if relevant
  • I have tried my changes with data and code:
    • I have run the integration tests with ./scripts/actions.sh integration-test
    • (bigger changes) I have run a full training and I have written in the comment the run_id(s): launch-slurm.py --time 60
    • (bigger changes and experiments) I have shared a hegdedoc in the github issue with all the configurations and runs for this experiments
  • I have informed and aligned with people impacted by my change:
    • for config changes: the MatterMost channels and/or a design doc
    • for changes of dependencies: the MatterMost software development channel

wang85 and others added 30 commits July 16, 2025 10:07
Copy link
Collaborator

@clessig clessig left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can simplify the code if we change the syntax of the forward fct of the attention blocks slightly. This should probably be done consistently for all heads, even those without 2D rope.

)

return iter_start, iter_end
return iter_start, iter_end
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we revert this

def forward(self, tokens, coords=None, use_reentrant=False):
for block in self.ae_aggregation_blocks:
tokens = checkpoint(block, tokens, use_reentrant=use_reentrant)
if isinstance(block, MultiSelfAttentionHead | MultiSelfAttentionHeadLocal):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could avoid the branches if we would follow the approach in the MLP:

def forward(self, *args):

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or some compromise with *args and **kwargs

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Personal preference is the if statement

def forward(self, tokens, coords=None, use_reentrant=False):
for block in self.ae_global_blocks:
tokens = checkpoint(block, tokens, use_reentrant=use_reentrant)
if isinstance(block, MultiSelfAttentionHead | MultiSelfAttentionHeadLocal):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as above: if-statement is not necessary

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

but cleaner to read imho

for _b_idx, block in enumerate(self.fe_blocks):
if isinstance(block, torch.nn.modules.normalization.LayerNorm):
tokens = block(tokens)
elif isinstance(block, MultiSelfAttentionHead | MultiSelfAttentionHeadLocal):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as above

)
self.pe_global = torch.nn.Parameter(pe, requires_grad=False)

### ROPE COORDS ###
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

standard comment:

# rope coords

ks = self.lnorm_k(self.proj_heads_k(x).reshape(s)).to(self.dtype)
vs = self.proj_heads_v(x).reshape(s).to(self.dtype)

if coords is not None:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MultiSelfAttenionHead is a vanilla self attention block. The 2D rope positional encoding makes strong assumption of the structure of the qs and ks. At the very least, we need some documentation on what the option means and when it makes sense. Not sure if there's another good way to ensure proper use of this option (one could have a separate class but then one should make sure there's no code duplication).

@clessig clessig mentioned this pull request Jan 5, 2026
4 tasks
Copy link
Contributor

@sophie-xhonneux sophie-xhonneux left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did a first review of the code and left some comments that should be addressed.

Will check the correctness next


if self.rope_2D:
# Precompute per-cell center coordinates (lat, lon in radians) for 2D RoPE.
# Shape: (num_healpix_cells, ae_local_num_queries, 2)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why isn't the shape (num_healpix_cells, 2)?

### ROPE COORDS ###
self.rope_2D = cf.get("rope_2D", False)
if self.rope_2D:
self.rope_coords = torch.nn.Parameter(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this should be a registered buffer, not parameters

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.



####################################################################################################
def rotary_embedding_2d(coords, dim, base=10000.0):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There should be an option to learn the frequencies, this proposed in the original RoPE (https://arxiv.org/pdf/2403.13298v1 section 3.2 at the end) or we should have a reference explaining why not

k: Key tensor.
cos: Cosine embedding tensor.
sin: Sine embedding tensor.
position_ids: Deprecated and unused; present for API compatibility.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's delete, we have no requirement to be backwards compatible

return torch.cat((-x2, x1), dim=-1)


def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks like 1D-rope to me?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we please label the function as such?

"""

if coords.shape[-1] != 2:
raise ValueError(f"coords last dimension must be 2 (lat, lon); got {coords.shape[-1]}")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we just make these asserts? it is cleaner to read

self.flex_attention = torch.compile(flex_attention, dynamic=False)

def forward(self, x, ada_ln_aux=None):
def forward(self, x, coords=None, ada_ln_aux=None):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From a code perspective I prefer if we decide at init time if this attention module has 2D rope, because a) we may wish to learn the frequencies theta_t and b) we should not use an attention module trained with 2D-rope without it (or at least be very intentional about it)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

Update positional encodings in model to be purely local

4 participants