import math
import torch
from typing import Union, Tuple
def lex_sign(v: torch.Tensor) -> torch.Tensor:
# more generalized version of sign(v_0)
# due to the fact that v_0 might be zero
first_nonzero = (v != 0).to(torch.uint8).argmax(dim=-1, keepdim=True)
return torch.sign(v.gather(-1, first_nonzero))
def flip_invariant_embedding(
paths: torch.Tensor,
concatenate_results: bool = True
) -> Union[torch.Tensor,
Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]]:
# Assumes path_len to be odd
n, path_len, dimension = paths.size()
flipped_paths = torch.flip(input=paths, dims=[1])
# Shape [n, half, dimension]
half = math.ceil(path_len / 2) # = 8
alpha_sum = 0.5 * (paths[:, :half] + flipped_paths[:, :half])
# Shape [n, half -1, dimension]
alpha_abs_diff = 0.5 * (paths[:, :half-1] - flipped_paths[:, :half-1])
# Calculate the abs for dim 0, for the rest: use relative signing
alpha_abs_diff = alpha_abs_diff * lex_sign(alpha_abs_diff)
# Shape [n, (path_len-3) / 2, dimension]
delta_half_len = (path_len - 3) // 2
delta_sum = 0.5 * (
paths[:, 1 : delta_half_len + 1]
- paths[:, : delta_half_len]
+ flipped_paths[:, 1 : delta_half_len + 1]
- flipped_paths[:, : delta_half_len]
)
# Shape [n, (path_len-3) / 2, dimension]
delta_abs_diff = 0.5 * (
paths[:, 1 : delta_half_len + 1]
- paths[:, : delta_half_len]
- (flipped_paths[:, 1 : delta_half_len + 1]
- flipped_paths[:, : delta_half_len])
)
# Calculate the abs for dim 0, for the rest: use relative signing
delta_abs_diff = delta_abs_diff * lex_sign(delta_abs_diff)
if concatenate_results:
return torch.cat(
(alpha_sum, alpha_abs_diff, delta_sum, delta_abs_diff), dim = 1)
else:
return alpha_sum, alpha_abs_diff, delta_sum, delta_abs_diffSmooth, Invertible Flip-Invariant Vector Embeddings for Undirected 3D Paths
TL;DR
Handling millions of simple undirected 3D paths in geometric deep learning comes with a tradeoff: either you are locked into specific architectures (like graph neural networks) or you handle each path as a vector, which allows usage of more general methods. But by storing undirected paths as vectors you have to handle flips (i.e., cases where you start at one or the other end). This post highlights some solutions for this challenge.
Motivation
Inside the RapidParc project1 I had the following issue: A streamline can be seen as an undirected 3D path: i.e., a chain of vertices with two ends. Each point on the chain is a 3D coordinate. We can assume every streamline to be resampled to 15 supporting points. We get a chain v_{1} - v_{2} - \cdots - v_{15} \; \; \text{ where } v_i \in \mathbb{R}^3. But the catch is: These chains have neither a fixed beginning nor an end. Selecting v_1 as a starting point is as valid as selecting v_{15}.
This results in a problem: we want to reduce each streamline into a single vector, i.e., s_1 := (v_1, \dots, v_{15}) \in \mathbb{R}^{15 \times 3} \text{ or } s_2:= (v_{15}, \dots, v_{1}) \in \mathbb{R}^{15 \times 3}. But mathematically speaking s_1 does not equal s_2.
But is this something that happens only in theory or can we see this behavior in the data?
So yes, as Figure 1 shows, this is a real problem. Another point of view: RapidParc processes bags of streamlines simultaneously. What if some of them are all stored in one direction during training and during inference they are flipped? Can this influence the predictions for a single streamline?
Initial Flip-Invariant Embedding
It would be great to have a function f such that f(v) = f(\text{flip}(v)) where flip is the function that reorders the elements (1, \dots, 15 to 15, \dots, 1).
But not every function f with this attribute is a great choice. (f(x) = 0 does the job, but also discards all information). So f has to be invertible up to the decision whether v_1 or v_{15} is the first element.
My solution for this problem combines two main ideas:
- If f(v) = f(\text{flip}(v)), the first and the last element of the chain have some kind of correspondence, the 2nd with the 14th and so on. Think about a horseshoe.
- The midpoint formula: \frac{x + y \pm \vert x - y \vert}{2} = \{x, y\} \; \; \text{ for any } x, y \in \mathbb{R} While the left-hand side of the equation is (kind of) ordered (x: 1st, y: 2nd), the right-hand side is not (as sets are unordered). In practice, we store the midpoints \frac{x+y}{2} and the signed half-differences \frac{|x-y|_\text{entangle}}{2} (defined in Note 1 below) instead of the sets \{x, y\}.
Combining both ideas, we can define \alpha(v) := \begin{bmatrix}\{v_1, v_{15}\} & \{v_2, v_{14}\}& \cdots & \{v_7, v_{9}\} & \{v_8\} \end{bmatrix}. Note that this representation is flip-invariant as sets do not have an order.
But these sets have a problem. They contain too little information to reconstruct the whole path: If you select for example v_{15} as the first element for reconstruction, v_{14} should be the next choice. But the selection of v_{15} \in \{v_1, v_{15}\} and v_{14} \in \{v_2, v_{14}\} happens independently of each other. That said, v_{15} - v_{2} - \cdots - v_{14} - v_{1} could be a possible reconstruction from the embedding \alpha. Therefore, we have to connect them to a chain again, adding the term:
\delta(v) := \begin{bmatrix}\{v_2-v_1, v_{14} - v_{15}\} & \{v_3 - v_2 , v_{13} - v_{14}\}& \cdots & \{v_7 - v_6, v_9 - v_{10}\}\end{bmatrix}. The final embedding is then defined as: f(v) := \begin{bmatrix}\alpha(v) & \delta(v)\end{bmatrix}
We can also apply the flip-invariant embedding to the example from above:
Improvement: A Smooth Flip-Invariant Embedding
The code above works as shown, but there is one issue with the flip-invariant method itself: Assume we have v_1 - v_{15} = (-0.0001, 2)^T. But if we apply some augmentations first, we get v'_1 - v_{15}' = (0.0001, 2)^T. If we now apply \lvert \cdot \rvert_\text{entangle} we get (0.0001, -2)^T or (0.0001, 2)^T depending on whether the minor augmentation had been applied or not. These points are very far away from each other and we see that \lvert x \rvert_\text{entangle} might behave just as discontinuously as \text{sign}(x).
The solution: Get rid of absolute value calculations altogether.
Smooth Flip-Invariant Embedding
In this section, we define \bar{v}:= \text{flip}(v) to improve readability. As above, we use the good parts of the midpoint formula:
- \text{sym}(v) := \frac{1}{2}(v + \bar{v}) symmetric part, flip-invariant
- \text{asym}(v) := \frac{1}{2}(v - \bar{v}) anti-symmetric part, not flip-invariant
Note:
- v = \text{sym}(v) + \text{asym}(v)
- \text{flip}(v) = \text{sym}(v) - \text{asym}(v)
- \text{sym}(v) is a palindrome (i.e., we only keep the first “half” in memory)
- \text{asym}(v) = \frac{1}{2}(v - \bar{v}) = -\frac{1}{2}(\bar{v} - v) = -\text{asym}(\bar{v}) is point-symmetric (i.e., we only keep the first “half” in memory)
While \text{sym}(v) is already flip-invariant, \text{asym}(v) is not. Therefore, we flatten it a := \text{flatten}(\text{asym}(v)) and then apply a normalized version of the outer product o(a) := \frac{a \cdot a^T}{\| a \|_2 + \varepsilon}. The outer product acts here as a fine-grained sign absorber (like x^2 = (-x)^2) which does not discard the sign-interactions between components.
The resulting smooth flip-invariant embedding is: f_\text{smooth}(v) := \begin{bmatrix} \text{sym}(v) & o(a) \end{bmatrix}
Note:
- The embedding is flip invariant: As \text{asym}(v) = -\text{asym}(\bar{v}) we have a = -\bar{a} where we define \bar{a} := \text{flatten}(\text{asym}(\bar{v})). Therefore, we have \begin{align*} o(a) = \frac{a \cdot a^T}{\| a \|_2 + \varepsilon} = \frac{-\bar{a} \cdot (-\bar{a})^T}{\| -\bar{a} \|_2 + \varepsilon} = \frac{\bar{a} \cdot \bar{a}^T}{\| \bar{a} \|_2 + \varepsilon} = o(\bar{a}) \end{align*}
- We only have to store the upper triangle of o(a) since the outer product is symmetric.
Applying the smooth flip-invariant embedding to the example above, we get:
def smooth_flip_invariant_embedding(
paths: torch.Tensor,
eps: float = 1e-8) -> torch.Tensor:
# Assumes path_len to be odd.
N, path_len, dimension = paths.size()
half = (path_len + 1) // 2 # 8
flipped = torch.flip(paths, dims=[1])
# Symmetric part: [N, 24]
sym = 0.5 * (paths[:, :half] + flipped[:, :half]).flatten(1)
# Antisymmetric part: [N, 21]
asym = 0.5 * (paths[:, :half - 1] - flipped[:, :half - 1]).flatten(1)
# Normalized outer product (upper triangle): [N, 231]
normalized_outer = torch.einsum("bi,bj->bij", asym, asym) / (
asym.norm(dim=-1, keepdim=True).unsqueeze(-1) + eps)
tri_indices = torch.triu_indices(
asym.shape[1], asym.shape[1], device=paths.device)
upper_triangle = normalized_outer[:, tri_indices[0], tri_indices[1]]
return torch.cat([sym, upper_triangle], dim=-1) # [N, 255]Code
####### Example Tensor #######
paths = torch.randn(100,15,3)
print(f"If we embed a tensor of shape {paths.shape},\nwe get "
f"a tensor of shape {smooth_flip_invariant_embedding(paths).shape}. \n")
####### Test if flip invariant #######
is_flip_invariant = \
torch.allclose(
smooth_flip_invariant_embedding(paths),
smooth_flip_invariant_embedding(torch.flip(input=paths, dims=[1])),
atol=1e-6, rtol=1e-5)
if is_flip_invariant:
print("On random data, the embedding is flip invariant.")
else:
print("The embedding is not flip invariant on random data.")If we embed a tensor of shape torch.Size([100, 15, 3]),
we get a tensor of shape torch.Size([100, 255]).
On random data, the embedding is flip invariant.
Alternative: Learned Flip Invariance through Data Augmentation
Data augmentation is a well-established method for telling a model what invariances the data should have. For example: A picture of a cow is still a picture of a cow if you flip it horizontally. Therefore, it is common to apply some random data augmentations to image classification training pipelines (PyTorch transforms gallery lists some examples).
So in terms of streamline paths, randomly flipping them (i.e., reversing the order of supporting points from last to first) during training can teach the model that both forms represent the same streamline path.
Comparison of the Approaches
| Method | Output Size (for 15 \times 3) | Flip-Invariant? | Preserves all Information? | Smooth? (w.r.t. v) |
|---|---|---|---|---|
| No Embedding | 45 | No | Yes | Yes |
| 9D Embedding | 9 | Yes | No | Yes |
| DeepWMA (FiberMap) | 2,700 | Depends on implementation | Usable through / after CNN | CNN: at least C^0 |
| Initial Embedding | 81 | Yes | Yes | No |
| Smooth Embedding | 255 | Yes | Yes | Yes7 |
| Flip Augmentation | 45 | Not guaranteed | Yes | Yes |
Comparison of the Flip-Invariant Embeddings
As we can see in Figure 5, using clustering without an embedding leads to no clear cluster separation. Using the initial flip-invariant embedding leads to a more distinct result. The smooth flip-invariant embedding yields the best results.
Flip-Invariant Embedding vs. Flip Augmentations
- Both flip-invariant embeddings from above guarantee flip invariance of the model in any case. They can be implemented in fast PyTorch code (see above).
- The flip-augmentation-based approach is faster during inference time (no embedding calculations at all) and actually also very flip-stable (see paper).
- During an earlier stage of RapidParc, we compared the (non-smooth) flip-invariant embedding with the flip augmentation approach. Unfortunately, I did not correctly extend the approach to 3D data (see Note 1). This might be why the flip-invariant model performed a bit worse compared to the flip-augmented model in this paper draft. But since the augmentation-based method performed very well (and even a bit faster), there was no fundamental argument to introduce the novel concept of a flip-invariant embedding in the resulting RapidParc paper.
Footnotes
Valentin von Bornhaupt, Justus Bisten et al. RapidParc: A Global-Context Transformer for Parallel, Accurate, and Lesion-Robust Tractogram Parcellation, Imaging Neuroscience (2026) 10.1162/IMAG.a.1168↩︎
Anders Brun et al. Clustering Fiber Traces Using Normalized Cuts, Medical Image Computing and Computer-Assisted Intervention (MICCAI) (2004) 10.1007/978-3-540-30135-6_45↩︎
Fan Zhang et al. Deep white matter analysis (DeepWMA): Fast and consistent tractography segmentation, Medical Image Analysis (2020) 10.1016/j.media.2020.101761↩︎
DeepWMA’s Implementation uses zero-padding with
MaxPooling2D. Note that this breaks the exact flip invariance of the network. For exact analytical flip invariance, the architecture must avoid boundary effects (such as zero-padding) and strided pooling misalignment. Note that this does not mean that the network is not able to learn to handle these ambiguities during training.↩︎Tengfei Xue et al. TractCloud: Registration-Free Tractography Parcellation with a Novel Local-Global Streamline Point Cloud Representation, MICCAI (2023) 10.1007/978-3-031-43993-3_40↩︎
All entries in \text{diag}(a a^T) are non-negative. If they are all zero, then a = \vec{0}.↩︎
The normalized outer product o(a) = \frac{a \cdot a^T}{\|a\|_2 + \varepsilon} is at least in C^2 (in fact, C^\infty everywhere except zero). Select o^*(a) = \frac{a \cdot a^T}{\sqrt{\|a\|_2^2 + \varepsilon^2}} if you are aiming for C^\infty.↩︎
Citation
@online{von_bornhaupt2026,
author = {von Bornhaupt, Valentin},
title = {Smooth, {Invertible} {Flip-Invariant} {Vector} {Embeddings}
for {Undirected} {3D} {Paths}},
date = {2026-11-25},
url = {https://vavobo.de/posts/flip_invariance.html},
langid = {en}
}