Skip to main content

omnibias.fields.scale

0.2.0rc1Release candidatePython >=3.10Apache-2.0

Structured scalar, vector, and tensor fields with derivative caches, calculus operators, and coordinate conventions.

import omnibias.fields.scale
Module contract & mathematical conventions

Field-side scale schedule and grid-free V-cycle (theory 03-07).

alpha is a tempering scale, not a collapse parameter. The founding bias collapse is delta -> 0. Temperature collapse is beta -> inf (feasibility). Do not conflate the two. Scale flow is a third axis.

Shared formulas do not imply universal floating-point identity. Verify dtype, shape, derivative-order support, and the stated numerical assumptions for the path you use.

Imports & aliases​

These names share a definition with another public module. Follow a name for its full contract, parameters, and examples.

Import from this moduleCanonical reference
ScaleBandomnibias.core.ScaleBand
FUNCTION

grid_free_vcycle​

omnibias.fields.scale.grid_free_vcycleSource ↗
grid_free_vcycle(packs: Sequence[ScaledPack], rhs: Sequence[float], *, bands: Sequence[ScaleBand], u0: Sequence[float] | None=None, pre_sweeps: int=2, post_sweeps: int=2, omega: float=0.6) -> tuple[float, ...]

One V-cycle on scale bands. Restriction / prolongation are exact rescales.

Parameters

NameType & defaultContract
packspositional-or-keywordSequence[ScaledPack]RequiredSee the operation contract and implementation below.
rhspositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
bandskeyword-onlySequence[ScaleBand]RequiredSee the operation contract and implementation below.
u0keyword-onlySequence[float] | NoneDefault: NoneSee the operation contract and implementation below.
pre_sweepskeyword-onlyintDefault: 2See the operation contract and implementation below.
post_sweepskeyword-onlyintDefault: 2See the operation contract and implementation below.
omegakeyword-onlyfloatDefault: 0.6See the operation contract and implementation below.
Returnstuple[float, ...]
Explicit validation & failure cases
  • When len(bands) < 2, raises ValueError('V-cycle needs at least two scale bands').
  • When not coarse_idx, raises ValueError('coarse band contains no packs').

These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.

Executed regression · g5 vcycle reduces residual

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_g5_vcycle_reduces_residual() -> None:
    packs = (
        ScaledPack(order=0, mean=-0.8, alpha=0.8),
        ScaledPack(order=0, mean=0.8, alpha=0.8),
        ScaledPack(order=0, mean=-0.4, alpha=2.0),
        ScaledPack(order=0, mean=0.0, alpha=2.0),
        ScaledPack(order=0, mean=0.4, alpha=2.0),
    )
    a = -stiffness_matrix(packs, derivative_order=2)
    rng = np.random.default_rng(0)
    true = rng.normal(size=len(packs))
    rhs = a @ true
    bands = (ScaleBand(0.5, 1.0), ScaleBand(1.5, 2.5))
    u0 = np.zeros(len(packs))
    single = _jacobi(a, rhs, u0.copy(), omega=0.6, sweeps=4)
    cycled = np.asarray(
        grid_free_vcycle(packs, rhs, bands=bands, u0=u0, pre_sweeps=2, post_sweeps=2),
        dtype=np.float64,
    )
    r0 = float(np.linalg.norm(rhs))
    r_single = residual_norm(packs, rhs, single)
    r_cycle = residual_norm(packs, rhs, cycled)
    assert r_cycle <= r0 / 5.0
    assert r_cycle < r_single
python -m pytest "packages/omnibias-fields/tests/test_scale.py::test_g5_vcycle_reduces_residual" -q
Read the implementation
def grid_free_vcycle(
    packs: Sequence[ScaledPack],
    rhs: Sequence[float],
    *,
    bands: Sequence[ScaleBand],
    u0: Sequence[float] | None = None,
    pre_sweeps: int = 2,
    post_sweeps: int = 2,
    omega: float = 0.6,
) -> tuple[float, ...]:
    """One V-cycle on scale bands. Restriction / prolongation are exact rescales."""
    if len(bands) < 2:
        raise ValueError("V-cycle needs at least two scale bands")
    packs_t = tuple(packs)
    # Poisson ``-d^2/dx^2`` so the diagonal is positive for gaussian bumps.
    a = -stiffness_matrix(packs_t, derivative_order=2)
    b = np.asarray(rhs, dtype=np.float64)
    u = np.zeros(len(packs_t), dtype=np.float64) if u0 is None else np.asarray(u0, dtype=np.float64)
    u = _jacobi(a, b, u, omega=omega, sweeps=pre_sweeps)
    residual = b - a @ u
    coarse = bands[0]
    fine = bands[-1]
    coarse_idx = [i for i, p in enumerate(packs_t) if coarse.contains(p.alpha)]
    fine_idx = [i for i, p in enumerate(packs_t) if fine.contains(p.alpha) or coarse.contains(p.alpha)]
    if not coarse_idx:
        raise ValueError("coarse band contains no packs")
    a_c = a[np.ix_(coarse_idx, coarse_idx)]
    r_c = residual[coarse_idx]
    try:
        e_c = np.linalg.solve(a_c + 1e-12 * np.eye(len(coarse_idx)), r_c)
    except np.linalg.LinAlgError:
        e_c = np.linalg.lstsq(a_c, r_c, rcond=None)[0]
    e = np.zeros_like(u)
    e[coarse_idx] = e_c
    # Prolongation onto the fine band is the identity on shared slow modes.
    _ = fine_idx
    u = u + e
    u = _jacobi(a, b, u, omega=omega, sweeps=post_sweeps)
    return tuple(float(v) for v in u)
FUNCTION

lstsq_readout_mse​

omnibias.fields.scale.lstsq_readout_mseSource ↗
lstsq_readout_mse(x: Sequence[float], y: Sequence[float], alphas: Sequence[float], *, n_means: int=24) -> float

One-shot least-squares readout on a scale bank. No gradient descent.

Parameters

NameType & defaultContract
xpositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
ypositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
alphaspositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
n_meanskeyword-onlyintDefault: 24See the operation contract and implementation below.
Returnsfloat
Executed regression · g4 derived schedule matches or beats hand tuned

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_g4_derived_schedule_matches_or_beats_hand_tuned() -> None:
    freq = 8
    x = np.linspace(0.0, 1.0, 256)
    y = np.sin(2.0 * np.pi * freq * x)
    hand = (1.0, 2.0, 4.0)
    derived = scale_schedule(
        target_band=lambda t: 2.0 * np.pi * (1.0 + (freq - 1) * t),
        steps=3,
        base="gaussian",
        order=1,
    )
    mse_hand = lstsq_readout_mse(x, y, hand, n_means=16)
    mse_derived = lstsq_readout_mse(x, y, derived, n_means=16)
    assert mse_derived <= mse_hand * 1.0000001
python -m pytest "packages/omnibias-fields/tests/test_scale.py::test_g4_derived_schedule_matches_or_beats_hand_tuned" -q
Read the implementation
def lstsq_readout_mse(
    x: Sequence[float],
    y: Sequence[float],
    alphas: Sequence[float],
    *,
    n_means: int = 24,
) -> float:
    """One-shot least-squares readout on a scale bank. No gradient descent."""
    means = tuple(float(v) for v in np.linspace(0.0, 1.0, int(n_means)))
    phi = tanh_feature_matrix(x, alphas, means)
    target = np.asarray(y, dtype=np.float64).reshape(-1)
    coef, *_ = np.linalg.lstsq(phi, target, rcond=None)
    pred = phi @ coef
    return float(np.mean((pred - target) ** 2))
FUNCTION

residual_norm​

omnibias.fields.scale.residual_normSource ↗
residual_norm(packs: Sequence[ScaledPack], rhs: Sequence[float], coeffs: Sequence[float]) -> float

The module contract describes the context for this operation. Its signature, explicit validation, return expressions, and implementation are recorded below.

Parameters

NameType & defaultContract
packspositional-or-keywordSequence[ScaledPack]RequiredSee the operation contract and implementation below.
rhspositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
coeffspositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
Returnsfloat
Executed regression · g5 vcycle reduces residual

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_g5_vcycle_reduces_residual() -> None:
    packs = (
        ScaledPack(order=0, mean=-0.8, alpha=0.8),
        ScaledPack(order=0, mean=0.8, alpha=0.8),
        ScaledPack(order=0, mean=-0.4, alpha=2.0),
        ScaledPack(order=0, mean=0.0, alpha=2.0),
        ScaledPack(order=0, mean=0.4, alpha=2.0),
    )
    a = -stiffness_matrix(packs, derivative_order=2)
    rng = np.random.default_rng(0)
    true = rng.normal(size=len(packs))
    rhs = a @ true
    bands = (ScaleBand(0.5, 1.0), ScaleBand(1.5, 2.5))
    u0 = np.zeros(len(packs))
    single = _jacobi(a, rhs, u0.copy(), omega=0.6, sweeps=4)
    cycled = np.asarray(
        grid_free_vcycle(packs, rhs, bands=bands, u0=u0, pre_sweeps=2, post_sweeps=2),
        dtype=np.float64,
    )
    r0 = float(np.linalg.norm(rhs))
    r_single = residual_norm(packs, rhs, single)
    r_cycle = residual_norm(packs, rhs, cycled)
    assert r_cycle <= r0 / 5.0
    assert r_cycle < r_single
python -m pytest "packages/omnibias-fields/tests/test_scale.py::test_g5_vcycle_reduces_residual" -q
Read the implementation
def residual_norm(packs: Sequence[ScaledPack], rhs: Sequence[float], coeffs: Sequence[float]) -> float:
    a = -stiffness_matrix(tuple(packs), derivative_order=2)
    r = np.asarray(rhs, dtype=np.float64) - a @ np.asarray(coeffs, dtype=np.float64)
    return float(np.linalg.norm(r))
FUNCTION

scale_schedule​

omnibias.fields.scale.scale_scheduleSource ↗
scale_schedule(*, target_band: Callable[[float], float], steps: int, base: str='gaussian', order: int=1) -> tuple[float, ...]

Cutoff schedule from order-as-frequency, not a hand-tuned window list.

Parameters

NameType & defaultContract
target_bandkeyword-onlyCallable[[float], float]RequiredSee the operation contract and implementation below.
stepskeyword-onlyintRequiredSee the operation contract and implementation below.
basekeyword-onlystrDefault: 'gaussian'See the operation contract and implementation below.
orderkeyword-onlyintDefault: 1See the operation contract and implementation below.
Returnstuple[float, ...]
Explicit validation & failure cases
  • When n < 1, raises ValueError('steps must be >= 1').
  • When xi <= 0.0, raises ValueError('target_band must return a positive frequency').

These are explicit source guards. Backend operations may also raise for invalid shapes, dtypes, or unsupported devices.

Executed regression · schedule tracks target band

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_schedule_tracks_target_band() -> None:
    def band(t: float) -> float:
        return 2.0 + 14.0 * t

    alphas = scale_schedule(target_band=band, steps=5, base="gaussian", order=1)
    assert len(alphas) == 5
    for t, a in zip(np.linspace(0.0, 1.0, 5), alphas, strict=True):
        assert abs(peak_frequency("gaussian", 1, a) - band(float(t))) <= 1e-12
python -m pytest "packages/omnibias-fields/tests/test_scale.py::test_schedule_tracks_target_band" -q
Regression example · g4 derived schedule matches or beats hand tuned

This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_g4_derived_schedule_matches_or_beats_hand_tuned() -> None:
    freq = 8
    x = np.linspace(0.0, 1.0, 256)
    y = np.sin(2.0 * np.pi * freq * x)
    hand = (1.0, 2.0, 4.0)
    derived = scale_schedule(
        target_band=lambda t: 2.0 * np.pi * (1.0 + (freq - 1) * t),
        steps=3,
        base="gaussian",
        order=1,
    )
    mse_hand = lstsq_readout_mse(x, y, hand, n_means=16)
    mse_derived = lstsq_readout_mse(x, y, derived, n_means=16)
    assert mse_derived <= mse_hand * 1.0000001
python -m pytest packages/omnibias-fields/tests/test_scale.py -k test_g4_derived_schedule_matches_or_beats_hand_tuned -q
Read the implementation
def scale_schedule(
    *,
    target_band: Callable[[float], float],
    steps: int,
    base: str = "gaussian",
    order: int = 1,
) -> tuple[float, ...]:
    """Cutoff schedule from order-as-frequency, not a hand-tuned window list."""
    n = int(steps)
    if n < 1:
        raise ValueError("steps must be >= 1")
    out: list[float] = []
    for i in range(n):
        t = 0.0 if n == 1 else i / (n - 1)
        xi = float(target_band(t))
        if xi <= 0.0:
            raise ValueError("target_band must return a positive frequency")
        out.append(float(alpha_for_peak(base, int(order), xi)))
    return tuple(out)
FUNCTION

tanh_feature_matrix​

omnibias.fields.scale.tanh_feature_matrixSource ↗
tanh_feature_matrix(x: Sequence[float], alphas: Sequence[float], means: Sequence[float]) -> np.ndarray

tanh(alpha (x - mu)) bank used by the derived curriculum.

Parameters

NameType & defaultContract
xpositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
alphaspositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
meanspositional-or-keywordSequence[float]RequiredSee the operation contract and implementation below.
Returnsnp.ndarray
Executed regression · g4 derived schedule matches or beats hand tuned

Recorded coverage confirms this test executed the API body. This example belongs to the pinned upstream test suite. It may use fixtures and imports from its full file. Run it from that checkout with its test dependencies installed.

def test_g4_derived_schedule_matches_or_beats_hand_tuned() -> None:
    freq = 8
    x = np.linspace(0.0, 1.0, 256)
    y = np.sin(2.0 * np.pi * freq * x)
    hand = (1.0, 2.0, 4.0)
    derived = scale_schedule(
        target_band=lambda t: 2.0 * np.pi * (1.0 + (freq - 1) * t),
        steps=3,
        base="gaussian",
        order=1,
    )
    mse_hand = lstsq_readout_mse(x, y, hand, n_means=16)
    mse_derived = lstsq_readout_mse(x, y, derived, n_means=16)
    assert mse_derived <= mse_hand * 1.0000001
python -m pytest "packages/omnibias-fields/tests/test_scale.py::test_g4_derived_schedule_matches_or_beats_hand_tuned" -q
Read the implementation
def tanh_feature_matrix(
    x: Sequence[float],
    alphas: Sequence[float],
    means: Sequence[float],
) -> np.ndarray:
    """``tanh(alpha (x - mu))`` bank used by the derived curriculum."""
    xv = np.asarray(x, dtype=np.float64).reshape(-1)
    cols = [np.tanh(float(a) * (xv - float(m))) for a in alphas for m in means]
    return np.column_stack(cols)