File size: 3,017 Bytes
8b003e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# (c) Copyright 2026 Zenseact AB
"""Embeddings of the encoder inputs: the positional encoding of the points and the voxel size embedding."""

import math

import torch
from torch import nn


class PEDynamic(nn.Module):
    """Sinusoidal positional encoding of Attention Is All You Need (https://arxiv.org/abs/1706.03762), computed for
    arbitrary positions."""

    def __init__(self, embed_dim: int, pos_dim: int, max_freq: float):
        """Initialize.

        Args:
            embed_dim: Dimensionality of the positional encoding.
            pos_dim: Dimensionality of the positions to encode.
            max_freq: Maximum frequency value.
        """
        super().__init__()
        # Too many encodings are computed if the dimensionalities do not line up, and cut off in forward.
        dim_offset = embed_dim % (pos_dim * 2)
        self._embed_dim = embed_dim
        axis_dim = math.ceil((embed_dim + dim_offset) / pos_dim)
        fqs = torch.arange(axis_dim // 2, dtype=torch.float)
        fqs = torch.exp(-2 * (fqs / axis_dim) * math.log(max_freq))
        self.register_buffer("_fqs", fqs.unsqueeze(0))

    def forward(self, pos: torch.Tensor) -> torch.Tensor:
        """(..., pos_dim) positions -> (..., embed_dim) positional encodings."""
        pe = pos.unsqueeze(-1) * self._fqs  # (..., N, 1) * (1, D/N/2) -> (..., N, D/N/2)
        pe = pe.flatten(start_dim=-2, end_dim=-1)  # (..., N, D/N/2) -> (..., D/2)
        pe = torch.cat([torch.sin(pe), torch.cos(pe)], dim=-1)  # (..., D)
        # Cutting off after the concatenation only drops cosines, of different axes.
        return pe[..., : self._embed_dim]


def log_voxel_size_coordinate(voxel_size: torch.Tensor, voxel_size_range: tuple[float, float]) -> torch.Tensor:
    """log2 voxel size mapped linearly so that the training range of voxel sizes spans [-1, 1]."""
    low, high = math.log2(voxel_size_range[0]), math.log2(voxel_size_range[1])
    return (voxel_size.float().log2() - (low + high) / 2) / ((high - low) / 2)


class VoxelSizeEmbedding(nn.Module):
    """Fourier features of the normalised log voxel size (see log_voxel_size_coordinate) followed by a small MLP."""

    def __init__(self, out_dim: int, num_freqs: int = 8, hidden_dim: int = 64):
        super().__init__()
        # 0.25*pi .. 2*pi: at most two periods over [-1, 1], so the embedding stays smooth in the voxel size. Not in
        # the checkpoints, and computed on the CPU as in training so that the values are the same.
        freqs = math.pi * 2 ** torch.linspace(-2, 1, num_freqs, device="cpu")
        self.register_buffer("_freqs", freqs, persistent=False)
        self._mlp = nn.Sequential(nn.Linear(2 * num_freqs + 1, hidden_dim), nn.GELU(), nn.Linear(hidden_dim, out_dim))

    def forward(self, u: torch.Tensor) -> torch.Tensor:
        """(B,) normalised log voxel sizes -> (B, out_dim)."""
        u = u.float().unsqueeze(-1)
        phase = u * self._freqs
        return self._mlp(torch.cat([u, phase.sin(), phase.cos()], dim=-1))