Encode (x, y) with sinusoidal PE. x, y: [N] normalized to [0,1].
(x: torch.Tensor, y: torch.Tensor, num_pos_feats: int = 128,
temperature: int = 10000, scale: float = 2 * math.pi)
| 89 | # ── Sinusoidal position encoding (matches PositionEmbeddingSine) ────────── |
| 90 | |
| 91 | def sine_encode_xy(x: torch.Tensor, y: torch.Tensor, num_pos_feats: int = 128, |
| 92 | temperature: int = 10000, scale: float = 2 * math.pi): |
| 93 | """Encode (x, y) with sinusoidal PE. x, y: [N] normalized to [0,1].""" |
| 94 | x_embed = x * scale |
| 95 | y_embed = y * scale |
| 96 | |
| 97 | dim_t = torch.arange(num_pos_feats, dtype=torch.float32, device=x.device) |
| 98 | dim_t = temperature ** (2 * (dim_t // 2) / num_pos_feats) |
| 99 | |
| 100 | pos_x = x_embed[:, None] / dim_t # [N, 128] |
| 101 | pos_y = y_embed[:, None] / dim_t # [N, 128] |
| 102 | pos_x = torch.stack((pos_x[:, 0::2].sin(), pos_x[:, 1::2].cos()), dim=2).flatten(1) # [N, 128] |
| 103 | pos_y = torch.stack((pos_y[:, 0::2].sin(), pos_y[:, 1::2].cos()), dim=2).flatten(1) # [N, 128] |
| 104 | return pos_x, pos_y |
| 105 | |
| 106 | |
| 107 | def sine_encode_boxes(cx, cy, w, h, num_pos_feats=128, temperature=10000): |