diff --git a/CITATION.cff b/CITATION.cff index 9304e4c..7d93f29 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -26,7 +26,7 @@ keywords: - pytorch preferred-citation: type: article - title: "GB-LSR: A Fast Local Spectral Image Representation with a Single Global Bandwidth for Continuous Reconstruction and Super-Resolution" + title: "GB-LSR: Local Spectral Decoding with a Learned Global Bandwidth for Arbitrary-Scale Super-Resolution" authors: - family-names: Shad given-names: Max diff --git a/README.md b/README.md index a52d2e7..b664fd4 100644 --- a/README.md +++ b/README.md @@ -2,24 +2,25 @@ [![CI](https://github.com/KempnerInstitute/gblsr/actions/workflows/ci.yml/badge.svg)](https://github.com/KempnerInstitute/gblsr/actions/workflows/ci.yml) [![arXiv](https://img.shields.io/badge/arXiv-2606.19617-b31b1b.svg)](https://arxiv.org/abs/2606.19617) -[![Hugging Face](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Models-ffcc4d.svg)](https://huggingface.co/KempnerInstituteAI/gblsr) +[![Hugging Face](https://img.shields.io/badge/Hugging%20Face-Models-ffcc4d.svg)](https://huggingface.co/KempnerInstituteAI/gblsr) [![License: BSD 3-Clause](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](https://github.com/KempnerInstitute/gblsr/blob/main/LICENSE) [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/) [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff) -**Global-Bandwidth Local Spectral Representation** for continuous image +Global-Bandwidth Local Spectral Representation for continuous image reconstruction. -**Paper**: [arXiv:2606.19617](https://arxiv.org/abs/2606.19617) +Paper: [arXiv:2606.19617](https://arxiv.org/abs/2606.19617) A fixed-grid local spectral image representation: the image domain is partitioned into a fixed grid of non-overlapping square patches, each patch carries a small block of coefficients for a truncated Fourier basis predicted from shared convolutional-encoder features by a single linear projection, and a single trainable scalar bandwidth is shared -globally across all patches. Reconstruction at any continuous -coordinate is a fixed-size basis contraction whose cost is independent -of image size. +across every patch and every image. As in earlier local spectral +decoders, decoding at a continuous coordinate is a fixed-size basis +contraction whose cost is set by the spectral cutoff; GB-LSR learns the +bandwidth of that basis instead of fixing it. ## Repository layout @@ -74,7 +75,8 @@ pip install -e . # editable install for development pip install -e ".[dev]" # also installs pytest + ruff ``` -CUDA toolkit and a matching `torch` build must be installed separately. +`uv sync` installs torch from the PyTorch CUDA 12.1 index; with pip, install a +torch build that matches your CUDA driver. ## Command-line tools @@ -109,7 +111,9 @@ uv run gblsr-decode \ --input features.pt --output recon.png ``` -Also reachable as `python -m gblsr.cli.` or `scripts/.py`. +Also reachable as `python -m gblsr.cli.` or `scripts/.py`; for +`gblsr-measure-latency` these are `gblsr.cli.latency` and +`scripts/measure_latency.py`. ## Using gblsr from Python @@ -136,10 +140,9 @@ from gblsr.metrics import psnr, ssim, lpips_metric, edge_lpips, local_spectrum_ from gblsr.data import DataConfig, build_datasets, label_patches ``` -Each ``__init__.py`` declares an ``__all__`` listing the canonical -public symbols; the deep-import paths (e.g. -``gblsr.models.arms.LocalSpectralArm``) continue to work for power -users. +The package and each subpackage except ``gblsr.cli`` declare an +``__all__`` listing the public symbols; deep imports (e.g. +``gblsr.models.arms.LocalSpectralArm``) also work. ### Quick API check @@ -148,7 +151,7 @@ import torch from gblsr import LocalSpectralArm, ModelConfig, EncoderConfig, BasisConfig from gblsr.latency import measure_latency -# Build a tiny model +# GB-LSR-Scalar at patch size 32, as in the design study mc = ModelConfig( arm="local_spectral", image_size=256, @@ -156,7 +159,7 @@ mc = ModelConfig( basis=BasisConfig(patch_size=32, p_max=16), encoder=EncoderConfig(d_feat=128), ) -model = LocalSpectralArm(mc, bandwidth_mode="global_scalar").eval() +model = LocalSpectralArm(mc, bandwidth_mode="global_scalar", adapt_order=False).eval() # Forward pass x = torch.randn(1, 3, 256, 256) @@ -172,16 +175,22 @@ print(f"median latency: {result.median_ms:.2f} ms") ## Variants -The GB-LSR family is parameterized by ``bandwidth_mode`` in -``LocalSpectralDecoder``: +The GB-LSR family is parameterized by ``bandwidth_mode`` and +``adapt_order`` in ``LocalSpectralDecoder``: | ``bandwidth_mode`` | Description | |---------------------|----------------------------------------------------------| | ``fixed_midpoint`` | Bandwidth pinned to a single fixed value (no training). | -| ``global_scalar`` | **Main variant**: one global trainable scalar shared across all patches. | +| ``global_scalar`` | Main variant: one global trainable scalar shared across all patches. | | ``local_linear`` | Per-patch bandwidth from a linear-sigmoid head. | | ``local_logspace`` | Per-patch bandwidth from a log-space sigmoid head. | +With ``adapt_order=True`` (the default), the decoder also predicts a +per-patch cutoff order. The paper's GB-LSR-Scalar, GB-LSR-Fixed, and +GB-LSR-Bandwidth are ``global_scalar``, ``fixed_midpoint``, and +``local_logspace`` with ``adapt_order=False``; GB-LSR-Full is +``local_logspace`` with ``adapt_order=True``. + ## Arbitrary-scale super-resolution (ASR) extension `gblsr.asr` decodes one RDN-encoder feature map at any output resolution via @@ -203,9 +212,18 @@ hr = model.predict_full(torch.rand(1, 3, 64, 64), H_q=256, W_q=256) # (1,3,256, `GBLSRScalarASRDecoder` arguments (`p_max`, `bandwidth_init`, `local_ensemble`); variants compose (e.g. `nf96+noLE`). -**Scope:** ships the method (encoder + decoder + `predict_full`). The training -recipe (1M steps on DIV2K) is in the paper appendix; the timing harness and -the LIIF/LTE/SwinIR baselines are not bundled. +Scope: ships the method (encoder + decoder + `predict_full`). The training +recipe (1M steps on DIV2K) is in the paper; the harness that timed the +super-resolution comparison and the methods the paper compares with are +not bundled. + +## Pretrained models + +Trained weights for four super-resolution models and two design-study +models from the paper (training seed 0) are on the Hugging Face Hub at +[KempnerInstituteAI/gblsr](https://huggingface.co/KempnerInstituteAI/gblsr), +tag `arxiv-v2`, under CC BY-NC 4.0. The model card gives their scores +and loading code. ## Datasets @@ -218,8 +236,9 @@ run). Canonical sources: - Set14 / Set5 / Urban100: - BSDS300 / B100: -Kodak / Set14 / Urban100 are the native-reconstruction benchmark; Set5 / -B100 (and Set14 / Urban100) are the arbitrary-scale SR evaluation datasets. +Kodak / Set14 / Urban100 are the test sets of the native-reconstruction +design study; Set5 / Set14 / B100 / Urban100 and the DIV2K validation +split are the arbitrary-scale SR evaluation datasets. ## Production speedup @@ -228,12 +247,11 @@ Defaults are deployment-conservative (batch=1, no AMP, no same defaults. For production, layer these on top of `LocalSpectralArm`: -- **`torch.compile`** (`model = torch.compile(model)`): ~2.4x at - 256x256 (1.43 ms -> 0.58 ms on NVIDIA H200 SXM 141GB). One-time - ~60 s compile per input shape. -- **Batching**: pass `(B, 3, H, W)`; per-image cost amortizes. -- **CUDA Graphs**: capture + replay at a fixed input shape. -- **AMP** (bf16/fp16): use only inside a larger AMP pipeline. +- `torch.compile` (`model = torch.compile(model)`): the first call + compiles, and a new input shape can trigger a recompile. +- Batching: pass `(B, 3, H, W)`; per-image cost amortizes. +- CUDA Graphs: capture + replay at a fixed input shape. +- AMP (bf16/fp16): use only inside a larger AMP pipeline. ## Citation @@ -241,9 +259,8 @@ If you use GB-LSR in your work, please cite: ```bibtex @article{shad2026gblsr, - title = {GB-LSR: A Fast Local Spectral Image Representation with a - Single Global Bandwidth for Continuous Reconstruction and - Super-Resolution}, + title = {{GB-LSR}: Local Spectral Decoding with a Learned Global + Bandwidth for Arbitrary-Scale Super-Resolution}, author = {Shad, Max and Khoshnevis, Naeem}, journal = {arXiv preprint arXiv:2606.19617}, year = {2026}, diff --git a/configs/example.yaml b/configs/example.yaml index 3f7ec33..d96b611 100644 --- a/configs/example.yaml +++ b/configs/example.yaml @@ -72,6 +72,7 @@ arms: - arm: local_spectral slug: gb_lsr_scalar bandwidth_mode: global_scalar + adapt_order: false # To add more variants, append more stanzas. Examples (commented): # @@ -82,6 +83,7 @@ arms: # - arm: local_spectral # slug: gb_lsr_fixed # bandwidth_mode: fixed_midpoint + # adapt_order: false # # - arm: global_fourier_mlp # slug: gfm_baseline diff --git a/src/gblsr/__init__.py b/src/gblsr/__init__.py index 2c75d92..1e0a46c 100644 --- a/src/gblsr/__init__.py +++ b/src/gblsr/__init__.py @@ -5,12 +5,13 @@ non-overlapping square patches; each patch carries a small block of coefficients for a truncated Fourier basis, predicted from shared convolutional-encoder features by a single linear projection. A single -trainable scalar bandwidth is shared globally across all patches, and -reconstruction at any continuous coordinate is a fixed-size basis -contraction whose cost is independent of image size. A separate -arbitrary-scale super-resolution extension (:mod:`gblsr.asr`) reuses the -same local-spectral decoder behind an RDN encoder and a continuous-query -interface. +trainable scalar bandwidth is shared across every patch and every image. +As in earlier local spectral decoders, decoding at a continuous coordinate +is a fixed-size basis contraction whose cost is set by the spectral +cutoff; GB-LSR learns the bandwidth of that basis instead of fixing it. A +separate arbitrary-scale super-resolution extension (:mod:`gblsr.asr`) +adapts the local-spectral decoder to an RDN encoder and a +continuous-query interface. Quick start ----------- diff --git a/src/gblsr/asr/__init__.py b/src/gblsr/asr/__init__.py index 786104d..356fed5 100644 --- a/src/gblsr/asr/__init__.py +++ b/src/gblsr/asr/__init__.py @@ -4,7 +4,8 @@ (:class:`gblsr.encoders.rdn.RDNEncoder`) with the :class:`GBLSRScalarASRDecoder`, exposing the LIIF / LTE continuous-query interface so a single encoder feature map can be decoded at any output -resolution. The reported family variants (base, noLE, nf48, nf96) are all +resolution. The variants reported in the paper (base, noLE, nf32, nf48, nf96, +their combinations, and other ``p_max`` or ``bandwidth_init`` values) are all reachable by configuration; see :class:`GBLSRScalarASR` for the recipe. The native-reconstruction model lives in :mod:`gblsr.models.arms`; this diff --git a/src/gblsr/asr/coord.py b/src/gblsr/asr/coord.py index 03f4d23..1146516 100644 --- a/src/gblsr/asr/coord.py +++ b/src/gblsr/asr/coord.py @@ -1,7 +1,7 @@ """Coordinate helper for the arbitrary-scale SR decoder. The LIIF / LTE convention uses (y, x) ordering in coords and -``align_corners=False``-style grid centres: ``v_i = -1 + 1/n + (2/n) * i`` +``align_corners=False``-style grid centers: ``v_i = -1 + 1/n + (2/n) * i`` for ``i = 0..n-1``. ``torch.nn.functional.grid_sample`` expects (x, y) order, so callers use ``coord.flip(-1)`` at the sample site. """ @@ -12,7 +12,7 @@ def make_coord(shape: tuple[int, int], flatten: bool = True) -> torch.Tensor: - """Centred grid in ``[-1 + 1/n, 1 - 1/n]``. + """Centered grid in ``[-1 + 1/n, 1 - 1/n]``. Args: shape: ``(H, W)`` spatial shape. diff --git a/src/gblsr/asr/decoder.py b/src/gblsr/asr/decoder.py index 77efa27..1570555 100644 --- a/src/gblsr/asr/decoder.py +++ b/src/gblsr/asr/decoder.py @@ -12,12 +12,12 @@ evaluates the 2D truncated Fourier basis at that point with a single global trainable bandwidth ``s_e``, and contracts the basis against the cell's coefficients. A 4-corner local ensemble is applied for -LIIF / LTE-compatible behaviour (essentially free in parameters). +LIIF / LTE-compatible behavior (parameter-free). Design notes: - * Single global trainable scalar bandwidth, parameterised as + * Single global trainable scalar bandwidth, parameterized as ``s_e = softplus(log_s_e)`` for strict positivity; ``log_s_e`` is - initialised at ``softplus_inv(bandwidth_init)`` so that ``s_e`` equals + initialized at ``softplus_inv(bandwidth_init)`` so that ``s_e`` equals ``bandwidth_init`` exactly at step 0 (default 1.0). Note that the naive ``log_s_e = log(1.0) = 0`` would instead give ``softplus(0) = ln 2 = 0.693``; the exact softplus inverse is used so @@ -30,7 +30,7 @@ * ``cell`` is accepted in the forward signature (unified with LIIF and LTE) but not used inside the decoder: scale adaptation happens via the density of the high-resolution query grid, so the native-reconstruction - decoder's cell-free behaviour is preserved while respecting the shared + decoder's cell-free behavior is preserved while respecting the shared API. * The basis-element footprint is the high-resolution region owned by one low-resolution feature cell at the evaluation scale @@ -57,7 +57,7 @@ def _fourier_basis_1d(coord: torch.Tensor, p_max: int, s_e: torch.Tensor) -> tor [1, cos(pi*c*s), sin(pi*c*s), cos(2*pi*c*s), sin(2*pi*c*s), ..., up to ``p_max`` terms] - coord: (...,) arbitrary shape in the normalised local coordinate. + coord: (...,) arbitrary shape in the normalized local coordinate. s_e: scalar-compatible bandwidth; broadcasts with ``coord``. returns: (..., p_max) basis values. """ diff --git a/src/gblsr/asr/model.py b/src/gblsr/asr/model.py index e868aad..46fffcf 100644 --- a/src/gblsr/asr/model.py +++ b/src/gblsr/asr/model.py @@ -4,15 +4,15 @@ :class:`gblsr.asr.decoder.GBLSRScalarASRDecoder` to form the arbitrary-scale super-resolution model. -The reported family variants are all reachable by configuration, with no -separate code path: +The variants reported in the paper are all reachable by configuration, with +no separate code path: - * **base**: ``GBLSRScalarASR()`` - * **noLE** (no 4-corner local ensemble):: + * base: ``GBLSRScalarASR()`` + * noLE (no 4-corner local ensemble):: GBLSRScalarASR(decoder_cfg={"local_ensemble": False}) - * **nf48 / nf96** (narrower / wider RDN encoder):: + * nf32 / nf48 / nf96 (narrower or wider RDN encoder):: GBLSRScalarASR(encoder_cfg={"num_features": 96}) diff --git a/src/gblsr/models/arms.py b/src/gblsr/models/arms.py index 4159857..32324ac 100644 --- a/src/gblsr/models/arms.py +++ b/src/gblsr/models/arms.py @@ -6,7 +6,8 @@ to the patch-grid resolution. - ``LocalSpectralDecoder``: the per-patch truncated-Fourier decoder with four bandwidth modes (``fixed_midpoint``, ``global_scalar`` - (the main variant), ``local_linear``, ``local_logspace``). + (the main variant, with ``adapt_order=False``), ``local_linear``, + ``local_logspace``). - ``GlobalFourierMLPDecoder`` / ``BaselineArm``: a Global Fourier-MLP that pools encoder features to a global code and renders each pixel via a coordinate-MLP. Provided as a no-local-basis control variant. diff --git a/src/gblsr/training/trainer.py b/src/gblsr/training/trainer.py index 881a5eb..1624128 100644 --- a/src/gblsr/training/trainer.py +++ b/src/gblsr/training/trainer.py @@ -1,7 +1,7 @@ """GB-LSR training driver. Launch example: - python -m gblsr.training.trainer --config configs/example.yaml + python -m gblsr.cli.train --config configs/example.yaml Produces under ````: experiment.json aggregated per-run metadata + metrics diff --git a/tests/test_asr.py b/tests/test_asr.py index 88779f2..86de982 100644 --- a/tests/test_asr.py +++ b/tests/test_asr.py @@ -1,14 +1,15 @@ """Tests for the arbitrary-scale SR extension (``gblsr.asr``). Verifies: - - The base and nf96 models reproduce the paper's trainable-parameter - counts (GB-LSR-Scalar-ASR 22.024M; nf96 24.927M), with the total - decomposing exactly into encoder + decoder coefficient head. + - The base and nf96 models match the paper's trainable-parameter + counts (22.02M and 24.93M; checked at three decimals, 22.024M and + 24.927M), with the total decomposing exactly into encoder + decoder + coefficient head. - Forward (continuous-query) and ``predict_full`` (full-image) shapes. - ``predict_full`` tiling produces the same result as the untiled path. - The reported family variants (noLE, nf96) build and run by config, and the local ensemble is parameter-free. - - The scalar bandwidth initialises at exactly 1.0. + - The scalar bandwidth initializes at exactly 1.0. """ import pytest @@ -38,8 +39,8 @@ def _tiny() -> GBLSRScalarASR: @pytest.mark.parametrize( "num_features,paper_millions", [ - # Paper trainable-parameter counts (pareto table, 3-decimal M): - # GB-LSR-Scalar-ASR (base) = 22.024M; nf96 variant = 24.927M. + # Paper parameter counts: 22.02M (base) and 24.93M (nf96); + # checked here at three decimals. (64, 22.024), (96, 24.927), ], @@ -50,7 +51,7 @@ def test_asr_param_count_matches_paper(num_features: int, paper_millions: float) total = _trainable(model) assert round(total / 1e6, 3) == paper_millions - # Structural decomposition (derived, not memorised): the only trainable + # Structural decomposition (derived, not memorized): the only trainable # parts are the RDN encoder and the decoder's coefficient head, which is # a Conv2d(num_features -> 3*p_max^2, 1x1, bias) plus the scalar log_s_e. enc = _trainable(model.encoder) @@ -109,7 +110,7 @@ def test_asr_noLE_variant_builds_and_is_param_free() -> None: def test_asr_bandwidth_init_is_one() -> None: - """The scalar bandwidth initialises at exactly 1.0 (softplus_inv init).""" + """The scalar bandwidth initializes at exactly 1.0 (softplus_inv init).""" dec = GBLSRScalarASRDecoder(in_dim=16) assert float(dec.bandwidth()) == pytest.approx(1.0, abs=1e-5) diff --git a/tests/test_example_config.py b/tests/test_example_config.py index 5b3cbc0..9a42ddd 100644 --- a/tests/test_example_config.py +++ b/tests/test_example_config.py @@ -31,6 +31,7 @@ def test_example_config_parses_and_expands() -> None: assert rc.experiment_id == "gblsr_example" assert rc.arm == "local_spectral" assert rc.bandwidth_mode == "global_scalar" + assert rc.adapt_order is False assert rc.seed == 0 # The run dir should incorporate the slug + seed. assert "gb_lsr_scalar__seed0" in rc.run_dir diff --git a/tests/test_training_losses.py b/tests/test_training_losses.py index 8561531..d90cede 100644 --- a/tests/test_training_losses.py +++ b/tests/test_training_losses.py @@ -95,7 +95,7 @@ def test_pointwise_loss_dispatches(loss_name: str, expected_at_zero: float) -> N def test_pointwise_loss_rejects_unknown_name() -> None: - """An unrecognised ``loss_name`` raises ``ValueError``.""" + """An unrecognized ``loss_name`` raises ``ValueError``.""" x = torch.randn(1, 3, 4, 4) with pytest.raises(ValueError, match="unknown loss_name"): pointwise_loss(x, x, loss_name="bogus_loss", charbonnier_eps=1e-3)