Optimizing Anthropic's VLIW SIMD Assignment

đź“… 2026-01-22

⌛ 310 days ago

đź“– 8 min read



Anthropic recently open sourced their performance engineering take-home. You get a tree traversal with some hashing and have to make it run as fast as possible on a simulated VLIW SIMD CPU.

I started this on a quiet evening, thinking “I’ll just poke at it for an hour.”

Four days later I was obsessed with instruction scheduling, and getting under 2,000 cycles was all I could think about.

147,734 cycles down to 1,524. That’s 96.9x.

TIL I have an unhealthy obsession with making numbers go down.

The Problem

256 “walkers” traverse a binary tree over 16 rounds. Each round:

  1. Load current node’s value
  2. XOR with walker’s value
  3. Hash the result (6 stages of multiply-add and xor/shift)
  4. Use the LSB to decide: go left (even) or right (odd)
  5. If we fall off the tree (depth > 10), reset to root

The tree is stored as an implicit array: node i has children at 2i+1 and 2i+2.

Le Machine

You can’t do much here without knowing the hardware. It’s VLIW (Very Long Instruction Word), so a single cycle can run several operations in parallel across different “engines”:

  • ALU: 12 scalar ops per cycle
  • VALU: 6 vector ops per cycle
  • Load: 2 memory reads per cycle
  • Store: 2 memory writes per cycle
  • Flow: 1 control op per cycle

And it’s SIMD, so each vector op works on 8 elements at once.

On paper that’s 23 ops per cycle. In practice:

  • You can’t read a register that’s being written in the same cycle (RAW hazard)
  • You can’t write the same register twice in one cycle (WAW hazard)
  • Anything that depends on another op has to go in a later cycle

The one that matters is the load engine. Only 2 loads per cycle, and this problem does a lot of loads. Pretty much every optimization after this was about keeping those two slots busy, or not needing them at all.

The Baseline: 147,734 Cycles

The starter code processes walkers sequentially. One walker at a time, one round at a time:

for round in range(16):
    for walker in range(256):
        # Load, XOR, Hash, Store

That uses maybe 1-2% of the machine per cycle.

Step 1: SIMD → 25,165 cycles (5.87x)

Process 8 walkers at a time instead of 1.

# Before: scalar
load(val, addr)
alu("+", result, val, const)

# After: vector (8 walkers at once)
vload(v_val, addr)
valu("+", v_result, v_val, v_const)

8x the work per instruction, and with 6 VALU slots that’s up to 48 walkers worth of math per cycle. Everything after this builds on it.

Step 2: Hazard-Aware Packing → 15,438 cycles (9.57x)

After vectorizing there were lots of independent instructions, but they still ran one per cycle. So I wrote pack_slots() to bundle independent instructions into the same cycle.

The algorithm tracks which registers are written in the current cycle. A new instruction can pack if:

  • Its reads don’t overlap with current writes (RAW hazard)
  • Its writes don’t overlap with current writes (WAW hazard)
  • The engine slot limit isn’t exceeded
def pack_slots(instructions):
    cycles = []
    current_cycle = []
    current_writes = set()
    engine_counts = defaultdict(int)

    for inst in instructions:
        reads, writes = get_registers(inst)
        engine = inst.engine

        # Check hazards and slot limits
        has_raw = reads & current_writes
        has_waw = writes & current_writes
        engine_full = engine_counts[engine] >= ENGINE_LIMITS[engine]

        if has_raw or has_waw or engine_full:
            # Start new cycle
            cycles.append(current_cycle)
            current_cycle = []
            current_writes = set()
            engine_counts = defaultdict(int)

        current_cycle.append(inst)
        current_writes |= writes
        engine_counts[engine] += 1

    return cycles

That got it from 1 op per cycle to 5-10 wherever possible. A dumb greedy packer gets you surprisingly far.

Step 3: Phase Interleaving → 5,870 cycles (25.2x)

This was the big one.

Before, I processed all 16 rounds for chunk 0, then chunk 1, and so on:

chunk0: round0 → round1 → ... → round15
chunk1: round0 → round1 → ... → round15

But each round depends on the previous one, so that’s a dependency chain 16 rounds long and the packer can’t overlap any of it.

So I flipped it: round 0 for every chunk, then round 1 for every chunk, and so on:

round0: chunk0, chunk1, ..., chunk31
round1: chunk0, chunk1, ..., chunk31

Within a round, different chunks are completely independent. While chunk 0 is waiting for its load to complete, we can work on chunks 1, 2, 3…

I swapped two nested loops and got 4x. Shorter dependency chains, more to run in parallel.

Step 4: Stream Scheduler → 2,779 cycles (53x)

Still plenty of idle slots, so I got fancier. Each chunk becomes a “stream” of operations, and the scheduler interleaves streams to keep the engines busy. The trick was capping how many streams can switch from VALU work to loads in a single cycle (switch_cap=1), so they don’t all pile onto the load engine at once.

I couldn’t fully explain why some of the knobs worked. But the load engine stayed busy much more consistently.

Step 5: Shallow Tree Preloading → 2,516 cycles (59x)

A tree of height 10 has 2047 nodes, but the first few levels are tiny:

  • Level 0: 1 node (root)
  • Level 1: 2 nodes
  • Level 2: 4 nodes

For the first few rounds, all 256 walkers are guaranteed to access these same 7 nodes.

So: preload nodes 0-6 into vector registers at startup. Precompute the differences. For shallow rounds, use multiply_add to select the right node without memory access:

# Branchless mux using multiply_add
left = b1 * diff34 + node3   # node3 or node4
right = b1 * diff56 + node5  # node5 or node6
result = b0 * (right - left) + left

Loads are the bottleneck, so every load I don’t do is free cycles.

2,779 to 2,516 is only about 10%, much smaller than the earlier jumps. I was running out of big ideas by this point.

Step 6: Scratch Optimization → 2,347 cycles (63x)

The input values only need to be read once at the start and written once at the end, but I was reading and writing them every round. So now they get loaded into scratch memory once, stay there for all 16 rounds, and get written back at the end.

Also, the flow engine only has 1 slot for add_imm. With two pointers I could increment both on the ALU in parallel instead of queueing up on flow.

Step 7: Skip Redundant Ops → 2,257 cycles (65.5x)

A bunch of tiny ones:

  • Skip the pointer update in the last round (nothing uses it)
  • Simpler reset logic, since we know exactly which round it happens in
  • Stop storing the direction bit in later rounds (only the shallow tree trick needs it)

Step 8: Global List Scheduler + multiply_add → 1,524 cycles (96.9x)

Two things got me the rest of the way.

Global List Scheduler

The setup phase (loading constants, preloading nodes, initializing pointers) has messy dependencies and my simple packer was doing a bad job of it. So:

  1. Build a dependency graph across all instructions
  2. Compute instruction “levels” via BFS (distance from root operations)
  3. Use priority queues per engine, prioritizing higher-level (more critical) instructions
  4. Greedily schedule the highest-priority ready instruction each cycle

The setup phase went from taking forever to barely anything.

multiply_add Fusion

The hash function has 6 stages. Three are affine+shift:

a = (a + C1) + (a << 12)   # a*4097 + C1
a = (a + C3) + (a << 5)    # a*33 + C3
a = (a + C5) + (a << 3)    # a*9 + C5

Each of those is 3 VALU ops (shift + add + add). But the machine has a fused multiply_add(a, b, c) that does a * b + c in one op, and a + (a << 12) is just a * 4097. So 3 ops become 1.

That’s 33% fewer VALU ops per hash, times 256 walkers × 16 rounds. Took me embarrassingly long to see. ✨

The Obsession

Every time I ran the tests and saw a number starting with 2, I had to try one more thing. Meanwhile the load engine sat at 100% the whole time.

When I finally hit 1,524 I just stared at the terminal for a minute. The load engine was still at 100%, so there’s probably more in there.

But I had to get back to work :>

The Numbers

Metric Value
Total cycles 1,524
Total operations 11,152
Ops/cycle 7.32 / 23 possible (31.8%)
VALU utilization 5.72/6 slots (95.3%)
Load utilization 2.00/2 slots (100%)

The final code is 720 lines of Python generating ~11,000 VLIW instructions.

I love problems like this. Monkey brain like number go down.