Skip to content

torch_world.losses ​

class SIGReg ​

torch_world.losses.SIGReg GitHub

python
SIGReg(num_slices: int = 1024, knots: int = 17, t_max: float = 3.0)

Sketched Isotropic Gaussian Regularization.

Projects embeddings on num_slices random unit directions and averages the Epps-Pulley statistic, which measures each 1D projection's distance from a standard normal by comparing characteristic functions on knots trapezoid points in [0, t_max].

Balestriero & LeCun, "LeJEPA: Provable and Scalable Self-Supervised Learning Without the Heuristics", 2025. Paper: https://arxiv.org/abs/2511.08544 Code: https://github.com/galilai-group/lejepa

Source code in torch_world/losses/sigreg.py
python
class SIGReg(nn.Module):
    """Sketched Isotropic Gaussian Regularization.

    Projects embeddings on ``num_slices`` random unit directions and averages the Epps-Pulley statistic,
    which measures each 1D projection's distance from a standard normal by comparing characteristic
    functions on ``knots`` trapezoid points in ``[0, t_max]``.

    Balestriero & LeCun, "LeJEPA: Provable and Scalable Self-Supervised Learning Without the Heuristics", 2025.
    Paper: https://arxiv.org/abs/2511.08544
    Code: https://github.com/galilai-group/lejepa
    """

    def __init__(self, num_slices: int = 1024, knots: int = 17, t_max: float = 3.0):
        super().__init__()
        self.num_slices = num_slices
        t = torch.linspace(0, t_max, knots)
        dt = t_max / (knots - 1)
        weights = torch.full((knots,), 2 * dt)
        weights[[0, -1]] = dt
        phi = (-t.square() / 2).exp()
        self.register_buffer("t", t)
        self.register_buffer("phi", phi)
        self.register_buffer("weights", weights * phi)

    def forward(self, x: Tensor, generator: torch.Generator | None = None) -> Tensor:
        """``x`` is ``(..., N, D)`` with samples on dim ``-2``; returns the statistic averaged over slices and leading dims."""
        A = torch.randn(x.size(-1), self.num_slices, device=x.device, dtype=x.dtype, generator=generator)
        A = A / A.norm(dim=0)
        xt = (x @ A).unsqueeze(-1) * self.t
        err = (xt.cos().mean(-3) - self.phi).square() + xt.sin().mean(-3).square()
        return ((err @ self.weights) * x.size(-2)).mean()

method forward ​

torch_world.losses.SIGReg.forward GitHub

python
forward(x: Tensor, generator: torch.Generator | None = None) -> Tensor

x is (..., N, D) with samples on dim -2; returns the statistic averaged over slices and leading dims.

Source code in torch_world/losses/sigreg.py
python
def forward(self, x: Tensor, generator: torch.Generator | None = None) -> Tensor:
    """``x`` is ``(..., N, D)`` with samples on dim ``-2``; returns the statistic averaged over slices and leading dims."""
    A = torch.randn(x.size(-1), self.num_slices, device=x.device, dtype=x.dtype, generator=generator)
    A = A / A.norm(dim=0)
    xt = (x @ A).unsqueeze(-1) * self.t
    err = (xt.cos().mean(-3) - self.phi).square() + xt.sin().mean(-3).square()
    return ((err @ self.weights) * x.size(-2)).mean()

class RDMReg ​

torch_world.losses.RDMReg GitHub

python
RDMReg(
    num_slices: int = 1024,
    p: float = 1.0,
    mu: float = 0.0,
    rectify: bool = True,
)

Rectified Distribution-Matching Regularization: sliced 2-Wasserstein distance to a rectified product prior.

Embeddings and samples of the target ReLU(mu + sigma * GN_p) (each coordinate i.i.d., sigma giving GN_p unit variance) are projected on num_slices random unit directions; each 1D projection is sorted over samples and matched by squared error. p = 1 (a rectified Laplace) yields non-negative codes with exact zeros; p = 2 without rectify recovers the isotropic Gaussian of LeJEPA/LeWM.

Kuang et al., "LpWM: A Case for Sparse Representations in World Models", 2026. Paper: https://arxiv.org/abs/2608.22764 Code: https://github.com/YilunKuang/lpworldmodel

Members

MemberDescription
sampleTarget samples: |x| = (p g)^(1/p) with g ~ Gamma(1/p, 1) and a random sign is GN_p.
forwardz is (N, ..., D) with samples on dim 0; middle dims are matched separately and averaged.
Source code in torch_world/losses/rdmreg.py
python
class RDMReg(nn.Module):
    """Rectified Distribution-Matching Regularization: sliced 2-Wasserstein distance to a rectified product prior.

    Embeddings and samples of the target ``ReLU(mu + sigma * GN_p)`` (each coordinate i.i.d., ``sigma`` giving
    ``GN_p`` unit variance) are projected on ``num_slices`` random unit directions; each 1D projection is sorted over
    samples and matched by squared error. ``p = 1`` (a rectified Laplace) yields non-negative codes with exact zeros;
    ``p = 2`` without ``rectify`` recovers the isotropic Gaussian of LeJEPA/LeWM.

    Kuang et al., "LpWM: A Case for Sparse Representations in World Models", 2026.
    Paper: https://arxiv.org/abs/2608.22764
    Code: https://github.com/YilunKuang/lpworldmodel
    """

    def __init__(self, num_slices: int = 1024, p: float = 1.0, mu: float = 0.0, rectify: bool = True):
        super().__init__()
        self.num_slices, self.p, self.mu, self.rectify = num_slices, p, mu, rectify
        self.sigma = math.sqrt(math.gamma(1 / p) / math.gamma(3 / p)) / p ** (1 / p)

    def sample(self, shape: tuple[int, ...], device=None, dtype=None) -> Tensor:
        """Target samples: ``|x| = (p g)^(1/p)`` with ``g ~ Gamma(1/p, 1)`` and a random sign is ``GN_p``."""
        g = torch.distributions.Gamma(torch.tensor(1 / self.p, device=device), 1.0).sample(shape)
        sign = torch.randint(2, shape, device=device) * 2 - 1
        x = self.mu + self.sigma * sign * (self.p * g).pow(1 / self.p)
        return (x.relu() if self.rectify else x).to(dtype)

    def forward(self, z: Tensor) -> Tensor:
        """``z`` is ``(N, ..., D)`` with samples on dim ``0``; middle dims are matched separately and averaged."""
        directions = F.normalize(torch.randn(z.size(-1), self.num_slices, device=z.device, dtype=z.dtype), dim=0)
        target = self.sample(z.shape, z.device, z.dtype)
        return ((z @ directions).sort(0).values - (target @ directions).sort(0).values).square().mean()

method sample ​

torch_world.losses.RDMReg.sample GitHub

python
sample(shape: tuple[int, ...], device=None, dtype=None) -> Tensor

Target samples: |x| = (p g)^(1/p) with g ~ Gamma(1/p, 1) and a random sign is GN_p.

Source code in torch_world/losses/rdmreg.py
python
def sample(self, shape: tuple[int, ...], device=None, dtype=None) -> Tensor:
    """Target samples: ``|x| = (p g)^(1/p)`` with ``g ~ Gamma(1/p, 1)`` and a random sign is ``GN_p``."""
    g = torch.distributions.Gamma(torch.tensor(1 / self.p, device=device), 1.0).sample(shape)
    sign = torch.randint(2, shape, device=device) * 2 - 1
    x = self.mu + self.sigma * sign * (self.p * g).pow(1 / self.p)
    return (x.relu() if self.rectify else x).to(dtype)

method forward ​

torch_world.losses.RDMReg.forward GitHub

python
forward(z: Tensor) -> Tensor

z is (N, ..., D) with samples on dim 0; middle dims are matched separately and averaged.

Source code in torch_world/losses/rdmreg.py
python
def forward(self, z: Tensor) -> Tensor:
    """``z`` is ``(N, ..., D)`` with samples on dim ``0``; middle dims are matched separately and averaged."""
    directions = F.normalize(torch.randn(z.size(-1), self.num_slices, device=z.device, dtype=z.dtype), dim=0)
    target = self.sample(z.shape, z.device, z.dtype)
    return ((z @ directions).sort(0).values - (target @ directions).sort(0).values).square().mean()

function info_nce ​

torch_world.losses.info_nce GitHub

python
info_nce(
    a: Tensor,
    b: Tensor,
    temperature: float | Tensor = 0.07,
    symmetric: bool = True,
) -> Tensor

InfoNCE between paired rows of a and b, both (B, D); averaged over both directions when symmetric.

Source code in torch_world/losses/contrastive.py
python
def info_nce(a: Tensor, b: Tensor, temperature: float | Tensor = 0.07, symmetric: bool = True) -> Tensor:
    """InfoNCE between paired rows of ``a`` and ``b``, both ``(B, D)``; averaged over both directions when ``symmetric``."""
    logits = F.normalize(a, dim=-1) @ F.normalize(b, dim=-1).T / temperature
    labels = torch.arange(len(a), device=a.device)
    loss = F.cross_entropy(logits, labels)
    return (loss + F.cross_entropy(logits.T, labels)) / 2 if symmetric else loss

module koleo ​

torch_world.losses.koleo

function koleo ​

torch_world.losses.koleo.koleo GitHub

python
koleo(x: Tensor, eps: float = 1e-08) -> Tensor

KoLeo regularizer on (N, D) embeddings: minus the mean log distance from each to its nearest neighbor.

It is the Kozachenko-Leonenko differential-entropy estimator up to constants, computed on L2-normalized rows, so minimizing it spreads the embeddings uniformly within the batch.

Sablayrolles et al., "Spreading vectors for similarity search", ICLR 2019. Paper: https://arxiv.org/abs/1806.03198

Source code in torch_world/losses/koleo.py
python
def koleo(x: Tensor, eps: float = 1e-8) -> Tensor:
    """KoLeo regularizer on ``(N, D)`` embeddings: minus the mean log distance from each to its nearest neighbor.

    It is the Kozachenko-Leonenko differential-entropy estimator up to constants, computed on L2-normalized rows, so
    minimizing it spreads the embeddings uniformly within the batch.

    Sablayrolles et al., "Spreading vectors for similarity search", ICLR 2019.
    Paper: https://arxiv.org/abs/1806.03198
    """
    x = F.normalize(x, dim=-1, eps=eps)
    with torch.no_grad():
        nearest = (x @ x.T).fill_diagonal_(-1).argmax(dim=1)
    return -torch.log(F.pairwise_distance(x, x[nearest], eps=eps) + eps).mean()