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
- Model
- Word RAM
- Properties
- not comparison baseddeterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
Simple-9 codes a list of nonnegative integers below , 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 of integers with . The output is a list of 32-bit words from which the decoder, given , 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 , the input is the list of gaps .
The algorithm
The nine layouts, as (count , width ) for selector , are:
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | |
|---|---|---|---|---|---|---|---|---|---|
| values | 28 | 14 | 9 | 7 | 5 | 4 | 3 | 2 | 1 |
| bits each | 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.
S9-ENCODE(x[0..n-1]) ▷ each x[i] in [0, 2^28)- 1
out ← empty list, i ← 0 - 2
while i < n do - 3
for s ← 0 to 8 do ▷ most values first - 4
k ← min(c_s, n - i) - 5
if x[i], ..., x[i + k - 1] are all below 2^(w_s) then stop the loop - 6
word ← s · 2^28 ▷ selector in the top 4 bits - 7
for j ← 0 to k - 1 do put x[i + j] in bits j·w_s to (j+1)·w_s - 1 of word - 8
append word to out, i ← i + k - 9
return out S9-DECODE(out, n)- 10
x ← empty list - 11
for each word of out do - 12
s ← ⌊word / 2^28⌋ - 13
for 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 - 14
return x
Line L3 tries the layouts from the one with the most values to the one with the fewest. Line L4 takes values, or the values that are left at the end of the list. Line L5 tests whether they all fit in 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 , or some other end mark.
The decoder reads the selector of each word at line L12, and line L13 cuts the data bits into fields of 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 | : 2 does not fit 1 bit. : 4 does not fit 2 bits. : 10 does not fit 3 bits | , 7 values of 4 bits | 1, 1, 2, 4, 3, 1, 10 | 3A134211 |
| 2 | to 4: 200 does not fit 5 bits or less. : 200 does not fit 7 bits | , 3 values of 9 bits | 1, 200, 7 | 601D9001 |
| 3 | and : 7 does not fit 2 bits | , 9 values of 3 bits, 2 used | 7, 1 | 2000000F |
The first word is 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 , and each word takes at least one value. In each word the selector is in the top four bits, and the values are in disjoint fields of bits below bit , 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 values, and the count 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 be integers with . The layouts are the pairs for : . For each of them .
-
Each step of the encoder ends and makes progress. At line L3, selector has and , and by the precondition, so the test of line L5 holds for at the latest. So the loop of line L3 always stops with some and , since . Line L8 adds to , so the loop of line L2 ends after at most words.
-
Each word is a valid 32-bit word. Line L5 ensures that for . Line L7 puts in bits to . These fields are disjoint and all lie below bit . Line L6 puts in bits 28 to 31. So the word is below , its top four bits are , its field holds for , and its bits from to 27 are zero.
-
The decoder reads back the same values. Let the encoder write words with selectors and counts , so that , and only the last word can have , because only when . By induction on , before the decoder reads word the list holds with . Line L12 recovers from the top four bits, by step 2. For , and , so line L13 reads all fields, which by step 2 are . For , line L13 reads fields until the list has values, that is the first fields, and these are the last values. So line L14 returns .
-
Word count for values of one width. Suppose every value has bit length exactly , with (for , the values 0 and 1). Let be the least selector with , and . A selector has , so it fails at line L5 on the first value. Selector fits any values. So every word takes values, and the encoding has words and bits.
The greedy choice of line L3 takes the selector with the most values that fit. This is not always the fewest words. For the encoder writes 4 words, in the layouts , and , and a last word in layout that holds only 300. The split , , 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 work per word and in total. A table of bit lengths or a running maximum makes the test faster in practice.
- Decoding. work for each word and for each value, so . 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 , the encoder uses the layout with the least width , so it writes words, that is bits. For this is the layout with 4 values of 7 bits, so 8 bits for each value; for 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 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 . 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 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 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 or more. Line L5 never passes for such a value, not even at , 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 values from every word in place of stopping at in line L13, it adds zeros from the unused fields of the last word. Store , or pad with a value the caller can tell apart.
- Testing only the first value. A test of line L5 that checks only in place of all 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.
# 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
- 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
- Techniques for inverted index compression, Section 3, the word-aligned codes Simple9, Simple16 and Simple8b, with the table of the Simple9 layouts
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag QCGBFK Edit this page History Report an error Markdown