GeoZL
Examples

Sentinel-2 benchmark with Rumi

Sentinel-2 ships its bands as JPEG2000. The files are small, but decoding them is slow and all of it runs on the CPU. A training loop pays that cost on every read of every epoch, while the GPU waits for data.

Rumi stores the same pixels, also lossless, in 512×512 chunks compressed with GeoZL that the GPU decodes itself. The CPU only reads the file and sends the compressed bytes over.

This small benchmark reads one whole scene into a GPU tensor from JPEG2000, GeoTIFF and Rumi, with one CPU thread, and compares read time and file size. Pick a GPU runtime in Colab before running it. JPEG2000 alone takes a few minutes.

Installcode
%pip install -q -U geozl rumi-eo rasterio
import os
import time
import urllib.request

# One CPU thread for every reader, so the comparison is about the format.
os.environ["GDAL_NUM_THREADS"] = os.environ["OPJ_NUM_THREADS"] = "1"

import geozl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import rasterio
import rumi
import torch

rumi.set_num_threads(1)
print("Rumi", rumi.__version__, "· GeoZL", geozl.__version__)
print("GPU", torch.cuda.get_device_name(0))
Rumi 0.30.0 · GeoZL 0.32.0
GPU NVIDIA A100 80GB PCIe

The scene

Tile 32TPT over the Alps, 28 September 2023, with almost no clouds. The red, green and blue bands at 10 m are 10980×10980 pixels of uint16 each, about 723 MB uncompressed. They come from the public Sentinel-2 L2A bucket on AWS.

URL = "https://sentinel-s2-l2a.s3.amazonaws.com/tiles/32/T/PT/2023/9/28/0/R10m/{}.jp2"
names = ["B04", "B03", "B02"]
jp2 = [f"{band}.jp2" for band in names]

bands = []
for band, path in zip(names, jp2, strict=True):
    urllib.request.urlretrieve(URL.format(band), path)
    with rasterio.open(path) as src:
        bands.append(src.read(1))
        crs, transform = src.crs, src.transform
rgb = np.stack(bands)
print(rgb.shape, rgb.dtype, f"{rgb.nbytes / 1e6:.0f} MB")
(3, 10980, 10980) uint16 723 MB
preview = np.moveaxis(rgb[:, ::8, ::8], 0, -1).astype(np.float32)
low, high = np.percentile(preview, (2, 98), axis=(0, 1))
plt.figure(figsize=(7, 7))
plt.imshow(np.clip((preview - low) / (high - low), 0, 1))
plt.axis("off")
plt.show()
True colour preview of Sentinel-2 tile 32TPT over the Alps, every eighth pixel.

Write the files

The GeoTIFF is the usual choice for tiled rasters, with 512×512 blocks per band, ZSTD and a horizontal predictor. It decodes on the CPU.

Rumi also cuts each band into 512×512 chunks, and GeoZL compresses each chunk. The scene is written twice, with the two codecs the GPU decodes:

  • PFOR packs the values into blocks of bits, and is the fastest to decode.
  • PivCo adds entropy coding, so the file is smaller. Its recipe, planar>zigzag>lanes, codes each byte lane with PivCo.

What a GPU wants from a format explains why these two suit a GPU.

with rasterio.open(
    "rgb.tif",
    "w",
    driver="GTiff",
    height=rgb.shape[1],
    width=rgb.shape[2],
    count=3,
    dtype="uint16",
    crs=crs,
    transform=transform,
    tiled=True,
    blockxsize=512,
    blockysize=512,
    interleave="band",
    compress="zstd",
    predictor=2,
    zstd_level=9,
) as dst:
    dst.write(rgb)

headers = {}
for name, recipe in (("pfor", "planar>zigzag>pfor"), ("pivco", "planar>zigzag>lanes")):
    frames = rumi.frames(rgb, "b (row h) (col w) -> row col b (h w)", tile_size=512)
    graphs = {}
    for frame in frames:
        if frame.shape not in graphs:
            graphs[frame.shape] = geozl.graph(frame.data, recipe)
        frame.compressed = geozl.compress(frame.data, graph=graphs[frame.shape])
    headers[name] = rumi.write(
        f"{name}.rumi",
        frames,
        bands=names,
        time=["2023-09-28T10:27:44Z"],
        crs=crs,
        transform=transform,
    )
os.sync()

Compare

Each read ends when the tensor is ready on the GPU.

  • Cold drops the file from the page cache first, so it comes from disk, like a first epoch.
  • Warm finds the file already in memory, like later epochs.

The first reads of a Rumi file on the GPU are slower than the rest. GeoZL sets up its kernels and pins host memory for the compressed bytes, and it keeps two such buffers so one read can overlap the next. Pinning a few hundred MB takes a few hundred ms, once. So each Rumi file is read three times before the clock starts, and every format keeps its best of several reads. JPEG2000 gets one cold and one warm read, since each takes about a minute. The CPU prepares the work shows what happens on the host during a read.

def read_jp2():
    for band, path in enumerate(jp2):
        with rasterio.open(path) as src:
            src.read(1, out=rgb[band])
    return torch.from_numpy(rgb).cuda()


def read_tif():
    with rasterio.open("rgb.tif") as src:
        src.read(out=rgb)
    return torch.from_numpy(rgb).cuda()


def read_rumi(name):
    return rumi.read(f"{name}.rumi", headers[name], framework="torch", device="cuda:0")


def timed(read, paths, cold):
    if cold:
        for path in paths:
            fd = os.open(path, os.O_RDONLY)
            os.posix_fadvise(fd, 0, 0, os.POSIX_FADV_DONTNEED)
            os.close(fd)
    start = time.perf_counter()
    read()
    torch.cuda.synchronize()
    return time.perf_counter() - start


# name: (read, files, cold reads, warm reads)
formats = {
    "JPEG2000": (read_jp2, jp2, 1, 1),
    "GeoTIFF": (read_tif, ["rgb.tif"], 3, 5),
    "PFOR": (lambda: read_rumi("pfor"), ["pfor.rumi"], 3, 5),
    "PivCo": (lambda: read_rumi("pivco"), ["pivco.rumi"], 3, 5),
}
for name in headers:  # the one-off GPU setup, kept off the clock
    for _ in range(3):
        read_rumi(name)
torch.cuda.synchronize()

rows = []
for name, (read, paths, n_cold, n_warm) in formats.items():
    cold = min(timed(read, paths, cold=True) for _ in range(n_cold))
    warm = min(timed(read, paths, cold=False) for _ in range(n_warm))
    rows.append((name, sum(map(os.path.getsize, paths)) / 2**20, cold, warm))

results = pd.DataFrame(rows, columns=["format", "MiB", "cold s", "warm s"]).set_index("format")
results.round({"MiB": 0, "cold s": 3, "warm s": 3})
MiB cold s warm s
format
JPEG2000 350.0 53.536 50.123
GeoTIFF 441.0 1.755 1.601
PFOR 386.0 0.113 0.061
PivCo 377.0 0.157 0.128
File size and time to a GPU tensorcode
COLD, WARM = "#492AE8", "#E0532A"
order = results.index[::-1]
y = np.arange(len(order))

fig, (size, speed) = plt.subplots(
    1, 2, figsize=(11, 3.8), gridspec_kw={"width_ratios": [1, 1.4]})

size.barh(y, results.loc[order, "MiB"], height=0.5, color="#8A8F98")
for i, v in enumerate(results.loc[order, "MiB"]):
    size.text(v + 8, i, f"{v:.0f} MiB", va="center", fontsize=9)
size.set_title("File size", loc="left")
size.set_xlim(0, results["MiB"].max() * 1.3)

for offset, column, color, label in ((0.17, "cold s", COLD, "cold"),
                                     (-0.17, "warm s", WARM, "warm")):
    values = results.loc[order, column]
    speed.barh(y + offset, values, height=0.32, color=color, label=label)
    for i, v in enumerate(values):
        text = f"{v:.2f} s" if v >= 1 else f"{v * 1000:.0f} ms"
        speed.text(v * 1.08, i + offset, text, va="center", fontsize=9)
speed.set_xscale("log")
speed.xaxis.set_major_formatter(lambda v, _: f"{v:g} s")
speed.set_xlim(results[["cold s", "warm s"]].min().min() / 2,
               results[["cold s", "warm s"]].max().max() * 4)
speed.set_title("Time to a GPU tensor, one CPU thread (log scale)", loc="left")
speed.legend(frameon=False, loc="lower right")

for ax in (size, speed):
    ax.set_yticks(y, order)
    ax.spines[["top", "right"]].set_visible(False)
    ax.tick_params(axis="x", labelsize=8, colors="#5C6370")
speed.set_yticklabels([])
plt.tight_layout()
plt.show()
Bar charts of file size and of cold and warm read time into a GPU tensor for JPEG2000, GeoTIFF, Rumi with PFOR and Rumi with PivCo.
jpeg, tif = results.loc["JPEG2000"], results.loc["GeoTIFF"]
pd.DataFrame({
    "size vs JPEG2000": (results["MiB"] / jpeg["MiB"]).map("{:.0%}".format),
    "warm read vs JPEG2000": (jpeg["warm s"] / results["warm s"]).map("{:.3g}x faster".format),
    "warm read vs GeoTIFF": (tif["warm s"] / results["warm s"]).map("{:.2g}x faster".format),
})
size vs JPEG2000 warm read vs JPEG2000 warm read vs GeoTIFF
format
JPEG2000 100% 1x faster 0.032x faster
GeoTIFF 126% 31.3x faster 1x faster
PFOR 110% 828x faster 26x faster
PivCo 108% 392x faster 13x faster

What the numbers say

JPEG2000 is the smallest file and by far the slowest read, since one CPU thread has to decode every pixel. GeoTIFF decodes much faster but is the largest file here. Rumi sits close to JPEG2000 in size, and its read time is mostly moving the compressed bytes, because the GPU does the decoding. PFOR is the fastest read and PivCo the smaller file, so pick PFOR when the loader is the bottleneck and PivCo when storage is.

The outputs on this page come from one machine, and Colab's GPU and two CPUs give different numbers. On Colab, JPEG2000 took about 80 s and GeoTIFF about 3 s. Rerun the notebook to measure your own.

GeoZL's GPU decoding guide describes the C API Rumi uses, and How Rumi reads follows one read through Rumi.

Back to the examples