Files
vosr2_core/models/pos_embed.py
2026-10-20 15:33:43 +08:00

54 lines
2.3 KiB
Python

# Vendored from VOSR's models/pos_embed.py (upstream: EVA-02 rotary
# embeddings, MIT, itself adapted from lucidrains/rotary-embedding-torch),
# trimmed to VisionRotaryEmbeddingFast and its helpers -- the only pieces
# LightningDiT's use_rope path calls.
import torch
from einops import rearrange, repeat
from torch import nn
def broadcat(tensors, dim=-1):
num_tensors = len(tensors)
shape_lens = set(len(t.shape) for t in tensors)
assert len(shape_lens) == 1, "tensors must all have the same number of dimensions"
shape_len = list(shape_lens)[0]
dim = (dim + shape_len) if dim < 0 else dim
dims = list(zip(*map(lambda t: list(t.shape), tensors)))
expandable_dims = [(i, val) for i, val in enumerate(dims) if i != dim]
assert all(len(set(t[1])) <= 2 for t in expandable_dims), "invalid dimensions for broadcastable concatenation"
max_dims = list(map(lambda t: (t[0], max(t[1])), expandable_dims))
expanded_dims = list(map(lambda t: (t[0], (t[1],) * num_tensors), max_dims))
expanded_dims.insert(dim, (dim, dims[dim]))
expandable_shapes = list(zip(*map(lambda t: t[1], expanded_dims)))
tensors = list(map(lambda t: t[0].expand(*t[1]), zip(tensors, expandable_shapes)))
return torch.cat(tensors, dim=dim)
def rotate_half(x):
x = rearrange(x, "... (d r) -> ... d r", r=2)
x1, x2 = x.unbind(dim=-1)
x = torch.stack((-x2, x1), dim=-1)
return rearrange(x, "... d r -> ... (d r)")
class VisionRotaryEmbeddingFast(nn.Module):
def __init__(self, dim, pt_seq_len=16, theta=10000):
super().__init__()
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
t = torch.arange(pt_seq_len) / pt_seq_len * pt_seq_len
freqs = torch.einsum("..., f -> ... f", t, freqs)
freqs = repeat(freqs, "... n -> ... (n r)", r=2)
freqs = broadcat((freqs[:, None, :], freqs[None, :, :]), dim=-1)
freqs_cos = freqs.cos().view(-1, freqs.shape[-1])
freqs_sin = freqs.sin().view(-1, freqs.shape[-1])
self.register_buffer("freqs_cos", freqs_cos)
self.register_buffer("freqs_sin", freqs_sin)
@torch.compiler.disable
def forward(self, t):
cos = self.freqs_cos.clone().to(t.dtype)
sin = self.freqs_sin.clone().to(t.dtype)
return (t * cos + rotate_half(t) * sin).contiguous()