MCPcopy Create free account
hub / github.com/apple/ml-pointersect / positional_encoding

Function positional_encoding

pointersect/models/model_utils.py:199–250  ·  view source on GitHub ↗

r"""Apply positional encoding to the input. Args: tensor: (*, dim_in) Input tensor to be positionally encoded. num_encoding_functions: Number of encoding functions used to compute a positional encoding (default: 6). include_input: Whet

(
        tensor: torch.Tensor,
        num_encoding_functions: int = 6,
        include_input: bool = True,
        log_sampling: bool = True,
)

Source from the content-addressed store, hash-verified

197
198
199def positional_encoding(
200 tensor: torch.Tensor,
201 num_encoding_functions: int = 6,
202 include_input: bool = True,
203 log_sampling: bool = True,
204) -> torch.Tensor:
205 r"""Apply positional encoding to the input.
206
207 Args:
208 tensor:
209 (*, dim_in) Input tensor to be positionally encoded.
210 num_encoding_functions:
211 Number of encoding functions used to compute a positional encoding (default: 6).
212 include_input:
213 Whether to include the input in the positional encoding (default: True).
214 log_sampling:
215 whether to sample the sinusoid frequencies in log scale.
216
217 Returns:
218 (torch.Tensor): Positional encoding of the input tensor. (*, dim_out)
219
220 .. math::
221 dim_{out} = d_{in} * include_input + num_encoding_functions * 2
222 """
223 encoding = [tensor] if include_input else []
224 frequency_bands = None
225 if log_sampling:
226 frequency_bands = 2.0 ** torch.linspace(
227 0.0,
228 num_encoding_functions - 1,
229 num_encoding_functions,
230 dtype=tensor.dtype,
231 device=tensor.device,
232 )
233 else:
234 frequency_bands = torch.linspace(
235 2.0 ** 0.0,
236 2.0 ** (num_encoding_functions - 1),
237 num_encoding_functions,
238 dtype=tensor.dtype,
239 device=tensor.device,
240 )
241
242 for freq in frequency_bands:
243 for func in [torch.sin, torch.cos]:
244 encoding.append(func(tensor * freq))
245
246 # Special case, for no positional encoding
247 if len(encoding) == 1:
248 return encoding[0]
249 else:
250 return torch.cat(encoding, dim=-1)
251
252
253def get_embedding_function(

Callers 1

get_embedding_functionFunction · 0.85

Calls 1

catMethod · 0.45

Tested by

no test coverage detected