TExcelTAD
Home › Online Algorithms & Competitive Analysis › The Randomized Marking Algorithm

The Randomized Marking Algorithm

Deterministic paging is stuck at ratio kk because the adversary always knows which page is missing. The marking algorithm of Fiat, Karp, Luby, McGeoch, Sleator and Young (1991) hides that information: it evicts a uniformly random page among those not requested recently. Against an oblivious adversary its expected cost is at most 2Hk2H_k times OPT, where Hk≈ln⁡kH_k \approx \ln k, an exponential improvement over kk. This lesson states the algorithm, proves the 2Hk2H_k bound with the classic "new pages versus old pages" argument, and tests the bound on the sequences that hurt LRU most.

The algorithm

MARK uses the phases of LRU and FIFO Are k-Competitive, but discovers them online: a new phase starts when a page is requested, it is not in the cache, and every cached page is already marked.

text
MARK(k)
0  on request for page p
1      if p is not in the cache
2          if the cache is full
3              if every cached page is marked
4                  unmark all pages                  // a new phase begins
5              evict a page chosen uniformly at random among the unmarked cached pages
6          load p
7      mark p

MARK is a marking algorithm in the sense of the earlier lesson, so it is also kk-competitive in the worst case; the point is the much better expected cost. The trace below runs it on a short sequence with k=3k = 3 and a fixed seed, showing the marks after each request (an asterisk marks a page).

python · try it yourself
import random

def mark_trace(reqs, k, rng):
    cache, marked, misses, lines = [], set(), 0, []
    for p in reqs:
        note = "hit"
        if p not in cache:
            misses += 1
            note = "miss"
            if len(cache) == k:
                if marked >= set(cache):
                    marked = set()
                    note += ", new phase"
                victim = rng.choice(sorted(q for q in cache if q not in marked))
                cache[cache.index(victim)] = p
                note += f", evict {victim}"
            else:
                cache.append(p)
        marked.add(p)
        shown = " ".join(q + ("*" if q in marked else " ") for q in cache)
        lines.append(f"{p}: {shown:12} {note}")
    return misses, lines

reqs = "A B C D A B E C A D B E".split()
misses, lines = mark_trace(reqs, 3, random.Random(3))
print("\n".join(lines))
print(f"{misses} misses")
A: A*           miss
B: A* B*        miss
C: A* B* C*     miss
D: D* B  C      miss, new phase, evict A
A: D* A* C      miss, evict B
B: D* A* B*     miss, evict C
E: E* A  B      miss, new phase, evict D
C: E* A  C*     miss, evict B
A: E* A* C*     hit
D: D* A  C      miss, new phase, evict E
B: D* B* C      miss, evict A
E: D* B* E*     miss, evict C
11 misses

The analysis: new and old pages

Theorem (Fiat, Karp, Luby, McGeoch, Sleator and Young, 1991). For every request sequence σ\sigma fixed in advance, with both caches starting empty,

E[MARK(σ)]≤2Hk⋅OPT(σ).\mathbb{E}\bigl[\mathrm{MARK}(\sigma)\bigr] \le 2H_k \cdot \mathrm{OPT}(\sigma) .

So MARK is strictly 2Hk2H_k-competitive against an oblivious adversary.

Call a page requested in phase ii new if it was not requested in phase i−1i - 1, and old otherwise. Let mim_i be the number of new pages in phase ii; phase ii has mim_i new and k−mik - m_i old distinct pages (all phases but the last have kk distinct pages; the last can only have fewer, which only helps).

Step 1: MARK's expected cost in a phase is at most $m_i(1 + H_k - H_{m_i})$

At the start of phase ii, MARK's cache holds exactly the kk pages of phase i−1i - 1 (they were all marked when the phase ended). Each new page causes exactly one miss. An old page may or may not still be in the cache when it is first requested in phase ii.

Consider the jj-th distinct old page requested in the phase, j=1,…,k−mij = 1, \ldots, k - m_i. Just before that request, j−1j - 1 old pages and at most mim_i new pages have been requested and marked. Of the k−(j−1)k - (j - 1) old pages not yet requested in this phase, the cache is missing exactly as many as there have been evictions of unmarked old pages, at most mim_i (each new page and each old page that missed forced one eviction, and old misses only replace a previously evicted old page). The evictions are uniformly random among unmarked pages, so by symmetry every one of the k−j+1k - j + 1 unrequested old pages is equally likely to be among the missing ones. Hence

Pr⁡[the j-th old page misses]≤mik−j+1,\Pr[\text{the } j\text{-th old page misses}] \le \frac{m_i}{k - j + 1},

and summing over jj gives the expected number of old misses:

∑j=1k−mimik−j+1=mi(Hk−Hmi).\sum_{j=1}^{k - m_i} \frac{m_i}{k - j + 1} = m_i \bigl(H_k - H_{m_i}\bigr) .

Adding the mim_i misses on new pages gives at most mi(1+Hk−Hmi)≤miHkm_i(1 + H_k - H_{m_i}) \le m_i H_k, since Hmi≥1H_{m_i} \ge 1.

Step 2: OPT is at least half the number of new pages

Let OPTi\mathrm{OPT}_i be OPT's misses during phase ii. During phases i−1i - 1 and ii together, at least k+mik + m_i distinct pages are requested: the kk pages of phase i−1i - 1 and the mim_i new pages of phase ii. A cache of size kk cannot avoid missing on at least mim_i of them, so OPTi−1+OPTi≥mi\mathrm{OPT}_{i-1} + \mathrm{OPT}_i \ge m_i. In phase 1 the cache starts empty and OPT1≥k=m1\mathrm{OPT}_1 \ge k = m_1. Summing over all ii, each OPTi\mathrm{OPT}_i appears at most twice:

2 OPT≥∑imi.2\,\mathrm{OPT} \ge \sum_i m_i .

Combining the steps: E[MARK]≤Hk∑imi≤2Hk OPT\mathbb{E}[\mathrm{MARK}] \le H_k \sum_i m_i \le 2H_k\,\mathrm{OPT}.

Both steps can be tight, but not on the same sequence, and the true ratio of MARK is slightly smaller: Achlioptas, Chrobak and Noga (2000) showed that it is exactly 2Hk−12H_k - 1. The best possible randomized ratio is HkH_k (the next lesson), achieved by the more elaborate algorithms PARTITION (McGeoch and Sleator, 1991) and EQUITABLE (Achlioptas, Chrobak and Noga, 2000).

Checking the phase bound

The per-phase bound of Step 1 is attained when the new pages come first in the phase, so that the old pages are requested while the cache is missing as many of them as possible. The program builds such phases: phase 1 requests pages 0,…,k−10, \ldots, k - 1; every later phase requests mm brand-new pages and then k−mk - m of the previous phase's pages. It averages MARK's misses per phase over many seeded runs and compares with m(1+Hk−Hm)m(1 + H_k - H_m).

python · try it yourself
import random

def mark_misses(reqs, k, rng):
    cache, pos, marked, misses = [], {}, set(), 0
    for p in reqs:
        if p not in pos:
            misses += 1
            if len(cache) == k:
                if len(marked) == k:
                    marked = set()
                unmarked = [q for q in cache if q not in marked]
                victim = unmarked[rng.randrange(len(unmarked))]
                i = pos.pop(victim)
                cache[i] = p
            else:
                cache.append(p)
                i = len(cache) - 1
            pos[p] = i
        marked.add(p)
    return misses

def phased_sequence(k, m, phases, rng):
    prev, nxt_page, reqs = list(range(k)), k, list(range(k))
    for _ in range(phases):
        new = list(range(nxt_page, nxt_page + m))
        nxt_page += m
        old = rng.sample(prev, k - m)
        reqs += new + old
        prev = new + old
    return reqs

H = lambda n: sum(1 / i for i in range(1, n + 1))
rng = random.Random(10)
k, phases, runs = 8, 40, 30
print(f"k = {k}")
print(" m   measured misses/phase   m(1 + H_k - H_m)   m H_k")
for m in [1, 2, 4, 8]:
    total = 0
    for _ in range(runs):
        reqs = phased_sequence(k, m, phases, rng)
        total += mark_misses(reqs, k, rng) - k          # drop the k misses of phase 1
    print(f"{m:2}   {total / (runs * phases):21.3f}   {m * (1 + H(k) - H(m)):16.3f}   {m * H(k):5.3f}")
k = 8
 m   measured misses/phase   m(1 + H_k - H_m)   m H_k
 1                   2.684              2.718   2.718
 2                   4.466              4.436   5.436
 4                   6.523              6.538   10.871
 8                   8.000              8.000   21.743

The measurements sit at the formula, so the per-phase analysis is exact for this kind of phase.

In C++

An implementation with O(1)O(1) work per request: the unmarked cached pages are kept in an array, so a random one is drawn with one call to the generator and removed by swapping it with the last element. The program measures MARK against LRU and OPT on the cyclic sequence over k+1k + 1 pages, the cruel adversary's sequence against LRU.

cpp · try it yourself
#include <cstdio>
#include <random>
#include <unordered_map>
#include <vector>

struct Mark {
    int k;
    std::mt19937 rng;
    std::vector<int> unmarked;                    // cached, not yet requested this phase
    std::unordered_map<int, int> where;           // page -> index in unmarked, or -1 if marked
    int cached = 0;
    std::vector<int> marked_pages;
    Mark(int k, unsigned seed) : k(k), rng(seed) {}
    bool access(int p) {
        auto it = where.find(p);
        bool miss = it == where.end();
        if (miss) {
            if (cached == k) {
                if (unmarked.empty()) {                       // new phase: unmark everything
                    for (int q : marked_pages) { where[q] = unmarked.size(); unmarked.push_back(q); }
                    marked_pages.clear();
                }
                int i = rng() % unmarked.size();
                int victim = unmarked[i];
                unmarked[i] = unmarked.back();
                where[unmarked[i]] = i;
                unmarked.pop_back();
                where.erase(victim);
                --cached;
            }
            ++cached;
        } else if (it->second >= 0) {                         // cached and unmarked: mark it
            int i = it->second;
            unmarked[i] = unmarked.back();
            where[unmarked[i]] = i;
            unmarked.pop_back();
        } else {
            return false;                                     // already marked
        }
        where[p] = -1;
        marked_pages.push_back(p);
        return miss;
    }
};

int main() {
    for (int k : {4, 8, 16, 32}) {
        int n = 40000;
        std::vector<int> r(n);
        for (int t = 0; t < n; ++t) r[t] = t % (k + 1);
        Mark mark(k, 7);
        int m = 0;
        for (int p : r) m += mark.access(p);
        int lru = n;                                  // LRU misses on every request of the cycle
        int opt = k + (n - k + k - 1) / k;            // compulsory misses, then one per k requests
        double H = 0;
        for (int i = 1; i <= k; ++i) H += 1.0 / i;
        std::printf("k = %2d: MARK/OPT = %.3f, LRU/OPT = %.3f, 2H_k = %.3f, H_k = %.3f\n",
                    k, double(m) / opt, double(lru) / opt, 2 * H, H);
    }
}
k =  4: MARK/OPT = 2.095, LRU/OPT = 3.999, 2H_k = 4.167, H_k = 2.083
k =  8: MARK/OPT = 2.698, LRU/OPT = 7.989, 2H_k = 5.436, H_k = 2.718
k = 16: MARK/OPT = 3.382, LRU/OPT = 15.905, 2H_k = 6.761, H_k = 3.381
k = 32: MARK/OPT = 3.966, LRU/OPT = 31.226, 2H_k = 8.117, H_k = 4.058

On the cycle MARK's ratio is close to HkH_k, well inside its guarantee 2Hk2H_k, while LRU pays the full factor kk. (The cycle is a sequence where every phase has exactly one new page, the case m=1m = 1 of the table above, and 1+Hk−H1=Hk1 + H_k - H_1 = H_k.)

In practice

Randomized eviction is used in real systems: some processor caches use (pseudo-)random replacement because it needs no recency bookkeeping, and the marking idea, "evict something not recently used, but not deterministically", appears in CLOCK variants. The competitive analysis explains a practical advantage: a deterministic policy has pathological access patterns (a loop slightly larger than the cache defeats LRU completely), while a randomized one degrades gracefully on every pattern.

Test yourself

Which page does MARK evict on a miss with a full cache?

  1. The least recently used page
  2. A uniformly random unmarked page
  3. A uniformly random cached page
  4. The page requested furthest in the future

A phase of MARK with k=4k = 4 has m=2m = 2 new pages, requested first. What is the expected number of misses in the phase according to the analysis?

  1. 22
  2. 2(1+H4−H2)=2+2(1/3+1/4)≈3.172(1 + H_4 - H_2) = 2 + 2(1/3 + 1/4) \approx 3.17
  3. 44
  4. 2H4≈4.172H_4 \approx 4.17

Why is OPTi−1+OPTi≥mi\mathrm{OPT}_{i-1} + \mathrm{OPT}_i \ge m_i?

  1. Because OPT misses on every new page
  2. Because phases i−1i-1 and ii together request at least k+mik + m_i distinct pages, which a cache of size kk cannot all hold
  3. Because MARK misses mim_i times
  4. Because OPT is lazy

What is known about the exact competitive ratio of MARK against an oblivious adversary?

  1. It is exactly HkH_k
  2. It is exactly 2Hk−12H_k - 1
  3. It is kk
  4. It is unknown