LearnTopic guide

Coding for ML and LLM engineering

Coding rounds for AI roles are rarely pure puzzle-solving. Expect practical Python: an async client with rate limits and retries, an agent loop, an eval harness, a streaming parser, sampling or BPE from scratch, NumPy retrieval, attention in PyTorch, and classic data-structure problems under time pressure (heavy hitters, quickselect, tries, a key–value store built in stages). Interviewers grade correctness, complexity, edge cases, tests and how clearly you narrate trade-offs, and increasingly how you use and check AI coding tools.

Research · Applied LLM · ML engineering7 key concepts12 questions

Start: Key concepts 6 lessons · about 16 min
Contents

Key concepts

Asyncio essentials

The event loop is single-threaded, so any blocking call (time.sleep, a synchronous HTTP client, heavy CPU work) stalls every coroutine; use asyncio.sleep, async clients, or run_in_executor. Cap in-flight work with asyncio.Semaphore; prefer asyncio.TaskGroup (Python 3.11+) for structured concurrency (one failure cancels the siblings), or gather with return_exceptions=True when you want every outcome, failures included, as a result; use asyncio.timeout (3.11+) per request. gather returns results in input order regardless of completion order.

Rate limits, retries and backoff

Providers enforce requests per minute and tokens per minute; a token bucket (capacity plus refill rate) models both. Retry only transient failures (429, 5xx, timeouts), never 400s or auth errors; honour Retry-After; use capped exponential backoff with jitter, for example sleep = uniform(0, min(cap, base × 2^attempt)) (“full jitter”), so clients do not retry in lockstep; cap attempts and make retried actions idempotent.

Sequence · 5 stepsRetry and backoff request path

Retry and backoff request pathThe client takes estimated tokens from the token bucket, calls the API under the semaphore and timeout, and on a transient 429 or 5xx sleeps outside the semaphore before retrying. The retry repeats the bucket take and then re-enters the semaphore, with gather preserving input order.ClientToken bucketAPI1take est tokenstokens grantedcall(p)2429 / 5xx3backoff sleep4take est tokenstokens granted5retry call(p)response
Retry and backoff request pathThe client takes estimated tokens from the token bucket, calls the API under the semaphore and timeout, and on a transient 429 or 5xx sleeps outside the semaphore before retrying. The retry repeats the bucket take and then re-enters the semaphore, with gather preserving input order.ClientToken bucketAPI1take est tokenstokens grantedcall(p)2429 / 5xx3backoff sleep4take est tokenstokens granted5retry call(p)response
  1. First attempt The first attempt takes estimated tokens before entering the semaphore and timeout.
  2. Transient failure A 429 or 5xx is raised by call; 400s and auth errors are not retried.
  3. Backoff The backoff sleep happens outside the semaphore; honour Retry-After or capped exponential backoff with jitter.
  4. Retry bucket take Every attempt calls bucket.take(est_tokens(p)) again, so the retry respects the TPM limit.
  5. Retry call The retry re-enters the semaphore and timeout; gather preserves input order.

Each attempt re-takes estimated tokens from the bucket before re-entering the semaphore, so retries stay within the TPM limit.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Messages
StepFromToMessage
1ClientToken buckettake est tokens
1Token bucketClienttokens granted (reply)
1ClientAPIcall(p)
2APIClient429 / 5xx (reply)
3ClientClientbackoff sleep
4ClientToken buckettake est tokens
4Token bucketClienttokens granted (reply)
5ClientAPIretry call(p)
5APIClientresponse (reply)

Source: This page's text

Vectorised numerics in NumPy and PyTorch

Know broadcasting (dimensions are compared from the right; each pair must match or one must be 1). Use argpartition for top-k in O(n) rather than a full O(n log n) sort; compute softmax as exp(z − max) and log-softmax as z − logsumexp(z); mask with −inf before softmax instead of slicing; keep tensor shapes explicit, e.g. (B, T, H, D), and remember view needs compatible (usually contiguous) memory where reshape copies if needed.

Algorithms to know cold

Hash-map counting in O(n); heaps for top-k in O(n log k); quickselect for the k-th largest in expected O(n) but O(n²) worst case; tries for prefix queries; two pointers and sliding windows; reservoir sampling; and streaming sketches: Misra–Gries with k counters under-counts by at most n/(k+1), Count-Min only over-counts with ε/δ guarantees and merges across shards.

LLM-flavoured implementations

Sampling with temperature, top-k and top-p (keep the token that crosses p and at least one token, then renormalise); BPE training on a word-frequency table with careful handling of overlapping pairs and encoding by merge rank; BM25 plus reciprocal rank fusion (k ≈ 60) for hybrid retrieval; multi-head causal attention with the mask applied before softmax; a streaming parser as a linear-time state machine that handles tags split across chunks.

Testing under time pressure

Write a tiny fake early (a scripted model, a server that injects 429s and latency), seed every random generator, add property-style tests (random chunk boundaries, random inputs compared with a slow reference) and cover edge cases: empty input, Unicode, ties, k larger than n. In staged problems keep level-one code simple and extend it with tests at each level rather than rewriting.

Code review and AI coding tools

Reviewers look at correctness, design, readability, tests and whether complexity is justified. When AI assistants are allowed, interviewers watch how you verify their output: reading every line, running tests, checking edge cases and security-sensitive code. Narrate what you accept, what you change and why. Formats vary by employer and round: some allow an AI assistant, others forbid AI unless a step says otherwise, and some take-homes have been redesigned because frontier models now match strong candidates. Evidence on productivity is mixed (METR found experienced developers took 19% longer with early-2025 tools, and its 2026 follow-up could not pin down the effect), so claim speed-ups only with measurements.

Next: Worked examples Lesson 3 of 6 · about 5 min

Worked examples

Async LLM client with concurrency cap, token bucket and backoff

Send N = 1,000 prompts of about 1,200 tokens each (input plus expected output) to an API with a limit of 400,000 tokens per minute (TPM). Average latency is 3 s. Implement the client, then work out how long the run takes and how many requests should be in flight.

Capacity first. TPM bound: 400,000 / 1,200 ≈ 333 requests per minute. By Little’s law, in-flight requests = throughput × latency = (333 / 60) × 3 ≈ 17. The run takes 1,000 / 333 ≈ 3 minutes; allowing 32 in flight would not speed it up, it would only trigger 429s.

import asyncio, random, time

class TokenBucket:
    def __init__(self, rate_per_s: float, capacity: float):
        self.rate, self.capacity = rate_per_s, capacity
        self.tokens, self.t = capacity, time.monotonic()
        self.lock = asyncio.Lock()

    async def take(self, n: float) -> None:
        async with self.lock:                     # FIFO-ish fairness between waiters
            while True:
                now = time.monotonic()
                self.tokens = min(self.capacity, self.tokens + (now - self.t) * self.rate)
                self.t = now
                if self.tokens >= n:
                    self.tokens -= n
                    return
                await asyncio.sleep((n - self.tokens) / self.rate)

class Retryable(Exception):                       # raised by `call` on 429 / 5xx
    def __init__(self, retry_after: float | None = None):
        self.retry_after = retry_after

async def run_all(prompts, call, est_tokens, c=17, tpm=400_000, max_tries=5, timeout_s=60):
    sem = asyncio.Semaphore(c)
    bucket = TokenBucket(rate_per_s=tpm / 60, capacity=tpm / 10)

    async def one(p):
        for attempt in range(max_tries):
            await bucket.take(est_tokens(p))
            try:
                async with sem, asyncio.timeout(timeout_s):
                    return await call(p)
            except (Retryable, TimeoutError) as e:
                if attempt == max_tries - 1:
                    return e                      # isolate the failure, keep going
                ra = getattr(e, "retry_after", None)
                await asyncio.sleep(ra if ra is not None
                                    else random.uniform(0, min(30.0, 2.0 ** attempt)))
            except Exception as e:                # 400, auth, schema: do not retry
                return e

    return await asyncio.gather(*(one(p) for p in prompts))   # input order preserved

Talking points: the backoff sleep happens outside the semaphore so a waiting retry does not hold a slot; the token estimate should include the max output tokens because providers usually count them; asyncio.CancelledError is not caught, so cancelling the run works; tests use a fake call that raises Retryable on a schedule and records timestamps to assert the TPM limit holds.

Flow · 4 stepsAsync LLM client with cap, bucket and backoff

Async LLM client with cap, bucket and backoffA flow shows 1,000 prompts entering a token bucket, then a semaphore-capped async call under a timeout. Successful calls and isolated failures flow to the gathered result, while transient 429, 5xx or timeout failures loop back through jittered backoff into the bucket.PromptsN = 1,000 promptsToken bucketcapacity + refill rateSemaphorecap in-flight workAsync callunder asyncio.timeoutResultsinput order preservedBackoffcapped exponentialwith jittersuccess / failure429 / 5xx / timeout1234InputRate limitComputeOutput
  1. Take tokens Prompts enter and the token bucket takes the estimated tokens before any call.
  2. Cap and call In-flight work is capped by the semaphore and the call runs under asyncio.timeout.
  3. Retry transient failures Transient failures back off with jitter and re-enter the bucket; non-retryable failures return.
  4. Gather results Successful calls and isolated failures are gathered in input order.

Prompts pass through a token bucket and a concurrency cap before the async call, with transient failures retried through capped exponential backoff.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Steps
StepTitleWhat happens
1Take tokensPrompts enter and the token bucket takes the estimated tokens before any call.
2Cap and callIn-flight work is capped by the semaphore and the call runs under asyncio.timeout.
3Retry transient failuresTransient failures back off with jitter and re-enter the bucket; non-retryable failures return.
4Gather resultsSuccessful calls and isolated failures are gathered in input order.

Source: This page's text

Boxes
BoxGroupDetail
PromptsInputN = 1,000 prompts
Token bucketRate limitcapacity + refill rate
SemaphoreComputecap in-flight work
Async callComputeunder asyncio.timeout
BackoffComputecapped exponential with jitter
ResultsOutputinput order preserved

Source: This page's text

Temperature, top-k and top-p sampling with the boundary done right

For logits [2.0, 1.0, 0.5, −1.0], compute the distribution after temperature 1 and top-p = 0.8, then with temperature 0.5. Implement a seeded sampler.

T = 1. exp values: 7.389, 2.718, 1.649, 0.368; sum 12.124 → p = [0.609, 0.224, 0.136, 0.030]. Sorted cumulative sums: 0.609, 0.834, … The token that crosses 0.8 (the second) is kept, so the nucleus is {0, 1}; renormalised: 0.609 / 0.834 = 0.731 and 0.224 / 0.834 = 0.269.

T = 0.5. Logits become [4, 2, 1, −2]: exp 54.60, 7.39, 2.72, 0.14; sum 64.84 → p = [0.842, 0.114, 0.042, 0.002]. The first token alone already exceeds 0.8, so the nucleus is {0} and sampling is greedy. Lower temperature sharpens the distribution, so the nucleus shrinks.

import numpy as np

def sample(logits, temperature=1.0, top_k=None, top_p=None, rng=None):
    rng = rng or np.random.default_rng(0)
    if temperature == 0:
        return int(np.argmax(logits))
    z = np.asarray(logits, dtype=np.float64) / temperature
    if top_k is not None and top_k < z.size:
        kth = np.partition(z, -top_k)[-top_k]          # O(n), ties at kth are kept
        z = np.where(z < kth, -np.inf, z)
    p = np.exp(z - z.max())
    p /= p.sum()
    if top_p is not None and top_p < 1.0:
        order = np.argsort(-p)
        cum = np.cumsum(p[order])
        keep = order[: np.searchsorted(cum, top_p) + 1]   # include the crossing token
        mask = np.zeros(p.size, dtype=bool)
        mask[keep] = True
        p = np.where(mask, p, 0.0)
        p /= p.sum()
    return int(rng.choice(p.size, p=p))

For a batch with per-row parameters: divide by a (B, 1) temperature tensor, compute per-row thresholds, set excluded logits to −inf instead of slicing, and sample with torch.multinomial on the GPU. Test by drawing 100,000 samples and comparing frequencies with the expected nucleus probabilities.

Heavy hitters in bounded memory with Misra–Gries

A stream has n = 1,000,000 items and you may keep k = 99 counters. Implement Misra–Gries, state its error bound and say which items are guaranteed to be reported.

def misra_gries(stream, k):
    counters = {}
    for x in stream:
        if x in counters:
            counters[x] += 1
        elif len(counters) < k:
            counters[x] = 1
        else:                                   # decrement everyone, drop zeros
            for key in list(counters):
                counters[key] -= 1
                if counters[key] == 0:
                    del counters[key]
    return counters

Error bound. Each decrement round removes k + 1 units of count (one from each of the k counters plus the discarded arrival), and at most n units exist, so there are at most n / (k + 1) rounds. Every estimate is therefore an under-count by at most n / (k + 1) = 1,000,000 / 100 = 10,000.

Guarantee. Any item with true frequency above 10,000 (1% of the stream) must still hold a counter. Reported counts can be low by up to 10,000; if the stream can be replayed, a second pass gives exact counts for the at most 99 candidates.

Cost. Each round costs O(k) and there are at most n / (k + 1) rounds, so total time is O(n) and memory is O(k). For distributed streams Misra–Gries summaries (and Count-Min sketches) can be merged. Contrast: an exact dictionary needs memory proportional to the number of distinct items, which breaks the budget.

Next: What changed Lesson 4 of 6 · about 2 min

What changed recently

  1. Python 3.15: lazy imports and a free-threading stable ABI

    Python 3.15 added explicit lazy imports (PEP 810), made UTF-8 the default text encoding (PEP 686), shipped a sampling profiler and introduced a stable ABI for free-threaded builds (PEP 803), so extensions can target no-GIL Python without rebuilding for every release. For ML services with heavy import chains and CPU-bound pre-processing, interviewers may ask how you would adopt lazy imports and free-threading safely.

    Source

  2. METR's second developer study cannot pin down AI's effect

    METR’s follow-up with 57 developers and over 800 tasks estimated that AI cut task time by 18% for returning and 4% for new participants, but both confidence intervals include zero, and 30–50% of developers said they held back tasks they did not want to do without AI, a selection effect that led METR to redesign the study. With its 2025 result (experienced developers 19% slower while believing they were faster), it is the evidence interviewers expect when they ask how you know AI tools help.

    Source

  3. Anthropic redesigns its take-home after models beat candidates

    Anthropic described how its performance-engineering take-home had to be redesigned repeatedly: given the same time limit, Claude Opus 4 outperformed most applicants, and by the two-hour mark Opus 4.5 matched the best human score, so the current version uses novel puzzles on a tiny, heavily constrained instruction set with no debugging tools supplied. It illustrates a direction in technical assessment: novel rather than familiar problems, and credit for building your own tooling and verifying results.

    Source

  4. Python 3.14 makes free-threading officially supported

    Python 3.14 (7 October 2025) moved the free-threaded build to supported status (PEP 779) with a single-threaded penalty of roughly 5–10%, and added subinterpreters in the standard library, template strings and asyncio introspection commands (python -m asyncio ps/pstree). Interviewers now ask when threads, asyncio, subinterpreters or processes fit a workload, and what breaks when the GIL no longer hides data races.

    Source

Next: Pitfalls and interview angles Lesson 5 of 6 · about 2 min

Pitfalls

  • Calling time.sleep or a synchronous HTTP client inside a coroutine, which blocks the whole event loop.
  • Uncapped retry loops, retrying 400s, ignoring Retry-After, or backoff without jitter.
  • Sorting everything for a top-k, or writing Python loops where one matrix operation is expected.
  • Softmax without subtracting the max, softmax over the wrong axis, or applying the causal mask after softmax.
  • Assuming tags or JSON never split across streamed chunks, or re-parsing the whole buffer on every chunk (quadratic time).
  • Skipping tests, or over-engineering stage one of a staged problem so later stages run out of time.

How interviewers probe it

  • Start simple, then extend: ‘now add concurrency’, ‘now each row has its own top-p’, ‘now the input is a stream’.
  • Complexity probes: ‘what does your encode cost?’, ‘what is quickselect’s worst case?’, ‘how does this scale to 10M documents?’
  • ‘How would you test this?’ — fakes, seeded randomness, property tests, comparison with a slow reference.
  • Code comprehension: read 40 lines of unfamiliar numerical code, predict its output and spot edge cases.
  • Debug-style coding rounds: a repository or notebook with failing tests or silent bugs to find while narrating.
  • Some companies allow AI assistants in coding rounds and assess how you check their output rather than banning them.
Next: Quiz Lesson 6 of 6 · about 3 min

Quiz

Three questions from this guide. Answer each in your head or out loud, show the model answer, then rate yourself. The cards join your practice deck and come back when they are due.

  1. Question 1 of 3 · Applied LLM · Coding · Medium

    Implement an async client that sends N prompts to an LLM API with at most C requests in flight, a tokens-per-minute limit, exponential backoff with jitter and per-request timeouts, returning results in input order.

  2. Question 2 of 3 · Applied LLM · Coding · Medium

    Implement an agent loop in Python that takes a goal, a set of tools with JSON-schema arguments and a model client. Handle tool errors, a step limit and a token budget; then let independent tool calls run concurrently.

  3. Question 3 of 3 · Applied LLM · Coding · Medium

    Write a small eval harness: load a JSONL dataset, call a model concurrently under a rate limit, apply code-based and judge-based graders, cache results and print a per-slice report.

Reading

Practise this topic

  1. Implement an async client that sends N prompts to an LLM API with at most C requests in flight, a tokens-per-minute limit, exponential backoff with jitter and per-request timeouts, returning results in input order.Applied LLM · Coding · Medium
  2. Implement an agent loop in Python that takes a goal, a set of tools with JSON-schema arguments and a model client. Handle tool errors, a step limit and a token budget; then let independent tool calls run concurrently.Applied LLM · Coding · Medium
  3. Write a small eval harness: load a JSONL dataset, call a model concurrently under a rate limit, apply code-based and judge-based graders, cache results and print a per-slice report.Applied LLM · Coding · Medium
  4. Given a logits vector, implement sampling with temperature, top-k and top-p and a fixed seed. Then explain how you would vectorise it across a batch where each row has different parameters.Applied LLM · Coding · Medium
  5. In about 45 minutes, write a function that learns N BPE merges from a small corpus and an encode() that applies them to new text. Then discuss complexity and how you would make encoding fast.Applied LLM · Coding · Medium
  6. Without a vector database, implement top-k retrieval: cosine similarity over an embedding matrix, a simple BM25 scorer, and reciprocal rank fusion of the two lists. Then discuss complexity and scaling.Applied LLM · Coding · Easy
  7. Implement multi-head causal self-attention from scratch in PyTorch or JAX, without built-in attention functions. Be explicit about tensor shapes, the mask and the output projection.Research · Coding · Medium
  8. Given an unbounded stream and a small fixed memory budget, report approximately which items are most frequent. Implement your approach and state its error guarantee.Research · Coding · Hard
  9. Build an in-memory key–value store in stages under a time limit: basic get/set/delete, then expiring entries, then nested transactions with rollback, and finally saving and restoring state.Research · Coding · Medium
  10. Find the least frequent value in a list in O(n log n) or better, and the k-th largest element in expected O(n) time. Explain the complexity.Research · Coding · Easy
  11. Python 3.14 made the free-threaded (no-GIL) build officially supported. For an LLM data-processing service that tokenises, parses JSON and calls model APIs, what would you change, what would you keep, and what could break?Applied LLM · Technical · Medium
  12. In this coding round you may use an AI assistant. Implement a rate-limited async client that retries failed model calls with exponential backoff and jitter. Talk through how you use the assistant and how you check its output.Applied LLM · Coding · Medium

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.