TExcelTAD
Home › Advanced & Succinct Data Structures › The Word-RAM Model

The Word-RAM Model

The RAM model of Part I says that a word holds clg⁡nc \lg n bits and that word operations cost one step, then never uses the bits. The word-RAM takes the bits seriously. It is the model behind every integer data structure in this section, and its power comes from one observation: a single word operation acts on ww bits in parallel, so with care it can do w/bw / b independent things to bb-bit fields at once.

The model

  • Memory is an array of words of ww bits. A word is read or written in one step at an address that is itself a word.
  • Keys are integers in the universe {0,…,U−1}\{0, \ldots, U - 1\} with U=2wU = 2^w: each key fills one word.
  • w≥lg⁡nw \ge \lg n, so that a word can address the input. This assumption ties the machine to the problem size and is called trans-dichotomous (Fredman and Willard, 1990). Nothing else about ww is assumed; bounds are stated in terms of both nn and ww.
  • In one step: addition, subtraction, multiplication, integer division, comparisons, bitwise AND, OR, XOR, NOT, and left and right shifts by any amount.

Some results need only the AC0^0 operations (addition, comparison, bitwise operations, shifts, no multiplication), because multiplication cannot be done by constant-depth circuits. When a bound depends on multiplication, the literature says so; fusion trees use it, van Emde Boas trees do not.

Word-level parallelism: counting bits

Count the 1 bits of a 64-bit word (popcount). Looking at bits one by one costs ww steps. Instead, treat the word as 32 fields of 2 bits, add neighbouring bits into each field at once, then add neighbouring 2-bit fields into 4-bit fields, and so on. After lg⁡w\lg w rounds the word holds the count. Each round is a constant number of word operations, so popcount costs O(lg⁡w)O(\lg w), and with one multiplication the last three rounds collapse into one (the sum of all bytes appears in the top byte of x⋅0x0101…01x \cdot \texttt{0x0101}\ldots\texttt{01}).

python · try it yourself
M = (1 << 64) - 1                                   # simulate 64-bit words

def popcount_swar(x):
    ops = 0
    x = x - ((x >> 1) & 0x5555555555555555); ops += 3          # 2-bit fields
    x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333); ops += 4   # 4-bit fields
    x = (x + (x >> 4)) & 0x0F0F0F0F0F0F0F0F; ops += 3          # bytes
    x = ((x * 0x0101010101010101) & M) >> 56; ops += 3          # add all bytes into the top byte
    return x, ops

def popcount_naive(x):
    c = ops = 0
    while x:
        c += x & 1; x >>= 1; ops += 3
    return c, ops

for x in [0, 1, 0xFF, 0xDEADBEEFCAFEF00D, M]:
    s, so = popcount_swar(x)
    n, no = popcount_naive(x)
    assert s == n == bin(x).count("1")
    print(f"{x:#018x}: popcount {s:2}   word ops: SWAR {so}, bit by bit {no}")
0x0000000000000000: popcount  0   word ops: SWAR 13, bit by bit 0
0x0000000000000001: popcount  1   word ops: SWAR 13, bit by bit 3
0x00000000000000ff: popcount  8   word ops: SWAR 13, bit by bit 24
0xdeadbeefcafef00d: popcount 42   word ops: SWAR 13, bit by bit 192
0xffffffffffffffff: popcount 64   word ops: SWAR 13, bit by bit 192

This style is called SWAR (SIMD within a register). Modern processors also have a popcnt instruction, but the technique matters for operations without one.

Parallel comparison of packed fields

The trick behind fusion trees compares one small key yy against kk small keys x0,…,xk−1x_0, \ldots, x_{k-1} in O(1)O(1) word operations. Store the xix_i in bb-bit fields, each preceded by a 1 bit (a sentinel), and replicate yy into fields preceded by a 0 bit:

text
A = [1 x_{k-1}] ... [1 x_1] [1 x_0]          each field b + 1 bits
C = [0 y]       ... [0 y]   [0 y]            C = y * (1 + 2^(b+1) + 2^(2(b+1)) + ...)
A - C: the sentinel of field i stays 1 exactly when x_i >= y (no borrow crosses a field)

Masking the sentinels and counting them gives the rank of yy among the xix_i, how many of them are at least yy. With sorted xix_i the sentinel bits form a run of ones, so their number is also the position of the boundary.

python · try it yourself
def pack(values, b):
    word = 0
    for i, v in enumerate(values):
        word |= ((1 << b) | v) << (i * (b + 1))       # sentinel 1, then the b-bit value
    return word

def parallel_rank(packed, k, b, y):
    ones = sum(1 << (i * (b + 1)) for i in range(k)) # 0..01 0..01 ... 0..01
    c = y * ones                                     # y replicated into every field (one multiply)
    diff = packed - c                                # one subtraction compares all k fields
    sentinels = diff & (ones << b)                   # keep only the sentinel bits
    return bin(sentinels).count("1")                 # = number of fields with x_i >= y

b, xs = 7, [3, 17, 40, 41, 88, 100, 127]             # 7 sorted 7-bit keys fit in 56 bits
A = pack(xs, b)
print("packed word:", hex(A), "uses", A.bit_length(), "bits")
for y in [0, 18, 41, 99, 127]:
    r = parallel_rank(A, len(xs), b, y)
    print(f"y = {y:3}: {r} keys are >= y, so {len(xs) - r} keys are < y  (check {sum(x < y for x in xs)})")
packed word: 0xffe4d8a9a89183 uses 56 bits
y =   0: 7 keys are >= y, so 0 keys are < y  (check 0)
y =  18: 5 keys are >= y, so 2 keys are < y  (check 2)
y =  41: 4 keys are >= y, so 3 keys are < y  (check 3)
y =  99: 2 keys are >= y, so 5 keys are < y  (check 5)
y = 127: 1 keys are >= y, so 6 keys are < y  (check 6)

The final bin(...).count stands in for a constant-time step: since the set sentinels are contiguous (for sorted fields), the count can be read off with a most-significant-bit computation, or with one more multiplication that sums the sentinel bits into one field.

In C++

The same two techniques on real 64-bit words. std::popcount (C++20) compiles to the hardware instruction where one exists; the SWAR version shows what it replaces.

cpp · try it yourself
#include <bit>
#include <cstdint>
#include <cstdio>
#include <vector>

using u64 = std::uint64_t;

int popcount_swar(u64 x) {
    x = x - ((x >> 1) & 0x5555555555555555ULL);
    x = (x & 0x3333333333333333ULL) + ((x >> 2) & 0x3333333333333333ULL);
    x = (x + (x >> 4)) & 0x0F0F0F0F0F0F0F0FULL;
    return static_cast<int>((x * 0x0101010101010101ULL) >> 56);
}

// k fields of b bits, each with a sentinel bit above it: rank of y = number of fields >= y.
int parallel_rank(u64 packed, int k, int b, u64 y) {
    u64 ones = 0;
    for (int i = 0; i < k; ++i) ones |= u64{1} << (i * (b + 1));
    u64 diff = packed - y * ones;
    return std::popcount(diff & (ones << b));
}

int main() {
    for (u64 x : {u64{0}, u64{0xFF}, u64{0xDEADBEEFCAFEF00DULL}, ~u64{0}}) {
        std::printf("0x%016llx: swar %2d, std::popcount %2d\n",
                    static_cast<unsigned long long>(x), popcount_swar(x), std::popcount(x));
    }
    const int b = 7;
    std::vector<u64> xs = {3, 17, 40, 41, 88, 100, 127};
    u64 packed = 0;
    for (std::size_t i = 0; i < xs.size(); ++i) packed |= ((u64{1} << b) | xs[i]) << (i * (b + 1));
    for (u64 y : {0, 18, 41, 99, 127}) {
        int r = parallel_rank(packed, static_cast<int>(xs.size()), b, y);
        std::printf("y = %3llu: %d keys < y\n", static_cast<unsigned long long>(y), static_cast<int>(xs.size()) - r);
    }
}
0x0000000000000000: swar  0, std::popcount  0
0x00000000000000ff: swar  8, std::popcount  8
0xdeadbeefcafef00d: swar 42, std::popcount 42
0xffffffffffffffff: swar 64, std::popcount 64
y =   0: 0 keys < y
y =  18: 2 keys < y
y =  41: 3 keys < y
y =  99: 5 keys < y
y = 127: 6 keys < y

The most significant bit

Many structures need msb⁡(x)=⌊lg⁡x⌋\operatorname{msb}(x) = \lfloor \lg x \rfloor, the position of the highest 1 bit. Binary search over shifts finds it in O(lg⁡w)O(\lg w) word operations: test whether x≥232x \ge 2^{32}, then 2162^{16} within the remaining half, and so on. Fredman and Willard (1993) showed it can be done in O(1)O(1) word operations using multiplication, by the same packing ideas as above; hardware has it as lzcnt/bsr (std::bit_width in C++). The lessons that follow use msb, lowest set bit (x&−xx \mathbin{\&} {-x}) and popcount as O(1)O(1) operations.

python · try it yourself
def msb(x):
    """Index of the highest set bit of a 64-bit x > 0, by binary search on shift amounts."""
    pos, steps = 0, 0
    for shift in (32, 16, 8, 4, 2, 1):
        steps += 1
        if x >> shift:
            x >>= shift
            pos += shift
    return pos, steps

for x in [1, 2, 1000, 2 ** 40 + 5, 2 ** 63]:
    p, s = msb(x)
    assert p == x.bit_length() - 1
    lowest = x & -x
    print(f"x = {x:20}: msb {p:2} in {s} steps, lowest set bit 2^{lowest.bit_length() - 1}")
x =                    1: msb  0 in 6 steps, lowest set bit 2^0
x =                    2: msb  1 in 6 steps, lowest set bit 2^1
x =                 1000: msb  9 in 6 steps, lowest set bit 2^3
x =        1099511627781: msb 40 in 6 steps, lowest set bit 2^0
x =  9223372036854775808: msb 63 in 6 steps, lowest set bit 2^63

What the model buys

Problem Comparison model Word-RAM
sorting nn keys Θ(nlg⁡n)\Theta(n \lg n) O(nlg⁡lg⁡n)O(n \lg \lg n) deterministic (Han, 2002); O(nlg⁡lg⁡n)O(n \sqrt{\lg \lg n}) expected (Han and Thorup, 2002)
predecessor, nn keys Θ(lg⁡n)\Theta(\lg n) O(min⁡(lg⁡w,log⁡wn))O(\min(\lg w, \log_w n)) with linear space, roughly
priority queue Θ(lg⁡n)\Theta(\lg n) O(lg⁡lg⁡n)O(\lg \lg n) (Thorup's reduction from sorting)

Treat the last two rows as orientation: the precise statements, with their space and randomization conditions, come in the lessons on van Emde Boas trees, y-fast tries, fusion trees and integer sorting.

Note: "Constant time" on a word-RAM assumes ww-bit operations are unit cost. That is realistic for w=64w = 64, and that is the only regime in which these structures are used in practice. Python's integers have no fixed width, so the programs mask to 64 bits where it matters.

Test yourself

What does the trans-dichotomous assumption w≥lg⁡nw \ge \lg n guarantee?

  1. Keys are random
  2. A word can hold an address (index) into the input
  3. Multiplication is available
  4. Words have exactly 64 bits

In the parallel comparison, why is each field stored with a **1** sentinel bit above it while the copies of yy get a **0**?

  1. To make the word longer
  2. So that subtracting yy from a field never borrows from the next field, and the sentinel survives exactly when xi≥yx_i \ge y
  3. To mark the field as sorted
  4. So that multiplication is not needed

How many word operations does SWAR popcount need on a ww-bit word, without the multiplication shortcut?

  1. O(1)O(1)
  2. O(lg⁡w)O(\lg w)
  3. O(w)O(w)
  4. O(wlg⁡w)O(w \lg w)