File size: 22,795 Bytes
9c890d3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 | # (c) Meta Platforms, Inc. and affiliates. Confidential and proprietary.
"""Relative-ray attention adapted from UCPE and PRoPE.
This file contains code adapted from:
* UCPE, Copyright (c) 2026 Cheng Zhang
https://github.com/chengzhag/UCPE
* PRoPE, "Cameras as Relative Positional Encoding"
https://arxiv.org/abs/2507.10496
Both sources are distributed under the MIT License:
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from __future__ import annotations
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
_GEOMETRY_EPS = 1e-06
_UP_PERTURBATION_RADIANS = 0.1
def _normalize(vector: torch.Tensor) -> torch.Tensor:
return F.normalize(vector, dim=-1, eps=_GEOMETRY_EPS)
def _invert_se3(transform: torch.Tensor) -> torch.Tensor:
rotation_inv = transform[..., :3, :3].transpose(-1, -2)
inverse = torch.zeros_like(transform)
inverse[..., :3, :3] = rotation_inv
inverse[..., :3, 3] = -torch.einsum(
"...ij,...j->...i", rotation_inv, transform[..., :3, 3]
)
inverse[..., 3, 3] = 1.0
return inverse
def _validate_camera_inputs(
T_world_cam: torch.Tensor, T_pix_cam: torch.Tensor
) -> tuple[int, int]:
if T_world_cam.ndim != 4 or T_world_cam.shape[-2:] != (4, 4):
raise ValueError(
(
f"T_world_cam must have shape [batch, frames, 4, 4], got "
f"{tuple(T_world_cam.shape)}"
)
)
if T_pix_cam.ndim != 4 or T_pix_cam.shape[-2:] not in ((3, 3), (4, 4)):
raise ValueError(
(
f"T_pix_cam must have shape [batch, frames, 3, 3] or "
f"[batch, frames, 4, 4], got {tuple(T_pix_cam.shape)}"
)
)
if T_world_cam.shape[:2] != T_pix_cam.shape[:2]:
raise ValueError(
(
"T_world_cam and T_pix_cam must have matching batch/frame "
"dimensions"
)
)
if T_world_cam.device != T_pix_cam.device:
raise ValueError("T_world_cam and T_pix_cam must be on the same device")
return (int(T_world_cam.shape[0]), int(T_world_cam.shape[1]))
def build_relative_ray_transforms(
T_world_cam: torch.Tensor,
T_pix_cam: torch.Tensor,
*,
image_height: int,
image_width: int,
patch_size: int,
tubelet_size: int,
) -> torch.Tensor:
(batch_size, num_frames) = _validate_camera_inputs(T_world_cam, T_pix_cam)
if min(image_height, image_width, patch_size, tubelet_size) <= 0:
raise ValueError(
"image dimensions, patch_size, and tubelet_size must be positive"
)
num_tubelets = num_frames // tubelet_size
spatial_height = image_height // patch_size
spatial_width = image_width // patch_size
if num_tubelets == 0 or spatial_height == 0 or spatial_width == 0:
raise ValueError(
"camera sequence and image must contain at least one tubelet"
)
frame_indices = (
torch.arange(num_tubelets, device=T_world_cam.device, dtype=torch.long)
* tubelet_size
)
with torch.amp.autocast(device_type=T_world_cam.device.type, enabled=False):
return _build_relative_ray_transforms_fp32(
T_world_cam,
T_pix_cam,
frame_indices=frame_indices,
batch_size=batch_size,
num_tubelets=num_tubelets,
spatial_height=spatial_height,
spatial_width=spatial_width,
patch_size=patch_size,
)
def _build_relative_ray_transforms_fp32(
T_world_cam: torch.Tensor,
T_pix_cam: torch.Tensor,
*,
frame_indices: torch.Tensor,
batch_size: int,
num_tubelets: int,
spatial_height: int,
spatial_width: int,
patch_size: int,
) -> torch.Tensor:
(camera_to_world, _, _, world_rays) = _build_token_ray_geometry_fp32(
T_world_cam,
T_pix_cam,
frame_indices=frame_indices,
spatial_height=spatial_height,
spatial_width=spatial_width,
patch_size=patch_size,
)
camera_rotation = camera_to_world[..., :3, :3]
camera_y = (
camera_rotation[..., :, 1]
.unsqueeze(-2)
.unsqueeze(-2)
.expand_as(world_rays)
)
ray_x = _normalize(torch.cross(camera_y, world_rays, dim=-1))
ray_y = _normalize(torch.cross(world_rays, ray_x, dim=-1))
ray_to_world_rotation = torch.stack((ray_x, ray_y, world_rays), dim=-1)
camera_center = (
camera_to_world[..., :3, 3]
.unsqueeze(-2)
.unsqueeze(-2)
.expand_as(world_rays)
)
ray_to_world = torch.zeros(
(batch_size, num_tubelets, spatial_height, spatial_width, 4, 4),
device=T_world_cam.device,
dtype=torch.float32,
)
ray_to_world[..., :3, :3] = ray_to_world_rotation
ray_to_world[..., :3, 3] = camera_center
ray_to_world[..., 3, 3] = 1.0
world_to_ray = _invert_se3(ray_to_world)
return world_to_ray.flatten(1, 3)
def _build_token_ray_geometry_fp32(
T_world_cam: torch.Tensor,
T_pix_cam: torch.Tensor,
*,
frame_indices: torch.Tensor,
spatial_height: int,
spatial_width: int,
patch_size: int,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
camera_to_world = T_world_cam.index_select(1, frame_indices).float()
intrinsics = T_pix_cam.index_select(1, frame_indices)[..., :3, :3].float()
patch_offset = (patch_size - 1) * 0.5
pixel_x = (
torch.arange(
spatial_width, device=T_world_cam.device, dtype=torch.float32
)
* patch_size
+ patch_offset
)
pixel_y = (
torch.arange(
spatial_height, device=T_world_cam.device, dtype=torch.float32
)
* patch_size
+ patch_offset
)
(grid_y, grid_x) = torch.meshgrid(pixel_y, pixel_x, indexing="ij")
pixels = torch.stack((grid_x, grid_y, torch.ones_like(grid_x)), dim=-1)
camera_rays = torch.einsum(
"btij,hwj->bthwi", torch.linalg.inv(intrinsics), pixels
)
camera_rays = _normalize(camera_rays)
camera_rotation = camera_to_world[..., :3, :3]
world_rays = _normalize(
torch.einsum("btij,bthwj->bthwi", camera_rotation, camera_rays)
)
return (camera_to_world, intrinsics, pixels, world_rays)
def prepare_world_up(
world_up: torch.Tensor | None,
world_up_valid: torch.Tensor | None,
*,
batch_size: int,
device: torch.device,
) -> tuple[torch.Tensor, torch.Tensor]:
if world_up_valid is not None:
if (
world_up_valid.shape != (batch_size,)
or world_up_valid.dtype != torch.bool
):
raise ValueError("world_up_valid must be bool with shape (B,)")
if world_up_valid.device != device:
raise ValueError(
"world_up_valid and camera poses must be on the same device"
)
if world_up is None:
if world_up_valid is not None and bool(world_up_valid.any()):
raise ValueError("valid gravity requires world_up")
return (
torch.zeros(batch_size, 3, device=device),
torch.zeros(batch_size, dtype=torch.bool, device=device),
)
if world_up.shape != (batch_size, 3) or not world_up.is_floating_point():
raise ValueError("world_up must be floating point with shape (B, 3)")
if world_up.device != device:
raise ValueError("world_up and camera poses must be on the same device")
valid = (
torch.ones(batch_size, dtype=torch.bool, device=device)
if world_up_valid is None
else world_up_valid
)
up = torch.where(valid[:, None], world_up.float(), 0.0)
norms = torch.linalg.vector_norm(up, dim=-1)
invalid = valid & (
~torch.isfinite(up).all(-1)
| ~torch.isfinite(norms)
| (norms <= _GEOMETRY_EPS)
)
if bool(invalid.any()):
raise ValueError("valid world_up directions must be finite and nonzero")
return (up / norms.clamp_min(_GEOMETRY_EPS)[:, None], valid)
def build_lat_up_encoding(
T_world_cam: torch.Tensor,
T_pix_cam: torch.Tensor,
*,
world_up: torch.Tensor,
image_height: int,
image_width: int,
patch_size: int,
tubelet_size: int,
) -> torch.Tensor:
(batch_size, num_frames) = _validate_camera_inputs(T_world_cam, T_pix_cam)
if min(image_height, image_width, patch_size, tubelet_size) <= 0:
raise ValueError(
"image dimensions, patch_size, and tubelet_size must be positive"
)
if (
world_up.shape != (batch_size, 3)
or world_up.device != T_world_cam.device
):
raise ValueError("world_up must have shape (B, 3) on the camera device")
if not world_up.is_floating_point() or not bool(
torch.isfinite(world_up).all()
):
raise ValueError("world_up must be finite floating point")
num_tubelets = num_frames // tubelet_size
spatial_height = image_height // patch_size
spatial_width = image_width // patch_size
if num_tubelets == 0 or spatial_height == 0 or spatial_width == 0:
raise ValueError(
"camera sequence and image must contain at least one tubelet"
)
frame_indices = (
torch.arange(num_tubelets, device=T_world_cam.device, dtype=torch.long)
* tubelet_size
)
with torch.amp.autocast(device_type=T_world_cam.device.type, enabled=False):
lat_up = _build_lat_up_encoding_fp32(
T_world_cam,
T_pix_cam,
world_up=world_up,
frame_indices=frame_indices,
spatial_height=spatial_height,
spatial_width=spatial_width,
patch_size=patch_size,
)
return lat_up.reshape(
batch_size, num_tubelets * spatial_height * spatial_width, 3
)
def _build_lat_up_encoding_fp32(
T_world_cam: torch.Tensor,
T_pix_cam: torch.Tensor,
*,
world_up: torch.Tensor,
frame_indices: torch.Tensor,
spatial_height: int,
spatial_width: int,
patch_size: int,
) -> torch.Tensor:
(camera_to_world, intrinsics, pixels, world_rays) = (
_build_token_ray_geometry_fp32(
T_world_cam,
T_pix_cam,
frame_indices=frame_indices,
spatial_height=spatial_height,
spatial_width=spatial_width,
patch_size=patch_size,
)
)
up_direction = _normalize(world_up.float())[:, None, None, None, :]
vertical = (world_rays * up_direction).sum(dim=-1)
horizontal_norm = torch.linalg.vector_norm(
torch.cross(world_rays, up_direction.expand_as(world_rays), dim=-1),
dim=-1,
)
latitude = torch.atan2(vertical, horizontal_norm)
up = _build_up_map_fp32(
world_rays,
camera_to_world[..., :3, :3],
intrinsics,
pixels,
up_direction,
)
return torch.cat((latitude.unsqueeze(-1), up), dim=-1)
def _build_up_map_fp32(
world_rays: torch.Tensor,
camera_rotation: torch.Tensor,
intrinsics: torch.Tensor,
pixels: torch.Tensor,
world_up: torch.Tensor,
) -> torch.Tensor:
world_up = world_up.expand_as(world_rays)
rotation_axes = torch.cross(world_rays, world_up, dim=-1)
axis_norm = torch.linalg.vector_norm(rotation_axes, dim=-1, keepdim=True)
valid_axis = axis_norm > _GEOMETRY_EPS
rotation_axes = rotation_axes / axis_norm.clamp_min(_GEOMETRY_EPS)
cos_delta = math.cos(_UP_PERTURBATION_RADIANS)
sin_delta = math.sin(_UP_PERTURBATION_RADIANS)
axis_dot_ray = (rotation_axes * world_rays).sum(dim=-1, keepdim=True)
rotated_world_rays = (
world_rays * cos_delta
+ torch.cross(rotation_axes, world_rays, dim=-1) * sin_delta
+ rotation_axes * axis_dot_ray * (1.0 - cos_delta)
)
rotated_camera_rays = torch.einsum(
"btji,bthwj->bthwi", camera_rotation, rotated_world_rays
)
projected = torch.einsum(
"btij,bthwj->bthwi", intrinsics, rotated_camera_rays
)
depth = projected[..., 2:3]
safe_depth = torch.where(depth >= 0.0, 1.0, -1.0) * depth.abs().clamp_min(
_GEOMETRY_EPS
)
rotated_pixels = projected[..., :2] / safe_depth
pixel_offsets = rotated_pixels - pixels[..., :2]
offset_norm = torch.linalg.vector_norm(pixel_offsets, dim=-1, keepdim=True)
valid = valid_axis & (depth > _GEOMETRY_EPS) & (offset_norm > _GEOMETRY_EPS)
normalized_offsets = pixel_offsets / offset_norm.clamp_min(_GEOMETRY_EPS)
return torch.where(
valid, normalized_offsets, torch.zeros_like(normalized_offsets)
)
def _apply_tiled_transform(
features: torch.Tensor, transform: torch.Tensor
) -> torch.Tensor:
(batch_size, num_heads, sequence_length, feature_dim) = features.shape
if feature_dim % 4 != 0:
raise ValueError("SE(3) feature block must be divisible by 4")
grouped = features.reshape(
batch_size, num_heads, sequence_length, feature_dim // 4, 4
)
transformed = torch.einsum("blij,bhlpj->bhlpi", transform, grouped)
return transformed.reshape_as(features)
def _rope_coefficients(
positions: torch.Tensor, feature_dim: int
) -> tuple[torch.Tensor, torch.Tensor]:
if feature_dim % 2 != 0:
raise ValueError("RoPE feature block must be even")
num_frequencies = feature_dim // 2
frequencies = 100.0 ** (
-torch.arange(
num_frequencies, device=positions.device, dtype=torch.float32
)
/ num_frequencies
)
angles = positions.float()[None, None, :, None] * frequencies
return (torch.cos(angles), torch.sin(angles))
def _apply_rope(
features: torch.Tensor,
coefficients: tuple[torch.Tensor, torch.Tensor],
*,
inverse: bool = False,
) -> torch.Tensor:
(cos, sin) = coefficients
(first, second) = features.chunk(2, dim=-1)
if inverse:
return torch.cat(
(cos * first - sin * second, sin * first + cos * second), dim=-1
)
return torch.cat(
(cos * first + sin * second, -sin * first + cos * second), dim=-1
)
def _apply_ucpe_transform(
features: torch.Tensor,
se3_transform: torch.Tensor,
rope_x: tuple[torch.Tensor, torch.Tensor],
rope_y: tuple[torch.Tensor, torch.Tensor],
*,
inverse_rope: bool = False,
) -> torch.Tensor:
feature_dtype = features.dtype
with torch.amp.autocast(device_type=features.device.type, enabled=False):
quarter_dim = features.shape[-1] // 4
(se3_features, x_features, y_features) = torch.split(
features.float(),
[2 * quarter_dim, quarter_dim, quarter_dim],
dim=-1,
)
se3_features = _apply_tiled_transform(
se3_features, se3_transform.float()
)
x_features = _apply_rope(x_features, rope_x, inverse=inverse_rope)
y_features = _apply_rope(y_features, rope_y, inverse=inverse_rope)
transformed = torch.cat((se3_features, x_features, y_features), dim=-1)
return transformed.to(dtype=feature_dtype)
class RelativeRayAttention(nn.Module):
def __init__(
self,
dim: int,
num_heads: int,
compression: int = 8,
dropout: float = 0.0,
use_absolute_orientation: bool = False,
) -> None:
super().__init__()
if dim <= 0 or num_heads <= 0 or compression <= 0:
raise ValueError("dim, num_heads, and compression must be positive")
if dim % compression != 0 or num_heads % compression != 0:
raise ValueError("compression must divide both dim and num_heads")
if dim % num_heads != 0:
raise ValueError("num_heads must divide dim")
if dim // num_heads % 8 != 0:
raise ValueError("attention head dimension must be divisible by 8")
if not 0.0 <= dropout < 1.0:
raise ValueError("dropout must be in [0, 1)")
self.dim = dim
self.num_heads = num_heads // compression
self.head_dim = dim // num_heads
self.attention_dim = dim // compression
self.dropout = dropout
self.q_proj = nn.Linear(dim, self.attention_dim)
self.k_proj = nn.Linear(dim, self.attention_dim)
self.v_proj = nn.Linear(dim, self.attention_dim)
self.out_proj = nn.Linear(self.attention_dim, dim)
self.lat_up_proj = (
nn.Linear(3, dim) if use_absolute_orientation else None
)
nn.init.zeros_(self.out_proj.weight)
nn.init.zeros_(self.out_proj.bias)
def forward(
self,
tokens: torch.Tensor,
ray_transforms: torch.Tensor,
*,
spatial_height: int,
spatial_width: int,
lat_up_encoding: torch.Tensor | None = None,
lat_up_valid: torch.Tensor | None = None,
) -> torch.Tensor:
if tokens.ndim != 3 or tokens.shape[-1] != self.dim:
raise ValueError(
(
f"tokens must have shape [batch, length, {self.dim}], got "
f"{tuple(tokens.shape)}"
)
)
(batch_size, sequence_length, _) = tokens.shape
if ray_transforms.shape != (batch_size, sequence_length, 4, 4):
raise ValueError(
(
f"ray_transforms must have shape [{batch_size}, "
f"{sequence_length}, 4, 4], got "
f"{tuple(ray_transforms.shape)}"
)
)
if ray_transforms.device != tokens.device:
raise ValueError(
"tokens and ray_transforms must be on the same device"
)
if lat_up_encoding is not None:
expected_lat_up_shape = (batch_size, sequence_length, 3)
if lat_up_encoding.shape != expected_lat_up_shape:
raise ValueError(
(
"lat_up_encoding must have shape "
f"{expected_lat_up_shape}, "
f"got {tuple(lat_up_encoding.shape)}"
)
)
if lat_up_encoding.device != tokens.device:
raise ValueError(
"tokens and lat_up_encoding must be on the same device"
)
if self.lat_up_proj is None:
raise ValueError(
"lat_up_encoding requires use_absolute_orientation=True"
)
spatial_tokens = spatial_height * spatial_width
if spatial_height <= 0 or spatial_width <= 0:
raise ValueError("spatial dimensions must be positive")
if sequence_length % spatial_tokens != 0:
raise ValueError(
"token length must be divisible by the spatial token count"
)
attention_tokens = tokens
if lat_up_encoding is not None:
assert self.lat_up_proj is not None
if lat_up_valid is not None:
if (
lat_up_valid.shape != (batch_size,)
or lat_up_valid.dtype != torch.bool
):
raise ValueError(
"lat_up_valid must be bool with shape (B,)"
)
if lat_up_valid.device != tokens.device:
raise ValueError(
"lat_up_valid and tokens must be on the same device"
)
lat_up_encoding = torch.where(
lat_up_valid[:, None, None], lat_up_encoding, 0.0
)
orientation_bias = self.lat_up_proj(
lat_up_encoding.to(dtype=tokens.dtype)
)
if lat_up_valid is not None:
orientation_bias = torch.where(
lat_up_valid[:, None, None], orientation_bias, 0.0
)
attention_tokens = attention_tokens + orientation_bias
q = self._project(self.q_proj(attention_tokens))
k = self._project(self.k_proj(attention_tokens))
v = self._project(self.v_proj(attention_tokens))
num_frames = sequence_length // spatial_tokens
x_positions = torch.arange(
spatial_width, device=tokens.device, dtype=torch.float32
).repeat(spatial_height)
y_positions = torch.arange(
spatial_height, device=tokens.device, dtype=torch.float32
).repeat_interleave(spatial_width)
x_positions = x_positions.repeat(num_frames)
y_positions = y_positions.repeat(num_frames)
rope_dim = self.head_dim // 4
with torch.amp.autocast(device_type=tokens.device.type, enabled=False):
rope_x = _rope_coefficients(x_positions, rope_dim)
rope_y = _rope_coefficients(y_positions, rope_dim)
ray_transforms_fp32 = ray_transforms.float()
inverse_ray_transforms = _invert_se3(ray_transforms_fp32)
q = _apply_ucpe_transform(
q, ray_transforms_fp32.transpose(-1, -2), rope_x, rope_y
)
k = _apply_ucpe_transform(k, inverse_ray_transforms, rope_x, rope_y)
v = _apply_ucpe_transform(v, inverse_ray_transforms, rope_x, rope_y)
output = F.scaled_dot_product_attention(
q, k, v, dropout_p=self.dropout if self.training else 0.0
)
output = _apply_ucpe_transform(
output, ray_transforms_fp32, rope_x, rope_y, inverse_rope=True
)
output = output.transpose(1, 2).reshape(
batch_size, sequence_length, self.attention_dim
)
return self.out_proj(output)
def _project(self, projected_tokens: torch.Tensor) -> torch.Tensor:
(batch_size, sequence_length, _) = projected_tokens.shape
return projected_tokens.reshape(
batch_size, sequence_length, self.num_heads, self.head_dim
).transpose(1, 2)
|