Algorithm Search⌘K

Algorithmadvanced

Simple-9 coding

Also called Simple9, Anh-Moffat word-aligned coding.

Packs as many small integers as fit into each 32-bit word, using 4 selector bits to choose one of nine equal-width layouts.

Time
O(n + W) decodeO(n) encode
Space
O(1) extraΘ(W) output
Where
W = the number of 32-bit words of the output; n = the number of integers
Properties
not comparison baseddeterministicofflineiterative

Simple-9 codes a list of nonnegative integers below 2282^{28}, usually the gaps of a posting list, in 32-bit words. Each word has a 4-bit selector and 28 data bits, and the selector picks one of nine ways to cut the 28 bits into equal fields: 28 fields of 1 bit, 14 of 2, 9 of 3, 7 of 4, 5 of 5, 4 of 7, 3 of 9, 2 of 14, or 1 of 28. The encoder packs, in each word, as many of the next values as fit in one layout. Anh and Moffat introduced it in 2005. It differs from variable-byte encoding, which spends one flag bit in each byte of each value, and from PForDelta, which fixes one width for a block of 128 values and stores the exceptions apart: here every word has its own width, chosen for a few values at a time. How the gaps are formed is the subject of postings gap encoding; this page is only the word-aligned code.

In plain words

A computer reads memory one word at a time, and a word is 32 bits. Small numbers need only a few bits, so it is a waste to give each one a full word. Simple-9 puts several numbers in one word. It keeps 4 bits of each word for a small label that says how the other 28 bits are cut. If the next 28 numbers are all 0 or 1, one word holds all of them, one bit each. If the next numbers are larger, the word holds fewer of them, each with more bits. The reader looks at the label and knows at once how to cut the word, with no work for each bit. This is why Simple-9 decodes fast.

The problem

The input is a list x0,…,xn−1x_0, \ldots, x_{n-1} of integers with 0≤xi<2280 \le x_i < 2^{28}. The output is a list of 32-bit words from which the decoder, given nn, gets the list back. The goal is a small output with a decoder that does a constant amount of work for each word and each value, with no bit-by-bit loop. For a posting list d1<d2<⋯d_1 < d_2 < \cdots, the input is the list of gaps d1,d2−d1,d3−d2,…d_1, d_2 - d_1, d_3 - d_2, \ldots.

The algorithm

The nine layouts, as (count csc_s, width wsw_s) for selector ss, are:

ss 0 1 2 3 4 5 6 7 8
values csc_s 28 14 9 7 5 4 3 2 1
bits each wsw_s 1 2 3 4 5 7 9 14 28
unused bits 0 0 1 0 3 0 1 0 0

There are nine layouts, not sixteen, because these are the ways to cut 28 bits into equal fields with few unused bits. Four bits can name sixteen selectors, so seven are free.

  1. S9-ENCODE(x[0..n-1]) ▷ each x[i] in [0, 2^28)
  2. 1out ← empty list, i ← 0
  3. 2while i < n do
  4. 3for s ← 0 to 8 do ▷ most values first
  5. 4k ← min(c_s, n - i)
  6. 5if x[i], ..., x[i + k - 1] are all below 2^(w_s) then stop the loop
  7. 6word ← s · 2^28 ▷ selector in the top 4 bits
  8. 7for j ← 0 to k - 1 do put x[i + j] in bits j·w_s to (j+1)·w_s - 1 of word
  9. 8append word to out, i ← i + k
  10. 9return out
  11. S9-DECODE(out, n)
  12. 10x ← empty list
  13. 11for each word of out do
  14. 12s ← ⌊word / 2^28⌋
  15. 13for j ← 0 to c_s - 1 while |x| < n do append bits j·w_s to (j+1)·w_s - 1 of word to x
  16. 14return x

Line L3 tries the layouts from the one with the most values to the one with the fewest. Line L4 takes k=csk = c_s values, or the values that are left at the end of the list. Line L5 tests whether they all fit in wsw_s bits. The first layout that passes is used. Selector 8, one value of 28 bits, always passes, so the loop always stops. Lines L6 and L7 build the word: the selector in the top 4 bits and the values in the data fields, here with the first value in the lowest bits. The last word can be partly filled, so the decoder needs nn, or some other end mark.

The decoder reads the selector of each word at line L12, and line L13 cuts the data bits into csc_s fields of wsw_s bits each. Real decoders write one unrolled block of shifts and masks for each of the nine selectors, and jump to it with a table.

Example

Take the posting list with ids 1, 2, 4, 8, 11, 12, 22, 23, 223, 230, 237, 238. Its gaps are 1, 1, 2, 4, 3, 1, 10, 1, 200, 7, 7, 1.

word line L3 tries first layout that fits values packed word in hexadecimal
1 s=0s = 0: 2 does not fit 1 bit. s=1s = 1: 4 does not fit 2 bits. s=2s = 2: 10 does not fit 3 bits s=3s = 3, 7 values of 4 bits 1, 1, 2, 4, 3, 1, 10 3A134211
2 s=0s = 0 to 4: 200 does not fit 5 bits or less. s=5s = 5: 200 does not fit 7 bits s=6s = 6, 3 values of 9 bits 1, 200, 7 601D9001
3 s=0s = 0 and s=1s = 1: 7 does not fit 2 bits s=2s = 2, 9 values of 3 bits, 2 used 7, 1 2000000F

The first word is 3⋅2283 \cdot 2^{28} plus the values 1, 1, 2, 4, 3, 1, 10 in fields of 4 bits from the low end, which gives the hexadecimal digits 3, then A, 1, 3, 4, 2, 1, 1 from the top. The 12 gaps take 3 words, 96 bits, or 8 bits for each gap. For comparison, Elias gamma coding takes 48 bits for the same gaps, and variable-byte encoding takes 13 bytes, 104 bits, because 200 needs two bytes. Simple-9 is not the smallest here; it is chosen for decode speed, and on long lists of small gaps its words are full and the gap to gamma is smaller.

Correctness

The encoder always ends, because selector 8 fits any value below 2282^{28}, and each word takes at least one value. In each word the selector is in the top four bits, and the kk values are in disjoint fields of wsw_s bits below bit kws≤28k w_s \le 28, each value small enough for its field by the test of line L5. The decoder reads the selector, so it knows the layout of each word, and it reads the fields in the order the encoder wrote them. Only the last word can hold fewer than csc_s values, and the count nn tells the decoder where to stop. So decoding returns the input. The full proof, with the word count below, is in the proof file below.

Proof: Simple-9 decoding inverts encoding, and the word count for values of one widthfull

Let x0,…,xn−1x_0, \ldots, x_{n-1} be integers with 0≤xi<2280 \le x_i < 2^{28}. The layouts are the pairs (cs,ws)(c_s, w_s) for s=0,…,8s = 0, \ldots, 8: (28,1),(14,2),(9,3),(7,4),(5,5),(4,7),(3,9),(2,14),(1,28)(28, 1), (14, 2), (9, 3), (7, 4), (5, 5), (4, 7), (3, 9), (2, 14), (1, 28). For each of them csws≤28c_s w_s \le 28.

  1. Each step of the encoder ends and makes progress. At line L3, selector s=8s = 8 has c8=1c_8 = 1 and w8=28w_8 = 28, and xi<228x_i < 2^{28} by the precondition, so the test of line L5 holds for s=8s = 8 at the latest. So the loop of line L3 always stops with some ss and k=min⁡(cs,n−i)≥1k = \min(c_s, n - i) \ge 1, since i<ni < n. Line L8 adds kk to ii, so the loop of line L2 ends after at most nn words.

  2. Each word is a valid 32-bit word. Line L5 ensures that xi+j<2wsx_{i+j} < 2^{w_s} for 0≤j<k0 \le j < k. Line L7 puts xi+jx_{i+j} in bits jwsj w_s to (j+1)ws−1(j+1) w_s - 1. These fields are disjoint and all lie below bit kws≤csws≤28k w_s \le c_s w_s \le 28. Line L6 puts s≤8<16s \le 8 < 16 in bits 28 to 31. So the word is below 2322^{32}, its top four bits are ss, its field jj holds xi+jx_{i+j} for j<kj < k, and its bits from kwsk w_s to 27 are zero.

  3. The decoder reads back the same values. Let the encoder write words u1,…,uWu_1, \ldots, u_W with selectors s1,…,sWs_1, \ldots, s_W and counts k1,…,kWk_1, \ldots, k_W, so that k1+⋯+kW=nk_1 + \cdots + k_W = n, and only the last word can have kW<csWk_W < c_{s_W}, because k<csk < c_s only when k=n−ik = n - i. By induction on qq, before the decoder reads word uqu_q the list holds x0,…,xK−1x_0, \ldots, x_{K-1} with K=k1+⋯+kq−1K = k_1 + \cdots + k_{q-1}. Line L12 recovers sqs_q from the top four bits, by step 2. For q<Wq < W, kq=csqk_q = c_{s_q} and K+kq≤nK + k_q \le n, so line L13 reads all csqc_{s_q} fields, which by step 2 are xK,…,xK+kq−1x_K, \ldots, x_{K + k_q - 1}. For q=Wq = W, line L13 reads fields until the list has nn values, that is the first kW=n−Kk_W = n - K fields, and these are the last values. So line L14 returns x0,…,xn−1x_0, \ldots, x_{n-1}.

  4. Word count for values of one width. Suppose every value has bit length exactly ww, with 1≤w≤281 \le w \le 28 (for w=1w = 1, the values 0 and 1). Let s∗s^\ast be the least selector with ws∗≥ww_{s^\ast} \ge w, and c=cs∗c = c_{s^\ast}. A selector s<s∗s < s^\ast has ws<ww_s < w, so it fails at line L5 on the first value. Selector s∗s^\ast fits any kk values. So every word takes min⁡(c,n−i)\min(c, n - i) values, and the encoding has ⌈n/c⌉\lceil n / c \rceil words and 32⌈n/c⌉32 \lceil n / c \rceil bits. ■\blacksquare

The greedy choice of line L3 takes the selector with the most values that fit. This is not always the fewest words. For x=(7,300,0,2,5,3,12,3,0,100,1,300)x = (7, 300, 0, 2, 5, 3, 12, 3, 0, 100, 1, 300) the encoder writes 4 words, in the layouts 3×93 \times 9, 5×55 \times 5 and 3×93 \times 9, and a last word in layout 3×93 \times 9 that holds only 300. The split 2×142 \times 14, 7×47 \times 4, 3×93 \times 9 uses 3 words. Correctness does not depend on this choice: step 3 holds for any rule that picks, at each word, a selector whose test at line L5 holds.

Complexity

  • Encoding. Each word tries at most 9 layouts and tests at most 28 values for each, so O(1)O(1) work per word and O(n)O(n) in total. A table of bit lengths or a running maximum makes the test faster in practice.
  • Decoding. O(1)O(1) work for each word and for each value, so O(n+W)O(n + W). There is no branch for each bit and no test for each value, which is the point of the code.
  • Size for values of one width. If every value has bit length exactly ww, the encoder uses the layout with the least width ws≥ww_s \ge w, so it writes ⌈n/cs⌉\lceil n / c_s \rceil words, that is 32⌈n/cs⌉32 \lceil n / c_s \rceil bits. For w=6w = 6 this is the layout with 4 values of 7 bits, so 8 bits for each value; for w=1w = 1 it is 28 values in one word, about 1.14 bits for each value.
  • Overhead. Each word spends 4 bits on its selector, and up to 3 data bits are unused in some layouts, so the cost is at least 32/2832/28 of the data bits. A run of values of one width can take about twice their bits: values of 15 bits take a whole word each, and values of 10 bits take 16 bits each in the layout with 2 fields of 14 bits.
  • Range. Values must be below 2282^{28}. Gaps of very large collections can exceed this, and need an escape.

Properties

  • Word aligned. Each word decodes on its own, so decoding can start at any word, and the code suits skips by block.
  • Greedy, not optimal. The rule of line L3 takes the most values that fit in the current word. This does not always give the fewest words. For x=7,300,0,2,5,3,12,3,0,100,1,300x = 7, 300, 0, 2, 5, 3, 12, 3, 0, 100, 1, 300 the encoder writes 4 words, while the split into 2 values of 14 bits, 7 values of 4 bits and 3 values of 9 bits uses 3. A dynamic program over the positions finds the fewest words in O(n)O(n) time, but the gain is usually small.
  • A code for sequences. The code is for a list, not for one value, and the decoder needs the count of values or a fixed block size.

Variants and improvements

  • Simple-16. Uses all 16 selector values with layouts whose fields have different widths inside one word, which packs better. Zhang, Long and Suel used it in their study of compressed list caching.
  • Simple-8b. Anh and Moffat later applied the same idea to 64-bit words, with a 4-bit selector and 60 data bits, and selectors for long runs of equal values.
  • Relative-10 and Carryover-12. In the same 2005 paper, Anh and Moffat describe codes that choose the next layout relative to the last one, with 2-bit selectors, and that use the unused bits of a word to hold the selector of the next word.
  • Blocks with a common width. PForDelta and binary packing fix one width for a block of 128 values, which suits SIMD decoding better than one selector per word.
  • Optimal split. A shortest path over the positions, with one edge for each layout that fits, gives the least number of words for the same nine layouts.

When to use it

Use Simple-9 for posting lists of small gaps when decoding speed matters more than the last bits of space, and when the engine reads whole words. It is a simple choice on 32-bit platforms and needs no SIMD. For lists with very uneven gaps, a code with exceptions such as PForDelta usually packs better. For lists that need fast skips over ranges of ids, Elias-Fano encoding or a partitioned Elias-Fano index gives direct NEXT-GEQ without full decoding.

Pitfalls

  • Values of 2282^{28} or more. Line L5 never passes for such a value, not even at s=8s = 8, and a loop that assumes it does runs past the end of the layout table. The input must be checked, as the implementation does, or large values need an escape word.
  • Partial last word. If the decoder takes csc_s values from every word in place of stopping at nn in line L13, it adds zeros from the unused fields of the last word. Store nn, or pad with a value the caller can tell apart.
  • Testing only the first value. A test of line L5 that checks only x[i]x[i] in place of all kk values packs a larger later value into a field that is too small, and the extra high bits spill into the next field.
  • Gaps of zero. Strictly increasing ids give gaps of at least 1. Simple-9 can code 0, so an engine can store gap minus 1 to gain a little in the narrow layouts; encoder and decoder must agree on this.
  • Byte order. The words are 32-bit integers. A file written on one machine and read on a machine with another byte order must convert the words.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

simple_9.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/simple-9/. The authors are listed in prov/QCGBFK.jsonl.

# The nine layouts of a 32-bit word: selector s gives COUNT[s] values of WIDTH[s] bits.
COUNT = (28, 14, 9, 7, 5, 4, 3, 2, 1)
WIDTH = (1, 2, 3, 4, 5, 7, 9, 14, 28)
LIMIT = 1 << 28


def fits(x: list[int], i: int, k: int, w: int) -> bool:
    """True when x[i], ..., x[i + k - 1] are all below 2^w."""
    bound = 1 << w
    for j in range(i, i + k):
        if x[j] >= bound:
            return False
    return True


def encode(x: list[int]) -> list[int]:
    """Simple-9 encoding of a list of integers, each in [0, 2^28).

    Each output word is a 32-bit unsigned integer: a 4-bit selector in the top
    bits and up to 28 data bits. The greedy rule takes, at each word, the first
    selector (the one with the most values) whose values all fit. The last word
    may be partly filled, so the decoder needs len(x). Cost O(9 * 28) per word,
    O(n) for n values.
    """
    for v in x:
        if v < 0 or v >= LIMIT:
            raise ValueError("Simple-9 codes integers in [0, 2^28)")
    out: list[int] = []  # @line L1
    i, n = 0, len(x)
    while i < n:  # @line L2
        for s in range(9):  # @line L3
            k = min(COUNT[s], n - i)  # @line L4
            if fits(x, i, k, WIDTH[s]):  # @line L5
                break
        word = s << 28  # @line L6
        for j in range(k):  # @line L7
            word |= x[i + j] << (j * WIDTH[s])
        out.append(word)  # @line L8
        i += k
    return out  # @line L9


def decode(words: list[int], n: int) -> list[int]:
    """Decode n integers from Simple-9 words. Cost O(n + len(words))."""
    x: list[int] = []  # @line L10
    for word in words:  # @line L11
        s = word >> 28  # @line L12
        if s > 8:
            raise ValueError("selector out of range")
        w, mask = WIDTH[s], (1 << WIDTH[s]) - 1
        for j in range(COUNT[s]):  # @line L13
            if len(x) == n:
                break
            x.append((word >> (j * w)) & mask)
    if len(x) != n:
        raise ValueError("the words hold fewer than n integers")
    return x  # @line L14


def bits(words: list[int]) -> int:
    """The size of an encoding in bits: 32 for each word."""
    return 32 * len(words)


def optimal_word_count(x: list[int]) -> int:
    """The least number of Simple-9 words for x over all ways to split it.

    Dynamic programming over suffixes, for comparison with the greedy rule.
    Cost O(9 * 28 * n).
    """
    n = len(x)
    best = [0] * (n + 1)
    for i in range(n - 1, -1, -1):
        m = n + 1
        for s in range(9):
            k = min(COUNT[s], n - i)
            if fits(x, i, k, WIDTH[s]):
                m = min(m, 1 + best[i + k])
        best[i] = m
    return best[0]
test_simple_9.py 101 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/simple-9/. The authors are listed in prov/QCGBFK.jsonl.

import math
import random

from simple_9 import COUNT, WIDTH, bits, decode, encode, optimal_word_count


def width(v: int) -> int:
    """Bits needed for v, with 1 for v = 0."""
    return max(1, v.bit_length())


def check_words(words: list[int], x: list[int]) -> None:
    """Each word is 32 bits, and its data fields hold the next values in order."""
    i = 0
    for word in words:
        assert 0 <= word < 1 << 32
        s = word >> 28
        assert 0 <= s <= 8
        assert COUNT[s] * WIDTH[s] <= 28
        k = min(COUNT[s], len(x) - i)
        for j in range(k):
            assert (word >> (j * WIDTH[s])) & ((1 << WIDTH[s]) - 1) == x[i + j]
        assert (word & ((1 << 28) - 1)) >> (k * WIDTH[s]) == 0
        i += k
    assert i == len(x)


def gaps(ids: list[int]) -> list[int]:
    return [b - a for a, b in zip([0] + ids, ids)]


def test_layouts() -> None:
    assert list(zip(COUNT, WIDTH)) == [(28, 1), (14, 2), (9, 3), (7, 4), (5, 5), (4, 7), (3, 9), (2, 14), (1, 28)]
    assert [28 - c * w for c, w in zip(COUNT, WIDTH)] == [0, 0, 1, 0, 3, 0, 1, 0, 0]


def test_example() -> None:
    x = [1, 1, 2, 4, 3, 1, 10, 1, 200, 7, 7, 1]
    words = encode(x)
    assert [w >> 28 for w in words] == [3, 6, 2]
    assert words == [0x3A134211, 0x601D9001, 0x2000000F]
    assert gaps([1, 2, 4, 8, 11, 12, 22, 23, 223, 230, 237, 238]) == x
    assert decode(words, len(x)) == x
    assert bits(words) == 96


def test_edge_cases() -> None:
    assert encode([]) == [] and decode([], 0) == []
    assert decode(encode([0]), 1) == [0]
    top = (1 << 28) - 1
    assert encode([top]) == [(8 << 28) | top]
    assert decode(encode([top, 0, top]), 3) == [top, 0, top]
    assert len(encode([1] * 28)) == 1 and len(encode([1] * 29)) == 2
    for bad in ([1 << 28], [-1]):
        try:
            encode(bad)
        except ValueError:
            pass
        else:
            raise AssertionError("value out of range was accepted")


def test_bit_count_for_one_width() -> None:
    rng = random.Random(9)
    for w in range(1, 29):
        c = next(cnt for cnt, wd in zip(COUNT, WIDTH) if wd >= w)
        for n in (1, 2, 5, 13, 28, 29, 57, 100):
            lo = 0 if w == 1 else 1 << (w - 1)
            x = [rng.randrange(lo, 1 << w) for _ in range(n)]
            words = encode(x)
            assert len(words) == math.ceil(n / c)
            assert bits(words) == 32 * math.ceil(n / c)
            assert decode(words, n) == x


def test_greedy_is_not_always_optimal() -> None:
    x = [7, 300, 0, 2, 5, 3, 12, 3, 0, 100, 1, 300]
    assert len(encode(x)) == 4
    assert optimal_word_count(x) == 3


def test_random_lists() -> None:
    rng = random.Random(20261119)
    for _ in range(1500):
        n = rng.randint(0, 80)
        kind = rng.randrange(3)
        if kind == 0:
            ids = sorted(rng.sample(range(1, 5000), min(n, 4999)))
            x = gaps(ids)
        elif kind == 1:
            x = [rng.randrange(1 << rng.randint(0, 28)) for _ in range(n)]
        else:
            x = [rng.choice([0, 1, 1, 2, 3, (1 << 28) - 1]) for _ in range(n)]
        words = encode(x)
        assert decode(words, len(x)) == x
        check_words(words, x)
        assert len(words) >= optimal_word_count(x)
        assert len(words) >= math.ceil(sum(width(v) for v in x) / 28)

History

Anh and Moffat published Simple-9, with Relative-10 and Carryover-12, in Information Retrieval in 2005, as word-aligned codes that decode faster than bit-aligned codes such as Elias gamma and Golomb codes at a small cost in space. Later work extended the idea to 16 layouts in Simple-16 and to 64-bit words in Simple-8b, and the survey of Pibiri and Venturini lists these codes next to block codes such as PForDelta.

References

  1. Vo Ngoc Anh and Alistair Moffat, Inverted index compression using word-aligned binary codes, Information Retrieval 8(1), 2005, pages 151 to 166, the Simple-9 code with its nine layouts and 4-bit selector, and the Relative-10 and Carryover-12 codes of the same paper
  2. Techniques for inverted index compression, Section 3, the word-aligned codes Simple9, Simple16 and Simple8b, with the table of the Simple9 layouts
  3. Stefan Buettcher, Charles L. A. Clarke and Gordon V. Cormack, Information Retrieval, Implementing and Evaluating Search Engines, MIT Press, 2010, Chapter 6, Section 6.3 (compressing postings lists), and Section 6.3.4 (index compression for high query performance)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.decode
  • a full proof of time.encode
  • a full proof of space.extra
  • a full proof of space.output
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example