Foundations
Stable vector norms, normalization, dot and cross features
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
| Parameter | Shape and meaning |
|---|---|
atorch.Tensor | [\ldots, 3]First vector in each independent pair. |
btorch.Tensor | Exactly 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-08 | Positive 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
bwith 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) usesn(v)=\sqrt{\sum_{\mathrm{xyz}}(v^{2})+\varepsilon};norm_mode='clamped'usesn(v)=\sqrt{\operatorname{max}(\sum_{\mathrm{xyz}}(v^{2}),\varepsilon)}.epsis a finite positive squared-norm stabilizer, default10^{-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 andcrossuse 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, withTruemeaning valid; absent means all valid. AtFalseentries 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 returnedunit_*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
crossproducts 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.
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.