---
title: Coding for ML and LLM engineering
url: https://gurkanozkan.ai/learn/topics/coding-engineering/
markdown: https://gurkanozkan.ai/learn/topics/coding-engineering.md
kind: topic
tracks:
  - Research
  - Applied LLM
  - ML engineering
json: https://gurkanozkan.ai/api/learn/topics/coding-engineering.json
---

# 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.

## 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.

### 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.

## 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.

**Solution**

**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.

```python
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.


### 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.

**Solution**

**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.

```python
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.

**Solution**

```python
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.


## What changed recently

- **Oct 2026: 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](https://docs.python.org/3.15/whatsnew/3.15.html)
- **Feb 2026: 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](https://metr.org/blog/2026-02-24-uplift-update/)
- **Jan 2026: 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](https://www.anthropic.com/research/AI-resistant-technical-evaluations)
- **Oct 2025: 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](https://docs.python.org/3/whatsnew/3.14.html)

## 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.

## Reading

- [Coroutines and tasks (Python asyncio documentation)](https://docs.python.org/3/library/asyncio-task.html) (Docs, 40 min, Core): TaskGroup, gather, timeouts and cancellation semantics you will use in every async coding round.
- [Exponential Backoff and Jitter](https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/) (Blog, 15 min, Core): Why retries need jitter and how the main jitter strategies compare.
- [Broadcasting (NumPy user guide)](https://numpy.org/doc/stable/user/basics.broadcasting.html) (Docs, 15 min, Intro): The shape rules behind every vectorised NumPy or PyTorch solution.
- [Autograd mechanics (PyTorch notes)](https://docs.pytorch.org/docs/stable/notes/autograd.html) (Docs, 30 min, Core): Grad modes, no_grad versus inference mode, eval mode and in-place pitfalls that appear in debugging rounds.
- [minbpe](https://github.com/karpathy/minbpe) (Course, 60 min, Core): Minimal, readable byte-level BPE training and encoding, with exercises matching the BPE coding question.
- [Google engineering practices: code review](https://google.github.io/eng-practices/review/) (Docs, 30 min, Intro): What reviewers check and how to write reviewable changes, useful for code-review style rounds.
- [What's new in Python 3.14](https://docs.python.org/3/whatsnew/3.14.html) (Docs, 30 min, Core): Free-threaded build support, subinterpreters, template strings, deferred annotations and new asyncio debugging tools in one place.
- [Designing AI-resistant technical evaluations](https://www.anthropic.com/research/AI-resistant-technical-evaluations) (Blog, 15 min, Intro): A frontier lab explains how models broke its take-home and what it now looks for, which tells you how to prepare.

## Practise this topic

- [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…](https://gurkanozkan.ai/learn/questions/applied-llm-cod-01.md)
- [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…](https://gurkanozkan.ai/learn/questions/applied-llm-agt-03.md)
- [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…](https://gurkanozkan.ai/learn/questions/applied-llm-evl-09.md)
- [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…](https://gurkanozkan.ai/learn/questions/applied-llm-fnd-08.md)
- [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…](https://gurkanozkan.ai/learn/questions/applied-llm-fnd-02.md)
- [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…](https://gurkanozkan.ai/learn/questions/applied-llm-cod-03.md)
- [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…](https://gurkanozkan.ai/learn/questions/research-multi-head-causal-self-attention-033.md)
- [Given an unbounded stream and a small fixed memory budget, report approximately which items are most frequent. Implement your approach and state its error…](https://gurkanozkan.ai/learn/questions/research-heavy-hitters-in-bounded-memory-086.md)
- [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…](https://gurkanozkan.ai/learn/questions/research-progressive-timed-implementation-083.md)
- [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.](https://gurkanozkan.ai/learn/questions/research-frequency-and-selection-basics-087.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-a-coding-01.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-a-coding-02.md)
---

*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.*
