Foundations

Stable vector norms, normalization, dot and cross features

EasyRaw PyTorchAbout 10 min2 public examples plus private tests

Write and run your solution Sign in

Free account with email, Google or GitHub. Your code runs in an isolated PyTorch sandbox.

Your task

For each pair of 3D vectors, return their stabilized lengths and directions, dot product, and right-handed cross product. Apply the optional validity mask to every result.

Function signature

safe_vector_ops(
    a: torch.Tensor,
    b: torch.Tensor,
    mask: torch.Tensor | None = None,
    norm_mode: str = 'additive',
    eps: float = 1e-08,
) -> dict[str, torch.Tensor]

Worked example

Lengths are stabilized; dot and cross use the originals

For a=[3,0,0], b=[0,4,0], norm_mode="clamped", eps=1 and mask=True, norm_a=3, norm_b=4, unit_a=[1,0,0] and unit_b=[0,1,0]. The dot product is 0, while a×b=[0,0,12]. Crossing the unit vectors would incorrectly return [0,0,1].

Parameters

ParameterShape and meaning
atorch.Tensor[\ldots, 3]First vector in each independent pair.
btorch.TensorExactly a.shape: [\ldots, 3].Second vector; exactly the same shape as a.
masktorch.Tensor | NoneDefault None[\ldots]Optional pair mask; False zeroes all six returned fields.
norm_modestrDefault 'additive'Choose "additive" or "clamped" squared-norm stabilization. Neither result is guaranteed to have exactly unit length.
epsfloatDefault 1e-08Positive squared-norm stabilizer: additive mode uses \sqrt{\sum v^2+\varepsilon}; clamped mode uses \sqrt{\max(\sum v^2,\varepsilon)}. Do not square eps again.

Return

dict[str, torch.Tensor]

Return exactly the named fields applicable to this operation.

Required behavior

  • Given finite floating a and b with identical shape [\ldots,3], compute geometric features along the final xyz axis. All leading axes identify independent vector pairs; even shape [3] and empty leading axes are valid.
  • norm_mode='additive' (default) uses n(v)=\sqrt{\sum_{\mathrm{xyz}}(v^{2})+\varepsilon}; norm_mode='clamped' uses n(v)=\sqrt{\operatorname{max}(\sum_{\mathrm{xyz}}(v^{2}),\varepsilon)}. eps is a finite positive squared-norm stabilizer, default 10^{-8}: it is neither added after sqrt nor squared again.
  • Return \mathrm{norm\_a}=n(a), \mathrm{norm\_b}=n(b), \mathrm{unit\_a}=a/n(a), \mathrm{unit\_b}=b/n(b), \operatorname{dot}=\sum_{\mathrm{xyz}}(a\cdot b), and \mathrm{cross}=a\times b. Dot and cross use the original vectors, not the normalized ones. Cross is right-handed: e_x\times e_y=e_z.
  • An optional Boolean mask [\ldots] has exactly the leading shape, with True meaning valid; absent means all valid. At False entries all six outputs are zero and both input gradients are zero.
  • For a valid zero vector, its safe norm is \sqrt{\varepsilon} and its normalized vector is zero, with finite derivatives. The returned unit_* are stabilized directions, not guaranteed unit length: additive mode shrinks every nonzero vector, and clamped mode shrinks vectors below the norm floor.
  • Norms/dots are invariant under rotations; normalized vectors and cross products transform as vectors under proper rotations. Cross is a pseudovector under reflections. Preserve dtype/device and all leading dimensions; no weights, residual additions or input mutation.

Why this matters

Norm stabilization protects gradients at zero, while dot and cross products still use the original unnormalized vectors.

Starter code

You write the body of this function in the BioTorch workspace. Your code runs in an isolated PyTorch sandbox; Run checks the public examples and Submit grades the full test suite, including gradients.

import torch


def safe_vector_ops(
    a: torch.Tensor,  # (..., 3)
    b: torch.Tensor,  # Exactly a.shape: (..., 3).
    mask: torch.Tensor | None = None,  # (...)
    norm_mode: str = 'additive',
    eps: float = 1e-08,
) -> dict[str, torch.Tensor]:
    """Return dict[str, torch.Tensor]:
    
    norm_a: (...).
    norm_b: (...).
    unit_a: (..., 3).
    unit_b: (..., 3).
    dot: (...).
    cross: (..., 3)."""
    # Implement the operation. Inputs and test setup are supplied by BioTorch.
    raise NotImplementedError("Implement safe_vector_ops")

Ready to implement it?

3 progressive hints, a solution walkthrough, and grading that checks values, shapes and gradients are waiting in the workspace.

Write and run your solution Sign in

Free account with email, Google or GitHub. Your code runs in an isolated PyTorch sandbox.

Sources and further reading

A primitive exercise, not an end-to-end reproduction of the named models. No affiliation or endorsement is implied.