Download dflow/rope3d.py from data-archetype/dflow_2b: direct link, hf CLI and curl.
- Browser
- Download file 6.71 kB
-
https://huggingface.co/data-archetype/dflow_2b/resolve/main/dflow/rope3d.py
- Command line
-
hf download hf://data-archetype/dflow_2b/dflow/rope3d.py
-
curl -L -o rope3d.py https://huggingface.co/data-archetype/dflow_2b/resolve/main/dflow/rope3d.py
6.71 kB
| """Centred three-axis rotary position embedding of the joint text-image stream. | |
| Every token has a 3-axis position ``(a, y, x)``; each axis rotates its own | |
| channel pairs of every attention head (``rope_axes_dims`` channels, adjacent | |
| pairs). Text token ``i`` (1-based) of an ``L``-token prompt sits at | |
| ``(i, 0, 0)``. Image token ``(row, col)`` of an ``H x W`` grid sits at | |
| ``(L + 1, row - (H - 1) / 2, col - (W - 1) / 2)``: the grid is centred on the | |
| text, so its spatial positions are half-integers on even sides. Angles are | |
| ``position * theta^(-2k / dim)`` computed in float64 and rounded to float32 | |
| before the sine and cosine; nothing in this module passes through bfloat16. | |
| Two evaluation paths reproduce the trained model bit for bit: | |
| - the text refiner reads rows of a per-axis table built on the CPU with | |
| ``torch.polar`` (``text_rope_rows``); | |
| - the joint stream evaluates its real-valued positions directly on the | |
| positions' device (``joint_rope_rows``). | |
| """ | |
| from __future__ import annotations | |
| from functools import lru_cache | |
| from typing import TYPE_CHECKING | |
| import torch | |
| from torch import Tensor | |
| if TYPE_CHECKING: | |
| from .configuration import DFlowConfig | |
| RopeRows = tuple[Tensor, Tensor] | |
| """``(sin, cos)``, each ``[N, head_width]`` float32, adjacent-pair layout.""" | |
| def validate_rope_capacity( | |
| config: DFlowConfig, *, text_length: int, grid_height: int, grid_width: int | |
| ) -> None: | |
| """Check a prompt length and token grid fit the RoPE capacity. | |
| Raises: | |
| ValueError: If the text or image axis-0 position (``L + 1``) reaches | |
| ``rope_axes_lens[0]``, a grid side exceeds its axis capacity, or a | |
| size is not positive. | |
| """ | |
| axis0, axis1, axis2 = config.rope_axes_lens | |
| if text_length <= 0 or grid_height <= 0 or grid_width <= 0: | |
| raise ValueError( | |
| "text length and token grid must be positive, got " | |
| f"L={text_length}, grid={grid_height}x{grid_width}" | |
| ) | |
| if text_length + 1 >= axis0: | |
| raise ValueError( | |
| f"A {text_length}-token prompt exceeds the RoPE text capacity: the " | |
| f"image sits at axis-0 position {text_length + 1}, which must stay " | |
| f"below {axis0}" | |
| ) | |
| if grid_height > axis1 or grid_width > axis2: | |
| raise ValueError( | |
| f"Token grid {grid_height}x{grid_width} exceeds the RoPE spatial " | |
| f"capacity {axis1}x{axis2}" | |
| ) | |
| def _axis_frequencies(*, dim: int, theta: float, device: torch.device) -> Tensor: | |
| """One axis's float64 rotation frequencies ``theta^(-2k / dim)``.""" | |
| exponents = torch.arange(0, dim, 2, dtype=torch.float64, device=device) | |
| return 1.0 / (theta ** (exponents / float(dim))) | |
| def text_position_ids(length: int, *, device: torch.device) -> Tensor: | |
| """Int64 positions ``(1..L, 0, 0)`` ``[L, 3]`` of an ``L``-token prompt.""" | |
| axis0 = torch.arange(1, length + 1, dtype=torch.int64, device=device) | |
| zeros = torch.zeros_like(axis0) | |
| return torch.stack((axis0, zeros, zeros), dim=-1) | |
| def image_position_ids( | |
| *, text_length: int, grid_height: int, grid_width: int, device: torch.device | |
| ) -> Tensor: | |
| """Float64 centred positions ``[H * W, 3]`` of a row-major token grid after | |
| an ``L``-token prompt: ``(L + 1, row - (H - 1) / 2, col - (W - 1) / 2)``.""" | |
| local = torch.arange(grid_height * grid_width, dtype=torch.int64, device=device) | |
| row = local // grid_width | |
| col = local - row * grid_width | |
| ids = torch.stack((torch.full_like(local, text_length + 1), row, col), dim=-1) | |
| centred = ids.to(torch.float64) | |
| centred[:, 1] -= (grid_height - 1) / 2 | |
| centred[:, 2] -= (grid_width - 1) / 2 | |
| return centred | |
| def rope_rows_at(config: DFlowConfig, positions: Tensor) -> RopeRows: | |
| """RoPE rows of real-valued positions ``[N, 3]`` on their own device. | |
| Angles are ``position * frequency`` in float64, then float32; sine and | |
| cosine run in float32 and repeat over each adjacent channel pair. | |
| """ | |
| sins: list[Tensor] = [] | |
| coses: list[Tensor] = [] | |
| for axis, dim in enumerate(config.rope_axes_dims): | |
| freqs = _axis_frequencies( | |
| dim=dim, theta=config.rope_theta, device=positions.device | |
| ) | |
| angles = torch.outer(positions[:, axis].to(torch.float64), freqs).float() | |
| sins.append(torch.sin(angles).repeat_interleave(2, dim=-1)) | |
| coses.append(torch.cos(angles).repeat_interleave(2, dim=-1)) | |
| return torch.cat(sins, dim=-1), torch.cat(coses, dim=-1) | |
| def _axis_tables(config: DFlowConfig) -> tuple[RopeRows, ...]: | |
| """Per-axis CPU tables ``(sin, cos)`` ``[axis_len, dim]`` of integer | |
| positions, from ``torch.polar`` of the float32-rounded float64 angles.""" | |
| cpu = torch.device("cpu") | |
| tables: list[RopeRows] = [] | |
| for dim, length in zip(config.rope_axes_dims, config.rope_axes_lens, strict=True): | |
| timestep = torch.arange(length, dtype=torch.float64, device=cpu) | |
| freqs = _axis_frequencies(dim=dim, theta=config.rope_theta, device=cpu) | |
| angles = torch.outer(timestep, freqs).float() | |
| rotation = torch.polar(torch.ones_like(angles), angles) | |
| tables.append( | |
| ( | |
| rotation.imag.repeat_interleave(2, dim=-1).float(), | |
| rotation.real.repeat_interleave(2, dim=-1).float(), | |
| ) | |
| ) | |
| return tuple(tables) | |
| def text_rope_rows( | |
| config: DFlowConfig, length: int, *, device: torch.device | |
| ) -> RopeRows: | |
| """RoPE rows ``[L, head_width]`` of an ``L``-token prompt for the text | |
| refiner: rows of the CPU integer-position tables, moved to ``device``.""" | |
| ids = text_position_ids(length, device=torch.device("cpu")) | |
| sins: list[Tensor] = [] | |
| coses: list[Tensor] = [] | |
| for axis, (sin_table, cos_table) in enumerate(_axis_tables(config)): | |
| sins.append(sin_table.index_select(0, ids[:, axis])) | |
| coses.append(cos_table.index_select(0, ids[:, axis])) | |
| return torch.cat(sins, dim=-1).to(device), torch.cat(coses, dim=-1).to(device) | |
| def joint_rope_rows( | |
| config: DFlowConfig, | |
| *, | |
| text_length: int, | |
| grid_height: int, | |
| grid_width: int, | |
| device: torch.device, | |
| ) -> RopeRows: | |
| """RoPE rows ``[H * W + L, head_width]`` of the joint stream | |
| ``[image tokens, text tokens]``, evaluated on ``device``.""" | |
| positions = torch.cat( | |
| ( | |
| image_position_ids( | |
| text_length=text_length, | |
| grid_height=grid_height, | |
| grid_width=grid_width, | |
| device=device, | |
| ), | |
| text_position_ids(text_length, device=device).to(torch.float64), | |
| ), | |
| dim=0, | |
| ) | |
| return rope_rows_at(config, positions) | |