The Word-RAM Model
The RAM model of Part I says that a word holds 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 bits in parallel, so with care it can do independent things to -bit fields at once.
The model
- Memory is an array of words of bits. A word is read or written in one step at an address that is itself a word.
- Keys are integers in the universe with : each key fills one word.
- , 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 is assumed; bounds are stated in terms of both and .
- 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 AC 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 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 rounds the word holds the count. Each round is a constant number of word operations, so popcount costs , and with one multiplication the last three rounds collapse into one (the sum of all bytes appears in the top byte of ).
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 against small keys in word operations. Store the in -bit fields, each preceded by a 1 bit (a sentinel), and replicate into fields preceded by a 0 bit:
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 among the , how many of them are at least . With sorted the sentinel bits form a run of ones, so their number is also the position of the boundary.
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.
#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 , the position of the highest 1 bit. Binary search over shifts finds it in word operations: test whether , then within the remaining half, and so on. Fredman and Willard (1993) showed it can be done in 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 () and popcount as operations.
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 keys | deterministic (Han, 2002); expected (Han and Thorup, 2002) | |
| predecessor, keys | with linear space, roughly | |
| priority queue | (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 -bit operations are unit cost. That is realistic for , 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 guarantee?
- Keys are random
- A word can hold an address (index) into the input
- Multiplication is available
- 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 get a **0**?
- To make the word longer
- So that subtracting from a field never borrows from the next field, and the sentinel survives exactly when
- To mark the field as sorted
- So that multiplication is not needed
How many word operations does SWAR popcount need on a -bit word, without the multiplication shortcut?